/
AbstractSurefireMojo.java
3635 lines (3169 loc) · 150 KB
/
AbstractSurefireMojo.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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;
import javax.annotation.Nonnull;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
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.Optional;
import java.util.Properties;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.zip.ZipFile;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.DefaultArtifact;
import org.apache.maven.artifact.handler.ArtifactHandler;
import org.apache.maven.artifact.resolver.filter.ArtifactFilter;
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.model.Dependency;
import org.apache.maven.model.Plugin;
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.ClasspathForkConfiguration;
import org.apache.maven.plugin.surefire.booterclient.ForkConfiguration;
import org.apache.maven.plugin.surefire.booterclient.ForkStarter;
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.extensions.LegacyForkNodeFactory;
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.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.surefire.api.booter.ProviderParameterNames;
import org.apache.maven.surefire.api.booter.Shutdown;
import org.apache.maven.surefire.api.cli.CommandLineOption;
import org.apache.maven.surefire.api.report.ReporterConfiguration;
import org.apache.maven.surefire.api.suite.RunResult;
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.testset.TestSetFailedException;
import org.apache.maven.surefire.api.util.DefaultScanResult;
import org.apache.maven.surefire.api.util.RunOrder;
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.ProcessCheckerType;
import org.apache.maven.surefire.booter.ProviderConfiguration;
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.ForkNodeFactory;
import org.apache.maven.surefire.providerapi.ConfigurableProviderInfo;
import org.apache.maven.surefire.providerapi.ProviderDetector;
import org.apache.maven.surefire.providerapi.ProviderInfo;
import org.apache.maven.surefire.providerapi.ProviderRequirements;
import org.apache.maven.surefire.shared.utils.io.FileUtils;
import org.apache.maven.toolchain.DefaultToolchain;
import org.apache.maven.toolchain.Toolchain;
import org.apache.maven.toolchain.ToolchainManager;
import org.apache.maven.toolchain.java.DefaultJavaToolChain;
import org.codehaus.plexus.languages.java.jpms.JavaModuleDescriptor;
import org.codehaus.plexus.languages.java.jpms.LocationManager;
import org.codehaus.plexus.languages.java.jpms.ResolvePathRequest;
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.logging.Logger;
import static java.lang.Integer.parseInt;
import static java.util.Arrays.asList;
import static java.util.Collections.addAll;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static java.util.Collections.singletonMap;
import static org.apache.maven.plugin.surefire.AbstractSurefireMojo.PluginFailureReason.COULD_NOT_RUN_DEFAULT_TESTS;
import static org.apache.maven.plugin.surefire.AbstractSurefireMojo.PluginFailureReason.COULD_NOT_RUN_SPECIFIED_TESTS;
import static org.apache.maven.plugin.surefire.AbstractSurefireMojo.PluginFailureReason.NONE;
import static org.apache.maven.plugin.surefire.SurefireDependencyResolver.isWithinVersionSpec;
import static org.apache.maven.plugin.surefire.SurefireHelper.replaceThreadNumberPlaceholders;
import static org.apache.maven.plugin.surefire.util.DependencyScanner.filter;
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.suite.RunResult.failure;
import static org.apache.maven.surefire.api.suite.RunResult.noTestsRun;
import static org.apache.maven.surefire.api.util.ReflectionUtils.invokeMethodWithArray;
import static org.apache.maven.surefire.api.util.ReflectionUtils.tryGetMethod;
import static org.apache.maven.surefire.booter.Classpath.emptyClasspath;
import static org.apache.maven.surefire.booter.SystemUtils.endsWithJavaPath;
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.shared.lang3.JavaVersion.JAVA_RECENT;
import static org.apache.maven.surefire.shared.lang3.StringUtils.substringBeforeLast;
import static org.apache.maven.surefire.shared.lang3.SystemUtils.IS_OS_WINDOWS;
import static org.apache.maven.surefire.shared.utils.StringUtils.capitalizeFirstLetter;
import static org.apache.maven.surefire.shared.utils.StringUtils.isEmpty;
import static org.apache.maven.surefire.shared.utils.StringUtils.isNotBlank;
import static org.apache.maven.surefire.shared.utils.StringUtils.isNotEmpty;
import static org.apache.maven.surefire.shared.utils.StringUtils.split;
import static org.apache.maven.surefire.shared.utils.cli.ShutdownHookUtils.addShutDownHook;
import static org.apache.maven.surefire.shared.utils.cli.ShutdownHookUtils.removeShutdownHook;
/**
* 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 Map<String, String> JAVA_9_MATCHER_OLD_NOTATION = singletonMap("version", "[1.9,)");
private static final Map<String, String> JAVA_9_MATCHER = singletonMap("version", "[9,)");
private static final Platform PLATFORM = new Platform();
private final ClasspathCache classpathCache = new ClasspathCache();
/**
* Note: use the legacy system property <em>disableXmlReport</em> set to {@code true} to disable the report.
*/
@Parameter
private SurefireStatelessReporter statelessTestsetReporter;
@Parameter
private SurefireConsoleOutputReporter consoleOutputReporter;
@Parameter
private SurefireStatelessTestsetInfoReporter statelessTestsetInfoReporter;
/**
* 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, required = 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.<br>
* Failsafe plugin deprecated the parameter {@code skipTests} and the parameter will be removed in
* <i>Failsafe 3.0.0</i> as it is a source of conflicts between Failsafe and Surefire plugin.
*
* @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.
*/
@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)
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 at runtime.
* Each item is passed as pattern to {@link PatternIncludesArtifactFilter}.
* The pattern is matched against the following artifact ids:
* <ul>
* <li>{@code groupId:artifactId} (Short ID)</li>
* <li>{@code groupId:artifactId:type:classifier} (Dependency Conflict ID)</li>
* <li>{@code groupId:artifactId:type:classifier:version} (Full ID)</li>
* </ul>
* The matching algorithm is described in detail in <a href="https://maven.apache.org/plugins/maven-assembly-plugin/advanced-descriptor-topics.html#advanced-artifact-matching-in-includes-and-excludes">Advanced Artifact-Matching</a> for the maven-assembly-plugin. This parameter behaves the same as the {@code excludes} pattern described there.
* The dependency matching is applied to the project dependency IDs (including transitive ones) <i>after resolving</i>, i.e. excluding
* one dependency will not exclude its transitive dependencies!
* @since 2.6
*/
@Parameter(property = "maven.test.dependency.excludes")
private String[] classpathDependencyExcludes;
/**
* A dependency scope to exclude from the test classpath at runtime. The scope should be one of the scopes defined by
* org.apache.maven.artifact.Artifact. This includes the following:
* <br>
* <ul>
* <li><i>compile</i> - system, provided, compile
* <li><i>runtime</i> - compile, runtime
* <li><i>compile+runtime</i> - system, provided, compile, runtime
* <li><i>runtime+system</i> - system, compile, runtime
* <li><i>test</i> - system, provided, compile, runtime, test
* </ul>
*
* @since 2.6
*/
@Parameter(defaultValue = "")
private String classpathDependencyScopeExclude;
/**
* Additional elements to be appended to the test classpath at runtime.
* Each element must be a file system path to a JAR file or a directory containing classes.
* No wildcards are allowed here.
*
* @since 2.4
*/
@Parameter(property = "maven.test.additionalClasspath")
private String[] additionalClasspathElements;
/**
* Additional Maven dependencies to be added to the test classpath at runtime.
* Each element supports the parametrization like documented in <a href="https://maven.apache.org/pom.html#dependencies">POM Reference: Dependencies</a>.
* <p>
* Those dependencies are automatically collected (i.e. have their full dependency tree calculated) and then all underlying artifacts are resolved from the repository (including their transitive dependencies).
* Afterwards the resolved artifacts are filtered to only contain {@code compile} and {@code runtime} scoped ones and appended to the test classpath at runtime
* (after the ones from {@link #additionalClasspathElements}).
* <p>
* The following differences to regular project dependency resolving apply:
* <ul>
* <li>The dependency management from the project is not taken into account.</li>
* <li>Conflicts between the different items and the project dependencies are not resolved.</li>
* <li>Only external dependencies (outside the current Maven reactor) are supported.</li>
* </ul>
*
* @since 3.2
*/
@Parameter(property = "maven.test.additionalClasspathDependencies")
private List<Dependency> additionalClasspathDependencies;
/**
* The test source directory containing test class sources.
* Important <b>only</b> for TestNG HTML reports.
*
* @since 2.2
*/
@Parameter(defaultValue = "${project.build.testSourceDirectory}")
private File testSourceDirectory;
/**
* List of System properties to pass to a provider.
*
* @deprecated Use systemPropertyVariables instead.
*/
@Deprecated
@Parameter
private Properties systemProperties;
/**
* List of System properties to pass to a provider.
*
* @since 2.5
*/
@Parameter
private Map<String, String> systemPropertyVariables;
/**
* 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.
*/
@Parameter(property = "plugin.artifactMap", required = true, readonly = true)
private Map<String, Artifact> pluginArtifactMap;
/**
* Map of project artifacts.
*/
@Parameter(property = "project.artifactMap", readonly = true, required = true)
private Map<String, Artifact> 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", defaultValue = "false")
private boolean failIfNoTests;
/**
* Relative path to <i>temporary-surefire-boot</i> directory containing internal Surefire temporary files.
* <br>
* The <i>temporary-surefire-boot</i> directory is <i>project.build.directory</i> on most platforms or
* <i>system default temporary-directory</i> specified by the system property {@code java.io.tmpdir}
* on Windows (see <a href="https://issues.apache.org/jira/browse/SUREFIRE-1400">SUREFIRE-1400</a>).
* <br>
* 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.
* <br>
* <br>
* Since the Version 2.17 using an alternate syntax for {@code argLine}, <b>@{...}</b> 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:<br>
* <a href="http://maven.apache.org/surefire/maven-surefire-plugin/faq.html">
* http://maven.apache.org/surefire/maven-surefire-plugin/faq.html</a>
* <br>
* <a href="http://maven.apache.org/surefire/maven-failsafe-plugin/faq.html">
* http://maven.apache.org/surefire/maven-failsafe-plugin/faq.html</a>
*
* @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<String, String> 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 forkCount} is greater than zero).<br>
* 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 and JUnit5+ provider since 2.22.0) Groups/categories/tags for this
* test. Only classes/methods/etc decorated with one of the groups/categories/tags specified here will be included
* in test run, if specified.<br>
* For JUnit4 tests, this parameter forces the use of the 4.7 provider. For JUnit5 tests, this parameter forces
* the use of the JUnit platform provider.<br>
* This parameter is ignored if the {@code suiteXmlFiles} parameter is specified.<br>
* 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 and JUnit5+ provider since 2.22.0) Excluded groups/categories/tags.
* Any methods/classes/etc with one of the groups/categories/tags specified in this list will specifically not be
* run.<br>
* For JUnit4, this parameter forces the use of the 4.7 provider. For JUnit5, this parameter forces the use of the
* JUnit platform provider.<br>
* This parameter is ignored if the {@code suiteXmlFiles} parameter is specified.<br>
* 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 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.<br>
* <br>
* Example values: "1.5C", "4"<br>
* <br>
* The system properties and the {@code argLine} of the forked processes may contain the place holder string
* <code>${surefire.forkNumber}</code>, which is replaced with a fixed number for each of the parallel forks,
* ranging from <b>1</b> 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 <b>-T</b> 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. Supports two values: {@code classes} or {@code methods}.
* <br>
* (JUnit 4.7 provider) Supports values {@code classes}, {@code methods}, {@code both} to run
* in separate threads been controlled by {@code threadCount}.
* <br>
* <br>
* Since version 2.16 (JUnit 4.7 provider), the value {@code both} is <strong>DEPRECATED</strong>.
* Use {@code classesAndMethods} instead.
* <br>
* <br>
* Since version 2.16 (JUnit 4.7 provider), additional vales are available:
* <br>
* {@code suites}, {@code suitesAndClasses}, {@code suitesAndMethods}, {@code classesAndMethods}, {@code all}.
* <br>
* By default, Surefire does not execute tests in parallel. You can set the parameter {@code parallel} to
* {@code none} to explicitly disable parallel execution (e.g. when disabling parallel execution in special Maven
* profiles when executing coverage analysis).
*
* @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 <strong>true</strong>.
* <br>
* 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.:
* <ul>
* <li>number of concurrent suites if {@code threadCount} is 0 or unspecified</li>
* <li>limited suites concurrency if {@code useUnlimitedThreads} is set to <strong>true</strong></li>
* <li>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
* <b>2</b>:3:5, there is 20% of {@code threadCount} which appeared in concurrent suites.</li>
* </ul>
*
* Only makes sense to use in conjunction with the {@code parallel} parameter.
* The default value <b>0</b> 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.:
* <ul>
* <li>number of concurrent classes if {@code threadCount} is 0 or unspecified</li>
* <li>limited classes concurrency if {@code useUnlimitedThreads} is set to <strong>true</strong></li>
* <li>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:<b>3</b>:5, there is 30% of {@code threadCount} in concurrent classes.</li>
* <li>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.</li>
* </ul>
*
* Only makes sense to use in conjunction with the {@code parallel} parameter.
* The default value <b>0</b> 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.:
* <ul>
* <li>number of concurrent methods if {@code threadCount} is 0 or unspecified</li>
* <li>limited concurrency of methods if {@code useUnlimitedThreads} is set to <strong>true</strong></li>
* <li>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:<b>5</b>,
* there is 50% of {@code threadCount} which appears in concurrent methods.</li>
* <li>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.</li>
* </ul>
* Only makes sense to use in conjunction with the {@code parallel} parameter. The default value <b>0</b>
* 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 = "false")
private boolean trimStackTrace;
/**
* Flag to disable the generation of report files in xml format.
* Deprecated since 3.0.0-M4.
* Instead use <em>disable</em> within {@code statelessTestsetReporter} since of 3.0.0-M6.
* @since 2.2
*/
@Deprecated // todo make readonly to handle system property
@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.
*/
@Parameter(defaultValue = "${session}", required = true, readonly = true)
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;
/**
* Parallel Maven Execution.
*/
@Parameter(defaultValue = "${session.parallel}", readonly = true)
private Boolean parallelMavenExecution;
/**
* Read-only parameter with value of Maven property <i>project.build.directory</i>.
* @since 2.20
*/
@Parameter(defaultValue = "${project.build.directory}", readonly = true, required = 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 general form:
*
* <p>{@code groupId[:artifactId[:type[:classifier][:version]]]}</p>
*
* <p>The wildcard character <code>*</code> can be used within the sub parts of those composite identifiers to
* do glob-like pattern matching. The classifier may be omitted when matching dependencies without a classifier.</p>
*
* <p>Examples:</p>
*
* <ul>
* <li>{@code group} or, equivalently, {@code group:*}</li>
* <li>{@code g*p:*rtifac*}</li>
* <li>{@code group:*:jar}</li>
* <li>{@code group:artifact:*:1.0.0} (no classifier)</li>
* <li>{@code group:*:test-jar:tests}</li>
* <li>{@code *:artifact:*:*:1.0.0}</li>
* </ul>
*
* <p>Since version 2.22.0 you can scan for test classes from a project
* dependency of your multi-module project.</p>
*
* <p>In versions before 3.0.0-M4, only <code>groupId:artifactId</code> is supported.</p>
*
* @since 2.15
*/
@Parameter(property = "dependenciesToScan")
private String[] dependenciesToScan;
/**
* <p>
* Allow for configuration of the test jvm via maven toolchains.
* This permits a configuration where the project is built with one jvm and tested with another.
* This is similar to {@link #jvm}, but avoids hardcoding paths.
* The two parameters are mutually exclusive (jvm wins)
* </p>
*
* <p>Examples:</p>
* (see <a href="https://maven.apache.org/guides/mini/guide-using-toolchains.html">
* Guide to Toolchains</a> for more info)
*
* <pre>
* {@code
* <configuration>
* ...
* <jdkToolchain>
* <version>1.11</version>
* </jdkToolchain>
* </configuration>
*
* <configuration>
* ...
* <jdkToolchain>
* <version>1.8</version>
* <vendor>zulu</vendor>
* </jdkToolchain>
* </configuration>
* }
* </pre>
*
* @since 3.0.0-M5 and Maven 3.3.x
*/
@Parameter
private Map<String, String> jdkToolchain;
/**
*
*/
@Component
private ToolchainManager toolchainManager;
@Component
private LocationManager locationManager;
@Component
private ProviderDetector providerDetector;
private Toolchain toolchain;
private int effectiveForkCount = -1;
protected abstract String getPluginName();
protected abstract int getRerunFailingTestsCount();
@Override
public abstract List<String> getIncludes();
public abstract File getIncludesFile();
@Override
public abstract void setIncludes(List<String> includes);
public abstract File getExcludesFile();
/**
* Calls {@link #getSuiteXmlFiles()} as {@link List list}.
* Never returns <code>null</code>.
*
* @return list of TestNG suite XML files provided by MOJO
*/
protected abstract List<File> suiteXmlFiles();
/**
* @return {@code true} if {@link #getSuiteXmlFiles() suite-xml files array} is not empty.
*/
protected abstract boolean hasSuiteXmlFiles();
protected abstract String[] getExcludedEnvironmentVariables();
public abstract File[] getSuiteXmlFiles();
public abstract void setSuiteXmlFiles(File[] suiteXmlFiles);
public abstract String getRunOrder();
public abstract void setRunOrder(String runOrder);
public abstract Long getRunOrderRandomSeed();
public abstract void setRunOrderRandomSeed(Long runOrderRandomSeed);
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 boolean useModulePath();
protected abstract void setUseModulePath(boolean useModulePath);
protected abstract String getEnableProcessChecker();
protected abstract ForkNodeFactory getForkNode();
/**
* This plugin MOJO artifact.
*
* @return non-null plugin artifact
*/
protected Artifact getMojoArtifact() {
return getPluginDescriptor().getPluginArtifact();
}
private String getDefaultExcludes() {
return "**/*$*";
}
@Component(role = SurefireDependencyResolver.class)
private SurefireDependencyResolver surefireDependencyResolver;
private TestListResolver specificTests;
private TestListResolver includedExcludedTests;
private List<CommandLineOption> cli;
private volatile PluginConsoleLogger consoleLogger;
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
if (isSkipExecution()) {
getConsoleLogger().info("Tests are skipped.");
return;
}
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()) {
DefaultScanResult scan = scanForTestClasses();
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.)");
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.)");
default:
handleSummary(noTestsRun(), null);
return;
}
}
logReportsDirectory();
executeAfterPreconditionsChecked(scan, platform);
}
} finally {
platform.clearShutdownState();
removeShutdownHook(shutdownThread);
}
}
void setLogger(Logger logger) {
this.logger = logger;
}
void setSurefireDependencyResolver(SurefireDependencyResolver surefireDependencyResolver) {
this.surefireDependencyResolver = surefireDependencyResolver;
}
@Nonnull
protected final PluginConsoleLogger getConsoleLogger() {
if (consoleLogger == null) {
synchronized (this) {
if (consoleLogger == null) {
consoleLogger = new PluginConsoleLogger(logger);
}
}
}
return consoleLogger;
}
private static <T extends ToolchainManager> Toolchain getToolchainMaven33x(
Class<T> toolchainManagerType, T toolchainManager, MavenSession session, Map<String, String> toolchainArgs)
throws MojoFailureException {
Method getToolchainsMethod =
tryGetMethod(toolchainManagerType, "getToolchains", MavenSession.class, String.class, Map.class);
if (getToolchainsMethod != null) {
//noinspection unchecked
List<Toolchain> tcs =
invokeMethodWithArray(toolchainManager, getToolchainsMethod, session, "jdk", toolchainArgs);
if (tcs.isEmpty()) {
throw new MojoFailureException(
"Requested toolchain specification did not match any configured toolchain: " + toolchainArgs);
}
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 {
Toolchain tc = null;
if (getJdkToolchain() != null) {
tc = getToolchainMaven33x(ToolchainManager.class, getToolchainManager(), getSession(), getJdkToolchain());
}
if (tc == null) {
tc = getToolchainManager().getToolchainFromBuildContext("jdk", getSession());
}
return tc;
}
private void setupStuff() throws MojoFailureException {
if (getBooterArtifact() == null) {
throw new RuntimeException("Unable to locate surefire-booter in the list of plugin artifacts");
}
if (getToolchainManager() != null) {
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();
}
List<Artifact> getProjectTestArtifacts() {
return project.getTestArtifacts();
}
DefaultScanResult scanDependencies() throws MojoFailureException {
if (getDependenciesToScan() == null) {