Many resources are needed to download a project. Please understand that we have to compensate our server costs. Thank you in advance. Project price only 1 $
You can buy this project and download/modify it how often you want.
// 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
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR 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.artifact.Artifact;
import org.apache.maven.artifact.factory.ArtifactFactory;
import org.apache.maven.artifact.metadata.ArtifactMetadataSource;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.resolver.AbstractArtifactResolutionException;
import org.apache.maven.artifact.resolver.ArtifactNotFoundException;
import org.apache.maven.artifact.resolver.ArtifactResolutionException;
import org.apache.maven.artifact.resolver.ArtifactResolutionResult;
import org.apache.maven.artifact.resolver.ArtifactResolver;
import org.apache.maven.artifact.resolver.filter.ArtifactFilter;
import org.apache.maven.artifact.resolver.filter.ExcludesArtifactFilter;
import org.apache.maven.artifact.resolver.filter.ScopeArtifactFilter;
import org.apache.maven.artifact.versioning.ArtifactVersion;
import org.apache.maven.artifact.versioning.DefaultArtifactVersion;
import org.apache.maven.artifact.versioning.InvalidVersionSpecificationException;
import org.apache.maven.artifact.versioning.VersionRange;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugin.descriptor.PluginDescriptor;
import org.apache.maven.plugin.surefire.booterclient.ChecksumCalculator;
import org.apache.maven.plugin.surefire.booterclient.ForkConfiguration;
import org.apache.maven.plugin.surefire.booterclient.ForkStarter;
import org.apache.maven.plugin.surefire.booterclient.ClasspathForkConfiguration;
import org.apache.maven.plugin.surefire.booterclient.JarManifestForkConfiguration;
import org.apache.maven.plugin.surefire.booterclient.ModularClasspathForkConfiguration;
import org.apache.maven.plugin.surefire.booterclient.Platform;
import org.apache.maven.plugin.surefire.booterclient.ProviderDetector;
import org.apache.maven.plugin.surefire.log.PluginConsoleLogger;
import org.apache.maven.plugin.surefire.log.api.ConsoleLogger;
import org.apache.maven.plugin.surefire.util.DependencyScanner;
import org.apache.maven.plugin.surefire.util.DirectoryScanner;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;
import org.apache.maven.shared.artifact.filter.PatternIncludesArtifactFilter;
import org.apache.maven.shared.utils.io.FileUtils;
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.KeyValueSource;
import org.apache.maven.surefire.booter.ModularClasspath;
import org.apache.maven.surefire.booter.ModularClasspathConfiguration;
import org.apache.maven.surefire.booter.ProviderConfiguration;
import org.apache.maven.surefire.booter.ProviderParameterNames;
import org.apache.maven.surefire.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.cli.CommandLineOption;
import org.apache.maven.surefire.providerapi.SurefireProvider;
import org.apache.maven.surefire.report.ReporterConfiguration;
import org.apache.maven.surefire.suite.RunResult;
import org.apache.maven.surefire.testset.DirectoryScannerParameters;
import org.apache.maven.surefire.testset.RunOrderParameters;
import org.apache.maven.surefire.testset.TestArtifactInfo;
import org.apache.maven.surefire.testset.TestListResolver;
import org.apache.maven.surefire.testset.TestRequest;
import org.apache.maven.surefire.testset.TestSetFailedException;
import org.apache.maven.surefire.util.DefaultScanResult;
import org.apache.maven.surefire.util.RunOrder;
import org.apache.maven.surefire.util.SurefireReflectionException;
import org.apache.maven.toolchain.DefaultToolchain;
import org.apache.maven.toolchain.Toolchain;
import org.apache.maven.toolchain.ToolchainManager;
import org.codehaus.plexus.logging.Logger;
import org.codehaus.plexus.languages.java.jpms.LocationManager;
import org.codehaus.plexus.languages.java.jpms.ResolvePathsRequest;
import org.codehaus.plexus.languages.java.jpms.ResolvePathsResult;
import javax.annotation.Nonnull;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Array;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import static java.lang.Thread.currentThread;
import static java.util.Arrays.asList;
import static java.util.Collections.addAll;
import static java.util.Collections.singletonList;
import static java.util.Collections.singletonMap;
import static org.apache.commons.lang3.StringUtils.substringBeforeLast;
import static org.apache.commons.lang3.SystemUtils.IS_OS_WINDOWS;
import static org.apache.maven.plugin.surefire.util.DependencyScanner.filter;
import static org.apache.maven.shared.utils.StringUtils.capitalizeFirstLetter;
import static org.apache.maven.shared.utils.StringUtils.isEmpty;
import static org.apache.maven.shared.utils.StringUtils.isNotBlank;
import static org.apache.maven.shared.utils.StringUtils.isNotEmpty;
import static org.apache.maven.shared.utils.StringUtils.split;
import static org.apache.maven.surefire.booter.SystemUtils.JAVA_SPECIFICATION_VERSION;
import static org.apache.maven.surefire.booter.SystemUtils.endsWithJavaPath;
import static org.apache.maven.surefire.booter.SystemUtils.isBuiltInJava7AtLeast;
import static org.apache.maven.surefire.booter.SystemUtils.isBuiltInJava9AtLeast;
import static org.apache.maven.surefire.booter.SystemUtils.isJava9AtLeast;
import static org.apache.maven.surefire.booter.SystemUtils.toJdkHomeFromJvmExec;
import static org.apache.maven.surefire.booter.SystemUtils.toJdkVersionFromReleaseFile;
import static org.apache.maven.surefire.suite.RunResult.failure;
import static org.apache.maven.surefire.suite.RunResult.noTestsRun;
import static org.apache.maven.surefire.util.ReflectionUtils.invokeGetter;
import static org.apache.maven.surefire.util.ReflectionUtils.invokeStaticMethod;
import static org.apache.maven.surefire.util.ReflectionUtils.tryLoadClass;
/**
* Abstract base class for running tests using Surefire.
*
* @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 String FORK_ONCE = "once";
private static final String FORK_ALWAYS = "always";
private static final String FORK_NEVER = "never";
private static final String FORK_PERTHREAD = "perthread";
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 static final File SYSTEM_TMP_DIR = new File( System.getProperty( "java.io.tmpdir" ) );
private final ProviderDetector providerDetector = new ProviderDetector();
/**
* Information about this plugin, mainly used to lookup this plugin's configuration from the currently executing
* project.
*
* @since 2.12
*/
@Parameter( defaultValue = "${plugin}", readonly = true )
private PluginDescriptor pluginDescriptor;
/**
* Set this to "true" to skip running tests, but still compile them. Its use is NOT RECOMMENDED, but quite
* convenient on occasion.
*
* @since 2.4
*/
@Parameter( property = "skipTests", defaultValue = "false" )
protected boolean skipTests;
/**
* This old parameter is just like {@code skipTests}, but bound to the old property "maven.test.skip.exec".
*
* @since 2.3
* @deprecated Use skipTests instead.
*/
@Deprecated
@Parameter( property = "maven.test.skip.exec" )
protected boolean skipExec;
/**
* Set this to "true" to bypass unit tests entirely. Its use is NOT RECOMMENDED, especially if you enable it using
* 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" )
protected boolean skip;
/**
* The Maven Project Object.
*/
@Component
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}" )
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}" )
protected File testClassesDirectory;
/**
* List of dependencies to exclude from the test classpath. Each dependency string must follow the format
* groupId:artifactId. For example: org.acme:project-a
*
* @since 2.6
*/
@Parameter( property = "maven.test.dependency.excludes" )
private String[] classpathDependencyExcludes;
/**
* A dependency scope to exclude from the test classpath. The scope should be one of the scopes defined by
* org.apache.maven.artifact.Artifact. This includes the following:
*
*
*
* @since 2.6
*/
@Parameter( defaultValue = "" )
private String classpathDependencyScopeExclude;
/**
* Additional elements to be appended to the classpath.
*
* @since 2.4
*/
@Parameter( property = "maven.test.additionalClasspath" )
private String[] additionalClasspathElements;
/**
* The test source directory containing test class sources.
*
* @since 2.2
*/
@Parameter( defaultValue = "${project.build.testSourceDirectory}", required = true )
private File testSourceDirectory;
/**
* A list of <exclude> elements specifying the tests (by pattern) that should be excluded in testing. When not
* specified and when the {@code test} parameter is not specified, the default excludes will be
*
* (which excludes all inner classes).
*
* This parameter is ignored if the TestNG {@code suiteXmlFiles} parameter is specified.
*
* Each exclude item may also contain a comma-separated sub-list of items, which will be treated as multiple
* <exclude> entries.
* Since 2.19 a complex syntax is supported in one parameter (JUnit 4, JUnit 4.7+, TestNG):
*
*
* Notice that these values are relative to the directory containing generated test classes of the project
* being tested. This directory is declared by the parameter {@code testClassesDirectory} which defaults
* to the POM property ${project.build.testOutputDirectory}, typically
* {@literal src/test/java} unless overridden.
*/
@Parameter
// TODO use regex for fully qualified class names in 3.0 and change the filtering abilities
private List excludes;
/**
* ArtifactRepository of the localRepository. To obtain the directory of localRepository in unit tests use
* System.getProperty("localRepository").
*/
@Parameter( defaultValue = "${localRepository}", required = true, readonly = true )
private ArtifactRepository localRepository;
/**
* List of System properties to pass to the JUnit tests.
*
* @deprecated Use systemPropertyVariables instead.
*/
@Deprecated
@Parameter
private Properties systemProperties;
/**
* List of System properties to pass to the JUnit tests.
*
* @since 2.5
*/
@Parameter
private Map systemPropertyVariables;
/**
* List of System properties, loaded from a file, to pass to the JUnit tests.
*
* @since 2.8.2
*/
@Parameter
private File systemPropertiesFile;
/**
* List of properties for configuring all TestNG related configurations. This is the new preferred method of
* configuring TestNG.
*
* @since 2.4
*/
@Parameter
private Properties properties;
/**
* Map of plugin artifacts.
*/
// olamy: would make more sense using defaultValue but doesn't work with maven 2.x
@Parameter( property = "plugin.artifactMap", required = true, readonly = true )
private Map pluginArtifactMap;
/**
* Map of project artifacts.
*/
// olamy: would make more sense using defaultValue but doesn't work with maven 2.x
@Parameter( property = "project.artifactMap", readonly = true, required = true )
private Map projectArtifactMap;
/**
* Add custom text into report filename: TEST-testClassName-reportNameSuffix.xml,
* testClassName-reportNameSuffix.txt and testClassName-reportNameSuffix-output.txt.
* 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 = "" )
private String reportNameSuffix;
/**
* Set this to "true" to redirect the unit test standard output to a file (found in
* reportsDirectory/testName-output.txt).
*
* @since 2.3
*/
@Parameter( property = "maven.test.redirectTestOutputToFile", defaultValue = "false" )
private boolean redirectTestOutputToFile;
/**
* Set this to "true" to cause a failure if there are no tests to run. Defaults to "false".
*
* @since 2.4
*/
@Parameter( property = "failIfNoTests" )
private Boolean failIfNoTests;
/**
* DEPRECATED since version 2.14. Use {@code forkCount} and {@code reuseForks} instead.
*
*
* Option to specify the forking mode. Can be {@code never}, {@code once}, {@code always}, {@code perthread}.
* The {@code none} and {@code pertest} are also accepted for backwards compatibility.
* The {@code always} forks for each test-class.
* The {@code perthread} creates the number of parallel forks specified by {@code threadCount}, where each forked
* JVM is executing one test-class. See also the parameter {@code reuseForks} for the lifetime of JVM.
*
* @since 2.1
*/
@Parameter( property = "forkMode", defaultValue = "once" )
private String forkMode;
/**
* Relative path to temporary-surefire-boot directory containing internal Surefire temporary files.
*
* The temporary-surefire-boot directory is project.build.directory on most platforms or
* system default temporary-directory specified by the system property {@code java.io.tmpdir}
* on Windows (see SUREFIRE-1400).
*
* It is deleted after the test set has completed.
*
* @since 2.20
*/
@Parameter( property = "tempDir", defaultValue = "surefire" )
private String tempDir;
/**
* Option to specify the jvm (or path to the java executable) to use with the forking options. For the default, the
* jvm will be a new instance of the same VM as the one used to run Maven. JVM settings are not inherited from
* MAVEN_OPTS.
*
* @since 2.1
*/
@Parameter( property = "jvm" )
private String jvm;
/**
* Arbitrary JVM options to set on the command line.
*
*
* Since the Version 2.17 using an alternate syntax for {@code argLine}, @{...} allows late replacement
* of properties when the plugin is executed, so properties that have been modified by other plugins will be picked
* up correctly.
* See the Frequently Asked Questions page with more details:
*
* http://maven.apache.org/surefire/maven-surefire-plugin/faq.html
*
*
* http://maven.apache.org/surefire/maven-failsafe-plugin/faq.html
*
* @since 2.1
*/
@Parameter( property = "argLine" )
private String argLine;
/**
* Additional environment variables to set on the command line.
*
* @since 2.1.3
*/
@Parameter
private Map environmentVariables = new HashMap();
/**
* Command line working directory.
*
* @since 2.1.3
*/
@Parameter( property = "basedir" )
private File workingDirectory;
/**
* When false it makes tests run using the standard classloader delegation instead of the default Maven isolated
* classloader. Only used when forking ({@code forkMode} is not {@code none}).
* Setting it to false helps with some problems caused by conflicts between xml parsers in the classpath and the
* Java 5 provider parser.
*
* @since 2.1
*/
@Parameter( property = "childDelegation", defaultValue = "false" )
private boolean childDelegation;
/**
* (TestNG/JUnit47 provider with JUnit4.8+ only) Groups for this test. Only classes/methods/etc decorated with one
* of the groups specified here will be included in test run, if specified.
* For JUnit, this parameter forces the use of the 4.7 provider
* This parameter is ignored if the {@code suiteXmlFiles} parameter is specified.
* Since version 2.18.1 and JUnit 4.12, the {@code @Category} annotation type is automatically inherited from
* superclasses, see {@code @java.lang.annotation.Inherited}. Make sure that test class inheritance still makes
* sense together with {@code @Category} annotation of the JUnit 4.12 or higher appeared in superclass.
*
* @since 2.2
*/
@Parameter( property = "groups" )
private String groups;
/**
* (TestNG/JUnit47 provider with JUnit4.8+ only) Excluded groups. Any methods/classes/etc with one of the groups
* specified in this list will specifically not be run.
* For JUnit, this parameter forces the use of the 4.7 provider.
* This parameter is ignored if the {@code suiteXmlFiles} parameter is specified.
* Since version 2.18.1 and JUnit 4.12, the {@code @Category} annotation type is automatically inherited from
* superclasses, see {@code @java.lang.annotation.Inherited}. Make sure that test class inheritance still makes
* sense together with {@code @Category} annotation of the JUnit 4.12 or higher appeared in superclass.
*
* @since 2.2
*/
@Parameter( property = "excludedGroups" )
private String excludedGroups;
/**
* Allows you to specify the name of the JUnit artifact. If not set, {@code junit:junit} will be used.
*
* @since 2.3.1
*/
@Parameter( property = "junitArtifactName", defaultValue = "junit:junit" )
private String junitArtifactName;
/**
* Allows you to specify the name of the JUnit Platform artifact.
* If not set, {@code org.junit.platform:junit-platform-engine} will be used.
*
* @since 2.22.0
*/
@Parameter( property = "junitPlatformArtifactName", defaultValue = "org.junit.platform:junit-platform-engine" )
private String junitPlatformArtifactName;
/**
* Allows you to specify the name of the TestNG artifact. If not set, {@code org.testng:testng} will be used.
*
* @since 2.3.1
*/
@Parameter( property = "testNGArtifactName", defaultValue = "org.testng:testng" )
private String testNGArtifactName;
/**
* (TestNG/JUnit 4.7 provider) The attribute thread-count allows you to specify how many threads should be
* allocated for this execution. Only makes sense to use in conjunction with the {@code parallel} parameter.
*
* @since 2.2
*/
@Parameter( property = "threadCount" )
private int threadCount;
/**
* Option to specify the number of VMs to fork in parallel in order to execute the tests. When terminated with "C",
* the number part is multiplied with the number of CPU cores. Floating point value are only accepted together with
* "C". If set to "0", no VM is forked and all tests are executed within the main process.
*
* Example values: "1.5C", "4"
*
* The system properties and the {@code argLine} of the forked processes may contain the place holder string
* ${surefire.forkNumber}, which is replaced with a fixed number for each of the parallel forks,
* ranging from 1 to the effective value of {@code forkCount} times the maximum number of parallel
* Surefire executions in maven parallel builds, i.e. the effective value of the -T command line
* argument of maven core.
*
* @since 2.14
*/
@Parameter( property = "forkCount", defaultValue = "1" )
private String forkCount;
/**
* Indicates if forked VMs can be reused. If set to "false", a new VM is forked for each test class to be executed.
* If set to "true", up to {@code forkCount} VMs will be forked and then reused to execute all tests.
*
* @since 2.13
*/
@Parameter( property = "reuseForks", defaultValue = "true" )
private boolean reuseForks;
/**
* (JUnit 4.7 provider) Indicates that threadCount, threadCountSuites, threadCountClasses, threadCountMethods
* are per cpu core.
*
* @since 2.5
*/
@Parameter( property = "perCoreThreadCount", defaultValue = "true" )
private boolean perCoreThreadCount;
/**
* (JUnit 4.7 provider) Indicates that the thread pool will be unlimited. The {@code parallel} parameter and
* the actual number of classes/methods will decide. Setting this to "true" effectively disables
* {@code perCoreThreadCount} and {@code threadCount}. Defaults to "false".
*
* @since 2.5
*/
@Parameter( property = "useUnlimitedThreads", defaultValue = "false" )
private boolean useUnlimitedThreads;
/**
* (TestNG provider) When you use the parameter {@code parallel}, TestNG will try to run all your test methods
* in separate threads, except for methods that depend on each other, which will be run in the same thread in order
* to respect their order of execution.
*
* (JUnit 4.7 provider) Supports values {@code classes}, {@code methods}, {@code both} to run
* in separate threads been controlled by {@code threadCount}.
*
*
* Since version 2.16 (JUnit 4.7 provider), the value {@code both} is DEPRECATED.
* Use {@code classesAndMethods} instead.
*
*
* Since version 2.16 (JUnit 4.7 provider), additional vales are available:
*
* {@code suites}, {@code suitesAndClasses}, {@code suitesAndMethods}, {@code classesAndMethods}, {@code all}.
*
* @since 2.2
*/
@Parameter( property = "parallel" )
private String parallel;
/**
* (JUnit 4.7 / provider only) The thread counts do not exceed the number of parallel suite, class runners and
* average number of methods per class if set to true.
*
* True by default.
*
* @since 2.17
*/
@Parameter( property = "parallelOptimized", defaultValue = "true" )
private boolean parallelOptimized;
/**
* (JUnit 4.7 provider) This attribute allows you to specify the concurrency in test suites, i.e.:
*
*
number of concurrent suites if {@code threadCount} is 0 or unspecified
*
limited suites concurrency if {@code useUnlimitedThreads} is set to true
*
if {@code threadCount} and certain thread-count parameters are > 0 for {@code parallel}, the
* concurrency is computed from ratio. For instance {@code parallel=all} and the ratio between
* {@code threadCountSuites}:{@code threadCountClasses}:{@code threadCountMethods} is
* 2:3:5, there is 20% of {@code threadCount} which appeared in concurrent suites.
*
*
* Only makes sense to use in conjunction with the {@code parallel} parameter.
* The default value 0 behaves same as unspecified one.
*
* @since 2.16
*/
@Parameter( property = "threadCountSuites", defaultValue = "0" )
private int threadCountSuites;
/**
* (JUnit 4.7 provider) This attribute allows you to specify the concurrency in test classes, i.e.:
*
*
number of concurrent classes if {@code threadCount} is 0 or unspecified
*
limited classes concurrency if {@code useUnlimitedThreads} is set to true
*
if {@code threadCount} and certain thread-count parameters are > 0 for {@code parallel}, the
* concurrency is computed from ratio. For instance {@code parallel=all} and the ratio between
* {@code threadCountSuites}:{@code threadCountClasses}:{@code threadCountMethods} is
* 2:3:5, there is 30% of {@code threadCount} in concurrent classes.
*
as in the previous case but without this leaf thread-count. Example: {@code parallel=suitesAndClasses},
* {@code threadCount=16}, {@code threadCountSuites=5}, {@code threadCountClasses} is unspecified leaf, the number
* of concurrent classes is varying from >= 11 to 14 or 15. The {@code threadCountSuites} become
* given number of threads.
*
*
* Only makes sense to use in conjunction with the {@code parallel} parameter.
* The default value 0 behaves same as unspecified one.
*
* @since 2.16
*/
@Parameter( property = "threadCountClasses", defaultValue = "0" )
private int threadCountClasses;
/**
* (JUnit 4.7 provider) This attribute allows you to specify the concurrency in test methods, i.e.:
*
*
number of concurrent methods if {@code threadCount} is 0 or unspecified
*
limited concurrency of methods if {@code useUnlimitedThreads} is set to true
*
if {@code threadCount} and certain thread-count parameters are > 0 for {@code parallel}, the
* concurrency is computed from ratio. For instance parallel=all and the ratio between
* {@code threadCountSuites}:{@code threadCountClasses}:{@code threadCountMethods} is 2:3:5,
* there is 50% of {@code threadCount} which appears in concurrent methods.
*
as in the previous case but without this leaf thread-count. Example: {@code parallel=all},
* {@code threadCount=16}, {@code threadCountSuites=2}, {@code threadCountClasses=3}, but {@code threadCountMethods}
* is unspecified leaf, the number of concurrent methods is varying from >= 11 to 14 or 15.
* The {@code threadCountSuites} and {@code threadCountClasses} become given number of threads.
*
* Only makes sense to use in conjunction with the {@code parallel} parameter. The default value 0
* behaves same as unspecified one.
*
* @since 2.16
*/
@Parameter( property = "threadCountMethods", defaultValue = "0" )
private int threadCountMethods;
/**
* Whether to trim the stack trace in the reports to just the lines within the test, or show the full trace.
*
* @since 2.2
*/
@Parameter( property = "trimStackTrace", defaultValue = "true" )
private boolean trimStackTrace;
/**
* Resolves the artifacts needed.
*/
@Component
private ArtifactResolver artifactResolver;
/**
* Creates the artifact.
*/
@Component
private ArtifactFactory artifactFactory;
/**
* The remote plugin repositories declared in the POM.
*
* @since 2.2
*/
@Parameter( defaultValue = "${project.pluginArtifactRepositories}" )
private List remoteRepositories;
/**
* For retrieval of artifact's metadata.
*/
@Component
private ArtifactMetadataSource metadataSource;
/**
* Flag to disable the generation of report files in xml format.
*
* @since 2.2
*/
@Parameter( property = "disableXmlReport", defaultValue = "false" )
private boolean disableXmlReport;
/**
* By default, Surefire enables JVM assertions for the execution of your test cases. To disable the assertions, set
* this flag to "false".
*
* @since 2.3.1
*/
@Parameter( property = "enableAssertions", defaultValue = "true" )
private boolean enableAssertions;
/**
* The current build session instance.
*/
@Component
private MavenSession session;
@Component
private Logger logger;
/**
* (TestNG only) Define the factory class used to create all test instances.
*
* @since 2.5
*/
@Parameter( property = "objectFactory" )
private String objectFactory;
/**
*
*/
@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 )
private File projectBuildDirectory;
/**
* List of dependencies to scan for test classes to include in the test run.
* The child elements of this element must be <dependency> elements, and the
* contents of each of these elements must be a string which follows the format:
*
* groupId:artifactId. For example: org.acme:project-a.
*
* Since version 2.22.0 you can scan for test classes from a project
* dependency of your multi-module project.
*
* @since 2.15
*/
@Parameter( property = "dependenciesToScan" )
private String[] dependenciesToScan;
/**
*
*/
@Component
private ToolchainManager toolchainManager;
// todo use in 3.0.0 with java 1.7 and substitute new LocationManager() with component in underneath code
// @Component
// private LocationManager locationManager;
private Artifact surefireBooterArtifact;
private Toolchain toolchain;
private int effectiveForkCount = -1;
/**
* The placeholder that is replaced by the executing thread's running number. The thread number
* range starts with 1
* Deprecated.
*/
public static final String THREAD_NUMBER_PLACEHOLDER = "${surefire.threadNumber}";
/**
* The placeholder that is replaced by the executing fork's running number. The fork number
* range starts with 1
*/
public static final String FORK_NUMBER_PLACEHOLDER = "${surefire.forkNumber}";
protected abstract String getPluginName();
protected abstract int getRerunFailingTestsCount();
@Override
public abstract List getIncludes();
public abstract File getIncludesFile();
@Override
public abstract void setIncludes( List includes );
public abstract File getExcludesFile();
/**
* Calls {@link #getSuiteXmlFiles()} as {@link List list}.
* Never returns null.
*
* @return list of TestNG suite XML files provided by MOJO
*/
protected abstract List suiteXmlFiles();
/**
* @return {@code true} if {@link #getSuiteXmlFiles() suite-xml files array} is not empty.
*/
protected abstract boolean hasSuiteXmlFiles();
public abstract File[] getSuiteXmlFiles();
public abstract void setSuiteXmlFiles( File[] suiteXmlFiles );
public abstract String getRunOrder();
public abstract void setRunOrder( String runOrder );
protected abstract void handleSummary( RunResult summary, Exception firstForkException )
throws MojoExecutionException, MojoFailureException;
protected abstract boolean isSkipExecution();
protected abstract String[] getDefaultIncludes();
protected abstract String getReportSchemaLocation();
protected abstract Artifact getMojoArtifact();
private String getDefaultExcludes()
{
return "**/*$*";
}
private SurefireDependencyResolver dependencyResolver;
private TestListResolver specificTests;
private TestListResolver includedExcludedTests;
private List cli;
private volatile PluginConsoleLogger consoleLogger;
@Override
public void execute()
throws MojoExecutionException, MojoFailureException
{
cli = commandLineOptions();
// Stuff that should have been final
setupStuff();
if ( verifyParameters() && !hasExecutedBefore() )
{
DefaultScanResult scan = scanForTestClasses();
if ( !hasSuiteXmlFiles() && scan.isEmpty() )
{
if ( getEffectiveFailIfNoTests() )
{
throw new MojoFailureException(
"No tests were executed! (Set -DfailIfNoTests=false to ignore this error.)" );
}
handleSummary( noTestsRun(), null );
return;
}
logReportsDirectory();
executeAfterPreconditionsChecked( scan );
}
}
@Nonnull
protected final PluginConsoleLogger getConsoleLogger()
{
if ( consoleLogger == null )
{
synchronized ( this )
{
if ( consoleLogger == null )
{
consoleLogger = new PluginConsoleLogger( logger );
}
}
}
return consoleLogger;
}
private void setupStuff()
{
createDependencyResolver();
surefireBooterArtifact = getSurefireBooterArtifact();
toolchain = getToolchain();
}
@Nonnull
private DefaultScanResult scanForTestClasses()
throws MojoFailureException
{
DefaultScanResult scan = scanDirectories();
DefaultScanResult scanDeps = scanDependencies();
return scan.append( scanDeps );
}
private DefaultScanResult scanDirectories()
throws MojoFailureException
{
DirectoryScanner scanner = new DirectoryScanner( getTestClassesDirectory(), getIncludedAndExcludedTests() );
return scanner.scan();
}
@SuppressWarnings( "unchecked" )
List getProjectTestArtifacts()
{
return project.getTestArtifacts();
}
DefaultScanResult scanDependencies() throws MojoFailureException
{
if ( getDependenciesToScan() == null )
{
return null;
}
else
{
try
{
DefaultScanResult result = null;
List dependenciesToScan =
filter( getProjectTestArtifacts(), asList( getDependenciesToScan() ) );
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" ) ) )
{
continue;
}
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() );
}
}
return result;
}
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." );
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 ( !getTestClassesDirectory().exists()
&& ( getDependenciesToScan() == null || getDependenciesToScan().length == 0 ) )
{
if ( Boolean.TRUE.equals( getFailIfNoTests() ) )
{
throw new MojoFailureException( "No tests to run!" );
}
getConsoleLogger().info( "No tests to run." );
}
else
{
convertDeprecatedForkMode();
ensureWorkingDirectoryExists();
ensureParallelRunningCompatibility();
ensureThreadCountWithPerThread();
warnIfUselessUseSystemClassLoaderParameter();
warnIfDefunctGroupsCombinations();
warnIfRerunClashes();
warnIfWrongShutdownValue();
warnIfNotApplicableSkipAfterFailureCount();
warnIfIllegalTempDir();
}
return true;
}
private void executeAfterPreconditionsChecked( @Nonnull DefaultScanResult scanResult )
throws MojoExecutionException, MojoFailureException
{
List providers = createProviders();
RunResult current = noTestsRun();
Exception firstForkException = null;
for ( ProviderInfo provider : providers )
{
try
{
current = current.aggregate( executeProvider( provider, scanResult ) );
}
catch ( SurefireBooterForkException e )
{
if ( firstForkException == null )
{
firstForkException = e;
}
}
catch ( SurefireExecutionException e )
{
if ( firstForkException == null )
{
firstForkException = e;
}
}
catch ( TestSetFailedException e )
{
if ( firstForkException == null )
{
firstForkException = e;
}
}
}
if ( firstForkException != null )
{
current = failure( current, firstForkException );
}
handleSummary( current, firstForkException );
}
private void createDependencyResolver()
{
dependencyResolver = new SurefireDependencyResolver( getArtifactResolver(), getArtifactFactory(),
getConsoleLogger(), getLocalRepository(),
getRemoteRepositories(), getMetadataSource(),
getPluginName() );
}
protected List createProviders()
throws MojoFailureException, MojoExecutionException
{
Artifact junitDepArtifact = getJunitDepArtifact();
return new ProviderList( new DynamicProviderInfo( null ),
new TestNgProviderInfo( getTestNgArtifact() ),
new JUnitPlatformProviderInfo( getJunitPlatformArtifact() ),
new JUnitCoreProviderInfo( getJunitArtifact(), junitDepArtifact ),
new JUnit4ProviderInfo( getJunitArtifact(), junitDepArtifact ),
new JUnit3ProviderInfo() )
.resolve();
}
private SurefireProperties setupProperties()
{
SurefireProperties sysProps = null;
try
{
sysProps = SurefireProperties.loadProperties( systemPropertiesFile );
}
catch ( IOException e )
{
String msg = "The system property file '" + systemPropertiesFile.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( "user.dir", getWorkingDirectory().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 ) )
{
getConsoleLogger()
.warning( "The system property "
+ systemPropertyMatchingArgLine
+ " is configured twice! "
+ "The property appears in and any of , "
+ " or user property."
);
}
}
if ( getConsoleLogger().isDebugEnabled() )
{
showToLog( result, getConsoleLogger() );
}
return result;
}
private Set