From 6d175844115cc32d795610e449186f87ab631245 Mon Sep 17 00:00:00 2001 From: Tibor Digana Date: Sun, 30 Jun 2013 23:21:32 +0200 Subject: [PATCH 1/2] Merged --- .gitattributes | 8 + README.TXT | 38 +- deploySite.sh | 22 + maven-failsafe-plugin/pom.xml | 89 +- .../plugin/failsafe/IntegrationTestMojo.java | 62 +- maven-surefire-common/pom.xml | 20 +- .../plugin/surefire/AbstractSurefireMojo.java | 476 ++++++++--- .../maven/plugin/surefire/ClasspathCache.java | 6 +- .../plugin/surefire/CommonReflector.java | 8 +- .../surefire/InPluginVMSurefireStarter.java | 19 +- .../maven/plugin/surefire/ProviderInfo.java | 6 +- .../maven/plugin/surefire/ProviderList.java | 6 +- .../surefire/StartupReportConfiguration.java | 5 +- .../surefire/SurefireDependencyResolver.java | 7 +- .../surefire/SurefireExecutionParameters.java | 12 - .../plugin/surefire/SurefireProperties.java | 182 ++++- .../booterclient/BooterSerializer.java | 27 +- .../booterclient/ChecksumCalculator.java | 8 +- .../booterclient/ForkConfiguration.java | 59 +- .../booterclient/ForkNumberBucket.java | 87 ++ .../surefire/booterclient/ForkStarter.java | 214 +++-- .../booterclient/ProviderDetector.java | 7 +- .../lazytestprovider/FlushReceiver.java | 76 +- .../FlushReceiverProvider.java | 66 +- .../OutputStreamFlushableCommandline.java | 162 ++-- .../TestProvidingInputStream.java | 237 +++--- .../output/DeserializedStacktraceWriter.java | 10 +- .../booterclient/output/ForkClient.java | 20 +- .../output/ThreadedStreamConsumer.java | 43 +- .../surefire/report/ConsoleReporter.java | 255 +++--- .../report/DefaultReporterFactory.java | 281 +++---- .../surefire/report/DirectConsoleOutput.java | 130 +-- .../plugin/surefire/report/FileReporter.java | 14 +- .../surefire/report/FileReporterUtils.java | 50 ++ .../surefire/report/PrettyPrintXMLWriter.java | 7 +- .../surefire/report/ReportEntryType.java | 58 +- .../surefire/report/StatelessXmlReporter.java | 767 +++++++++++------- .../surefire/report/TestSetRunListener.java | 514 ++++++------ .../plugin/surefire/report/TestSetStats.java | 3 + .../TestcycleConsoleOutputReceiver.java | 76 +- .../surefire/report/WrappedReportEntry.java | 24 +- .../surefire/util/DependencyScanner.java | 185 +++++ .../surefire/util/DirectoryScanner.java | 219 ++--- .../maven/plugin/surefire/util/Relocator.java | 12 +- .../plugin/surefire/util/ScannerUtil.java | 86 ++ .../surefire/util/SpecificFileFilter.java | 134 +-- .../internal/FunkyTwoThreadBlockingQueue.java | 102 --- .../util/internal/TwoThreadBlockingQueue.java | 104 --- .../surefire/report/ReportTestCase.java | 0 .../surefire/report/ReportTestSuite.java | 0 .../surefire/report/SurefireReportParser.java | 2 +- .../surefire/report/TestSuiteXmlParser.java | 595 +++++++------- .../maven/surefire/report/RunStatistics.java | 303 ++++--- .../surefire/SurefirePropertiesTest.java | 5 +- ...rDeserializerStartupConfigurationTest.java | 20 +- .../booterclient/ForkConfigurationTest.java | 11 +- .../booterclient/ForkingRunListenerTest.java | 6 +- .../report/StatelessXMLReporterTest.java | 87 +- .../report/WrappedReportEntryTest.java | 146 ++-- .../util/DependenciesScannerTest.java | 94 +++ .../surefire/util/DirectoryScannerTest.java | 120 +-- .../surefire/util/SpecificFileFilterTest.java | 127 +-- .../surefire/report/ReportTestCaseTest.java | 0 .../surefire/report/ReportTestSuiteTest.java | 0 .../report/SurefireReportParserTest.java | 0 .../report/TestSuiteXmlParserTest.java | 213 +++-- .../surefire/report/RunStatisticsTest.java | 228 +++--- .../internal/TwoThreadBlockingQueueTest.java | 182 ----- ...apache.maven.surefire.test.FailingTest.xml | 0 .../failsafe-summary-old.xml | 0 .../testsuitexmlparser/failsafe-summary.xml | 0 .../resources/test-reports/TEST-AntUnit.xml | 0 .../test-reports/TEST-NoPackageTest.xml | 0 .../test-reports/TEST-NoTimeTestCaseTest.xml | 0 ...EST-classWithNoTests.NoMethodsTestCase.xml | 0 .../TEST-com.shape.CircleTest.xml | 0 .../test-reports/TEST-com.shape.PointTest.xml | 0 ...unit.twoTestCaseSuite.WrapperTestSuite.xml | 0 .../test-reports/com.shape.CircleTest.txt | 0 .../com.shapeclone.CircleTest.txt | 0 maven-surefire-plugin/pom.xml | 97 +-- .../src/assembly/site-source.xml | 9 + .../maven/plugin/surefire/SurefirePlugin.java | 61 +- maven-surefire-plugin/src/site/apt/api.apt.vm | 105 ++- .../src/site/apt/developing.apt.vm | 148 ++-- .../site/apt/examples/class-loading.apt.vm | 414 ++++------ .../apt/examples/configuring-classpath.apt.vm | 251 +++--- .../src/site/apt/examples/debugging.apt.vm | 180 ++-- ...fork-options-and-parallel-execution.apt.vm | 197 +++++ .../apt/examples/inclusion-exclusion.apt.vm | 279 ++++--- .../src/site/apt/examples/junit.apt.vm | 460 +++++------ .../src/site/apt/examples/pojo-test.apt.vm | 94 +-- .../src/site/apt/examples/providers.apt.vm | 97 ++- .../src/site/apt/examples/single-test.apt.vm | 170 ++-- .../site/apt/examples/skipping-test.apt.vm | 224 +++-- .../apt/examples/system-properties.apt.vm | 274 +++---- .../src/site/apt/examples/testng.apt.vm | 404 +++++---- .../src/site/apt/featurematrix.apt.vm | 49 +- .../src/site/apt/index.apt.vm | 175 ++-- .../src/site/apt/usage.apt.vm | 710 ++++++++-------- maven-surefire-plugin/src/site/fml/faq.fml | 4 +- .../src/site/markdown/newerrorsummary.md | 27 + maven-surefire-plugin/src/site/site.xml | 20 +- .../plugin/surefire/SurefirePluginTest.java | 34 + maven-surefire-report-plugin/pom.xml | 34 +- .../report/AbstractSurefireReportMojo.java | 27 +- .../surefire/report/FailsafeReportMojo.java | 13 +- .../surefire/report/SurefireReportMojo.java | 15 +- .../report/SurefireReportOnlyMojo.java | 9 +- .../apt/examples/changing-report-name.apt.vm | 63 +- .../apt/examples/cross-referencing.apt.vm | 111 ++- .../examples/report-custom-location.apt.vm | 99 ++- .../site/apt/examples/show-failures.apt.vm | 77 +- .../src/site/apt/usage.apt.vm | 62 +- .../src/site/site.xml | 5 - pom.xml | 164 +++- src/site/site.xml | 35 +- surefire-api/pom.xml | 19 +- .../surefire/runorder/RunEntryStatistics.java | 4 +- .../runorder/RunEntryStatisticsMap.java | 103 ++- .../runorder/ThreadedExecutionScheduler.java | 11 +- .../surefire/SpecificTestClassFilter.java | 15 +- .../surefire/booter/BaseProviderFactory.java | 10 +- .../booter/ForkingReporterFactory.java | 2 +- .../surefire/booter/ForkingRunListener.java | 18 +- .../maven/surefire/booter/JdkReflector.java | 64 -- .../booter/SurefireClassLoadersAware.java | 2 +- .../surefire/booter/SurefireReflector.java | 20 +- .../report/CategorizedReportEntry.java | 20 + .../surefire/report/ConsoleOutputCapture.java | 2 + ...ConsoleOutputReceiverForCurrentThread.java | 4 +- .../report/DefaultConsoleReporter.java | 82 +- .../report/DefaultDirectConsoleReporter.java | 80 +- .../report/LegacyPojoStackTraceWriter.java | 153 ++++ .../maven/surefire/report/ReportEntry.java | 7 + .../maven/surefire/report/SafeThrowable.java | 5 + .../surefire/report/SimpleReportEntry.java | 5 +- .../surefire/report/StackTraceWriter.java | 7 + .../maven/surefire/suite/RunResult.java | 7 +- .../surefire/testset/RunOrderParameters.java | 10 - .../maven/surefire/testset/TestRequest.java | 12 +- .../util/DefaultDirectoryScanner.java | 37 +- .../util/DefaultRunOrderCalculator.java | 40 +- .../surefire/util/DefaultScanResult.java | 295 +++---- .../maven/surefire/util/ReflectionUtils.java | 4 +- .../apache/maven/surefire/util/RunOrder.java | 12 +- .../maven/surefire/util/ScanResult.java | 78 +- .../maven/surefire/util/TestsToRun.java | 77 +- .../apache/maven/surefire/util/UrlUtils.java | 9 +- .../surefire/util/internal/ByteBuffer.java | 2 +- ...va => LegacyPojoStackTraceWriterTest.java} | 28 +- .../maven/surefire/report/MockReporter.java | 6 +- .../util/DefaultDirectoryScannerTest.java | 2 +- .../surefire/util/RunOrderCalculatorTest.java | 4 +- .../maven/surefire/util/ScanResultTest.java | 96 +-- .../maven/surefire/util/TestsToRunTest.java | 35 +- .../maven/surefire/util/UrlUtilsTest.java | 2 +- surefire-booter/pom.xml | 14 +- .../maven/surefire/booter/Classpath.java | 141 ++-- .../booter/ClasspathConfiguration.java | 63 +- .../maven/surefire/booter/ForkedBooter.java | 100 ++- .../surefire/booter/IsolatedClassLoader.java | 2 +- .../surefire/booter}/LazyTestsToRun.java | 376 +++++---- .../surefire/booter/PropertiesWrapper.java | 39 +- .../booter/ProviderConfiguration.java | 4 - .../surefire/booter/ProviderFactory.java | 34 +- .../surefire/booter/StartupConfiguration.java | 51 +- .../surefire/booter/TypeEncodedValue.java | 1 + .../maven/surefire/booter/ClasspathTest.java | 39 +- .../org/apache/maven/surefire/booter/Foo.java | 6 +- .../booter/PropertiesWrapperTest.java | 7 +- .../booter/SurefireReflectorTest.java | 20 +- surefire-grouper/pom.xml | 7 +- .../surefire/group/match/AndGroupMatcher.java | 6 +- .../group/match/InverseGroupMatcher.java | 4 +- .../surefire/group/match/OrGroupMatcher.java | 6 +- surefire-integration-tests/pom.xml | 34 +- .../surefire/its/AbstractTestCaseIT.java | 9 +- .../surefire/its/AdditionalClasspathIT.java | 8 +- .../maven/surefire/its/AggregateReportIT.java | 15 +- .../apache/maven/surefire/its/ArgLineIT.java | 8 +- .../maven/surefire/its/CheckSingleTestIT.java | 24 +- .../its/CheckTestFailIfNoTestsForkModeIT.java | 36 +- .../its/CheckTestFailIfNoTestsIT.java | 21 +- .../its/CheckTestNgBeforeMethodFailureIT.java | 10 +- .../its/CheckTestNgBeforeMethodIT.java | 8 +- .../its/CheckTestNgExecuteErrorIT.java | 2 +- .../its/CheckTestNgGroupThreadParallelIT.java | 8 +- .../surefire/its/CheckTestNgJdk14IT.java | 13 +- .../its/CheckTestNgListenerReporterIT.java | 8 +- .../its/CheckTestNgPathWithSpacesIT.java | 8 +- .../surefire/its/CheckTestNgReportTestIT.java | 8 +- .../surefire/its/CheckTestNgSuiteXmlIT.java | 11 +- .../its/CheckTestNgSuiteXmlSingleIT.java | 8 +- .../surefire/its/CheckTestNgVersionsIT.java | 30 +- .../maven/surefire/its/ClassPathOrderIT.java | 8 +- .../surefire/its/ClasspathFilteringIT.java | 8 +- .../its/ClasspathScopeFilteringIT.java | 8 +- .../maven/surefire/its/ConsoleOutputIT.java | 16 +- .../maven/surefire/its/CrashDetectionIT.java | 22 +- .../surefire/its/DefaultConfigurationIT.java | 8 +- .../surefire/its/EnvironmentVariableIT.java | 8 +- .../surefire/its/ForkConsoleOutputIT.java | 28 +- .../its/ForkConsoleOutputWithErrorsIT.java | 10 +- .../apache/maven/surefire/its/ForkModeIT.java | 130 ++- .../surefire/its/ForkModeMultiModuleIT.java | 164 ++++ .../its/IncludesExcludesFromFileIT.java | 43 +- .../surefire/its/IncludesExcludesIT.java | 17 +- .../maven/surefire/its/JUnit44HamcrestIT.java | 6 +- .../surefire/its/JUnit47RedirectOutputIT.java | 15 +- .../surefire/its/JUnit48TestCategoriesIT.java | 26 +- ...JUnit4ForkAlwaysStaticInitPollutionIT.java | 6 +- .../surefire/its/JUnit4RunListenerIT.java | 12 +- .../apache/maven/surefire/its/JUnitDepIT.java | 17 +- .../its/Junit47StaticInnerClassTestsIT.java | 13 + .../surefire/its/Junit47WithCucumberIT.java | 66 ++ .../surefire/its/Junit47concurrencyIT.java | 8 +- .../maven/surefire/its/Junit4IgnoreIT.java | 7 +- .../maven/surefire/its/Junit4VersionsIT.java | 19 +- .../its/NoRunnableTestsInClassIT.java | 6 +- .../surefire/its/PlainOldJavaClasspathIT.java | 6 +- .../maven/surefire/its/PlexusConflictIT.java | 9 +- .../maven/surefire/its/PojoSimpleIT.java | 6 +- .../maven/surefire/its/ReportersIT.java | 8 +- .../maven/surefire/its/ResultCountingIT.java | 11 +- .../apache/maven/surefire/its/RunOrderIT.java | 11 +- .../surefire/its/SiblingAggregatorIT.java | 13 +- .../maven/surefire/its/SmartStackTraceIT.java | 44 + .../surefire/its/SystemPropertiesTestIT.java | 7 +- .../surefire/its/TestMethodPatternIT.java | 16 +- .../surefire/its/TestMultipleMethodsIT.java | 7 +- .../its/TestNgParallelWithAnnotationsIT.java | 6 +- .../surefire/its/TestSingleMethodIT.java | 10 +- .../surefire/its/TimeoutForkedTestIT.java | 8 +- .../maven/surefire/its/TwoTestCasesIT.java | 17 +- .../maven/surefire/its/UmlautDirIT.java | 26 +- .../surefire/its/UnicodeTestNamesIT.java | 6 +- .../its/UseIsolatedClassLoaderIT.java | 6 +- .../surefire/its/WorkingDirectoryIT.java | 16 +- .../WorkingDirectoryIsInvalidPropertyIT.java | 8 +- .../its/WorkingDirectoryMissingIT.java | 7 +- .../surefire/its/XmlReporterRunTimeIT.java | 16 +- .../its/fixture/FailsafeOutputValidator.java | 5 +- .../its/fixture/HelperAssertions.java | 13 +- .../surefire/its/fixture/MavenLauncher.java | 446 ++++++++++ .../surefire/its/fixture/OutputValidator.java | 49 +- .../fixture/SurefireIntegrationTestCase.java | 76 -- .../SurefireJUnit4IntegrationTestCase.java | 31 +- .../its/fixture/SurefireLauncher.java | 430 +++------- .../its/fixture/SurefireLauncherTest.java | 3 +- .../its/fixture/SurefireReportParser.java | 109 --- .../maven/surefire/its/fixture/TestFile.java | 11 +- .../its/fixture/TestSuiteXmlParserTest.java | 36 - .../Surefire141PluggableProvidersIT.java | 13 +- .../Surefire146ForkPerTestNoSetupIT.java | 6 +- .../jiras/Surefire162CharsetProviderIT.java | 18 +- .../Surefire224WellFormedXmlFailuresIT.java | 20 +- .../jiras/Surefire257NotRerunningTestsIT.java | 8 +- .../Surefire260TestWithIdenticalNamesIT.java | 13 +- .../jiras/Surefire34SecurityManagerIT.java | 7 +- .../Surefire376TestNgAfterSuiteFailureIT.java | 8 +- .../Surefire377TestNgAndJUnitTogetherIT.java | 6 +- .../Surefire408ManualProviderSelectionIT.java | 6 +- .../Surefire42NotExtendingTestCaseIT.java | 6 +- .../its/jiras/Surefire44InnerClassTestIT.java | 6 +- .../its/jiras/Surefire500PuzzlingErrorIT.java | 6 +- .../Surefire510TestClassPathForkModesIT.java | 7 +- ...urefire569RunTestFromDependencyJarsIT.java | 25 + ...urefire570MultipleReportDirectoriesIT.java | 14 +- .../Surefire613TestCountInParallelIT.java | 8 +- ...fire621TestCountingJunit3InParallelIT.java | 6 +- ...628ConsoleOutputBeforeAndAfterClassIT.java | 6 +- ...34UnsettableSystemPropertiesWarningIT.java | 6 +- .../its/jiras/Surefire673MockitoIT.java | 6 +- .../Surefire674BuildFailingWhenErrorsIT.java | 9 +- ...re674BuildFailingWhenFailsafeErrorsIT.java | 8 +- .../Surefire685CommaSeparatedIncludesIT.java | 6 +- .../its/jiras/Surefire697NiceSummaryIT.java | 8 +- .../Surefire705ParallelForkTimeoutIT.java | 8 +- .../Surefire733AllOverrridesCapturedIT.java | 6 +- ...35ForkFailWithRedirectConsoleOutputIT.java | 2 +- .../jiras/Surefire740TruncatedCommaIT.java | 11 +- ...fire747MethodParallelWithSuiteCountIT.java | 7 +- .../Surefire763EnvironmentForkModeIT.java | 7 +- .../its/jiras/Surefire772BothReportsIT.java | 25 +- .../jiras/Surefire772NoFailsafeReportsIT.java | 19 +- .../jiras/Surefire772NoSurefireReportsIT.java | 24 +- .../jiras/Surefire772SpecifiedReportsIT.java | 24 +- .../Surefire801ForkModeNoneClassLoaderIT.java | 6 +- .../Surefire803MultiFailsafeExecsIT.java | 14 +- .../jiras/Surefire809GroupExpressionsIT.java | 2 +- .../jiras/Surefire812Log4JClassLoaderIT.java | 6 +- .../jiras/Surefire818NpeIgnoresTestsIT.java | 9 +- .../jiras/Surefire828EmptyGroupExprIT.java | 17 +- .../jiras/Surefire832ProviderSelectionIT.java | 6 +- .../jiras/Surefire847AdditionalFailureIT.java | 6 +- ...efire907PerThreadWithoutThreadCountIT.java | 4 +- ...fire920TestFailureIgnoreWithTimeoutIT.java | 6 +- .../Surefire926FailureWith2ProvidersIT.java | 8 +- .../jiras/Surefire930TestNgSuiteXmlIT.java | 5 +- .../its/jiras/Surefire943ReportContentIT.java | 131 +++ ...ire946KillMainProcessInReusableForkIT.java | 71 ++ .../jiras/Surefire972BizarreNoClassDefIT.java | 32 + .../jiras/Surefire975DefaultVMEncodingIT.java | 40 + .../jiras/Surefire979WrongClassLoaderIT.java | 39 + ...985ParameterizedRunnerAndCategoriesIT.java | 68 ++ .../resources/additional-classpath/pom.xml | 15 +- .../resources/aggregate-report/child1/pom.xml | 10 +- .../resources/aggregate-report/child2/pom.xml | 8 +- .../test/resources/aggregate-report/pom.xml | 30 +- .../src/test/resources/ant-ignore/.gitignore | 6 +- .../src/test/resources/ant-ignore/build.xml | 104 +-- .../src/test/resources/ant-ignore/ivy.xml | 12 +- .../src/test/resources/ant-ignore/pom.xml | 27 +- .../src/test/resources/ant-ignore/src/ivy.xml | 12 +- .../src/test/java/antignore/BasicTest.java | 4 +- .../test/resources/argLine-parameter/pom.xml | 10 +- .../resources/classpath-filtering/pom.xml | 8 +- .../test/resources/classpath-order/pom.xml | 9 +- .../classpath-scope-filtering/pom.xml | 8 +- .../test/resources/concurrentjunit47/pom.xml | 17 +- .../src/test/resources/consoleOutput/pom.xml | 17 +- .../resources/consoleoutput-noisy/pom.xml | 18 +- .../test/java/consoleoutput_noisy/Test1.java | 11 +- .../test/java/consoleoutput_noisy/Test2.java | 8 +- .../test/resources/crash-detection/pom.xml | 17 +- .../java/junit44/environment/BasicTest.java | 8 +- .../default-configuration-abstract/pom.xml | 18 +- .../pom.xml | 18 +- .../default-configuration-noTests/pom.xml | 18 +- .../resources/default-configuration/pom.xml | 18 +- .../java/failingbuilds/ExceptionsTest.java | 36 +- .../failsafe-regular/invoker.properties | 19 + .../test/resources/failsafe-regular/pom.xml | 83 ++ .../failsafe-regular/src/test/java/MyAT.java | 26 + .../failsafe-regular/src/test/java/MyIT.java | 26 + .../BeforeClassError.java | 84 +- .../BeforeClassFailure.java | 84 +- .../failureresultcounting/BeforeError.java | 94 +-- .../failureresultcounting/BeforeFailure.java | 84 +- .../java/failureresultcounting/NoErrors.java | 84 +- .../failureresultcounting/OrdinaryError.java | 82 +- .../src/test/resources/failureOutput/pom.xml | 56 ++ .../test/java/forkConsoleOutput/Test1.java | 85 ++ .../test/java/forkConsoleOutput/Test2.java | 29 +- .../src/test/resources/failureOutput/test | 15 + .../fork-mode-multimodule/module-a/pom.xml | 36 + .../src/test/java/forkMode/Test1.java | 48 ++ .../src/test/java/forkMode/Test2.java | 17 + .../src/test/java/forkMode/Test3.java | 15 + .../fork-mode-multimodule/module-b/pom.xml | 36 + .../src/test/java/forkMode/Test1.java | 48 ++ .../src/test/java/forkMode/Test2.java | 17 + .../src/test/java/forkMode/Test3.java | 15 + .../resources/fork-mode-multimodule/pom.xml | 69 ++ .../src/test/resources/fork-mode/pom.xml | 1 + .../src/test/java/forkMode/Test1.java | 4 +- .../test/resources/includes-excludes/pom.xml | 2 + .../src/test/resources/junit-ignore/pom.xml | 4 +- ...ClassAndMethodIgnoreNothingToRunTest.java} | 2 +- ...velIgnore1WithMethodThatIsNormalTest.java} | 2 +- ...velIgnore2WithMethodThatIsNormalTest.java} | 2 +- ...oredMethodsAnd1AssumptionFailureTest.java} | 2 +- .../test/resources/junit47-cucumber/pom.xml | 81 ++ .../sample/cucumber/FailingCucumberTest.java | 20 +- .../java/org/sample/cucumber/StepDefs.java | 57 ++ .../sample/cucumber/SuccessCucumberTest.java | 31 + .../src/test/resources/failing/Sample.feature | 10 + .../src/test/resources/success/Sample.feature | 10 + .../resources/junit47-redirect-output/pom.xml | 1 + .../test/java/junit47ConsoleOutput/Test0.java | 63 ++ .../junit47-static-inner-class-tests/pom.xml | 44 + .../src/test/java/junit4/BasicTest.java | 13 + .../junit4/TopLevelAbstractClassTest.java | 13 + .../java/junit4/TopLevelInterfaceTest.java | 13 + .../src/test/java/junit4/BasicTest.java | 2 + .../src/test/java/junit4/SampleCategory.java | 6 + .../resources/junit48-smartStackTrace/pom.xml | 63 ++ .../test/java/junit4/SmartStackTraceTest.java | 30 + .../src/test/resources/pom.xml | 40 + .../java/resultcounting/MySuiteTest1.java | 48 +- .../java/resultcounting/MySuiteTest2.java | 50 +- .../java/resultcounting/MySuiteTest3.java | 52 +- .../src/test/java/resultcounting/Test1.java | 150 ++-- .../test/java/smallresultcounting/Test1.java | 92 +-- .../test/java/smallresultcounting/Test2.java | 174 ++-- .../test/java/surefire500/PassingTest.java | 66 +- .../src/test/java/surefire500/Suite.java | 20 +- .../module1/pom.xml | 50 ++ .../pom.xml | 17 + .../testjar/pom.xml | 47 ++ .../testjar/src/test/java/org/test/TestA.java | 10 + .../testjar/src/test/java/org/test/TestB.java | 10 + ...eReport.surefireReportTest.MyClassTest.xml | 71 -- ...eReport.surefireReportTest.MyClassTest.txt | 13 - ...eReport.surefireReportTest.MyClassTest.xml | 71 -- ...eReport.surefireReportTest.MyClassTest.txt | 13 - .../src/it/java/mho/MySuiteTest1.java | 58 +- .../src/it/java/mho/MySuiteTest2.java | 60 +- .../src/it/java/mho/MySuiteTest3.java | 60 +- .../src/test/java/surefire685/TestA.java | 58 +- .../src/test/java/surefire685/TestB.java | 58 +- .../src/test/java/surefire685/TestC.java | 58 +- .../surefire-818-ignored-tests-on-npe/pom.xml | 74 +- .../src/test/java/cyril/test/FirstTest.java | 72 +- .../src/test/java/cyril/test/IgnoredTest.java | 32 +- .../src/test/java/cyril/test/Message.java | 36 +- .../src/test/java/cyril/test/MyService.java | 16 +- .../test/java/cyril/test/MyServiceImpl.java | 24 +- .../surefire/testcase/JunitParamsTest.java | 102 +-- .../surefire/testcase/NonJunitParamsTest.java | 74 +- .../resources/surefire-847-testngfail/pom.xml | 134 +-- .../surefire-926-2-provider-failure/pom.xml | 82 +- .../src/test/java/com/company/JUnitTest.java | 24 +- .../src/test/java/com/company/TestNGTest.java | 24 +- .../surefire-931-provider-failure/pom.xml | 96 +-- .../java/com/mycompany/testfailed/App.java | 26 +- .../com/mycompany/testfailed/AppTest.java | 36 +- .../surefire-942-testngSuite/pom.xml | 37 + .../src/test/java/org/BasicTest.java | 48 ++ .../src/test/resources/config.xml | 8 + .../surefire-943-report-content/pom.xml | 47 ++ .../test/java/org/sample/module/My1Test.java | 34 + .../test/java/org/sample/module/My2Test.java | 33 + .../test/java/org/sample/module/My3Test.java | 25 + .../test/java/org/sample/module/My4Test.java | 27 + .../pom.xml | 64 ++ .../java/junit44/environment/Basic01Test.java | 26 + .../java/junit44/environment/Basic02Test.java | 26 + .../java/junit44/environment/Basic03Test.java | 26 + .../java/junit44/environment/Basic04Test.java | 26 + .../java/junit44/environment/Basic05Test.java | 26 + .../java/junit44/environment/Basic06Test.java | 26 + .../java/junit44/environment/Basic07Test.java | 26 + .../java/junit44/environment/Basic08Test.java | 26 + .../java/junit44/environment/Basic09Test.java | 26 + .../java/junit44/environment/Basic10Test.java | 26 + .../surefire-946-self-destruct-plugin/pom.xml | 56 ++ .../selfdestruct/SelfDestructMojo.java | 142 ++++ .../boom/pom.xml | 51 ++ .../maven/surefire/crb/ClassRuleIT.java | 24 + .../class-rule/pom.xml | 17 + .../ExampleClassRule.java | 29 + .../surefire-972-bizarre-noclassdef/pom.xml | 32 + .../surefire-975-wrong-encoding/pom.xml | 37 + .../src/test/java/EncodingInReportTest.java | 14 + .../module1/pom.xml | 36 + .../src/main/java/surefire979/TestBase.java | 17 + .../module2/pom.xml | 37 + .../FailingStaticInitializerTest.java | 17 + .../pom.xml | 28 + .../pom.xml | 55 ++ .../test/java/sample/CategoryActivated.java | 6 + .../test/java/sample/CategoryNotSelected.java | 6 + .../parameterized/Parameterized01Test.java | 42 + .../parameterized/Parameterized02Test.java | 42 + .../parameterized/Parameterized03Test.java | 42 + .../test-helper-dump-pid-plugin/pom.xml | 62 ++ .../plugins/surefire/dumppid/DumpPidMojo.java | 70 ++ .../test/resources/unicode-testnames/pom.xml | 5 + .../resources/working-directory/child/pom.xml | 8 +- .../test/resources/working-directory/pom.xml | 17 +- surefire-providers/common-java5/pom.xml | 74 ++ .../surefire/report/PojoStackTraceWriter.java | 46 +- .../report/SmartStackTraceParser.java | 318 ++++++++ .../maven/surefire/report/ABaseClass.java | 29 + .../surefire/report/ADifferen0tTestClass.java | 25 + .../maven/surefire/report/ASubClass.java | 24 + .../maven/surefire/report/ATestClass.java | 63 ++ .../surefire/report/AssertionNoMessage.java | 31 + .../surefire/report/CaseThatWillFail.java | 31 + .../maven/surefire/report/FailWithFail.java | 31 + .../surefire/report/InnerATestClass.java} | 26 +- .../report/PojoStackTraceWriterTest.java | 63 ++ .../surefire/report/RunnableTestClass1.java | 52 ++ .../surefire/report/RunnableTestClass2.java | 43 + .../report/SmartStackTraceParserTest.java | 324 ++++++++ .../maven/surefire/report/TestClass1.java | 42 + .../maven/surefire/report/TestClass2.java | 31 + surefire-providers/common-junit3/pom.xml | 5 +- .../common/junit3/JUnit3Reflector.java | 2 +- surefire-providers/common-junit4/pom.xml | 10 +- .../common/junit4/JUnit4RunListener.java | 62 +- .../common/junit4/JUnit4StackTraceWriter.java | 36 +- .../common/junit4/JUnit4TestChecker.java | 19 +- surefire-providers/common-junit48/pom.xml | 10 +- .../common/junit48/FilterFactory.java | 144 ++-- .../junit48/JUnit46StackTraceWriter.java | 55 ++ .../common/junit48/JUnit48Reflector.java | 4 +- .../common/junit48/JUnit48TestChecker.java | 70 ++ .../common/junit48/JUnit48ReflectorTest.java | 6 + .../junit48/JUnit48TestCheckerTest.java | 75 ++ surefire-providers/pom.xml | 8 +- surefire-providers/surefire-junit3/pom.xml | 5 +- .../maven/surefire/junit/JUnit3Provider.java | 3 +- .../maven/surefire/junit/PojoTestSet.java | 32 +- .../junit/TestListenerInvocationHandler.java | 7 +- .../surefire/junit/JUnitTestSetTest.java | 240 +++--- surefire-providers/surefire-junit4/pom.xml | 12 +- .../maven/surefire/junit4/JUnit4Provider.java | 13 +- .../surefire/junit4/JUnit4Provider.java.orig | 297 +++++++ .../surefire/junit4/JUnit4ProviderTest.java | 2 +- surefire-providers/surefire-junit47/pom.xml | 27 +- .../junitcore/AsynchronousRunner.java | 162 ++-- .../junitcore/ClassesParallelRunListener.java | 2 +- ...anager.java => ConcurrentRunListener.java} | 64 +- .../junitcore/JUnitCoreParameters.java | 1 - .../surefire/junitcore/JUnitCoreProvider.java | 65 +- .../junitcore/JUnitCoreRunListener.java | 40 +- .../surefire/junitcore/JUnitCoreWrapper.java | 75 +- .../maven/surefire/junitcore/JUnitUtils.java | 99 +++ .../junitcore/MethodsParallelRunListener.java | 2 +- .../junitcore/NonConcurrentRunListener.java | 165 ++++ .../surefire/junitcore/SynchronousRunner.java | 74 +- .../maven/surefire/junitcore/TestMethod.java | 31 +- .../maven/surefire/junitcore/TestSet.java | 12 +- ...st.java => ConcurrentRunListenerTest.java} | 2 +- .../junitcore/JUnitCoreRunListenerTest.java | 22 + .../surefire/junitcore/JUnitCoreTester.java | 4 +- .../surefire/junitcore/Surefire746Test.java | 4 +- .../surefire/junitcore/TestMethodTest.java | 4 +- .../surefire-testng-utils/pom.xml | 5 +- surefire-providers/surefire-testng/pom.xml | 24 +- .../testng/TestNGDirectoryTestSuite.java | 51 +- .../maven/surefire/testng/TestNGExecutor.java | 80 +- .../maven/surefire/testng/TestNGProvider.java | 9 +- .../maven/surefire/testng/TestNGReporter.java | 2 +- .../surefire/testng/TestNGXmlTestSuite.java | 24 +- surefire-report-parser/pom.xml | 94 +++ .../surefire/report}/ReportTestCase.java | 2 +- .../surefire/report}/ReportTestSuite.java | 2 +- .../surefire/report/SurefireReportParser.java | 274 +++++++ .../surefire/report}/TestSuiteXmlParser.java | 58 +- .../surefire/report/ReportTestCaseTest.java | 82 ++ .../surefire/report/ReportTestSuiteTest.java | 118 +++ .../report/SurefireReportParserTest.java | 242 ++++++ .../report/TestSuiteXmlParserTest.java | 136 ++++ ...apache.maven.surefire.test.FailingTest.xml | 154 ++++ .../failsafe-summary-old.xml | 8 + .../testsuitexmlparser/failsafe-summary.xml | 8 + .../resources/test-reports/TEST-AntUnit.xml | 11 + .../test-reports/TEST-NoPackageTest.xml | 256 ++++++ .../test-reports/TEST-NoTimeTestCaseTest.xml | 92 +++ ...EST-classWithNoTests.NoMethodsTestCase.xml | 73 ++ .../TEST-com.shape.CircleTest.xml | 200 +++++ .../test-reports/TEST-com.shape.PointTest.xml | 142 ++++ ...unit.twoTestCaseSuite.WrapperTestSuite.xml | 73 ++ .../test-reports/com.shape.CircleTest.txt | 122 +++ .../com.shapeclone.CircleTest.txt | 122 +++ surefire-setup-integration-tests/pom.xml | 68 +- surefire-shadefire/pom.xml | 5 +- 551 files changed, 19273 insertions(+), 10153 deletions(-) create mode 100644 .gitattributes create mode 100644 deploySite.sh create mode 100644 maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/ForkNumberBucket.java create mode 100644 maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/FileReporterUtils.java create mode 100644 maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/util/DependencyScanner.java create mode 100644 maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/util/ScannerUtil.java delete mode 100644 maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/util/internal/FunkyTwoThreadBlockingQueue.java delete mode 100644 maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/util/internal/TwoThreadBlockingQueue.java rename {maven-surefire-report-plugin => maven-surefire-common}/src/main/java/org/apache/maven/plugins/surefire/report/ReportTestCase.java (100%) rename {maven-surefire-report-plugin => maven-surefire-common}/src/main/java/org/apache/maven/plugins/surefire/report/ReportTestSuite.java (100%) rename {maven-surefire-report-plugin => maven-surefire-common}/src/main/java/org/apache/maven/plugins/surefire/report/SurefireReportParser.java (99%) rename {maven-surefire-report-plugin => maven-surefire-common}/src/main/java/org/apache/maven/plugins/surefire/report/TestSuiteXmlParser.java (91%) create mode 100644 maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/util/DependenciesScannerTest.java rename {maven-surefire-report-plugin => maven-surefire-common}/src/test/java/org/apache/maven/plugins/surefire/report/ReportTestCaseTest.java (100%) rename {maven-surefire-report-plugin => maven-surefire-common}/src/test/java/org/apache/maven/plugins/surefire/report/ReportTestSuiteTest.java (100%) rename {maven-surefire-report-plugin => maven-surefire-common}/src/test/java/org/apache/maven/plugins/surefire/report/SurefireReportParserTest.java (100%) rename {maven-surefire-report-plugin => maven-surefire-common}/src/test/java/org/apache/maven/plugins/surefire/report/TestSuiteXmlParserTest.java (64%) delete mode 100644 maven-surefire-common/src/test/java/org/apache/maven/surefire/util/internal/TwoThreadBlockingQueueTest.java rename {surefire-integration-tests => maven-surefire-common}/src/test/resources/fixture/testsuitexmlparser/TEST-org.apache.maven.surefire.test.FailingTest.xml (100%) rename {surefire-integration-tests => maven-surefire-common}/src/test/resources/fixture/testsuitexmlparser/failsafe-summary-old.xml (100%) rename {surefire-integration-tests => maven-surefire-common}/src/test/resources/fixture/testsuitexmlparser/failsafe-summary.xml (100%) rename {maven-surefire-report-plugin => maven-surefire-common}/src/test/resources/test-reports/TEST-AntUnit.xml (100%) rename {maven-surefire-report-plugin => maven-surefire-common}/src/test/resources/test-reports/TEST-NoPackageTest.xml (100%) rename {maven-surefire-report-plugin => maven-surefire-common}/src/test/resources/test-reports/TEST-NoTimeTestCaseTest.xml (100%) rename {maven-surefire-report-plugin => maven-surefire-common}/src/test/resources/test-reports/TEST-classWithNoTests.NoMethodsTestCase.xml (100%) rename {maven-surefire-report-plugin => maven-surefire-common}/src/test/resources/test-reports/TEST-com.shape.CircleTest.xml (100%) rename {maven-surefire-report-plugin => maven-surefire-common}/src/test/resources/test-reports/TEST-com.shape.PointTest.xml (100%) rename {maven-surefire-report-plugin => maven-surefire-common}/src/test/resources/test-reports/TEST-junit.twoTestCaseSuite.WrapperTestSuite.xml (100%) rename {maven-surefire-report-plugin => maven-surefire-common}/src/test/resources/test-reports/com.shape.CircleTest.txt (100%) rename {maven-surefire-report-plugin => maven-surefire-common}/src/test/resources/test-reports/com.shapeclone.CircleTest.txt (100%) create mode 100644 maven-surefire-plugin/src/site/apt/examples/fork-options-and-parallel-execution.apt.vm create mode 100644 maven-surefire-plugin/src/site/markdown/newerrorsummary.md delete mode 100644 surefire-api/src/main/java/org/apache/maven/surefire/booter/JdkReflector.java create mode 100644 surefire-api/src/main/java/org/apache/maven/surefire/report/LegacyPojoStackTraceWriter.java rename surefire-api/src/test/java/org/apache/maven/surefire/report/{PojoStackTraceWriterTest.java => LegacyPojoStackTraceWriterTest.java} (87%) rename {surefire-api/src/main/java/org/apache/maven/surefire/util => surefire-booter/src/main/java/org/apache/maven/surefire/booter}/LazyTestsToRun.java (75%) create mode 100644 surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/ForkModeMultiModuleIT.java create mode 100644 surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/Junit47StaticInnerClassTestsIT.java create mode 100644 surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/Junit47WithCucumberIT.java create mode 100644 surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/SmartStackTraceIT.java create mode 100644 surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/fixture/MavenLauncher.java delete mode 100644 surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/fixture/SurefireIntegrationTestCase.java delete mode 100644 surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/fixture/SurefireReportParser.java delete mode 100644 surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/fixture/TestSuiteXmlParserTest.java create mode 100644 surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire569RunTestFromDependencyJarsIT.java create mode 100644 surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire943ReportContentIT.java create mode 100644 surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire946KillMainProcessInReusableForkIT.java create mode 100644 surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire972BizarreNoClassDefIT.java create mode 100644 surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire975DefaultVMEncodingIT.java create mode 100644 surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire979WrongClassLoaderIT.java create mode 100644 surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire985ParameterizedRunnerAndCategoriesIT.java create mode 100644 surefire-integration-tests/src/test/resources/failsafe-regular/invoker.properties create mode 100644 surefire-integration-tests/src/test/resources/failsafe-regular/pom.xml create mode 100644 surefire-integration-tests/src/test/resources/failsafe-regular/src/test/java/MyAT.java create mode 100644 surefire-integration-tests/src/test/resources/failsafe-regular/src/test/java/MyIT.java create mode 100644 surefire-integration-tests/src/test/resources/failureOutput/pom.xml create mode 100644 surefire-integration-tests/src/test/resources/failureOutput/src/test/java/forkConsoleOutput/Test1.java rename maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/util/internal/Java15BlockingQueue.java => surefire-integration-tests/src/test/resources/failureOutput/src/test/java/forkConsoleOutput/Test2.java (62%) create mode 100644 surefire-integration-tests/src/test/resources/failureOutput/test create mode 100644 surefire-integration-tests/src/test/resources/fork-mode-multimodule/module-a/pom.xml create mode 100644 surefire-integration-tests/src/test/resources/fork-mode-multimodule/module-a/src/test/java/forkMode/Test1.java create mode 100644 surefire-integration-tests/src/test/resources/fork-mode-multimodule/module-a/src/test/java/forkMode/Test2.java create mode 100644 surefire-integration-tests/src/test/resources/fork-mode-multimodule/module-a/src/test/java/forkMode/Test3.java create mode 100644 surefire-integration-tests/src/test/resources/fork-mode-multimodule/module-b/pom.xml create mode 100644 surefire-integration-tests/src/test/resources/fork-mode-multimodule/module-b/src/test/java/forkMode/Test1.java create mode 100644 surefire-integration-tests/src/test/resources/fork-mode-multimodule/module-b/src/test/java/forkMode/Test2.java create mode 100644 surefire-integration-tests/src/test/resources/fork-mode-multimodule/module-b/src/test/java/forkMode/Test3.java create mode 100644 surefire-integration-tests/src/test/resources/fork-mode-multimodule/pom.xml rename surefire-integration-tests/src/test/resources/junit-ignore/src/test/java/junit/ignore/{BasicTest.java => ClassAndMethodIgnoreNothingToRunTest.java} (84%) rename surefire-integration-tests/src/test/resources/junit-ignore/src/test/java/junit/ignore/{ClassLevelIgnore1Test.java => ClassLevelIgnore1WithMethodThatIsNormalTest.java} (80%) rename surefire-integration-tests/src/test/resources/junit-ignore/src/test/java/junit/ignore/{ClassLevelIgnore2Test.java => ClassLevelIgnore2WithMethodThatIsNormalTest.java} (80%) rename surefire-integration-tests/src/test/resources/junit-ignore/src/test/java/junit/ignore/{IgnoreWithMessagesTest.java => NormalClassWithThreeIgnoredMethodsAnd1AssumptionFailureTest.java} (87%) create mode 100644 surefire-integration-tests/src/test/resources/junit47-cucumber/pom.xml rename maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/util/internal/BlockingQueue.java => surefire-integration-tests/src/test/resources/junit47-cucumber/src/test/java/org/sample/cucumber/FailingCucumberTest.java (71%) create mode 100644 surefire-integration-tests/src/test/resources/junit47-cucumber/src/test/java/org/sample/cucumber/StepDefs.java create mode 100644 surefire-integration-tests/src/test/resources/junit47-cucumber/src/test/java/org/sample/cucumber/SuccessCucumberTest.java create mode 100644 surefire-integration-tests/src/test/resources/junit47-cucumber/src/test/resources/failing/Sample.feature create mode 100644 surefire-integration-tests/src/test/resources/junit47-cucumber/src/test/resources/success/Sample.feature create mode 100644 surefire-integration-tests/src/test/resources/junit47-redirect-output/src/test/java/junit47ConsoleOutput/Test0.java create mode 100644 surefire-integration-tests/src/test/resources/junit47-static-inner-class-tests/pom.xml create mode 100644 surefire-integration-tests/src/test/resources/junit47-static-inner-class-tests/src/test/java/junit4/BasicTest.java create mode 100644 surefire-integration-tests/src/test/resources/junit47-static-inner-class-tests/src/test/java/junit4/TopLevelAbstractClassTest.java create mode 100644 surefire-integration-tests/src/test/resources/junit47-static-inner-class-tests/src/test/java/junit4/TopLevelInterfaceTest.java create mode 100644 surefire-integration-tests/src/test/resources/junit48-method-pattern/src/test/java/junit4/SampleCategory.java create mode 100644 surefire-integration-tests/src/test/resources/junit48-smartStackTrace/pom.xml create mode 100644 surefire-integration-tests/src/test/resources/junit48-smartStackTrace/src/test/java/junit4/SmartStackTraceTest.java create mode 100644 surefire-integration-tests/src/test/resources/pom.xml create mode 100644 surefire-integration-tests/src/test/resources/surefire-569-RunTestFromDependencyJars/module1/pom.xml create mode 100644 surefire-integration-tests/src/test/resources/surefire-569-RunTestFromDependencyJars/pom.xml create mode 100644 surefire-integration-tests/src/test/resources/surefire-569-RunTestFromDependencyJars/testjar/pom.xml create mode 100644 surefire-integration-tests/src/test/resources/surefire-569-RunTestFromDependencyJars/testjar/src/test/java/org/test/TestA.java create mode 100644 surefire-integration-tests/src/test/resources/surefire-569-RunTestFromDependencyJars/testjar/src/test/java/org/test/TestB.java delete mode 100644 surefire-integration-tests/src/test/resources/surefire-570-multipleReportDirectories/module1/src/test/resources/surefire-reports/TEST-org.apache.maven.surefireReport.surefireReportTest.MyClassTest.xml delete mode 100644 surefire-integration-tests/src/test/resources/surefire-570-multipleReportDirectories/module1/src/test/resources/surefire-reports/org.apache.maven.surefireReport.surefireReportTest.MyClassTest.txt delete mode 100644 surefire-integration-tests/src/test/resources/surefire-570-multipleReportDirectories/module2/src/test/resources/surefire-reports/TEST-org.apache.maven.surefireReport.surefireReportTest.MyClassTest.xml delete mode 100644 surefire-integration-tests/src/test/resources/surefire-570-multipleReportDirectories/module2/src/test/resources/surefire-reports/org.apache.maven.surefireReport.surefireReportTest.MyClassTest.txt create mode 100644 surefire-integration-tests/src/test/resources/surefire-942-testngSuite/pom.xml create mode 100644 surefire-integration-tests/src/test/resources/surefire-942-testngSuite/src/test/java/org/BasicTest.java create mode 100644 surefire-integration-tests/src/test/resources/surefire-942-testngSuite/src/test/resources/config.xml create mode 100644 surefire-integration-tests/src/test/resources/surefire-943-report-content/pom.xml create mode 100644 surefire-integration-tests/src/test/resources/surefire-943-report-content/src/test/java/org/sample/module/My1Test.java create mode 100644 surefire-integration-tests/src/test/resources/surefire-943-report-content/src/test/java/org/sample/module/My2Test.java create mode 100644 surefire-integration-tests/src/test/resources/surefire-943-report-content/src/test/java/org/sample/module/My3Test.java create mode 100644 surefire-integration-tests/src/test/resources/surefire-943-report-content/src/test/java/org/sample/module/My4Test.java create mode 100644 surefire-integration-tests/src/test/resources/surefire-946-killMainProcessInReusableFork/pom.xml create mode 100644 surefire-integration-tests/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic01Test.java create mode 100644 surefire-integration-tests/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic02Test.java create mode 100644 surefire-integration-tests/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic03Test.java create mode 100644 surefire-integration-tests/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic04Test.java create mode 100644 surefire-integration-tests/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic05Test.java create mode 100644 surefire-integration-tests/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic06Test.java create mode 100644 surefire-integration-tests/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic07Test.java create mode 100644 surefire-integration-tests/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic08Test.java create mode 100644 surefire-integration-tests/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic09Test.java create mode 100644 surefire-integration-tests/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic10Test.java create mode 100644 surefire-integration-tests/src/test/resources/surefire-946-self-destruct-plugin/pom.xml create mode 100644 surefire-integration-tests/src/test/resources/surefire-946-self-destruct-plugin/src/main/java/org/apache/maven/plugins/surefire/selfdestruct/SelfDestructMojo.java create mode 100644 surefire-integration-tests/src/test/resources/surefire-972-bizarre-noclassdef/boom/pom.xml create mode 100644 surefire-integration-tests/src/test/resources/surefire-972-bizarre-noclassdef/boom/src/test/java/org/apache/maven/surefire/crb/ClassRuleIT.java create mode 100644 surefire-integration-tests/src/test/resources/surefire-972-bizarre-noclassdef/class-rule/pom.xml create mode 100644 surefire-integration-tests/src/test/resources/surefire-972-bizarre-noclassdef/class-rule/src/main/java/org.apache.maven.surefire.crb/ExampleClassRule.java create mode 100644 surefire-integration-tests/src/test/resources/surefire-972-bizarre-noclassdef/pom.xml create mode 100644 surefire-integration-tests/src/test/resources/surefire-975-wrong-encoding/pom.xml create mode 100644 surefire-integration-tests/src/test/resources/surefire-975-wrong-encoding/src/test/java/EncodingInReportTest.java create mode 100644 surefire-integration-tests/src/test/resources/surefire-979-smartStackTrace-wrongClassloader/module1/pom.xml create mode 100644 surefire-integration-tests/src/test/resources/surefire-979-smartStackTrace-wrongClassloader/module1/src/main/java/surefire979/TestBase.java create mode 100644 surefire-integration-tests/src/test/resources/surefire-979-smartStackTrace-wrongClassloader/module2/pom.xml create mode 100644 surefire-integration-tests/src/test/resources/surefire-979-smartStackTrace-wrongClassloader/module2/src/test/java/surefire979/FailingStaticInitializerTest.java create mode 100644 surefire-integration-tests/src/test/resources/surefire-979-smartStackTrace-wrongClassloader/pom.xml create mode 100644 surefire-integration-tests/src/test/resources/surefire-985-parameterized-and-categories/pom.xml create mode 100644 surefire-integration-tests/src/test/resources/surefire-985-parameterized-and-categories/src/test/java/sample/CategoryActivated.java create mode 100644 surefire-integration-tests/src/test/resources/surefire-985-parameterized-and-categories/src/test/java/sample/CategoryNotSelected.java create mode 100644 surefire-integration-tests/src/test/resources/surefire-985-parameterized-and-categories/src/test/java/sample/parameterized/Parameterized01Test.java create mode 100644 surefire-integration-tests/src/test/resources/surefire-985-parameterized-and-categories/src/test/java/sample/parameterized/Parameterized02Test.java create mode 100644 surefire-integration-tests/src/test/resources/surefire-985-parameterized-and-categories/src/test/java/sample/parameterized/Parameterized03Test.java create mode 100644 surefire-integration-tests/src/test/resources/test-helper-dump-pid-plugin/pom.xml create mode 100644 surefire-integration-tests/src/test/resources/test-helper-dump-pid-plugin/src/main/java/org/apache/maven/plugins/surefire/dumppid/DumpPidMojo.java create mode 100644 surefire-providers/common-java5/pom.xml rename {surefire-api => surefire-providers/common-java5}/src/main/java/org/apache/maven/surefire/report/PojoStackTraceWriter.java (61%) create mode 100644 surefire-providers/common-java5/src/main/java/org/apache/maven/surefire/report/SmartStackTraceParser.java create mode 100644 surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/ABaseClass.java create mode 100644 surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/ADifferen0tTestClass.java create mode 100644 surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/ASubClass.java create mode 100644 surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/ATestClass.java create mode 100644 surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/AssertionNoMessage.java create mode 100644 surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/CaseThatWillFail.java create mode 100644 surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/FailWithFail.java rename surefire-providers/{surefire-junit3/src/main/java/org/apache/maven/surefire/junit/JUnitStackTraceWriter.java => common-java5/src/test/java/org/apache/maven/surefire/report/InnerATestClass.java} (66%) create mode 100644 surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/PojoStackTraceWriterTest.java create mode 100644 surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/RunnableTestClass1.java create mode 100644 surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/RunnableTestClass2.java create mode 100644 surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/SmartStackTraceParserTest.java create mode 100644 surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/TestClass1.java create mode 100644 surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/TestClass2.java create mode 100644 surefire-providers/common-junit48/src/main/java/org/apache/maven/surefire/common/junit48/JUnit46StackTraceWriter.java create mode 100644 surefire-providers/common-junit48/src/main/java/org/apache/maven/surefire/common/junit48/JUnit48TestChecker.java create mode 100644 surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/JUnit48TestCheckerTest.java create mode 100644 surefire-providers/surefire-junit4/src/main/java/org/apache/maven/surefire/junit4/JUnit4Provider.java.orig rename surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/{ConcurrentReporterManager.java => ConcurrentRunListener.java} (75%) create mode 100644 surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/JUnitUtils.java create mode 100644 surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/NonConcurrentRunListener.java rename surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/{ConcurrentReporterManagerTest.java => ConcurrentRunListenerTest.java} (99%) create mode 100644 surefire-report-parser/pom.xml rename {surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/fixture => surefire-report-parser/src/main/java/org/apache/maven/plugins/surefire/report}/ReportTestCase.java (97%) rename {surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/fixture => surefire-report-parser/src/main/java/org/apache/maven/plugins/surefire/report}/ReportTestSuite.java (98%) create mode 100644 surefire-report-parser/src/main/java/org/apache/maven/plugins/surefire/report/SurefireReportParser.java rename {surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/fixture => surefire-report-parser/src/main/java/org/apache/maven/plugins/surefire/report}/TestSuiteXmlParser.java (85%) mode change 100755 => 100644 create mode 100644 surefire-report-parser/src/test/java/org/apache/maven/plugins/surefire/report/ReportTestCaseTest.java create mode 100644 surefire-report-parser/src/test/java/org/apache/maven/plugins/surefire/report/ReportTestSuiteTest.java create mode 100644 surefire-report-parser/src/test/java/org/apache/maven/plugins/surefire/report/SurefireReportParserTest.java create mode 100644 surefire-report-parser/src/test/java/org/apache/maven/plugins/surefire/report/TestSuiteXmlParserTest.java create mode 100644 surefire-report-parser/src/test/resources/fixture/testsuitexmlparser/TEST-org.apache.maven.surefire.test.FailingTest.xml create mode 100644 surefire-report-parser/src/test/resources/fixture/testsuitexmlparser/failsafe-summary-old.xml create mode 100644 surefire-report-parser/src/test/resources/fixture/testsuitexmlparser/failsafe-summary.xml create mode 100644 surefire-report-parser/src/test/resources/test-reports/TEST-AntUnit.xml create mode 100644 surefire-report-parser/src/test/resources/test-reports/TEST-NoPackageTest.xml create mode 100644 surefire-report-parser/src/test/resources/test-reports/TEST-NoTimeTestCaseTest.xml create mode 100644 surefire-report-parser/src/test/resources/test-reports/TEST-classWithNoTests.NoMethodsTestCase.xml create mode 100644 surefire-report-parser/src/test/resources/test-reports/TEST-com.shape.CircleTest.xml create mode 100644 surefire-report-parser/src/test/resources/test-reports/TEST-com.shape.PointTest.xml create mode 100644 surefire-report-parser/src/test/resources/test-reports/TEST-junit.twoTestCaseSuite.WrapperTestSuite.xml create mode 100644 surefire-report-parser/src/test/resources/test-reports/com.shape.CircleTest.txt create mode 100644 surefire-report-parser/src/test/resources/test-reports/com.shapeclone.CircleTest.txt diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000000..3bb3b5ea8a --- /dev/null +++ b/.gitattributes @@ -0,0 +1,8 @@ +# Auto detect text files and perform LF normalization +* text=auto + +*.java text diff=java +*.html text diff=html +*.css text +*.js text +*.sql text diff --git a/README.TXT b/README.TXT index 573fe5a412..611bc3a1ed 100644 --- a/README.TXT +++ b/README.TXT @@ -1,5 +1,35 @@ -Surefire need maven 3 to be build. -But in order to test it tests you can do: -* -DmavenHomeUsed= path to a maven 2.x home -* or -Pmaven-2.2.1 this profile will download a maven 2.2.1 distrib and use it for integration tests. +Surefire needs Maven 3 to be built. +But in order to test it tests, you can do: +* -DmavenHomeUsed= path to a Maven 2.x home +* or -Pmaven-2.2.1, this profile will download a Maven 2.2.1 distrib and use it for integration tests. + +Deploying web site +------------------ +You can use the deploySite.sh script +Without any profile the site will be deployed to http://maven.apache.org/surefire-archives/surefire-${project.version} +sh ./deploySite.sh -Preporting + +To deploy main version http://maven.apache.org/surefire, use +sh ./deploySite.sh -Preporting -Psite-release + +Note you can add arguments to the script to pass your svn credentials: +-Dusername= +-Dpassword= + +Workflow for site when releasing +-------------------------------- +Once release staged, you can publish a staged site. +cd target/checkout +sh ./deploySite.sh -Preporting +content will be in http://maven.apache.org/surefire-archives/surefire-${project.version} + +If something goes wrong when publishing the site to svnpubsub (like https://jira.codehaus.org/browse/MSCMPUB-6), +you can avoid rebuilding the site before publishing with +mvn -Preporting scm-publish:publish-scm + +Once vote passed, redeploy main site: +cd target/checkout (or use the version tag) +sh ./deploySite.sh -Preporting -Psite-release + + diff --git a/deploySite.sh b/deploySite.sh new file mode 100644 index 0000000000..b6517a2a26 --- /dev/null +++ b/deploySite.sh @@ -0,0 +1,22 @@ +#!/bin/sh + +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# + +mvn clean site-deploy scm-publish:publish-scm $@ diff --git a/maven-failsafe-plugin/pom.xml b/maven-failsafe-plugin/pom.xml index b69a17714b..d8dcd0cec6 100644 --- a/maven-failsafe-plugin/pom.xml +++ b/maven-failsafe-plugin/pom.xml @@ -18,14 +18,13 @@ ~ under the License. --> - + 4.0.0 org.apache.maven.surefire surefire - 2.13-SNAPSHOT + 2.16-SNAPSHOT ../pom.xml @@ -35,80 +34,6 @@ Maven Failsafe Plugin - - - - Maven User List - users-subscribe@maven.apache.org - users-unsubscribe@maven.apache.org - users@maven.apache.org - http://mail-archives.apache.org/mod_mbox/maven-users - - http://www.mail-archive.com/users@maven.apache.org/ - http://old.nabble.com/Maven---Users-f178.html - http://markmail.org/list/org.apache.maven.users - - - - Maven Developer List - dev-subscribe@maven.apache.org - dev-unsubscribe@maven.apache.org - dev@maven.apache.org - http://mail-archives.apache.org/mod_mbox/maven-dev - - http://www.mail-archive.com/dev@maven.apache.org/ - http://old.nabble.com/Maven-Developers-f179.html - http://markmail.org/list/org.apache.maven.dev - - - - Maven Commits List - commits-subscribe@maven.apache.org - commits-unsubscribe@maven.apache.org - http://mail-archives.apache.org/mod_mbox/maven-commits - - http://www.mail-archive.com/commits@maven.apache.org - http://old.nabble.com/Maven---Commits-f15575.html - http://markmail.org/list/org.apache.maven.commits - - - - - Maven Announcements List - announce@maven.apache.org - announce-subscribe@maven.apache.org - announce-unsubscribe@maven.apache.org - http://mail-archives.apache.org/mod_mbox/maven-announce/ - - http://www.mail-archive.com/announce@maven.apache.org - http://old.nabble.com/Maven-Announcements-f15617.html - http://markmail.org/list/org.apache.maven.announce - - - - Maven Issues List - issues-subscribe@maven.apache.org - issues-unsubscribe@maven.apache.org - http://mail-archives.apache.org/mod_mbox/maven-issues/ - - http://www.mail-archive.com/issues@maven.apache.org - http://old.nabble.com/Maven---Issues-f15573.html - http://markmail.org/list/org.apache.maven.issues - - - - Maven Notifications List - notifications-subscribe@maven.apache.org - notifications-unsubscribe@maven.apache.org - http://mail-archives.apache.org/mod_mbox/maven-notifications/ - - http://www.mail-archive.com/notifications@maven.apache.org - http://old.nabble.com/Maven---Notifications-f15574.html - http://markmail.org/list/org.apache.maven.notifications - - - - 2.0.9 @@ -180,7 +105,7 @@ org.apache.maven.surefire surefire-shadefire - ${project.version} + ${shadedVersion} @@ -226,6 +151,13 @@ + + org.apache.maven.plugins + maven-site-plugin + + ${project.build.directory}/source-site + + org.apache.maven.plugins maven-shade-plugin @@ -282,7 +214,6 @@ maven-compiler-plugin false - 1.4 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 fd1f5fb2b5..23f8dc1c01 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 @@ -24,6 +24,7 @@ import java.io.FileOutputStream; import java.io.IOException; import java.util.List; + import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugin.surefire.AbstractSurefireMojo; @@ -136,7 +137,24 @@ public class IntegrationTestMojo */ @Parameter( property = "failsafe.timeout" ) private int forkedProcessTimeoutInSeconds; - + + /** + * A list of <include> elements specifying the tests (by pattern) that should be included in testing. When not + * specified and when the test parameter is not specified, the default includes will be
+ * <includes>
+ *  <include>**/IT*.java</include>
+ *  <include>**/*IT.java</include>
+ *  <include>**/*ITCase.java</include>
+ * </includes>
+ *
+ *

+ * Each include item may also contain a comma-separated sublist of items, which will be treated as multiple + *  <include> entries.
+ *

+ * This parameter is ignored if the TestNG suiteXmlFiles parameter is specified. + */ + @Parameter + private List includes; /** * Option to pass dependencies to the system's classloader instead of using an isolated class loader when forking. @@ -308,36 +326,6 @@ public void setClassesDirectory( File classesDirectory ) this.classesDirectory = classesDirectory; } - public List getClasspathDependencyExcludes() - { - return classpathDependencyExcludes; - } - - public void setClasspathDependencyExcludes( List classpathDependencyExcludes ) - { - this.classpathDependencyExcludes = classpathDependencyExcludes; - } - - public String getClasspathDependencyScopeExclude() - { - return classpathDependencyScopeExclude; - } - - public void setClasspathDependencyScopeExclude( String classpathDependencyScopeExclude ) - { - this.classpathDependencyScopeExclude = classpathDependencyScopeExclude; - } - - public List getAdditionalClasspathElements() - { - return additionalClasspathElements; - } - - public void setAdditionalClasspathElements( List additionalClasspathElements ) - { - this.additionalClasspathElements = additionalClasspathElements; - } - public File getReportsDirectory() { return reportsDirectory; @@ -492,4 +480,16 @@ public void setFailIfNoSpecifiedTests( Boolean failIfNoSpecifiedTests ) { this.failIfNoSpecifiedTests = failIfNoSpecifiedTests; } + + @Override + public List getIncludes() + { + return includes; + } + + @Override + public void setIncludes( List includes ) + { + this.includes = includes; + } } diff --git a/maven-surefire-common/pom.xml b/maven-surefire-common/pom.xml index a6a03ca212..9c801dba8b 100644 --- a/maven-surefire-common/pom.xml +++ b/maven-surefire-common/pom.xml @@ -18,14 +18,13 @@ ~ under the License. --> - + 4.0.0 org.apache.maven.surefire surefire - 2.13-SNAPSHOT + 2.16-SNAPSHOT ../pom.xml @@ -71,6 +70,10 @@ org.apache.maven maven-project + + commons-io + commons-io + org.apache.maven maven-model @@ -87,6 +90,10 @@ org.apache.commons commons-lang3 + + com.google.code.findbugs + jsr305 + org.apache.maven.shared maven-common-artifact-filters @@ -111,7 +118,7 @@ org.apache.maven.surefire surefire-shadefire - ${project.version} + ${shadedVersion} @@ -130,6 +137,7 @@ org.apache.maven.shared:maven-shared-utils org.apache.maven.shared:maven-common-artifact-filters + commons-io:commons-io @@ -137,6 +145,10 @@ org.apache.maven.shared org.apache.maven.surefire.shade.org.apache.maven.shared + + org.apache.commons.io + org.apache.maven.surefire.shade.org.apache.commons.io + 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 963601793b..677920e6c2 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 @@ -32,6 +32,7 @@ import java.util.Map.Entry; import java.util.Properties; import java.util.Set; + import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.factory.ArtifactFactory; import org.apache.maven.artifact.metadata.ArtifactMetadataSource; @@ -43,6 +44,7 @@ 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; @@ -52,9 +54,11 @@ import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugin.descriptor.PluginDescriptor; +import org.apache.maven.plugin.logging.Log; 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.util.DependencyScanner; import org.apache.maven.plugin.surefire.util.DirectoryScanner; import org.apache.maven.plugins.annotations.Component; import org.apache.maven.plugins.annotations.Parameter; @@ -65,6 +69,7 @@ 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.ProviderConfiguration; import org.apache.maven.surefire.booter.ProviderParameterNames; import org.apache.maven.surefire.booter.StartupConfiguration; @@ -84,6 +89,8 @@ import org.apache.maven.toolchain.Toolchain; import org.apache.maven.toolchain.ToolchainManager; +import javax.annotation.Nonnull; + /** * Abstract base class for running tests using Surefire. * @@ -165,8 +172,8 @@ public abstract class AbstractSurefireMojo * * @since 2.6 */ - @Parameter - protected List classpathDependencyExcludes; + @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 @@ -183,15 +190,15 @@ public abstract class AbstractSurefireMojo * @since 2.6 */ @Parameter( defaultValue = "" ) - protected String classpathDependencyScopeExclude; + private String classpathDependencyScopeExclude; /** * Additional elements to be appended to the classpath. * * @since 2.4 */ - @Parameter - protected List additionalClasspathElements; + @Parameter( property = "maven.test.additionalClasspath" ) + private String[] additionalClasspathElements; /** * The test source directory containing test class sources. @@ -201,24 +208,6 @@ public abstract class AbstractSurefireMojo @Parameter( defaultValue = "${project.build.testSourceDirectory}", required = true ) protected File testSourceDirectory; - /** - * A list of <include> elements specifying the tests (by pattern) that should be included in testing. When not - * specified and when the test parameter is not specified, the default includes will be
- * <includes>
- *  <include>**/IT*.java</include>
- *  <include>**/*IT.java</include>
- *  <include>**/*ITCase.java</include>
- * </includes>
- *
- *

- * Each include item may also contain a comma-separated sublist of items, which will be treated as multiple - *  <include> entries.
- *

- * This parameter is ignored if the TestNG suiteXmlFiles parameter is specified. - */ - @Parameter - protected List includes; - /** * A file containing include patterns. * Blank lines, or lines starting with # are ignored. If {@code includes} are also specified these patterns are appended. @@ -329,11 +318,11 @@ public abstract class AbstractSurefireMojo protected Boolean failIfNoTests; /** - * Option to specify the forking mode. Can be "never", "once", "always", "perthread" or "onceperthread". "none" and "pertest" are also accepted - * for backwards compatibility. "always" forks for each test-class. "perthread" will create "threadCount" parallel forks, each executing one test-class. - * "onceperthread" will fork "threadCount" processes that each execute a 1/"threadCount" of all test-classes.
- * The system properties and the "argLine" of the forked processes may contain the place holder string ${surefire.threadNumber}, - * which is replaced with a fixed number for each thread, ranging from 1 to "threadCount". + * DEPRECATED since version 2.14. Use forkCount and reuseForks instead.
+ *
+ * Option to specify the forking mode. Can be "never", "once", "always", "perthread". "none" and "pertest" are also accepted + * for backwards compatibility. "always" forks for each test-class. "perthread" will create threadCount + * parallel forks, each executing one test-class. See also parameter reuseForks.
* * @since 2.1 */ @@ -434,15 +423,42 @@ public abstract class AbstractSurefireMojo protected String testNGArtifactName; /** - * (forkMode=perthread, forkmode=onceperthread or 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 parallel parameter or with forkMode=perthread - * or forkmode=onceperthread. + * (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 parallel parameter. * * @since 2.2 */ @Parameter( property = "threadCount" ) protected 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 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 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 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 is per cpu core. * @@ -568,6 +584,15 @@ public abstract class AbstractSurefireMojo @Parameter( defaultValue = "filesystem" ) protected String runOrder; + /** + * List of dependencies to scan for test classes to include in the test run. Each dependency string must follow the format + * groupId:artifactId. For example: org.acme:project-a + * + * @since 2.15 + */ + @Parameter( property = "dependenciesToScan" ) + private String[] dependenciesToScan; + /** * */ @@ -578,12 +603,21 @@ public abstract class AbstractSurefireMojo 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(); private SurefireDependencyResolver dependencyResolver; @@ -596,7 +630,7 @@ public void execute() if ( verifyParameters() && !hasExecutedBefore() ) { - DefaultScanResult scan = scanDirectories(); + DefaultScanResult scan = scanForTestClasses(); if ( !isValidSuiteXmlFileConfig() && scan.isEmpty() ) { if ( getEffectiveFailIfNoTests() ) @@ -619,12 +653,41 @@ private void setupStuff() toolchain = getToolchain(); } + private DefaultScanResult scanForTestClasses() + { + DefaultScanResult scan = scanDirectories(); + DefaultScanResult scanDeps = scanDependencies(); + return scan.append( scanDeps ); + } + private DefaultScanResult scanDirectories() { return new DirectoryScanner( getTestClassesDirectory(), getIncludeList(), getExcludeList(), getSpecificTests() ).scan(); } + private DefaultScanResult scanDependencies() + { + if ( getDependenciesToScan() == null ) + { + return null; + } + else + { + try + { + // noinspection unchecked + return new DependencyScanner( DependencyScanner.filter( project.getTestArtifacts(), + Arrays.asList( getDependenciesToScan() ) ), + getIncludeList(), getExcludeList(), getSpecificTests() ).scan(); + } + catch ( Exception e ) + { + throw new RuntimeException( e ); + } + } + } + boolean verifyParameters() throws MojoFailureException, MojoExecutionException { @@ -645,7 +708,8 @@ boolean verifyParameters() } } - if ( !getTestClassesDirectory().exists() ) + if ( !getTestClassesDirectory().exists() + && ( getDependenciesToScan() == null || getDependenciesToScan().length == 0 ) ) { if ( Boolean.TRUE.equals( getFailIfNoTests() ) ) { @@ -655,6 +719,7 @@ boolean verifyParameters() } else { + convertDeprecatedForkMode(); ensureWorkingDirectoryExists(); ensureParallelRunningCompatibility(); ensureThreadCountWithPerThread(); @@ -735,23 +800,53 @@ protected List createProviders() 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 ( getLog().isDebugEnabled() ) + { + getLog().warn( msg, e ); + } + else + { + getLog().warn( msg ); + } + } + SurefireProperties result = - SurefireProperties.calculateEffectiveProperties( getSystemProperties(), getSystemPropertiesFile(), - getSystemPropertyVariables(), getUserProperties(), - getLog() ); + SurefireProperties.calculateEffectiveProperties( getSystemProperties(), getSystemPropertyVariables(), + getUserProperties(), sysProps ); result.setProperty( "basedir", getBasedir().getAbsolutePath() ); result.setProperty( "user.dir", getWorkingDirectory().getAbsolutePath() ); result.setProperty( "localRepository", getLocalRepository().getBasedir() ); - result.verifyLegalSystemProperties( getLog() ); + for ( Object o : result.propertiesThatCannotBeSetASystemProperties() ) + { + getLog().warn( o + " cannot be set as system property, use -D" + o + "=... instead" ); + + } if ( getLog().isDebugEnabled() ) { - result.showToLog( getLog(), "system property" ); + showToLog( result, getLog(), "system property" ); } return result; } + public void showToLog( SurefireProperties props, org.apache.maven.plugin.logging.Log log, String setting ) + { + for ( Object key : props.getStringKeySet() ) + { + String value = props.getProperty( (String) key ); + log.debug( "Setting " + setting + " [" + key + "]=[" + value + "]" ); + } + } + + private RunResult executeProvider( ProviderInfo provider, DefaultScanResult scanResult ) throws MojoExecutionException, MojoFailureException, SurefireExecutionException, SurefireBooterForkException, TestSetFailedException @@ -763,9 +858,9 @@ private RunResult executeProvider( ProviderInfo provider, DefaultScanResult scan new RunOrderParameters( getRunOrder(), getStatisticsFileName( getConfigChecksum() ) ); final RunResult result; - if ( isForkModeNever() ) + if ( isNotForking() ) { - createCopyAndReplaceThreadNumPlaceholder( effectiveProperties, 1 ).copyToSystemProperties(); + createCopyAndReplaceForkNumPlaceholder( effectiveProperties, 1 ).copyToSystemProperties(); InPluginVMSurefireStarter surefireStarter = createInprocessStarter( provider, classLoaderConfiguration, runOrderParameters ); @@ -784,8 +879,8 @@ private RunResult executeProvider( ProviderInfo provider, DefaultScanResult scan { ForkStarter forkStarter = createForkStarter( provider, forkConfiguration, classLoaderConfiguration, runOrderParameters, - effectiveProperties ); - result = forkStarter.run( effectiveProperties, scanResult, getEffectiveForkMode() ); + getLog() ); + result = forkStarter.run( effectiveProperties, scanResult ); } finally { @@ -797,18 +892,20 @@ private RunResult executeProvider( ProviderInfo provider, DefaultScanResult scan } - public static SurefireProperties createCopyAndReplaceThreadNumPlaceholder( + public static SurefireProperties createCopyAndReplaceForkNumPlaceholder( SurefireProperties effectiveSystemProperties, int threadNumber ) { - SurefireProperties filteredProperties = new SurefireProperties( effectiveSystemProperties ); + SurefireProperties filteredProperties = new SurefireProperties( ( KeyValueSource) effectiveSystemProperties ); String threadNumberString = String.valueOf( threadNumber ); for ( Entry entry : effectiveSystemProperties.entrySet() ) { if ( entry.getValue() instanceof String ) { - filteredProperties.put( entry.getKey(), - ( (String) entry.getValue() ).replace( THREAD_NUMBER_PLACEHOLDER, - threadNumberString ) ); + String value = (String) entry.getValue(); + value = value.replace( THREAD_NUMBER_PLACEHOLDER, threadNumberString ); + value = value.replace( FORK_NUMBER_PLACEHOLDER, threadNumberString ); + + filteredProperties.put( entry.getKey(), value ); } } return filteredProperties; @@ -856,7 +953,7 @@ final Toolchain getToolchain() * Converts old TestNG configuration parameters over to new properties based configuration * method. (if any are defined the old way) */ - private void convertTestNGParameters() + private void convertTestNGParameters() throws MojoExecutionException { if ( this.getParallel() != null ) { @@ -878,9 +975,51 @@ private void convertTestNGParameters() 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 ) ); + } + + + } + + private static String getConfiguratorName( ArtifactVersion version ) + throws MojoExecutionException + { + try + { + VersionRange range = VersionRange.createFromVersionSpec( "[4.7,5.1]" ); + if ( range.containsVersion( version ) ) + { + return "org.apache.maven.surefire.testng.conf.TestNG4751Configurator"; + } + range = VersionRange.createFromVersionSpec( "[5.2]" ); + if ( range.containsVersion( version ) ) + { + return "org.apache.maven.surefire.testng.conf.TestNG52Configurator"; + } + range = VersionRange.createFromVersionSpec( "[5.3,6.4]" ); + if ( range.containsVersion( version ) ) + { + return "org.apache.maven.surefire.testng.conf.TestNGMapConfigurator"; + } + range = VersionRange.createFromVersionSpec( "[6.5,)" ); + if ( range.containsVersion( version ) ) + { + return "org.apache.maven.surefire.testng.conf.TestNG652Configurator"; + } + 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 ) @@ -909,17 +1048,19 @@ protected boolean isAnyGroupsSelected() */ private void convertJunitCoreParameters() { - if ( this.getParallel() != null ) - { - getProperties().setProperty( ProviderParameterNames.PARALLEL_PROP, this.getParallel() ); - } - if ( this.getThreadCount() > 0 ) - { - getProperties().setProperty( ProviderParameterNames.THREADCOUNT_PROP, - Integer.toString( this.getThreadCount() ) ); - } + String usedParallel = ( getParallel() != null ) ? getParallel() : "none"; + String usedThreadCount = ( getThreadCount() > 0 ) ? Integer.toString( getThreadCount() ) : "2"; + + getProperties().setProperty( ProviderParameterNames.PARALLEL_PROP, usedParallel ); + getProperties().setProperty( ProviderParameterNames.THREADCOUNT_PROP, usedThreadCount ); getProperties().setProperty( "perCoreThreadCount", Boolean.toString( getPerCoreThreadCount() ) ); getProperties().setProperty( "useUnlimitedThreads", Boolean.toString( getUseUnlimitedThreads() ) ); + + String message = + "parallel='" + usedParallel + '\'' + ", perCoreThreadCount=" + getPerCoreThreadCount() + ", threadCount=" + + usedThreadCount + ", useUnlimitedThreads=" + getUseUnlimitedThreads(); + + getLog().info( message ); } private boolean isJunit47Compatible( Artifact artifact ) @@ -932,11 +1073,6 @@ private boolean isAnyJunit4( Artifact artifact ) return dependencyResolver.isWithinVersionSpec( artifact, "[4.0,)" ); } - boolean isForkModeNever() - { - return isForkModeNever( getEffectiveForkMode() ); - } - static boolean isForkModeNever( String forkMode ) { return ForkConfiguration.FORK_NEVER.equals( forkMode ); @@ -944,7 +1080,7 @@ static boolean isForkModeNever( String forkMode ) boolean isForking() { - return !isForkModeNever(); + return 0 < getEffectiveForkCount(); } String getEffectiveForkMode() @@ -1072,14 +1208,17 @@ StartupConfiguration createStartupConfiguration( ProviderInfo provider, ClasspathCache.setCachedClasspath( providerName, providerClasspath ); } - Classpath inprocClassPath = new Classpath( providerClasspath ); Artifact surefireArtifact = getCommonArtifact(); - inprocClassPath.addClassPathElementUrl( surefireArtifact.getFile().getAbsolutePath() ); + Classpath inprocClassPath = providerClasspath.addClassPathElementUrl( surefireArtifact.getFile().getAbsolutePath() ); final Classpath testClasspath = generateTestClasspath(); - logClasspath( testClasspath, "test classpath" ); - logClasspath( providerClasspath, "provider classpath" ); + getLog().debug( testClasspath.getLogMessage( "test" ) ); + getLog().debug( providerClasspath.getLogMessage( "provider" ) ); + + getLog().debug( testClasspath.getCompactLogMessage( "test(compact)" ) ); + getLog().debug( providerClasspath.getCompactLogMessage( "provider(compact)" ) ); + final ClasspathConfiguration classpathConfiguration = new ClasspathConfiguration( testClasspath, providerClasspath, inprocClassPath, effectiveIsEnableAssertions(), isChildDelegation() ); @@ -1115,24 +1254,6 @@ private StartupReportConfiguration getStartupReportConfiguration( String configC configChecksum, requiresRunHistory() ); } - void logClasspath( Classpath classpath, String descriptor ) - { - getLog().debug( descriptor + " classpath:" ); - @SuppressWarnings( "unchecked" ) final List classPath = classpath.getClassPath(); - for ( String classpathElement : classPath ) - { - if ( classpathElement == null ) - { - getLog().warn( "The test classpath contains a null element." ); - } - else - { - getLog().debug( " " + classpathElement ); - } - } - } - - private boolean isSpecificTestSpecified() { return getTest() != null; @@ -1143,7 +1264,7 @@ private boolean isValidSuiteXmlFileConfig() return getSuiteXmlFiles() != null && getSuiteXmlFiles().length > 0; } - private List readListFromFile( final File file ) + @Nonnull private List readListFromFile( @Nonnull final File file ) { List list; @@ -1182,7 +1303,7 @@ private void maybeAppendList( final List base, final List list ) } } - private List getExcludeList() + private @Nonnull List getExcludeList() { List excludes = null; if ( isSpecificTestSpecified() ) @@ -1214,10 +1335,10 @@ private List getExcludeList() // Have to wrap in an ArrayList as surefire expects an ArrayList instead of a List for some reason if ( excludes == null || excludes.size() == 0 ) { - excludes = new ArrayList( Arrays.asList( new String[]{ "**/*$*" } ) ); + excludes = Arrays.asList( "**/*$*" ); } } - return excludes; + return filterNulls( excludes ); } private List getIncludeList() @@ -1249,10 +1370,24 @@ private List getIncludeList() // Have to wrap in an ArrayList as surefire expects an ArrayList instead of a List for some reason if ( includes == null || includes.size() == 0 ) { - includes = new ArrayList( Arrays.asList( getDefaultIncludes() ) ); + includes = Arrays.asList( getDefaultIncludes() ); + } + + return filterNulls( includes ); + } + + private @Nonnull List filterNulls( @Nonnull List toFilter ) + { + List result = new ArrayList( toFilter.size() ); + for ( String item : toFilter ) + { + if ( item != null ) + { + result.add( item ); + } } - return includes; + return result; } private boolean isMultipleExecutionBlocksDetected() @@ -1341,8 +1476,7 @@ private Artifact getJunitDepArtifact() protected ForkStarter createForkStarter( ProviderInfo provider, ForkConfiguration forkConfiguration, ClassLoaderConfiguration classLoaderConfiguration, - RunOrderParameters runOrderParameters, - SurefireProperties effectiveSystemProperties ) + RunOrderParameters runOrderParameters, Log log ) throws MojoExecutionException, MojoFailureException { StartupConfiguration startupConfiguration = createStartupConfiguration( provider, classLoaderConfiguration ); @@ -1350,7 +1484,7 @@ protected ForkStarter createForkStarter( ProviderInfo provider, ForkConfiguratio StartupReportConfiguration startupReportConfiguration = getStartupReportConfiguration( configChecksum ); ProviderConfiguration providerConfiguration = createProviderConfiguration( runOrderParameters ); return new ForkStarter( providerConfiguration, startupConfiguration, forkConfiguration, - getForkedProcessTimeoutInSeconds(), startupReportConfiguration ); + getForkedProcessTimeoutInSeconds(), startupReportConfiguration, log ); } protected InPluginVMSurefireStarter createInprocessStarter( ProviderInfo provider, @@ -1381,14 +1515,67 @@ protected ForkConfiguration getForkConfiguration() getEffectiveJvm(), getWorkingDirectory() != null ? getWorkingDirectory() : getBasedir(), getArgLine(), getEnvironmentVariables(), getLog().isDebugEnabled(), - getEffectiveForkCount() ); + getEffectiveForkCount(), reuseForks ); } + private void convertDeprecatedForkMode() + { + String effectiveForkMode = getEffectiveForkMode(); + // FORK_ONCE (default) is represented by the default values of forkCount and reuseForks + if ( ForkConfiguration.FORK_PERTHREAD.equals( effectiveForkMode ) ) + { + forkCount = String.valueOf( threadCount ); + } + else if ( ForkConfiguration.FORK_NEVER.equals( effectiveForkMode ) ) + { + forkCount = "0"; + } + else if ( ForkConfiguration.FORK_ALWAYS.equals( effectiveForkMode ) ) + { + forkCount = "1"; + reuseForks = false; + } + + if ( !ForkConfiguration.FORK_ONCE.equals( getForkMode() ) ) + { + getLog().warn( + "The parameter forkMode is deprecated since version 2.14. Use forkCount and reuseForks instead." ); + } + } + + 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." ); + } + } + + return effectiveForkCount; + } - private int getEffectiveForkCount() + protected int convertWithCoreCount( String count ) { - return ( ForkConfiguration.FORK_PERTHREAD.equals( getEffectiveForkMode() ) - || ForkConfiguration.FORK_ONCE_PERTHREAD.equals( getEffectiveForkMode() ) ) ? getThreadCount() : 1; + String trimmed = count.trim(); + if ( trimmed.endsWith( "C" ) ) + { + double multiplier = Double.parseDouble( trimmed.substring( 0, trimmed.length() - 1 ) ); + return (int) ( multiplier * ( (double) Runtime.getRuntime().availableProcessors() ) ); + } + else + { + return Integer.parseInt( trimmed ); + } } private String getEffectiveDebugForkedProcess() @@ -1475,6 +1662,8 @@ private String getConfigChecksum() checksum.add( isUseFile() ); checksum.add( isRedirectTestOutputToFile() ); checksum.add( getForkMode() ); + checksum.add( getForkCount() ); + checksum.add( isReuseForks() ); checksum.add( getJvm() ); checksum.add( getArgLine() ); checksum.add( getDebugForkedProcess() ); @@ -1500,6 +1689,7 @@ private String getConfigChecksum() checksum.add( getObjectFactory() ); checksum.add( getFailIfNoTests() ); checksum.add( getRunOrder() ); + checksum.add( getDependenciesToScan() ); addPluginSpecificChecksumItems( checksum ); return checksum.getSha1(); @@ -1564,7 +1754,7 @@ Classpath generateTestClasspath() if ( getClasspathDependencyExcludes() != null ) { - ArtifactFilter dependencyFilter = new PatternIncludesArtifactFilter( getClasspathDependencyExcludes() ); + ArtifactFilter dependencyFilter = new PatternIncludesArtifactFilter( Arrays.asList( getClasspathDependencyExcludes() ) ); classpathArtifacts = this.filterArtifacts( classpathArtifacts, dependencyFilter ); } @@ -1763,30 +1953,34 @@ void ensureWorkingDirectoryExists() void ensureParallelRunningCompatibility() throws MojoFailureException { - if ( isMavenParallel() && isForkModeNever() ) + if ( isMavenParallel() && isNotForking() ) { - throw new MojoFailureException( "parallel maven execution is not compatible with surefire forkmode NEVER" ); + throw new MojoFailureException( "parallel maven execution is not compatible with surefire forkCount 0" ); } } void ensureThreadCountWithPerThread() throws MojoFailureException { - if ( ( ForkConfiguration.FORK_PERTHREAD.equals( getEffectiveForkMode() ) - || ForkConfiguration.FORK_ONCE_PERTHREAD.equals( getEffectiveForkMode() ) ) && getThreadCount() < 1 ) + if ( ForkConfiguration.FORK_PERTHREAD.equals( getEffectiveForkMode() ) && getThreadCount() < 1 ) { - throw new MojoFailureException( "Fork modes perthread and onceperthread require a thread count" ); + throw new MojoFailureException( "Fork mode perthread requires a thread count" ); } } void warnIfUselessUseSystemClassLoaderParameter() { - if ( isUseSystemClassLoader() && isForkModeNever() ) + if ( isUseSystemClassLoader() && isNotForking() ) { getLog().warn( "useSystemClassloader setting has no effect when not forking" ); } } + private boolean isNotForking() + { + return !isForking(); + } + void warnIfDefunctGroupsCombinations() throws MojoFailureException, MojoExecutionException { @@ -1823,7 +2017,7 @@ class TestNgProviderInfo this.testNgArtifact = testNgArtifact; } - public String getProviderName() + public @Nonnull String getProviderName() { return "org.apache.maven.surefire.testng.TestNGProvider"; } @@ -1833,7 +2027,7 @@ public boolean isApplicable() return testNgArtifact != null; } - public void addProviderProperties() + public void addProviderProperties() throws MojoExecutionException { convertTestNGParameters(); } @@ -1850,7 +2044,7 @@ public Classpath getProviderClasspath() class JUnit3ProviderInfo implements ProviderInfo { - public String getProviderName() + @Nonnull public String getProviderName() { return "org.apache.maven.surefire.junit.JUnit3Provider"; } @@ -1889,7 +2083,7 @@ class JUnit4ProviderInfo this.junitDepArtifact = junitDepArtifact; } - public String getProviderName() + @Nonnull public String getProviderName() { return "org.apache.maven.surefire.junit4.JUnit4Provider"; } @@ -1926,7 +2120,7 @@ class JUnitCoreProviderInfo this.junitDepArtifact = junitDepArtifact; } - public String getProviderName() + @Nonnull public String getProviderName() { return "org.apache.maven.surefire.junitcore.JUnitCoreProvider"; } @@ -1973,6 +2167,7 @@ public ProviderInfo instantiate( String providerName ) return new DynamicProviderInfo( providerName ); } + @Nonnull public String getProviderName() { return providerName; @@ -1983,7 +2178,7 @@ public boolean isApplicable() return true; } - public void addProviderProperties() + public void addProviderProperties() throws MojoExecutionException { // Ok this is a bit lazy. convertJunitCoreParameters(); @@ -2002,20 +2197,14 @@ public Classpath getProviderClasspath() } - public List getIncludes() - { - return includes; - } + public abstract List getIncludes(); public File getIncludesFile() { return includesFile; } - public void setIncludes( List includes ) - { - this.includes = includes; - } + public abstract void setIncludes( List includes ); public List getExcludes() { @@ -2446,6 +2635,16 @@ public void setRunOrder( String runOrder ) this.runOrder = runOrder; } + public String[] getDependenciesToScan() + { + return dependenciesToScan; + } + + public void setDependenciesToScan( String[] dependenciesToScan ) + { + this.dependenciesToScan = dependenciesToScan; + } + public PluginDescriptor getPluginDescriptor() { return pluginDescriptor; @@ -2472,4 +2671,43 @@ public void setTestSourceDirectory( File testSourceDirectory ) this.testSourceDirectory = testSourceDirectory; } + public String getForkCount() + { + return forkCount; + } + + public boolean isReuseForks() + { + return reuseForks; + } + + public String[] getAdditionalClasspathElements() + { + return additionalClasspathElements; + } + + public void setAdditionalClasspathElements( String[] additionalClasspathElements ) + { + this.additionalClasspathElements = additionalClasspathElements; + } + + public String[] getClasspathDependencyExcludes() + { + return classpathDependencyExcludes; + } + + public void setClasspathDependencyExcludes( String[] classpathDependencyExcludes ) + { + this.classpathDependencyExcludes = classpathDependencyExcludes; + } + + public String getClasspathDependencyScopeExclude() + { + return classpathDependencyScopeExclude; + } + + public void setClasspathDependencyScopeExclude( String classpathDependencyScopeExclude ) + { + this.classpathDependencyScopeExclude = classpathDependencyScopeExclude; + } } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/ClasspathCache.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/ClasspathCache.java index 1bcb06551f..ea250c2c2a 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/ClasspathCache.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/ClasspathCache.java @@ -21,6 +21,8 @@ import java.util.concurrent.ConcurrentHashMap; import org.apache.maven.surefire.booter.Classpath; +import javax.annotation.Nonnull; + /** * @author Kristian Rosenvold */ @@ -29,12 +31,12 @@ public class ClasspathCache private static final ConcurrentHashMap classpaths = new ConcurrentHashMap( 4 ); - public static Classpath getCachedClassPath( String artifactId ) + public static Classpath getCachedClassPath( @Nonnull String artifactId ) { return classpaths.get( artifactId ); } - public static void setCachedClasspath( String key, Classpath classpath ) + public static void setCachedClasspath( @Nonnull String key, @Nonnull Classpath classpath ) { classpaths.put( key, 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 538b7e05d1..685153961c 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 @@ -25,6 +25,8 @@ import org.apache.maven.surefire.util.ReflectionUtils; import org.apache.maven.surefire.util.SurefireReflectionException; +import javax.annotation.Nonnull; + /** * @author Kristian Rosenvold */ @@ -34,7 +36,7 @@ public class CommonReflector private final ClassLoader surefireClassLoader; - public CommonReflector( ClassLoader surefireClassLoader ) + public CommonReflector( @Nonnull ClassLoader surefireClassLoader ) { this.surefireClassLoader = surefireClassLoader; @@ -48,7 +50,7 @@ public CommonReflector( ClassLoader surefireClassLoader ) } } - public Object createReportingReporterFactory( StartupReportConfiguration startupReportConfiguration ) + public Object createReportingReporterFactory( @Nonnull StartupReportConfiguration startupReportConfiguration ) { Class[] args = new Class[]{ this.startupReportConfiguration }; Object src = createStartupReportConfiguration( startupReportConfiguration ); @@ -58,7 +60,7 @@ public Object createReportingReporterFactory( StartupReportConfiguration startup } - Object createStartupReportConfiguration( StartupReportConfiguration reporterConfiguration ) + Object createStartupReportConfiguration( @Nonnull StartupReportConfiguration reporterConfiguration ) { Constructor constructor = ReflectionUtils.getConstructor( this.startupReportConfiguration, new Class[]{ boolean.class, boolean.class, 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 6a1a394e6c..ec864c35d2 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 @@ -29,6 +29,8 @@ import org.apache.maven.surefire.testset.TestSetFailedException; import org.apache.maven.surefire.util.DefaultScanResult; +import javax.annotation.Nonnull; + /** * Starts the provider in the same VM as the surefire plugin. *

@@ -50,16 +52,16 @@ public class InPluginVMSurefireStarter private final ProviderConfiguration providerConfiguration; - public InPluginVMSurefireStarter( StartupConfiguration startupConfiguration, - ProviderConfiguration providerConfiguration, - StartupReportConfiguration startupReportConfiguration ) + public InPluginVMSurefireStarter( @Nonnull StartupConfiguration startupConfiguration, + @Nonnull ProviderConfiguration providerConfiguration, + @Nonnull StartupReportConfiguration startupReportConfiguration ) { this.startupConfiguration = startupConfiguration; this.startupReportConfiguration = startupReportConfiguration; this.providerConfiguration = providerConfiguration; } - public RunResult runSuitesInProcess( DefaultScanResult scanResult ) + 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 @@ -69,18 +71,15 @@ public RunResult runSuitesInProcess( DefaultScanResult scanResult ) scanResult.writeTo( providerProperties ); startupConfiguration.writeSurefireTestClasspathProperty(); - ClassLoader testsClassLoader = startupConfiguration.getClasspathConfiguration().createTestClassLoader(); - - ClassLoader surefireClassLoader = - startupConfiguration.getClasspathConfiguration().createInprocSurefireClassLoader( testsClassLoader ); + ClassLoader testsClassLoader = startupConfiguration.getClasspathConfiguration().createMergedClassLoader(); - CommonReflector surefireReflector = new CommonReflector( surefireClassLoader ); + CommonReflector surefireReflector = new CommonReflector( testsClassLoader ); final Object factory = surefireReflector.createReportingReporterFactory( startupReportConfiguration ); try { - return ProviderFactory.invokeProvider( null, testsClassLoader, surefireClassLoader, factory, + return ProviderFactory.invokeProvider( null, testsClassLoader, factory, providerConfiguration, false, startupConfiguration, true ); } catch ( InvocationTargetException e ) diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/ProviderInfo.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/ProviderInfo.java index a75ad1e678..50de7ea1d7 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/ProviderInfo.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/ProviderInfo.java @@ -21,13 +21,17 @@ import org.apache.maven.artifact.resolver.ArtifactNotFoundException; import org.apache.maven.artifact.resolver.ArtifactResolutionException; +import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.surefire.booter.Classpath; +import javax.annotation.Nonnull; + /** * @author Kristian Rosenvold */ public interface ProviderInfo { + @Nonnull String getProviderName(); boolean isApplicable(); @@ -35,5 +39,5 @@ public interface ProviderInfo Classpath getProviderClasspath() throws ArtifactResolutionException, ArtifactNotFoundException; - void addProviderProperties(); + void addProviderProperties() throws MojoExecutionException; } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/ProviderList.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/ProviderList.java index 5465ba401f..d7424af928 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/ProviderList.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/ProviderList.java @@ -28,6 +28,8 @@ import org.apache.maven.surefire.providerapi.SurefireProvider; import org.apache.maven.surefire.util.NestedRuntimeException; +import javax.annotation.Nonnull; + /** * @author Kristian Rosenvold */ @@ -44,7 +46,7 @@ public ProviderList( ConfigurableProviderInfo dynamicProviderInfo, ProviderInfo. } - public List resolve( Log log ) + public @Nonnull List resolve( @Nonnull Log log ) { List providersToRun = new ArrayList(); @@ -64,7 +66,7 @@ public List resolve( Log log ) return autoDetectOneProvider(); } - private List autoDetectOneProvider() + private @Nonnull List autoDetectOneProvider() { List providersToRun = new ArrayList(); for ( ProviderInfo wellKnownProvider : wellKnownProviders ) 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 a9f1245ba6..f974ace2a4 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 @@ -30,6 +30,8 @@ import org.apache.maven.plugin.surefire.report.TestcycleConsoleOutputReceiver; import org.apache.maven.plugin.surefire.runorder.StatisticsReporter; +import javax.annotation.Nonnull; + /** * All the parameters used to construct reporters *

@@ -70,7 +72,8 @@ public class StartupReportConfiguration public StartupReportConfiguration( boolean useFile, boolean printSummary, String reportFormat, boolean redirectTestOutputToFile, boolean disableXmlReport, - File reportsDirectory, boolean trimStackTrace, String reportNameSuffix, + @Nonnull File reportsDirectory, + boolean trimStackTrace, String reportNameSuffix, String configurationHash, boolean requiresRunHistory ) { this.useFile = useFile; 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 2ec5e00eef..41b6171e00 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 @@ -40,6 +40,9 @@ import org.apache.maven.plugin.logging.Log; import org.apache.maven.surefire.booter.Classpath; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + /** * Does dependency resolution and artifact handling for the surefire plugin. * @@ -78,7 +81,7 @@ protected SurefireDependencyResolver( ArtifactResolver artifactResolver, Artifac } - public boolean isWithinVersionSpec( Artifact artifact, String versionSpec ) + public boolean isWithinVersionSpec( @Nullable Artifact artifact, @Nonnull String versionSpec ) { if ( artifact == null ) { @@ -107,7 +110,7 @@ public boolean isWithinVersionSpec( Artifact artifact, String versionSpec ) } - public ArtifactResolutionResult resolveArtifact( Artifact filteredArtifact, Artifact providerArtifact ) + public ArtifactResolutionResult resolveArtifact( @Nullable Artifact filteredArtifact, Artifact providerArtifact ) throws ArtifactResolutionException, ArtifactNotFoundException { ArtifactFilter filter = null; 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 5b79bcfbe2..44c7d197bd 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 @@ -55,18 +55,6 @@ public interface SurefireExecutionParameters void setClassesDirectory( File classesDirectory ); - List getClasspathDependencyExcludes(); - - void setClasspathDependencyExcludes( List classpathDependencyExcludes ); - - String getClasspathDependencyScopeExclude(); - - void setClasspathDependencyScopeExclude( String classpathDependencyScopeExclude ); - - List getAdditionalClasspathElements(); - - void setAdditionalClasspathElements( List additionalClasspathElements ); - File getReportsDirectory(); void setReportsDirectory( File reportsDirectory ); 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 93e44a707e..606c26b522 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 @@ -18,18 +18,23 @@ * under the License. */ +import org.apache.maven.surefire.booter.Classpath; +import org.apache.maven.surefire.booter.KeyValueSource; +import org.apache.maven.surefire.util.internal.StringUtils; + import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Collections; import java.util.Enumeration; +import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; +import java.util.List; import java.util.Map; import java.util.Properties; -import org.apache.maven.plugin.logging.Log; -import org.apache.maven.surefire.booter.KeyValueSource; +import java.util.Set; /** * A properties implementation that preserves insertion order. @@ -52,6 +57,14 @@ public SurefireProperties( Properties source ) } } + public SurefireProperties( KeyValueSource source ) + { + if ( source != null ) + { + source.copyTo( this ); + } + } + @Override public synchronized Object put( Object key, Object value ) { @@ -78,7 +91,7 @@ public synchronized Enumeration keys() return Collections.enumeration( items ); } - public void copyProperties( Properties source ) + public void copyPropertiesFrom( Properties source ) { if ( source != null ) { @@ -91,32 +104,31 @@ public void copyProperties( Properties source ) } } - private Iterable getStringKeySet() + public Iterable getStringKeySet() { //noinspection unchecked return keySet(); } - public void showToLog( org.apache.maven.plugin.logging.Log log, String setting ) - { - for ( Object key : getStringKeySet() ) - { - String value = getProperty( (String) key ); - log.debug( "Setting " + setting + " [" + key + "]=[" + value + "]" ); - } - } + private static final Set keysThatCannotBeUsedAsSystemProperties = new HashSet() + {{ + add( "java.library.path" ); + add( "file.encoding" ); + add( "jdk.map.althashing.threshold" ); + }}; - public void verifyLegalSystemProperties( org.apache.maven.plugin.logging.Log log ) + public Set propertiesThatCannotBeSetASystemProperties() { + Set result = new HashSet(); for ( Object key : getStringKeySet() ) { - if ( "java.library.path".equals( key ) ) + if ( keysThatCannotBeUsedAsSystemProperties.contains( key ) ) { - log.warn( - "java.library.path cannot be set as system property, use -Djava.library.path=... instead" ); + result.add( key ); } } + return result; } @@ -133,37 +145,14 @@ public void copyToSystemProperties() } } - static SurefireProperties calculateEffectiveProperties( Properties systemProperties, File systemPropertiesFile, + static SurefireProperties calculateEffectiveProperties( Properties systemProperties, Map systemPropertyVariables, - Properties userProperties, Log log ) + Properties userProperties, SurefireProperties props ) { SurefireProperties result = new SurefireProperties(); - result.copyProperties( systemProperties ); + result.copyPropertiesFrom( systemProperties ); - if ( systemPropertiesFile != null ) - { - Properties props = new SurefireProperties(); - try - { - InputStream fis = new FileInputStream( systemPropertiesFile ); - props.load( fis ); - fis.close(); - } - catch ( IOException e ) - { - String msg = "The system property file '" + systemPropertiesFile.getAbsolutePath() + "' can't be read."; - if ( log.isDebugEnabled() ) - { - log.warn( msg, e ); - } - else - { - log.warn( msg ); - } - } - - result.copyProperties( props ); - } + result.copyPropertiesFrom( props ); copyProperties( result, systemPropertyVariables ); copyProperties( result, systemPropertyVariables ); @@ -173,7 +162,7 @@ static SurefireProperties calculateEffectiveProperties( Properties systemPropert // 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.copyProperties( userProperties ); + result.copyPropertiesFrom( userProperties ); return result; } @@ -205,5 +194,110 @@ public void copyTo( Map target ) } } + 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 addList( List items, String propertyPrefix ) + { + if ( items == null || items.size() == 0 ) + { + return; + } + int i = 0; + for ( Object item : items ) + { + if ( item == null ) + { + throw new NullPointerException( propertyPrefix + i + " has null value" ); + } + + String[] stringArray = StringUtils.split( item.toString(), "," ); + + for ( String aStringArray : stringArray ) + { + setProperty( propertyPrefix + i, aStringArray ); + i++; + } + + } + } + + public void setClasspath( String prefix, Classpath classpath ) + { + List classpathElements = classpath.getClassPath(); + for ( int i = 0; i < classpathElements.size(); ++i ) + { + String element = (String) classpathElements.get( i ); + setProperty( prefix + i, element ); + } + } + + private static SurefireProperties loadProperties( InputStream inStream ) + throws IOException + { + Properties p = new Properties(); + + try + { + p.load( inStream ); + } + finally + { + close( inStream ); + } + + return new SurefireProperties( p ); + } + + public static SurefireProperties loadProperties( File file ) + throws IOException + { + if ( file != null ) + { + return loadProperties( new FileInputStream( file ) ); + } + + return new SurefireProperties(); + } + + private static void close( InputStream inputStream ) + { + if ( inputStream == null ) + { + return; + } + + try + { + inputStream.close(); + } + catch ( IOException ex ) + { + // ignore + } + } + + 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/booterclient/BooterSerializer.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/BooterSerializer.java index a80a8ae17e..84371c8c49 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 @@ -21,11 +21,12 @@ import java.io.File; import java.io.IOException; -import java.util.Properties; + +import org.apache.maven.plugin.surefire.SurefireProperties; import org.apache.maven.surefire.booter.BooterConstants; import org.apache.maven.surefire.booter.ClassLoaderConfiguration; +import org.apache.maven.surefire.booter.ClasspathConfiguration; import org.apache.maven.surefire.booter.KeyValueSource; -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.SystemPropertyManager; @@ -69,29 +70,31 @@ public File serialize( KeyValueSource sourceProperties, ProviderConfiguration bo throws IOException { - PropertiesWrapper properties = new PropertiesWrapper( new Properties() ); - sourceProperties.copyTo( properties.getProperties() ); + SurefireProperties properties = new SurefireProperties( sourceProperties ); - providerConfiguration.getClasspathConfiguration().addForkProperties( properties ); + ClasspathConfiguration cp = providerConfiguration.getClasspathConfiguration(); + properties.setClasspath( ClasspathConfiguration.CLASSPATH, cp.getTestClasspath() ); + properties.setClasspath( ClasspathConfiguration.SUREFIRE_CLASSPATH, cp.getProviderClasspath() ); + properties.setProperty( ClasspathConfiguration.ENABLE_ASSERTIONS, String.valueOf( cp.isEnableAssertions()) ); + properties.setProperty( ClasspathConfiguration.CHILD_DELEGATION, String.valueOf( cp.isChildDelegation() ) ); TestArtifactInfo testNg = booterConfiguration.getTestArtifact(); if ( testNg != null ) { properties.setProperty( BooterConstants.TESTARTIFACT_VERSION, testNg.getVersion() ); - properties.setProperty( BooterConstants.TESTARTIFACT_CLASSIFIER, testNg.getClassifier() ); + properties.setNullableProperty( BooterConstants.TESTARTIFACT_CLASSIFIER, testNg.getClassifier() ); } - properties.setProperty( BooterConstants.FORKTESTSET_PREFER_TESTS_FROM_IN_STREAM, - Boolean.valueOf( readTestsFromInStream ) ); - properties.setProperty( BooterConstants.FORKTESTSET, getTypeEncoded( testSet ) ); + properties.setProperty( BooterConstants.FORKTESTSET_PREFER_TESTS_FROM_IN_STREAM, readTestsFromInStream ); + properties.setNullableProperty( BooterConstants.FORKTESTSET, getTypeEncoded( testSet ) ); TestRequest testSuiteDefinition = booterConfiguration.getTestSuiteDefinition(); if ( testSuiteDefinition != null ) { properties.setProperty( BooterConstants.SOURCE_DIRECTORY, testSuiteDefinition.getTestSourceDirectory() ); properties.addList( testSuiteDefinition.getSuiteXmlFiles(), BooterConstants.TEST_SUITE_XML_FILES ); - properties.setProperty( BooterConstants.REQUESTEDTEST, testSuiteDefinition.getRequestedTest() ); - properties.setProperty( BooterConstants.REQUESTEDTESTMETHOD, testSuiteDefinition.getRequestedTestMethod() ); + properties.setNullableProperty( BooterConstants.REQUESTEDTEST, testSuiteDefinition.getRequestedTest() ); + properties.setNullableProperty( BooterConstants.REQUESTEDTESTMETHOD, testSuiteDefinition.getRequestedTestMethod() ); } DirectoryScannerParameters directoryScannerParameters = booterConfiguration.getDirScannerParams(); @@ -129,7 +132,7 @@ public File serialize( KeyValueSource sourceProperties, ProviderConfiguration bo String.valueOf( booterConfiguration.isFailIfNoTests() ) ); properties.setProperty( BooterConstants.PROVIDER_CONFIGURATION, providerConfiguration.getProviderClassName() ); - return SystemPropertyManager.writePropertiesFile( properties.getProperties(), + return SystemPropertyManager.writePropertiesFile( properties, forkConfiguration.getTempDirectory(), "surefire", forkConfiguration.isDebug() ); } 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 7b2baebd12..03cbd4cfb4 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 @@ -93,13 +93,13 @@ public void add( List items ) } - public void add( File[] fileList ) + public void add( Object[] items ) { - if ( fileList != null ) + if ( items != null ) { - for ( File file : fileList ) + for ( Object item : items ) { - appendObject( file ); + appendObject( item ); } } else 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 28c4fee3be..ba1aa27316 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 @@ -27,13 +27,14 @@ import java.util.jar.JarEntry; import java.util.jar.JarOutputStream; import java.util.jar.Manifest; + import org.apache.maven.plugin.surefire.AbstractSurefireMojo; import org.apache.maven.plugin.surefire.booterclient.lazytestprovider.OutputStreamFlushableCommandline; import org.apache.maven.plugin.surefire.util.Relocator; import org.apache.maven.shared.utils.StringUtils; -import org.apache.maven.surefire.booter.ClassLoaderConfiguration; import org.apache.maven.surefire.booter.Classpath; import org.apache.maven.surefire.booter.ForkedBooter; +import org.apache.maven.surefire.booter.StartupConfiguration; import org.apache.maven.surefire.booter.SurefireBooterForkException; import org.apache.maven.surefire.util.UrlUtils; @@ -54,10 +55,10 @@ public class ForkConfiguration public static final String FORK_PERTHREAD = "perthread"; - public static final String FORK_ONCE_PERTHREAD = "onceperthread"; - private final int forkCount; + private final boolean reuseForks; + private final Classpath bootClasspathConfiguration; private final String jvmExecutable; @@ -76,7 +77,7 @@ public class ForkConfiguration public ForkConfiguration( Classpath bootClasspathConfiguration, File tmpDir, String debugLine, String jvmExecutable, File workingDirectory, String argLine, Map environmentVariables, - boolean debugEnabled, int forkCount ) + boolean debugEnabled, int forkCount, boolean reuseForks ) { this.bootClasspathConfiguration = bootClasspathConfiguration; this.tempDirectory = tmpDir; @@ -87,6 +88,7 @@ public ForkConfiguration( Classpath bootClasspathConfiguration, File tmpDir, Str this.environmentVariables = environmentVariables; this.debug = debugEnabled; this.forkCount = forkCount; + this.reuseForks = reuseForks; } public Classpath getBootClasspath() @@ -105,8 +107,7 @@ else if ( "none".equalsIgnoreCase( forkMode ) ) return FORK_NEVER; } else if ( forkMode.equals( FORK_NEVER ) || forkMode.equals( FORK_ONCE ) || - forkMode.equals( FORK_ALWAYS ) || forkMode.equals( FORK_PERTHREAD ) || - forkMode.equals( FORK_ONCE_PERTHREAD ) ) + forkMode.equals( FORK_ALWAYS ) || forkMode.equals( FORK_PERTHREAD ) ) { return forkMode; } @@ -116,27 +117,27 @@ else if ( forkMode.equals( FORK_NEVER ) || forkMode.equals( FORK_ONCE ) || } } - /** - * @param classPath cla the classpath arguments - * @param classpathConfiguration the classpath configuration - * @param shadefire true if running shadefire - * @param threadNumber the thread number, to be the replacement in the argLine - * @return A commandline + * @param classPath cla the classpath arguments + * @param startupConfiguration The startup configuration + * @param threadNumber the thread number, to be the replacement in the argLine @return A commandline * @throws org.apache.maven.surefire.booter.SurefireBooterForkException * when unable to perform the fork */ public OutputStreamFlushableCommandline createCommandLine( List classPath, - ClassLoaderConfiguration classpathConfiguration, - boolean shadefire, int threadNumber ) + StartupConfiguration startupConfiguration, + int threadNumber ) throws SurefireBooterForkException { - return createCommandLine( classPath, classpathConfiguration.isManifestOnlyJarRequestedAndUsable(), shadefire, - threadNumber ); + return createCommandLine( classPath, + startupConfiguration.getClassLoaderConfiguration().isManifestOnlyJarRequestedAndUsable(), + startupConfiguration.isShadefire(), startupConfiguration.isProviderMainClass() + ? startupConfiguration.getActualClassName() + : ForkedBooter.class.getName(), threadNumber ); } - public OutputStreamFlushableCommandline createCommandLine( List classPath, boolean useJar, - boolean shadefire, int threadNumber ) + OutputStreamFlushableCommandline createCommandLine( List classPath, boolean useJar, boolean shadefire, + String providerThatHasMainMethod, int threadNumber ) throws SurefireBooterForkException { OutputStreamFlushableCommandline cli = new OutputStreamFlushableCommandline(); @@ -169,7 +170,7 @@ public OutputStreamFlushableCommandline createCommandLine( List classPat File jarFile; try { - jarFile = createJar( classPath ); + jarFile = createJar( classPath, providerThatHasMainMethod ); } catch ( IOException e ) { @@ -184,7 +185,8 @@ public OutputStreamFlushableCommandline createCommandLine( List classPat { cli.addEnvironment( "CLASSPATH", StringUtils.join( classPath.iterator(), File.pathSeparator ) ); - final String forkedBooter = ForkedBooter.class.getName(); + final String forkedBooter = + providerThatHasMainMethod != null ? providerThatHasMainMethod : ForkedBooter.class.getName(); cli.createArg().setValue( shadefire ? new Relocator().relocate( forkedBooter ) : forkedBooter ); } @@ -196,18 +198,21 @@ public OutputStreamFlushableCommandline createCommandLine( List classPat private String replaceThreadNumberPlaceholder( String argLine, int threadNumber ) { - return argLine.replace( AbstractSurefireMojo.THREAD_NUMBER_PLACEHOLDER, String.valueOf( threadNumber ) ); + return argLine.replace( AbstractSurefireMojo.THREAD_NUMBER_PLACEHOLDER, + String.valueOf( threadNumber ) ).replace( AbstractSurefireMojo.FORK_NUMBER_PLACEHOLDER, + String.valueOf( threadNumber ) ); } /** * Create a jar with just a manifest containing a Main-Class entry for BooterConfiguration and a Class-Path entry * for all classpath elements. * - * @param classPath List<String> of all classpath elements. + * @param classPath List<String> of all classpath elements. + * @param startClassName The classname to start (main-class) * @return The file pointint to the jar * @throws java.io.IOException When a file operation fails. */ - public File createJar( List classPath ) + private File createJar( List classPath, String startClassName ) throws IOException { File file = File.createTempFile( "surefirebooter", ".jar", tempDirectory ); @@ -234,7 +239,7 @@ public File createJar( List classPath ) man.getMainAttributes().putValue( "Manifest-Version", "1.0" ); man.getMainAttributes().putValue( "Class-Path", cp.trim() ); - man.getMainAttributes().putValue( "Main-Class", ForkedBooter.class.getName() ); + man.getMainAttributes().putValue( "Main-Class", startClassName ); man.write( jos ); jos.close(); @@ -266,4 +271,10 @@ public int getForkCount() { return forkCount; } + + + public boolean isReuseForks() + { + return reuseForks; + } } 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 new file mode 100644 index 0000000000..c107982c5a --- /dev/null +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/ForkNumberBucket.java @@ -0,0 +1,87 @@ +package org.apache.maven.plugin.surefire.booterclient; + +import java.util.Queue; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.atomic.AtomicInteger; + +/** + * A bucket from which fork numbers can be drawn. Any drawn number needs to be returned to the bucket, in order to keep + * the range of provided values delivered as small as possible. + * + * @author Andreas Gudian + */ +public class ForkNumberBucket +{ + + private static final ForkNumberBucket INSTANCE = new ForkNumberBucket(); + + private Queue qFree = new ConcurrentLinkedQueue(); + + private AtomicInteger highWaterMark = new AtomicInteger( 1 ); + + /** + * Non-public constructor + */ + protected 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() + { + return getInstance()._drawNumber(); + } + + /** + * @param number the number to return to the bucket so that it can be reused. + */ + public static void returnNumber( int number ) + { + getInstance()._returnNumber( number ); + } + + /** + * @return a singleton instance + */ + private static ForkNumberBucket getInstance() + { + return INSTANCE; + } + + /** + * @return a fork number that is not currently in use. The value must be returned to the bucket using + * {@link #returnNumber(int)}. + */ + protected int _drawNumber() + { + Integer nextFree = qFree.poll(); + + if ( null == nextFree ) + { + return highWaterMark.getAndIncrement(); + } + else + { + return nextFree.intValue(); + } + } + + /** + * @return the highest number that has been drawn + */ + protected int getHighestDrawnNumber() + { + return highWaterMark.get() - 1; + } + + /** + * @param number the number to return to the bucket so that it can be reused. + */ + protected void _returnNumber( int number ) + { + qFree.add( Integer.valueOf( 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 bcd193110a..95bc007a13 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 @@ -21,6 +21,7 @@ import java.io.File; import java.io.IOException; +import java.io.InputStream; import java.util.ArrayList; import java.util.Iterator; import java.util.List; @@ -35,7 +36,8 @@ import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; + +import org.apache.maven.plugin.logging.Log; import org.apache.maven.plugin.surefire.AbstractSurefireMojo; import org.apache.maven.plugin.surefire.CommonReflector; import org.apache.maven.plugin.surefire.StartupReportConfiguration; @@ -48,6 +50,7 @@ import org.apache.maven.shared.utils.cli.CommandLineException; import org.apache.maven.shared.utils.cli.CommandLineTimeOutException; import org.apache.maven.shared.utils.cli.CommandLineUtils; +import org.apache.maven.shared.utils.cli.ShutdownHookUtils; import org.apache.maven.surefire.booter.Classpath; import org.apache.maven.surefire.booter.ClasspathConfiguration; import org.apache.maven.surefire.booter.KeyValueSource; @@ -63,6 +66,7 @@ import org.apache.maven.surefire.suite.RunResult; import org.apache.maven.surefire.util.DefaultScanResult; +import static org.apache.maven.surefire.booter.Classpath.join; /** * Starts the fork or runs in-process. @@ -80,6 +84,36 @@ */ public class ForkStarter { + /** + * Closes an InputStream + */ + private final class InputStreamCloser + implements Runnable + { + private InputStream testProvidingInputStream; + + public InputStreamCloser( InputStream testProvidingInputStream ) + { + this.testProvidingInputStream = testProvidingInputStream; + } + + public synchronized void run() + { + if ( testProvidingInputStream != null ) + { + try + { + testProvidingInputStream.close(); + } + catch ( IOException e ) + { + // ignore + } + testProvidingInputStream = null; + } + } + } + private final int forkedProcessTimeoutInSeconds; private final ProviderConfiguration providerConfiguration; @@ -90,36 +124,26 @@ public class ForkStarter private final StartupReportConfiguration startupReportConfiguration; - private final DefaultReporterFactory fileReporterFactory; - - private static volatile int systemPropertiesFileCounter = 0; - - private final ThreadLocal threadNumber = new ThreadLocal() - { - private final AtomicInteger nextThreadNumber = new AtomicInteger( 1 ); + private Log log; - @Override - protected Integer initialValue() - { - return nextThreadNumber.getAndIncrement(); - } - }; + private final DefaultReporterFactory defaultReporterFactory; + private static volatile int systemPropertiesFileCounter = 0; public ForkStarter( ProviderConfiguration providerConfiguration, StartupConfiguration startupConfiguration, ForkConfiguration forkConfiguration, int forkedProcessTimeoutInSeconds, - StartupReportConfiguration startupReportConfiguration ) + StartupReportConfiguration startupReportConfiguration, Log log ) { this.forkConfiguration = forkConfiguration; this.providerConfiguration = providerConfiguration; this.forkedProcessTimeoutInSeconds = forkedProcessTimeoutInSeconds; this.startupConfiguration = startupConfiguration; this.startupReportConfiguration = startupReportConfiguration; - fileReporterFactory = new DefaultReporterFactory( startupReportConfiguration ); + this.log = log; + defaultReporterFactory = new DefaultReporterFactory( startupReportConfiguration ); } - public RunResult run( SurefireProperties effectiveSystemProperties, DefaultScanResult scanResult, - String requestedForkMode ) + public RunResult run( SurefireProperties effectiveSystemProperties, DefaultScanResult scanResult ) throws SurefireBooterForkException, SurefireExecutionException { final RunResult result; @@ -127,39 +151,38 @@ public RunResult run( SurefireProperties effectiveSystemProperties, DefaultScanR { Properties providerProperties = providerConfiguration.getProviderProperties(); scanResult.writeTo( providerProperties ); - if ( ForkConfiguration.FORK_ONCE.equals( requestedForkMode ) ) + if ( isForkOnce() ) { final ForkClient forkClient = - new ForkClient( fileReporterFactory, startupReportConfiguration.getTestVmSystemProperties() ); - result = - fork( null, new PropertiesWrapper( providerProperties ), forkClient, effectiveSystemProperties, 1, - null ); - } - else if ( ForkConfiguration.FORK_ALWAYS.equals( requestedForkMode ) ) - { - result = runSuitesForkPerTestSet( effectiveSystemProperties, 1 ); - } - else if ( ForkConfiguration.FORK_PERTHREAD.equals( requestedForkMode ) ) - { - result = runSuitesForkPerTestSet( effectiveSystemProperties, forkConfiguration.getForkCount() ); - } - else if ( ForkConfiguration.FORK_ONCE_PERTHREAD.equals( requestedForkMode ) ) - { - result = runSuitesForkOncePerThread( effectiveSystemProperties, forkConfiguration.getForkCount() ); + new ForkClient( defaultReporterFactory, startupReportConfiguration.getTestVmSystemProperties() ); + result = fork( null, new PropertiesWrapper( providerProperties ), forkClient, effectiveSystemProperties, + null ); } else { - throw new SurefireExecutionException( "Unknown forkmode: " + requestedForkMode, null ); + if ( forkConfiguration.isReuseForks() ) + { + result = runSuitesForkOnceMultiple( effectiveSystemProperties, forkConfiguration.getForkCount() ); + } + else + { + result = runSuitesForkPerTestSet( effectiveSystemProperties, forkConfiguration.getForkCount() ); + } } } finally { - fileReporterFactory.close(); + defaultReporterFactory.close(); } return result; } - private RunResult runSuitesForkOncePerThread( final SurefireProperties effectiveSystemProperties, int forkCount ) + private boolean isForkOnce() + { + return forkConfiguration.isReuseForks() && 1 == forkConfiguration.getForkCount(); + } + + private RunResult runSuitesForkOnceMultiple( final SurefireProperties effectiveSystemProperties, int forkCount ) throws SurefireBooterForkException { @@ -184,10 +207,8 @@ private RunResult runSuitesForkOncePerThread( final SurefireProperties effective messageQueue.add( clazz.getName() ); } - for ( int threadNum = 0; threadNum < forkCount && threadNum < suites.size(); threadNum++ ) + for ( int forkNum = 0; forkNum < forkCount && forkNum < suites.size(); forkNum++ ) { - final int finalThreadNumber = threadNum + 1; - Callable pf = new Callable() { public RunResult call() @@ -196,13 +217,12 @@ public RunResult call() TestProvidingInputStream testProvidingInputStream = new TestProvidingInputStream( messageQueue ); - ForkClient forkClient = - new ForkClient( fileReporterFactory, startupReportConfiguration.getTestVmSystemProperties(), - testProvidingInputStream ); + ForkClient forkClient = new ForkClient( defaultReporterFactory, + startupReportConfiguration.getTestVmSystemProperties(), + testProvidingInputStream ); return fork( null, new PropertiesWrapper( providerConfiguration.getProviderProperties() ), - forkClient, effectiveSystemProperties, finalThreadNumber, - testProvidingInputStream ); + forkClient, effectiveSystemProperties, testProvidingInputStream ); } }; @@ -263,18 +283,10 @@ private RunResult runSuitesForkPerTestSet( final SurefireProperties effectiveSys public RunResult call() throws Exception { - int thisThreadsThreadNumber = threadNumber.get(); - if ( thisThreadsThreadNumber > forkCount ) - { - // this would be a bug in the ThreadPoolExecutor - throw new IllegalStateException( - "More threads than " + forkCount + " have been created by the ThreadPoolExecutor." ); - } - - ForkClient forkClient = new ForkClient( fileReporterFactory, + ForkClient forkClient = new ForkClient( defaultReporterFactory, startupReportConfiguration.getTestVmSystemProperties() ); return fork( testSet, new PropertiesWrapper( providerConfiguration.getProviderProperties() ), - forkClient, effectiveSystemProperties, thisThreadsThreadNumber, null ); + forkClient, effectiveSystemProperties, null ); } }; results.add( executorService.submit( pf ) ); @@ -330,7 +342,24 @@ private void closeExecutor( ExecutorService executorService ) } private RunResult fork( Object testSet, KeyValueSource providerProperties, ForkClient forkClient, - SurefireProperties effectiveSystemProperties, int threadNumber, + SurefireProperties effectiveSystemProperties, + TestProvidingInputStream testProvidingInputStream ) + throws SurefireBooterForkException + { + int forkNumber = ForkNumberBucket.drawNumber(); + try + { + return fork( testSet, providerProperties, forkClient, effectiveSystemProperties, forkNumber, + testProvidingInputStream ); + } + finally + { + ForkNumberBucket.returnNumber( forkNumber ); + } + } + + private RunResult fork( Object testSet, KeyValueSource providerProperties, ForkClient forkClient, + SurefireProperties effectiveSystemProperties, int forkNumber, TestProvidingInputStream testProvidingInputStream ) throws SurefireBooterForkException { @@ -347,8 +376,8 @@ private RunResult fork( Object testSet, KeyValueSource providerProperties, ForkC if ( effectiveSystemProperties != null ) { SurefireProperties filteredProperties = - AbstractSurefireMojo.createCopyAndReplaceThreadNumPlaceholder( effectiveSystemProperties, - threadNumber ); + AbstractSurefireMojo.createCopyAndReplaceForkNumPlaceholder( effectiveSystemProperties, + forkNumber ); systPropsFile = SystemPropertyManager.writePropertiesFile( filteredProperties, forkConfiguration.getTempDirectory(), "surefire_" + systemPropertiesFileCounter++, @@ -360,24 +389,36 @@ private RunResult fork( Object testSet, KeyValueSource providerProperties, ForkC throw new SurefireBooterForkException( "Error creating properties files for forking", e ); } - final Classpath bootClasspathConfiguration = forkConfiguration.getBootClasspath(); - - final Classpath additionlClassPathUrls = startupConfiguration.useSystemClassLoader() - ? startupConfiguration.getClasspathConfiguration().getTestClasspath() - : null; + // this could probably be simplified further + final Classpath bootClasspathConfiguration = startupConfiguration.isProviderMainClass() + ? startupConfiguration.getClasspathConfiguration().getProviderClasspath() + : forkConfiguration.getBootClasspath(); - // Surefire-booter + all test classes if "useSystemClassloader" - // Surefire-booter if !useSystemClassLoader - Classpath bootClasspath = Classpath.join( bootClasspathConfiguration, additionlClassPathUrls ); + Classpath bootClasspath = join( + join( bootClasspathConfiguration, startupConfiguration.getClasspathConfiguration().getTestClasspath() ), + startupConfiguration.getClasspathConfiguration().getProviderClasspath() ); - @SuppressWarnings( "unchecked" ) OutputStreamFlushableCommandline cli = - forkConfiguration.createCommandLine( bootClasspath.getClassPath(), - startupConfiguration.getClassLoaderConfiguration(), - startupConfiguration.isShadefire(), threadNumber ); + if ( log.isDebugEnabled() ) + { + log.debug( bootClasspath.getLogMessage( "boot" ) ); + log.debug( bootClasspath.getCompactLogMessage( "boot(compact)" ) ); + } + OutputStreamFlushableCommandline cli = + forkConfiguration.createCommandLine( bootClasspath.getClassPath(), startupConfiguration, forkNumber ); + final InputStreamCloser inputStreamCloser; + final Thread inputStreamCloserHook; if ( testProvidingInputStream != null ) { testProvidingInputStream.setFlushReceiverProvider( cli ); + inputStreamCloser = new InputStreamCloser( testProvidingInputStream ); + inputStreamCloserHook = new Thread( inputStreamCloser ); + ShutdownHookUtils.addShutDownHook( inputStreamCloserHook ); + } + else + { + inputStreamCloser = null; + inputStreamCloserHook = null; } cli.createArg().setFile( surefireProperties ); @@ -401,45 +442,49 @@ private RunResult fork( Object testSet, KeyValueSource providerProperties, ForkC final int timeout = forkedProcessTimeoutInSeconds > 0 ? forkedProcessTimeoutInSeconds : 0; final int result = CommandLineUtils.executeCommandLine( cli, testProvidingInputStream, threadedStreamConsumer, - threadedStreamConsumer, timeout ); + threadedStreamConsumer, timeout, inputStreamCloser ); if ( result != RunResult.SUCCESS ) { throw new SurefireBooterForkException( "Error occurred in starting fork, check output in log" ); } - } catch ( CommandLineTimeOutException e ) { - runResult = RunResult.timeout( fileReporterFactory.getGlobalRunStatistics().getRunResult() ); + runResult = RunResult.timeout( defaultReporterFactory.getGlobalRunStatistics().getRunResult() ); } catch ( CommandLineException e ) { - runResult = RunResult.failure( fileReporterFactory.getGlobalRunStatistics().getRunResult(), e ); + runResult = RunResult.failure( defaultReporterFactory.getGlobalRunStatistics().getRunResult(), e ); throw new SurefireBooterForkException( "Error while executing forked tests.", e.getCause() ); } finally { threadedStreamConsumer.close(); + if ( inputStreamCloser != null ) + { + inputStreamCloser.run(); + ShutdownHookUtils.removeShutdownHook( inputStreamCloserHook ); + } if ( runResult == null ) { - runResult = fileReporterFactory.getGlobalRunStatistics().getRunResult(); + runResult = defaultReporterFactory.getGlobalRunStatistics().getRunResult(); } if ( !runResult.isTimeout() ) { StackTraceWriter errorInFork = forkClient.getErrorInFork(); if ( errorInFork != null ) { - //noinspection ThrowFromFinallyBlock + // noinspection ThrowFromFinallyBlock throw new RuntimeException( "There was an error in the forked process\n" + errorInFork.writeTraceToString() ); } if ( !forkClient.isSaidGoodBye() ) { - //noinspection ThrowFromFinallyBlock + // noinspection ThrowFromFinallyBlock throw new RuntimeException( - "The forked VM terminated without saying properly goodbye. VM crash or System.exit called ?" + - "\nCommand was" + cli.toString() ); + "The forked VM terminated without saying properly goodbye. VM crash or System.exit called ?" + + "\nCommand was" + cli.toString() ); } } @@ -456,15 +501,13 @@ private Iterator> getSuitesIterator() try { final ClasspathConfiguration classpathConfiguration = startupConfiguration.getClasspathConfiguration(); - ClassLoader testsClassLoader = classpathConfiguration.createTestClassLoader( false ); - ClassLoader surefireClassLoader = - classpathConfiguration.createInprocSurefireClassLoader( testsClassLoader ); + ClassLoader unifiedClassLoader = classpathConfiguration.createMergedClassLoader(); - CommonReflector commonReflector = new CommonReflector( surefireClassLoader ); + CommonReflector commonReflector = new CommonReflector( unifiedClassLoader ); Object reporterFactory = commonReflector.createReportingReporterFactory( startupReportConfiguration ); final ProviderFactory providerFactory = - new ProviderFactory( startupConfiguration, providerConfiguration, surefireClassLoader, testsClassLoader, + new ProviderFactory( startupConfiguration, providerConfiguration, unifiedClassLoader, reporterFactory ); SurefireProvider surefireProvider = providerFactory.createProvider( false ); return surefireProvider.getSuites(); @@ -474,5 +517,4 @@ private Iterator> getSuitesIterator() throw new SurefireBooterForkException( "Unable to create classloader to find test suites", e ); } } - } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/ProviderDetector.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/ProviderDetector.java index 57ee3679a6..cc71fe9a7f 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/ProviderDetector.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/ProviderDetector.java @@ -19,6 +19,7 @@ * under the License. */ +import javax.annotation.Nonnull; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; @@ -37,7 +38,7 @@ public class ProviderDetector { - public static Set getServiceNames( Class clazz, ClassLoader classLoader ) + @Nonnull public static Set getServiceNames( Class clazz, ClassLoader classLoader ) throws IOException { final String resourceName = "META-INF/services/" + clazz.getName(); @@ -59,7 +60,7 @@ public static Set getServiceNames( Class clazz, ClassLoader classLoad * @return The set of service provider names * @throws IOException When reading the streams fails */ - private static Set getNames( final Enumeration urlEnumeration ) + @Nonnull private static Set getNames( final Enumeration urlEnumeration ) throws IOException { final Set names = new HashSet(); @@ -117,7 +118,7 @@ private static Set getNames( final Enumeration urlEnumeration ) return names; } - private static BufferedReader getReader( URL url ) + @Nonnull private static BufferedReader getReader( @Nonnull URL url ) throws IOException { final InputStream inputStream = url.openStream(); diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/lazytestprovider/FlushReceiver.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/lazytestprovider/FlushReceiver.java index 969affac8b..a7aa62e951 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/lazytestprovider/FlushReceiver.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/lazytestprovider/FlushReceiver.java @@ -1,38 +1,38 @@ -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 - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES 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; - -/** - * Something that can be flushed. - * - * @author Andreas Gudian - */ -public interface FlushReceiver -{ - /** - * Performs a flush, releasing any buffered resources. - * - * @throws IOException in case the flush operation failed - */ - void flush() - throws IOException; -} +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 + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES 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; + +/** + * Something that can be flushed. + * + * @author Andreas Gudian + */ +public interface FlushReceiver +{ + /** + * Performs a flush, releasing any buffered resources. + * + * @throws IOException in case the flush operation failed + */ + void flush() + throws IOException; +} diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/lazytestprovider/FlushReceiverProvider.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/lazytestprovider/FlushReceiverProvider.java index 8c15fa6567..96ea32ca5b 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/lazytestprovider/FlushReceiverProvider.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/lazytestprovider/FlushReceiverProvider.java @@ -1,34 +1,34 @@ -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 - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/** - * Provides a {@link FlushReceiver}. - * - * @author Andreas Gudian - */ -public interface FlushReceiverProvider -{ - - /** - * @return a {@link FlushReceiver} - */ - FlushReceiver getFlushReceiver(); +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 + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +/** + * Provides a {@link FlushReceiver}. + * + * @author Andreas Gudian + */ +public interface FlushReceiverProvider +{ + + /** + * @return a {@link FlushReceiver} + */ + FlushReceiver getFlushReceiver(); } \ No newline at end of file diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/lazytestprovider/OutputStreamFlushableCommandline.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/lazytestprovider/OutputStreamFlushableCommandline.java index 60b8325d89..deefbd0ee0 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/lazytestprovider/OutputStreamFlushableCommandline.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/lazytestprovider/OutputStreamFlushableCommandline.java @@ -1,82 +1,82 @@ -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 - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES 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.io.OutputStream; -import org.apache.maven.shared.utils.cli.CommandLineException; -import org.apache.maven.shared.utils.cli.Commandline; - -/** - * A {@link Commandline} implementation that provides the output stream of - * the executed process in form of a {@link FlushReceiver}, for it to be - * flushed on demand. - * - * @author Andreas Gudian - */ -public class OutputStreamFlushableCommandline - extends Commandline - implements FlushReceiverProvider -{ - /** - * Wraps an output stream in order to delegate a flush. - */ - private final class OutputStreamFlushReceiver - implements FlushReceiver - { - private final OutputStream outputStream; - - private OutputStreamFlushReceiver( OutputStream outputStream ) - { - this.outputStream = outputStream; - } - - public void flush() - throws IOException - { - outputStream.flush(); - } - } - - private FlushReceiver flushReceiver; - - @Override - public Process execute() - throws CommandLineException - { - Process process = super.execute(); - - if ( process.getOutputStream() != null ) - { - flushReceiver = new OutputStreamFlushReceiver( process.getOutputStream() ); - } - - return process; - } - - /* (non-Javadoc) - * @see org.apache.maven.plugin.surefire.booterclient.lazytestprovider.FlushReceiverProvider#getFlushReceiver() - */ - public FlushReceiver getFlushReceiver() - { - return flushReceiver; - } - +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 + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES 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.io.OutputStream; +import org.apache.maven.shared.utils.cli.CommandLineException; +import org.apache.maven.shared.utils.cli.Commandline; + +/** + * A {@link Commandline} implementation that provides the output stream of + * the executed process in form of a {@link FlushReceiver}, for it to be + * flushed on demand. + * + * @author Andreas Gudian + */ +public class OutputStreamFlushableCommandline + extends Commandline + implements FlushReceiverProvider +{ + /** + * Wraps an output stream in order to delegate a flush. + */ + private final class OutputStreamFlushReceiver + implements FlushReceiver + { + private final OutputStream outputStream; + + private OutputStreamFlushReceiver( OutputStream outputStream ) + { + this.outputStream = outputStream; + } + + public void flush() + throws IOException + { + outputStream.flush(); + } + } + + private FlushReceiver flushReceiver; + + @Override + public Process execute() + throws CommandLineException + { + Process process = super.execute(); + + if ( process.getOutputStream() != null ) + { + flushReceiver = new OutputStreamFlushReceiver( process.getOutputStream() ); + } + + return process; + } + + /* (non-Javadoc) + * @see org.apache.maven.plugin.surefire.booterclient.lazytestprovider.FlushReceiverProvider#getFlushReceiver() + */ + public FlushReceiver getFlushReceiver() + { + return flushReceiver; + } + } \ No newline at end of file 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 1e63234537..730443559f 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,114 +1,125 @@ -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 - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES 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.io.InputStream; -import java.util.Queue; -import java.util.concurrent.Semaphore; - -/** - * An {@link InputStream} that, when read, provides test class names out of - * a queue. - *

- * The Stream provides only one test at a time, but only after {@link #provideNewTest()} - * has been invoked. - *

- * After providing each test class name, followed by a newline character, a flush is - * performed on the {@link FlushReceiver} provided by the {@link FlushReceiverProvider} - * that can be set using {@link #setFlushReceiverProvider(FlushReceiverProvider)}. - * - * @author Andreas Gudian - */ -public class TestProvidingInputStream - extends InputStream -{ - private final Queue testItemQueue; - - private byte[] currentBuffer; - - private int currentPos; - - private Semaphore semaphore = new Semaphore( 0 ); - - private FlushReceiverProvider flushReceiverProvider; - - /** - * C'tor - * - * @param testItemQueue source of the tests to be read from this stream - */ - public TestProvidingInputStream( Queue testItemQueue ) - { - this.testItemQueue = testItemQueue; - } - - /** - * @param flushReceiverProvider the provider for a flush receiver. - */ - public void setFlushReceiverProvider( FlushReceiverProvider flushReceiverProvider ) - { - this.flushReceiverProvider = flushReceiverProvider; - } - - @Override - public synchronized int read() - throws IOException - { - if ( null == currentBuffer ) - { - if ( null != flushReceiverProvider && null != flushReceiverProvider.getFlushReceiver() ) - { - flushReceiverProvider.getFlushReceiver().flush(); - } - - semaphore.acquireUninterruptibly(); - - String currentElement = testItemQueue.poll(); - if ( null != currentElement ) - { - currentBuffer = currentElement.getBytes(); - currentPos = 0; - } - else - { - return -1; - } - } - - if ( currentPos < currentBuffer.length ) - { - return ( currentBuffer[currentPos++] & 0xff ); - } - else - { - currentBuffer = null; - return ( '\n' & 0xff ); - } - } - - /** - * Signal that a new test is to be provided. - */ - public void provideNewTest() - { - semaphore.release(); - } +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 + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES 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.io.InputStream; +import java.util.Queue; +import java.util.concurrent.Semaphore; + +/** + * An {@link InputStream} that, when read, provides test class names out of a queue. + *

+ * The Stream provides only one test at a time, but only after {@link #provideNewTest()} has been invoked. + *

+ * After providing each test class name, followed by a newline character, a flush is performed on the + * {@link FlushReceiver} provided by the {@link FlushReceiverProvider} that can be set using + * {@link #setFlushReceiverProvider(FlushReceiverProvider)}. + * + * @author Andreas Gudian + */ +public class TestProvidingInputStream + extends InputStream +{ + private final Queue testItemQueue; + + private byte[] currentBuffer; + + private int currentPos; + + private Semaphore semaphore = new Semaphore( 0 ); + + private FlushReceiverProvider flushReceiverProvider; + + private boolean closed = false; + + /** + * C'tor + * + * @param testItemQueue source of the tests to be read from this stream + */ + public TestProvidingInputStream( Queue testItemQueue ) + { + this.testItemQueue = testItemQueue; + } + + /** + * @param flushReceiverProvider the provider for a flush receiver. + */ + public void setFlushReceiverProvider( FlushReceiverProvider flushReceiverProvider ) + { + this.flushReceiverProvider = flushReceiverProvider; + } + + @Override + public synchronized int read() + throws IOException + { + if ( null == currentBuffer ) + { + if ( null != flushReceiverProvider && null != flushReceiverProvider.getFlushReceiver() ) + { + flushReceiverProvider.getFlushReceiver().flush(); + } + + semaphore.acquireUninterruptibly(); + + if ( closed ) + { + return -1; + } + + String currentElement = testItemQueue.poll(); + if ( null != currentElement ) + { + currentBuffer = currentElement.getBytes(); + currentPos = 0; + } + else + { + return -1; + } + } + + if ( currentPos < currentBuffer.length ) + { + return ( currentBuffer[currentPos++] & 0xff ); + } + else + { + currentBuffer = null; + return ( '\n' & 0xff ); + } + } + + /** + * Signal that a new test is to be provided. + */ + public void provideNewTest() + { + semaphore.release(); + } + + public void close() + { + closed = true; + semaphore.release(); + } } \ No newline at end of file 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 19af86f50a..daa3f29a70 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 @@ -37,10 +37,18 @@ public class DeserializedStacktraceWriter private final String stackTrace; - public DeserializedStacktraceWriter( String message, String stackTrace ) + private final String smartTrimmed; + + public DeserializedStacktraceWriter( String message, String smartTrimmed, String stackTrace ) { this.message = message; this.stackTrace = stackTrace; + this.smartTrimmed = smartTrimmed; + } + + public String smartTrimmedStackTrace() + { + return smartTrimmed; } // Trimming or not is decided on the forking side 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 13fe457a60..fa2f41d48e 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 @@ -44,14 +44,14 @@ /** * Knows how to reconstruct *all* the state transmitted over stdout by the forked process. - * + * * @author Kristian Rosenvold */ public class ForkClient implements StreamConsumer { - private final DefaultReporterFactory providerReporterFactory; + private final DefaultReporterFactory defaultReporterFactory; private final TestProvidingInputStream testProvidingInputStream; @@ -64,15 +64,15 @@ public class ForkClient private volatile StackTraceWriter errorInFork = null; - public ForkClient( DefaultReporterFactory providerReporterFactory, Properties testVmSystemProperties ) + public ForkClient( DefaultReporterFactory defaultReporterFactory, Properties testVmSystemProperties ) { - this( providerReporterFactory, testVmSystemProperties, null ); + this( defaultReporterFactory, testVmSystemProperties, null ); } - public ForkClient( DefaultReporterFactory providerReporterFactory, Properties testVmSystemProperties, + public ForkClient( DefaultReporterFactory defaultReporterFactory, Properties testVmSystemProperties, TestProvidingInputStream testProvidingInputStream ) { - this.providerReporterFactory = providerReporterFactory; + this.defaultReporterFactory = defaultReporterFactory; this.testVmSystemProperties = testVmSystemProperties; this.testProvidingInputStream = testProvidingInputStream; } @@ -215,9 +215,11 @@ private StackTraceWriter deserializeStackStraceWriter( StringTokenizer tokens ) { StackTraceWriter stackTraceWriter; String stackTraceMessage = nullableCsv( tokens.nextToken() ); + String smartStackTrace = nullableCsv( tokens.nextToken() ); String stackTrace = tokens.hasMoreTokens() ? nullableCsv( tokens.nextToken() ) : null; stackTraceWriter = - stackTrace != null ? new DeserializedStacktraceWriter( stackTraceMessage, stackTrace ) : null; + stackTrace != null ? new DeserializedStacktraceWriter( stackTraceMessage, smartStackTrace, stackTrace ) + : null; return stackTraceWriter; } @@ -240,7 +242,7 @@ private String unescape( String source ) /** * Used when getting reporters on the plugin side of a fork. - * + * * @param channelNumber The logical channel number * @return A mock provider reporter */ @@ -254,7 +256,7 @@ private RunListener getOrCreateReporter( Integer channelNumber ) RunListener reporter = testSetReporters.get( channelNumber ); if ( reporter == null ) { - reporter = providerReporterFactory.createReporter(); + reporter = defaultReporterFactory.createReporter(); testSetReporters.put( channelNumber, reporter ); } return reporter; 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 c2c1519a49..d4d6991e20 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 @@ -19,10 +19,10 @@ * under the License. */ -import org.apache.maven.plugin.surefire.util.internal.BlockingQueue; -import org.apache.maven.plugin.surefire.util.internal.Java15BlockingQueue; import org.apache.maven.shared.utils.cli.StreamConsumer; +import java.util.concurrent.LinkedBlockingQueue; + /** * Knows how to reconstruct *all* the state transmitted over stdout by the forked process. * @@ -32,7 +32,7 @@ public class ThreadedStreamConsumer implements StreamConsumer { - private final BlockingQueue items = new Java15BlockingQueue(); + private final java.util.concurrent.BlockingQueue items = new LinkedBlockingQueue(); private static final String poison = "Pioson"; @@ -43,14 +43,14 @@ public class ThreadedStreamConsumer static class Pumper implements Runnable { - private final BlockingQueue queue; + private final java.util.concurrent.BlockingQueue queue; private final StreamConsumer target; - private volatile InterruptedException interruptedException; + private volatile Throwable throwable; - Pumper( BlockingQueue queue, StreamConsumer target ) + Pumper( java.util.concurrent.BlockingQueue queue, StreamConsumer target ) { this.queue = queue; this.target = target; @@ -68,15 +68,17 @@ public void run() item = queue.take(); } } - catch ( InterruptedException e ) + catch ( Throwable t ) { - this.interruptedException = e; + // Think about what happens if the producer overruns us and creates an OOME. Not nice. + // Maybe limit length of blocking queue + this.throwable = t; } } - public InterruptedException getInterruptedException() + public Throwable getThrowable() { - return interruptedException; + return throwable; } } @@ -90,6 +92,16 @@ public ThreadedStreamConsumer( StreamConsumer target ) public void consumeLine( String s ) { items.add( s ); + if ( items.size() > 10000 ) + { + try + { + Thread.sleep( 100 ); + } + catch ( InterruptedException ignore ) + { + } + } } @@ -99,15 +111,16 @@ public void close() { items.add( poison ); thread.join(); - //noinspection ThrowableResultOfMethodCallIgnored - if ( pumper.getInterruptedException() != null ) - { - throw pumper.getInterruptedException(); - } } catch ( InterruptedException e ) { throw new RuntimeException( e ); } + + //noinspection ThrowableResultOfMethodCallIgnored + if ( pumper.getThrowable() != null ) + { + throw new RuntimeException( pumper.getThrowable() ); + } } } 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 52165af113..14e8c67ffc 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,133 +1,122 @@ -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 - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES 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.BufferedOutputStream; -import java.io.OutputStreamWriter; -import java.io.PrintStream; -import java.io.PrintWriter; -import java.util.List; -import org.apache.maven.surefire.report.ReportEntry; -import org.apache.maven.surefire.report.ReporterException; - -/** - * Base class for console reporters. - * - * @author Brett Porter - * @author Kristian Rosenvold - */ -public class ConsoleReporter -{ - public static final String BRIEF = "brief"; - - public static final String PLAIN = "plain"; - - private static final String TEST_SET_STARTING_PREFIX = "Running "; - - private static final String TEST_SET_STARTING_GROUP_PREFIX = " (of "; - - private static final String TEST_SET_STARTING_GROUP_SUFIX = ")"; - - private static final int BUFFER_SIZE = 4096; - - private final PrintWriter writer; - - - public ConsoleReporter( PrintStream originalSystemOut ) - { - OutputStreamWriter out = new OutputStreamWriter( new BufferedOutputStream( originalSystemOut, BUFFER_SIZE ) ); - this.writer = new PrintWriter( out ); - } - - public void testSetStarting( ReportEntry report ) - throws ReporterException - { - writeMessage( getTestSetStartingMessage( report ) ); - } - - public void writeMessage( String message ) - { - if ( writer != null ) - { - writer.print( message ); - - writer.flush(); - } - } - - public void writeLnMessage( String message ) - { - if ( writer != null ) - { - writer.println( message ); - - writer.flush(); - } - } - - public void testSetCompleted( WrappedReportEntry report, TestSetStats testSetStats, List testResults ) - throws ReporterException - { - writeMessage( testSetStats.getTestSetSummary( report ) ); - - if ( testResults != null ) - { - for ( String testResult : testResults ) - { - writeLnMessage( testResult ); - } - } - } - - - public void reset() - { - if ( writer != null ) - { - writer.flush(); - } - } - - /** - * Get the test set starting message for a report. - * eg. "Running org.foo.BarTest ( of group )" - * - * @param report report whose test set is starting - * @return the message - */ - static String getTestSetStartingMessage( ReportEntry report ) - { - StringBuilder message = new StringBuilder(); - message.append( TEST_SET_STARTING_PREFIX ); - message.append( report.getName() ); - - if ( report.getGroup() != null && !report.getName().equals( report.getGroup() ) ) - { - message.append( TEST_SET_STARTING_GROUP_PREFIX ); - message.append( report.getGroup() ); - message.append( TEST_SET_STARTING_GROUP_SUFIX ); - } - - message.append( "\n" ); - return message.toString(); - } - - -} +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 + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES 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.BufferedOutputStream; +import java.io.OutputStreamWriter; +import java.io.PrintStream; +import java.io.PrintWriter; +import java.util.List; +import org.apache.maven.surefire.report.ReportEntry; +import org.apache.maven.surefire.report.ReporterException; + +/** + * Base class for console reporters. + * + * @author Brett Porter + * @author Kristian Rosenvold + */ +public class ConsoleReporter +{ + public static final String BRIEF = "brief"; + + public static final String PLAIN = "plain"; + + private static final String TEST_SET_STARTING_PREFIX = "Running "; + + private static final int BUFFER_SIZE = 4096; + + private final PrintWriter writer; + + + public ConsoleReporter( PrintStream originalSystemOut ) + { + OutputStreamWriter out = new OutputStreamWriter( new BufferedOutputStream( originalSystemOut, BUFFER_SIZE ) ); + this.writer = new PrintWriter( out ); + } + + public void testSetStarting( ReportEntry report ) + throws ReporterException + { + writeMessage( getTestSetStartingMessage( report ) ); + } + + public void writeMessage( String message ) + { + if ( writer != null ) + { + writer.print( message ); + + writer.flush(); + } + } + + public void writeLnMessage( String message ) + { + if ( writer != null ) + { + writer.println( message ); + + writer.flush(); + } + } + + public void testSetCompleted( WrappedReportEntry report, TestSetStats testSetStats, List testResults ) + throws ReporterException + { + writeMessage( testSetStats.getTestSetSummary( report ) ); + + if ( testResults != null ) + { + for ( String testResult : testResults ) + { + writeLnMessage( testResult ); + } + } + } + + + public void reset() + { + if ( writer != null ) + { + writer.flush(); + } + } + + /** + * Get the test set starting message for a report. + * eg. "Running org.foo.BarTest ( of group )" + * + * @param report report whose test set is starting + * @return the message + */ + static String getTestSetStartingMessage( ReportEntry report ) + { + StringBuilder message = new StringBuilder(); + message.append( TEST_SET_STARTING_PREFIX ); + message.append( report.getNameWithGroup() ); + + message.append( "\n" ); + return message.toString(); + } + + +} 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 55784ff761..d02eddc9a8 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,138 +1,143 @@ -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 - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES 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.Collections; -import java.util.List; -import org.apache.maven.plugin.surefire.StartupReportConfiguration; -import org.apache.maven.plugin.surefire.runorder.StatisticsReporter; -import org.apache.maven.surefire.report.DefaultDirectConsoleReporter; -import org.apache.maven.surefire.report.ReporterFactory; -import org.apache.maven.surefire.report.RunListener; -import org.apache.maven.surefire.report.RunStatistics; -import org.apache.maven.surefire.suite.RunResult; - -/** - * Provides reporting modules on the plugin side. - *

- * Keeps a centralized count of test run results. - * - * @author Kristian Rosenvold - */ -public class DefaultReporterFactory - implements ReporterFactory -{ - - private final RunStatistics globalStats = new RunStatistics(); - - private final ConsoleReporter multicastingReporter; - - private final StartupReportConfiguration reportConfiguration; - - private final StatisticsReporter statisticsReporter; - - private final List listeners = - Collections.synchronizedList( new ArrayList() ); - - public DefaultReporterFactory( StartupReportConfiguration reportConfiguration ) - { - this.reportConfiguration = reportConfiguration; - multicastingReporter = reportConfiguration.instantiateConsoleReporter(); - this.statisticsReporter = reportConfiguration.instantiateStatisticsReporter(); - runStarting(); - } - - public RunListener createReporter() - { - TestSetRunListener testSetRunListener = - new TestSetRunListener( reportConfiguration.instantiateConsoleReporter(), - reportConfiguration.instantiateFileReporter(), - reportConfiguration.instantiateStatelessXmlReporter(), - reportConfiguration.instantiateConsoleOutputFileReporter(), statisticsReporter, - globalStats, reportConfiguration.isTrimStackTrace(), - ConsoleReporter.PLAIN.equals( reportConfiguration.getReportFormat() ), - reportConfiguration.isBriefOrPlainFormat() ); - listeners.add( testSetRunListener ); - return testSetRunListener; - } - - public RunResult close() - { - runCompleted(); - for ( TestSetRunListener listener : listeners ) - { - listener.close(); - } - return globalStats.getRunResult(); - } - - private DefaultDirectConsoleReporter createConsoleLogger() - { - return new DefaultDirectConsoleReporter( reportConfiguration.getOriginalSystemOut() ); - } - - public void runStarting() - { - final DefaultDirectConsoleReporter consoleReporter = createConsoleLogger(); - consoleReporter.info( "" ); - consoleReporter.info( "-------------------------------------------------------" ); - consoleReporter.info( " T E S T S" ); - consoleReporter.info( "-------------------------------------------------------" ); - } - - private void runCompleted() - { - final DefaultDirectConsoleReporter logger = createConsoleLogger(); - logger.info( "" ); - logger.info( "Results :" ); - logger.info( "" ); - if ( globalStats.hadFailures() ) - { - multicastingReporter.writeMessage( "Failed tests: " ); - for ( Object o : this.globalStats.getFailureSources() ) - { - logger.info( " " + o ); - } - logger.info( "" ); - } - if ( globalStats.hadErrors() ) - { - logger.info( "Tests in error: " ); - for ( Object o : this.globalStats.getErrorSources() ) - { - logger.info( " " + o ); - } - logger.info( "" ); - } - logger.info( globalStats.getSummary() ); - logger.info( "" ); - } - - public RunStatistics getGlobalRunStatistics() - { - return globalStats; - } - - public static DefaultReporterFactory defaultNoXml() - { - return new DefaultReporterFactory( StartupReportConfiguration.defaultNoXml() ); - } -} +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 + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES 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.Collections; +import java.util.List; +import org.apache.maven.plugin.surefire.StartupReportConfiguration; +import org.apache.maven.plugin.surefire.runorder.StatisticsReporter; +import org.apache.maven.surefire.report.DefaultDirectConsoleReporter; +import org.apache.maven.surefire.report.ReporterFactory; +import org.apache.maven.surefire.report.RunListener; +import org.apache.maven.surefire.report.RunStatistics; +import org.apache.maven.surefire.suite.RunResult; + +/** + * Provides reporting modules on the plugin side. + *

+ * Keeps a centralized count of test run results. + * + * @author Kristian Rosenvold + */ +public class DefaultReporterFactory + implements ReporterFactory +{ + + private final RunStatistics globalStats = new RunStatistics(); + + private final StartupReportConfiguration reportConfiguration; + + private final StatisticsReporter statisticsReporter; + + private final List listeners = + Collections.synchronizedList( new ArrayList() ); + + public DefaultReporterFactory( StartupReportConfiguration reportConfiguration ) + { + this.reportConfiguration = reportConfiguration; + this.statisticsReporter = reportConfiguration.instantiateStatisticsReporter(); + runStarting(); + } + + public RunListener createReporter() + { + return createTestSetRunListener(); + } + + public RunListener createTestSetRunListener() + { + TestSetRunListener testSetRunListener = + new TestSetRunListener( reportConfiguration.instantiateConsoleReporter(), + reportConfiguration.instantiateFileReporter(), + reportConfiguration.instantiateStatelessXmlReporter(), + reportConfiguration.instantiateConsoleOutputFileReporter(), statisticsReporter, + globalStats, reportConfiguration.isTrimStackTrace(), + ConsoleReporter.PLAIN.equals( reportConfiguration.getReportFormat() ), + reportConfiguration.isBriefOrPlainFormat() ); + listeners.add( testSetRunListener ); + return testSetRunListener; + } + + public RunResult close() + { + runCompleted(); + for ( TestSetRunListener listener : listeners ) + { + listener.close(); + } + return globalStats.getRunResult(); + } + + private DefaultDirectConsoleReporter createConsoleLogger() + { + return new DefaultDirectConsoleReporter( reportConfiguration.getOriginalSystemOut() ); + } + + public void runStarting() + { + final DefaultDirectConsoleReporter consoleReporter = createConsoleLogger(); + consoleReporter.info( "" ); + consoleReporter.info( "-------------------------------------------------------" ); + consoleReporter.info( " T E S T S" ); + consoleReporter.info( "-------------------------------------------------------" ); + } + + private void runCompleted() + { + final DefaultDirectConsoleReporter logger = createConsoleLogger(); + if ( reportConfiguration.isPrintSummary() ) + { + logger.info( "" ); + logger.info( "Results :" ); + logger.info( "" ); + } + if ( globalStats.hadFailures() ) + { + logger.info( "Failed tests: " ); + for ( Object o : this.globalStats.getFailureSources() ) + { + logger.info( " " + o ); + } + logger.info( "" ); + } + if ( globalStats.hadErrors() ) + { + logger.info( "Tests in error: " ); + for ( Object o : this.globalStats.getErrorSources() ) + { + logger.info( " " + o ); + } + logger.info( "" ); + } + logger.info( globalStats.getSummary() ); + logger.info( "" ); + } + + public RunStatistics getGlobalRunStatistics() + { + return globalStats; + } + + public static DefaultReporterFactory defaultNoXml() + { + return new DefaultReporterFactory( StartupReportConfiguration.defaultNoXml() ); + } +} 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 9bc883f8ee..ab710e964d 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,65 +1,65 @@ -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 - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES 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.PrintStream; -import org.apache.maven.surefire.report.ReportEntry; - -/** - * Outputs test system out/system err directly to the console - *

- * Just a step on the road to getting the separation of reporting concerns - * operating properly. - * - * @author Kristian Rosenvold - */ -public class DirectConsoleOutput - implements TestcycleConsoleOutputReceiver -{ - private final PrintStream sout; - - private final PrintStream serr; - - public DirectConsoleOutput( PrintStream sout, PrintStream serr ) - { - this.sout = sout; - this.serr = serr; - } - - - public void writeTestOutput( byte[] buf, int off, int len, boolean stdout ) - { - PrintStream stream = stdout ? sout : serr; - stream.write( buf, off, len ); - } - - public void testSetStarting( ReportEntry reportEntry ) - { - } - - public void testSetCompleted( ReportEntry report ) - { - } - - public void close() - { - //To change body of implemented methods use File | Settings | File Templates. - } -} +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 + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES 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.PrintStream; +import org.apache.maven.surefire.report.ReportEntry; + +/** + * Outputs test system out/system err directly to the console + *

+ * Just a step on the road to getting the separation of reporting concerns + * operating properly. + * + * @author Kristian Rosenvold + */ +public class DirectConsoleOutput + implements TestcycleConsoleOutputReceiver +{ + private final PrintStream sout; + + private final PrintStream serr; + + public DirectConsoleOutput( PrintStream sout, PrintStream serr ) + { + this.sout = sout; + this.serr = serr; + } + + + public void writeTestOutput( byte[] buf, int off, int len, boolean stdout ) + { + PrintStream stream = stdout ? sout : serr; + stream.write( buf, off, len ); + } + + public void testSetStarting( ReportEntry reportEntry ) + { + } + + public void testSetCompleted( ReportEntry report ) + { + } + + public void close() + { + //To change body of implemented methods use File | Settings | File Templates. + } +} 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 3bab9f538c..f2e8e28455 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 @@ -27,9 +27,11 @@ import org.apache.maven.surefire.report.ReportEntry; import org.apache.maven.surefire.report.ReporterException; +import static org.apache.maven.plugin.surefire.report.FileReporterUtils.stripIllegalFilenameChars; + /** * Base class for file reporters. - * + * * @author Brett Porter * @author Kristian Rosenvold */ @@ -55,12 +57,12 @@ private PrintWriter testSetStarting( ReportEntry report ) File reportDir = reportFile.getParentFile(); - //noinspection ResultOfMethodCallIgnored + // noinspection ResultOfMethodCallIgnored reportDir.mkdirs(); if ( deleteOnStarting && reportFile.exists() ) { - //noinspection ResultOfMethodCallIgnored + // noinspection ResultOfMethodCallIgnored reportFile.delete(); } @@ -89,11 +91,13 @@ public static File getReportFile( File reportsDirectory, String reportEntryName, if ( reportNameSuffix != null && reportNameSuffix.length() > 0 ) { - reportFile = new File( reportsDirectory, reportEntryName + "-" + reportNameSuffix + fileExtension ); + reportFile = + new File( reportsDirectory, stripIllegalFilenameChars( reportEntryName + "-" + reportNameSuffix + + fileExtension ) ); } else { - reportFile = new File( reportsDirectory, reportEntryName + fileExtension ); + reportFile = new File( reportsDirectory, stripIllegalFilenameChars( reportEntryName + fileExtension ) ); } return reportFile; } 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 new file mode 100644 index 0000000000..5009da9fa9 --- /dev/null +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/FileReporterUtils.java @@ -0,0 +1,50 @@ +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 + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +/** + * Utils class for file-based reporters + * + * @author Andreas Gudian + */ +public class FileReporterUtils +{ + public static String stripIllegalFilenameChars( String original ) + { + String result = original; + String illegalChars = getOSSpecificIllegalChars(); + for ( int i = 0; i < illegalChars.length(); i++ ) + result = result.replace( illegalChars.charAt( i ), '_' ); + + return result; + } + + private static String getOSSpecificIllegalChars() + { + if ( System.getProperty( "os.name" ).toLowerCase().startsWith( "win" ) ) + { + return "\\/:*?\"<>|\0"; + } + else + { + return "/\0"; + } + } +} diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/PrettyPrintXMLWriter.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/PrettyPrintXMLWriter.java index ddb4ed9f6e..b0fea62284 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/PrettyPrintXMLWriter.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/PrettyPrintXMLWriter.java @@ -21,9 +21,8 @@ import java.io.PrintWriter; import java.util.LinkedList; -import org.apache.maven.shared.utils.xml.XMLWriter; -import sun.reflect.generics.reflectiveObjects.NotImplementedException; +import org.apache.maven.shared.utils.xml.XMLWriter; public class PrettyPrintXMLWriter implements XMLWriter @@ -69,12 +68,12 @@ private PrettyPrintXMLWriter( PrintWriter writer, String lineIndenter, String en public void setEncoding( String encoding ) { - throw new NotImplementedException(); + throw new RuntimeException( "Not Implemented" ); } public void setDocType( String docType ) { - throw new NotImplementedException(); + throw new RuntimeException( "Not Implemented" ); } private PrettyPrintXMLWriter( PrintWriter writer, String encoding, String doctype ) 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 734a5aef9e..562b123066 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,29 +1,29 @@ -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 - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -public enum ReportEntryType -{ - error, - failure, - skipped, - success - -} +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 + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +public enum ReportEntryType +{ + error, + failure, + skipped, + success + +} 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 c306b1de5f..a7e61b9907 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,304 +1,463 @@ -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 - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES 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.BufferedWriter; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.OutputStreamWriter; -import java.io.PrintWriter; -import java.io.UnsupportedEncodingException; -import java.util.Enumeration; -import java.util.Properties; -import java.util.StringTokenizer; -import org.apache.maven.shared.utils.io.IOUtil; -import org.apache.maven.shared.utils.xml.Xpp3Dom; -import org.apache.maven.shared.utils.xml.Xpp3DomWriter; -import org.apache.maven.surefire.report.ReportEntry; -import org.apache.maven.surefire.report.ReporterException; -import org.apache.maven.surefire.report.SafeThrowable; - -/** - * XML format reporter writing to TEST-reportName[-suffix].xml file like written and read - * by Ant's <junit> and - * <junitreport> tasks, - * then supported by many tools like CI servers. - *

- *

<?xml version="1.0" encoding="UTF-8"?>
- * <testsuite name="suite name" [group="group"] tests="0" failures="0" errors="0" skipped="0" time="0,###.###">
- *  <properties>
- *    <property name="name" value="value"/>
- *    [...]
- *  </properties>
- *  <testcase time="0,###.###" name="test name [classname="class name"] [group="group"]"/>
- *  <testcase time="0,###.###" name="test name [classname="class name"] [group="group"]">
- *    <error message="message" type="exception class name">stacktrace</error>
- *    <system-out>system out content (present only if not empty)</system-out>
- *    <system-err>system err content (present only if not empty)</system-err>
- *  </testcase>
- *  <testcase time="0,###.###" name="test name [classname="class name"] [group="group"]">
- *    <failure message="message" type="exception class name">stacktrace</failure>
- *    <system-out>system out content (present only if not empty)</system-out>
- *    <system-err>system err content (present only if not empty)</system-err>
- *  </testcase>
- *  <testcase time="0,###.###" name="test name [classname="class name"] [group="group"]">
- *    <skipped/>
- *  </testcase>
- *  [...]
- * - * @author Johnny R. Ruiz III - * @author Kristian Rosenvold - * @see Ant's format enhancement proposal - * (not yet implemented by Ant 1.8.2) - */ -public class StatelessXmlReporter -{ - private static final String LS = System.getProperty( "line.separator" ); - - private final File reportsDirectory; - - private final String reportNameSuffix; - - private final boolean trimStackTrace; - - public StatelessXmlReporter( File reportsDirectory, String reportNameSuffix, boolean trimStackTrace ) - { - this.reportsDirectory = reportsDirectory; - this.reportNameSuffix = reportNameSuffix; - this.trimStackTrace = trimStackTrace; - } - - public void testSetCompleted( WrappedReportEntry testSetReportEntry, TestSetStats testSetStats ) - throws ReporterException - { - - Xpp3Dom testSuite = createTestSuiteElement( testSetReportEntry, testSetStats, reportNameSuffix ); - - showProperties( testSuite ); - - testSuite.setAttribute( "tests", String.valueOf( testSetStats.getCompletedCount() ) ); - - testSuite.setAttribute( "errors", String.valueOf( testSetStats.getErrors() ) ); - - testSuite.setAttribute( "skipped", String.valueOf( testSetStats.getSkipped() ) ); - - testSuite.setAttribute( "failures", String.valueOf( testSetStats.getFailures() ) ); - - for ( WrappedReportEntry entry : testSetStats.getReportEntries() ) - { - if ( ReportEntryType.success.equals( entry.getReportEntryType() ) ) - { - testSuite.addChild( createTestElement( entry, reportNameSuffix ) ); - } - else - { - testSuite.addChild( getTestProblems( entry, trimStackTrace, reportNameSuffix ) ); - } - - } - - File reportFile = getReportFile( testSetReportEntry, reportsDirectory, reportNameSuffix ); - - File reportDir = reportFile.getParentFile(); - - //noinspection ResultOfMethodCallIgnored - reportDir.mkdirs(); - - PrintWriter writer = null; - - try - { - writer = new PrintWriter( - new BufferedWriter( new OutputStreamWriter( new FileOutputStream( reportFile ), "UTF-8" ) ) ); - - writer.write( "" + LS ); - - Xpp3DomWriter.write( new PrettyPrintXMLWriter( writer ), testSuite ); - } - catch ( UnsupportedEncodingException e ) - { - throw new ReporterException( "Unable to use UTF-8 encoding", e ); - } - catch ( FileNotFoundException e ) - { - throw new ReporterException( "Unable to create file: " + e.getMessage(), e ); - } - - finally - { - IOUtil.close( writer ); - } - } - - private File getReportFile( ReportEntry report, File reportsDirectory, String reportNameSuffix ) - { - File reportFile; - - if ( reportNameSuffix != null && reportNameSuffix.length() > 0 ) - { - reportFile = new File( reportsDirectory, "TEST-" + report.getName() + "-" + reportNameSuffix + ".xml" ); - } - else - { - reportFile = new File( reportsDirectory, "TEST-" + report.getName() + ".xml" ); - } - - return reportFile; - } - - private static Xpp3Dom createTestElement( WrappedReportEntry report, String reportNameSuffix ) - { - Xpp3Dom testCase = new Xpp3Dom( "testcase" ); - testCase.setAttribute( "name", report.getReportName() ); - if ( report.getGroup() != null ) - { - testCase.setAttribute( "group", report.getGroup() ); - } - if ( report.getSourceName() != null ) - { - if ( reportNameSuffix != null && reportNameSuffix.length() > 0 ) - { - testCase.setAttribute( "classname", report.getSourceName() + "(" + reportNameSuffix + ")" ); - } - else - { - testCase.setAttribute( "classname", report.getSourceName() ); - } - } - testCase.setAttribute( "time", report.elapsedTimeAsString() ); - return testCase; - } - - private static Xpp3Dom createTestSuiteElement( WrappedReportEntry report, TestSetStats testSetStats, - String reportNameSuffix1 ) - { - Xpp3Dom testCase = new Xpp3Dom( "testsuite" ); - - testCase.setAttribute( "name", report.getReportName( reportNameSuffix1 ) ); - - if ( report.getGroup() != null ) - { - testCase.setAttribute( "group", report.getGroup() ); - } - testCase.setAttribute( "time", testSetStats.getElapsedForTestSet() ); - return testCase; - } - - - private Xpp3Dom getTestProblems( WrappedReportEntry report, boolean trimStackTrace, String reportNameSuffix ) - { - - Xpp3Dom testCase = createTestElement( report, reportNameSuffix ); - - Xpp3Dom element = createElement( testCase, report.getReportEntryType().name() ); - - String stackTrace = report.getStackTrace( trimStackTrace ); - - if ( report.getMessage() != null && report.getMessage().length() > 0 ) - { - element.setAttribute( "message", report.getMessage() ); - } - - if ( report.getStackTraceWriter() != null ) - { - //noinspection ThrowableResultOfMethodCallIgnored - SafeThrowable t = report.getStackTraceWriter().getThrowable(); - if ( t != null ) - { - if ( t.getMessage() != null ) - { - element.setAttribute( "type", ( stackTrace.contains( ":" ) - ? stackTrace.substring( 0, stackTrace.indexOf( ":" ) ) - : stackTrace ) ); - } - else - { - element.setAttribute( "type", new StringTokenizer( stackTrace ).nextToken() ); - } - } - } - - if ( stackTrace != null ) - { - element.setValue( stackTrace ); - } - - addOutputStreamElement( report.getStdout(), "system-out", testCase ); - - addOutputStreamElement( report.getStdErr(), "system-err", testCase ); - - return testCase; - } - - private void addOutputStreamElement( String stdOut, String name, Xpp3Dom testCase ) - { - if ( stdOut != null && stdOut.trim().length() > 0 ) - { - createElement( testCase, name ).setValue( stdOut ); - } - } - - private Xpp3Dom createElement( Xpp3Dom element, String name ) - { - Xpp3Dom component = new Xpp3Dom( name ); - - element.addChild( component ); - - return component; - } - - /** - * Adds system properties to the XML report. - *

- * - * @param testSuite The test suite to report to - */ - private void showProperties( Xpp3Dom testSuite ) - { - Xpp3Dom properties = createElement( testSuite, "properties" ); - - Properties systemProperties = System.getProperties(); - - if ( systemProperties != null ) - { - Enumeration propertyKeys = systemProperties.propertyNames(); - - while ( propertyKeys.hasMoreElements() ) - { - String key = (String) propertyKeys.nextElement(); - - String value = systemProperties.getProperty( key ); - - if ( value == null ) - { - value = "null"; - } - - Xpp3Dom property = createElement( properties, "property" ); - - property.setAttribute( "name", key ); - - property.setAttribute( "value", value ); - - } - } - } -} +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 + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR 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.output.DeferredFileOutputStream; +import org.apache.maven.shared.utils.io.IOUtil; +import org.apache.maven.shared.utils.xml.XMLWriter; +import org.apache.maven.surefire.report.ReportEntry; +import org.apache.maven.surefire.report.ReporterException; +import org.apache.maven.surefire.report.SafeThrowable; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.FilterOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.util.Enumeration; +import java.util.Properties; +import java.util.StringTokenizer; + +import static org.apache.maven.plugin.surefire.report.FileReporterUtils.stripIllegalFilenameChars; + +/** + * XML format reporter writing to TEST-reportName[-suffix].xml file like written and read + * by Ant's <junit> and + * <junitreport> tasks, + * then supported by many tools like CI servers. + *

+ *

<?xml version="1.0" encoding="UTF-8"?>
+ * <testsuite name="suite name" [group="group"] tests="0" failures="0" errors="0" skipped="0" time="0,###.###">
+ *  <properties>
+ *    <property name="name" value="value"/>
+ *    [...]
+ *  </properties>
+ *  <testcase time="0,###.###" name="test name [classname="class name"] [group="group"]"/>
+ *  <testcase time="0,###.###" name="test name [classname="class name"] [group="group"]">
+ *    <error message="message" type="exception class name">stacktrace</error>
+ *    <system-out>system out content (present only if not empty)</system-out>
+ *    <system-err>system err content (present only if not empty)</system-err>
+ *  </testcase>
+ *  <testcase time="0,###.###" name="test name [classname="class name"] [group="group"]">
+ *    <failure message="message" type="exception class name">stacktrace</failure>
+ *    <system-out>system out content (present only if not empty)</system-out>
+ *    <system-err>system err content (present only if not empty)</system-err>
+ *  </testcase>
+ *  <testcase time="0,###.###" name="test name [classname="class name"] [group="group"]">
+ *    <skipped/>
+ *  </testcase>
+ *  [...]
+ * + * @author Kristian Rosenvold + * @see Ant's format enhancement proposal + * (not yet implemented by Ant 1.8.2) + */ +public class StatelessXmlReporter +{ + + private static final byte[] ampBytes = "&#".getBytes(); + + private final File reportsDirectory; + + private final String reportNameSuffix; + + private final boolean trimStackTrace; + + private final String encoding = "UTF-8"; + + public StatelessXmlReporter( File reportsDirectory, String reportNameSuffix, boolean trimStackTrace ) + { + this.reportsDirectory = reportsDirectory; + this.reportNameSuffix = reportNameSuffix; + this.trimStackTrace = trimStackTrace; + } + + public void testSetCompleted( WrappedReportEntry testSetReportEntry, TestSetStats testSetStats ) + throws ReporterException + { + + FileOutputStream outputStream = getOutputStream( testSetReportEntry ); + OutputStreamWriter fw = getWriter( outputStream ); + try + { + + org.apache.maven.shared.utils.xml.XMLWriter ppw = + new org.apache.maven.shared.utils.xml.PrettyPrintXMLWriter( fw ); + ppw.setEncoding( encoding ); + + createTestSuiteElement( ppw, testSetReportEntry, testSetStats, reportNameSuffix ); + + showProperties( ppw ); + + for ( WrappedReportEntry entry : testSetStats.getReportEntries() ) + { + if ( ReportEntryType.success.equals( entry.getReportEntryType() ) ) + { + startTestElement( ppw, entry, reportNameSuffix ); + ppw.endElement(); + } + else + { + getTestProblems( fw, ppw, entry, trimStackTrace, reportNameSuffix, outputStream ); + } + + } + ppw.endElement(); // TestSuite + + } + finally + { + IOUtil.close( fw ); + } + } + + private OutputStreamWriter getWriter( FileOutputStream fos ) + { + try + { + + return new OutputStreamWriter( fos, encoding ); + } + catch ( IOException e ) + { + throw new ReporterException( "When writing report", e ); + } + } + + private FileOutputStream getOutputStream( WrappedReportEntry testSetReportEntry ) + { + File reportFile = getReportFile( testSetReportEntry, reportsDirectory, reportNameSuffix ); + + File reportDir = reportFile.getParentFile(); + + //noinspection ResultOfMethodCallIgnored + reportDir.mkdirs(); + + try + { + + return new FileOutputStream( reportFile ); + } + catch ( Exception e ) + { + throw new ReporterException( "When writing report", e ); + } + } + + private File getReportFile( ReportEntry report, File reportsDirectory, String reportNameSuffix ) + { + File reportFile; + + if ( reportNameSuffix != null && reportNameSuffix.length() > 0 ) + { + reportFile = new File( reportsDirectory, stripIllegalFilenameChars( + "TEST-" + report.getName() + "-" + reportNameSuffix + ".xml" ) ); + } + else + { + reportFile = new File( reportsDirectory, stripIllegalFilenameChars( "TEST-" + report.getName() + ".xml" ) ); + } + + return reportFile; + } + + private static void startTestElement( XMLWriter ppw, WrappedReportEntry report, String reportNameSuffix ) + { + ppw.startElement( "testcase" ); + ppw.addAttribute( "name", report.getReportName() ); + if ( report.getGroup() != null ) + { + ppw.addAttribute( "group", report.getGroup() ); + } + if ( report.getSourceName() != null ) + { + if ( reportNameSuffix != null && reportNameSuffix.length() > 0 ) + { + ppw.addAttribute( "classname", report.getSourceName() + "(" + reportNameSuffix + ")" ); + } + else + { + ppw.addAttribute( "classname", report.getSourceName() ); + } + } + ppw.addAttribute( "time", report.elapsedTimeAsString() ); + } + + private static void createTestSuiteElement( XMLWriter ppw, WrappedReportEntry report, TestSetStats testSetStats, + String reportNameSuffix1 ) + { + ppw.startElement( "testsuite" ); + + ppw.addAttribute( "name", report.getReportName( reportNameSuffix1 ) ); + + if ( report.getGroup() != null ) + { + ppw.addAttribute( "group", report.getGroup() ); + } + + ppw.addAttribute( "time", testSetStats.getElapsedForTestSet() ); + + ppw.addAttribute( "tests", String.valueOf( testSetStats.getCompletedCount() ) ); + + ppw.addAttribute( "errors", String.valueOf( testSetStats.getErrors() ) ); + + ppw.addAttribute( "skipped", String.valueOf( testSetStats.getSkipped() ) ); + + ppw.addAttribute( "failures", String.valueOf( testSetStats.getFailures() ) ); + + } + + + private void getTestProblems( OutputStreamWriter outputStreamWriter, XMLWriter ppw, WrappedReportEntry report, + boolean trimStackTrace, String reportNameSuffix, FileOutputStream fw ) + { + + startTestElement( ppw, report, reportNameSuffix ); + + ppw.startElement( report.getReportEntryType().name() ); + + String stackTrace = report.getStackTrace( trimStackTrace ); + + if ( report.getMessage() != null && report.getMessage().length() > 0 ) + { + ppw.addAttribute( "message", extraEscape( report.getMessage(), true ) ); + } + + if ( report.getStackTraceWriter() != null ) + { + //noinspection ThrowableResultOfMethodCallIgnored + SafeThrowable t = report.getStackTraceWriter().getThrowable(); + if ( t != null ) + { + if ( t.getMessage() != null ) + { + ppw.addAttribute( "type", ( stackTrace.contains( ":" ) + ? stackTrace.substring( 0, stackTrace.indexOf( ":" ) ) + : stackTrace ) ); + } + else + { + ppw.addAttribute( "type", new StringTokenizer( stackTrace ).nextToken() ); + } + } + } + + if ( stackTrace != null ) + { + ppw.writeText( extraEscape( stackTrace, false ) ); + } + + ppw.endElement(); // entry type + + EncodingOutputStream eos = new EncodingOutputStream( fw ); + + addOutputStreamElement( outputStreamWriter, fw, eos, ppw, report.getStdout(), "system-out" ); + + addOutputStreamElement( outputStreamWriter, fw, eos, ppw, report.getStdErr(), "system-err" ); + + ppw.endElement(); // test element + } + + private void addOutputStreamElement( OutputStreamWriter outputStreamWriter, OutputStream fw, + EncodingOutputStream eos, XMLWriter xmlWriter, DeferredFileOutputStream stdOut, + String name ) + { + if ( stdOut != null && stdOut.getByteCount() > 0 ) + { + + xmlWriter.startElement( name ); + + try + { + xmlWriter.writeText( "" ); // Cheat sax to emit element + outputStreamWriter.flush(); + stdOut.close(); + eos.getUnderlying().write( "".getBytes() ); + eos.flush(); + } + catch ( IOException e ) + { + throw new ReporterException( "When writing xml report stdout/stderr", e ); + } + xmlWriter.endElement(); + } + } + + /** + * Adds system properties to the XML report. + *

+ * + * @param xmlWriter The test suite to report to + */ + private void showProperties( XMLWriter xmlWriter ) + { + xmlWriter.startElement( "properties" ); + + Properties systemProperties = System.getProperties(); + + if ( systemProperties != null ) + { + Enumeration propertyKeys = systemProperties.propertyNames(); + + while ( propertyKeys.hasMoreElements() ) + { + String key = (String) propertyKeys.nextElement(); + + String value = systemProperties.getProperty( key ); + + if ( value == null ) + { + value = "null"; + } + + xmlWriter.startElement( "property" ); + + xmlWriter.addAttribute( "name", key ); + + xmlWriter.addAttribute( "value", extraEscape( value, true ) ); + + xmlWriter.endElement(); + + } + } + xmlWriter.endElement(); + } + + /** + * Handle stuff that may pop up in java that is not legal in xml + * + * @param message The string + * @param attribute true if the escaped value is inside an attribute + * @return The escaped string + */ + private static String extraEscape( String message, boolean attribute ) + { + // Someday convert to xml 1.1 which handles everything but 0 inside string + if ( !containsEscapesIllegalnXml10( message ) ) + { + return message; + } + return escapeXml( message, attribute ); + } + + private static class EncodingOutputStream + extends FilterOutputStream + { + private int c1; + + private int c2; + + private static final byte[] cdataEscapeString = "]]>".getBytes(); + + public EncodingOutputStream( OutputStream out ) + { + super( out ); + } + + public OutputStream getUnderlying() + { + return out; + } + + private boolean isCdataEndBlock( int c ) + { + return c1 == ']' && c2 == ']' && c == '>'; + } + + @Override + public void write( int b ) + throws IOException + { + if ( isCdataEndBlock( b ) ) + { + out.write( cdataEscapeString ); + } + 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( ampBytes ); + out.write( b ); + out.write( ';' ); // & Will be encoded to amp inside xml encodingSHO + } + else + { + out.write( b ); //To change body of overridden methods use File | Settings | File Templates. + } + c1 = c2; + c2 = b; + } + } + + private static boolean containsEscapesIllegalnXml10( String message ) + { + int size = message.length(); + for ( int i = 0; i < size; i++ ) + { + if ( isIllegalEscape( message.charAt( i ) ) ) + { + return true; + } + + } + return false; + } + + private static boolean isIllegalEscape( char c ) + { + return c >= 0 && c < 32 && c != '\n' && c != '\r' && c != '\t'; + } + + private static boolean isIllegalEscape( int c ) + { + return c >= 0 && c < 32 && c != '\n' && c != '\r' && c != '\t'; + } + + 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 ); + } + } + return sb.toString(); + } + +} 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 aab6ad349e..50eaa380b8 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,252 +1,262 @@ -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 - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES 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.Collections; -import java.util.List; -import org.apache.maven.plugin.surefire.runorder.StatisticsReporter; -import org.apache.maven.surefire.report.ConsoleLogger; -import org.apache.maven.surefire.report.ConsoleOutputReceiver; -import org.apache.maven.surefire.report.ReportEntry; -import org.apache.maven.surefire.report.RunListener; -import org.apache.maven.surefire.report.RunStatistics; -import org.apache.maven.surefire.util.internal.ByteBuffer; - -/** - * Reports data for a single test set. - *

- * - * @author Kristian Rosenvold - */ -public class TestSetRunListener - implements RunListener, ConsoleOutputReceiver, ConsoleLogger -{ - private final RunStatistics globalStatistics; - - private final TestSetStats detailsForThis; - - static - { - System.out.println( "static = " + true ); - } - - private final List testStdOut = Collections.synchronizedList( new ArrayList() ); - - private final List testStdErr = Collections.synchronizedList( new ArrayList() ); - - private final TestcycleConsoleOutputReceiver consoleOutputReceiver; - - private final boolean briefOrPlainFormat; - - private final StatelessXmlReporter simpleXMLReporter; - - private final ConsoleReporter consoleReporter; - - private final FileReporter fileReporter; - - private final StatisticsReporter statisticsReporter; - - public TestSetRunListener( ConsoleReporter consoleReporter, FileReporter fileReporter, - StatelessXmlReporter simpleXMLReporter, - TestcycleConsoleOutputReceiver consoleOutputReceiver, - StatisticsReporter statisticsReporter, RunStatistics globalStats, boolean trimStackTrace, - boolean isPlainFormat, boolean briefOrPlainFormat ) - { - this.consoleReporter = consoleReporter; - this.fileReporter = fileReporter; - this.statisticsReporter = statisticsReporter; - this.simpleXMLReporter = simpleXMLReporter; - this.consoleOutputReceiver = consoleOutputReceiver; - this.briefOrPlainFormat = briefOrPlainFormat; - this.detailsForThis = new TestSetStats( trimStackTrace, isPlainFormat ); - this.globalStatistics = globalStats; - } - - public void info( String message ) - { - if ( consoleReporter != null ) - { - consoleReporter.writeMessage( message ); - } - } - - public void writeTestOutput( byte[] buf, int off, int len, boolean stdout ) - { - ByteBuffer byteBuffer = new ByteBuffer( buf, off, len ); - if ( stdout ) - { - testStdOut.add( byteBuffer ); - } - else - { - testStdErr.add( byteBuffer ); - } - consoleOutputReceiver.writeTestOutput( buf, off, len, stdout ); - } - - public void testSetStarting( ReportEntry report ) - { - detailsForThis.testSetStart(); - if ( consoleReporter != null ) - { - consoleReporter.testSetStarting( report ); - } - consoleOutputReceiver.testSetStarting( report ); - } - - public void clearCapture() - { - testStdErr.clear(); - testStdOut.clear(); - } - - public void testSetCompleted( ReportEntry report ) - { - WrappedReportEntry wrap = wrapTestSet( report, null ); - List testResults = briefOrPlainFormat ? detailsForThis.getTestResults() : null; - if ( consoleReporter != null ) - { - consoleReporter.testSetCompleted( wrap, detailsForThis, testResults ); - } - consoleOutputReceiver.testSetCompleted( wrap ); - if ( fileReporter != null ) - { - fileReporter.testSetCompleted( wrap, detailsForThis, testResults ); - } - if ( simpleXMLReporter != null ) - { - simpleXMLReporter.testSetCompleted( wrap, detailsForThis ); - } - if ( statisticsReporter != null ) - { - statisticsReporter.testSetCompleted(); - } - if ( consoleReporter != null ) - { - consoleReporter.reset(); - } - - globalStatistics.add( detailsForThis ); - detailsForThis.reset(); - - } - - // ---------------------------------------------------------------------- - // Test - // ---------------------------------------------------------------------- - - public void testStarting( ReportEntry report ) - { - detailsForThis.testStart(); - - } - - public void testSucceeded( ReportEntry reportEntry ) - { - WrappedReportEntry wrapped = wrap( reportEntry, ReportEntryType.success ); - detailsForThis.testSucceeded( wrapped ); - if ( statisticsReporter != null ) - { - statisticsReporter.testSucceeded( reportEntry ); - } - clearCapture(); - } - - public void testError( ReportEntry reportEntry ) - { - WrappedReportEntry wrapped = wrap( reportEntry, ReportEntryType.error ); - detailsForThis.testError( wrapped ); - if ( statisticsReporter != null ) - { - statisticsReporter.testError( reportEntry ); - } - globalStatistics.addErrorSource( reportEntry.getName(), reportEntry.getStackTraceWriter() ); - clearCapture(); - } - - public void testFailed( ReportEntry reportEntry ) - { - WrappedReportEntry wrapped = wrap( reportEntry, ReportEntryType.failure ); - detailsForThis.testFailure( wrapped ); - if ( statisticsReporter != null ) - { - statisticsReporter.testFailed( reportEntry ); - } - globalStatistics.addFailureSource( reportEntry.getName(), reportEntry.getStackTraceWriter() ); - clearCapture(); - } - - // ---------------------------------------------------------------------- - // Counters - // ---------------------------------------------------------------------- - - public void testSkipped( ReportEntry reportEntry ) - { - - WrappedReportEntry wrapped = wrap( reportEntry, ReportEntryType.skipped ); - detailsForThis.testSkipped( wrapped ); - if ( statisticsReporter != null ) - { - statisticsReporter.testSkipped( reportEntry ); - } - clearCapture(); - } - - public void testAssumptionFailure( ReportEntry report ) - { - testSkipped( report ); - } - - public String getAsString( List byteBufferList ) - { - StringBuilder stringBuffer = new StringBuilder(); - // To avoid getting a java.util.ConcurrentModificationException while iterating (see SUREFIRE-879) we need to - // iterate over a copy or the elements array. Since the passed in byteBufferList is always wrapped with - // Collections.synchronizedList( ) we are guaranteed toArray() is going to be atomic, so we are safe. - for ( Object byteBuffer : byteBufferList.toArray() ) - { - stringBuffer.append( byteBuffer.toString() ); - } - return stringBuffer.toString(); - } - - private WrappedReportEntry wrap( ReportEntry other, ReportEntryType reportEntryType ) - { - return new WrappedReportEntry( other, reportEntryType, other.getElapsed() != null - ? other.getElapsed() - : detailsForThis.getElapsedSinceLastStart(), getAsString( testStdOut ), getAsString( testStdErr ) ); - } - - private WrappedReportEntry wrapTestSet( ReportEntry other, ReportEntryType reportEntryType ) - { - return new WrappedReportEntry( other, reportEntryType, other.getElapsed() != null - ? other.getElapsed() - : detailsForThis.getElapsedSinceTestSetStart(), getAsString( testStdOut ), getAsString( testStdErr ) ); - } - - public void close() - { - if ( consoleOutputReceiver != null ) - { - consoleOutputReceiver.close(); - } - } -} +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 + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR 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.output.DeferredFileOutputStream; +import org.apache.maven.plugin.surefire.runorder.StatisticsReporter; +import org.apache.maven.surefire.report.ConsoleLogger; +import org.apache.maven.surefire.report.ConsoleOutputReceiver; +import org.apache.maven.surefire.report.ReportEntry; +import org.apache.maven.surefire.report.RunListener; +import org.apache.maven.surefire.report.RunStatistics; +import org.apache.maven.surefire.util.NestedRuntimeException; + +import java.io.File; +import java.io.IOException; +import java.util.List; + +/** + * Reports data for a single test set. + *

+ * + * @author Kristian Rosenvold + */ +public class TestSetRunListener + implements RunListener, ConsoleOutputReceiver, ConsoleLogger +{ + private final RunStatistics globalStatistics; + + private final TestSetStats detailsForThis; + + private DeferredFileOutputStream testStdOut = initDeferred( "stdout" ); + + private DeferredFileOutputStream testStdErr = initDeferred( "stderr" ); + + private DeferredFileOutputStream initDeferred( String channel ) + { + return new DeferredFileOutputStream( 1000000, channel , "deferred", null ); + } + + + private final TestcycleConsoleOutputReceiver consoleOutputReceiver; + + private final boolean briefOrPlainFormat; + + private final StatelessXmlReporter simpleXMLReporter; + + private final ConsoleReporter consoleReporter; + + private final FileReporter fileReporter; + + private final StatisticsReporter statisticsReporter; + + public TestSetRunListener( ConsoleReporter consoleReporter, FileReporter fileReporter, + StatelessXmlReporter simpleXMLReporter, + TestcycleConsoleOutputReceiver consoleOutputReceiver, + StatisticsReporter statisticsReporter, RunStatistics globalStats, boolean trimStackTrace, + boolean isPlainFormat, boolean briefOrPlainFormat ) + { + this.consoleReporter = consoleReporter; + this.fileReporter = fileReporter; + this.statisticsReporter = statisticsReporter; + this.simpleXMLReporter = simpleXMLReporter; + this.consoleOutputReceiver = consoleOutputReceiver; + this.briefOrPlainFormat = briefOrPlainFormat; + this.detailsForThis = new TestSetStats( trimStackTrace, isPlainFormat ); + this.globalStatistics = globalStats; + } + + public void info( String message ) + { + if ( consoleReporter != null ) + { + consoleReporter.writeMessage( message ); + } + } + + public void writeTestOutput( byte[] buf, int off, int len, boolean stdout ) + { + try + { + if ( stdout ) + { + testStdOut.write( buf, off, len ); + } + else + { + testStdErr.write( buf, off, len ); + } + } + catch ( IOException e ) + { + throw new NestedRuntimeException( e ); + } + consoleOutputReceiver.writeTestOutput( buf, off, len, stdout ); + } + + public void testSetStarting( ReportEntry report ) + { + detailsForThis.testSetStart(); + if ( consoleReporter != null ) + { + consoleReporter.testSetStarting( report ); + } + consoleOutputReceiver.testSetStarting( report ); + } + + public void clearCapture() + { + testStdOut = initDeferred( "stdout" ); + testStdErr = initDeferred( "stderr" ); + } + + public void testSetCompleted( ReportEntry report ) + { + WrappedReportEntry wrap = wrapTestSet( report ); + List testResults = briefOrPlainFormat ? detailsForThis.getTestResults() : null; + if ( consoleReporter != null ) + { + consoleReporter.testSetCompleted( wrap, detailsForThis, testResults ); + } + consoleOutputReceiver.testSetCompleted( wrap ); + if ( fileReporter != null ) + { + fileReporter.testSetCompleted( wrap, detailsForThis, testResults ); + } + if ( simpleXMLReporter != null ) + { + simpleXMLReporter.testSetCompleted( wrap, detailsForThis ); + } + if ( statisticsReporter != null ) + { + statisticsReporter.testSetCompleted(); + } + if ( consoleReporter != null ) + { + consoleReporter.reset(); + } + + globalStatistics.add( detailsForThis ); + detailsForThis.reset(); + + } + + // ---------------------------------------------------------------------- + // Test + // ---------------------------------------------------------------------- + + public void testStarting( ReportEntry report ) + { + detailsForThis.testStart(); + + } + + public void testSucceeded( ReportEntry reportEntry ) + { + WrappedReportEntry wrapped = wrap( reportEntry, ReportEntryType.success ); + detailsForThis.testSucceeded( wrapped ); + if ( statisticsReporter != null ) + { + statisticsReporter.testSucceeded( reportEntry ); + } + clearCapture(); + } + + public void testError( ReportEntry reportEntry ) + { + WrappedReportEntry wrapped = wrap( reportEntry, ReportEntryType.error ); + detailsForThis.testError( wrapped ); + if ( statisticsReporter != null ) + { + statisticsReporter.testError( reportEntry ); + } + globalStatistics.addErrorSource( reportEntry.getStackTraceWriter() ); + clearCapture(); + } + + public void testFailed( ReportEntry reportEntry ) + { + WrappedReportEntry wrapped = wrap( reportEntry, ReportEntryType.failure ); + detailsForThis.testFailure( wrapped ); + if ( statisticsReporter != null ) + { + statisticsReporter.testFailed( reportEntry ); + } + globalStatistics.addFailureSource( reportEntry.getStackTraceWriter() ); + clearCapture(); + } + + // ---------------------------------------------------------------------- + // Counters + // ---------------------------------------------------------------------- + + public void testSkipped( ReportEntry reportEntry ) + { + WrappedReportEntry wrapped = wrap( reportEntry, ReportEntryType.skipped ); + detailsForThis.testSkipped( wrapped ); + if ( statisticsReporter != null ) + { + statisticsReporter.testSkipped( reportEntry ); + } + clearCapture(); + } + + public void testAssumptionFailure( ReportEntry report ) + { + testSkipped( report ); + } + + private WrappedReportEntry wrap( ReportEntry other, ReportEntryType reportEntryType ) + { + final int estimatedElapsed; + if ( reportEntryType != ReportEntryType.skipped ) + { + if ( other.getElapsed() != null ) + { + estimatedElapsed = other.getElapsed(); + } + else + { + estimatedElapsed = detailsForThis.getElapsedSinceLastStart(); + } + } + else + { + estimatedElapsed = 0; + } + + return new WrappedReportEntry( other, reportEntryType, estimatedElapsed, testStdOut, testStdErr ); + } + + private WrappedReportEntry wrapTestSet( ReportEntry other ) + { + return new WrappedReportEntry( other, null, other.getElapsed() != null + ? other.getElapsed() + : detailsForThis.getElapsedSinceTestSetStart(), testStdOut, testStdErr ); + } + + public void close() + { + if ( consoleOutputReceiver != null ) + { + consoleOutputReceiver.close(); + } + } +} 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 fd5fb27231..ef253bf64a 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 @@ -188,6 +188,9 @@ public String getTestSetSummary( WrappedReportEntry reportEntry ) { buf.append( " <<< FAILURE!" ); } + + buf.append( " - in " ); + buf.append( reportEntry.getNameWithGroup() ); buf.append( "\n" ); 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 09710e33a0..d2c59ff4e7 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,38 +1,38 @@ -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 - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR 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.report.ConsoleOutputReceiver; -import org.apache.maven.surefire.report.ReportEntry; - -/** - * @author Kristian Rosenvold - */ -public interface TestcycleConsoleOutputReceiver - extends ConsoleOutputReceiver -{ - - void testSetStarting( ReportEntry reportEntry ); - - void testSetCompleted( ReportEntry report ); - - void close(); - -} +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 + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR 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.report.ConsoleOutputReceiver; +import org.apache.maven.surefire.report.ReportEntry; + +/** + * @author Kristian Rosenvold + */ +public interface TestcycleConsoleOutputReceiver + extends ConsoleOutputReceiver +{ + + void testSetStarting( ReportEntry reportEntry ); + + void testSetCompleted( ReportEntry report ); + + void close(); + +} 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 c77867c94e..cd7a9560fd 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 @@ -19,11 +19,13 @@ * under the License. */ -import java.text.NumberFormat; -import java.util.Locale; +import org.apache.commons.io.output.DeferredFileOutputStream; import org.apache.maven.surefire.report.ReportEntry; import org.apache.maven.surefire.report.StackTraceWriter; +import java.text.NumberFormat; +import java.util.Locale; + /** * @author Kristian Rosenvold */ @@ -36,9 +38,9 @@ public class WrappedReportEntry private final Integer elapsed; - private final String stdout; + private final DeferredFileOutputStream stdout; - private final String stdErr; + private final DeferredFileOutputStream stdErr; private final NumberFormat numberFormat = NumberFormat.getInstance( Locale.ENGLISH ); @@ -47,7 +49,7 @@ public class WrappedReportEntry static final String NL = System.getProperty( "line.separator" ); public WrappedReportEntry( ReportEntry original, ReportEntryType reportEntryType, Integer estimatedElapsed, - String stdout, String stdErr ) + DeferredFileOutputStream stdout, DeferredFileOutputStream stdErr ) { this.original = original; this.reportEntryType = reportEntryType; @@ -58,21 +60,20 @@ public WrappedReportEntry( ReportEntry original, ReportEntryType reportEntryType public Integer getElapsed() { - return original.getElapsed() != null ? original.getElapsed() : elapsed; + return elapsed; } - public ReportEntryType getReportEntryType() { return reportEntryType; } - public String getStdout() + public DeferredFileOutputStream getStdout() { return stdout; } - public String getStdErr() + public DeferredFileOutputStream getStdErr() { return stdErr; } @@ -172,4 +173,9 @@ public boolean isSucceeded() { return ReportEntryType.success == getReportEntryType(); } + + public String getNameWithGroup() + { + return original.getNameWithGroup(); + } } 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 new file mode 100644 index 0000000000..636662fbf2 --- /dev/null +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/util/DependencyScanner.java @@ -0,0 +1,185 @@ +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 + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES 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.apache.maven.plugin.surefire.util.ScannerUtil.convertJarFileResourceToJavaClassName; +import static org.apache.maven.plugin.surefire.util.ScannerUtil.convertSlashToSystemFileSeparator; +import static org.apache.maven.plugin.surefire.util.ScannerUtil.processIncludesExcludes; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.List; +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.utils.io.MatchPatterns; +import org.apache.maven.surefire.util.DefaultScanResult; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +/** + * Scans dependencies looking for tests. + * + * @author Aslak Knutsen + */ +public class DependencyScanner +{ + + private final List dependenciesToScan; + + protected final List includes; + + protected final @Nonnull List excludes; + + protected final List specificTests; + + public DependencyScanner( List dependenciesToScan, List includes, @Nonnull List excludes, List specificTests ) + { + this.dependenciesToScan = dependenciesToScan; + this.includes = includes; + this.excludes = excludes; + this.specificTests = specificTests; + } + + public DefaultScanResult scan() + throws MojoExecutionException + { + Matcher matcher = new Matcher( includes, excludes, specificTests ); + List found = new ArrayList(); + for ( File artifact : dependenciesToScan ) + { + try + { + found.addAll( scanArtifact( artifact, matcher ) ); + } + catch ( IOException e ) + { + throw new MojoExecutionException( "Could not scan dependency " + artifact.toString(), e ); + } + } + return new DefaultScanResult( found ); + } + + private List scanArtifact( File artifact, Matcher matcher ) + throws IOException + { + List found = new ArrayList(); + + if ( artifact != null ) + { + if ( artifact.isFile() ) + { + JarFile jar = null; + try + { + jar = new JarFile( artifact ); + Enumeration entries = jar.entries(); + while ( entries.hasMoreElements() ) + { + JarEntry entry = entries.nextElement(); + if ( matcher.shouldInclude( entry.getName() ) ) + { + found.add( convertJarFileResourceToJavaClassName( entry.getName() ) ); + } + } + } + finally + { + if ( jar != null ) + { + jar.close(); + } + } + } + } + return found; + } + + public static List filter( List artifacts, List groupArtifactIds ) + { + List matches = new ArrayList(); + if ( groupArtifactIds == null || artifacts == null ) + { + return matches; + } + for ( Artifact artifact : artifacts ) + { + for ( String groups : groupArtifactIds ) + { + String[] groupArtifact = groups.split( ":" ); + if ( groupArtifact.length != 2 ) + { + throw new IllegalArgumentException( + "dependencyToScan argument should be in format 'groupid:artifactid': " + + groups ); + } + if ( artifact.getGroupId().matches( groupArtifact[0] ) + && artifact.getArtifactId().matches( groupArtifact[1] ) ) + { + matches.add( artifact.getFile() ); + } + } + } + return matches; + } + + private class Matcher + { + + private MatchPatterns includes; + + private MatchPatterns excludes; + + private SpecificFileFilter specificTestFilter; + + public Matcher( @Nullable List includes, @Nonnull List excludes, @Nullable List specificTests ) + { + String[] specific = specificTests == null ? new String[0] : processIncludesExcludes( specificTests ); + specificTestFilter = new SpecificFileFilter( specific ); + + if ( includes != null && includes.size() > 0 ) + { + this.includes = MatchPatterns.from( processIncludesExcludes( includes ) ); + } + else + { + this.includes = MatchPatterns.from( "**" ); + } + this.excludes = MatchPatterns.from( processIncludesExcludes( excludes ) ); + } + + public boolean shouldInclude( String name ) + { + if ( !name.endsWith( ".class" ) ) + { + return false; + } + name = convertSlashToSystemFileSeparator( name ); + boolean isIncluded = includes.matches( name, false ); + boolean isExcluded = excludes.matches( name, false ); + + return isIncluded && !isExcluded && specificTestFilter.accept( name ); + } + } +} 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 73fcaf1150..e0cc18dcad 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,129 +1,90 @@ -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 - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES 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.util.ArrayList; -import java.util.Collections; -import java.util.List; -import org.apache.commons.lang3.StringUtils; -import org.apache.maven.surefire.util.DefaultScanResult; - -/** - * Scans directories looking for tests. - * - * @author Karl M. Davis - * @author Kristian Rosenvold - */ -public class DirectoryScanner -{ - - private static final String FS = System.getProperty( "file.separator" ); - - private static final String JAVA_SOURCE_FILE_EXTENSION = ".java"; - - private static final String JAVA_CLASS_FILE_EXTENSION = ".class"; - - private final File basedir; - - private final List includes; - - private final List excludes; - - private final List specificTests; - - public DirectoryScanner( File basedir, List includes, List excludes, List specificTests ) - { - this.basedir = basedir; - this.includes = includes; - this.excludes = excludes; - this.specificTests = specificTests; - } - - public DefaultScanResult scan() - { - String[] specific = specificTests == null ? new String[0] : processIncludesExcludes( specificTests ); - SpecificFileFilter specificTestFilter = new SpecificFileFilter( specific ); - - List result = new ArrayList(); - if ( basedir.exists() ) - { - org.apache.maven.shared.utils.io.DirectoryScanner scanner = - new org.apache.maven.shared.utils.io.DirectoryScanner(); - - scanner.setBasedir( basedir ); - - if ( includes != null ) - { - scanner.setIncludes( processIncludesExcludes( includes ) ); - } - - if ( excludes != null ) - { - scanner.setExcludes( processIncludesExcludes( excludes ) ); - } - - scanner.scan(); - for ( String test : scanner.getIncludedFiles() ) - { - if ( specificTestFilter.accept( stripBaseDir( basedir.getAbsolutePath(), test ) ) ) - { - result.add( convertToJavaClassName( test ) ); - } - } - } - return new DefaultScanResult( result ); - } - - private String convertToJavaClassName( String test ) - { - return StringUtils.removeEnd( test, ".class" ).replace( FS, "." ); - } - - private String stripBaseDir( String basedir, String test ) - { - return StringUtils.removeStart( test, basedir ); - } - - private static String[] processIncludesExcludes( List list ) - { - List newList = new ArrayList(); - for ( Object aList : list ) - { - String include = (String) aList; - 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 = StringUtils.removeEnd( inc, JAVA_SOURCE_FILE_EXTENSION ) + JAVA_CLASS_FILE_EXTENSION; - } - incs[i] = inc; - - } - return incs; - } -} +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 + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES 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.apache.maven.plugin.surefire.util.ScannerUtil.convertSlashToSystemFileSeparator; +import static org.apache.maven.plugin.surefire.util.ScannerUtil.convertToJavaClassName; +import static org.apache.maven.plugin.surefire.util.ScannerUtil.processIncludesExcludes; +import static org.apache.maven.plugin.surefire.util.ScannerUtil.stripBaseDir; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +import org.apache.maven.surefire.util.DefaultScanResult; + +/** + * Scans directories looking for tests. + * + * @author Karl M. Davis + * @author Kristian Rosenvold + */ +public class DirectoryScanner +{ + private final File basedir; + + private final List includes; + + private final List excludes; + + private final List specificTests; + + public DirectoryScanner( File basedir, List includes, List excludes, List specificTests ) + { + this.basedir = basedir; + this.includes = includes; + this.excludes = excludes; + this.specificTests = specificTests; + } + + public DefaultScanResult scan() + { + String[] specific = specificTests == null ? new String[0] : processIncludesExcludes( specificTests ); + SpecificFileFilter specificTestFilter = new SpecificFileFilter( specific ); + + List result = new ArrayList(); + if ( basedir.exists() ) + { + org.apache.maven.shared.utils.io.DirectoryScanner scanner = + new org.apache.maven.shared.utils.io.DirectoryScanner(); + + scanner.setBasedir( basedir ); + + if ( includes != null ) + { + scanner.setIncludes( processIncludesExcludes( includes ) ); + } + + if ( excludes != null ) + { + scanner.setExcludes( processIncludesExcludes( excludes ) ); + } + + scanner.scan(); + for ( String test : scanner.getIncludedFiles() ) + { + if ( specificTestFilter.accept( convertSlashToSystemFileSeparator( stripBaseDir( basedir.getAbsolutePath(), test ) ) ) ) + { + result.add( convertToJavaClassName( test ) ); + } + } + } + return new DefaultScanResult( result ); + } +} \ No newline at end of file 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 31dde5d5ea..d61ee20506 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 @@ -19,6 +19,10 @@ * under the License. */ + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + /** * Relocates class names when running with relocated provider * @@ -26,12 +30,12 @@ */ public class Relocator { - private final String relocation; + private final @Nullable String relocation; private static final String relocationBase = "org.apache.maven.surefire."; - public Relocator( String relocation ) + public Relocator( @Nullable String relocation ) { this.relocation = relocation; } @@ -41,12 +45,12 @@ public Relocator() relocation = "shadefire"; } - private String getRelocation() + private @Nullable String getRelocation() { return relocation; } - public String relocate( String className ) + public @Nonnull String relocate( @Nonnull String className ) { if ( relocation == null ) { 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 new file mode 100644 index 0000000000..124f656d46 --- /dev/null +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/util/ScannerUtil.java @@ -0,0 +1,86 @@ +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 + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES 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.Collections; +import java.util.List; + +import org.apache.commons.lang3.StringUtils; + +import javax.annotation.Nonnull; + +final class ScannerUtil { + + private ScannerUtil() {} + + private static final String FS = System.getProperty( "file.separator" ); + + private static final String JAVA_SOURCE_FILE_EXTENSION = ".java"; + + private static final String JAVA_CLASS_FILE_EXTENSION = ".class"; + + private static final boolean IS_NON_UNIX_FS = (!FS.equals( "/" )); + + public static @Nonnull String convertToJavaClassName( @Nonnull String test ) + { + return StringUtils.removeEnd( test, ".class" ).replace( FS, "." ); + } + + public static @Nonnull String convertJarFileResourceToJavaClassName( @Nonnull String test ) + { + return StringUtils.removeEnd( test, ".class" ).replace( "/", "." ); + } + + public static @Nonnull String convertSlashToSystemFileSeparator( @Nonnull String path ) + { + return ( IS_NON_UNIX_FS ? path.replace( "/", FS ) : path ); + } + + public static @Nonnull String stripBaseDir( String basedir, String test ) + { + return StringUtils.removeStart( test, basedir ); + } + + public static @Nonnull String[] processIncludesExcludes( @Nonnull List list ) + { + List newList = new ArrayList(); + for ( Object aList : list ) + { + String include = (String) aList; + 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 = StringUtils.removeEnd( inc, JAVA_SOURCE_FILE_EXTENSION ) + JAVA_CLASS_FILE_EXTENSION; + } + incs[i] = convertSlashToSystemFileSeparator( inc ); + + } + return incs; + } +} 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 0309ed82b8..db2d4770d3 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,67 +1,67 @@ -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 - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES 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.Collections; -import java.util.HashSet; -import java.util.Set; -import org.apache.maven.shared.utils.io.SelectorUtils; - -public class SpecificFileFilter -{ - - private static final char FS = System.getProperty( "file.separator" ).charAt( 0 ); - - private Set names; - - public SpecificFileFilter( String[] classNames ) - { - if ( classNames != null && classNames.length > 0 ) - { - this.names = new HashSet(); - boolean isBackslashFs = '\\' == FS; - for ( String name : classNames ) - { - names.add( isBackslashFs ? name.replace( '/', FS ) : name ); - } - Collections.addAll( names, classNames ); - } - } - - public boolean accept( String className ) - { - // If the tests enumeration is empty, allow anything. - 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, className, true ) ) - { - return true; - } - } - return false; - } - return true; - } - -} +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 + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES 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.HashSet; +import java.util.Set; + +import javax.annotation.Nullable; + +import org.apache.maven.shared.utils.io.SelectorUtils; + +import static org.apache.maven.plugin.surefire.util.ScannerUtil.convertSlashToSystemFileSeparator; + +public class SpecificFileFilter +{ + + private Set names; + + public SpecificFileFilter( @Nullable String[] classNames ) + { + if ( classNames != null && classNames.length > 0 ) + { + this.names = new HashSet(); + for ( String name : classNames ) + { + names.add( convertSlashToSystemFileSeparator( name ) ); + } + } + } + + public boolean accept( @Nullable String resourceName ) + { + // If the tests enumeration is empty, allow anything. + 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 ) ) + { + return true; + } + } + return false; + } + return true; + } + +} diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/util/internal/FunkyTwoThreadBlockingQueue.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/util/internal/FunkyTwoThreadBlockingQueue.java deleted file mode 100644 index 2d619f64fa..0000000000 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/util/internal/FunkyTwoThreadBlockingQueue.java +++ /dev/null @@ -1,102 +0,0 @@ -package org.apache.maven.plugin.surefire.util.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. - */ - -/** - * A producer/consumer queue that is optimized for *one* producer thread - * and *one* consumer thread, and solely optimized for efficient inserts - * by the producer, minimizing producer locking for hand-off to - * a second consumer. - *

- * TwoThreadBlockingQueue insert 5000000 elements in = 52 - * FunkyTwoThreadBlockingQueue insert 5000000 elements in = 42 - * TwoThreadBlockingQueue produced and taken 5000000 elements in = 104 - * LinkedBlockingQueue insert 5000000 elements in = 1815 - * LinkedBlockingDeque insert 5000000 elements in = 113 - * ArrayList insert 5000000 elements in = 18 - * LinkedList insert 5000000 elements in = 334 - *

- * Todo: Determine if this design actually works ;) - * - * @author Kristian Rosenvold - */ -public class FunkyTwoThreadBlockingQueue - implements BlockingQueue -{ - final int chunkSize = 100; - - private Chunk takeChunk = new Chunk(); - - private int takePos = 0; - - private Chunk insertChunk = takeChunk; - - private int insertPos = 0; - - private volatile boolean memoryModelGuard; - - - public void put( String object ) - { - insertChunk.elements[insertPos] = object; - if ( ++insertPos == chunkSize ) - { - Chunk newChunk = new Chunk(); - insertChunk.next = newChunk; - insertChunk = newChunk; - insertPos = 0; - } - memoryModelGuard = true; - } - - public void add( String object ) - { - put( object ); - } - - - public String take() - throws InterruptedException - { - if ( takePos >= chunkSize ) - { - takeChunk = takeChunk.next; - takePos = 0; - } - - boolean fud = memoryModelGuard; - String next = takeChunk.elements[takePos]; - while ( next == null ) - { - Thread.sleep( 1 ); - fud = memoryModelGuard; - next = takeChunk.elements[takePos]; - } - takePos++; - return next; - } - - final class Chunk - { - final String[] elements = new String[chunkSize]; - - volatile Chunk next; - } -} diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/util/internal/TwoThreadBlockingQueue.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/util/internal/TwoThreadBlockingQueue.java deleted file mode 100644 index 0fa7a75541..0000000000 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/util/internal/TwoThreadBlockingQueue.java +++ /dev/null @@ -1,104 +0,0 @@ -package org.apache.maven.plugin.surefire.util.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. - */ - -/** - * A producer/consumer queue that is optimized for *one* producer thread - * and *one* consumer thread, and solely optimized for efficient inserts - * by the producer, minimizing producer locking for hand-off to - * a second consumer. - *

- * The producer can actually come in on different threads - * (because lastInserted is volatile), but can/will lose - * items if they arrive concurrently. Take only supports a single - * client. - *

- * This runs like crazy, but is not the most garbage friendly around. - *

- * TwoThreadBlockingQueue insert 5000000 elements in = 52ms - * LinkedBlockingQueue insert 5000000 elements in = 179ms - * LikedBlockingDeque insert 5000000 elements in = 114ms - * ArrayList insert 5000000 elements in = 18ms (sized at correct size from start) - * - * @author Kristian Rosenvold - */ -public class TwoThreadBlockingQueue - implements BlockingQueue -{ - private volatile Element lastInserted; - - private volatile Element lastTaken; - - private volatile Element first; - - public static final String poison = "poison"; - - public void add( String object ) - { - Element next = new Element( object ); - if ( lastInserted == null ) - { - first = lastInserted = next; - } - else - { - lastInserted.next = next; - lastInserted = next; - } - } - - public String take() - throws InterruptedException - { - if ( lastTaken == null ) - { - while ( first == null ) - { - Thread.sleep( 1 ); - } - lastTaken = first; - first = null; - } - else - { - Element next = lastTaken.next; - while ( next == null ) - { - Thread.sleep( 1 ); - next = lastTaken.next; - } - lastTaken = next; - } - return lastTaken.object; - } - - private static class Element - { - private final String object; - - private volatile Element next; - - Element( String object ) - { - this.object = object; - } - } - -} diff --git a/maven-surefire-report-plugin/src/main/java/org/apache/maven/plugins/surefire/report/ReportTestCase.java b/maven-surefire-common/src/main/java/org/apache/maven/plugins/surefire/report/ReportTestCase.java similarity index 100% rename from maven-surefire-report-plugin/src/main/java/org/apache/maven/plugins/surefire/report/ReportTestCase.java rename to maven-surefire-common/src/main/java/org/apache/maven/plugins/surefire/report/ReportTestCase.java diff --git a/maven-surefire-report-plugin/src/main/java/org/apache/maven/plugins/surefire/report/ReportTestSuite.java b/maven-surefire-common/src/main/java/org/apache/maven/plugins/surefire/report/ReportTestSuite.java similarity index 100% rename from maven-surefire-report-plugin/src/main/java/org/apache/maven/plugins/surefire/report/ReportTestSuite.java rename to maven-surefire-common/src/main/java/org/apache/maven/plugins/surefire/report/ReportTestSuite.java diff --git a/maven-surefire-report-plugin/src/main/java/org/apache/maven/plugins/surefire/report/SurefireReportParser.java b/maven-surefire-common/src/main/java/org/apache/maven/plugins/surefire/report/SurefireReportParser.java similarity index 99% rename from maven-surefire-report-plugin/src/main/java/org/apache/maven/plugins/surefire/report/SurefireReportParser.java rename to maven-surefire-common/src/main/java/org/apache/maven/plugins/surefire/report/SurefireReportParser.java index 15621549f9..feba2458b5 100644 --- a/maven-surefire-report-plugin/src/main/java/org/apache/maven/plugins/surefire/report/SurefireReportParser.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugins/surefire/report/SurefireReportParser.java @@ -44,7 +44,7 @@ public class SurefireReportParser { private static final String INCLUDES = "*.xml"; - private static final String EXCLUDES = "*.txt, testng-failed.xml, testng-failures.xml, testng-results.xml"; + private static final String EXCLUDES = "*.txt, testng-failed.xml, testng-failures.xml, testng-results.xml, failsafe-summary*.xml"; private NumberFormat numberFormat = NumberFormat.getInstance(); diff --git a/maven-surefire-report-plugin/src/main/java/org/apache/maven/plugins/surefire/report/TestSuiteXmlParser.java b/maven-surefire-common/src/main/java/org/apache/maven/plugins/surefire/report/TestSuiteXmlParser.java similarity index 91% rename from maven-surefire-report-plugin/src/main/java/org/apache/maven/plugins/surefire/report/TestSuiteXmlParser.java rename to maven-surefire-common/src/main/java/org/apache/maven/plugins/surefire/report/TestSuiteXmlParser.java index 49e7c1577c..3f600b291a 100644 --- a/maven-surefire-report-plugin/src/main/java/org/apache/maven/plugins/surefire/report/TestSuiteXmlParser.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugins/surefire/report/TestSuiteXmlParser.java @@ -1,285 +1,310 @@ -package org.apache.maven.plugins.surefire.report; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES 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.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.text.NumberFormat; -import java.text.ParseException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.StringTokenizer; - -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.parsers.SAXParser; -import javax.xml.parsers.SAXParserFactory; - -import org.xml.sax.Attributes; -import org.xml.sax.SAXException; -import org.xml.sax.helpers.DefaultHandler; - -/** - * - */ -public class TestSuiteXmlParser - extends DefaultHandler -{ - private ReportTestSuite defaultSuite; - - private ReportTestSuite currentSuite; - - private Map classesToSuites; - - private final NumberFormat numberFormat = NumberFormat.getInstance( Locale.ENGLISH ); - - /** - * @noinspection StringBufferField - */ - private StringBuffer currentElement; - - private ReportTestCase testCase; - - public Collection parse( String xmlPath ) - throws ParserConfigurationException, SAXException, IOException - { - - File f = new File( xmlPath ); - - FileInputStream fileInputStream = new FileInputStream( f ); - - try - { - return parse( fileInputStream ); - } - finally - { - fileInputStream.close(); - } - } - - public Collection parse( InputStream stream ) - throws ParserConfigurationException, SAXException, IOException - { - SAXParserFactory factory = SAXParserFactory.newInstance(); - - SAXParser saxParser = factory.newSAXParser(); - - classesToSuites = new HashMap(); - - saxParser.parse( stream, this ); - - if ( currentSuite != defaultSuite ) - { // omit the defaultSuite if it's empty and there are alternatives - if ( defaultSuite.getNumberOfTests() == 0 ) - { - classesToSuites.remove( defaultSuite.getFullClassName() ); - } - } - - return classesToSuites.values(); - } - - /** - * {@inheritDoc} - */ - public void startElement( String uri, String localName, String qName, Attributes attributes ) - throws SAXException - { - try - { - if ( "testsuite".equals( qName ) ) - { - currentSuite = defaultSuite = new ReportTestSuite(); - - try - { - Number time = numberFormat.parse( attributes.getValue( "time" ) ); - - defaultSuite.setTimeElapsed( time.floatValue() ); - } - catch ( NullPointerException npe ) - { - System.err.println( "WARNING: no time attribute found on testsuite element" ); - } - - //check if group attribute is existing - if ( attributes.getValue( "group" ) != null && !"".equals( attributes.getValue( "group" ) ) ) - { - String packageName = attributes.getValue( "group" ); - String name = attributes.getValue( "name" ); - - defaultSuite.setFullClassName( packageName + "." + name ); - } - else - { - String fullClassName = attributes.getValue( "name" ); - defaultSuite.setFullClassName( fullClassName ); - } - - classesToSuites.put( defaultSuite.getFullClassName(), defaultSuite ); - } - else if ( "testcase".equals( qName ) ) - { - currentElement = new StringBuffer(); - - testCase = new ReportTestCase(); - - testCase.setName( attributes.getValue( "name" ) ); - - String fullClassName = attributes.getValue( "classname" ); - - // if the testcase declares its own classname, it may need to belong to its own suite - if ( fullClassName != null ) - { - currentSuite = classesToSuites.get( fullClassName ); - if ( currentSuite == null ) - { - currentSuite = new ReportTestSuite(); - currentSuite.setFullClassName( fullClassName ); - classesToSuites.put( fullClassName, currentSuite ); - } - } - - testCase.setFullClassName( currentSuite.getFullClassName() ); - testCase.setClassName( currentSuite.getName() ); - testCase.setFullName( currentSuite.getFullClassName() + "." + testCase.getName() ); - - String timeAsString = attributes.getValue( "time" ); - - Number time = new Integer( 0 ); - - if ( timeAsString != null ) - { - time = numberFormat.parse( timeAsString ); - } - - testCase.setTime( time.floatValue() ); - - if ( currentSuite != defaultSuite ) - { - currentSuite.setTimeElapsed( time.floatValue() + currentSuite.getTimeElapsed() ); - } - } - else if ( "failure".equals( qName ) ) - { - testCase.addFailure( attributes.getValue( "message" ), attributes.getValue( "type" ) ); - currentSuite.setNumberOfFailures( 1 + currentSuite.getNumberOfFailures() ); - } - else if ( "error".equals( qName ) ) - { - testCase.addFailure( attributes.getValue( "message" ), attributes.getValue( "type" ) ); - currentSuite.setNumberOfErrors( 1 + currentSuite.getNumberOfErrors() ); - } - else if ( "skipped".equals( qName ) ) - { - final String message = attributes.getValue( "message" ); - testCase.addFailure( message != null ? message : "skipped", "skipped" ); - currentSuite.setNumberOfSkipped( 1 + currentSuite.getNumberOfSkipped() ); - } - } - catch ( ParseException e ) - { - throw new SAXException( e.getMessage(), e ); - } - } - - /** - * {@inheritDoc} - */ - public void endElement( String uri, String localName, String qName ) - throws SAXException - { - if ( "testcase".equals( qName ) ) - { - currentSuite.getTestCases().add( testCase ); - } - else if ( "failure".equals( qName ) ) - { - Map failure = testCase.getFailure(); - - failure.put( "detail", parseCause( currentElement.toString() ) ); - } - else if ( "error".equals( qName ) ) - { - Map error = testCase.getFailure(); - - error.put( "detail", parseCause( currentElement.toString() ) ); - } - else if ( "time".equals( qName ) ) - { - try - { - Number time = numberFormat.parse( currentElement.toString() ); - defaultSuite.setTimeElapsed( time.floatValue() ); - } - catch ( ParseException e ) - { - throw new SAXException( e.getMessage(), e ); - } - } - // TODO extract real skipped reasons - } - - /** - * {@inheritDoc} - */ - public void characters( char[] ch, int start, int length ) - throws SAXException - { - String s = new String( ch, start, length ); - - if ( !"".equals( s.trim() ) ) - { - currentElement.append( s ); - } - } - - private List parseCause( String detail ) - { - String fullName = testCase.getFullName(); - String name = fullName.substring( fullName.lastIndexOf( "." ) + 1 ); - return parseCause( detail, name ); - } - - private List parseCause( String detail, String compareTo ) - { - StringTokenizer stringTokenizer = new StringTokenizer( detail, "\n" ); - List parsedDetail = new ArrayList( stringTokenizer.countTokens() ); - - while ( stringTokenizer.hasMoreTokens() ) - { - String lineString = stringTokenizer.nextToken().trim(); - parsedDetail.add( lineString ); - if ( lineString.indexOf( compareTo ) >= 0 ) - { - break; - } - } - - return parsedDetail; - } - -} +package org.apache.maven.plugins.surefire.report; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES 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.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.text.NumberFormat; +import java.text.ParseException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.StringTokenizer; + +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.parsers.SAXParser; +import javax.xml.parsers.SAXParserFactory; + +import org.xml.sax.Attributes; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.DefaultHandler; + +/** + * + */ +public class TestSuiteXmlParser + extends DefaultHandler +{ + private ReportTestSuite defaultSuite; + + private ReportTestSuite currentSuite; + + private Map classesToSuites; + + private final NumberFormat numberFormat = NumberFormat.getInstance( Locale.ENGLISH ); + + /** + * @noinspection StringBufferField + */ + private StringBuffer currentElement; + + private ReportTestCase testCase; + + private boolean valid; + + public Collection parse( String xmlPath ) + throws ParserConfigurationException, SAXException, IOException + { + + File f = new File( xmlPath ); + + FileInputStream fileInputStream = new FileInputStream( f ); + + InputStreamReader inputStreamReader = new InputStreamReader( fileInputStream, "UTF-8" ); + + try + { + return parse( inputStreamReader ); + } + finally + { + inputStreamReader.close(); + fileInputStream.close(); + } + } + + public Collection parse( InputStreamReader stream ) + throws ParserConfigurationException, SAXException, IOException + { + SAXParserFactory factory = SAXParserFactory.newInstance(); + + SAXParser saxParser = factory.newSAXParser(); + + valid = true; + + classesToSuites = new HashMap(); + + saxParser.parse( new InputSource( stream ), this ); + + if ( currentSuite != defaultSuite ) + { // omit the defaultSuite if it's empty and there are alternatives + if ( defaultSuite.getNumberOfTests() == 0 ) + { + classesToSuites.remove( defaultSuite.getFullClassName() ); + } + } + + return classesToSuites.values(); + } + + /** + * {@inheritDoc} + */ + public void startElement( String uri, String localName, String qName, Attributes attributes ) + throws SAXException + { + if ( !valid ) + { + return; + } + try + { + if ( "testsuite".equals( qName ) ) + { + currentSuite = defaultSuite = new ReportTestSuite(); + + try + { + Number time = numberFormat.parse( attributes.getValue( "time" ) ); + + defaultSuite.setTimeElapsed( time.floatValue() ); + } + catch ( NullPointerException npe ) + { + System.err.println( "WARNING: no time attribute found on testsuite element" ); + } + + //check if group attribute is existing + if ( attributes.getValue( "group" ) != null && !"".equals( attributes.getValue( "group" ) ) ) + { + String packageName = attributes.getValue( "group" ); + String name = attributes.getValue( "name" ); + + defaultSuite.setFullClassName( packageName + "." + name ); + } + else + { + String fullClassName = attributes.getValue( "name" ); + defaultSuite.setFullClassName( fullClassName ); + } + + classesToSuites.put( defaultSuite.getFullClassName(), defaultSuite ); + } + else if ( "testcase".equals( qName ) ) + { + currentElement = new StringBuffer(); + + testCase = new ReportTestCase(); + + testCase.setName( attributes.getValue( "name" ) ); + + String fullClassName = attributes.getValue( "classname" ); + + // if the testcase declares its own classname, it may need to belong to its own suite + if ( fullClassName != null ) + { + currentSuite = classesToSuites.get( fullClassName ); + if ( currentSuite == null ) + { + currentSuite = new ReportTestSuite(); + currentSuite.setFullClassName( fullClassName ); + classesToSuites.put( fullClassName, currentSuite ); + } + } + + testCase.setFullClassName( currentSuite.getFullClassName() ); + testCase.setClassName( currentSuite.getName() ); + testCase.setFullName( currentSuite.getFullClassName() + "." + testCase.getName() ); + + String timeAsString = attributes.getValue( "time" ); + + Number time = 0; + + if ( timeAsString != null ) + { + time = numberFormat.parse( timeAsString ); + } + + testCase.setTime( time.floatValue() ); + + if ( currentSuite != defaultSuite ) + { + currentSuite.setTimeElapsed( time.floatValue() + currentSuite.getTimeElapsed() ); + } + } + else if ( "failure".equals( qName ) ) + { + testCase.addFailure( attributes.getValue( "message" ), attributes.getValue( "type" ) ); + currentSuite.setNumberOfFailures( 1 + currentSuite.getNumberOfFailures() ); + } + else if ( "error".equals( qName ) ) + { + testCase.addFailure( attributes.getValue( "message" ), attributes.getValue( "type" ) ); + currentSuite.setNumberOfErrors( 1 + currentSuite.getNumberOfErrors() ); + } + else if ( "skipped".equals( qName ) ) + { + final String message = attributes.getValue( "message" ); + testCase.addFailure( message != null ? message : "skipped", "skipped" ); + currentSuite.setNumberOfSkipped( 1 + currentSuite.getNumberOfSkipped() ); + } + else if ( "failsafe-summary".equals( qName ) ) + { + valid = false; + } + } + catch ( ParseException e ) + { + throw new SAXException( e.getMessage(), e ); + } + } + + /** + * {@inheritDoc} + */ + public void endElement( String uri, String localName, String qName ) + throws SAXException + { + if ( "testcase".equals( qName ) ) + { + currentSuite.getTestCases().add( testCase ); + } + else if ( "failure".equals( qName ) ) + { + Map failure = testCase.getFailure(); + + failure.put( "detail", parseCause( currentElement.toString() ) ); + } + else if ( "error".equals( qName ) ) + { + Map error = testCase.getFailure(); + + error.put( "detail", parseCause( currentElement.toString() ) ); + } + else if ( "time".equals( qName ) ) + { + try + { + Number time = numberFormat.parse( currentElement.toString() ); + defaultSuite.setTimeElapsed( time.floatValue() ); + } + catch ( ParseException e ) + { + throw new SAXException( e.getMessage(), e ); + } + } + // TODO extract real skipped reasons + } + + /** + * {@inheritDoc} + */ + public void characters( char[] ch, int start, int length ) + throws SAXException + { + if ( !valid ) + { + return; + } + String s = new String( ch, start, length ); + + if ( !"".equals( s.trim() ) ) + { + currentElement.append( s ); + } + } + + private List parseCause( String detail ) + { + String fullName = testCase.getFullName(); + String name = fullName.substring( fullName.lastIndexOf( "." ) + 1 ); + return parseCause( detail, name ); + } + + private List parseCause( String detail, String compareTo ) + { + StringTokenizer stringTokenizer = new StringTokenizer( detail, "\n" ); + List parsedDetail = new ArrayList( stringTokenizer.countTokens() ); + + while ( stringTokenizer.hasMoreTokens() ) + { + String lineString = stringTokenizer.nextToken().trim(); + parsedDetail.add( lineString ); + if ( lineString.contains( compareTo ) ) + { + break; + } + } + + return parsedDetail; + } + + public boolean isValid() + { + return valid; + } +} 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 bd543e8505..139c3d78a2 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,158 +1,145 @@ -package org.apache.maven.surefire.report; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES 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.Collection; -import java.util.Collections; -import org.apache.maven.plugin.surefire.report.TestSetStats; -import org.apache.maven.surefire.suite.RunResult; -import org.apache.maven.surefire.util.internal.StringUtils; - -/** - * @author Kristian Rosenvold - */ -public class RunStatistics -{ - /** - * Holds the source(s) that causes the error(s). - */ - private final Sources errorSources = new Sources(); - - /** - * Holds the source(s) that causes the failure(s). - */ - private final Sources failureSources = new Sources(); - - private int completedCount; - - private int errors; - - private int failures; - - private int skipped; - - - public void addErrorSource( String errorSource, StackTraceWriter stackTraceWriter ) - { - errorSources.addSource( errorSource, stackTraceWriter ); - } - - public void addFailureSource( String failureSource, StackTraceWriter stackTraceWriter ) - { - failureSources.addSource( failureSource, stackTraceWriter ); - } - - public Collection getErrorSources() - { - return errorSources.getListOfSources(); - } - - public Collection getFailureSources() - { - return failureSources.getListOfSources(); - } - - public synchronized boolean hadFailures() - { - return failures > 0; - } - - public synchronized boolean hadErrors() - { - return errors > 0; - } - - public synchronized int getCompletedCount() - { - return completedCount; - } - - public synchronized int getSkipped() - { - return skipped; - } - - public synchronized void add( TestSetStats testSetStats ) - { - this.completedCount += testSetStats.getCompletedCount(); - this.errors += testSetStats.getErrors(); - this.failures += testSetStats.getFailures(); - this.skipped += testSetStats.getSkipped(); - } - - public synchronized RunResult getRunResult() - { - return new RunResult( completedCount, errors, failures, skipped ); - } - - public synchronized String getSummary() - { - return "Tests run: " + completedCount + ", Failures: " + failures + ", Errors: " + errors + ", Skipped: " - + skipped; - } - - - private static class Sources - { - private final Collection listOfSources = new ArrayList(); - - void addSource( String source ) - { - synchronized ( listOfSources ) - { - listOfSources.add( source ); - } - } - - void addSource( String source, StackTraceWriter stackTraceWriter ) - { - String message = getMessageOfThrowable( stackTraceWriter ); - String extendedSource = - StringUtils.isBlank( message ) ? source : source + ": " + trimToSingleLine( message ); - addSource( extendedSource ); - } - - private String trimToSingleLine( String str ) - { - int i = str.indexOf( "\n" ); - return i >= 0 ? str.substring( 0, i ) + "(..)" : str; - } - - Collection getListOfSources() - { - synchronized ( listOfSources ) - { - return Collections.unmodifiableCollection( listOfSources ); - } - } - - private String getMessageOfThrowable( StackTraceWriter stackTraceWriter ) - { - //noinspection ThrowableResultOfMethodCallIgnored - return stackTraceWriter != null ? getMessageOfThrowable( stackTraceWriter.getThrowable() ) : ""; - } - - private String getMessageOfThrowable( SafeThrowable throwable ) - { - return throwable != null ? throwable.getLocalizedMessage() : ""; - } - } -} +package org.apache.maven.surefire.report; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES 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.Collection; +import java.util.Collections; +import org.apache.maven.plugin.surefire.report.TestSetStats; +import org.apache.maven.surefire.suite.RunResult; + +/** + * @author Kristian Rosenvold + */ +public class RunStatistics +{ + /** + * Holds the source(s) that causes the error(s). + */ + private final Sources errorSources = new Sources(); + + /** + * Holds the source(s) that causes the failure(s). + */ + private final Sources failureSources = new Sources(); + + private int completedCount; + + private int errors; + + private int failures; + + private int skipped; + + + public void addErrorSource( StackTraceWriter stackTraceWriter ) + { + if ( stackTraceWriter == null ) + { + throw new IllegalArgumentException( "Cant be null" ); + } + errorSources.addSource( stackTraceWriter ); + } + + public void addFailureSource( StackTraceWriter stackTraceWriter ) + { + if ( stackTraceWriter == null ) + { + throw new IllegalArgumentException( "Cant be null" ); + } + failureSources.addSource( stackTraceWriter ); + } + + public Collection getErrorSources() + { + return errorSources.getListOfSources(); + } + + public Collection getFailureSources() + { + return failureSources.getListOfSources(); + } + + public synchronized boolean hadFailures() + { + return failures > 0; + } + + public synchronized boolean hadErrors() + { + return errors > 0; + } + + public synchronized int getCompletedCount() + { + return completedCount; + } + + public synchronized int getSkipped() + { + return skipped; + } + + public synchronized void add( TestSetStats testSetStats ) + { + this.completedCount += testSetStats.getCompletedCount(); + this.errors += testSetStats.getErrors(); + this.failures += testSetStats.getFailures(); + this.skipped += testSetStats.getSkipped(); + } + + public synchronized RunResult getRunResult() + { + return new RunResult( completedCount, errors, failures, skipped ); + } + + public synchronized String getSummary() + { + return "Tests run: " + completedCount + ", Failures: " + failures + ", Errors: " + errors + ", Skipped: " + + skipped; + } + + + private static class Sources + { + private final Collection listOfSources = new ArrayList(); + + void addSource( String source ) + { + synchronized ( listOfSources ) + { + listOfSources.add( source ); + } + } + + void addSource( StackTraceWriter stackTraceWriter ) + { + addSource( stackTraceWriter.smartTrimmedStackTrace() ); + } + + Collection getListOfSources() + { + synchronized ( listOfSources ) + { + return Collections.unmodifiableCollection( listOfSources ); + } + } + } +} 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 5a4663a5d1..af9ee75ca6 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 @@ -22,6 +22,7 @@ import java.util.Properties; import junit.framework.TestCase; +import org.apache.maven.surefire.booter.KeyValueSource; /** * Tests the insertion-order preserving properties collection @@ -33,7 +34,7 @@ public class SurefirePropertiesTest public void testKeys() throws Exception { - SurefireProperties orderedProperties = new SurefireProperties( null ); + SurefireProperties orderedProperties = new SurefireProperties( (KeyValueSource) null ); orderedProperties.setProperty( "abc", "1" ); orderedProperties.setProperty( "xyz", "1" ); orderedProperties.setProperty( "efg", "1" ); @@ -48,7 +49,7 @@ public void testKeys() public void testKeysReinsert() throws Exception { - SurefireProperties orderedProperties = new SurefireProperties( null ); + SurefireProperties orderedProperties = new SurefireProperties( (KeyValueSource)null ); orderedProperties.setProperty( "abc", "1" ); orderedProperties.setProperty( "xyz", "1" ); orderedProperties.setProperty( "efg", "1" ); 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 5446bd6972..7c11370b8b 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 @@ -70,16 +70,10 @@ private void assertEquals( ClasspathConfiguration expectedConfiguration, { assertEquals( expectedConfiguration.getTestClasspath().getClassPath(), actualConfiguration.getTestClasspath().getClassPath() ); - Properties propertiesForExpectedConfiguration = getPropertiesForClasspathConfiguration( expectedConfiguration ); - Properties propertiesForActualConfiguration = getPropertiesForClasspathConfiguration( actualConfiguration ); - assertEquals( propertiesForExpectedConfiguration, propertiesForActualConfiguration ); - } - - private Properties getPropertiesForClasspathConfiguration( ClasspathConfiguration configuration ) - { - Properties properties = new Properties(); - configuration.addForkProperties( new PropertiesWrapper( properties ) ); - return properties; + assertEquals( expectedConfiguration.isEnableAssertions(), actualConfiguration.isEnableAssertions() ); + assertEquals( expectedConfiguration.isChildDelegation(), actualConfiguration.isChildDelegation() ); + assertEquals( expectedConfiguration.getProviderClasspath(), actualConfiguration.getProviderClasspath() ); + assertEquals( expectedConfiguration.getTestClasspath(), actualConfiguration.getTestClasspath() ); } public void testClassLoaderConfiguration() @@ -99,9 +93,9 @@ public void testClassLoaderConfigurationTrues() private ClasspathConfiguration createClasspathConfiguration() { - Classpath testClassPath = new Classpath( Arrays.asList( new String[]{ "CP1", "CP2" } ) ); - Classpath providerClasspath = new Classpath( Arrays.asList( new String[]{ "SP1", "SP2" } ) ); - return new ClasspathConfiguration( testClassPath, providerClasspath, new Classpath(), true, true ); + 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 ); } public static ClassLoaderConfiguration getSystemClassLoaderConfiguration() 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 5c9372223a..9a310b282c 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 @@ -22,6 +22,7 @@ import java.io.File; import java.io.IOException; import java.util.Collections; + import org.apache.maven.shared.utils.StringUtils; import org.apache.maven.shared.utils.cli.Commandline; import org.apache.maven.surefire.booter.Classpath; @@ -40,7 +41,7 @@ public void testCreateCommandLine_UseSystemClassLoaderForkOnce_ShouldConstructMa File cpElement = getTempClasspathFile(); Commandline cli = - config.createCommandLine( Collections.singletonList( cpElement.getAbsolutePath() ), true, false, 1 ); + config.createCommandLine( Collections.singletonList( cpElement.getAbsolutePath() ), true, false, null, 1 ); String line = StringUtils.join( cli.getCommandline(), " " ); assertTrue( line.contains( "-jar" ) ); @@ -55,7 +56,7 @@ public void testArglineWithNewline() final Commandline commandLine = forkConfiguration.createCommandLine( Collections.singletonList( cpElement.getAbsolutePath() ), false, false, - 1 ); + null, 1 ); assertTrue( commandLine.toString().contains( "abc def" ) ); } @@ -70,10 +71,8 @@ private File getTempClasspathFile() public static ForkConfiguration getForkConfiguration( String argLine, String jvm ) throws IOException { - ForkConfiguration forkConfiguration = - new ForkConfiguration( new Classpath(), null, null, jvm, new File( "." ).getCanonicalFile(), argLine, null, - false, 1 ); - return forkConfiguration; + return new ForkConfiguration( Classpath.emptyClasspath(), null, null, jvm, new File( "." ).getCanonicalFile(), argLine, + null, false, 1, false ); } } 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 2006d6b79a..e2615a238b 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 @@ -30,7 +30,7 @@ import org.apache.maven.surefire.report.CategorizedReportEntry; import org.apache.maven.surefire.report.ConsoleLogger; import org.apache.maven.surefire.report.ConsoleOutputReceiver; -import org.apache.maven.surefire.report.PojoStackTraceWriter; +import org.apache.maven.surefire.report.LegacyPojoStackTraceWriter; import org.apache.maven.surefire.report.ReportEntry; import org.apache.maven.surefire.report.ReporterException; import org.apache.maven.surefire.report.RunListener; @@ -296,7 +296,7 @@ private SimpleReportEntry createReportEntryWithStackTrace() catch ( RuntimeException e ) { StackTraceWriter stackTraceWriter = - new PojoStackTraceWriter( "org.apache.tests.TestClass", "testMethod11", e ); + new LegacyPojoStackTraceWriter( "org.apache.tests.TestClass", "testMethod11", e ); return new CategorizedReportEntry( "com.abc.TestClass", "testMethod", "aGroup", stackTraceWriter, 77 ); } } @@ -310,7 +310,7 @@ private SimpleReportEntry createReportEntryWithSpecialMessage( String message ) catch ( RuntimeException e ) { StackTraceWriter stackTraceWriter = - new PojoStackTraceWriter( "org.apache.tests.TestClass", "testMethod11", e ); + new LegacyPojoStackTraceWriter( "org.apache.tests.TestClass", "testMethod11", e ); return new CategorizedReportEntry( "com.abc.TestClass", "testMethod", "aGroup", stackTraceWriter, 77 ); } } 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 340ab3c16f..9c55898baf 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 @@ -19,14 +19,25 @@ * under the License. */ -import java.io.File; -import org.apache.maven.surefire.report.PojoStackTraceWriter; +import junit.framework.AssertionFailedError; +import junit.framework.TestCase; +import org.apache.commons.io.output.DeferredFileOutputStream; +import org.apache.maven.plugin.surefire.booterclient.output.DeserializedStacktraceWriter; +import org.apache.maven.shared.utils.StringUtils; +import org.apache.maven.shared.utils.xml.Xpp3Dom; +import org.apache.maven.shared.utils.xml.Xpp3DomBuilder; +import org.apache.maven.surefire.report.LegacyPojoStackTraceWriter; import org.apache.maven.surefire.report.ReportEntry; import org.apache.maven.surefire.report.SimpleReportEntry; +import org.apache.maven.surefire.report.StackTraceWriter; -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileReader; +import java.io.IOException; +import java.io.InputStreamReader; +@SuppressWarnings( "ResultOfMethodCallIgnored" ) public class StatelessXMLReporterTest extends TestCase { @@ -35,17 +46,14 @@ public class StatelessXMLReporterTest private ReportEntry reportEntry; - private String message; - private TestSetStats stats; protected void setUp() throws Exception { super.setUp(); - message = "junit.framework.AssertionFailedError"; reportEntry = new SimpleReportEntry( this.getClass().getName(), "StatelessXMLReporterTest", - new PojoStackTraceWriter( "", "", new AssertionFailedError() ), 17 ); + new LegacyPojoStackTraceWriter( "", "", new AssertionFailedError() ), 17 ); stats = new TestSetStats( false, true ); } @@ -66,4 +74,67 @@ public void testFileNameWithoutSuffix() expectedReportFile.delete(); } + + public void testAllFieldsSerialized() + throws IOException + { + File reportDir = new File( "." ); + String testName = "aTestMethod"; + String testName2 = "bTestMethod"; + reportEntry = new SimpleReportEntry( this.getClass().getName(), testName, 12 ); + WrappedReportEntry testSetReportEntry = + new WrappedReportEntry( reportEntry, ReportEntryType.success, 12, null, null ); + File expectedReportFile = new File( reportDir, "TEST-" + testName + ".xml" ); + + stats.testSucceeded( testSetReportEntry ); + StackTraceWriter stackTraceWriter = new DeserializedStacktraceWriter( "A fud msg", "trimmed", "fail at foo" ); + DeferredFileOutputStream s = new DeferredFileOutputStream( 1000000, "fds", "fdx", new File( "" ) ); + String expected = "st]]>d-o\u00DCt!"; + s.write( expected.getBytes( "UTF-8" ) ); + DeferredFileOutputStream s1 = new DeferredFileOutputStream( 1000000, "fds", "fdx", new File( "" ) ); + byte[] bytes = "std-\u0115rr?&-&£".getBytes("UTF-8"); + s1.write( bytes ); + WrappedReportEntry t2 = + new WrappedReportEntry( new SimpleReportEntry( Inner.class.getName(), testName2, stackTraceWriter, 13 ), + ReportEntryType.error, 13, s, s1 ); + + stats.testSucceeded( t2 ); + StatelessXmlReporter reporter = new StatelessXmlReporter( new File( "." ), null, 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( StringUtils.isEmpty( child.getAttribute( "value" ) ) ); + assertFalse( StringUtils.isEmpty( child.getAttribute( "name" ) ) ); + + Xpp3Dom[] testcase = testSuite.getChildren( "testcase" ); + Xpp3Dom tca = testcase[0]; + assertEquals( testName, tca.getAttribute( "name" ) ); // Hopefully same order on jdk5 + assertEquals( "0.012", tca.getAttribute( "time" ) ); + assertEquals( this.getClass().getName(), tca.getAttribute( "classname" ) ); + + Xpp3Dom tcb = testcase[1]; + assertEquals( testName2, tcb.getAttribute( "name" ) ); + assertEquals( "0.013", tcb.getAttribute( "time" ) ); + assertEquals( Inner.class.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( expected, tcb.getChild( "system-out" ).getValue() ); + assertEquals( "std-\u0115rr?&-&£", tcb.getChild( "system-err" ).getValue() ); + + expectedReportFile.delete(); + } + + class Inner + { + + } + } 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 f568fa82e2..0e34754dd9 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,73 +1,73 @@ -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 - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR 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.report.ReportEntry; -import org.apache.maven.surefire.report.SimpleReportEntry; - -import junit.framework.TestCase; - -/** - * @author Kristian Rosenvold - */ -public class WrappedReportEntryTest - extends TestCase -{ - - public void testClassNameOnly() - throws Exception - { - String category = "surefire.testcase.JunitParamsTest"; - WrappedReportEntry wr = - new WrappedReportEntry( new SimpleReportEntry( "fud", category ), null, 12, null, null ); - final String reportName = wr.getReportName(); - assertEquals( "surefire.testcase.JunitParamsTest", reportName ); - } - - public void testRegular() - { - ReportEntry reportEntry = new SimpleReportEntry( "fud", "testSum(surefire.testcase.NonJunitParamsTest)" ); - WrappedReportEntry wr = new WrappedReportEntry( reportEntry, null, 12, null, null ); - final String reportName = wr.getReportName(); - assertEquals( "testSum", reportName ); - } - - public void testGetReportNameWithParams() - throws Exception - { - String category = "[0] 1\u002C 2\u002C 3 (testSum)(surefire.testcase.JunitParamsTest)"; - ReportEntry reportEntry = new SimpleReportEntry( "fud", category ); - WrappedReportEntry wr = new WrappedReportEntry( reportEntry, null, 12, null, null ); - final String reportName = wr.getReportName(); - assertEquals( "[0] 1, 2, 3 (testSum)", reportName ); - } - - public void testElapsed() - throws Exception - { - String category = "[0] 1\u002C 2\u002C 3 (testSum)(surefire.testcase.JunitParamsTest)"; - ReportEntry reportEntry = new SimpleReportEntry( "fud", category ); - WrappedReportEntry wr = new WrappedReportEntry( reportEntry, null, 12, null, null ); - String elapsedTimeSummary = wr.getElapsedTimeSummary(); - assertEquals( "[0] 1, 2, 3 (testSum)(surefire.testcase.JunitParamsTest) Time elapsed: 0.012 sec", - elapsedTimeSummary ); - } - - -} +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 + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR 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.report.ReportEntry; +import org.apache.maven.surefire.report.SimpleReportEntry; + +import junit.framework.TestCase; + +/** + * @author Kristian Rosenvold + */ +public class WrappedReportEntryTest + extends TestCase +{ + + public void testClassNameOnly() + throws Exception + { + String category = "surefire.testcase.JunitParamsTest"; + WrappedReportEntry wr = + new WrappedReportEntry( new SimpleReportEntry( "fud", category ), null, 12, null, null ); + final String reportName = wr.getReportName(); + assertEquals( "surefire.testcase.JunitParamsTest", reportName ); + } + + public void testRegular() + { + ReportEntry reportEntry = new SimpleReportEntry( "fud", "testSum(surefire.testcase.NonJunitParamsTest)" ); + WrappedReportEntry wr = new WrappedReportEntry( reportEntry, null, 12, null, null ); + final String reportName = wr.getReportName(); + assertEquals( "testSum", reportName ); + } + + public void testGetReportNameWithParams() + throws Exception + { + String category = "[0] 1\u002C 2\u002C 3 (testSum)(surefire.testcase.JunitParamsTest)"; + ReportEntry reportEntry = new SimpleReportEntry( "fud", category ); + WrappedReportEntry wr = new WrappedReportEntry( reportEntry, null, 12, null, null ); + final String reportName = wr.getReportName(); + assertEquals( "[0] 1, 2, 3 (testSum)", reportName ); + } + + public void testElapsed() + throws Exception + { + String category = "[0] 1\u002C 2\u002C 3 (testSum)(surefire.testcase.JunitParamsTest)"; + ReportEntry reportEntry = new SimpleReportEntry( "fud", category ); + WrappedReportEntry wr = new WrappedReportEntry( reportEntry, null, 12, null, null ); + String elapsedTimeSummary = wr.getElapsedTimeSummary(); + assertEquals( "[0] 1, 2, 3 (testSum)(surefire.testcase.JunitParamsTest) Time elapsed: 0.012 sec", + elapsedTimeSummary ); + } + + +} 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 new file mode 100644 index 0000000000..c897e1ec74 --- /dev/null +++ b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/util/DependenciesScannerTest.java @@ -0,0 +1,94 @@ +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 + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES 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.FileOutputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Properties; +import java.util.jar.JarFile; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; + +import junit.framework.TestCase; + +import org.apache.maven.artifact.Artifact; +import org.apache.maven.artifact.DefaultArtifact; +import org.apache.maven.artifact.versioning.VersionRange; +import org.apache.maven.plugin.MojoExecutionException; +import org.apache.maven.surefire.testset.TestSetFailedException; +import org.apache.maven.surefire.util.ScanResult; + +/** + * @author Aslak Knutsen + */ +public class DependenciesScannerTest + extends TestCase +{ + public void testLocateTestClasses() + throws Exception + { + File testFile = writeTestFile(); + + // 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); + + List scanDependencies = new ArrayList(); + scanDependencies.add("org.surefire.dependency:test-jar"); + + List include = new ArrayList(); + include.add( "**/*A.java" ); + List exclude = new ArrayList(); + + DependencyScanner scanner = new DependencyScanner( + DependencyScanner.filter(Arrays.asList(artifact), scanDependencies), + include, exclude, new ArrayList() ); + + ScanResult classNames = scanner.scan(); + assertNotNull( classNames ); + System.out.println( "classNames " + classNames.toString() ); + assertEquals( 1, classNames.size() ); + System.out.println(classNames.getClassName(0)); + + Properties props = new Properties(); + classNames.writeTo( props ); + assertEquals( 1, props.size() ); + } + + private File writeTestFile() throws Exception { + File output = new File("target/DependenciesScannerTest-tests.jar"); + output.delete(); + + ZipOutputStream out = new ZipOutputStream(new FileOutputStream(output)); + + out.putNextEntry(new ZipEntry("org/test/TestA.class")); + out.closeEntry(); + out.putNextEntry(new ZipEntry("org/test/TestB.class")); + out.closeEntry(); + out.close(); + 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 232f28c0f8..bf3d383bf5 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,60 +1,60 @@ -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 - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES 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.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Properties; -import org.apache.maven.surefire.testset.TestSetFailedException; -import org.apache.maven.surefire.util.ScanResult; - -import junit.framework.TestCase; - -/** - * @author Kristian Rosenvold - */ -public class DirectoryScannerTest - 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/test-classes" ).getCanonicalPath() ); - List include = new ArrayList(); - include.add( "**/*ZT*A.java" ); - List exclude = new ArrayList(); - - DirectoryScanner surefireDirectoryScanner = - new DirectoryScanner( baseDir, include, exclude, new ArrayList() ); - - ScanResult classNames = surefireDirectoryScanner.scan(); - assertNotNull( classNames ); - System.out.println( "classNames " + Arrays.asList( classNames ) ); - assertEquals( 3, classNames.size() ); - - Properties props = new Properties(); - classNames.writeTo( props ); - assertEquals( 3, props.size() ); - } -} +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 + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES 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.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Properties; +import org.apache.maven.surefire.testset.TestSetFailedException; +import org.apache.maven.surefire.util.ScanResult; + +import junit.framework.TestCase; + +/** + * @author Kristian Rosenvold + */ +public class DirectoryScannerTest + 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/test-classes" ).getCanonicalPath() ); + List include = new ArrayList(); + include.add( "**/*ZT*A.java" ); + List exclude = new ArrayList(); + + DirectoryScanner surefireDirectoryScanner = + new DirectoryScanner( baseDir, include, exclude, new ArrayList() ); + + ScanResult classNames = surefireDirectoryScanner.scan(); + assertNotNull( classNames ); + System.out.println( "classNames " + Arrays.asList( classNames ) ); + assertEquals( 3, classNames.size() ); + + Properties props = new Properties(); + classNames.writeTo( props ); + assertEquals( 3, props.size() ); + } +} 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 dd7fcd30b5..752c7cb142 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,63 +1,64 @@ -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 - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES 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; - -/** - * @author Kristian Rosenvold - */ -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 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() ) ); - } - - private SpecificFileFilter createFileFilter( String s ) - { - return new SpecificFileFilter( new String[]{ s } ); - } - - private String getFile() - { - return "org/apache/maven/surefire/SpecificTestClassFilter.class"; - } -} +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 + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES 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.apache.maven.plugin.surefire.util.ScannerUtil.convertSlashToSystemFileSeparator; +import junit.framework.TestCase; + +/** + * @author Kristian Rosenvold + */ +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 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() ) ); + } + + private SpecificFileFilter createFileFilter( String s ) + { + return new SpecificFileFilter( new String[]{ s } ); + } + + private String getFile() + { + return convertSlashToSystemFileSeparator( "org/apache/maven/surefire/SpecificTestClassFilter.class" ); + } +} diff --git a/maven-surefire-report-plugin/src/test/java/org/apache/maven/plugins/surefire/report/ReportTestCaseTest.java b/maven-surefire-common/src/test/java/org/apache/maven/plugins/surefire/report/ReportTestCaseTest.java similarity index 100% rename from maven-surefire-report-plugin/src/test/java/org/apache/maven/plugins/surefire/report/ReportTestCaseTest.java rename to maven-surefire-common/src/test/java/org/apache/maven/plugins/surefire/report/ReportTestCaseTest.java diff --git a/maven-surefire-report-plugin/src/test/java/org/apache/maven/plugins/surefire/report/ReportTestSuiteTest.java b/maven-surefire-common/src/test/java/org/apache/maven/plugins/surefire/report/ReportTestSuiteTest.java similarity index 100% rename from maven-surefire-report-plugin/src/test/java/org/apache/maven/plugins/surefire/report/ReportTestSuiteTest.java rename to maven-surefire-common/src/test/java/org/apache/maven/plugins/surefire/report/ReportTestSuiteTest.java diff --git a/maven-surefire-report-plugin/src/test/java/org/apache/maven/plugins/surefire/report/SurefireReportParserTest.java b/maven-surefire-common/src/test/java/org/apache/maven/plugins/surefire/report/SurefireReportParserTest.java similarity index 100% rename from maven-surefire-report-plugin/src/test/java/org/apache/maven/plugins/surefire/report/SurefireReportParserTest.java rename to maven-surefire-common/src/test/java/org/apache/maven/plugins/surefire/report/SurefireReportParserTest.java diff --git a/maven-surefire-report-plugin/src/test/java/org/apache/maven/plugins/surefire/report/TestSuiteXmlParserTest.java b/maven-surefire-common/src/test/java/org/apache/maven/plugins/surefire/report/TestSuiteXmlParserTest.java similarity index 64% rename from maven-surefire-report-plugin/src/test/java/org/apache/maven/plugins/surefire/report/TestSuiteXmlParserTest.java rename to maven-surefire-common/src/test/java/org/apache/maven/plugins/surefire/report/TestSuiteXmlParserTest.java index a3f9f3f66b..beaf1b2dcc 100644 --- a/maven-surefire-report-plugin/src/test/java/org/apache/maven/plugins/surefire/report/TestSuiteXmlParserTest.java +++ b/maven-surefire-common/src/test/java/org/apache/maven/plugins/surefire/report/TestSuiteXmlParserTest.java @@ -1,77 +1,136 @@ -package org.apache.maven.plugins.surefire.report; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES 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.ByteArrayInputStream; -import java.io.InputStream; -import java.util.Collection; - -import junit.framework.TestCase; - -/** - * @author Kristian Rosenvold - */ -public class TestSuiteXmlParserTest - extends TestCase -{ - public void testParse() - throws Exception - { - TestSuiteXmlParser testSuiteXmlParser = new TestSuiteXmlParser(); - String xml = "\n" + - "\n" - + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " junit.framework.AssertionFailedError: \n" - + - "\tat junit.framework.Assert.fail(Assert.java:47)\n" + - "\tat wellFormedXmlFailures.TestSurefire3.testU0000(TestSurefire3.java:40)\n" + - "\n" + - " \n" + - " \n" + - " junit.framework.AssertionFailedError: >\n" - + - "\tat junit.framework.Assert.fail(Assert.java:47)\n" + - "\tat wellFormedXmlFailures.TestSurefire3.testGreater(TestSurefire3.java:35)\n" + - "\n" + - " \n" + - " \n" + - " junit.framework.AssertionFailedError: \"\n" - + - "\tat junit.framework.Assert.fail(Assert.java:47)\n" + - "\tat wellFormedXmlFailures.TestSurefire3.testQuote(TestSurefire3.java:25)\n" + - "\n" + - " \n" + - ""; - InputStream byteArrayIs = new ByteArrayInputStream( xml.getBytes() ); - Collection parse = testSuiteXmlParser.parse( byteArrayIs ); - } -} +package org.apache.maven.plugins.surefire.report; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES 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.ByteArrayInputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.Collection; + +import javax.xml.parsers.ParserConfigurationException; + +import junit.framework.TestCase; +import org.xml.sax.SAXException; + +/** + * @author Kristian Rosenvold + */ +public class TestSuiteXmlParserTest + extends TestCase +{ + public void testParse() + throws Exception + { + TestSuiteXmlParser testSuiteXmlParser = new TestSuiteXmlParser(); + String xml = "\n" + + "\n" + + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " junit.framework.AssertionFailedError: \n" + + + "\tat junit.framework.Assert.fail(Assert.java:47)\n" + + "\tat wellFormedXmlFailures.TestSurefire3.testU0000(TestSurefire3.java:40)\n" + + "\n" + + " \n" + + " \n" + + " junit.framework.AssertionFailedError: >\n" + + + "\tat junit.framework.Assert.fail(Assert.java:47)\n" + + "\tat wellFormedXmlFailures.TestSurefire3.testGreater(TestSurefire3.java:35)\n" + + "\n" + + " \n" + + " \n" + + " junit.framework.AssertionFailedError: \"\n" + + + "\tat junit.framework.Assert.fail(Assert.java:47)\n" + + "\tat wellFormedXmlFailures.TestSurefire3.testQuote(TestSurefire3.java:25)\n" + + "\n" + + " \n" + + ""; + InputStream byteArrayIs = new ByteArrayInputStream( xml.getBytes() ); + Collection parse = testSuiteXmlParser.parse( new InputStreamReader(byteArrayIs, "UTF-8") ); + } + + public void testParser() + throws IOException, SAXException, ParserConfigurationException + { + TestSuiteXmlParser parser = new TestSuiteXmlParser(); + + Collection oldResult = parser.parse( + "src/test/resources/fixture/testsuitexmlparser/TEST-org.apache.maven.surefire.test.FailingTest.xml" ); + + assertNotNull( oldResult ); + + assertEquals( 1, oldResult.size() ); + ReportTestSuite next = oldResult.iterator().next(); + assertEquals( 2, next.getNumberOfTests() ); + + + } + + public void noTestParserBadFile() // Determine problem with xml file. + throws IOException, SAXException, ParserConfigurationException + { + TestSuiteXmlParser parser = new TestSuiteXmlParser(); + + File file = new File( "../surefire-integration-tests/target/UmlautDirIT/junit-pathWith\u00DCmlaut/target/surefire-reports/TEST-umlautTest.BasicTest.xml" ); + assertTrue(file.exists()); + Collection oldResult = parser.parse( + "..\\surefire-integration-tests\\target\\UmlautDirIT\\junit-pathWith\u00DCmlaut\\target\\surefire-reports\\TEST-umlautTest.BasicTest.xml" ); + + assertNotNull( oldResult ); + + assertEquals( 1, oldResult.size() ); + ReportTestSuite next = oldResult.iterator().next(); + assertEquals( 2, next.getNumberOfTests() ); + + + } + + public void testParserHitsFailsafeSummary() + throws IOException, SAXException, ParserConfigurationException + { + TestSuiteXmlParser parser = new TestSuiteXmlParser(); + + parser.parse( "src/test/resources/fixture/testsuitexmlparser/failsafe-summary.xml" ); + + assertFalse( parser.isValid() ); + + parser.parse( + "src/test/resources/fixture/testsuitexmlparser/TEST-org.apache.maven.surefire.test.FailingTest.xml" ); + + assertTrue( parser.isValid() ); + } + + +} 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 ba86030530..ca6c4699b7 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,120 +1,108 @@ -package org.apache.maven.surefire.report; - -import java.util.Collection; - -import junit.framework.TestCase; - -/* - * Copyright 2002-2009 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -public class RunStatisticsTest - extends TestCase -{ - private static final String DUMMY_ERROR_SOURCE = "dummy error source"; - - private static final String DUMMY_FAILURE_SOURCE = "dummy failure source"; - - private static final String DUMMY_MESSAGE = "dummy message"; - - public void testAddErrorSourceWithThrowableMessage() - { - RuntimeException throwable = new RuntimeException( DUMMY_MESSAGE ); - RunStatistics statistics = createRunStatisticsAndAddErrorSourceWithThrowable( throwable ); - assertRunStatisticsHasErrorSource( statistics, DUMMY_ERROR_SOURCE + ": " + DUMMY_MESSAGE ); - } - - public void testAddErrorSourceWithoutStackTraceWriter() - { - RunStatistics statistics = new RunStatistics(); - statistics.addErrorSource( DUMMY_ERROR_SOURCE, null ); - assertRunStatisticsHasErrorSource( statistics, DUMMY_ERROR_SOURCE ); - } - - public void testAddErrorSourceWithoutThrowable() - { - RunStatistics statistics = createRunStatisticsAndAddErrorSourceWithThrowable( null ); - assertRunStatisticsHasErrorSource( statistics, DUMMY_ERROR_SOURCE ); - } - - public void testAddErrorSourceWithThrowableWithoutMessage() - { - RuntimeException throwable = new RuntimeException(); - RunStatistics statistics = createRunStatisticsAndAddErrorSourceWithThrowable( throwable ); - assertRunStatisticsHasErrorSource( statistics, DUMMY_ERROR_SOURCE ); - } - - public void testAddFailureSourceWithThrowableMessage() - { - RuntimeException throwable = new RuntimeException( DUMMY_MESSAGE ); - RunStatistics statistics = createRunStatisticsAndAddFailureSourceWithThrowable( throwable ); - assertRunStatisticsHasFailureSource( statistics, DUMMY_FAILURE_SOURCE + ": " + DUMMY_MESSAGE ); - } - - public void testAddFailureSourceWithoutStackTraceWriter() - { - RunStatistics statistics = new RunStatistics(); - statistics.addFailureSource( DUMMY_FAILURE_SOURCE, null ); - assertRunStatisticsHasFailureSource( statistics, DUMMY_FAILURE_SOURCE ); - } - - public void testAddFailureSourceWithoutThrowable() - { - RunStatistics statistics = createRunStatisticsAndAddFailureSourceWithThrowable( null ); - assertRunStatisticsHasFailureSource( statistics, DUMMY_FAILURE_SOURCE ); - } - - public void testAddFailureSourceWithThrowableWithoutMessage() - { - RuntimeException throwable = new RuntimeException(); - RunStatistics statistics = createRunStatisticsAndAddFailureSourceWithThrowable( throwable ); - assertRunStatisticsHasFailureSource( statistics, DUMMY_FAILURE_SOURCE ); - } - - private RunStatistics createRunStatisticsAndAddErrorSourceWithThrowable( Throwable throwable ) - { - StackTraceWriter stackTraceWriter = new PojoStackTraceWriter( null, null, throwable ); - RunStatistics statistics = new RunStatistics(); - statistics.addErrorSource( DUMMY_ERROR_SOURCE, stackTraceWriter ); - - return statistics; - } - - private RunStatistics createRunStatisticsAndAddFailureSourceWithThrowable( Throwable throwable ) - { - StackTraceWriter stackTraceWriter = new PojoStackTraceWriter( null, null, throwable ); - RunStatistics statistics = new RunStatistics(); - statistics.addFailureSource( DUMMY_FAILURE_SOURCE, stackTraceWriter ); - - return statistics; - } - - private void assertRunStatisticsHasErrorSource( RunStatistics statistics, String expectedErrorSource ) - { - Collection errorSources = statistics.getErrorSources(); - assertNotNull( "No error sources.", errorSources ); - assertEquals( "Wrong number of error sources.", 1, errorSources.size() ); - assertEquals( "Wrong error sources.", expectedErrorSource, errorSources.iterator().next() ); - } - - private void assertRunStatisticsHasFailureSource( RunStatistics statistics, String expectedFailureSource ) - { - Collection failureSources = statistics.getFailureSources(); - assertNotNull( "No failure sources.", failureSources ); - assertEquals( "Wrong number of failure sources.", 1, failureSources.size() ); - assertEquals( "Wrong failure sources.", expectedFailureSource, failureSources.iterator().next() ); - } -} +package org.apache.maven.surefire.report; + +import java.util.Collection; + +import junit.framework.TestCase; + +/* + * Copyright 2002-2009 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +public class RunStatisticsTest + extends TestCase +{ + private static final String Method = "AClass#AMethod"; + + private static final String DUMMY_ERROR_SOURCE = Method + " RuntimeException"; + + private static final String DUMMY_FAILURE_SOURCE = "dummy failure source"; + + private static final String DUMMY_MESSAGE = "foo"; + + public void testAddErrorSourceWithThrowableMessage() + { + RuntimeException throwable = new RuntimeException( DUMMY_MESSAGE ); + RunStatistics statistics = createRunStatisticsAndAddErrorSourceWithThrowable( throwable ); + assertRunStatisticsHasErrorSource( statistics, DUMMY_ERROR_SOURCE + " " + DUMMY_MESSAGE ); + } + + public void testAddErrorSourceWithoutThrowable() + { + RunStatistics statistics = createRunStatisticsAndAddErrorSourceWithThrowable( null ); + assertRunStatisticsHasErrorSource( statistics, Method ); + } + + public void testAddErrorSourceWithThrowableWithoutMessage() + { + RuntimeException throwable = new RuntimeException(); + RunStatistics statistics = createRunStatisticsAndAddErrorSourceWithThrowable( throwable ); + assertRunStatisticsHasErrorSource( statistics, DUMMY_ERROR_SOURCE ); + } + + public void testAddFailureSourceWithThrowableMessage() + { + RuntimeException throwable = new RuntimeException( DUMMY_MESSAGE ); + RunStatistics statistics = createRunStatisticsAndAddFailureSourceWithThrowable( throwable ); + assertRunStatisticsHasFailureSource( statistics, DUMMY_ERROR_SOURCE + " " + DUMMY_MESSAGE ); + } + + public void testAddFailureSourceWithoutThrowable() + { + RunStatistics statistics = createRunStatisticsAndAddFailureSourceWithThrowable( null ); + assertRunStatisticsHasFailureSource( statistics, Method ); + } + + public void testAddFailureSourceWithThrowableWithoutMessage() + { + RuntimeException throwable = new RuntimeException(); + RunStatistics statistics = createRunStatisticsAndAddFailureSourceWithThrowable( throwable ); + assertRunStatisticsHasFailureSource( statistics, DUMMY_ERROR_SOURCE ); + } + + private RunStatistics createRunStatisticsAndAddErrorSourceWithThrowable( Throwable throwable ) + { + StackTraceWriter stackTraceWriter = new LegacyPojoStackTraceWriter( "AClass", "AMethod", throwable ); + RunStatistics statistics = new RunStatistics(); + statistics.addErrorSource( stackTraceWriter ); + + return statistics; + } + + private RunStatistics createRunStatisticsAndAddFailureSourceWithThrowable( Throwable throwable ) + { + StackTraceWriter stackTraceWriter = new LegacyPojoStackTraceWriter( "AClass", "AMethod", throwable ); + RunStatistics statistics = new RunStatistics(); + statistics.addFailureSource( stackTraceWriter ); + + return statistics; + } + + private void assertRunStatisticsHasErrorSource( RunStatistics statistics, String expectedErrorSource ) + { + Collection errorSources = statistics.getErrorSources(); + assertNotNull( "No error sources.", errorSources ); + assertEquals( "Wrong number of error sources.", 1, errorSources.size() ); + assertEquals( "Wrong error sources.", expectedErrorSource, errorSources.iterator().next() ); + } + + private void assertRunStatisticsHasFailureSource( RunStatistics statistics, String expectedFailureSource ) + { + Collection failureSources = statistics.getFailureSources(); + assertNotNull( "No failure sources.", failureSources ); + assertEquals( "Wrong number of failure sources.", 1, failureSources.size() ); + assertEquals( "Wrong failure sources.", expectedFailureSource, failureSources.iterator().next() ); + } +} diff --git a/maven-surefire-common/src/test/java/org/apache/maven/surefire/util/internal/TwoThreadBlockingQueueTest.java b/maven-surefire-common/src/test/java/org/apache/maven/surefire/util/internal/TwoThreadBlockingQueueTest.java deleted file mode 100644 index ba701604fb..0000000000 --- a/maven-surefire-common/src/test/java/org/apache/maven/surefire/util/internal/TwoThreadBlockingQueueTest.java +++ /dev/null @@ -1,182 +0,0 @@ -package org.apache.maven.surefire.util.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 java.util.ArrayList; -import java.util.LinkedList; -import java.util.List; -import java.util.concurrent.Callable; -import java.util.concurrent.FutureTask; -import java.util.concurrent.LinkedBlockingQueue; -import org.apache.maven.plugin.surefire.util.internal.BlockingQueue; -import org.apache.maven.plugin.surefire.util.internal.FunkyTwoThreadBlockingQueue; -import org.apache.maven.plugin.surefire.util.internal.TwoThreadBlockingQueue; - -import junit.framework.Assert; -import junit.framework.TestCase; - -/** - * @author Kristian Rosenvold - */ -public class TwoThreadBlockingQueueTest - extends TestCase -{ - final int num = 100000; - - public void testPut() - throws Exception - { - BlockingQueue twoThreadBlockingQueue = new TwoThreadBlockingQueue(); - - String[] items = generate( num ); - //long start = System.currentTimeMillis(); - for ( String item : items ) - { - twoThreadBlockingQueue.add( item ); - } - //long elapsed = System.currentTimeMillis() - start; - //System.out.println( "TwoThreadBlockingQueue insert " + num + " elements in = " + elapsed ); - System.gc(); - } - - public void testFunkyPut() - throws Exception - { - FunkyTwoThreadBlockingQueue twoThreadBlockingQueue = new FunkyTwoThreadBlockingQueue(); - - String[] items = generate( num ); - //long start = System.currentTimeMillis(); - for ( String item : items ) - { - twoThreadBlockingQueue.put( item ); - } - //long elapsed = System.currentTimeMillis() - start; - //System.out.println( "FunkyTwoThreadBlockingQueue insert " + num + " elements in = " + elapsed ); - System.gc(); - } - - - public void testPutAndTake() - throws Exception - { - final FunkyTwoThreadBlockingQueue twoThreadBlockingQueue = new FunkyTwoThreadBlockingQueue(); - - Callable consumer = new Callable() - { - public String call() - throws Exception - { - int num = 0; - String taken; - do - { - taken = twoThreadBlockingQueue.take(); - if ( taken != TwoThreadBlockingQueue.poison ) - { - Assert.assertEquals( "item" + num++, taken ); - } - } - while ( taken != TwoThreadBlockingQueue.poison ); - return taken; - } - }; - - FutureTask futureTask = new FutureTask( consumer ); - Thread thread = new Thread( futureTask ); - thread.start(); - - String[] items = generate( num ); - //long start = System.currentTimeMillis(); - for ( String item : items ) - { - twoThreadBlockingQueue.put( item ); - } - twoThreadBlockingQueue.put( TwoThreadBlockingQueue.poison ); - //long elapsed = System.currentTimeMillis() - start; - - futureTask.get(); - - // System.out.println( "TwoThreadBlockingQueue produced and taken " + num + " elements in = " + elapsed ); - System.gc(); - } - - public void testLBQPut() - throws Exception - { - LinkedBlockingQueue twoThreadBlockingQueue = new LinkedBlockingQueue(); - - String[] items = generate( num ); - //long start = System.currentTimeMillis(); - for ( String item : items ) - { - twoThreadBlockingQueue.put( item ); - } - //long elapsed = System.currentTimeMillis() - start; - //System.out.println( "LinkedBlockingQueue insert " + num + " elements in = " + elapsed ); - System.gc(); - } - - public void testArrayList() - throws Exception - { - List twoThreadBlockingQueue = new ArrayList( num ); - - String[] items = generate( num ); - //long start = System.currentTimeMillis(); - for ( String item : items ) - { - twoThreadBlockingQueue.add( item ); - } - //long elapsed = System.currentTimeMillis() - start; - //System.out.println( "ArrayList insert " + num + " elements in = " + elapsed ); - System.gc(); - } - - public void testLinkedList() - throws Exception - { - LinkedList twoThreadBlockingQueue = new LinkedList(); - - String[] items = generate( num ); - //long start = System.currentTimeMillis(); - for ( String item : items ) - { - twoThreadBlockingQueue.add( item ); - } - //long elapsed = System.currentTimeMillis() - start; - //System.out.println( "LinkedList insert " + num + " elements in = " + elapsed ); - System.gc(); - } - - public void testTake() - throws Exception - { - } - - String[] generate( int num ) - { - String[] result = new String[num]; - for ( int i = 0; i < num; i++ ) - { - result[i] = "item" + i; - } - return result; - } -} diff --git a/surefire-integration-tests/src/test/resources/fixture/testsuitexmlparser/TEST-org.apache.maven.surefire.test.FailingTest.xml b/maven-surefire-common/src/test/resources/fixture/testsuitexmlparser/TEST-org.apache.maven.surefire.test.FailingTest.xml similarity index 100% rename from surefire-integration-tests/src/test/resources/fixture/testsuitexmlparser/TEST-org.apache.maven.surefire.test.FailingTest.xml rename to maven-surefire-common/src/test/resources/fixture/testsuitexmlparser/TEST-org.apache.maven.surefire.test.FailingTest.xml diff --git a/surefire-integration-tests/src/test/resources/fixture/testsuitexmlparser/failsafe-summary-old.xml b/maven-surefire-common/src/test/resources/fixture/testsuitexmlparser/failsafe-summary-old.xml similarity index 100% rename from surefire-integration-tests/src/test/resources/fixture/testsuitexmlparser/failsafe-summary-old.xml rename to maven-surefire-common/src/test/resources/fixture/testsuitexmlparser/failsafe-summary-old.xml diff --git a/surefire-integration-tests/src/test/resources/fixture/testsuitexmlparser/failsafe-summary.xml b/maven-surefire-common/src/test/resources/fixture/testsuitexmlparser/failsafe-summary.xml similarity index 100% rename from surefire-integration-tests/src/test/resources/fixture/testsuitexmlparser/failsafe-summary.xml rename to maven-surefire-common/src/test/resources/fixture/testsuitexmlparser/failsafe-summary.xml diff --git a/maven-surefire-report-plugin/src/test/resources/test-reports/TEST-AntUnit.xml b/maven-surefire-common/src/test/resources/test-reports/TEST-AntUnit.xml similarity index 100% rename from maven-surefire-report-plugin/src/test/resources/test-reports/TEST-AntUnit.xml rename to maven-surefire-common/src/test/resources/test-reports/TEST-AntUnit.xml diff --git a/maven-surefire-report-plugin/src/test/resources/test-reports/TEST-NoPackageTest.xml b/maven-surefire-common/src/test/resources/test-reports/TEST-NoPackageTest.xml similarity index 100% rename from maven-surefire-report-plugin/src/test/resources/test-reports/TEST-NoPackageTest.xml rename to maven-surefire-common/src/test/resources/test-reports/TEST-NoPackageTest.xml diff --git a/maven-surefire-report-plugin/src/test/resources/test-reports/TEST-NoTimeTestCaseTest.xml b/maven-surefire-common/src/test/resources/test-reports/TEST-NoTimeTestCaseTest.xml similarity index 100% rename from maven-surefire-report-plugin/src/test/resources/test-reports/TEST-NoTimeTestCaseTest.xml rename to maven-surefire-common/src/test/resources/test-reports/TEST-NoTimeTestCaseTest.xml diff --git a/maven-surefire-report-plugin/src/test/resources/test-reports/TEST-classWithNoTests.NoMethodsTestCase.xml b/maven-surefire-common/src/test/resources/test-reports/TEST-classWithNoTests.NoMethodsTestCase.xml similarity index 100% rename from maven-surefire-report-plugin/src/test/resources/test-reports/TEST-classWithNoTests.NoMethodsTestCase.xml rename to maven-surefire-common/src/test/resources/test-reports/TEST-classWithNoTests.NoMethodsTestCase.xml diff --git a/maven-surefire-report-plugin/src/test/resources/test-reports/TEST-com.shape.CircleTest.xml b/maven-surefire-common/src/test/resources/test-reports/TEST-com.shape.CircleTest.xml similarity index 100% rename from maven-surefire-report-plugin/src/test/resources/test-reports/TEST-com.shape.CircleTest.xml rename to maven-surefire-common/src/test/resources/test-reports/TEST-com.shape.CircleTest.xml diff --git a/maven-surefire-report-plugin/src/test/resources/test-reports/TEST-com.shape.PointTest.xml b/maven-surefire-common/src/test/resources/test-reports/TEST-com.shape.PointTest.xml similarity index 100% rename from maven-surefire-report-plugin/src/test/resources/test-reports/TEST-com.shape.PointTest.xml rename to maven-surefire-common/src/test/resources/test-reports/TEST-com.shape.PointTest.xml diff --git a/maven-surefire-report-plugin/src/test/resources/test-reports/TEST-junit.twoTestCaseSuite.WrapperTestSuite.xml b/maven-surefire-common/src/test/resources/test-reports/TEST-junit.twoTestCaseSuite.WrapperTestSuite.xml similarity index 100% rename from maven-surefire-report-plugin/src/test/resources/test-reports/TEST-junit.twoTestCaseSuite.WrapperTestSuite.xml rename to maven-surefire-common/src/test/resources/test-reports/TEST-junit.twoTestCaseSuite.WrapperTestSuite.xml diff --git a/maven-surefire-report-plugin/src/test/resources/test-reports/com.shape.CircleTest.txt b/maven-surefire-common/src/test/resources/test-reports/com.shape.CircleTest.txt similarity index 100% rename from maven-surefire-report-plugin/src/test/resources/test-reports/com.shape.CircleTest.txt rename to maven-surefire-common/src/test/resources/test-reports/com.shape.CircleTest.txt diff --git a/maven-surefire-report-plugin/src/test/resources/test-reports/com.shapeclone.CircleTest.txt b/maven-surefire-common/src/test/resources/test-reports/com.shapeclone.CircleTest.txt similarity index 100% rename from maven-surefire-report-plugin/src/test/resources/test-reports/com.shapeclone.CircleTest.txt rename to maven-surefire-common/src/test/resources/test-reports/com.shapeclone.CircleTest.txt diff --git a/maven-surefire-plugin/pom.xml b/maven-surefire-plugin/pom.xml index 1208d39952..3524f9ec35 100644 --- a/maven-surefire-plugin/pom.xml +++ b/maven-surefire-plugin/pom.xml @@ -18,14 +18,13 @@ ~ under the License. --> - + 4.0.0 org.apache.maven.surefire surefire - 2.13-SNAPSHOT + 2.16-SNAPSHOT ../pom.xml @@ -35,80 +34,6 @@ Maven Surefire Plugin - - - - Maven User List - users-subscribe@maven.apache.org - users-unsubscribe@maven.apache.org - users@maven.apache.org - http://mail-archives.apache.org/mod_mbox/maven-users - - http://www.mail-archive.com/users@maven.apache.org/ - http://old.nabble.com/Maven---Users-f178.html - http://markmail.org/list/org.apache.maven.users - - - - Maven Developer List - dev-subscribe@maven.apache.org - dev-unsubscribe@maven.apache.org - dev@maven.apache.org - http://mail-archives.apache.org/mod_mbox/maven-dev - - http://www.mail-archive.com/dev@maven.apache.org/ - http://old.nabble.com/Maven-Developers-f179.html - http://markmail.org/list/org.apache.maven.dev - - - - Maven Commits List - commits-subscribe@maven.apache.org - commits-unsubscribe@maven.apache.org - http://mail-archives.apache.org/mod_mbox/maven-commits - - http://www.mail-archive.com/commits@maven.apache.org - http://old.nabble.com/Maven---Commits-f15575.html - http://markmail.org/list/org.apache.maven.commits - - - - - Maven Announcements List - announce@maven.apache.org - announce-subscribe@maven.apache.org - announce-unsubscribe@maven.apache.org - http://mail-archives.apache.org/mod_mbox/maven-announce/ - - http://www.mail-archive.com/announce@maven.apache.org - http://old.nabble.com/Maven-Announcements-f15617.html - http://markmail.org/list/org.apache.maven.announce - - - - Maven Issues List - issues-subscribe@maven.apache.org - issues-unsubscribe@maven.apache.org - http://mail-archives.apache.org/mod_mbox/maven-issues/ - - http://www.mail-archive.com/issues@maven.apache.org - http://old.nabble.com/Maven---Issues-f15573.html - http://markmail.org/list/org.apache.maven.issues - - - - Maven Notifications List - notifications-subscribe@maven.apache.org - notifications-unsubscribe@maven.apache.org - http://mail-archives.apache.org/mod_mbox/maven-notifications/ - - http://www.mail-archive.com/notifications@maven.apache.org - http://old.nabble.com/Maven---Notifications-f15574.html - http://markmail.org/list/org.apache.maven.notifications - - - - 2.0.9 @@ -172,10 +97,26 @@ org.apache.maven.surefire surefire-shadefire - ${project.version} + ${shadedVersion} + + maven-site-plugin + + + prepare-site-source + pre-site + + effective-site + + + ${basedir}/src/site + ${project.build.directory}/source-site/site.xml + + + + maven-assembly-plugin diff --git a/maven-surefire-plugin/src/assembly/site-source.xml b/maven-surefire-plugin/src/assembly/site-source.xml index 0c563ebd74..ff550c5afc 100644 --- a/maven-surefire-plugin/src/assembly/site-source.xml +++ b/maven-surefire-plugin/src/assembly/site-source.xml @@ -28,6 +28,15 @@ true ${basedir}/src/site + + site.xml + + false + / + + + true + ${project.build.directory}/source-site false / 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 7582ff9e4e..f0ac255039 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 @@ -61,7 +61,7 @@ public class SurefirePlugin * Specify this parameter to run individual tests by file name, overriding the includes/excludes * parameters. Each pattern you specify here will be used to create an include pattern formatted like * **/${test}.java, so you can just type "-Dtest=MyTest" to run a single test called - * "foo/MyTest.java".
+ * "foo/MyTest.java". The test patterns prefixed with a ! will be excluded.
* This parameter overrides the includes/excludes parameters, and the TestNG suiteXmlFiles * parameter. *

@@ -119,6 +119,24 @@ public class SurefirePlugin */ @Parameter( property = "surefire.timeout" ) private int forkedProcessTimeoutInSeconds; + + /** + * A list of <include> elements specifying the tests (by pattern) that should be included in testing. When not + * specified and when the test parameter is not specified, the default includes will be
+ * <includes>
+ *  <include>**/Test*.java</include>
+ *  <include>**/*Test.java</include>
+ *  <include>**/*TestCase.java</include>
+ * </includes>
+ *
+ *

+ * Each include item may also contain a comma-separated sublist of items, which will be treated as multiple + *  <include> entries.
+ *

+ * This parameter is ignored if the TestNG suiteXmlFiles parameter is specified. + */ + @Parameter + private List includes; /** * Option to pass dependencies to the system's classloader instead of using an isolated class loader when forking. @@ -262,37 +280,6 @@ public void setClassesDirectory( File classesDirectory ) this.classesDirectory = classesDirectory; } - - public List getClasspathDependencyExcludes() - { - return classpathDependencyExcludes; - } - - public void setClasspathDependencyExcludes( List classpathDependencyExcludes ) - { - this.classpathDependencyExcludes = classpathDependencyExcludes; - } - - public String getClasspathDependencyScopeExclude() - { - return classpathDependencyScopeExclude; - } - - public void setClasspathDependencyScopeExclude( String classpathDependencyScopeExclude ) - { - this.classpathDependencyScopeExclude = classpathDependencyScopeExclude; - } - - public List getAdditionalClasspathElements() - { - return additionalClasspathElements; - } - - public void setAdditionalClasspathElements( List additionalClasspathElements ) - { - this.additionalClasspathElements = additionalClasspathElements; - } - public File getReportsDirectory() { return reportsDirectory; @@ -444,5 +431,15 @@ public void setTest( String test ) this.test = test; } + @Override + public List getIncludes() + { + return includes; + } + @Override + public void setIncludes( List includes ) + { + this.includes = includes; + } } diff --git a/maven-surefire-plugin/src/site/apt/api.apt.vm b/maven-surefire-plugin/src/site/apt/api.apt.vm index 95c1a09cc6..31572c116e 100644 --- a/maven-surefire-plugin/src/site/apt/api.apt.vm +++ b/maven-surefire-plugin/src/site/apt/api.apt.vm @@ -1,11 +1,11 @@ ------- -Provider API ------- -Kristian Rosenvold ------- -2010-12-09 ------- - + ------ + Provider API + ------ + Kristian Rosenvold + ------ + 2010-12-09 + ------ + ~~ Licensed to the Apache Software Foundation (ASF) under one ~~ or more contributor license agreements. See the NOTICE file ~~ distributed with this work for additional information @@ -29,71 +29,64 @@ Kristian Rosenvold Maven Surefire Provider API -As of version 2.7 of surefire, there is a proposed public api available for -external providers to use surefire features. + As of version 2.7 of surefire, there is a proposed public api available for + external providers to use surefire features. -The key features of surefire are forking, reporting and directory/classpath scanning. -The remaining features are implemented in the providers. + The key features of surefire are forking, reporting and directory/classpath scanning. + The remaining features are implemented in the providers. -Please note that this API is still subject to change until otherwise declared, even in minor revisions. This would -mostly happen to facilitate needs in new providers. + Please note that this API is still subject to change until otherwise declared, even in minor revisions. This would + mostly happen to facilitate needs in new providers. * Requirements for a provider -There are three things any provider must fulfill: + There are three things any provider must fulfill: -* A provider must implement the << ->> interface. + * A provider must implement the <<>> interface. - * A provider contains a << - >> file entry named << - >> - ( as per {{{http://download.oracle.com/javase/6/docs/api/java/util/ServiceLoader.html}ServiceLoader}}). This - file - contains the name of the actual provider class. + * A provider contains a <<>> file entry named <<>> + ( as per {{{http://download.oracle.com/javase/6/docs/api/java/util/ServiceLoader.html}ServiceLoader}}). This file + contains the name of the actual provider class. - * The actual provider class contains a one-arg constructor that accepts an instance of - << - >>. This interface delivers all the surefire feature - to the provider implementation, please see the javadoc of this interface for options. + * The actual provider class contains a one-arg constructor that accepts an instance of + <<>>. This interface delivers all the surefire feature + to the provider implementation, please see the javadoc of this interface for options. - There are 4 well-known providers within surefire that are also implemented this way, so - examples can be found by looking at the surefire source code itself. surefire-junit47 is - the showcase implementation. + There are 4 well-known providers within surefire that are also implemented this way, so + examples can be found by looking at the surefire source code itself. surefire-junit47 is + the showcase implementation. - The javadoc on the intefaces mentioned in this article should otherwise be sufficient to write a provider. - Providers are added as dependencies to the surefire/failsafe plugins. + The javadoc on the intefaces mentioned in this article should otherwise be sufficient to write a provider. + Providers are added as dependencies to the surefire/failsafe plugins. - ** API Changes for 2.11 +** API Changes for 2.11 - Prior to 2.11, the provider would do + Prior to 2.11, the provider would do - +---+ - TestsToRun scanned = directoryScanner.locateTestClasses( testClassLoader, scannerFilter ); - +---+ ++---+ + TestsToRun scanned = directoryScanner.locateTestClasses( testClassLoader, scannerFilter ); ++---+ - and the classes would arrive in sorted order. In 2.11, an additional step must be implemented by the - provider; + and the classes would arrive in sorted order. In 2.11, an additional step must be implemented by the provider; - +---+ - TestsToRun scanned = directoryScanner.locateTestClasses( testClassLoader, scannerFilter ); - return providerParameters.getRunOrderCalculator().orderTestClasses( scanned ); - +---+ ++---+ + TestsToRun scanned = directoryScanner.locateTestClasses( testClassLoader, scannerFilter ); + return providerParameters.getRunOrderCalculator().orderTestClasses( scanned ); ++---+ - ** API changes for 2.12.2: +** API changes for 2.12.2: - Prior to this version, the provider would do + Prior to this version, the provider would do - +---+ - directoryScanner = booterParameters.getDirectoryScanner(); - final TestsToRun scanResult = directoryScanner.locateTestClasses( testClassLoader, testChecker ); - +---+ ++---+ + directoryScanner = booterParameters.getDirectoryScanner(); + final TestsToRun scanResult = directoryScanner.locateTestClasses( testClassLoader, testChecker ); ++---+ - from this version ProviderParameters#getDirectoryScanner has been deprecated, and *will* be removed - for the next major version. + from this version ProviderParameters#getDirectoryScanner has been deprecated, and *will* be removed + for the next major version. - +---+ - scanResult = booterParameters.getScanResult(); - final TestsToRun testsToRun = scanResult.applyFilter(testChecker, testClassLoader ); - +---+ ++---+ + scanResult = booterParameters.getScanResult(); + final TestsToRun testsToRun = scanResult.applyFilter(testChecker, testClassLoader ); ++---+ diff --git a/maven-surefire-plugin/src/site/apt/developing.apt.vm b/maven-surefire-plugin/src/site/apt/developing.apt.vm index 6a5012babf..954f0ce5ce 100644 --- a/maven-surefire-plugin/src/site/apt/developing.apt.vm +++ b/maven-surefire-plugin/src/site/apt/developing.apt.vm @@ -1,51 +1,51 @@ ------- -Developing surefire ------- -Kristian Rosenvold ------- -2011-03-07 ------- - -~~ Licensed to the Apache Software Foundation (ASF) under one -~~ or more contributor license agreements. See the NOTICE file -~~ distributed with this work for additional information -~~ regarding copyright ownership. The ASF licenses this file -~~ to you under the Apache License, Version 2.0 (the -~~ "License"); you may not use this file except in compliance -~~ with the License. You may obtain a copy of the License at -~~ -~~ http://www.apache.org/licenses/LICENSE-2.0 -~~ -~~ Unless required by applicable law or agreed to in writing, -~~ software distributed under the License is distributed on an -~~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -~~ KIND, either express or implied. See the License for the -~~ specific language governing permissions and limitations -~~ under the License. - -~~ NOTE: For help with the syntax of this file, see: -~~ http://maven.apache.org/doxia/references/apt-format.html + ------ + Developing surefire + ------ + Kristian Rosenvold + ------ + 2011-03-07 + ------ + + ~~ Licensed to the Apache Software Foundation (ASF) under one + ~~ or more contributor license agreements. See the NOTICE file + ~~ distributed with this work for additional information + ~~ regarding copyright ownership. The ASF licenses this file + ~~ to you under the Apache License, Version 2.0 (the + ~~ "License"); you may not use this file except in compliance + ~~ with the License. You may obtain a copy of the License at + ~~ + ~~ http://www.apache.org/licenses/LICENSE-2.0 + ~~ + ~~ Unless required by applicable law or agreed to in writing, + ~~ software distributed under the License is distributed on an + ~~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + ~~ KIND, either express or implied. See the License for the + ~~ specific language governing permissions and limitations + ~~ under the License. + + ~~ NOTE: For help with the syntax of this file, see: + ~~ http://maven.apache.org/doxia/references/apt-format.html Developer Center -When working with surefire, it is necessary to understand a few things: + When working with surefire, it is necessary to understand a few things: * Multi-Module project -The plugin is built as part of a multi-module plugin. The generated -'project information' will suggest that you check out (e.g.) -http://svn.apache.org/repos/asf/maven/surefire/trunk/${project.artifactId}. -In fact, you need to check out (e.g.) -http://svn.apache.org/repos/asf/maven/surefire/trunk and -build from there. + The plugin is built as part of a multi-module plugin. The generated + 'project information' will suggest that you check out (e.g.) + http://svn.apache.org/repos/asf/maven/surefire/trunk/${project.artifactId}. + In fact, you need to check out (e.g.) + http://svn.apache.org/repos/asf/maven/surefire/trunk and + build from there. * Making testcases for demonstrating problems -When reporting an issue, it is immensely useful to create a small sample project -that demonstrates the problem. Surefire already contains a large number of such -projects, and they can be found at -https://svn.apache.org/repos/asf/maven/surefire/trunk/surefire-integration-tests/src/test/resources/ -Typically you can check out one of the pre-existing projects and run it like this: + When reporting an issue, it is immensely useful to create a small sample project + that demonstrates the problem. Surefire already contains a large number of such + projects, and they can be found at + https://svn.apache.org/repos/asf/maven/surefire/trunk/surefire-integration-tests/src/test/resources/ + Typically you can check out one of the pre-existing projects and run it like this: +---+ svn co https://svn.apache.org/repos/asf/maven/surefire/trunk/surefire-integration-tests/src/test/resources/failsafe-buildfail @@ -55,34 +55,34 @@ mvn -Dsurefire.version=2.12 verify * Attaching a debugger -Sometimes it's appropriate to attach a remote debugger to the surefire fork to try to determine what -is /really/ going on. If you checkout & build trunk, you'd usually do something like this: + Sometimes it's appropriate to attach a remote debugger to the surefire fork to try to determine what + is /really/ going on. If you checkout & build trunk, you'd usually do something like this: +---+ -mvn -Dmaven.surefire.debug=true install + mvn -Dmaven.surefire.debug=true install +---+ -Load the source in your IDE, set a breakpoint at the start of ForkedBooter#main and attach -a debugger to port 5005. + Load the source in your IDE, set a breakpoint at the start of ForkedBooter#main and attach + a debugger to port 5005. * TestCases -All patches to surefire must contain test coverage, either as an integration test -or a unit test. All new features (changed/added plugin options) must be covered by -and end-to-end integration test. + All patches to surefire must contain test coverage, either as an integration test + or a unit test. All new features (changed/added plugin options) must be covered by + and end-to-end integration test. -There are -numerous other integration tests that all operate upon small sample projects in -surefire-integration-tests/src/test/resources + There are + numerous other integration tests that all operate upon small sample projects in + surefire-integration-tests/src/test/resources -Example integration tests are Surefire141PluggableProvidersIT and the corresponding -surefire-integration-tests/src/test/resources/surefire-141-pluggableproviders. + Example integration tests are Surefire141PluggableProvidersIT and the corresponding + surefire-integration-tests/src/test/resources/surefire-141-pluggableproviders. * Essential source code reading list -Some methods/classes reveal more about the basic working of a piece of code than others. The enclosed classes/methods -are a "reading list" for getting quickly acquainted with the code: + Some methods/classes reveal more about the basic working of a piece of code than others. The enclosed classes/methods + are a "reading list" for getting quickly acquainted with the code: +---+ AbstractSurefireMojo#executeAllProviders @@ -92,36 +92,36 @@ ForkedBooter#main * JDK Versions -The surefire booter is capable of booting all the way back to jdk1.3. Specifically -this means surefire-api, surefire-booter, common-junit3 and surefire-junit3 are -source/target 1.3. The plugin and several providers are 1.5. + The surefire booter is capable of booting all the way back to jdk1.3. Specifically + this means surefire-api, surefire-booter, common-junit3 and surefire-junit3 are + source/target 1.3. The plugin and several providers are 1.5. * Provider Isolation -Classes in the SUT (Subject Under Test), override any classes within the -surefire providers. This means providers using any -third party dependencies (other than the test framework itself), should -shade these classes to a different package. + Classes in the SUT (Subject Under Test), override any classes within the + surefire providers. This means providers using any + third party dependencies (other than the test framework itself), should + shade these classes to a different package. * Common provider modules -The surefire-providers module contains common-junitXX modules. These modules -depend on the XX version of JUnit and can access the JUnit API's at the correct -JUnit version level. Unit tests can also be written that will run with the -correct JUnit version. At build time, all of the relevant parts of these "common" -modules are just shaded into the providers jar files. + The surefire-providers module contains common-junitXX modules. These modules + depend on the XX version of JUnit and can access the JUnit API's at the correct + JUnit version level. Unit tests can also be written that will run with the + correct JUnit version. At build time, all of the relevant parts of these "common" + modules are just shaded into the providers jar files. * Shadefire -"Shadefire" is the first module to be run in the -surefire build. This creates as shaded version of the JUnit provider, and this provider -is thereafter used to build surefire itself (As of any release after 2.8). This is -because the SUT overrides the provider, and the shadefire provider has been -relocated to avoid this overriding when surefire is building itself. + "Shadefire" is the first module to be run in the + surefire build. This creates as shaded version of the JUnit provider, and this provider + is thereafter used to build surefire itself (As of any release after 2.8). This is + because the SUT overrides the provider, and the shadefire provider has been + relocated to avoid this overriding when surefire is building itself. * Deploying/releasing surefire -Surefire depends on a previous version of itself, which -is too advanced for maven 2.2.x dependency resolution, and maven 3.x is -required to build surefire \ No newline at end of file + Surefire depends on a previous version of itself, which + is too advanced for maven 2.2.x dependency resolution, and maven 3.x is + required to build surefire \ No newline at end of file diff --git a/maven-surefire-plugin/src/site/apt/examples/class-loading.apt.vm b/maven-surefire-plugin/src/site/apt/examples/class-loading.apt.vm index 719b524dca..dfa7e8ac81 100644 --- a/maven-surefire-plugin/src/site/apt/examples/class-loading.apt.vm +++ b/maven-surefire-plugin/src/site/apt/examples/class-loading.apt.vm @@ -1,252 +1,174 @@ ------- -Classloading and Forking ------- -Dan Fabulich ------- -2010-01-09 ------- - -~~ Licensed to the Apache Software Foundation (ASF) under one -~~ or more contributor license agreements. See the NOTICE file -~~ distributed with this work for additional information -~~ regarding copyright ownership. The ASF licenses this file -~~ to you under the Apache License, Version 2.0 (the -~~ "License"); you may not use this file except in compliance -~~ with the License. You may obtain a copy of the License at -~~ -~~ http://www.apache.org/licenses/LICENSE-2.0 -~~ -~~ Unless required by applicable law or agreed to in writing, -~~ software distributed under the License is distributed on an -~~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -~~ KIND, either express or implied. See the License for the -~~ specific language governing permissions and limitations -~~ under the License. - -~~ NOTE: For help with the syntax of this file, see: -~~ http://maven.apache.org/doxia/references/apt-format.html + ------ + Classloading and Forking + ------ + Dan Fabulich + ------ + 2010-01-09 + ------ + + ~~ Licensed to the Apache Software Foundation (ASF) under one + ~~ or more contributor license agreements. See the NOTICE file + ~~ distributed with this work for additional information + ~~ regarding copyright ownership. The ASF licenses this file + ~~ to you under the Apache License, Version 2.0 (the + ~~ "License"); you may not use this file except in compliance + ~~ with the License. You may obtain a copy of the License at + ~~ + ~~ http://www.apache.org/licenses/LICENSE-2.0 + ~~ + ~~ Unless required by applicable law or agreed to in writing, + ~~ software distributed under the License is distributed on an + ~~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + ~~ KIND, either express or implied. See the License for the + ~~ specific language governing permissions and limitations + ~~ under the License. + + ~~ NOTE: For help with the syntax of this file, see: + ~~ http://maven.apache.org/doxia/references/apt-format.html Classloading and Forking in Maven Surefire -This page discusses classloading and forking under Maven Surefire which is a shared component used by both -the Surefire and Failsafe Maven plugins, with an eye towards troubleshooting problems. + This page discusses classloading and forking under Maven Surefire which is a shared component used by both + the Surefire and Failsafe Maven plugins, with an eye towards troubleshooting problems. * Executive Summary -If you're having problems, you'll probably want to tinker with these three settings: << ->>, << - >>, and << - >>. - - * What problem does the Maven Surefire project solve? - - Initially, the problem seems simple enough. Just launch Java with a classpath, like this: - - +---+ - java -classpath foo.jar:bar.jar MyApp - +---+ - - But there's a problem here: on some operating systems (Windows), there's a limit on how long you can make - your command line, and therefore a limit on how long you can make your classpath. The limit is different - on different versions of Windows; in some versions only a few hundred characters are allowed, in others - a few thousand, but the limit can be pretty severe in either case. - - * Update for Maven Surefire 2.8.2 - - It turns out setting the << - >> as an environment variable may remove most of the - practical length limitations, as documented in - {{{http://jira.codehaus.org/browse/SUREFIRE-727}SUREFIRE-727}}. - This means most of the length-related problems in this article may be outdated. - - * How do people solve this problem in general? - - There are two "tricks" you can use to workaround this problem; both of them can cause other problems in - some cases. - - 1. < - >: One workaround is to use an isolated classloader. - Instead of launching MyApp directly, we can launch some other app (a "booter") - with a much shorter classpath. We can then create a new java.lang.ClassLoader - (usually a java.net.URLClassLoader) with your classpath configured. The booter - can then load up MyApp from the classloader; when MyApp refers to other classes, - they will be automatically loaded from our isolated classloader. - - The problem with using an isolated classloader is that your classpath isn't - correct, and some apps can detect this and object. For example, the - system property << - >> won't include your jars; if your app notices - this, it could cause a problem. - - There's another similar problem with using an isolated classloader: any class - may call the static method << - >> and attempt to - load classes out of that classloader, instead of using the default classloader. - Classes often do this if they need to create classloaders of their own. - Unfortunately, Java-based web application servers like Jetty, Tomcat, BEA - WebLogic and IBM WebSphere are very likely to try to escape the confines of an - isolated classloader. - - 2. < - >: Another workaround is to use a "manifest-only jar." In - this case, you create a temporary jar that's almost completely empty, except for - a META-INF/MANIFEST.MF file. Java manifests can contain attributes that the Java - VM will honor as directives; for example, you can have a "Class-Path" attribute, - which contains a list of other jars to add to the classpath. So then you can run - your code like this: - - +---+ - java -classpath booter.jar MyApp - +---+ - - This is a bit more realistic, because in this case the system classloader, the - thread context classloader and the default classloader are all the same; there's - no possibility of "escaping" the classloader. But this is still a weird - simulation of a "normal" classpath, and it's still possible for apps to notice - this. Again, << - >> may not be what you'd expect ("why does it contain - only one jar?"). Additionally, it's possible to query the system classloader to - get the list of jars back out of it; your app may be confused if it finds only - our << - >> there! - - * Advantages/Disadvantages of each solution - - If your app tries to interrogate its own classloader for a list of jars, it may - work better under an isolated classloader than it would with a manifest-only - jar. However, if your app tries to escape its default classloader, it may not - work under an isolated classloader at all. - - One advantage of using an isolated classloader is that it's the only way to use - an isolated classloader without forking a separate process, running all of the - tests in the same process as Maven itself. But that itself can be pretty risky, - especially if Maven is running embedded in your IDE! - - Finally, of course, you could just try to wire up a plain old Java classpath and - hope - it's short enough. The worst case there is that your classpath might work - on some machines and not others. Windows boxes would behave differently from - Linux boxes; users with short user names might have more success than users - with long user names, etc. For this reason, we chose not to make the basic - classpath the default, though we do provide it as an option (mostly as a last - resort). - - * What does Maven Surefire do? - - Surefire provides a mechanism for using multiple strategies. The main parameter - that - determines this is called << - >>. If << - >> is - << - >>, then we use a manifest-only JAR; otherwise, we use an isolated - classloader. If you want to use a basic plain old Java classpath, - you can set - << - >> which only has an effect when << - >>. - - The default value for << - >> changed between Surefire 2.3 and - Surefire 2.4, which was a pretty significant change. In Surefire - 2.3, - << - >> was << - >> by default, and we used an isolated classloader. - In Surefire 2.4, << - >> is << - >> by default. No value works for - everyone, but we think this default is an - improvement; a bunch of - hard-to-diagnose bugs get better when we << - >>. - - Unfortunately, if << - >> is set incorrectly for - your app, you're going to - have a problem on your hands that can be - quite difficult to diagnose. You might - even be forced to read a long doc page like - this one. ;-) - - If you're having problems loading classes, - try setting << - >> - to see if that helps. You can do that with - the POM snippet below, or by setting - <<<-Dsurefire.useSystemClassLoader=false>>>. - If that doesn't work, try setting - << - >> back to << - >> and setting << - >> to << - >>. - - +---+ - - [...] - - - - ${project.groupId} - ${project.artifactId} - ${project.version} - - - false - - - - - - [...] - - +---+ - - * Debugging Classpath - Problems - - If you've read this far, - you're probably fully - equipped to diagnose - problems that may occur - during classloading. Here's - some general tips to try: - - * Run mvn with --debug (aka - -X) to get more detailed - output - - * Check your << - >>. If << - >>, it's - impossible to use the - system classloader or a - plain old Java - classpath; we have to - use an isolated - classloader. - - * If you're using the - defaults, << - >> and << - >>. In that case, - look at the generated - manifest-only Surefire - booter JAR. Open it up - (it's just a zip) and - read its manifest. - - * Run mvn with - -Dmaven.${thisPlugin.toLowerCase()} - .debug, and attach to - the running process with - a debugger. \ No newline at end of file + If you're having problems, you'll probably want to tinker with these three settings: <<>>, <<>>, and <<>>. + +* What problem does the Maven Surefire project solve? + + Initially, the problem seems simple enough. Just launch Java with a classpath, like this: + ++---+ +java -classpath foo.jar:bar.jar MyApp ++---+ + + But there's a problem here: on some operating systems (Windows), there's a limit on how long you can make + your command line, and therefore a limit on how long you can make your classpath. The limit is different + on different versions of Windows; in some versions only a few hundred characters are allowed, in others + a few thousand, but the limit can be pretty severe in either case. + +* Update for Maven Surefire 2.8.2 + + It turns out setting the <<>> as an environment variable may remove most of the + practical length limitations, as documented in {{{http://jira.codehaus.org/browse/SUREFIRE-727}SUREFIRE-727}}. + This means most of the length-related problems in this article may be outdated. + +* How do people solve this problem in general? + + There are two "tricks" you can use to workaround this problem; both of them can cause other problems in some cases. + + 1. <>: One workaround is to use an isolated classloader. + Instead of launching MyApp directly, we can launch some other app (a "booter") + with a much shorter classpath. We can then create a new java.lang.ClassLoader + (usually a java.net.URLClassLoader) with your classpath configured. The booter + can then load up MyApp from the classloader; when MyApp refers to other classes, + they will be automatically loaded from our isolated classloader. + + The problem with using an isolated classloader is that your classpath isn't + correct, and some apps can detect this and object. For example, the + system property <<>> won't include your jars; if your app notices + this, it could cause a problem. + + There's another similar problem with using an isolated classloader: any class + may call the static method <<>> and attempt to + load classes out of that classloader, instead of using the default classloader. + Classes often do this if they need to create classloaders of their own. + Unfortunately, Java-based web application servers like Jetty, Tomcat, BEA + WebLogic and IBM WebSphere are very likely to try to escape the confines of an + isolated classloader. + + 2. <>: Another workaround is to use a "manifest-only jar." In + this case, you create a temporary jar that's almost completely empty, except for + a META-INF/MANIFEST.MF file. Java manifests can contain attributes that the Java + VM will honor as directives; for example, you can have a "Class-Path" attribute, + which contains a list of other jars to add to the classpath. So then you can run + your code like this: + ++---+ +java -classpath booter.jar MyApp ++---+ + + This is a bit more realistic, because in this case the system classloader, the + thread context classloader and the default classloader are all the same; there's + no possibility of "escaping" the classloader. But this is still a weird + simulation of a "normal" classpath, and it's still possible for apps to notice + this. Again, <<>> may not be what you'd expect ("why does it contain + only one jar?"). Additionally, it's possible to query the system classloader to + get the list of jars back out of it; your app may be confused if it finds only + our <<>> there! + +* Advantages/Disadvantages of each solution + + If your app tries to interrogate its own classloader for a list of jars, it may + work better under an isolated classloader than it would with a manifest-only + jar. However, if your app tries to escape its default classloader, it may not + work under an isolated classloader at all. + + One advantage of using an isolated classloader is that it's the only way to use + an isolated classloader without forking a separate process, running all of the + tests in the same process as Maven itself. But that itself can be pretty risky, + especially if Maven is running embedded in your IDE! + + Finally, of course, you could just try to wire up a plain old Java classpath and hope + it's short enough. The worst case there is that your classpath might work + on some machines and not others. Windows boxes would behave differently from + Linux boxes; users with short user names might have more success than users + with long user names, etc. For this reason, we chose not to make the basic + classpath the default, though we do provide it as an option (mostly as a last + resort). + +* What does Maven Surefire do? + + Surefire provides a mechanism for using multiple strategies. The main parameter that + determines this is called <<>>. If <<>> is + <<>>, then we use a manifest-only JAR; otherwise, we use an isolated + classloader. If you want to use a basic plain old Java classpath, you can set + <<>> which only has an effect when <<>>. + + The default value for <<>> changed between Surefire 2.3 and + Surefire 2.4, which was a pretty significant change. In Surefire 2.3, + <<>> was <<>> by default, and we used an isolated classloader. + In Surefire 2.4, <<>> is <<>> by default. No value works for + everyone, but we think this default is an improvement; a bunch of + hard-to-diagnose bugs get better when we <<>>. + + Unfortunately, if <<>> is set incorrectly for your app, you're going to + have a problem on your hands that can be quite difficult to diagnose. You might + even be forced to read a long doc page like this one. ;-) + + If you're having problems loading classes, try setting <<>> + to see if that helps. You can do that with the POM snippet below, or by setting + <<<-Dsurefire.useSystemClassLoader=false>>>. If that doesn't work, try setting + <<>> back to <<>> and setting <<>> to <<>>. + ++---+ + + [...] + + + + ${project.groupId} + ${project.artifactId} + ${project.version} + + false + + + + + [...] + ++---+ + +* Debugging Classpath Problems + + If you've read this far, you're probably fully equipped to diagnose problems that may occur during classloading. Here's some general tips to try: + + * Run mvn with --debug (aka -X) to get more detailed output + + * Check your <<>>. If <<>> (or <<>>, the deprecated version of that), it's impossible to use the system classloader or a plain old Java classpath; we have to use an isolated classloader. + + * If you're using the defaults, <<>> and <<>>. In that case, look at the generated manifest-only Surefire booter JAR. Open it up (it's just a zip) and read its manifest. + + * Run mvn with -Dmaven.${thisPlugin.toLowerCase()}.debug, and attach to the running process with a debugger. \ No newline at end of file diff --git a/maven-surefire-plugin/src/site/apt/examples/configuring-classpath.apt.vm b/maven-surefire-plugin/src/site/apt/examples/configuring-classpath.apt.vm index 2c425b986c..2b2ad4c191 100644 --- a/maven-surefire-plugin/src/site/apt/examples/configuring-classpath.apt.vm +++ b/maven-surefire-plugin/src/site/apt/examples/configuring-classpath.apt.vm @@ -1,146 +1,135 @@ ------- -Configuring the Classpath ------- -Pascal Lambert ------- -2010-01-09 ------- - -~~ Licensed to the Apache Software Foundation (ASF) under one -~~ or more contributor license agreements. See the NOTICE file -~~ distributed with this work for additional information -~~ regarding copyright ownership. The ASF licenses this file -~~ to you under the Apache License, Version 2.0 (the -~~ "License"); you may not use this file except in compliance -~~ with the License. You may obtain a copy of the License at -~~ -~~ http://www.apache.org/licenses/LICENSE-2.0 -~~ -~~ Unless required by applicable law or agreed to in writing, -~~ software distributed under the License is distributed on an -~~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -~~ KIND, either express or implied. See the License for the -~~ specific language governing permissions and limitations -~~ under the License. - -~~ NOTE: For help with the syntax of this file, see: -~~ http://maven.apache.org/doxia/references/apt-format.html + ------ + Configuring the Classpath + ------ + Pascal Lambert + ------ + 2010-01-09 + ------ + + ~~ Licensed to the Apache Software Foundation (ASF) under one + ~~ or more contributor license agreements. See the NOTICE file + ~~ distributed with this work for additional information + ~~ regarding copyright ownership. The ASF licenses this file + ~~ to you under the Apache License, Version 2.0 (the + ~~ "License"); you may not use this file except in compliance + ~~ with the License. You may obtain a copy of the License at + ~~ + ~~ http://www.apache.org/licenses/LICENSE-2.0 + ~~ + ~~ Unless required by applicable law or agreed to in writing, + ~~ software distributed under the License is distributed on an + ~~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + ~~ KIND, either express or implied. See the License for the + ~~ specific language governing permissions and limitations + ~~ under the License. + + ~~ NOTE: For help with the syntax of this file, see: + ~~ http://maven.apache.org/doxia/references/apt-format.html The Default Classpath -The surefire plugin builds the test classpath in the following order: + The surefire plugin builds the test classpath in the following order: #{if}(${project.artifactId}=="maven-surefire-plugin") -[[1]] The {{{../test-mojo.html#testClassesDirectory}test-classes}} directory + [[1]] The {{{../test-mojo.html#testClassesDirectory}test-classes}} directory -[[2]] The {{{../test-mojo.html#classesDirectory}classes}} directory + [[2]] The {{{../test-mojo.html#classesDirectory}classes}} directory #{else} -[[1]] The {{{../integration-test-mojo.html#testClassesDirectory}test-classes}} directory + [[1]] The {{{../integration-test-mojo.html#testClassesDirectory}test-classes}} directory -[[2]] The {{{../integration-test-mojo.html#classesDirectory}classes}} directory + [[2]] The {{{../integration-test-mojo.html#classesDirectory}classes}} directory #{end} -[[3]] The project dependencies + [[3]] The project dependencies -[[4]] Additional classpath elements + [[4]] Additional classpath elements Additional Classpath Elements -If you need to put more stuff in your classpath when ${thisPlugin} executes (e.g some funky resources or a container specific JAR), -we normally recommend you add it to your classpath as a dependency. Consider deploying shared jars to a private remote repository for your -organization. - -But, if you must, you can use the << ->> element to add custom resources/jars to your classpath. - This will be treated as an absolute file system path, so you may want use $\{basedir\} or another property combined - with a relative path. - Note that additional classpath elements are added to the end of the classpath, so you cannot use these to - override project dependencies or resources. - - +---+ - - [...] - - - - ${project.groupId} - ${project.artifactId} - ${project.version} - - - path/to/additional/resources - path/to/additional/jar - - - - - - [...] - - +---+ - - Removing Dependency Classpath Elements - - Dependencies can be removed from the test classpath using the parameters << - >> and - << - >>. A list of specific dependencies can be removed from the - classpath by specifying the groupId:artifactId to be removed. - - +---+ - - [...] - - - - ${project.groupId} - ${project.artifactId} - ${project.version} - - - org.apache.commons:commons-email - - - - - - - [...] - - +---+ - - Dependencies under a certain scope can be removed from the classpath using - << - >>. The valid values for the dependency scope - exclude are defined by << - >>. - - * < - > - system, provided, compile - - * < - > - compile, runtime - - * < - > - system, provided, compile, runtime, test - - +---+ - - [...] - - - - ${project.groupId} - ${project.artifactId} - ${project.version} - - runtime - - - - - - [...] - - +---+ + If you need to put more stuff in your classpath when ${thisPlugin} executes (e.g some funky resources or a container specific JAR), + we normally recommend you add it to your classpath as a dependency. Consider deploying shared jars to a private remote repository for your + organization. + + But, if you must, you can use the <<>> element to add custom resources/jars to your classpath. + This will be treated as an absolute file system path, so you may want use $\{basedir\} or another property combined with a relative path. + Note that additional classpath elements are added to the end of the classpath, so you cannot use these to + override project dependencies or resources. + ++---+ + + [...] + + + + ${project.groupId} + ${project.artifactId} + ${project.version} + + + path/to/additional/resources + path/to/additional/jar + + + + + + [...] + ++---+ + +Removing Dependency Classpath Elements + + Dependencies can be removed from the test classpath using the parameters <<>> and + <<>>. A list of specific dependencies can be removed from the + classpath by specifying the groupId:artifactId to be removed. + ++---+ + + [...] + + + + ${project.groupId} + ${project.artifactId} + ${project.version} + + + org.apache.commons:commons-email + + + + + + [...] + ++---+ + + Dependencies under a certain scope can be removed from the classpath using + <<>>. The valid values for the dependency scope + exclude are defined by <<>>. + + * <> - system, provided, compile + + * <> - compile, runtime + + * <> - system, provided, compile, runtime, test + ++---+ + + [...] + + + + ${project.groupId} + ${project.artifactId} + ${project.version} + + runtime + + + + + [...] + ++---+ diff --git a/maven-surefire-plugin/src/site/apt/examples/debugging.apt.vm b/maven-surefire-plugin/src/site/apt/examples/debugging.apt.vm index 9eba1480ae..6012e6c1fc 100644 --- a/maven-surefire-plugin/src/site/apt/examples/debugging.apt.vm +++ b/maven-surefire-plugin/src/site/apt/examples/debugging.apt.vm @@ -1,100 +1,92 @@ ------- -Debugging Tests ------- -Dan Fabulich ------- -2010-01-09 ------- - -~~ Licensed to the Apache Software Foundation (ASF) under one -~~ or more contributor license agreements. See the NOTICE file -~~ distributed with this work for additional information -~~ regarding copyright ownership. The ASF licenses this file -~~ to you under the Apache License, Version 2.0 (the -~~ "License"); you may not use this file except in compliance -~~ with the License. You may obtain a copy of the License at -~~ -~~ http://www.apache.org/licenses/LICENSE-2.0 -~~ -~~ Unless required by applicable law or agreed to in writing, -~~ software distributed under the License is distributed on an -~~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -~~ KIND, either express or implied. See the License for the -~~ specific language governing permissions and limitations -~~ under the License. - -~~ NOTE: For help with the syntax of this file, see: -~~ http://maven.apache.org/doxia/references/apt-format.html + ------ + Debugging Tests + ------ + Dan Fabulich + ------ + 2010-01-09 + ------ + + ~~ Licensed to the Apache Software Foundation (ASF) under one + ~~ or more contributor license agreements. See the NOTICE file + ~~ distributed with this work for additional information + ~~ regarding copyright ownership. The ASF licenses this file + ~~ to you under the Apache License, Version 2.0 (the + ~~ "License"); you may not use this file except in compliance + ~~ with the License. You may obtain a copy of the License at + ~~ + ~~ http://www.apache.org/licenses/LICENSE-2.0 + ~~ + ~~ Unless required by applicable law or agreed to in writing, + ~~ software distributed under the License is distributed on an + ~~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + ~~ KIND, either express or implied. See the License for the + ~~ specific language governing permissions and limitations + ~~ under the License. + + ~~ NOTE: For help with the syntax of this file, see: + ~~ http://maven.apache.org/doxia/references/apt-format.html Debugging Tests -Sometimes you need to debug the tests exactly as Maven ran them. Here's how! + Sometimes you need to debug the tests exactly as Maven ran them. Here's how! Forked Tests -By default, Maven runs your tests in a separate ("forked") process. You can use the << ->> property - to debug your forked tests remotely, like this: - - #{if}(${project.artifactId}=="maven-surefire-plugin") - +---+ - mvn -Dmaven.${thisPlugin.toLowerCase()}.debug test - +---+ - #{else} - +---+ - mvn -Dmaven.${thisPlugin.toLowerCase()}.debug verify - +---+ - #{end} - - The tests will automatically pause and await a remote debugger on port 5005. You can then attach to the running - tests - using Eclipse. You can setup a "Remote Java Application" launch configuration via the menu - command "Run" > "Open Debug Dialog..." - - If you need to configure a different port, you may pass a more detailed value. For example, the command below will - use port 8000 - instead of port 5005. - - #{if}(${project.artifactId}=="maven-surefire-plugin") - +---+ - mvn -Dmaven.surefire.debug="-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -Xnoagent - -Djava.compiler=NONE" test - +---+ - #{else} - +---+ - mvn -Dmaven.surefire.debug="-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -Xnoagent - -Djava.compiler=NONE" verify - +---+ - #{end} - - Non-forked Tests - - You can force Maven not to fork tests by configuring the << - >> configuration parameter. - - #{if}(${project.artifactId}=="maven-surefire-plugin") - +---+ - mvn -DforkMode=never test - +---+ - #{else} - +---+ - mvn -DforkMode=never verify - +---+ - #{end} - - Then all you need to do is debug Maven itself. Since Maven 2.0.8, Maven has shipped with a "mvnDebug" shell - script that you can - use to launch Maven with convenient debugging options: - - #{if}(${project.artifactId}=="maven-surefire-plugin") - +---+ - mvnDebug -DforkMode=never test - +---+ - #{else} - +---+ - mvnDebug -DforkMode=never verify - +---+ - #{end} - - Then you can attach Eclipse to Maven itself, which may be easier/more convenient than debugging the forked - executable. \ No newline at end of file + By default, Maven runs your tests in a separate ("forked") process. You can use the <<>> property + to debug your forked tests remotely, like this: + +#{if}(${project.artifactId}=="maven-surefire-plugin") ++---+ +mvn -Dmaven.${thisPlugin.toLowerCase()}.debug test ++---+ +#{else} ++---+ +mvn -Dmaven.${thisPlugin.toLowerCase()}.debug verify ++---+ +#{end} + + The tests will automatically pause and await a remote debugger on port 5005. You can then attach to the running tests + using Eclipse. You can setup a "Remote Java Application" launch configuration via the menu + command "Run" > "Open Debug Dialog..." + + If you need to configure a different port, you may pass a more detailed value. For example, the command below will use port 8000 + instead of port 5005. + +#{if}(${project.artifactId}=="maven-surefire-plugin") ++---+ +mvn -Dmaven.${thisPlugin.toLowerCase()}.debug="-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -Xnoagent -Djava.compiler=NONE" test ++---+ +#{else} ++---+ +mvn -Dmaven.${thisPlugin.toLowerCase()}.debug="-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -Xnoagent -Djava.compiler=NONE" verify ++---+ +#{end} + +Non-forked Tests + + You can force Maven not to fork tests by setting the configuration parameter <<>> to <0>. + +#{if}(${project.artifactId}=="maven-surefire-plugin") ++---+ +mvn -DforkCount=0 test ++---+ +#{else} ++---+ +mvn -DforkCount=0 verify ++---+ +#{end} + + Then all you need to do is debug Maven itself. Since Maven 2.0.8, Maven has shipped with a "mvnDebug" shell script that you can + use to launch Maven with convenient debugging options: + +#{if}(${project.artifactId}=="maven-surefire-plugin") ++---+ +mvnDebug -DforkCount=0 test ++---+ +#{else} ++---+ +mvnDebug -DforkCount=0 verify ++---+ +#{end} + + Then you can attach Eclipse to Maven itself, which may be easier/more convenient than debugging the forked executable. \ No newline at end of file diff --git a/maven-surefire-plugin/src/site/apt/examples/fork-options-and-parallel-execution.apt.vm b/maven-surefire-plugin/src/site/apt/examples/fork-options-and-parallel-execution.apt.vm new file mode 100644 index 0000000000..5e47b0dbbc --- /dev/null +++ b/maven-surefire-plugin/src/site/apt/examples/fork-options-and-parallel-execution.apt.vm @@ -0,0 +1,197 @@ + ------ + Fork Options and Parallel Test Execution + ------ + Andreas Gudian + ------ + 2013-01-03 + ------ + + ~~ Licensed to the Apache Software Foundation (ASF) under one + ~~ or more contributor license agreements. See the NOTICE file + ~~ distributed with this work for additional information + ~~ regarding copyright ownership. The ASF licenses this file + ~~ to you under the Apache License, Version 2.0 (the + ~~ "License"); you may not use this file except in compliance + ~~ with the License. You may obtain a copy of the License at + ~~ + ~~ http://www.apache.org/licenses/LICENSE-2.0 + ~~ + ~~ Unless required by applicable law or agreed to in writing, + ~~ software distributed under the License is distributed on an + ~~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + ~~ KIND, either express or implied. See the License for the + ~~ specific language governing permissions and limitations + ~~ under the License. + + ~~ NOTE: For help with the syntax of this file, see: + ~~ http://maven.apache.org/doxia/references/apt-format.html + +Fork Options and Parallel Test Execution + + Choosing the right forking strategy and parallel execution settings can have + substantial impact on the memory requirements and the execution time of your + build system. + + Surefire offers a variety of options to execute tests in parallel, allowing + you to make best use of the hardware at your disposal. But forking in + particular can also help keeping the memory requirements low. + + This page shall give you some ideas of how you can configure the test + execution in a way best suitable for your environment. + +* Parallel Test Execution + + Basically, there are two ways in Surefire to achieve parallel test execution. + The most obvious one is by using the <<>> parameter. The possible + values depend on the test provider used. For JUnit 4.7 and onwards, this may + be <<>>, <<>>, or <<>>. + + See the example pages for {{{./junit.html#Running_tests_in_parallel}JUnit}} + and {{{./testng.html#Running_tests_in_parallel}TestNG}} for details. + + The of the parallelism is configured using the parameters + <<>>, and optionally <<>>, or + <<>>. + + <> with the <<>> option is: the + concurrency happens within the same JVM process. That is efficient in terms of + memory and execution time, but you may be more vulnerable towards race + conditions or other unexpected and hard to reproduce behavior. + + The other possibility for parallel test execution is setting the parameter + <<>> to a value higher than 1. The next section covers the details + about this and the related <<>> property. + +* Parallel Surefire Execution in Multi-Module Maven Parallel Build + + Maven core allows building modules of multi-module projects in parallel with + the command line option <<<-T>>>. This the extent of concurrency + configured directly in Surefire. + +* Forked Test Execution + + The parameter <<>> defines the maximum number of JVM processes + that Surefire will spawn to execute the tests. It supports the + same syntax as <<<-T>>> in maven-core: if you termniate the value with a 'C', + that value will be multiplied with the number of available CPU cores in your + system. For example <<>> on a Quad-Core system will result + in forking up to ten concurrent JVM processes that execute tests. + + The parameter <<>> is used to define whether to terminate the + spawned process after one test class and to create a new process for the next + test in line (<<>>), or whether to reuse the processes to + execute the next tests (<<>>). + + The is <<>>/<<>>, which means + that Surefire creates one new JVM process to execute all tests in one maven + module. + + <<>>/<<>> executes each test class in its own + JVM process, one after another. It creates the highest level of separation for + the test execution, but it would probably also give you the longest execution + time of all the available options. Consider it as a last resort. + + With the <<>> property, you can specify additional parameters to be + passed to the forked JVM process, such as memory settings. System property + variables from the main maven process are passed to the forked process as + well. Additionally, you can use the element <<>> to + specify variables and values to be added to the system properties during the + test execution. + + You can use the place holder <<<$\{surefire.forkNumber\}>>> within + <<>>, or within the system properties (both those specified via + <<>> and via <<>>). Before executing + the tests, Surefire replaces that place holder by the number of the actually + executing process, counting from 1 to the effective value of <<>> + 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. + + In case forkig is disabled (<<>>), the place holder will be + replaced with <1>. + + The following is an example configuration that makes use of up to three forked + processes that execute the tests and then terminate. A system property + is passed to the processes, that shall specify the database + schema to use during the tests. The values for that will be + , , and for the three + processes. + ++---+ + +[...] + + ${project.groupId} + ${project.artifactId} + ${project.version} + + 3 + true + -Xmx1024m -XX:MaxPermSize=256m + + MY_TEST_SCHEMA_${surefire.forkNumber} + + + +[...] + ++---+ + + In case of a multi module project with tests in different modules, you could + also use, say, <<>> to start the build, yielding values for + <<<$\{surefire.forkNumber\}>>> ranging from 1 to 6. + + Imagine you execute some tests that use a JPA context, which has a notable + initial startup time. By setting <<>>, you can reuse that + context for consecutive tests. And as many tests tend to use and access the + same test data, you can avoid database locks during the concurrent execution + by using distinct but uniform database schemas. + + Port numbers and file names are other examples of resources for which it may + be hard or undesired to be shared among concurrent test executions. + +* Combining forkCount and parallel + + The modes <<>> and <<>>/<<>> can + be combined freely with the available settings for <<>>. + + As <<>> creates a new JVM process for each test class, + using <<>> would have no effect. You can still use + <<>>, though. + + When using <<>> and a <<>> value larger than one, + test classes are handed over to the forked process one-by-one. Thus, + <<>> would not change anything. However, you can use + <<>>: classes are executed in <<>> concurrent + processes, each of the processes can then use <<>> threads to + execute the methods of one class in parallel. + + Regarding the compatibility with multi-module parallel maven builds via + <<<-T>>>, the only limitation is that you can not use it together with + <<>>. + +* Migrating the Deprecated forkMode Parameter to forkCount and reuseForks + + Surefire versions prior 2.14 used the parameter <<>> to configure + forking. Although that parameter is still supported for backward + compatibility, users are strongly encouraged to migrate their configuration + and use <<>> and <<>> instead. + + The migration is quite simple, given the following mapping: + +*--------------------------+-------------------------------------------+ + <> | <> | +*--------------------------+-------------------------------------------+ + <<>> | <<>> (default), | + (default) | <<>> (default) | +*--------------------------+-------------------------------------------+ + <<>> | <<>> (default), | + | <<>> | +*--------------------------+-------------------------------------------+ + <<>> | <<>> | +*--------------------------+-------------------------------------------+ + <<>>, | <<>>, | + <<>> | (<<>>, if you did not | + | had that one set) | +*--------------------------+-------------------------------------------+ + diff --git a/maven-surefire-plugin/src/site/apt/examples/inclusion-exclusion.apt.vm b/maven-surefire-plugin/src/site/apt/examples/inclusion-exclusion.apt.vm index 172d64866a..4c7d9783d5 100644 --- a/maven-surefire-plugin/src/site/apt/examples/inclusion-exclusion.apt.vm +++ b/maven-surefire-plugin/src/site/apt/examples/inclusion-exclusion.apt.vm @@ -1,165 +1,164 @@ ------- -Inclusions and Exclusions of Tests ------- -Allan Ramirez ------- -2010-01-09 ------- - -~~ Licensed to the Apache Software Foundation (ASF) under one -~~ or more contributor license agreements. See the NOTICE file -~~ distributed with this work for additional information -~~ regarding copyright ownership. The ASF licenses this file -~~ to you under the Apache License, Version 2.0 (the -~~ "License"); you may not use this file except in compliance -~~ with the License. You may obtain a copy of the License at -~~ -~~ http://www.apache.org/licenses/LICENSE-2.0 -~~ -~~ Unless required by applicable law or agreed to in writing, -~~ software distributed under the License is distributed on an -~~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -~~ KIND, either express or implied. See the License for the -~~ specific language governing permissions and limitations -~~ under the License. - -~~ NOTE: For help with the syntax of this file, see: -~~ http://maven.apache.org/doxia/references/apt-format.html + ------ + Inclusions and Exclusions of Tests + ------ + Allan Ramirez + ------ + 2010-01-09 + ------ + + ~~ Licensed to the Apache Software Foundation (ASF) under one + ~~ or more contributor license agreements. See the NOTICE file + ~~ distributed with this work for additional information + ~~ regarding copyright ownership. The ASF licenses this file + ~~ to you under the Apache License, Version 2.0 (the + ~~ "License"); you may not use this file except in compliance + ~~ with the License. You may obtain a copy of the License at + ~~ + ~~ http://www.apache.org/licenses/LICENSE-2.0 + ~~ + ~~ Unless required by applicable law or agreed to in writing, + ~~ software distributed under the License is distributed on an + ~~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + ~~ KIND, either express or implied. See the License for the + ~~ specific language governing permissions and limitations + ~~ under the License. + + ~~ NOTE: For help with the syntax of this file, see: + ~~ http://maven.apache.org/doxia/references/apt-format.html Inclusions and Exclusions of Tests * Inclusions -By default, the ${thisPlugin} Plugin will automatically include all test classes -with the following wildcard patterns: + By default, the ${thisPlugin} Plugin will automatically include all test classes + with the following wildcard patterns: #{if}(${project.artifactId}=="maven-surefire-plugin") -* <<<"**/Test*.java">>> - includes all of its subdirectories and all java -filenames that start with "Test". + * <<<"**/Test*.java">>> - includes all of its subdirectories and all java + filenames that start with "Test". -* <<<"**/*Test.java">>> - includes all of its subdirectories and all java -filenames that end with "Test". + * <<<"**/*Test.java">>> - includes all of its subdirectories and all java + filenames that end with "Test". -* <<<"**/*TestCase.java">>> - includes all of its subdirectories and all java -filenames that end with "TestCase". + * <<<"**/*TestCase.java">>> - includes all of its subdirectories and all java + filenames that end with "TestCase". #{else} -* <<<"**/IT*.java">>> - includes all of its subdirectories and all java -filenames that start with "IT". + * <<<"**/IT*.java">>> - includes all of its subdirectories and all java + filenames that start with "IT". -* <<<"**/*IT.java">>> - includes all of its subdirectories and all java -filenames that end with "IT". + * <<<"**/*IT.java">>> - includes all of its subdirectories and all java + filenames that end with "IT". -* <<<"**/*ITCase.java">>> - includes all of its subdirectories and all java -filenames that end with "ITCase". + * <<<"**/*ITCase.java">>> - includes all of its subdirectories and all java + filenames that end with "ITCase". #{end} -[] + [] -If the test classes does not go with the naming convention, then configure -${thisPlugin} Plugin and specify the tests you want to include. + If the test classes does not go with the naming convention, then configure + ${thisPlugin} Plugin and specify the tests you want to include. +---+ - [...] - - - - ${project.groupId} - ${project.artifactId} - ${project.version} - - - Sample.java - - - - - - [...] + [...] + + + + ${project.groupId} + ${project.artifactId} + ${project.version} + + + Sample.java + + + + + + [...] +---+ * Exclusions -There are certain times when some tests are causing the build to fail. -Excluding them is one of the best workarounds to continue the build. -Exclusions can be done by configuring the < -> property of the - plugin. - - #{if}(${project.artifactId}=="maven-surefire-plugin") - +---+ - - [...] - - - - ${project.groupId} - ${project.artifactId} - ${project.version} - - - **/TestCircle.java - **/TestSquare.java - - - - - - [...] - - +---+ - #{else} - +---+ - - [...] - - - - ${project.groupId} - ${project.artifactId} - ${project.version} - - - **/CircleIT.java - **/SquareIT.java - - - - - - [...] - - +---+ - #{end} - - * Regular expression support - - An include/exclude pattern can be an ant-style path expression, but - regular expressions are also supported through this syntax: - - +---+ - - [...] - - - - ${project.groupId} - ${project.artifactId} - ${project.version} - - - %regex[.*[Cat|Dog].*Test.*] - - - - - - [...] - - +---+ - - Note the syntax %regex[expr], where expr is the actual expression and the rest is just wrapping. Also - note that regex matches are done over .class files and not .java files. \ No newline at end of file + There are certain times when some tests are causing the build to fail. + Excluding them is one of the best workarounds to continue the build. + Exclusions can be done by configuring the <> property of the + plugin. + +#{if}(${project.artifactId}=="maven-surefire-plugin") ++---+ + + [...] + + + + ${project.groupId} + ${project.artifactId} + ${project.version} + + + **/TestCircle.java + **/TestSquare.java + + + + + + [...] + ++---+ +#{else} ++---+ + + [...] + + + + ${project.groupId} + ${project.artifactId} + ${project.version} + + + **/CircleIT.java + **/SquareIT.java + + + + + + [...] + ++---+ +#{end} + +* Regular expression support + + An include/exclude pattern can be an ant-style path expression, but + regular expressions are also supported through this syntax: + ++---+ + + [...] + + + + ${project.groupId} + ${project.artifactId} + ${project.version} + + + %regex[.*[Cat|Dog].*Test.*] + + + + + + [...] + ++---+ + + Note the syntax %regex[expr], where expr is the actual expression and the rest is just wrapping. Also + note that regex matches are done over .class files and not .java files. \ No newline at end of file diff --git a/maven-surefire-plugin/src/site/apt/examples/junit.apt.vm b/maven-surefire-plugin/src/site/apt/examples/junit.apt.vm index b249606543..74e32cb1c0 100644 --- a/maven-surefire-plugin/src/site/apt/examples/junit.apt.vm +++ b/maven-surefire-plugin/src/site/apt/examples/junit.apt.vm @@ -1,285 +1,273 @@ ------- -Using JUnit ------- -Kristian Rosenvold - ------- -2010-10-10 ------- - -~~ Licensed to the Apache Software Foundation (ASF) under one -~~ or more contributor license agreements. See the NOTICE file -~~ distributed with this work for additional information -~~ regarding copyright ownership. The ASF licenses this file -~~ to you under the Apache License, Version 2.0 (the -~~ "License"); you may not use this file except in compliance -~~ with the License. You may obtain a copy of the License at -~~ -~~ http://www.apache.org/licenses/LICENSE-2.0 -~~ -~~ Unless required by applicable law or agreed to in writing, -~~ software distributed under the License is distributed on an -~~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -~~ KIND, either express or implied. See the License for the -~~ specific language governing permissions and limitations -~~ under the License. - -~~ NOTE: For help with the syntax of this file, see: -~~ http://maven.apache.org/doxia/references/apt-format.html + ------ + Using JUnit + ------ + Kristian Rosenvold + ------ + 2010-10-10 + ------ + + ~~ Licensed to the Apache Software Foundation (ASF) under one + ~~ or more contributor license agreements. See the NOTICE file + ~~ distributed with this work for additional information + ~~ regarding copyright ownership. The ASF licenses this file + ~~ to you under the Apache License, Version 2.0 (the + ~~ "License"); you may not use this file except in compliance + ~~ with the License. You may obtain a copy of the License at + ~~ + ~~ http://www.apache.org/licenses/LICENSE-2.0 + ~~ + ~~ Unless required by applicable law or agreed to in writing, + ~~ software distributed under the License is distributed on an + ~~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + ~~ KIND, either express or implied. See the License for the + ~~ specific language governing permissions and limitations + ~~ under the License. + + ~~ NOTE: For help with the syntax of this file, see: + ~~ http://maven.apache.org/doxia/references/apt-format.html Using JUnit * Configuring JUnit -To get started with JUnit, you need to add the required version of JUnit to your project: + To get started with JUnit, you need to add the required version of JUnit to your project: +---+ - [...] + [...] - junit - junit - 4.8.1 - test + junit + junit + 4.8.1 + test - [...] + [...] +---+ -This is the only step that is required to get started - you can now create tests in your test source directory -(eg, << ->>). + This is the only step that is required to get started - you can now create tests in your test source directory + (eg, <<>>). * Different Generations of JUnit support -Surefire supports three different generations of JUnit: JUnit 3.8.x, JUnit 4.x (serial provider) and JUnit 4.7 (junit-core provider -with parallel support). The provider is selected based on the JUnit version in your project and the configuration parameters (for parallel). + Surefire supports three different generations of JUnit: JUnit 3.8.x, JUnit 4.x (serial provider) and JUnit 4.7 (junit-core provider + with parallel support). The provider is selected based on the JUnit version in your project and the configuration parameters (for parallel). * Upgrade check for JUnit 4.x -As of Surefire version 2.7, the algorithm for choosing which tests to run -has changed. From 2.7 and on, only valid JUnit tests are run for all versions of JUnit, where older versions -of the plugin would also run invalid tests that satisfied the naming convention. + As of Surefire version 2.7, the algorithm for choosing which tests to run + has changed. From 2.7 and on, only valid JUnit tests are run for all versions of JUnit, where older versions + of the plugin would also run invalid tests that satisfied the naming convention. -When upgrading from a Surefire version prior to 2.7, the build can be run with -the flag -Dsurefire.junit4.upgradecheck. This will perform a check and notify you of any invalid tests that -will not be run with this version of Surefire (and the build fails). This is only meant to be used as a tool -when upgrading to check that all expected tests will be run. It is a transitional -feature that will be removed in a future version of surefire. + When upgrading from a Surefire version prior to 2.7, the build can be run with + the flag -Dsurefire.junit4.upgradecheck. This will perform a check and notify you of any invalid tests that + will not be run with this version of Surefire (and the build fails). This is only meant to be used as a tool + when upgrading to check that all expected tests will be run. It is a transitional + feature that will be removed in a future version of surefire. * How is the provider chosen ? -If nothing is configured, surefire detects which junit version to use by the following algorithm: + If nothing is configured, surefire detects which junit version to use by the following algorithm: +---+ if the JUnit version in the project >= 4.7 and the parallel attribute has ANY value -use junit47 provider + use junit47 provider if JUnit >= 4.0 is present -use junit4 provider + use junit4 provider else -use junit3.8.1 + use junit3.8.1 +---+ -Please note that the "else" part of this algorithm is also a FAQ response: + Please note that the "else" part of this algorithm is also a FAQ response: -You depend on the appropriate version of JUnit being present in the project dependencies, or surefire may choose the wrong -provider. If, for instance, one of your dependencies pulls in JUnit 3.8.1 you risk that surefire chooses the -3.8.1 provider, which will not support annotations or any of the 4.x features. + You depend on the appropriate version of JUnit being present in the project dependencies, or surefire may choose the wrong + provider. If, for instance, one of your dependencies pulls in JUnit 3.8.1 you risk that surefire chooses the + 3.8.1 provider, which will not support annotations or any of the 4.x features. -Use mvn dependency:tree, pom dependency ordering and/or and exclusion of transitive dependencies to fix this problem. + Use mvn dependency:tree, pom dependency ordering and/or and exclusion of transitive dependencies to fix this problem. ** Manually specifying a provider -You can also manually force a specific provider by adding it as a dependency to ${thisPlugin} itself: + You can also manually force a specific provider by adding it as a dependency to ${thisPlugin} itself: + ++---+ + +[...] + + ${project.groupId} + ${project.artifactId} + ${project.version} + + + org.apache.maven.surefire + surefire-junit47 + ${project.version} + + + +[...] + ++---+ + + When using this technique there is no check that the proper test-frameworks are present on your project's + classpath. Failing to add the proper test-frameworks will result in a build failure. + +* Running tests in parallel + + From JUnit 4.7 and onwards you can run your tests in parallel. To do this, you must set the + <<>> parameter, and may change the <<>> or <<>> attribute. + For example: +---+ [...] - + ${project.groupId} ${project.artifactId} ${project.version} - - - org.apache.maven.surefire - surefire-junit47 - ${project.version} - - - + + methods + 10 + + [...] +---+ -When using this technique there is no check that the proper test-frameworks are present on your project's -classpath. Failing to add the proper test-frameworks will result in a build failure. -* Running tests in parallel + If your tests specify any value for the "parallel" attribute and your project uses JUnit 4.7+, your request will be routed to + the concurrent JUnit provider, which uses the JUnit JUnitCore testrunner. + + This is particularly useful for slow tests that can have high concurrency. + + As of surefire 2.7, no additional dependencies are needed to use the full set of options with parallel. + + See also {{{./fork-options-and-parallel-execution.html}Fork Options and Parallel Test Execution}}. + +* Using custom listeners and reporters + + JUnit4/4.7 provider provides support for attaching custom RunListeners to your tests. + + You can configure multiple custom listeners like this: + ++---+ + +[...] + + ${project.groupId} + ${project.artifactId} + ${project.version} + + + + listener + com.mycompany.MyResultListener,com.mycompany.MyResultListener2 + + + +[...] + ++---+ + +* Using a security manager (JUnit3 only) + + As long as forkCount!=0 and you use JUnit3, you can run your tests with a java security manager active. + The classname of the security manager must be sent as a system property variable to the JUnit3 provider. + + JUnit4 uses mechanisms internally that are not compatible with the tested security managers and is not supported + by surefire. + ++---+ + +[...] + + ${project.groupId} + ${project.artifactId} + ${project.version} + + + java.lang.SecurityManager + + + +[...] + ++---+ + +* Using a security manager (All providers) + + Alternatively you can define a policy file that allows all providers to run with surefire + and send them using the argLine parameter and two system properties; + ++---+ + +[...] + + ${project.groupId} + ${project.artifactId} + ${project.version} + + -Djava.security.manager -Djava.security.policy=${basedir}/src/test/resources/java.policy + + +[...] + ++---+ + + The disadvantage of this solution is that the policy changes will affect the tests too, which make the + security environment less realistic. + +* Using JUnit Categories + + JUnit 4.8 introduced the notion of Categories. You can use JUnit categories by using the <<>> parameter. As long as + the JUnit version in the project is 4.8 or higher, the presence of the "groups" parameter will automatically make surefire select + the junit47 provider, which supports groups. + ++---+ + +[...] + + maven-surefire-plugin + 2.11 + + com.mycompany.SlowTests + + +[...] + ++---+ + + This will execute only those tests annotated with the <<<@Category(com.mycompany.SlowTests.class)>>> annotation and those tests + annotated with <<<@Category(com.mycompany.SlowerTests.class)>>> if class/interface <<>> is subclass of <<>>: + ++---+ + public interface SlowTests{} + public interface SlowerTests extends SlowTests{} ++---+ + ++---+ + public class AppTest { + @Test + @Category(com.mycompany.SlowTests.class) + public void testSlow() { + System.out.println("slow"); + } + + @Test + @Category(com.mycompany.SlowerTests.class) + public void testSlower() { + System.out.println("slower"); + } + + @Test + @Category(com.cmycompany.FastTests.class) + public void testSlow() { + System.out.println("fast"); + } + } ++---+ -From JUnit 4.7 and onwards you can run your tests in parallel. To do this, you must set the -<< ->> parameter, and may change the << - >> or << - >> attribute. - For example: - - +---+ - - [...] - - ${project.groupId} - ${project.artifactId} - ${project.version} - - methods - 10 - - - [...] - - +---+ - - - If your tests specify any value for the "parallel" attribute and your project uses JUnit 4.7+, your request - will be routed to - the concurrent JUnit provider, which uses the JUnit JUnitCore testrunner. - - This is particularly useful for slow tests that can have high concurrency. - - As of surefire 2.7, no additional dependencies are needed to use the full set of options with parallel. - - * Using custom listeners and reporters - - JUnit4/4.7 provider provides support for attaching custom RunListeners to your tests. - - You can configure multiple custom listeners like this: - - +---+ - - [...] - - ${project.groupId} - ${project.artifactId} - ${project.version} - - - - listener - com.mycompany.MyResultListener,com.mycompany.MyResultListener2 - - - - [...] - - +---+ - - * Using a security manager (JUnit3 only) - - As long as forkMode!=never and you use JUnit3, you can run your tests with a java security manager active. - The classname of the security manager must be sent as a system property variable to the JUnit3 provider. - - JUnit4 uses mechanisms internally that are not compatible with the tested security managers and is not - supported - by surefire. - - +---+ - - [...] - - ${project.groupId} - ${project.artifactId} - ${project.version} - - - java.lang.SecurityManager - - - - [...] - - +---+ - - * Using a security manager (All providers) - - Alternatively you can define a policy file that allows all providers to run with surefire - and send them using the argLine parameter and two system properties; - - +---+ - - [...] - - ${project.groupId} - ${project.artifactId} - ${project.version} - - -Djava.security.manager -Djava.security.policy=${basedir} - /src/test/resources/java.policy - - - - [...] - - +---+ - - The disadvantage of this solution is that the policy changes will affect the tests too, which make the - security environment less realistic. - - * Using JUnit Categories - - JUnit 4.8 introduced the notion of Categories. You can use JUnit categories by using the << - >> parameter. As long as - the JUnit version in the project is 4.8 or higher, the presence of the "groups" parameter will - automatically make surefire select - the junit47 provider, which supports groups. - - +---+ - - [...] - - maven-surefire-plugin - 2.11 - - com.mycompany.SlowTests - - - [...] - - +---+ - - This will execute only those tests annotated with the <<<@Category(com.mycompany.SlowTests.class)>>> - annotation and those tests - annotated with <<<@Category(com.mycompany.SlowerTests.class)>>> if class/interface << - >> is subclass of << - >>: - - +---+ - public interface SlowTests{} - public interface SlowerTests extends SlowTests{} - +---+ - - +---+ - public class AppTest { - @Test - @Category(com.mycompany.SlowTests.class) - public void testSlow() { - System.out.println("slow"); - } - - @Test - @Category(com.mycompany.SlowerTests.class) - public void testSlower() { - System.out.println("slower"); - } - - @Test - @Category(com.cmycompany.FastTests.class) - public void testSlow() { - System.out.println("fast"); - } - } - +---+ - - The @Category annotation can also be applied at class-level. - - For more information on JUnit, see the {{{http://www.junit.org}JUnit web site}}. + The @Category annotation can also be applied at class-level. + + For more information on JUnit, see the {{{http://www.junit.org}JUnit web site}}. diff --git a/maven-surefire-plugin/src/site/apt/examples/pojo-test.apt.vm b/maven-surefire-plugin/src/site/apt/examples/pojo-test.apt.vm index 4ebfe9e3d1..1d2661e6f6 100644 --- a/maven-surefire-plugin/src/site/apt/examples/pojo-test.apt.vm +++ b/maven-surefire-plugin/src/site/apt/examples/pojo-test.apt.vm @@ -1,54 +1,50 @@ ------- -Using POJO tests ------- -Christian Gruber ------- -May 2008 ------- - -~~ Licensed to the Apache Software Foundation (ASF) under one -~~ or more contributor license agreements. See the NOTICE file -~~ distributed with this work for additional information -~~ regarding copyright ownership. The ASF licenses this file -~~ to you under the Apache License, Version 2.0 (the -~~ "License"); you may not use this file except in compliance -~~ with the License. You may obtain a copy of the License at -~~ -~~ http://www.apache.org/licenses/LICENSE-2.0 -~~ -~~ Unless required by applicable law or agreed to in writing, -~~ software distributed under the License is distributed on an -~~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -~~ KIND, either express or implied. See the License for the -~~ specific language governing permissions and limitations -~~ under the License. - -~~ NOTE: For help with the syntax of this file, see: -~~ http://maven.apache.org/doxia/references/apt-format.html + ------ + Using POJO tests + ------ + Christian Gruber + ------ + May 2008 + ------ + + ~~ Licensed to the Apache Software Foundation (ASF) under one + ~~ or more contributor license agreements. See the NOTICE file + ~~ distributed with this work for additional information + ~~ regarding copyright ownership. The ASF licenses this file + ~~ to you under the Apache License, Version 2.0 (the + ~~ "License"); you may not use this file except in compliance + ~~ with the License. You may obtain a copy of the License at + ~~ + ~~ http://www.apache.org/licenses/LICENSE-2.0 + ~~ + ~~ Unless required by applicable law or agreed to in writing, + ~~ software distributed under the License is distributed on an + ~~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + ~~ KIND, either express or implied. See the License for the + ~~ specific language governing permissions and limitations + ~~ under the License. + + ~~ NOTE: For help with the syntax of this file, see: + ~~ http://maven.apache.org/doxia/references/apt-format.html Defining a POJO Test -POJO tests look very much like JUnit or TestNG tests, though they do not -require dependencies on these artifacts. A test class should be named -<<<**/*Test>>> and should contain << ->> methods which will each be -executed by surefire. - -Validating assertions can be done using the JDK 1.4 << ->> keyword. - Simultaneous test execution is not possible with POJO tests. - - Fixture can be setup before and after each << - >> method by implementing - a set-up and a tear-down method. These methods must match these signatures - to be recognized and executed before and after each test method. - - +---+ - public void setUp(); - public void tearDown(); - +---+ - - These fixture methods can also throw any exception and will still be valid. + POJO tests look very much like JUnit or TestNG tests, though they do not + require dependencies on these artifacts. A test class should be named + <<<**/*Test>>> and should contain <<>> methods which will each be + executed by surefire. + + Validating assertions can be done using the JDK 1.4 <<>> keyword. + Simultaneous test execution is not possible with POJO tests. + + Fixture can be setup before and after each <<>> method by implementing + a set-up and a tear-down method. These methods must match these signatures + to be recognized and executed before and after each test method. + ++---+ +public void setUp(); +public void tearDown(); ++---+ + + These fixture methods can also throw any exception and will still be valid. \ No newline at end of file diff --git a/maven-surefire-plugin/src/site/apt/examples/providers.apt.vm b/maven-surefire-plugin/src/site/apt/examples/providers.apt.vm index dd595f4d2e..39eff4d896 100644 --- a/maven-surefire-plugin/src/site/apt/examples/providers.apt.vm +++ b/maven-surefire-plugin/src/site/apt/examples/providers.apt.vm @@ -1,65 +1,64 @@ ------- -Selecting providers ------- -Kristian Rosenvold - ------- -2010-12-04 ------- - -~~ Licensed to the Apache Software Foundation (ASF) under one -~~ or more contributor license agreements. See the NOTICE file -~~ distributed with this work for additional information -~~ regarding copyright ownership. The ASF licenses this file -~~ to you under the Apache License, Version 2.0 (the -~~ "License"); you may not use this file except in compliance -~~ with the License. You may obtain a copy of the License at -~~ -~~ http://www.apache.org/licenses/LICENSE-2.0 -~~ -~~ Unless required by applicable law or agreed to in writing, -~~ software distributed under the License is distributed on an -~~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -~~ KIND, either express or implied. See the License for the -~~ specific language governing permissions and limitations -~~ under the License. + ------ + Selecting providers + ------ + Kristian Rosenvold + ------ + 2010-12-04 + ------ + + ~~ Licensed to the Apache Software Foundation (ASF) under one + ~~ or more contributor license agreements. See the NOTICE file + ~~ distributed with this work for additional information + ~~ regarding copyright ownership. The ASF licenses this file + ~~ to you under the Apache License, Version 2.0 (the + ~~ "License"); you may not use this file except in compliance + ~~ with the License. You may obtain a copy of the License at + ~~ + ~~ http://www.apache.org/licenses/LICENSE-2.0 + ~~ + ~~ Unless required by applicable law or agreed to in writing, + ~~ software distributed under the License is distributed on an + ~~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + ~~ KIND, either express or implied. See the License for the + ~~ specific language governing permissions and limitations + ~~ under the License. -~~ NOTE: For help with the syntax of this file, see: -~~ http://maven.apache.org/doxia/references/apt-format.html + ~~ NOTE: For help with the syntax of this file, see: + ~~ http://maven.apache.org/doxia/references/apt-format.html Selecting providers * Selecting a provider -Surefire normally automatically selects which test-framework provider to use based on the version of -TestNG/JUnit present in your project's classpath. In some cases it may be desirable to manually -override such a selection. This can be done by adding the required provider as a dependency to -the surefire-plugin. + Surefire normally automatically selects which test-framework provider to use based on the version of + TestNG/JUnit present in your project's classpath. In some cases it may be desirable to manually + override such a selection. This can be done by adding the required provider as a dependency to + the surefire-plugin. -The following example shows how to force the junit 4.7 provider: + The following example shows how to force the junit 4.7 provider: +---+ - [...] - - ${project.groupId} - ${project.artifactId} + [...] + + ${project.groupId} + ${project.artifactId} + ${project.version} + + + org.apache.maven.surefire + surefire-junit47 ${project.version} - - - org.apache.maven.surefire - surefire-junit47 - ${project.version} - - - - [...] + + + + [...] +---+ -The providers supplied with surefire are surefire-junit3, surefire-junit4, surefire-junit47 and surefire-testng. -Please note that forcing a provider still requires that the test framework is properly set up on your project classpath. + The providers supplied with surefire are surefire-junit3, surefire-junit4, surefire-junit47 and surefire-testng. + Please note that forcing a provider still requires that the test framework is properly set up on your project classpath. -You can also specify multiple providers as dependencies, and they will all be run and produce a common report. -This may be especially handy with external providers, since there are few use-cases for combining the included providers. + You can also specify multiple providers as dependencies, and they will all be run and produce a common report. + This may be especially handy with external providers, since there are few use-cases for combining the included providers. diff --git a/maven-surefire-plugin/src/site/apt/examples/single-test.apt.vm b/maven-surefire-plugin/src/site/apt/examples/single-test.apt.vm index d228673089..b67897f1ff 100644 --- a/maven-surefire-plugin/src/site/apt/examples/single-test.apt.vm +++ b/maven-surefire-plugin/src/site/apt/examples/single-test.apt.vm @@ -1,122 +1,116 @@ ------- -Running a Single Test ------- -Allan Ramirez -Olivier Lamy ------- -2012-02-28 ------- - -~~ Licensed to the Apache Software Foundation (ASF) under one -~~ or more contributor license agreements. See the NOTICE file -~~ distributed with this work for additional information -~~ regarding copyright ownership. The ASF licenses this file -~~ to you under the Apache License, Version 2.0 (the -~~ "License"); you may not use this file except in compliance -~~ with the License. You may obtain a copy of the License at -~~ -~~ http://www.apache.org/licenses/LICENSE-2.0 -~~ -~~ Unless required by applicable law or agreed to in writing, -~~ software distributed under the License is distributed on an -~~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -~~ KIND, either express or implied. See the License for the -~~ specific language governing permissions and limitations -~~ under the License. - -~~ NOTE: For help with the syntax of this file, see: -~~ http://maven.apache.org/doxia/references/apt-format.html + ------ + Running a Single Test + ------ + Allan Ramirez + Olivier Lamy + ------ + 2012-02-28 + ------ + + ~~ Licensed to the Apache Software Foundation (ASF) under one + ~~ or more contributor license agreements. See the NOTICE file + ~~ distributed with this work for additional information + ~~ regarding copyright ownership. The ASF licenses this file + ~~ to you under the Apache License, Version 2.0 (the + ~~ "License"); you may not use this file except in compliance + ~~ with the License. You may obtain a copy of the License at + ~~ + ~~ http://www.apache.org/licenses/LICENSE-2.0 + ~~ + ~~ Unless required by applicable law or agreed to in writing, + ~~ software distributed under the License is distributed on an + ~~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + ~~ KIND, either express or implied. See the License for the + ~~ specific language governing permissions and limitations + ~~ under the License. + + ~~ NOTE: For help with the syntax of this file, see: + ~~ http://maven.apache.org/doxia/references/apt-format.html Running a Single Test #{if}(${project.artifactId}=="maven-surefire-plugin") -During development, you may run a single test class repeatedly. To run this -through Maven, set the << ->> property to a specific test case. + During development, you may run a single test class repeatedly. To run this + through Maven, set the <<>> property to a specific test case. - +---+ - mvn -Dtest=TestCircle test - +---+ ++---+ +mvn -Dtest=TestCircle test ++---+ - The value for the << ->> parameter is the name of the test class (without the extension; we'll strip off the extension if you - accidentally provide one). + The value for the <<>> parameter is the name of the test class (without the extension; we'll strip off the extension if you accidentally provide one). #{else} - During development, you may run a single test class repeatedly. To run this - through Maven, set the << ->> property to a specific test case. + During development, you may run a single test class repeatedly. To run this + through Maven, set the <<>> property to a specific test case. - +---+ - mvn -Dit.test=ITCircle verify - +---+ ++---+ +mvn -Dit.test=ITCircle verify ++---+ - The value for the << ->> parameter is the name of the test class (without the extension; we'll strip off the extension if you - accidentally provide one). + The value for the <<>> parameter is the name of the test class (without the extension; we'll strip off the extension if you accidentally provide one). #{end} - You may also use patterns to run a number of tests: + You may also use patterns to run a number of tests: #{if}(${project.artifactId}=="maven-surefire-plugin") - +---+ - mvn -Dtest=TestCi*le test - +---+ ++---+ +mvn -Dtest=TestCi*le test ++---+ #{else} - +---+ - mvn -Dit.test=ITCi*le verify - +---+ ++---+ +mvn -Dit.test=ITCi*le verify ++---+ #{end} - And you may use multiple names/patterns, separated by commas: + And you may use multiple names/patterns, separated by commas: #{if}(${project.artifactId}=="maven-surefire-plugin") - +---+ - mvn -Dtest=TestSquare,TestCi*le test - +---+ ++---+ +mvn -Dtest=TestSquare,TestCi*le test ++---+ #{else} - +---+ - mvn -Dit.test=ITSquare,ITCi*le verify - +---+ ++---+ +mvn -Dit.test=ITSquare,ITCi*le verify ++---+ #{end} - Running a set of methods in a Single Test Class - - With version 2.7.3, you can run only n tests in a single Test Class. - - << NOTE : it's supported for junit 4.x and TestNG. >> - - You must use the following syntax +Running a set of methods in a Single Test Class + With version 2.7.3, you can run only n tests in a single Test Class. + + << NOTE : it's supported for junit 4.x and TestNG. >> + + You must use the following syntax + #{if}(${project.artifactId}=="maven-surefire-plugin") - +---+ - mvn -Dtest=TestCircle#mytest test - +---+ ++---+ +mvn -Dtest=TestCircle#mytest test ++---+ #{else} - +---+ - mvn -Dit.test=ITCircle#mytest verify - +---+ ++---+ +mvn -Dit.test=ITCircle#mytest verify ++---+ #{end} - You can use patterns too - + You can use patterns too + #{if}(${project.artifactId}=="maven-surefire-plugin") - +---+ - mvn -Dtest=TestCircle#test* test - +---+ ++---+ +mvn -Dtest=TestCircle#test* test ++---+ #{else} - +---+ - mvn -Dit.test=ITCircle#test* verify - +---+ ++---+ +mvn -Dit.test=ITCircle#test* verify ++---+ #{end} - As of surefire 2.12.1, you can select multiple methods (JUnit4X only at this time, patches welcome) + As of surefire 2.12.1, you can select multiple methods (JUnit4X only at this time, patches welcome) #{if}(${project.artifactId}=="maven-surefire-plugin") - +---+ - mvn -Dtest=TestCircle#testOne+testTwo test - +---+ ++---+ +mvn -Dtest=TestCircle#testOne+testTwo test ++---+ #{else} - +---+ - mvn -Dit.test=ITCircle#test* verify - +---+ ++---+ +mvn -Dit.test=ITCircle#test* verify ++---+ #{end} diff --git a/maven-surefire-plugin/src/site/apt/examples/skipping-test.apt.vm b/maven-surefire-plugin/src/site/apt/examples/skipping-test.apt.vm index 85a0d1f035..ff8584f73e 100644 --- a/maven-surefire-plugin/src/site/apt/examples/skipping-test.apt.vm +++ b/maven-surefire-plugin/src/site/apt/examples/skipping-test.apt.vm @@ -1,118 +1,112 @@ ------- -Skipping Test ------- -Johnny Ruiz -Brett Porter -Allan Ramirez ------- -July 2006 ------- - -~~ Licensed to the Apache Software Foundation (ASF) under one -~~ or more contributor license agreements. See the NOTICE file -~~ distributed with this work for additional information -~~ regarding copyright ownership. The ASF licenses this file -~~ to you under the Apache License, Version 2.0 (the -~~ "License"); you may not use this file except in compliance -~~ with the License. You may obtain a copy of the License at -~~ -~~ http://www.apache.org/licenses/LICENSE-2.0 -~~ -~~ Unless required by applicable law or agreed to in writing, -~~ software distributed under the License is distributed on an -~~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -~~ KIND, either express or implied. See the License for the -~~ specific language governing permissions and limitations -~~ under the License. - -~~ NOTE: For help with the syntax of this file, see: -~~ http://maven.apache.org/doxia/references/apt-format.html + ------ + Skipping Test + ------ + Johnny Ruiz + Brett Porter + Allan Ramirez + ------ + July 2006 + ------ + + ~~ Licensed to the Apache Software Foundation (ASF) under one + ~~ or more contributor license agreements. See the NOTICE file + ~~ distributed with this work for additional information + ~~ regarding copyright ownership. The ASF licenses this file + ~~ to you under the Apache License, Version 2.0 (the + ~~ "License"); you may not use this file except in compliance + ~~ with the License. You may obtain a copy of the License at + ~~ + ~~ http://www.apache.org/licenses/LICENSE-2.0 + ~~ + ~~ Unless required by applicable law or agreed to in writing, + ~~ software distributed under the License is distributed on an + ~~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + ~~ KIND, either express or implied. See the License for the + ~~ specific language governing permissions and limitations + ~~ under the License. + + ~~ NOTE: For help with the syntax of this file, see: + ~~ http://maven.apache.org/doxia/references/apt-format.html Skipping Tests -To skip running the tests for a particular project, set the < -> - property to < - >. - - +---+ - - [...] - - - - ${project.groupId} - ${project.artifactId} - ${project.version} - - true - - - - - [...] - - +---+ - - You can also skip the tests via command line by executing the following command: - - +---+ - mvn install -DskipTests - +---+ - - #{if}(${project.artifactId}=="maven-failsafe-plugin") - Since << - >> is also followed by the ${thatPlugin} Plugin, this will have the effect - of not running any tests. If, instead, you want to skip only the integration tests - being run by the ${thisPlugin} Plugin, you would use the << - >> property - - +---+ - mvn install -DskipITs - +---+ - - #{end} - If you absolutely must, you can also use the << - >> property to skip compiling the tests. - << - >> is honored by Surefire, Failsafe and the Compiler Plugin. - - +---+ - mvn install -Dmaven.test.skip=true - +---+ - - Skipping by default - - If you want to skip tests by default but want the ability to re-enable tests from the - command line, you need to go via a properties section in the pom: - - +---+ - - [...] - - true - - [...] - - - - ${project.groupId} - ${project.artifactId} - ${project.version} - - ${skipTests} - - - - - [...] - - +---+ - - This will allow you to run with tests disabled by default and to run them with this command: - - +---+ - mvn install -DskipTests=false - +---+ - - The same can be done with the "skip" parameter and other booleans on the plugin. + To skip running the tests for a particular project, set the <> + property to <>. + ++---+ + + [...] + + + + ${project.groupId} + ${project.artifactId} + ${project.version} + + true + + + + + [...] + ++---+ + + You can also skip the tests via command line by executing the following command: + ++---+ +mvn install -DskipTests ++---+ + +#{if}(${project.artifactId}=="maven-failsafe-plugin") + Since <<>> is also followed by the ${thatPlugin} Plugin, this will have the effect + of not running any tests. If, instead, you want to skip only the integration tests + being run by the ${thisPlugin} Plugin, you would use the <<>> property + ++---+ +mvn install -DskipITs ++---+ + +#{end} + If you absolutely must, you can also use the <<>> property to skip compiling the tests. + <<>> is honored by Surefire, Failsafe and the Compiler Plugin. + ++---+ +mvn install -Dmaven.test.skip=true ++---+ + +Skipping by default + + If you want to skip tests by default but want the ability to re-enable tests from the + command line, you need to go via a properties section in the pom: + ++---+ + + [...] + + true + + [...] + + + + ${project.groupId} + ${project.artifactId} + ${project.version} + + ${skipTests} + + + + + [...] + ++---+ + + This will allow you to run with tests disabled by default and to run them with this command: + ++---+ +mvn install -DskipTests=false ++---+ + + The same can be done with the "skip" parameter and other booleans on the plugin. diff --git a/maven-surefire-plugin/src/site/apt/examples/system-properties.apt.vm b/maven-surefire-plugin/src/site/apt/examples/system-properties.apt.vm index ecc30ae70f..76d8abf732 100644 --- a/maven-surefire-plugin/src/site/apt/examples/system-properties.apt.vm +++ b/maven-surefire-plugin/src/site/apt/examples/system-properties.apt.vm @@ -1,150 +1,140 @@ ------- -Using System Properties ------- -Allan Ramirez -Dan Tran ------- -2010-01-09 ------- - -~~ Licensed to the Apache Software Foundation (ASF) under one -~~ or more contributor license agreements. See the NOTICE file -~~ distributed with this work for additional information -~~ regarding copyright ownership. The ASF licenses this file -~~ to you under the Apache License, Version 2.0 (the -~~ "License"); you may not use this file except in compliance -~~ with the License. You may obtain a copy of the License at -~~ -~~ http://www.apache.org/licenses/LICENSE-2.0 -~~ -~~ Unless required by applicable law or agreed to in writing, -~~ software distributed under the License is distributed on an -~~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -~~ KIND, either express or implied. See the License for the -~~ specific language governing permissions and limitations -~~ under the License. - -~~ NOTE: For help with the syntax of this file, see: -~~ http://maven.apache.org/doxia/references/apt-format.html + ------ + Using System Properties + ------ + Allan Ramirez + Dan Tran + ------ + 2010-01-09 + ------ + + ~~ Licensed to the Apache Software Foundation (ASF) under one + ~~ or more contributor license agreements. See the NOTICE file + ~~ distributed with this work for additional information + ~~ regarding copyright ownership. The ASF licenses this file + ~~ to you under the Apache License, Version 2.0 (the + ~~ "License"); you may not use this file except in compliance + ~~ with the License. You may obtain a copy of the License at + ~~ + ~~ http://www.apache.org/licenses/LICENSE-2.0 + ~~ + ~~ Unless required by applicable law or agreed to in writing, + ~~ software distributed under the License is distributed on an + ~~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + ~~ KIND, either express or implied. See the License for the + ~~ specific language governing permissions and limitations + ~~ under the License. + + ~~ NOTE: For help with the syntax of this file, see: + ~~ http://maven.apache.org/doxia/references/apt-format.html Using System Properties -There are two ways to add a list of system properties to ${thisPlugin}: + There are two ways to add a list of system properties to ${thisPlugin}: * systemPropertyVariables -This configuration is the replacement of the deprecated << ->>. It can accept any value - from Maven's properties that can be converted < - >. - - +---+ - - [...] - - - - ${project.groupId} - ${project.artifactId} - ${project.version} - - - propertyValue - \${project.build.directory} - [...] - - - - - - [...] - - +---+ - - - * systemProperties ( deprecated ) - - +---+ - + This configuration is the replacement of the deprecated <<>>. It can accept any value + from Maven's properties that can be converted <>. + ++---+ + + [...] + + + + ${project.groupId} + ${project.artifactId} + ${project.version} + + + propertyValue + \${project.build.directory} [...] - - - - ${project.groupId} - ${project.artifactId} - ${project.version} - - - - propertyName - propertyValue - - [...] - - - - - + + + + + + [...] + ++---+ + + +* systemProperties ( deprecated ) + ++---+ + + [...] + + + + ${project.groupId} + ${project.artifactId} + ${project.version} + + + + propertyName + propertyValue + [...] - - +---+ - - Take note that only < - > properties can be passed as system - properties. Any attempt to pass any other Maven variable type (i.e. << - >> - or a << - >> variable) will cause the variable expression to be passed - literally (unevaluated). So having the example below: - - +---+ - - [...] - - - - ${project.groupId} - ${project.artifactId} - ${project.version} - - - - buildDir - \${project.build.outputDirectory} - - - - - - - [...] - - +---+ - - will literally pass <<$\{project.build.outputDirectory\}>> because the value - of that expression is a << - >>, not a << - >>. - - To inherit the "systemProperties" collection from the parent configuration, - you will need to specify combine.children="append" on the systemProperties node in the child - pom: - - +---+ - - - [...] - - - +---+ - - Special VM properties - - Some system properties must be set on the command line of the forked VM, and cannot be set - after the - VM has been started. These properties must be added to the argLine parameter of the surefire - plugin. - - +---+ - -Djava.endorsed.dirs=... - +---+ + + + + + + [...] + ++---+ + + Take note that only <> properties can be passed as system + properties. Any attempt to pass any other Maven variable type (i.e. <<>> + or a <<>> variable) will cause the variable expression to be passed + literally (unevaluated). So having the example below: + ++---+ + + [...] + + + + ${project.groupId} + ${project.artifactId} + ${project.version} + + + + buildDir + \${project.build.outputDirectory} + + + + + + + [...] + ++---+ + + will literally pass <<$\{project.build.outputDirectory\}>> because the value + of that expression is a <<>>, not a <<>>. + + To inherit the "systemProperties" collection from the parent configuration, + you will need to specify combine.children="append" on the systemProperties node in the child pom: + ++---+ + + + [...] + + ++---+ + +Special VM properties + + Some system properties must be set on the command line of the forked VM, and cannot be set after the + VM has been started. These properties must be added to the argLine parameter of the surefire plugin. + ++---+ + -Djava.endorsed.dirs=... ++---+ diff --git a/maven-surefire-plugin/src/site/apt/examples/testng.apt.vm b/maven-surefire-plugin/src/site/apt/examples/testng.apt.vm index beda88aa2b..f23ca80535 100644 --- a/maven-surefire-plugin/src/site/apt/examples/testng.apt.vm +++ b/maven-surefire-plugin/src/site/apt/examples/testng.apt.vm @@ -1,235 +1,211 @@ ------- -Using TestNG ------- -Brett Porter - ------- -2010-01-09 ------- - -~~ Licensed to the Apache Software Foundation (ASF) under one -~~ or more contributor license agreements. See the NOTICE file -~~ distributed with this work for additional information -~~ regarding copyright ownership. The ASF licenses this file -~~ to you under the Apache License, Version 2.0 (the -~~ "License"); you may not use this file except in compliance -~~ with the License. You may obtain a copy of the License at -~~ -~~ http://www.apache.org/licenses/LICENSE-2.0 -~~ -~~ Unless required by applicable law or agreed to in writing, -~~ software distributed under the License is distributed on an -~~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -~~ KIND, either express or implied. See the License for the -~~ specific language governing permissions and limitations -~~ under the License. - -~~ NOTE: For help with the syntax of this file, see: -~~ http://maven.apache.org/doxia/references/apt-format.html + ------ + Using TestNG + ------ + Brett Porter + ------ + 2010-01-09 + ------ + + ~~ Licensed to the Apache Software Foundation (ASF) under one + ~~ or more contributor license agreements. See the NOTICE file + ~~ distributed with this work for additional information + ~~ regarding copyright ownership. The ASF licenses this file + ~~ to you under the Apache License, Version 2.0 (the + ~~ "License"); you may not use this file except in compliance + ~~ with the License. You may obtain a copy of the License at + ~~ + ~~ http://www.apache.org/licenses/LICENSE-2.0 + ~~ + ~~ Unless required by applicable law or agreed to in writing, + ~~ software distributed under the License is distributed on an + ~~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + ~~ KIND, either express or implied. See the License for the + ~~ specific language governing permissions and limitations + ~~ under the License. + + ~~ NOTE: For help with the syntax of this file, see: + ~~ http://maven.apache.org/doxia/references/apt-format.html Using TestNG * Configuring TestNG -To get started with TestNG, include the following dependency in your project (replacing the version with the one you wish to use): + To get started with TestNG, include the following dependency in your project (replacing the version with the one you wish to use): +---+ - [...] + [...] - org.testng - testng - 6.3.1 - test + org.testng + testng + 6.3.1 + test - [...] + [...] +---+ -If you are using an older version of TestNG (\<= 5.11), the dependency would instead look like this: + If you are using an older version of TestNG (\<= 5.11), the dependency would instead look like this: +---+ - [...] + [...] - org.testng - testng - 6.3.1 - test - jdk15 + org.testng + testng + 6.3.1 + test + jdk15 - [...] + [...] +---+ -< -> if you are using JDK 1.4 Javadoc annotations for your TestNG tests, replace the classifier << - >> with << - >> above. - - #{if}(${project.artifactId}=="maven-surefire-plugin") - This is the only step that is required to get started - you can now create tests in your test source - directory - (eg, << - >>. As long as they are named using the defaults such as <<<*Test.java>>> they will be run - by ${thisPlugin} as TestNG tests. - #{else} - This is the only step that is required to get started - you can now create tests in your test source - directory - (eg, << - >>. As long as they are named using the defaults such as <<<*IT.java>>> they will be run - by ${thisPlugin} as TestNG tests. - #{end} - - If you'd like to use a different naming scheme, you can change the << - >> parameter, as discussed in the - {{{./inclusion-exclusion.html}Inclusions and Exclusions of Tests}} example. - - * Using Suite XML Files - - Another alternative is to use TestNG suite XML files. This allows flexible configuration of the tests to - be run. - These files are created in the normal way, and then added to the ${thisPlugin} Plugin configuration: - - +---+ - - [...] - - ${project.groupId} - ${project.artifactId} - ${project.version} - - - testng.xml - - - - [...] - - +---+ - - This configuration will override the includes and excludes patterns and run all tests in the suite - files. - - * Specifying Test Parameters - - Your TestNG test can accept parameters with the @Parameters annotation. You can also pass parameters - from Maven - into your TestNG test, by specifying them as system properties, like this: - - +---+ - - [...] - - ${project.groupId} - ${project.artifactId} - ${project.version} - - - firefox - - - - [...] - - +---+ - - For more information about setting system properties in ${thisPlugin} tests, see - {{{./system-properties.html}System Properties}}. - - * Using Groups - - TestNG allows you to group your tests. You can then execute one or more specific groups. To do this - with ${thisPlugin}, - use the << - >> parameter, for example: - - +---+ - - [...] - - ${project.groupId} - ${project.artifactId} - ${project.version} - - functest,perftest - - - [...] - - +---+ - - Likewise, the << - >> parameter can be used to run all but a certain set of groups. - - * Running tests in parallel - - TestNG allows you to run your tests in parallel, including JUnit tests. To do this, you must set - the - << - >> parameter, and may change the << - >> parameter if the default of 5 is not sufficient. - For example: - - +---+ - - [...] - - ${project.groupId} - ${project.artifactId} - ${project.version} - - methods - 10 - - - [...] - - +---+ - - This is particularly useful for slow tests that can have high concurrency, or to quickly - and roughly assess the independance - and thread safety of your tests and code. - - * Using custom listeners and reporters - - TestNG provides support for attaching custom listeners, reporters, annotation - transformers and method interceptors to your tests. - By default, TestNG attaches a few basic listeners to generate HTML and XML reports. - - You can configure multiple custom listeners like this: - - +---+ - - [...] - - ${project.groupId} - ${project.artifactId} - ${project.version} - - - - usedefaultlisteners - false - - - - listener - - com.mycompany.MyResultListener,com.mycompany.MyAnnotationTransformer,com.mycompany.MyMethodInterceptor - - - - reporter - listenReport.Reporter - - - - - [...] - - +---+ - - For more information on TestNG, see the {{{http://www.testng.org}TestNG web site}}. + <> if you are using JDK 1.4 Javadoc annotations for your TestNG tests, replace the classifier <<>> with <<>> above. + +#{if}(${project.artifactId}=="maven-surefire-plugin") + This is the only step that is required to get started - you can now create tests in your test source directory + (eg, <<>>. As long as they are named using the defaults such as <<<*Test.java>>> they will be run + by ${thisPlugin} as TestNG tests. +#{else} + This is the only step that is required to get started - you can now create tests in your test source directory + (eg, <<>>. As long as they are named using the defaults such as <<<*IT.java>>> they will be run + by ${thisPlugin} as TestNG tests. +#{end} + + If you'd like to use a different naming scheme, you can change the <<>> parameter, as discussed in the + {{{./inclusion-exclusion.html}Inclusions and Exclusions of Tests}} example. + +* Using Suite XML Files + + Another alternative is to use TestNG suite XML files. This allows flexible configuration of the tests to be run. + These files are created in the normal way, and then added to the ${thisPlugin} Plugin configuration: + ++---+ + + [...] + + ${project.groupId} + ${project.artifactId} + ${project.version} + + + testng.xml + + + + [...] + ++---+ + + This configuration will override the includes and excludes patterns and run all tests in the suite files. + +* Specifying Test Parameters + + Your TestNG test can accept parameters with the @Parameters annotation. You can also pass parameters from Maven + into your TestNG test, by specifying them as system properties, like this: + ++---+ + + [...] + + ${project.groupId} + ${project.artifactId} + ${project.version} + + + firefox + + + + [...] + ++---+ + + For more information about setting system properties in ${thisPlugin} tests, see {{{./system-properties.html}System Properties}}. + +* Using Groups + + TestNG allows you to group your tests. You can then execute one or more specific groups. To do this with ${thisPlugin}, + use the <<>> parameter, for example: + ++---+ + + [...] + + ${project.groupId} + ${project.artifactId} + ${project.version} + + functest,perftest + + + [...] + ++---+ + + Likewise, the <<>> parameter can be used to run all but a certain set of groups. + +* Running tests in parallel + + TestNG allows you to run your tests in parallel, including JUnit tests. To do this, you must set the + <<>> parameter, and may change the <<>> parameter if the default of 5 is not sufficient. + For example: + ++---+ + + [...] + + ${project.groupId} + ${project.artifactId} + ${project.version} + + methods + 10 + + + [...] + ++---+ + + This is particularly useful for slow tests that can have high concurrency, or to quickly and roughly assess the independance + and thread safety of your tests and code. + + See also {{{./fork-options-and-parallel-execution.html}Fork Options and Parallel Test Execution}}. + +* Using custom listeners and reporters + + TestNG provides support for attaching custom listeners, reporters, annotation transformers and method interceptors to your tests. + By default, TestNG attaches a few basic listeners to generate HTML and XML reports. + + You can configure multiple custom listeners like this: + ++---+ + + [...] + + ${project.groupId} + ${project.artifactId} + ${project.version} + + + + usedefaultlisteners + false + + + listener + com.mycompany.MyResultListener,com.mycompany.MyAnnotationTransformer,com.mycompany.MyMethodInterceptor + + + reporter + listenReport.Reporter + + + + + [...] + ++---+ + + For more information on TestNG, see the {{{http://www.testng.org}TestNG web site}}. diff --git a/maven-surefire-plugin/src/site/apt/featurematrix.apt.vm b/maven-surefire-plugin/src/site/apt/featurematrix.apt.vm index 63e06b0544..13a06a9c76 100644 --- a/maven-surefire-plugin/src/site/apt/featurematrix.apt.vm +++ b/maven-surefire-plugin/src/site/apt/featurematrix.apt.vm @@ -20,34 +20,27 @@ Feature matrix -Not all features are supported for all test frameworks, and the following table gives a brief overview -of support status: + Not all features are supported for all test frameworks, and the following table gives a brief overview + of support status: *---------------------------------------------+-----------+-----------+------------+-----------+----------+ -|| < -> ||< - >||< - >||< - >||< - >||< - > | - *---------------------------------------------+------------+----------+------------+-----------+----------+ - | groups/category support | N | N | Y | Y | N | - *---------------------------------------------+------------+----------+------------+-----------+----------+ - | security manager support | Y | N | N | N | N | - *---------------------------------------------+------------+----------+------------+-----------+----------+ - | runOrder support | Y | Y | Y | ? | Y | - *---------------------------------------------+------------+----------+------------+-----------+----------+ - | run >1 individual test method in a class | N | Y | Y | N | N | - *---------------------------------------------+------------+----------+------------+-----------+----------+ - | parallel support | N | N | Y | Y | N | - *---------------------------------------------+------------+----------+------------+-----------+----------+ - - - Legend: Y means supported, N means not supported. ? means not tested. - - If you would like to implement support for - a given provider with an N or a ? (or create tests for it), you should create a patch and mark - the issue is an - improvement. If there is something wrong with an implementation marked with "Y" it's a bug. +|| <> ||<>||<>||<>||<>||<> | +*---------------------------------------------+------------+----------+------------+-----------+----------+ +| groups/category support | N | N | Y | Y | N | +*---------------------------------------------+------------+----------+------------+-----------+----------+ +| security manager support | Y | N | N | N | N | +*---------------------------------------------+------------+----------+------------+-----------+----------+ +| runOrder support | Y | Y | Y | ? | Y | +*---------------------------------------------+------------+----------+------------+-----------+----------+ +| run >1 individual test method in a class | N | Y | Y | N | N | +*---------------------------------------------+------------+----------+------------+-----------+----------+ +| parallel support | N | N | Y | Y | N | +*---------------------------------------------+------------+----------+------------+-----------+----------+ + + + Legend: Y means supported, N means not supported. ? means not tested. + + If you would like to implement support for + a given provider with an N or a ? (or create tests for it), you should create a patch and mark the issue is an + improvement. If there is something wrong with an implementation marked with "Y" it's a bug. diff --git a/maven-surefire-plugin/src/site/apt/index.apt.vm b/maven-surefire-plugin/src/site/apt/index.apt.vm index 5d6f8914de..b27f3f29a0 100644 --- a/maven-surefire-plugin/src/site/apt/index.apt.vm +++ b/maven-surefire-plugin/src/site/apt/index.apt.vm @@ -1,12 +1,12 @@ ------- -Introduction ------- -Stephen Connolly -Allan Ramirez ------- -2011-06-27 ------- - + ------ + Introduction + ------ + Stephen Connolly + Allan Ramirez + ------ + 2011-06-27 + ------ + ~~ Licensed to the Apache Software Foundation (ASF) under one ~~ or more contributor license agreements. See the NOTICE file ~~ distributed with this work for additional information @@ -26,144 +26,127 @@ Allan Ramirez ~~ NOTE: For help with the syntax of this file, see: ~~ http://maven.apache.org/doxia/references/apt-format.html - + Maven ${thisPlugin} Plugin #{if}(${project.artifactId}=="maven-surefire-plugin") -The Surefire Plugin is used during the << ->> phase of the build - lifecycle to execute the unit tests of an application. It generates reports - in 2 different file formats: + The Surefire Plugin is used during the <<>> phase of the build + lifecycle to execute the unit tests of an application. It generates reports + in 2 different file formats: #{else} - The Failsafe Plugin is designed to run integration tests while the Surefire Plugins is designed to run unit tests. - The name (failsafe) was chosen both because it is a synonym of surefire and because it implies that when it fails, - it - does so in a safe way. + The Failsafe Plugin is designed to run integration tests while the Surefire Plugins is designed to run unit tests. + The name (failsafe) was chosen both because it is a synonym of surefire and because it implies that when it fails, it + does so in a safe way. - The Maven lifecycle has four phases for running integration tests: + The Maven lifecycle has four phases for running integration tests: - * << ->> for setting up the integration test environment. + * <<>> for setting up the integration test environment. - * << ->> for running the integration tests. + * <<>> for running the integration tests. - * << ->> for tearing down the integration test environment. + * <<>> for tearing down the integration test environment. - * << ->> for checking the results of the integration tests. + * <<>> for checking the results of the integration tests. - [] + [] - If you use the Surefire Plugin for running tests, then when you have a test failure, the build will stop at the - << ->> phase and your integration test environment will not have been torn down correctly. + If you use the Surefire Plugin for running tests, then when you have a test failure, the build will stop at the + <<>> phase and your integration test environment will not have been torn down correctly. - The Failsafe Plugin is used during the << ->> and << ->> phases of the build - lifecycle to execute the integration tests of an application. The Failsafe Plugin will not fail the build during - the << ->> phase thus enabling the << ->> phase to execute. + The Failsafe Plugin is used during the <<>> and <<>> phases of the build + lifecycle to execute the integration tests of an application. The Failsafe Plugin will not fail the build during + the <<>> phase thus enabling the <<>> phase to execute. - NOTE: when running integration tests, you should invoke maven with the (shorter to type too) + NOTE: when running integration tests, you should invoke maven with the (shorter to type too) - +---+ - mvn verify - +---+ ++---+ +mvn verify ++---+ - rather than trying to invoke the << ->> phase directly, as otherwise the << ->> - phase will not be executed. + rather than trying to invoke the <<>> phase directly, as otherwise the <<>> + phase will not be executed. - The Failsafe Plugin generates reports in 2 different file formats: + The Failsafe Plugin generates reports in 2 different file formats: #{end} - * Plain text files (<<<*.txt>>>) + * Plain text files (<<<*.txt>>>) - * XML files (<<<*.xml>>>) + * XML files (<<<*.xml>>>) - [] + [] - By default, these files are generated at <<<$\{basedir\}/target/${thisPlugin.toLowerCase()}-reports>>>. + By default, these files are generated at <<<$\{basedir\}/target/${thisPlugin.toLowerCase()}-reports>>>. - For an HTML format of the report, please see the - {{{http://maven.apache.org/plugins/maven-surefire-report-plugin/}Maven Surefire Report Plugin}}. + For an HTML format of the report, please see the + {{{http://maven.apache.org/plugins/maven-surefire-report-plugin/}Maven Surefire Report Plugin}}. - * Goals Overview +* Goals Overview #{if}(${project.artifactId}=="maven-surefire-plugin") - The Surefire Plugin has only 1 goal: + The Surefire Plugin has only 1 goal: - * {{{./test-mojo.html}surefire:test}} runs the unit tests of an application. + * {{{./test-mojo.html}surefire:test}} runs the unit tests of an application. - [] + [] #{else} - The Failsafe Plugin has only 2 goals: + The Failsafe Plugin has only 2 goals: - * {{{./integration-test-mojo.html}failsafe:integration-test}} runs the integration tests of an application. + * {{{./integration-test-mojo.html}failsafe:integration-test}} runs the integration tests of an application. - * {{{./verify-mojo.html}failsafe:verify}} verifies that the integration tests of an application passed. + * {{{./verify-mojo.html}failsafe:verify}} verifies that the integration tests of an application passed. - [] + [] #{end} - * Usage +* Usage - General instructions on how to use the ${thisPlugin} Plugin can be found on the {{{./usage.html}usage page}}. Some - more - specific use cases are described in the examples given below. -#{if}(${project.artifactId}=="maven-surefire-plugin") Last but not least, users occasionally contribute - additional examples, tips or errata to the - {{{http://docs.codehaus.org/display/MAVENUSER/Surefire+Plugin}plugin's wiki page}}.#{end} + General instructions on how to use the ${thisPlugin} Plugin can be found on the {{{./usage.html}usage page}}. Some more + specific use cases are described in the examples given below. + #{if}(${project.artifactId}=="maven-surefire-plugin") Last but not least, users occasionally contribute + additional examples, tips or errata to the + {{{http://docs.codehaus.org/display/MAVENUSER/Surefire+Plugin}plugin's wiki page}}.#{end} - In case you still have questions regarding the plugin's usage, please have a look at the {{{./faq.html}FAQ}} and - feel - free to contact the {{{./mail-lists.html}user mailing list}}. The posts to the mailing list are archived and could - already contain the answer to your question as part of an older thread. Hence, it is also worth browsing/searching - the {{{./mail-lists.html}mail archive}}. + In case you still have questions regarding the plugin's usage, please have a look at the {{{./faq.html}FAQ}} and feel + free to contact the {{{./mail-lists.html}user mailing list}}. The posts to the mailing list are archived and could + already contain the answer to your question as part of an older thread. Hence, it is also worth browsing/searching + the {{{./mail-lists.html}mail archive}}. - If you feel like the plugin is missing a feature or has a defect, you can fill a feature request or bug report in - our - {{{./issue-tracking.html}issue tracker}}. When creating a new issue, please provide a comprehensive description of - your - concern. Especially for fixing bugs it is crucial that the developers can reproduce your problem. For this reason, - entire debug logs, POMs or most preferably little demo projects attached to the issue are very much appreciated. - Of course, patches are welcome, too. Contributors can check out the project from our - {{{./source-repository.html}source repository}} and will find supplementary information in the - {{{http://maven.apache.org/guides/development/guide-helping.html}guide to helping with Maven}}. + If you feel like the plugin is missing a feature or has a defect, you can fill a feature request or bug report in our + {{{./issue-tracking.html}issue tracker}}. When creating a new issue, please provide a comprehensive description of your + concern. Especially for fixing bugs it is crucial that the developers can reproduce your problem. For this reason, + entire debug logs, POMs or most preferably little demo projects attached to the issue are very much appreciated. + Of course, patches are welcome, too. Contributors can check out the project from our + {{{./source-repository.html}source repository}} and will find supplementary information in the + {{{http://maven.apache.org/guides/development/guide-helping.html}guide to helping with Maven}}. - * Examples +* Examples - The following examples show how to use the ${thisPlugin} Plugin in more advanced use-cases: + The following examples show how to use the ${thisPlugin} Plugin in more advanced use-cases: - * {{{./examples/testng.html}Using TestNG}} + * {{{./examples/testng.html}Using TestNG}} - * {{{./examples/junit.html}Using JUnit}} + * {{{./examples/junit.html}Using JUnit}} - * {{{./examples/pojo-test.html}Using POJO Tests}} + * {{{./examples/pojo-test.html}Using POJO Tests}} - * {{{./examples/skipping-test.html}Skipping Tests}} + * {{{./examples/skipping-test.html}Skipping Tests}} - * {{{./examples/inclusion-exclusion.html}Inclusions and Exclusions of Tests}} + * {{{./examples/inclusion-exclusion.html}Inclusions and Exclusions of Tests}} - * {{{./examples/single-test.html}Running a Single Test}} + * {{{./examples/single-test.html}Running a Single Test}} - * {{{./examples/class-loading.html}Class Loading Issues}} + * {{{./examples/class-loading.html}Class Loading Issues}} - * {{{./examples/debugging.html}Debugging Tests}} + * {{{./examples/debugging.html}Debugging Tests}} - * {{{./examples/system-properties.html}Using System Properties}} + * {{{./examples/system-properties.html}Using System Properties}} - * {{{./examples/configuring-classpath.html}Configuring the Classpath}} + * {{{./examples/configuring-classpath.html}Configuring the Classpath}} - * {{{./examples/providers.html}Selecting providers}} + * {{{./examples/providers.html}Selecting providers}} - [] + [] diff --git a/maven-surefire-plugin/src/site/apt/usage.apt.vm b/maven-surefire-plugin/src/site/apt/usage.apt.vm index f32c5b031a..53dc424b81 100644 --- a/maven-surefire-plugin/src/site/apt/usage.apt.vm +++ b/maven-surefire-plugin/src/site/apt/usage.apt.vm @@ -1,13 +1,13 @@ ------- -Usage ------- -Brett Porter -Allan Ramirez -Stephen Connolly ------- -2011-06-27 ------- - + ------ + Usage + ------ + Brett Porter + Allan Ramirez + Stephen Connolly + ------ + 2011-06-27 + ------ + ~~ Licensed to the Apache Software Foundation (ASF) under one ~~ or more contributor license agreements. See the NOTICE file ~~ distributed with this work for additional information @@ -31,72 +31,67 @@ Stephen Connolly Usage #{if}(${project.artifactId}=="maven-surefire-plugin") -Best practice is to define the version of the Surefire plugin that you want to use in either your << ->> -or a parent << ->> + Best practice is to define the version of the Surefire plugin that you want to use in either your <<>> + or a parent <<>> +---+ - [...] - - - - - ${project.groupId} - ${project.artifactId} - ${project.version} - - - - - [...] + [...] + + + + + ${project.groupId} + ${project.artifactId} + ${project.version} + + + + + [...] +---+ #{else} -To use the ${thisPlugin} Plugin, you need to add the following configuration to -your << ->> + To use the ${thisPlugin} Plugin, you need to add the following configuration to + your <<>> +---+ - [...] - - - - ${project.groupId} - ${project.artifactId} - ${project.version} - - - - integration-test - verify - - - - - - - [...] + [...] + + + + ${project.groupId} + ${project.artifactId} + ${project.version} + + + + integration-test + verify + + + + + + + [...] +---+ #{end} #{if}(${project.artifactId}=="maven-surefire-plugin") -The ${thisPlugin} Plugin can be invoked by calling the << ->> phase of the -build lifecycle. + The ${thisPlugin} Plugin can be invoked by calling the <<>> phase of the + build lifecycle. +---+ mvn test +---+ #{else} -The ${thisPlugin} Plugin can be invoked by calling the << ->> phase of the -build lifecycle. + The ${thisPlugin} Plugin can be invoked by calling the <<>> phase of the + build lifecycle. +---+ mvn verify @@ -105,372 +100,341 @@ mvn verify * Using different testing providers -Tests in your test source directory can be any combination of the following: + Tests in your test source directory can be any combination of the following: -* TestNG + * TestNG -* JUnit (3.8 or 4.x) + * JUnit (3.8 or 4.x) -* POJO + * POJO -Which providers are available is controlled simply by the inclusion of the -appropriate dependencies (ie, junit:junit for JUnit, org.testng:testng 4.7+ -for TestNG). Since this is required to compile the test classes anyway, no -additional configuration is required. + Which providers are available is controlled simply by the inclusion of the + appropriate dependencies (ie, junit:junit for JUnit, org.testng:testng 4.7+ + for TestNG). Since this is required to compile the test classes anyway, no + additional configuration is required. -Note that any normal Surefire integration works identically no matter which -providers are in use - so you can still produce a Cobertura report and a -Surefire results report on your project web site for your TestNG tests, -for example. + Note that any normal Surefire integration works identically no matter which + providers are in use - so you can still produce a Cobertura report and a + Surefire results report on your project web site for your TestNG tests, + for example. -The POJO provider above allows you to write tests that do not depend on -JUnit. They behave in the same way, running all << ->> methods that are -public in the class, but the API dependency is not required. To perform -assertions, the JDK 1.4 << ->> keyword can be used. -See {{{./examples/pojo-test.html} using POJO tests}} for more information. + The POJO provider above allows you to write tests that do not depend on + JUnit. They behave in the same way, running all <<>> methods that are + public in the class, but the API dependency is not required. To perform + assertions, the JDK 1.4 <<>> keyword can be used. + See {{{./examples/pojo-test.html} using POJO tests}} for more information. -All of the providers support the Surefire Plugin parameter configurations. -However, there are additional options available if you are running TestNG -tests (including if you are using TestNG to execute your JUnit tests, which -occurs by default if both are present in Surefire). + All of the providers support the Surefire Plugin parameter configurations. + However, there are additional options available if you are running TestNG + tests (including if you are using TestNG to execute your JUnit tests, which + occurs by default if both are present in Surefire). -See {{{./examples/testng.html} Using TestNG}} for more information. + See {{{./examples/testng.html} Using TestNG}} for more information. #{if}(${project.artifactId}=="maven-failsafe-plugin") * Using jetty and ${project.artifactId} -You need to bind one of << ->>, << ->> or << ->> -to the << ->> phase with << ->> set to true, bind -<< ->> to the << ->> phase, bind << ->> -to the << ->> phase and finally bind << ->> to -the << ->> phase. Here is an example: + You need to bind one of <<>>, <<>> or <<>> + to the <<>> phase with <<>> set to true, bind + <<>> to the <<>> phase, bind <<>> + to the <<>> phase and finally bind <<>> to + the <<>> phase. Here is an example: +---+ + [...] + [...] - + + [...] + + ${project.groupId} + ${project.artifactId} + ${project.version} + + + integration-test + + integration-test + + + + verify + + verify + + + + + + org.mortbay.jetty + maven-jetty-plugin + 6.1.16 [...] - - [...] - - ${project.groupId} - ${project.artifactId} - ${project.version} - - - integration-test - - integration-test - - - - verify - - verify - - - - - - org.mortbay.jetty - maven-jetty-plugin - 6.1.16 - [...] - - [...] - 10 - 8005 - STOP - / - [...] - - [...] - - [...] - - start-jetty - pre-integration-test - - run-exploded - - - 0 - true - - - - stop-jetty - post-integration-test - - stop - - - [...] - - [...] - - [...] - + + [...] + 10 + 8005 + STOP + / + [...] + [...] - + + [...] + + start-jetty + pre-integration-test + + run-exploded + + + 0 + true + + + + stop-jetty + post-integration-test + + stop + + + [...] + + [...] + + [...] + [...] + + [...] +---+ -You then invoke maven with a phase of << ->> or later in order to run -the integration tests. DO NOT directly invoke any of the phases: -<< ->>, << ->>, or << ->> as -these are too long to type and they will likely leave a jetty container running. + You then invoke maven with a phase of <<>> or later in order to run + the integration tests. DO NOT directly invoke any of the phases: + <<>>, <<>>, or <<>> as + these are too long to type and they will likely leave a jetty container running. +---+ mvn verify +---+ -Note: during test development, you will likely run a jetty instance in the background. -to help running the integration tests, it can be handy to bind << ->> to -the << ->> phase before << ->> to flush out any -running jetty instance before starting the integration test jetty instance, e.g. + Note: during test development, you will likely run a jetty instance in the background. + to help running the integration tests, it can be handy to bind <<>> to + the <<>> phase before <<>> to flush out any + running jetty instance before starting the integration test jetty instance, e.g. +---+ + [...] + [...] - + + [...] + + org.mortbay.jetty + maven-jetty-plugin + 6.1.16 [...] - - [...] - - org.mortbay.jetty - maven-jetty-plugin - 6.1.16 - [...] - - [...] - - start-jetty - pre-integration-test - - - stop - run-exploded - - [...] - - [...] - - [...] - + + [...] + + start-jetty + pre-integration-test + + + stop + run-exploded + [...] - + + [...] + [...] - + + [...] + [...] + + [...] +---+ * Reporting integration test results -The ${thisPlugin} Plugin uses the exact same format as the ${thatPlugin} Plugin, so to generate a report you just add a -second -Surefire Report Plugin report set using the ${thisPlugin} reports directory, e.g. + The ${thisPlugin} Plugin uses the exact same format as the ${thatPlugin} Plugin, so to generate a report you just add a second + Surefire Report Plugin report set using the ${thisPlugin} reports directory, e.g. +---+ - [...] - - - - ${project.groupId} - maven-surefire-report-plugin - ${project.version} - - - integration-tests - - failsafe-report-only - - - - - - [...] + [...] + + + + ${project.groupId} + maven-surefire-report-plugin + ${project.version} + + + integration-tests + + failsafe-report-only + + + + + + [...] +---+ * Running integration tests multiple times -If you need to run your integration tests multiple times, just use multiple executions of the << ->> - goal. You will need to specify a different summary file for each execution, and then configure the << - >> goal - with the multiple summary files in order to fail the build when any one execution has failures, e.g. + If you need to run your integration tests multiple times, just use multiple executions of the <<>> + goal. You will need to specify a different summary file for each execution, and then configure the <<>> goal + with the multiple summary files in order to fail the build when any one execution has failures, e.g. - +---+ - - [...] - - - - ${project.groupId} - ${project.artifactId} - ${project.version} - - - integration-test-red-bevels - - integration-test - - - - red - - target/failsafe-reports/failsafe-summary-red-bevels.xml - - - - integration-test-no-bevels - - integration-test - - - - none - - target/failsafe-reports/failsafe-summary-no-bevels.xml - - - - verify - - verify - - - - target/failsafe-reports/failsafe-summary-red-bevels.xml - - target/failsafe-reports/failsafe-summary-no-bevels.xml - - - - - - - - - [...] - - +---+ - - * Using in multi-module projects - - The recommendations for using the ${thisPlugin} Plugin listed at the top of this page are fine for 95% of use - cases. - When you are defining a shared definition of the ${thisPlugin} Plugin in a parent pom, it is considered best - practice - to define an execution id in order to allow child projects to override the configuration. Thus you might have - the - following in your parent << - >> - - +---+ - - [...] - - - - - ${project.groupId} - ${project.artifactId} - ${project.version} - - - integration-test - - integration-test - verify - - - - - - - - [...] - - +---+ - - The child projects can then trigger usage of the ${thisPlugin} Plugin with - - +---+ - - [...] - - - - ${project.groupId} - ${project.artifactId} - ${project.version} - - - - [...] - - +---+ - - For very complex builds, it may be better to separate the executions for the << - >> and << - >> - goals. - - +---+ - - [...] - - - - - ${project.groupId} - ${project.artifactId} - ${project.version} - - - integration-test - - integration-test - - - - verify - - verify - - - - - - - - [...] - - +---+ ++---+ + + [...] + + + + ${project.groupId} + ${project.artifactId} + ${project.version} + + + integration-test-red-bevels + + integration-test + + + + red + + target/failsafe-reports/failsafe-summary-red-bevels.xml + + + + integration-test-no-bevels + + integration-test + + + + none + + target/failsafe-reports/failsafe-summary-no-bevels.xml + + + + verify + + verify + + + + target/failsafe-reports/failsafe-summary-red-bevels.xml + target/failsafe-reports/failsafe-summary-no-bevels.xml + + + + + + + + [...] + ++---+ + +* Using in multi-module projects + + The recommendations for using the ${thisPlugin} Plugin listed at the top of this page are fine for 95% of use cases. + When you are defining a shared definition of the ${thisPlugin} Plugin in a parent pom, it is considered best practice + to define an execution id in order to allow child projects to override the configuration. Thus you might have the + following in your parent <<>> + ++---+ + + [...] + + + + + ${project.groupId} + ${project.artifactId} + ${project.version} + + + integration-test + + integration-test + verify + + + + + + + + [...] + ++---+ + + The child projects can then trigger usage of the ${thisPlugin} Plugin with + ++---+ + + [...] + + + + ${project.groupId} + ${project.artifactId} + ${project.version} + + + + [...] + ++---+ + + For very complex builds, it may be better to separate the executions for the <<>> and <<>> + goals. + ++---+ + + [...] + + + + + ${project.groupId} + ${project.artifactId} + ${project.version} + + + integration-test + + integration-test + + + + verify + + verify + + + + + + + + [...] + ++---+ #{end} \ No newline at end of file diff --git a/maven-surefire-plugin/src/site/fml/faq.fml b/maven-surefire-plugin/src/site/fml/faq.fml index e7f6a93422..9c44fbc676 100644 --- a/maven-surefire-plugin/src/site/fml/faq.fml +++ b/maven-surefire-plugin/src/site/fml/faq.fml @@ -77,9 +77,9 @@ under the License. true]]>
false
]]>
- once
]]>
+ 1]]>
- forkMode at least once, always if not enough + try reuseForks=true and if it doesn't work, fall back to reuseForks=false

diff --git a/maven-surefire-plugin/src/site/markdown/newerrorsummary.md b/maven-surefire-plugin/src/site/markdown/newerrorsummary.md new file mode 100644 index 0000000000..98491ead77 --- /dev/null +++ b/maven-surefire-plugin/src/site/markdown/newerrorsummary.md @@ -0,0 +1,27 @@ +The 1-line error summary +======================== + +Surefire 2.13 introduced a compact one-line format for quickly being able to locate test failures. This format +is intended to give an overview and does necessarily lose some details, which can be found in the main +report of the run or the files on disk. + +### Example output: + + Failed tests: + Test1.assertion1:59 Bending maths expected:<[123]> but was:<[312]> + Test1.assertion2:64 True is false + + Tests in error: + Test1.nullPointerInLibrary:38 » NullPointer + Test1.failInMethod:43->innerFailure:68 NullPointer Fail here + Test1.failInLibInMethod:48 » NullPointer + Test1.failInNestedLibInMethod:54->nestedLibFailure:72 » NullPointer + Test2.test6281:33 Runtime FailHere + +The main rules of the format are: + * Assertion failures only show the message + * Exception/Error is stripped from the Exception name to save space. + * The exception message is trimmed to an approximate 80 chars. + * The » symbol means that the exception happened below the method shown (in library code called by test) + * Methods in superclasses are normally shown as SuperClassName.methodName + * If the first method in the stacktrace is in a a superclass it will be show as this: TestClass>Superclass.method diff --git a/maven-surefire-plugin/src/site/site.xml b/maven-surefire-plugin/src/site/site.xml index 04a0372ec5..2976c5b1d4 100644 --- a/maven-surefire-plugin/src/site/site.xml +++ b/maven-surefire-plugin/src/site/site.xml @@ -23,20 +23,8 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/DECORATION/1.0.0 http://maven.apache.org/xsd/decoration-1.0.0.xsd"> - - ${project.name} - http://maven.apache.org/images/apache-maven-project.png - http://maven.apache.org/ - - - http://maven.apache.org/images/maventxt_logo_200.gif - - - org.apache.maven.skins - maven-fluido-skin - 1.0 - + @@ -46,6 +34,7 @@ + @@ -58,9 +47,8 @@ - - - + + 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 5252a245f2..6fbe4bd192 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 @@ -38,6 +38,40 @@ public void testForkMode() assertEquals( ForkConfiguration.FORK_ONCE, surefirePlugin.getEffectiveForkMode() ); } + public void testForkCountComputation() + { + SurefirePlugin surefirePlugin = new SurefirePlugin(); + assertConversionFails( surefirePlugin, "nothing" ); + + assertConversionFails( surefirePlugin, "5,0" ); + assertConversionFails( surefirePlugin, "5.0" ); + assertConversionFails( surefirePlugin, "5,0C" ); + assertConversionFails( surefirePlugin, "5.0CC" ); + + 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" ); + } + + private void assertForkCount( SurefirePlugin surefirePlugin, int expected, String value ) + { + assertEquals( expected, surefirePlugin.convertWithCoreCount( value )); + } + + private void assertConversionFails( SurefirePlugin surefirePlugin, String value ) + { + try { + surefirePlugin.convertWithCoreCount( value ); + } catch (NumberFormatException nfe) + { + return; + } + fail( "Expected NumberFormatException when converting " + value ); + } + private void setFieldValue( SurefirePlugin plugin, String fieldName, Object value ) throws NoSuchFieldException, IllegalAccessException { diff --git a/maven-surefire-report-plugin/pom.xml b/maven-surefire-report-plugin/pom.xml index cc4036b1e8..0a6de65b81 100644 --- a/maven-surefire-report-plugin/pom.xml +++ b/maven-surefire-report-plugin/pom.xml @@ -18,14 +18,13 @@ ~ under the License. --> - + 4.0.0 org.apache.maven.surefire surefire - 2.13-SNAPSHOT + 2.16-SNAPSHOT ../pom.xml @@ -65,7 +64,22 @@ org.apache.maven maven-plugin-api + + org.apache.maven.plugin-tools + maven-plugin-annotations + + + org.apache.maven + maven-artifact + + + + + org.apache.maven.surefire + surefire-report-parser + ${project.version} + org.apache.maven.reporting @@ -123,8 +137,18 @@ org.apache.maven.plugins maven-plugin-plugin - 2.8 + 3.2 + + surefire-report + true + + + mojo-descriptor + + descriptor + + generated-helpmojo @@ -141,7 +165,7 @@ org.apache.maven.plugins maven-plugin-plugin - 2.7 + ${mavenPluginPluginVersion} 1.4 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 90cfc31402..25d3468be2 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 @@ -28,6 +28,8 @@ import java.util.ResourceBundle; import org.apache.maven.doxia.siterenderer.Renderer; import org.apache.maven.model.ReportPlugin; +import org.apache.maven.plugins.annotations.Component; +import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.project.MavenProject; import org.apache.maven.reporting.AbstractMavenReport; import org.apache.maven.reporting.MavenReportException; @@ -45,85 +47,82 @@ public abstract class AbstractSurefireReportMojo /** * Location where generated html will be created. * - * @parameter expression="${project.reporting.outputDirectory}" * @noinspection UnusedDeclaration */ + @Parameter(property = "project.reporting.outputDirectory") private File outputDirectory; /** * Doxia Site Renderer * - * @component * @noinspection UnusedDeclaration */ + @Component private Renderer siteRenderer; /** * Maven Project * - * @parameter expression="${project}" - * @required @readonly * @noinspection UnusedDeclaration */ + @Parameter(property = "project", required = true, readonly = true) private MavenProject project; /** * If set to false, only failures are shown. * - * @parameter expression="${showSuccess}" default-value="true" - * @required * @noinspection UnusedDeclaration */ + @Parameter(defaultValue = "true", required = true, property = "showSuccess") private boolean showSuccess; /** * Directories containing the XML Report files that will be parsed and rendered to HTML format. * - * @parameter * @noinspection UnusedDeclaration */ + @Parameter private File[] reportsDirectories; /** * (Deprecated, use reportsDirectories) This directory contains the XML Report files that will be parsed and rendered to HTML format. * - * @parameter * @noinspection UnusedDeclaration - * @deprecated */ + @Deprecated + @Parameter private File reportsDirectory; /** * The projects in the reactor for aggregation report. * - * @parameter expression="${reactorProjects}" - * @readonly * @noinspection MismatchedQueryAndUpdateOfCollection, UnusedDeclaration */ + @Parameter(property = "reactorProjects", readonly = true) private List reactorProjects; /** * Location of the Xrefs to link. * - * @parameter default-value="${project.reporting.outputDirectory}/xref-test" * @noinspection UnusedDeclaration */ + @Parameter(defaultValue = "${project.reporting.outputDirectory}/xref-test") private File xrefLocation; /** * Whether to link the XRef if found. * - * @parameter expression="${linkXRef}" default-value="true" * @noinspection UnusedDeclaration */ + @Parameter(defaultValue = "true", property = "linkXRef") private boolean linkXRef; /** * Whether to build an aggregated report at the root, or build individual reports. * - * @parameter expression="${aggregate}" default-value="false" * @noinspection UnusedDeclaration */ + @Parameter(defaultValue = "false", property = "aggregate") private boolean aggregate; /** 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 c2237de8b1..81e08e187c 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 @@ -22,6 +22,9 @@ import java.io.File; import java.util.Locale; import java.util.ResourceBundle; +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; @@ -31,10 +34,9 @@ * See http://jira.codehaus.org/browse/SUREFIRE-257 * * @author Stephen Connolly - * @goal failsafe-report-only - * @execute phase="validate" lifecycle="surefire" * @since 2.10 */ +@Mojo(name = "failsafe-report-only") public class FailsafeReportMojo extends AbstractSurefireReportMojo { @@ -42,29 +44,28 @@ public class FailsafeReportMojo /** * The filename to use for the report. * - * @parameter expression="${outputName}" default-value="failsafe-report" - * @required * @noinspection UnusedDeclaration */ + @Parameter(defaultValue = "failsafe-report", property = "outputName", required = true) private String outputName; /** * If set to true the failsafe report will be generated even when there are no failsafe result files. * Defaults to false to preserve legacy behaviour pre 2.10 * - * @parameter expression="${alwaysGenerateFailsafeReport}" default-value="false" * @noinspection UnusedDeclaration * @since 2.11 */ + @Parameter(defaultValue = "false", property = "alwaysGenerateFailsafeReport") private boolean alwaysGenerateFailsafeReport; /** * If set to true the failsafe report generation will be skipped. * - * @parameter expression="${skipFailsafeReport}" default-value="false" * @noinspection UnusedDeclaration * @since 2.11 */ + @Parameter(defaultValue = "false", property = "skipFailsafeReport") private boolean skipFailsafeReport; protected File getSurefireReportsDirectory( MavenProject subProject ) 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 d09ca971e1..966e99b75c 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 @@ -20,6 +20,10 @@ */ import java.io.File; +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; @@ -27,9 +31,9 @@ * Creates a nicely formatted Surefire Test Report in html format. * * @author Johnny R. Ruiz III - * @goal report - * @execute phase="test" lifecycle="surefire" */ +@Mojo(name = "report", inheritByDefault = false) +@Execute(lifecycle = "surefire", phase = LifecyclePhase.TEST) public class SurefireReportMojo extends AbstractSurefireReportMojo { @@ -37,29 +41,28 @@ public class SurefireReportMojo /** * The filename to use for the report. * - * @parameter expression="${outputName}" default-value="surefire-report" - * @required * @noinspection UnusedDeclaration */ + @Parameter(defaultValue = "surefire-report", property = "outputName", required = true) private String outputName; /** * If set to true the surefire report will be generated even when there are no surefire result files. * Defaulyts to true to preserve legacy behaviour pre 2.10. * - * @parameter expression="${alwaysGenerateSurefireReport}" default-value="true" * @noinspection UnusedDeclaration * @since 2.11 */ + @Parameter(defaultValue = "true", property = "alwaysGenerateSurefireReport") private boolean alwaysGenerateSurefireReport; /** * If set to true the surefire report generation will be skipped. * - * @parameter expression="${skipSurefireReport}" default-value="false" * @noinspection UnusedDeclaration * @since 2.11 */ + @Parameter(defaultValue = "false", property = "skipSurefireReport") private boolean skipSurefireReport; protected File getSurefireReportsDirectory( MavenProject subProject ) 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 a4208b473a..0b1fc59a39 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 @@ -19,6 +19,10 @@ * under the License. */ +import org.apache.maven.plugins.annotations.Execute; +import org.apache.maven.plugins.annotations.LifecyclePhase; +import org.apache.maven.plugins.annotations.Mojo; + /** * Creates a nicely formatted Surefire Test Report in html format. * This goal does not run the tests, it only builds the reports. @@ -26,12 +30,11 @@ * http://jira.codehaus.org/browse/SUREFIRE-257 * * @author Barrie Treloar - * @goal report-only - * @execute phase="validate" lifecycle="surefire" * @since 2.3 */ +@Mojo(name = "report-only") +@Execute(phase = LifecyclePhase.NONE) public class SurefireReportOnlyMojo extends SurefireReportMojo { - } diff --git a/maven-surefire-report-plugin/src/site/apt/examples/changing-report-name.apt.vm b/maven-surefire-report-plugin/src/site/apt/examples/changing-report-name.apt.vm index 15cc56170f..61da62f24a 100644 --- a/maven-surefire-report-plugin/src/site/apt/examples/changing-report-name.apt.vm +++ b/maven-surefire-report-plugin/src/site/apt/examples/changing-report-name.apt.vm @@ -1,10 +1,10 @@ ------- -Changing Report Name ------- -Allan Ramirez ------- -July 2006 ------- + ------ + Changing Report Name + ------ + Allan Ramirez + ------ + July 2006 + ------ ~~ Copyright 2006 The Apache Software Foundation. ~~ @@ -25,31 +25,28 @@ July 2006 Changing Report Name -In order to configure the file name of the generated report (which is -<"surefire-report"> by default), the < -> property should - be set to its new name. + In order to configure the file name of the generated report (which is + <"surefire-report"> by default), the <> property should + be set to its new name. - +----+ - - [...] - - - - org.apache.maven.plugins - maven-surefire-report-plugin - ${project.version} - - newname - - - - - [...] - - +----+ ++----+ + + [...] + + + + org.apache.maven.plugins + maven-surefire-report-plugin + ${project.version} + + newname + + + + + [...] + ++----+ - And after executing the << - >>, the generated report file is named - to < - >. + And after executing the <<>>, the generated report file is named + to <>. diff --git a/maven-surefire-report-plugin/src/site/apt/examples/cross-referencing.apt.vm b/maven-surefire-report-plugin/src/site/apt/examples/cross-referencing.apt.vm index e87600f5c6..0714e616ff 100644 --- a/maven-surefire-report-plugin/src/site/apt/examples/cross-referencing.apt.vm +++ b/maven-surefire-report-plugin/src/site/apt/examples/cross-referencing.apt.vm @@ -1,10 +1,10 @@ ------- -Source Code Cross Reference ------- -Allan Ramirez ------- -July 2006 ------- + ------ + Source Code Cross Reference + ------ + Allan Ramirez + ------ + July 2006 + ------ ~~ Copyright 2006 The Apache Software Foundation. ~~ @@ -25,65 +25,54 @@ July 2006 Source Code Cross Reference -There are times when we need to know right away the line number of the -source code that caused the failure of the test. The Surefire Report Plugin -has the capability to cross reference the source code that made the test -failed. To be able to activate it, the << ->> should - also be declared in the \ - section of the POM along with the - << - >>. For more details, please read the - documentation of the - {{{http://maven.apache.org/plugins/maven-jxr-plugin/}Maven JXR Plugin}}. + There are times when we need to know right away the line number of the + source code that caused the failure of the test. The Surefire Report Plugin + has the capability to cross reference the source code that made the test + failed. To be able to activate it, the <<>> should + also be declared in the \ section of the POM along with the + <<>>. For more details, please read the + documentation of the + {{{http://maven.apache.org/plugins/maven-jxr-plugin/}Maven JXR Plugin}}. - +----+ - - [...] - - - - org.apache.maven.plugins - maven-surefire-report-plugin - ${project.version} - - - - - - org.apache.maven.plugins - maven-jxr-plugin - 2.1 - - - - [...] - - +----+ ++----+ + + [...] + + + + org.apache.maven.plugins + maven-surefire-report-plugin + ${project.version} + + + + + + org.apache.maven.plugins + maven-jxr-plugin + 2.1 + + + + [...] + ++----+ - After executing << - >> for site generation, You'll notice that from - the < - > section of the report, the link is available to - redirect you to the source code that caused the failure. + After executing <<>> for site generation, You'll notice that from + the <> section of the report, the link is available to + redirect you to the source code that caused the failure. - From the figure below the code that caused the failure is - + From the figure below the code that caused the failure is + - [../images/failure-details.PNG] Failure Details +[../images/failure-details.PNG] Failure Details - The link will redirect you to the source by clicking it. + The link will redirect you to the source by clicking it. - [../images/xref.PNG] The source +[../images/xref.PNG] The source - * Disable the Cross Reference Link +* Disable the Cross Reference Link - To disable the link to the source code, the < - > property should - be set to < - >. Or another way is by not declaring the - << - >> to the \ - section. + To disable the link to the source code, the <> property should + be set to <>. Or another way is by not declaring the + <<>> to the \ section. diff --git a/maven-surefire-report-plugin/src/site/apt/examples/report-custom-location.apt.vm b/maven-surefire-report-plugin/src/site/apt/examples/report-custom-location.apt.vm index de5babc91a..ccebf0c268 100644 --- a/maven-surefire-report-plugin/src/site/apt/examples/report-custom-location.apt.vm +++ b/maven-surefire-report-plugin/src/site/apt/examples/report-custom-location.apt.vm @@ -1,10 +1,10 @@ ------- -Custom Location of the Surefire Report ------- -Allan Ramirez ------- -July 2006 ------- + ------ + Custom Location of the Surefire Report + ------ + Allan Ramirez + ------ + July 2006 + ------ ~~ Copyright 2006 The Apache Software Foundation. ~~ @@ -25,53 +25,48 @@ July 2006 Configuring the Output Location as part of the Project Reports -To change the location of the generated output report along with other -project reports. The < -> property of both - << - >> and << - >> should be set to the - new path. For more information, see the documentation of the - {{{http://maven.apache.org/plugins/maven-site-plugin/}Maven Site Plugin}}. + To change the location of the generated output report along with other + project reports. The <> property of both + <<>> and <<>> should be set to the + new path. For more information, see the documentation of the + {{{http://maven.apache.org/plugins/maven-site-plugin/}Maven Site Plugin}}. - +----+ - - [...] - - - - org.apache.maven.plugins - maven-surefire-report-plugin - ${project.version} - - ${basedir}/target/newsite - - - - org.apache.maven.plugins - maven-site-plugin - 2.1 - - ${basedir}/target/newsite - - - - - [...] - - +----+ ++----+ + + [...] + + + + org.apache.maven.plugins + maven-surefire-report-plugin + ${project.version} + + ${basedir}/target/newsite + + + + org.apache.maven.plugins + maven-site-plugin + 2.1 + + ${basedir}/target/newsite + + + + + [...] + ++----+ - Please take note that if the < - > of the Site Plugin - is not configured, the output location of the Surefire report will still - be the default. + Please take note that if the <> of the Site Plugin + is not configured, the output location of the Surefire report will still + be the default. - * Configuring the Output Location using Standalone Goal +* Configuring the Output Location using Standalone Goal - To change the location of the generated output report using the standalone - goal, the < - > property should be set to the new path. + To change the location of the generated output report using the standalone + goal, the <> property should be set to the new path. - +---+ - mvn surefire-report:report -DoutputDirectory=newpath - +---+ ++---+ +mvn surefire-report:report -DoutputDirectory=newpath ++---+ diff --git a/maven-surefire-report-plugin/src/site/apt/examples/show-failures.apt.vm b/maven-surefire-report-plugin/src/site/apt/examples/show-failures.apt.vm index 0fdcd52fce..7ee1edde2f 100644 --- a/maven-surefire-report-plugin/src/site/apt/examples/show-failures.apt.vm +++ b/maven-surefire-report-plugin/src/site/apt/examples/show-failures.apt.vm @@ -1,10 +1,10 @@ ------- -Showing Failure Tests ------- -Allan Ramirez ------- -July 2006 ------- + ------ + Showing Failure Tests + ------ + Allan Ramirez + ------ + July 2006 + ------ ~~ Copyright 2006 The Apache Software Foundation. ~~ @@ -25,36 +25,33 @@ July 2006 Showing Failure Tests -By default, the Surefire Report Plugin shows all test result status (success -and failures) in the generated HTML. To be able to show the failures only, the -property < -> should be set to < - >. - - +----+ - - [...] - - - - org.apache.maven.plugins - maven-surefire-report-plugin - ${project.version} - - false - - - - - [...] - - +----+ - - Then execute << - >> for the report generation. - - It can also be set via commandline with the standalone goal. - - +----+ - mvn surefire-report:report -DshowSuccess=false - +----+ + By default, the Surefire Report Plugin shows all test result status (success + and failures) in the generated HTML. To be able to show the failures only, the + property <> should be set to <>. + ++----+ + + [...] + + + + org.apache.maven.plugins + maven-surefire-report-plugin + ${project.version} + + false + + + + + [...] + ++----+ + + Then execute <<>> for the report generation. + + It can also be set via commandline with the standalone goal. + ++----+ + mvn surefire-report:report -DshowSuccess=false ++----+ diff --git a/maven-surefire-report-plugin/src/site/apt/usage.apt.vm b/maven-surefire-report-plugin/src/site/apt/usage.apt.vm index 62ba3664bd..ef71d13ac7 100644 --- a/maven-surefire-report-plugin/src/site/apt/usage.apt.vm +++ b/maven-surefire-report-plugin/src/site/apt/usage.apt.vm @@ -1,10 +1,10 @@ ------- -Usage ------- -Allan Ramirez ------- -July 2006 ------- + ------ + Usage + ------ + Allan Ramirez + ------ + July 2006 + ------ ~~ Copyright 2006 The Apache Software Foundation. ~~ @@ -27,41 +27,39 @@ Usage * Generate the report as part of Project Reports -To generate the Surefire report as part of the site generation, add the following in -the \ - section of your POM: + To generate the Surefire report as part of the site generation, add the following in + the \ section of your POM: +---+ - ... - - - - org.apache.maven.plugins - maven-surefire-report-plugin - ${project.version} - - - - ... + ... + + + + org.apache.maven.plugins + maven-surefire-report-plugin + ${project.version} + + + + ... +---+ -When the << ->> is invoked, the report will be automatically - included in the Project Reports menu as shown in the figure below. + When the <<>> is invoked, the report will be automatically + included in the Project Reports menu as shown in the figure below. - [images/surefire-sample1.PNG] Sample Surefire Report +[images/surefire-sample1.PNG] Sample Surefire Report - * Generate the report as standalone +* Generate the report as standalone - The Surefire report can also generate the report using its standalone goal: + The Surefire report can also generate the report using its standalone goal: - +---+ - mvn surefire-report:report - +---+ ++---+ +mvn surefire-report:report ++---+ - A HTML report should be generated in <<<$\{basedir\}/target/site/surefire-report.html>>>. + A HTML report should be generated in <<<$\{basedir\}/target/site/surefire-report.html>>>. - [images/surefire-sample2.PNG] Sample standalone surefire-report +[images/surefire-sample2.PNG] Sample standalone surefire-report diff --git a/maven-surefire-report-plugin/src/site/site.xml b/maven-surefire-report-plugin/src/site/site.xml index 34ef9108b6..65ad07038d 100644 --- a/maven-surefire-report-plugin/src/site/site.xml +++ b/maven-surefire-report-plugin/src/site/site.xml @@ -20,11 +20,6 @@ --> - - org.apache.maven.skins - maven-fluido-skin - 1.0 - diff --git a/pom.xml b/pom.xml index 2ee3ba6fc2..0dff50fd71 100644 --- a/pom.xml +++ b/pom.xml @@ -17,8 +17,7 @@ ~ under the License. --> - + 4.0.0 @@ -30,10 +29,10 @@ org.apache.maven.surefire surefire - 2.13-SNAPSHOT + 2.16-SNAPSHOT pom - SureFire + Apache Maven Surefire Surefire is a test framework project. http://maven.apache.org/surefire 2004 @@ -90,6 +89,7 @@ surefire-grouper surefire-providers maven-surefire-common + surefire-report-parser maven-surefire-plugin maven-failsafe-plugin maven-surefire-report-plugin @@ -108,15 +108,29 @@ Jenkins - https://builds.apache.org/hudson/job/maven-surefire/ + https://builds.apache.org/job/maven-surefire/ 2.0.9 2.12.4 3.2 + + + ${user.home}/maven-sites + ${maven.site.cache}/surefire-${project.version} + file://${maven.surefire.siteFilePath} + ${maven.site.cache}/maven-surefire-site-content-${project.version} + https://svn.apache.org/repos/infra/websites/production/maven/content/surefire-archives/maven-surefire-${project.version} + + + apache.website + ${maven.surefire.siteUrlDeployment} + + + @@ -129,6 +143,11 @@ commons-lang3 3.1 + + commons-io + commons-io + 2.2 + org.apache.maven.surefire surefire-booter @@ -144,6 +163,11 @@ maven-surefire-common ${project.version} + + org.apache.maven.reporting + maven-reporting-api + ${mavenVersion} + org.apache.maven maven-core @@ -222,7 +246,12 @@ org.apache.maven.shared maven-shared-utils - 0.2-SNAPSHOT + 0.4 + + + org.apache.maven.shared + maven-verifier + 1.4 jmock @@ -236,6 +265,12 @@ 3.8.1 test + + com.google.code.findbugs + jsr305 + 2.0.1 + provided + @@ -278,6 +313,34 @@ maven-plugin-plugin ${mavenPluginPluginVersion} + + true + true + + + + org.apache.maven.plugins + maven-site-plugin + 3.3 + + + org.apache.maven.doxia + doxia-module-markdown + 1.3 + + + + + org.apache.maven.plugins + maven-scm-publish-plugin + 1.0-beta-2 + + ${maven.surefire.scmPubCheckoutDirectory} + scm:svn:${maven.surefire.scmPubUrl} + Apache Maven Surefire site deployment + ${maven.surefire.siteFilePath} + true + org.apache.rat @@ -304,6 +367,57 @@ + + + + org.apache.maven.plugins + maven-project-info-reports-plugin + 2.6 + + false + + + + + index + summary + dependency-info + modules + license + project-team + scm + issue-tracking + mailing-list + dependency-management + dependencies + dependency-convergence + cim + plugin-management + plugins + distribution-management + + + + + + org.apache.maven.plugins + maven-surefire-report-plugin + ${shadedVersion} + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.9 + + + + + + + reporting @@ -318,31 +432,12 @@ org.apache.maven.plugins maven-site-plugin - 3.0 - - - - org.apache.maven.plugins - maven-surefire-plugin - ${project.version} - - - org.apache.maven.plugins - maven-project-info-reports-plugin - 2.6 - - - org.apache.maven.plugins - maven-plugin-plugin - - - - + @@ -369,9 +464,9 @@ customizable - - - + + + org.apache.maven.plugins:maven-resources-plugin:: @@ -381,5 +476,14 @@ + + site-release + + ${maven.site.cache}/surefire + file://${maven.surefire.siteFilePath} + ${maven.site.cache}/maven-surefire-site-content + https://svn.apache.org/repos/infra/websites/production/maven/content/surefire + + diff --git a/src/site/site.xml b/src/site/site.xml index 91b85e1253..acba838bcd 100644 --- a/src/site/site.xml +++ b/src/site/site.xml @@ -20,13 +20,46 @@ --> + + + ${project.name} + http://maven.apache.org/images/apache-maven-project.png + http://maven.apache.org/ + + + http://maven.apache.org/images/maventxt_logo_200.gif + + org.apache.maven.skins maven-fluido-skin - 1.2.2 + 1.3.0 + + + + true + true + + ${project.url} + + + apache/maven-surefire + right + gray + + + + + +
+
Apache ${project.name}, ${project.name}, Apache, the Apache feather logo, and the Apache ${project.name} project logos are trademarks of The Apache Software Foundation.
+ +
diff --git a/surefire-api/pom.xml b/surefire-api/pom.xml index caa5880c20..aa339256a6 100644 --- a/surefire-api/pom.xml +++ b/surefire-api/pom.xml @@ -17,14 +17,13 @@ ~ under the License. --> - + 4.0.0 org.apache.maven.surefire surefire - 2.13-SNAPSHOT + 2.16-SNAPSHOT ../pom.xml @@ -47,17 +46,10 @@ org.apache.maven.surefire surefire-shadefire - ${project.version} + ${shadedVersion} - - maven-compiler-plugin - - 1.3 - 1.3 - - org.apache.maven.plugins maven-shade-plugin @@ -71,16 +63,11 @@ true - org.codehaus.plexus:plexus-utils org.apache.maven.shared:maven-shared-utils commons-lang:commons-lang - - org.codehaus.plexus.util - org.apache.maven.surefire.shade.org.codehaus.plexus.util - org.apache.maven.shared org.apache.maven.surefire.shade.org.apache.maven.shared diff --git a/surefire-api/src/main/java/org/apache/maven/plugin/surefire/runorder/RunEntryStatistics.java b/surefire-api/src/main/java/org/apache/maven/plugin/surefire/runorder/RunEntryStatistics.java index c2465f588e..73d2adff72 100644 --- a/surefire-api/src/main/java/org/apache/maven/plugin/surefire/runorder/RunEntryStatistics.java +++ b/surefire-api/src/main/java/org/apache/maven/plugin/surefire/runorder/RunEntryStatistics.java @@ -42,7 +42,7 @@ private RunEntryStatistics( int runTime, int successfulBuilds, String testName ) public static RunEntryStatistics fromReportEntry( ReportEntry previous ) { final Integer elapsed = previous.getElapsed(); - return new RunEntryStatistics( elapsed != null ? elapsed.intValue() : 0, 0, previous.getName() ); + return new RunEntryStatistics( elapsed != null ? elapsed : 0, 0, previous.getName() ); } public static RunEntryStatistics fromValues( int runTime, int successfulBuilds, Class clazz, String testName ) @@ -87,7 +87,7 @@ public static RunEntryStatistics fromString( String line ) public String getAsString() { - StringBuffer stringBuffer = new StringBuffer(); + StringBuilder stringBuffer = new StringBuilder(); stringBuffer.append( successfulBuilds ); stringBuffer.append( "," ); stringBuffer.append( runTime ); diff --git a/surefire-api/src/main/java/org/apache/maven/plugin/surefire/runorder/RunEntryStatisticsMap.java b/surefire-api/src/main/java/org/apache/maven/plugin/surefire/runorder/RunEntryStatisticsMap.java index cd4e8ebe5f..5c516895b3 100644 --- a/surefire-api/src/main/java/org/apache/maven/plugin/surefire/runorder/RunEntryStatisticsMap.java +++ b/surefire-api/src/main/java/org/apache/maven/plugin/surefire/runorder/RunEntryStatisticsMap.java @@ -20,6 +20,8 @@ */ +import org.apache.maven.surefire.report.ReportEntry; + import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; @@ -32,28 +34,26 @@ import java.util.Collections; import java.util.Comparator; import java.util.HashMap; -import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; -import org.apache.maven.surefire.report.ReportEntry; /** * @author Kristian Rosenvold */ public class RunEntryStatisticsMap { - private final Map runEntryStatistics; + private final Map runEntryStatistics; - public RunEntryStatisticsMap( Map runEntryStatistics ) + public RunEntryStatisticsMap( Map runEntryStatistics ) { this.runEntryStatistics = Collections.synchronizedMap( runEntryStatistics ); } public RunEntryStatisticsMap() { - this( new HashMap() ); + this( new HashMap() ); } public static RunEntryStatisticsMap fromFile( File file ) @@ -81,7 +81,7 @@ public static RunEntryStatisticsMap fromFile( File file ) static RunEntryStatisticsMap fromReader( Reader fileReader ) throws IOException { - Map result = new HashMap(); + Map result = new HashMap(); BufferedReader bufferedReader = new BufferedReader( fileReader ); String line = bufferedReader.readLine(); while ( line != null ) @@ -101,12 +101,12 @@ public void serialize( File file ) { FileOutputStream fos = new FileOutputStream( file ); PrintWriter printWriter = new PrintWriter( fos ); - List items = new ArrayList( runEntryStatistics.values() ); + List items = new ArrayList( runEntryStatistics.values() ); Collections.sort( items, new RunCountComparator() ); RunEntryStatistics item; - for ( Iterator iter = items.iterator(); iter.hasNext(); ) + for ( RunEntryStatistics item1 : items ) { - item = (RunEntryStatistics) iter.next(); + item = item1; printWriter.println( item.getAsString() ); } printWriter.close(); @@ -115,7 +115,7 @@ public void serialize( File file ) public RunEntryStatistics findOrCreate( ReportEntry reportEntry ) { - final RunEntryStatistics item = (RunEntryStatistics) runEntryStatistics.get( reportEntry.getName() ); + final RunEntryStatistics item = runEntryStatistics.get( reportEntry.getName() ); return item != null ? item : RunEntryStatistics.fromReportEntry( reportEntry ); } @@ -123,14 +123,14 @@ public RunEntryStatistics createNextGeneration( ReportEntry reportEntry ) { final RunEntryStatistics newItem = findOrCreate( reportEntry ); final Integer elapsed = reportEntry.getElapsed(); - return newItem.nextGeneration( elapsed != null ? elapsed.intValue() : 0 ); + return newItem.nextGeneration( elapsed != null ? elapsed : 0 ); } public RunEntryStatistics createNextGenerationFailure( ReportEntry reportEntry ) { final RunEntryStatistics newItem = findOrCreate( reportEntry ); final Integer elapsed = reportEntry.getElapsed(); - return newItem.nextGenerationFailure( elapsed != null ? elapsed.intValue() : 0 ); + return newItem.nextGenerationFailure( elapsed != null ? elapsed : 0 ); } public void add( RunEntryStatistics item ) @@ -139,49 +139,47 @@ public void add( RunEntryStatistics item ) } class RunCountComparator - implements Comparator + implements Comparator { - public int compare( Object o, Object o1 ) + public int compare( RunEntryStatistics o, RunEntryStatistics o1 ) { - RunEntryStatistics re = (RunEntryStatistics) o; - RunEntryStatistics re1 = (RunEntryStatistics) o1; - int runtime = re.getSuccessfulBuilds() - re1.getSuccessfulBuilds(); + int runtime = o.getSuccessfulBuilds() - o1.getSuccessfulBuilds(); if ( runtime == 0 ) { - return re.getRunTime() - re1.getRunTime(); + return o.getRunTime() - o1.getRunTime(); } return runtime; } } - public List getPrioritizedTestsClassRunTime( List testsToRun, int threadCount ) + public List getPrioritizedTestsClassRunTime( List testsToRun, int threadCount ) { - final List prioritizedTests = getPrioritizedTests( testsToRun, new TestRuntimeComparator() ); + final List prioritizedTests = getPrioritizedTests( testsToRun, new TestRuntimeComparator() ); ThreadedExecutionScheduler threadedExecutionScheduler = new ThreadedExecutionScheduler( threadCount ); - for ( Iterator prioritizedTest = prioritizedTests.iterator(); prioritizedTest.hasNext(); ) + for ( Object prioritizedTest1 : prioritizedTests ) { - threadedExecutionScheduler.addTest( (PrioritizedTest) prioritizedTest.next() ); + threadedExecutionScheduler.addTest( (PrioritizedTest) prioritizedTest1 ); } return threadedExecutionScheduler.getResult(); } - public List getPrioritizedTestsByFailureFirst( List testsToRun ) + public List getPrioritizedTestsByFailureFirst( List testsToRun ) { final List prioritizedTests = getPrioritizedTests( testsToRun, new LeastFailureComparator() ); return transformToClasses( prioritizedTests ); } - private List getPrioritizedTests( List testsToRun, Comparator priorityComparator ) + private List getPrioritizedTests( List testsToRun, Comparator priorityComparator ) { Map classPriorities = getPriorities( priorityComparator ); - List tests = new ArrayList(); - for ( Iterator iter = testsToRun.iterator(); iter.hasNext(); ) + List tests = new ArrayList(); + for ( Object aTestsToRun : testsToRun ) { - Class clazz = (Class) iter.next(); + Class clazz = (Class) aTestsToRun; Priority pri = (Priority) classPriorities.get( clazz.getName() ); if ( pri == null ) { @@ -195,41 +193,40 @@ private List getPrioritizedTests( List testsToRun, Comparator priorityComparator } - private List transformToClasses( List tests ) + private List transformToClasses( List tests ) { - List result = new ArrayList(); - for ( int i = 0; i < tests.size(); i++ ) + List result = new ArrayList(); + for ( Object test : tests ) { - result.add( ( (PrioritizedTest) tests.get( i ) ).getClazz() ); + result.add( ( (PrioritizedTest) test ).getClazz() ); } return result; } - public Map getPriorities( Comparator priorityComparator ) + public Map getPriorities( Comparator priorityComparator ) { - Map priorities = new HashMap(); - for ( Iterator iter = runEntryStatistics.keySet().iterator(); iter.hasNext(); ) + Map priorities = new HashMap(); + for ( Object o : runEntryStatistics.keySet() ) { - String testNames = (String) iter.next(); + String testNames = (String) o; String clazzName = extractClassName( testNames ); - Priority priority = (Priority) priorities.get( clazzName ); + Priority priority = priorities.get( clazzName ); if ( priority == null ) { priority = new Priority( clazzName ); priorities.put( clazzName, priority ); } - RunEntryStatistics itemStat = (RunEntryStatistics) runEntryStatistics.get( testNames ); + RunEntryStatistics itemStat = runEntryStatistics.get( testNames ); priority.addItem( itemStat ); } - List items = new ArrayList( priorities.values() ); + List items = new ArrayList( priorities.values() ); Collections.sort( items, priorityComparator ); - Map result = new HashMap(); + Map result = new HashMap(); int i = 0; - for ( Iterator iter = items.iterator(); iter.hasNext(); ) + for ( Priority pri : items ) { - Priority pri = (Priority) iter.next(); pri.setPriority( i++ ); result.put( pri.getClassName(), pri ); } @@ -237,35 +234,29 @@ public Map getPriorities( Comparator priorityComparator ) } class PrioritizedTestComparator - implements Comparator + implements Comparator { - public int compare( Object o, Object o1 ) + public int compare( PrioritizedTest o, PrioritizedTest o1 ) { - PrioritizedTest re = (PrioritizedTest) o; - PrioritizedTest re1 = (PrioritizedTest) o1; - return re.getPriority() - re1.getPriority(); + return o.getPriority() - o1.getPriority(); } } class TestRuntimeComparator - implements Comparator + implements Comparator { - public int compare( Object o, Object o1 ) + public int compare( Priority o, Priority o1 ) { - Priority re = (Priority) o; - Priority re1 = (Priority) o1; - return re1.getTotalRuntime() - re.getTotalRuntime(); + return o1.getTotalRuntime() - o.getTotalRuntime(); } } class LeastFailureComparator - implements Comparator + implements Comparator { - public int compare( Object o, Object o1 ) + public int compare( Priority o, Priority o1 ) { - Priority re = (Priority) o; - Priority re1 = (Priority) o1; - return re.getMinSuccessRate() - re1.getMinSuccessRate(); + return o.getMinSuccessRate() - o1.getMinSuccessRate(); } } diff --git a/surefire-api/src/main/java/org/apache/maven/plugin/surefire/runorder/ThreadedExecutionScheduler.java b/surefire-api/src/main/java/org/apache/maven/plugin/surefire/runorder/ThreadedExecutionScheduler.java index ea3f8a623c..6519ff63ba 100644 --- a/surefire-api/src/main/java/org/apache/maven/plugin/surefire/runorder/ThreadedExecutionScheduler.java +++ b/surefire-api/src/main/java/org/apache/maven/plugin/surefire/runorder/ThreadedExecutionScheduler.java @@ -40,7 +40,7 @@ public ThreadedExecutionScheduler( int numThreads ) lists = new List[numThreads]; for ( int i = 0; i < numThreads; i++ ) { - lists[i] = new ArrayList(); + lists[i] = new ArrayList(); } } @@ -48,14 +48,15 @@ public void addTest( PrioritizedTest prioritizedTest ) { final int leastBusySlot = findLeastBusySlot(); runTime[leastBusySlot] += prioritizedTest.getTotalRuntime(); + //noinspection unchecked lists[leastBusySlot].add( prioritizedTest.getClazz() ); } - public List getResult() + public List getResult() { - List result = new ArrayList(); + List result = new ArrayList(); int index = 0; - boolean added = false; + boolean added; do { added = false; @@ -63,7 +64,7 @@ public List getResult() { if ( lists[i].size() > index ) { - result.add( lists[i].get( index ) ); + result.add( (Class) lists[i].get( index ) ); added = true; } } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/SpecificTestClassFilter.java b/surefire-api/src/main/java/org/apache/maven/surefire/SpecificTestClassFilter.java index 31b1340f2d..6288e8a8fe 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/SpecificTestClassFilter.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/SpecificTestClassFilter.java @@ -18,8 +18,8 @@ * under the License. */ +import java.util.Collections; import java.util.HashSet; -import java.util.Iterator; import java.util.Set; import org.apache.maven.shared.utils.io.SelectorUtils; import org.apache.maven.surefire.util.ScannerFilter; @@ -32,18 +32,14 @@ public class SpecificTestClassFilter private static final String JAVA_CLASS_FILE_EXTENSION = ".class"; - private Set names; + private Set names; public SpecificTestClassFilter( String[] classNames ) { if ( classNames != null && classNames.length > 0 ) { - this.names = new HashSet(); - for ( int i = 0; i < classNames.length; i++ ) - { - String name = classNames[i]; - names.add( name ); - } + this.names = new HashSet(); + Collections.addAll( names, classNames ); } } @@ -57,9 +53,8 @@ public boolean accept( Class testClass ) String className = testClass.getName().replace( '.', FS ) + JAVA_CLASS_FILE_EXTENSION; boolean found = false; - for ( Iterator it = names.iterator(); it.hasNext(); ) + for ( String pattern : names ) { - String pattern = (String) it.next(); if ( '\\' == FS ) { pattern = pattern.replace( '/', FS ); diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/booter/BaseProviderFactory.java b/surefire-api/src/main/java/org/apache/maven/surefire/booter/BaseProviderFactory.java index 626ff52e9b..a5e7daff17 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/booter/BaseProviderFactory.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/booter/BaseProviderFactory.java @@ -58,7 +58,7 @@ public class BaseProviderFactory private TestArtifactInfo testArtifactInfo; - private static final Integer ROOT_CHANNEl = new Integer( 0 ); + private static final Integer ROOT_CHANNEl = 0; private final ReporterFactory reporterFactory; @@ -69,7 +69,7 @@ public class BaseProviderFactory public BaseProviderFactory( ReporterFactory reporterFactory, Boolean insideFork ) { this.reporterFactory = reporterFactory; - this.insideFork = insideFork.booleanValue(); + this.insideFork = insideFork; } public DirectoryScanner getDirectoryScanner() @@ -119,7 +119,7 @@ public void setReporterConfiguration( ReporterConfiguration reporterConfiguratio this.reporterConfiguration = reporterConfiguration; } - public void setClassLoaders( ClassLoader surefireClassLoader, ClassLoader testClassLoader ) + public void setClassLoaders( ClassLoader testClassLoader ) { this.testClassLoader = testClassLoader; } @@ -128,8 +128,8 @@ public ConsoleLogger getConsoleLogger() { if ( insideFork ) { - return new ForkingRunListener( reporterConfiguration.getOriginalSystemOut(), ROOT_CHANNEl.intValue(), - reporterConfiguration.isTrimStackTrace().booleanValue() ); + return new ForkingRunListener( reporterConfiguration.getOriginalSystemOut(), ROOT_CHANNEl, + reporterConfiguration.isTrimStackTrace() ); } return new DefaultDirectConsoleReporter( reporterConfiguration.getOriginalSystemOut() ); } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/booter/ForkingReporterFactory.java b/surefire-api/src/main/java/org/apache/maven/surefire/booter/ForkingReporterFactory.java index de4bbdd5ea..ad8c87b555 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/booter/ForkingReporterFactory.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/booter/ForkingReporterFactory.java @@ -50,7 +50,7 @@ public ForkingReporterFactory( Boolean trimstackTrace, PrintStream originalSyste public synchronized RunListener createReporter() { - return new ForkingRunListener( originalSystemOut, testSetChannelId++, isTrimstackTrace.booleanValue() ); + return new ForkingRunListener( originalSystemOut, testSetChannelId++, isTrimstackTrace ); } public RunResult close() diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/booter/ForkingRunListener.java b/surefire-api/src/main/java/org/apache/maven/surefire/booter/ForkingRunListener.java index 0af3e5905c..9a8beecce9 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/booter/ForkingRunListener.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/booter/ForkingRunListener.java @@ -81,6 +81,7 @@ public class ForkingRunListener public static final byte BOOTERCODE_BYE = (byte) 'Z'; + private final PrintStream target; private final Integer testSetChannelId; @@ -94,7 +95,7 @@ public class ForkingRunListener public ForkingRunListener( PrintStream target, int testSetChannelId, boolean trimStackTraces ) { this.target = target; - this.testSetChannelId = new Integer( testSetChannelId ); + this.testSetChannelId = testSetChannelId; this.trimStackTraces = trimStackTraces; stdOutHeader = createHeader( BOOTERCODE_STDOUT, testSetChannelId ); stdErrHeader = createHeader( BOOTERCODE_STDERR, testSetChannelId ); @@ -131,7 +132,6 @@ public void testError( ReportEntry report ) target.print( toString( BOOTERCODE_TEST_ERROR, report, testSetChannelId ) ); } - public void testFailed( ReportEntry report ) { target.print( toString( BOOTERCODE_TEST_FAILED, report, testSetChannelId ) ); @@ -232,8 +232,10 @@ public void info( String message ) private String toPropertyString( String key, String value ) { StringBuffer stringBuffer = new StringBuffer(); - append( stringBuffer, BOOTERCODE_SYSPROPS ).comma( stringBuffer ); - append( stringBuffer, Integer.toHexString( testSetChannelId.intValue() ) ).comma( stringBuffer ); + + append( stringBuffer, BOOTERCODE_SYSPROPS );comma( stringBuffer ); + append( stringBuffer, Integer.toHexString( testSetChannelId ) );comma( stringBuffer ); + StringUtils.escapeJavaStyleString( stringBuffer, key ); append( stringBuffer, "," ); StringUtils.escapeJavaStyleString( stringBuffer, value ); @@ -244,8 +246,9 @@ private String toPropertyString( String key, String value ) private String toString( byte operationCode, ReportEntry reportEntry, Integer testSetChannelId ) { StringBuffer stringBuffer = new StringBuffer(); - append( stringBuffer, operationCode ).comma( stringBuffer ); - append( stringBuffer, Integer.toHexString( testSetChannelId.intValue() ) ).comma( stringBuffer ); + append( stringBuffer, operationCode ); comma( stringBuffer ); + append( stringBuffer, Integer.toHexString( testSetChannelId ) );comma( stringBuffer ); + nullableEncoding( stringBuffer, reportEntry.getSourceName() ); comma( stringBuffer ); nullableEncoding( stringBuffer, reportEntry.getName() ); @@ -325,7 +328,8 @@ public static void encode( StringBuffer stringBuffer, StackTraceWriter stackTrac nullableEncoding( stringBuffer, message ); } comma( stringBuffer ); - + nullableEncoding( stringBuffer, stackTraceWriter.smartTrimmedStackTrace() ); + comma( stringBuffer ); nullableEncoding( stringBuffer, trimStackTraces ? stackTraceWriter.writeTrimmedTraceToString() : stackTraceWriter.writeTraceToString() ); diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/booter/JdkReflector.java b/surefire-api/src/main/java/org/apache/maven/surefire/booter/JdkReflector.java deleted file mode 100644 index cf1eb5472a..0000000000 --- a/surefire-api/src/main/java/org/apache/maven/surefire/booter/JdkReflector.java +++ /dev/null @@ -1,64 +0,0 @@ -package org.apache.maven.surefire.booter; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES 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.lang.reflect.Method; -import org.apache.maven.surefire.util.NestedRuntimeException; -import org.apache.maven.surefire.util.ReflectionUtils; - -/** - * Does reflection based invocation of misc jdk method - *

- * - * @author Kristian Rosenvold - */ -public class JdkReflector -{ - private final Method assertionStatusMethod; - - - public JdkReflector() - { - assertionStatusMethod = ReflectionUtils.tryGetMethod( ClassLoader.class, "setDefaultAssertionStatus", - new Class[]{ boolean.class } ); - } - - public void invokeAssertionStatusMethod( ClassLoader classLoader, boolean enableAssertions ) - { - if ( assertionStatusMethod != null ) - { - try - { - Object[] args = new Object[]{ enableAssertions ? Boolean.TRUE : Boolean.FALSE }; - assertionStatusMethod.invoke( classLoader, args ); - } - catch ( IllegalAccessException e ) - { - throw new NestedRuntimeException( "Unable to access the assertion enablement method", e ); - } - catch ( InvocationTargetException e ) - { - throw new NestedRuntimeException( "Unable to invoke the assertion enablement method", e ); - } - } - } - -} diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/booter/SurefireClassLoadersAware.java b/surefire-api/src/main/java/org/apache/maven/surefire/booter/SurefireClassLoadersAware.java index 085e60a760..d55002eeac 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/booter/SurefireClassLoadersAware.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/booter/SurefireClassLoadersAware.java @@ -25,5 +25,5 @@ */ public interface SurefireClassLoadersAware { - void setClassLoaders( ClassLoader surefireClassLoader, ClassLoader testClassLoader ); + void setClassLoaders( ClassLoader testClassLoader ); } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/booter/SurefireReflector.java b/surefire-api/src/main/java/org/apache/maven/surefire/booter/SurefireReflector.java index aec4e92e62..54a6b5bf96 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/booter/SurefireReflector.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/booter/SurefireReflector.java @@ -115,8 +115,7 @@ public Object convertIfRunResult( Object result ) final Integer getErrors = (Integer) ReflectionUtils.invokeGetter( result, "getErrors" ); final Integer getSkipped = (Integer) ReflectionUtils.invokeGetter( result, "getSkipped" ); final Integer getFailures = (Integer) ReflectionUtils.invokeGetter( result, "getFailures" ); - return new RunResult( getCompletedCount1.intValue(), getErrors.intValue(), getFailures.intValue(), - getSkipped.intValue() ); + return new RunResult( getCompletedCount1, getErrors, getFailures, getSkipped ); } @@ -218,12 +217,9 @@ Object createReporterConfiguration( ReporterConfiguration reporterConfiguration reporterConfiguration.isTrimStackTrace() } ); } - public Object createForkingReporterFactory( Boolean trimStackTrace, PrintStream originalSystemOut ) + public static ReporterFactory createForkingReporterFactoryInCurrentClassLoader( Boolean trimStackTrace, PrintStream originalSystemOut ) { - Class[] args = new Class[]{ Boolean.class, PrintStream.class }; - Object[] values = new Object[]{ trimStackTrace, originalSystemOut }; - return ReflectionUtils.instantiateObject( ForkingReporterFactory.class.getName(), args, values, - surefireClassLoader ); + return new ForkingReporterFactory( trimStackTrace, originalSystemOut ); } public Object createBooterConfiguration( ClassLoader surefireClassLoader, Object factoryInstance, @@ -303,19 +299,19 @@ void setReporterConfiguration( Object o, ReporterConfiguration reporterConfigura ReflectionUtils.invokeSetter( o, "setReporterConfiguration", this.reporterConfiguration, param ); } - public void setTestClassLoaderAware( Object o, ClassLoader surefireClassLoader, ClassLoader testClassLoader ) + public void setTestClassLoaderAware( Object o, ClassLoader testClassLoader ) { if ( testClassLoaderAware.isAssignableFrom( o.getClass() ) ) { - setTestClassLoader( o, surefireClassLoader, testClassLoader ); + setTestClassLoader( o, testClassLoader ); } } - void setTestClassLoader( Object o, ClassLoader surefireClassLoader, ClassLoader testClassLoader ) + void setTestClassLoader( Object o, ClassLoader testClassLoader ) { final Method setter = - ReflectionUtils.getMethod( o, "setClassLoaders", new Class[]{ ClassLoader.class, ClassLoader.class } ); - ReflectionUtils.invokeMethodWithArray( o, setter, new Object[]{ surefireClassLoader, testClassLoader } ); + ReflectionUtils.getMethod( o, "setClassLoaders", new Class[]{ ClassLoader.class } ); + ReflectionUtils.invokeMethodWithArray( o, setter, new Object[]{ testClassLoader } ); } public void setTestArtifactInfoAware( Object o, TestArtifactInfo testArtifactInfo1 ) diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/report/CategorizedReportEntry.java b/surefire-api/src/main/java/org/apache/maven/surefire/report/CategorizedReportEntry.java index a91174e3bb..77cfaf363e 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/report/CategorizedReportEntry.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/report/CategorizedReportEntry.java @@ -26,6 +26,10 @@ public class CategorizedReportEntry extends SimpleReportEntry implements ReportEntry { + private static final String GROUP_PREFIX = " (of "; + + private static final String GROUP_SUFIX = ")"; + private final String group; public CategorizedReportEntry( String source, String name, String group ) @@ -60,6 +64,22 @@ public String getGroup() return group; } + @Override + public String getNameWithGroup() + { + StringBuilder result = new StringBuilder(); + result.append( getName() ); + + if ( getGroup() != null && !getName().equals( getGroup() ) ) + { + result.append( GROUP_PREFIX ); + result.append( getGroup() ); + result.append( GROUP_SUFIX ); + } + + return result.toString(); + } + public boolean equals( Object o ) { if ( this == o ) diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/report/ConsoleOutputCapture.java b/surefire-api/src/main/java/org/apache/maven/surefire/report/ConsoleOutputCapture.java index 9f237fd1f6..c7c6069d80 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/report/ConsoleOutputCapture.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/report/ConsoleOutputCapture.java @@ -53,6 +53,8 @@ private static class ForwardingPrintStream public void write( byte[] buf, int off, int len ) { + // Note: At this point the supplied "buf" instance is reused, which means + // data must be copied out of the buffer target.writeTestOutput( buf, off, len, isStdout ); } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/report/ConsoleOutputReceiverForCurrentThread.java b/surefire-api/src/main/java/org/apache/maven/surefire/report/ConsoleOutputReceiverForCurrentThread.java index c13bd4bd89..fb0152c74b 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/report/ConsoleOutputReceiverForCurrentThread.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/report/ConsoleOutputReceiverForCurrentThread.java @@ -24,7 +24,7 @@ */ public final class ConsoleOutputReceiverForCurrentThread { - private static final ThreadLocal current = new InheritableThreadLocal(); + private static final ThreadLocal current = new InheritableThreadLocal(); private ConsoleOutputReceiverForCurrentThread() { @@ -32,7 +32,7 @@ private ConsoleOutputReceiverForCurrentThread() public static ConsoleOutputReceiver get() { - return (ConsoleOutputReceiver) current.get(); + return current.get(); } public static void set( ConsoleOutputReceiver consoleOutputReceiver ) diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/report/DefaultConsoleReporter.java b/surefire-api/src/main/java/org/apache/maven/surefire/report/DefaultConsoleReporter.java index edb733ff36..6c5c850c05 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/report/DefaultConsoleReporter.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/report/DefaultConsoleReporter.java @@ -1,41 +1,41 @@ -package org.apache.maven.surefire.report; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES 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.PrintStream; - -/** - * @author Kristian Rosenvold - */ -public class DefaultConsoleReporter - implements ConsoleLogger -{ - private final PrintStream systemOut; - - public DefaultConsoleReporter( PrintStream systemOut ) - { - this.systemOut = systemOut; - } - - public void info( String message ) - { - systemOut.println( message ); - } -} +package org.apache.maven.surefire.report; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES 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.PrintStream; + +/** + * @author Kristian Rosenvold + */ +public class DefaultConsoleReporter + implements ConsoleLogger +{ + private final PrintStream systemOut; + + public DefaultConsoleReporter( PrintStream systemOut ) + { + this.systemOut = systemOut; + } + + public void info( String message ) + { + systemOut.println( message ); + } +} diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/report/DefaultDirectConsoleReporter.java b/surefire-api/src/main/java/org/apache/maven/surefire/report/DefaultDirectConsoleReporter.java index 3f341c3608..caee844d72 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/report/DefaultDirectConsoleReporter.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/report/DefaultDirectConsoleReporter.java @@ -1,40 +1,40 @@ -package org.apache.maven.surefire.report; -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES 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.PrintStream; - -/** - * @author Kristian Rosenvold - */ -public class DefaultDirectConsoleReporter - implements ConsoleLogger -{ - private final PrintStream systemOut; - - public DefaultDirectConsoleReporter( PrintStream systemOut ) - { - this.systemOut = systemOut; - } - - public void info( String message ) - { - systemOut.println( message ); - } -} +package org.apache.maven.surefire.report; +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES 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.PrintStream; + +/** + * @author Kristian Rosenvold + */ +public class DefaultDirectConsoleReporter + implements ConsoleLogger +{ + private final PrintStream systemOut; + + public DefaultDirectConsoleReporter( PrintStream systemOut ) + { + this.systemOut = systemOut; + } + + public void info( String message ) + { + systemOut.println( message ); + } +} diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/report/LegacyPojoStackTraceWriter.java b/surefire-api/src/main/java/org/apache/maven/surefire/report/LegacyPojoStackTraceWriter.java new file mode 100644 index 0000000000..3f6a352958 --- /dev/null +++ b/surefire-api/src/main/java/org/apache/maven/surefire/report/LegacyPojoStackTraceWriter.java @@ -0,0 +1,153 @@ +package org.apache.maven.surefire.report; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES 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.PrintWriter; +import java.io.StringWriter; +import org.apache.maven.surefire.util.internal.StringUtils; + +/** + * Write the trace out for a POJO test. Java 1.3 compatible. + * + * @author Brett Porter + * @noinspection ThrowableResultOfMethodCallIgnored + */ +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 ) + { + this.testClass = testClass; + this.testMethod = testMethod; + this.t = t; + } + + public String writeTraceToString() + { + StringWriter w = new StringWriter(); + if ( t != null ) + { + t.printStackTrace( new PrintWriter( w ) ); + w.flush(); + } + return w.toString(); + } + + public String smartTrimmedStackTrace() + { + StringBuilder result = new StringBuilder(); + result.append( testClass ); + result.append( "#" ); + result.append( testMethod ); + SafeThrowable throwable = getThrowable(); + if ( throwable.getTarget() instanceof AssertionError ) + { + result.append( " " ); + result.append( getTruncatedMessage( throwable.getMessage(), 77 - result.length() ) ); + } + else + { + Throwable target = throwable.getTarget(); + if ( target != null ) + { + result.append( " " ); + result.append( target.getClass().getSimpleName() ); + result.append( getTruncatedMessage( throwable.getMessage(), 77 - result.length() ) ); + } + } + return result.toString(); + } + + private static String getTruncatedMessage( String msg, int i ) + { + if ( i < 0 ) + { + return ""; + } + if ( msg == null ) + { + return ""; + } + String substring = msg.substring( 0, Math.min( i, msg.length() ) ); + if ( i < msg.length() ) + { + return " " + substring + "..."; + } + else + { + return " " + substring; + } + } + + + public String writeTrimmedTraceToString() + { + String text = writeTraceToString(); + + String marker = "at " + testClass + "." + testMethod; + + String[] lines = StringUtils.split( text, "\n" ); + int lastLine = lines.length - 1; + int causedByLine = -1; + // skip first + for ( int i = 1; i < lines.length; i++ ) + { + String line = lines[i].trim(); + if ( line.startsWith( marker ) ) + { + lastLine = i; + } + 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" ); + } + + if ( causedByLine != -1 ) + { + for ( int i = causedByLine; i < lines.length; i++ ) + { + trace.append( lines[i] ); + trace.append( "\n" ); + } + } + return trace.toString(); + } + + public SafeThrowable getThrowable() + { + return new SafeThrowable( t ); + } +} diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/report/ReportEntry.java b/surefire-api/src/main/java/org/apache/maven/surefire/report/ReportEntry.java index 8e87066524..65bcb56dbe 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/report/ReportEntry.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/report/ReportEntry.java @@ -64,4 +64,11 @@ public interface ReportEntry * @return A string that explains an anomaly */ public String getMessage(); + + /** + * A name of the test case together with the group or category (if any exists). + * + * @return A string with the test case name and group/category, or just the name. + */ + public String getNameWithGroup(); } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/report/SafeThrowable.java b/surefire-api/src/main/java/org/apache/maven/surefire/report/SafeThrowable.java index 211c6acfa4..1d8d0afff7 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/report/SafeThrowable.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/report/SafeThrowable.java @@ -53,4 +53,9 @@ public String getMessage() return t.getMessage(); } } + + public Throwable getTarget() + { + return target; + } } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/report/SimpleReportEntry.java b/surefire-api/src/main/java/org/apache/maven/surefire/report/SimpleReportEntry.java index ed081fd19a..ca33a5fdc8 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/report/SimpleReportEntry.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/report/SimpleReportEntry.java @@ -187,5 +187,8 @@ public int hashCode() return result; } - + public String getNameWithGroup() + { + return getName(); + } } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/report/StackTraceWriter.java b/surefire-api/src/main/java/org/apache/maven/surefire/report/StackTraceWriter.java index 01bf385e19..6414ec2b3b 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/report/StackTraceWriter.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/report/StackTraceWriter.java @@ -40,6 +40,13 @@ public interface StackTraceWriter */ String writeTrimmedTraceToString(); + /** + * Get the "smart" trimmed (1-2 lines) stacktrace. + * + * @return the trace + */ + String smartTrimmedStackTrace(); + /** * Retrieve the throwable for this writer. * diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/suite/RunResult.java b/surefire-api/src/main/java/org/apache/maven/surefire/suite/RunResult.java index 8749cfa9dc..595717bcfc 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/suite/RunResult.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/suite/RunResult.java @@ -131,11 +131,11 @@ public Integer getFailsafeCode() // Only used for compatibility reasons. { if ( completedCount == 0 ) { - return Integer.valueOf( NO_TESTS ); + return NO_TESTS; } if ( !isErrorFree() ) { - return Integer.valueOf( FAILURE ); + return FAILURE; } return null; } @@ -202,7 +202,7 @@ Xpp3Dom asXpp3Dom() Integer failsafeCode = getFailsafeCode(); if ( failsafeCode != null ) { - dom.setAttribute( "result", Integer.toString( failsafeCode.intValue() ) ); + dom.setAttribute( "result", Integer.toString( failsafeCode ) ); } dom.setAttribute( "timeout", Boolean.toString( this.timeout ) ); dom.addChild( create( "completed", this.completedCount ) ); @@ -261,6 +261,7 @@ public void writeSummary( File summaryFile, boolean inProgress, String encoding } } + @SuppressWarnings( "RedundantIfStatement" ) public boolean equals( Object o ) { if ( this == o ) diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/testset/RunOrderParameters.java b/surefire-api/src/main/java/org/apache/maven/surefire/testset/RunOrderParameters.java index f36c64096c..57f3f332cd 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/testset/RunOrderParameters.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/testset/RunOrderParameters.java @@ -43,11 +43,6 @@ public RunOrderParameters( String runOrder, String runStatisticsFile ) this.runStatisticsFile = runStatisticsFile != null ? new File( runStatisticsFile ) : null; } - public static RunOrderParameters DEFAULT() - { - return new RunOrderParameters( RunOrder.DEFAULT, null ); - } - public static RunOrderParameters ALPHABETICAL() { return new RunOrderParameters( new RunOrder[]{ RunOrder.ALPHABETICAL }, null ); @@ -63,9 +58,4 @@ public File getRunStatisticsFile() return runStatisticsFile; } - public String getRunStatisticsFileName() - { - return runStatisticsFile != null ? runStatisticsFile.getAbsolutePath() : null; - } - } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/testset/TestRequest.java b/surefire-api/src/main/java/org/apache/maven/surefire/testset/TestRequest.java index 4ce6ca6bea..190b71b17c 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/testset/TestRequest.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/testset/TestRequest.java @@ -30,7 +30,7 @@ */ public class TestRequest { - private final List suiteXmlFiles; + private final List suiteXmlFiles; private final File testSourceDirectory; @@ -62,7 +62,7 @@ public TestRequest( List suiteXmlFiles, File testSourceDirectory, String request * * @return A list of java.io.File objects. */ - public List getSuiteXmlFiles() + public List getSuiteXmlFiles() { return suiteXmlFiles; } @@ -98,15 +98,15 @@ public String getRequestedTestMethod() return requestedTestMethod; } - private static List createFiles( List suiteXmlFiles ) + private static List createFiles( List suiteXmlFiles ) { if ( suiteXmlFiles != null ) { - List files = new ArrayList(); + List files = new ArrayList(); Object element; - for ( int i = 0; i < suiteXmlFiles.size(); i++ ) + for ( Object suiteXmlFile : suiteXmlFiles ) { - element = suiteXmlFiles.get( i ); + element = suiteXmlFile; files.add( element instanceof String ? new File( (String) element ) : (File) element ); } return files; diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/util/DefaultDirectoryScanner.java b/surefire-api/src/main/java/org/apache/maven/surefire/util/DefaultDirectoryScanner.java index e5f8174ca8..559da21c1d 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/util/DefaultDirectoryScanner.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/util/DefaultDirectoryScanner.java @@ -19,11 +19,12 @@ * under the License. */ +import org.apache.maven.surefire.SpecificTestClassFilter; + import java.io.File; import java.util.ArrayList; -import java.util.Iterator; +import java.util.Collections; import java.util.List; -import org.apache.maven.surefire.SpecificTestClassFilter; /** * Scans directories looking for tests. @@ -51,7 +52,7 @@ public class DefaultDirectoryScanner private final List specificTests; - private final List classesSkippedByValidation = new ArrayList(); + private final List classesSkippedByValidation = new ArrayList(); public DefaultDirectoryScanner( File basedir, List includes, List excludes, List specificTests ) { @@ -64,15 +65,13 @@ public DefaultDirectoryScanner( File basedir, List includes, List excludes, List public TestsToRun locateTestClasses( ClassLoader classLoader, ScannerFilter scannerFilter ) { String[] testClassNames = collectTests(); - List result = new ArrayList(); + List result = new ArrayList(); String[] specific = specificTests == null ? new String[0] : processIncludesExcludes( specificTests ); SpecificTestClassFilter specificTestFilter = new SpecificTestClassFilter( specific ); - for ( int i = 0; i < testClassNames.length; i++ ) + for ( String className : testClassNames ) { - String className = testClassNames[i]; - Class testClass = loadClass( classLoader, className ); if ( !specificTestFilter.accept( testClass ) ) @@ -143,29 +142,22 @@ String[] collectTests() private static String[] processIncludesExcludes( List list ) { - List newList = new ArrayList(); - Iterator iter = list.iterator(); - while ( iter.hasNext() ) + List newList = new ArrayList(); + for ( Object aList : list ) { - String include = (String) iter.next(); + String include = (String) aList; String[] includes = include.split( "," ); - for ( int i = 0; i < includes.length; ++i ) - { - newList.add( includes[i] ); - } + Collections.addAll( newList, includes ); } String[] incs = new String[newList.size()]; for ( int i = 0; i < incs.length; i++ ) { - String inc = (String) newList.get( i ); + String inc = newList.get( i ); if ( inc.endsWith( JAVA_SOURCE_FILE_EXTENSION ) ) { - inc = new StringBuffer( - inc.length() - JAVA_SOURCE_FILE_EXTENSION.length() + JAVA_CLASS_FILE_EXTENSION.length() ).append( - inc.substring( 0, inc.lastIndexOf( JAVA_SOURCE_FILE_EXTENSION ) ) ).append( - JAVA_CLASS_FILE_EXTENSION ).toString(); + inc = inc.substring( 0, inc.lastIndexOf( JAVA_SOURCE_FILE_EXTENSION ) ) + JAVA_CLASS_FILE_EXTENSION; } incs[i] = inc; @@ -173,9 +165,4 @@ private static String[] processIncludesExcludes( List list ) return incs; } - public List getClassesSkippedByValidation() - { - return classesSkippedByValidation; - } - } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/util/DefaultRunOrderCalculator.java b/surefire-api/src/main/java/org/apache/maven/surefire/util/DefaultRunOrderCalculator.java index 52ad51078a..147c6e7c72 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/util/DefaultRunOrderCalculator.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/util/DefaultRunOrderCalculator.java @@ -19,14 +19,14 @@ * under the License. */ +import org.apache.maven.plugin.surefire.runorder.RunEntryStatisticsMap; +import org.apache.maven.surefire.testset.RunOrderParameters; + import java.util.ArrayList; -import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.List; -import org.apache.maven.plugin.surefire.runorder.RunEntryStatisticsMap; -import org.apache.maven.surefire.testset.RunOrderParameters; /** * Applies the final runorder of the tests @@ -36,7 +36,7 @@ public class DefaultRunOrderCalculator implements RunOrderCalculator { - private final Comparator sortOrder; + private final Comparator sortOrder; private final RunOrder[] runOrder; @@ -54,13 +54,19 @@ public DefaultRunOrderCalculator( RunOrderParameters runOrderParameters, int thr public TestsToRun orderTestClasses( TestsToRun scannedClasses ) { - List result = new ArrayList( Arrays.asList( scannedClasses.getLocatedClasses() ) ); + + List result = new ArrayList( 500 ); + + for ( Class scannedClass : scannedClasses ) + { + result.add( scannedClass ); + } orderTestClasses( result, runOrder.length != 0 ? runOrder[0] : null ); return new TestsToRun( result ); } - private void orderTestClasses( List testClasses, RunOrder runOrder ) + private void orderTestClasses( List testClasses, RunOrder runOrder ) { if ( RunOrder.RANDOM.equals( runOrder ) ) { @@ -70,7 +76,7 @@ else if ( RunOrder.FAILEDFIRST.equals( runOrder ) ) { RunEntryStatisticsMap runEntryStatisticsMap = RunEntryStatisticsMap.fromFile( runOrderParameters.getRunStatisticsFile() ); - final List prioritized = runEntryStatisticsMap.getPrioritizedTestsByFailureFirst( testClasses ); + final List prioritized = runEntryStatisticsMap.getPrioritizedTestsByFailureFirst( testClasses ); testClasses.clear(); testClasses.addAll( prioritized ); @@ -79,7 +85,7 @@ else if ( RunOrder.BALANCED.equals( runOrder ) ) { RunEntryStatisticsMap runEntryStatisticsMap = RunEntryStatisticsMap.fromFile( runOrderParameters.getRunStatisticsFile() ); - final List prioritized = runEntryStatisticsMap.getPrioritizedTestsClassRunTime( testClasses, threadCount ); + final List prioritized = runEntryStatisticsMap.getPrioritizedTestsClassRunTime( testClasses, threadCount ); testClasses.clear(); testClasses.addAll( prioritized ); @@ -90,7 +96,7 @@ else if ( sortOrder != null ) } } - private Comparator getSortOrderComparator( RunOrder runOrder ) + private Comparator getSortOrderComparator( RunOrder runOrder ) { if ( RunOrder.ALPHABETICAL.equals( runOrder ) ) { @@ -111,24 +117,24 @@ else if ( RunOrder.HOURLY.equals( runOrder ) ) } } - private Comparator getReverseAlphabeticalComparator() + private Comparator getReverseAlphabeticalComparator() { - return new Comparator() + return new Comparator() { - public int compare( Object o1, Object o2 ) + public int compare( Class o1, Class o2 ) { - return ( (Class) o2 ).getName().compareTo( ( (Class) o1 ).getName() ); + return o2.getName().compareTo( o1.getName() ); } }; } - private Comparator getAlphabeticalComparator() + private Comparator getAlphabeticalComparator() { - return new Comparator() + return new Comparator() { - public int compare( Object o1, Object o2 ) + public int compare( Class o1, Class o2 ) { - return ( (Class) o1 ).getName().compareTo( ( (Class) o2 ).getName() ); + return o1.getName().compareTo( o2.getName() ); } }; } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/util/DefaultScanResult.java b/surefire-api/src/main/java/org/apache/maven/surefire/util/DefaultScanResult.java index b009f34e30..cb34ae9b34 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/util/DefaultScanResult.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/util/DefaultScanResult.java @@ -1,141 +1,154 @@ -package org.apache.maven.surefire.util; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES 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.Collections; -import java.util.List; -import java.util.Properties; - -/** - * @author Kristian Rosenvold - */ -public class DefaultScanResult - implements ScanResult -{ - private final List files; - - private static final String scanResultNo = "tc."; - - public DefaultScanResult( List files ) - { - this.files = files; - } - - public int size() - { - return files.size(); - } - - public String getClassName( int index ) - { - return (String) files.get( index ); - } - - public void writeTo( Properties properties ) - { - int size = files.size(); - for ( int i = 0; i < size; i++ ) - { - properties.setProperty( scanResultNo + i, (String) files.get( i ) ); - } - } - - public static DefaultScanResult from( Properties properties ) - { - List result = new ArrayList(); - int i = 0; - while ( true ) - { - String item = properties.getProperty( scanResultNo + ( i++ ) ); - if ( item == null ) - { - return new DefaultScanResult( result ); - } - result.add( item ); - } - } - - public boolean isEmpty() - { - return files.isEmpty(); - } - - public List getFiles() - { - return Collections.unmodifiableList( files ); - } - - public TestsToRun applyFilter( ScannerFilter scannerFilter, ClassLoader testClassLoader ) - { - List result = new ArrayList(); - - int size = size(); - for ( int i = 0; i < size; i++ ) - { - String className = getClassName( i ); - - Class testClass = loadClass( testClassLoader, className ); - - if ( scannerFilter == null || scannerFilter.accept( testClass ) ) - { - result.add( testClass ); - } - } - - return new TestsToRun( result ); - } - - 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 ); - - Class testClass = loadClass( testClassLoader, className ); - - if ( scannerFilter != null && !scannerFilter.accept( testClass ) ) - { - result.add( testClass ); - } - } - - return result; - } - - private static Class loadClass( ClassLoader classLoader, String className ) - { - Class testClass; - try - { - testClass = classLoader.loadClass( className ); - } - catch ( ClassNotFoundException e ) - { - throw new NestedRuntimeException( "Unable to create test class '" + className + "'", e ); - } - return testClass; - } - - -} +package org.apache.maven.surefire.util; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES 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.Collections; +import java.util.List; +import java.util.Properties; + +/** + * @author Kristian Rosenvold + */ +public class DefaultScanResult + implements ScanResult +{ + private final List files; + + private static final String scanResultNo = "tc."; + + public DefaultScanResult( List files ) + { + this.files = Collections.unmodifiableList( files ); + } + + public int size() + { + return files.size(); + } + + public String getClassName( int index ) + { + return files.get( index ); + } + + public void writeTo( Properties properties ) + { + int size = files.size(); + for ( int i = 0; i < size; i++ ) + { + properties.setProperty( scanResultNo + i, files.get( i ) ); + } + } + + public static DefaultScanResult from( Properties properties ) + { + List result = new ArrayList(); + int i = 0; + while ( true ) + { + String item = properties.getProperty( scanResultNo + ( i++ ) ); + if ( item == null ) + { + return new DefaultScanResult( result ); + } + result.add( item ); + } + } + + public boolean isEmpty() + { + return files.isEmpty(); + } + + public List getFiles() + { + return files; + } + + public TestsToRun applyFilter( ScannerFilter scannerFilter, ClassLoader testClassLoader ) + { + List result = new ArrayList(); + + int size = size(); + for ( int i = 0; i < size; i++ ) + { + String className = getClassName( i ); + + Class testClass = loadClass( testClassLoader, className ); + + if ( scannerFilter == null || scannerFilter.accept( testClass ) ) + { + result.add( testClass ); + } + } + + return new TestsToRun( result ); + } + + 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 ); + + Class testClass = loadClass( testClassLoader, className ); + + if ( scannerFilter != null && !scannerFilter.accept( testClass ) ) + { + result.add( testClass ); + } + } + + return result; + } + + private static Class loadClass( ClassLoader classLoader, String className ) + { + Class testClass; + try + { + testClass = classLoader.loadClass( className ); + } + catch ( ClassNotFoundException e ) + { + throw new NestedRuntimeException( "Unable to create test class '" + className + "'", e ); + } + return testClass; + } + + public DefaultScanResult append(DefaultScanResult other){ + if ( other != null ) + { + List src = new ArrayList( files ); + src.addAll( other.files ); + return new DefaultScanResult( src ); + } + else + { + return this; + } + } + + +} diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/util/ReflectionUtils.java b/surefire-api/src/main/java/org/apache/maven/surefire/util/ReflectionUtils.java index bc7364a1a6..a3c9e156a6 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/util/ReflectionUtils.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/util/ReflectionUtils.java @@ -127,7 +127,7 @@ public static Object instantiateOneArg( ClassLoader classLoader, String classNam { Class aClass = loadClass( classLoader, className ); Constructor constructor = ReflectionUtils.getConstructor( aClass, new Class[]{ param1Class } ); - return constructor.newInstance( new Object[]{ param1 } ); + return constructor.newInstance( param1 ); } catch ( InvocationTargetException e ) { @@ -151,7 +151,7 @@ public static Object instantiateTwoArgs( ClassLoader classLoader, String classNa { Class aClass = loadClass( classLoader, className ); Constructor constructor = ReflectionUtils.getConstructor( aClass, new Class[]{ param1Class, param2Class } ); - return constructor.newInstance( new Object[]{ param1, param2 } ); + return constructor.newInstance( param1, param2 ); } catch ( InvocationTargetException e ) { diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/util/RunOrder.java b/surefire-api/src/main/java/org/apache/maven/surefire/util/RunOrder.java index 63fef0633d..e262e53ebd 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/util/RunOrder.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/util/RunOrder.java @@ -54,7 +54,7 @@ public class RunOrder */ public static RunOrder[] valueOfMulti( String values ) { - List result = new ArrayList(); + List result = new ArrayList(); if ( values != null ) { StringTokenizer stringTokenizer = new StringTokenizer( values, "," ); @@ -63,7 +63,7 @@ public static RunOrder[] valueOfMulti( String values ) result.add( valueOf( stringTokenizer.nextToken() ) ); } } - return (RunOrder[]) result.toArray( new RunOrder[result.size()] ); + return result.toArray( new RunOrder[result.size()] ); } public static RunOrder valueOf( String name ) @@ -75,11 +75,11 @@ public static RunOrder valueOf( String name ) else { RunOrder[] runOrders = values(); - for ( int i = 0; i < runOrders.length; i++ ) + for ( RunOrder runOrder : runOrders ) { - if ( runOrders[i].matches( name ) ) + if ( runOrder.matches( name ) ) { - return runOrders[i]; + return runOrder; } } @@ -114,7 +114,7 @@ private static RunOrder[] values() public static String asString( RunOrder[] runOrder ) { - StringBuffer stringBuffer = new StringBuffer(); + StringBuilder stringBuffer = new StringBuilder(); for ( int i = 0; i < runOrder.length; i++ ) { stringBuffer.append( runOrder[i].name ); diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/util/ScanResult.java b/surefire-api/src/main/java/org/apache/maven/surefire/util/ScanResult.java index 3c453f6589..79895ceae9 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/util/ScanResult.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/util/ScanResult.java @@ -1,39 +1,39 @@ -package org.apache.maven.surefire.util; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES 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 java.util.Properties; - -/** - * @author Kristian Rosenvold - */ -public interface ScanResult -{ - int size(); - - String getClassName( int index ); - - TestsToRun applyFilter( ScannerFilter scannerFilter, ClassLoader testClassLoader ); - - List getClassesSkippedByValidation( ScannerFilter scannerFilter, ClassLoader testClassLoader ); - - void writeTo( Properties properties ); -} +package org.apache.maven.surefire.util; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES 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 java.util.Properties; + +/** + * @author Kristian Rosenvold + */ +public interface ScanResult +{ + int size(); + + String getClassName( int index ); + + TestsToRun applyFilter( ScannerFilter scannerFilter, ClassLoader testClassLoader ); + + List getClassesSkippedByValidation( ScannerFilter scannerFilter, ClassLoader testClassLoader ); + + void writeTo( Properties properties ); +} diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/util/TestsToRun.java b/surefire-api/src/main/java/org/apache/maven/surefire/util/TestsToRun.java index 734783ebf1..607c332437 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/util/TestsToRun.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/util/TestsToRun.java @@ -19,6 +19,7 @@ * under the License. */ +import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; @@ -33,23 +34,22 @@ * * @author Kristian Rosenvold (junit core adaption) */ -public class TestsToRun +public class TestsToRun implements Iterable { - private final List locatedClasses; + private final List locatedClasses; /** * Constructor * * @param locatedClasses A list of java.lang.Class objects representing tests to run */ - public TestsToRun( List locatedClasses ) + public TestsToRun( List locatedClasses ) { this.locatedClasses = Collections.unmodifiableList( locatedClasses ); - Set testSets = new HashSet(); + Set testSets = new HashSet(); - for ( Iterator iterator = locatedClasses.iterator(); iterator.hasNext(); ) + for ( Class testClass : locatedClasses ) { - Class testClass = (Class) iterator.next(); if ( testSets.contains( testClass ) ) { throw new RuntimeException( "Duplicate test set '" + testClass.getName() + "'" ); @@ -61,17 +61,7 @@ public TestsToRun( List locatedClasses ) public static TestsToRun fromClass( Class clazz ) throws TestSetFailedException { - return new TestsToRun( Arrays.asList( new Class[]{ clazz } ) ); - } - - public int size() - { - return locatedClasses.size(); - } - - public Class[] getLocatedClasses() - { - return (Class[]) locatedClasses.toArray( new Class[locatedClasses.size()] ); + return new TestsToRun( Arrays.asList( clazz ) ); } /** @@ -79,14 +69,14 @@ public Class[] getLocatedClasses() * * @return an unmodifiable iterator */ - public Iterator iterator() + public Iterator iterator() { return locatedClasses.iterator(); } public String toString() { - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); sb.append( "TestsToRun: [" ); Iterator it = iterator(); while ( it.hasNext() ) @@ -99,4 +89,53 @@ public String toString() return sb.toString(); } + 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() ) + { + return false; + } + + it.next(); + } + + return true; + } + + public boolean containsExactly( int items ) + { + Iterator it = iterator(); + 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() + { + return true; + } + + public Class[] getLocatedClasses() + { + if ( !allowEagerReading() ) + { + throw new IllegalStateException( "Cannot eagerly read" ); + } + List result = new ArrayList(); + Iterator it = iterator(); + while ( it.hasNext() ) + { + result.add( it.next() ); + } + return result.toArray( new Class[result.size()] ); + } } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/util/UrlUtils.java b/surefire-api/src/main/java/org/apache/maven/surefire/util/UrlUtils.java index 475d2c4305..b7059d9c66 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/util/UrlUtils.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/util/UrlUtils.java @@ -48,9 +48,9 @@ private UrlUtils() { byte[] bytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.!~*'():/".getBytes( ENCODING ); - for ( int i = 0; i < bytes.length; i++ ) + for ( byte aByte : bytes ) { - UNRESERVED.set( bytes[i] ); + UNRESERVED.set( aByte ); } } catch ( UnsupportedEncodingException e ) @@ -70,10 +70,9 @@ public static URL getURL( File file ) try { byte[] bytes = url.toString().getBytes( ENCODING ); - StringBuffer buf = new StringBuffer( bytes.length ); - for ( int i = 0; i < bytes.length; i++ ) + StringBuilder buf = new StringBuilder( bytes.length ); + for ( byte b : bytes ) { - byte b = bytes[i]; if ( b > 0 && UNRESERVED.get( b ) ) { buf.append( (char) b ); diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/util/internal/ByteBuffer.java b/surefire-api/src/main/java/org/apache/maven/surefire/util/internal/ByteBuffer.java index 228dd3303c..97da38bae0 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/util/internal/ByteBuffer.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/util/internal/ByteBuffer.java @@ -65,7 +65,7 @@ public void advance( int i ) public void append( Integer integer ) { - toHex( integer.intValue() ); + toHex( integer ); } /** diff --git a/surefire-api/src/test/java/org/apache/maven/surefire/report/PojoStackTraceWriterTest.java b/surefire-api/src/test/java/org/apache/maven/surefire/report/LegacyPojoStackTraceWriterTest.java similarity index 87% rename from surefire-api/src/test/java/org/apache/maven/surefire/report/PojoStackTraceWriterTest.java rename to surefire-api/src/test/java/org/apache/maven/surefire/report/LegacyPojoStackTraceWriterTest.java index ccd5acebcd..6ee357aa0d 100644 --- a/surefire-api/src/test/java/org/apache/maven/surefire/report/PojoStackTraceWriterTest.java +++ b/surefire-api/src/test/java/org/apache/maven/surefire/report/LegacyPojoStackTraceWriterTest.java @@ -1,29 +1,13 @@ package org.apache.maven.surefire.report; -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES 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.PrintWriter; import junit.framework.TestCase; -public class PojoStackTraceWriterTest +/** + * @author Kristian Rosenvold + */ +public class LegacyPojoStackTraceWriterTest extends TestCase { @@ -61,7 +45,7 @@ public void testWriteTrimmedTraceToString() " 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 ); - PojoStackTraceWriter w = new PojoStackTraceWriter( "TestSurefire3", "testQuote", t ); + 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" + @@ -108,7 +92,7 @@ public void testCausedBy() " at TestSurefire3.testBlah(TestSurefire3.java:43)\n" + " ... 26 more\n"; MockThrowable t = new MockThrowable( stackTrace ); - PojoStackTraceWriter w = new PojoStackTraceWriter( "TestSurefire3", "testBlah", t ); + 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" + diff --git a/surefire-api/src/test/java/org/apache/maven/surefire/report/MockReporter.java b/surefire-api/src/test/java/org/apache/maven/surefire/report/MockReporter.java index 22617edcca..ad26f850c8 100644 --- a/surefire-api/src/test/java/org/apache/maven/surefire/report/MockReporter.java +++ b/surefire-api/src/test/java/org/apache/maven/surefire/report/MockReporter.java @@ -29,9 +29,9 @@ public class MockReporter implements RunListener, ConsoleLogger { - private final List events = new ArrayList(); + private final List events = new ArrayList(); - private final List data = new ArrayList(); + private final List data = new ArrayList(); public static final String SET_STARTING = "SET_STARTED"; @@ -117,7 +117,7 @@ public void testSkipped( ReportEntry report ) public String getFirstEvent() { - return (String) events.get( 0 ); + return events.get( 0 ); } public ReportEntry getFirstData() diff --git a/surefire-api/src/test/java/org/apache/maven/surefire/util/DefaultDirectoryScannerTest.java b/surefire-api/src/test/java/org/apache/maven/surefire/util/DefaultDirectoryScannerTest.java index d4d782e1bb..1b4757b56e 100644 --- a/surefire-api/src/test/java/org/apache/maven/surefire/util/DefaultDirectoryScannerTest.java +++ b/surefire-api/src/test/java/org/apache/maven/surefire/util/DefaultDirectoryScannerTest.java @@ -39,7 +39,7 @@ public void testLocateTestClasses() { // use target as people can configure ide to compile in an other place than maven File baseDir = new File( new File( "target" ).getCanonicalPath() ); - List include = new ArrayList(); + List include = new ArrayList(); include.add( "**/*ZT*A.java" ); List exclude = new ArrayList(); diff --git a/surefire-api/src/test/java/org/apache/maven/surefire/util/RunOrderCalculatorTest.java b/surefire-api/src/test/java/org/apache/maven/surefire/util/RunOrderCalculatorTest.java index 7f40a5049f..3c011d11e2 100644 --- a/surefire-api/src/test/java/org/apache/maven/surefire/util/RunOrderCalculatorTest.java +++ b/surefire-api/src/test/java/org/apache/maven/surefire/util/RunOrderCalculatorTest.java @@ -42,9 +42,9 @@ public void testOrderTestClasses() } - private List getClassesToRun() + private List getClassesToRun() { - List classesToRun = new ArrayList(); + List classesToRun = new ArrayList(); classesToRun.add( B.class ); classesToRun.add( A.class ); return classesToRun; diff --git a/surefire-api/src/test/java/org/apache/maven/surefire/util/ScanResultTest.java b/surefire-api/src/test/java/org/apache/maven/surefire/util/ScanResultTest.java index 8ca033bce5..7c6628a135 100644 --- a/surefire-api/src/test/java/org/apache/maven/surefire/util/ScanResultTest.java +++ b/surefire-api/src/test/java/org/apache/maven/surefire/util/ScanResultTest.java @@ -1,48 +1,48 @@ -package org.apache.maven.surefire.util; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES 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.List; -import java.util.Properties; - -import junit.framework.TestCase; - -/** - * @author Kristian Rosenvold - */ -public class ScanResultTest - extends TestCase -{ - public void testWriteTo() - throws Exception - { - List files = Arrays.asList( new String[]{ "abc", "cde" } ); - DefaultScanResult scanResult = new DefaultScanResult( files ); - Properties serialized = new Properties(); - scanResult.writeTo( serialized ); - - DefaultScanResult read = DefaultScanResult.from( serialized ); - List files1 = read.getFiles(); - assertEquals( 2, files1.size() ); - assertTrue( files1.contains( "abc" ) ); - assertTrue( files1.contains( "cde" ) ); - } -} +package org.apache.maven.surefire.util; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES 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.List; +import java.util.Properties; + +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 ); + Properties serialized = new Properties(); + scanResult.writeTo( serialized ); + + DefaultScanResult read = DefaultScanResult.from( serialized ); + List files1 = read.getFiles(); + assertEquals( 2, files1.size() ); + assertTrue( files1.contains( "abc" ) ); + assertTrue( files1.contains( "cde" ) ); + } +} diff --git a/surefire-api/src/test/java/org/apache/maven/surefire/util/TestsToRunTest.java b/surefire-api/src/test/java/org/apache/maven/surefire/util/TestsToRunTest.java index 8aacfb1237..c7029c0754 100644 --- a/surefire-api/src/test/java/org/apache/maven/surefire/util/TestsToRunTest.java +++ b/surefire-api/src/test/java/org/apache/maven/surefire/util/TestsToRunTest.java @@ -20,6 +20,7 @@ */ import java.util.Arrays; +import java.util.Iterator; import junit.framework.TestCase; @@ -34,11 +35,34 @@ public void testGetTestSets() throws Exception { TestsToRun testsToRun = new TestsToRun( Arrays.asList( new Class[]{ T1.class, T2.class } ) ); - assertEquals( 2, testsToRun.size() ); - Class[] stringJUnitCoreTestSetMap = testsToRun.getLocatedClasses(); - assertEquals( stringJUnitCoreTestSetMap[0], T1.class ); - assertEquals( stringJUnitCoreTestSetMap[1], T2.class ); - assertEquals( 2, stringJUnitCoreTestSetMap.length ); + Iterator it = testsToRun.iterator(); + assertTrue( it.hasNext() ); + assertEquals( it.next(), T1.class ); + assertTrue( it.hasNext() ); + assertEquals( it.next(), T2.class ); + assertFalse( it.hasNext() ); + } + + public void testContainsAtleast() + { + TestsToRun testsToRun = new TestsToRun( Arrays.asList( new Class[]{ T1.class, T2.class } ) ); + assertTrue( testsToRun.containsAtLeast( 2 ) ); + assertFalse( testsToRun.containsAtLeast( 3 ) ); + } + + public void testContainsExactly() + { + TestsToRun testsToRun = new TestsToRun( Arrays.asList( new Class[]{ T1.class, T2.class } ) ); + assertFalse( testsToRun.containsExactly( 1 ) ); + assertTrue( testsToRun.containsExactly( 2 ) ); + assertFalse( testsToRun.containsExactly( 3 ) ); + } + + public void testToRunArray() + { + TestsToRun testsToRun = new TestsToRun( Arrays.asList( new Class[]{ T1.class, T2.class } ) ); + Class[] locatedClasses = testsToRun.getLocatedClasses(); + assertEquals( 2, locatedClasses.length ); } class T1 @@ -51,3 +75,4 @@ class T2 } } + diff --git a/surefire-api/src/test/java/org/apache/maven/surefire/util/UrlUtilsTest.java b/surefire-api/src/test/java/org/apache/maven/surefire/util/UrlUtilsTest.java index 3c1bd8715b..a9d7df0602 100644 --- a/surefire-api/src/test/java/org/apache/maven/surefire/util/UrlUtilsTest.java +++ b/surefire-api/src/test/java/org/apache/maven/surefire/util/UrlUtilsTest.java @@ -68,7 +68,7 @@ private void verifyFileName( String fileName, String expectedFileName ) // use reflection to do "File urlFile = new File( uri )" if JDK 1.4+ Constructor newFile = File.class.getConstructor( new Class[]{ uri.getClass() } ); - File urlFile = (File) newFile.newInstance( new Object[]{ uri } ); + File urlFile = (File) newFile.newInstance( uri ); assertEquals( f, urlFile ); } diff --git a/surefire-booter/pom.xml b/surefire-booter/pom.xml index b2c81e9e46..10f7abcf0d 100644 --- a/surefire-booter/pom.xml +++ b/surefire-booter/pom.xml @@ -17,14 +17,13 @@ ~ specific language governing permissions and limitations ~ under the License. --> - + 4.0.0 org.apache.maven.surefire surefire - 2.13-SNAPSHOT + 2.16-SNAPSHOT ../pom.xml @@ -47,17 +46,10 @@ org.apache.maven.surefire surefire-shadefire - ${project.version} + ${shadedVersion} - - maven-compiler-plugin - - 1.3 - 1.3 - - org.apache.maven.plugins maven-shade-plugin 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 fe718557a8..536c077902 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 @@ -19,91 +19,93 @@ * under the License. */ +import org.apache.maven.surefire.util.UrlUtils; + import java.io.File; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; +import java.util.Collection; import java.util.Collections; import java.util.Iterator; +import java.util.LinkedHashSet; import java.util.List; -import org.apache.maven.surefire.util.UrlUtils; /** * An ordered list of classpath elements with set behaviour * + * A Classpath is immutable and thread safe. + * + * Immutable and thread safe + * * @author Kristian Rosenvold */ -public class Classpath +public class Classpath implements Iterable { - private static final JdkReflector jdkReflector = new JdkReflector(); + + private final List unmodifiableElements; public static Classpath join( Classpath firstClasspath, Classpath secondClasspath ) { - Classpath joinedClasspath = new Classpath(); - joinedClasspath.addElementsOfClasspath( firstClasspath ); - joinedClasspath.addElementsOfClasspath( secondClasspath ); - return joinedClasspath; + LinkedHashSet accumulated = new LinkedHashSet( ); + if (firstClasspath != null) firstClasspath.addTo( accumulated ); + if (secondClasspath != null) secondClasspath.addTo( accumulated ); + return new Classpath( accumulated ); } - private final List elements; - public Classpath() - { - this.elements = new ArrayList(); + private void addTo(Collection c){ + c.addAll( unmodifiableElements ); } - public Classpath( Classpath other ) + private Classpath() { - this.elements = new ArrayList( other.elements ); + this.unmodifiableElements = Collections.emptyList(); } - public Classpath( List elements ) + + public Classpath( Classpath other, String additionalElement ) { - this(); - addElements( elements ); + ArrayList elems = new ArrayList( other.unmodifiableElements ); + elems.add( additionalElement ); + this.unmodifiableElements = Collections.unmodifiableList( elems ); } - public void addClassPathElementUrl( String path ) + public Classpath( Iterable elements ) { - if ( path == null ) + List newCp = new ArrayList( ); + for ( String element : elements ) { - throw new IllegalArgumentException( "Null is not a valid class path element url." ); - } - else if ( !elements.contains( path ) ) - { - elements.add( path ); + newCp.add( element ); } + this.unmodifiableElements = Collections.unmodifiableList( newCp ); } - private void addElements( List additionalElements ) + public static Classpath emptyClasspath() { - for ( Iterator it = additionalElements.iterator(); it.hasNext(); ) - { - String element = (String) it.next(); - addClassPathElementUrl( element ); - } + return new Classpath(); } - private void addElementsOfClasspath( Classpath otherClasspath ) + public Classpath addClassPathElementUrl( String path ) { - if ( otherClasspath != null ) + if ( path == null ) { - addElements( otherClasspath.elements ); + throw new IllegalArgumentException( "Null is not a valid class path element url." ); } + return !unmodifiableElements.contains( path ) ? new Classpath( this, path ) : this; } - public List getClassPath() + public List getClassPath() { - return Collections.unmodifiableList( elements ); + return unmodifiableElements; } - public List getAsUrlList() + public List getAsUrlList() throws MalformedURLException { - List urls = new ArrayList(); - for ( Iterator i = elements.iterator(); i.hasNext(); ) + List urls = new ArrayList(); + for ( String url : unmodifiableElements ) { - String url = (String) i.next(); File f = new File( url ); urls.add( UrlUtils.getURL( f ) ); } @@ -112,10 +114,10 @@ public List getAsUrlList() public void writeToSystemProperty( String propertyName ) { - StringBuffer sb = new StringBuffer(); - for ( Iterator i = elements.iterator(); i.hasNext(); ) + StringBuilder sb = new StringBuilder(); + for ( String element : unmodifiableElements ) { - sb.append( (String) i.next() ).append( File.pathSeparatorChar ); + sb.append( element ).append( File.pathSeparatorChar ); } System.setProperty( propertyName, sb.toString() ); } @@ -133,7 +135,8 @@ public boolean equals( Object o ) Classpath classpath = (Classpath) o; - return !( elements != null ? !elements.equals( classpath.elements ) : classpath.elements != null ); + return !( unmodifiableElements + != null ? !unmodifiableElements.equals( classpath.unmodifiableElements ) : classpath.unmodifiableElements != null ); } @@ -145,16 +148,16 @@ public ClassLoader createClassLoader( ClassLoader parent, boolean childDelegatio { List urls = getAsUrlList(); IsolatedClassLoader classLoader = new IsolatedClassLoader( parent, childDelegation, roleName ); - for ( Iterator iter = urls.iterator(); iter.hasNext(); ) + for ( Object url1 : urls ) { - URL url = (URL) iter.next(); + URL url = (URL) url1; classLoader.addURL( url ); } if ( parent != null ) { - jdkReflector.invokeAssertionStatusMethod( parent, enableAssertions ); + parent.setDefaultAssertionStatus( enableAssertions ); } - jdkReflector.invokeAssertionStatusMethod( classLoader, enableAssertions ); + classLoader.setDefaultAssertionStatus( enableAssertions ); return classLoader; } catch ( MalformedURLException e ) @@ -166,6 +169,50 @@ public ClassLoader createClassLoader( ClassLoader parent, boolean childDelegatio public int hashCode() { - return elements != null ? elements.hashCode() : 0; + return unmodifiableElements != null ? unmodifiableElements.hashCode() : 0; + } + + public String getLogMessage( String descriptor ) + { + StringBuilder result = new StringBuilder(); + result.append( descriptor ).append( " classpath:" ); + for ( String element : unmodifiableElements ) + { + result.append( " " ).append( element ); + } + return result.toString(); + } + + public String getCompactLogMessage( String descriptor ) + { + StringBuilder result = new StringBuilder(); + result.append( descriptor ).append( " classpath:" ); + for ( String element : unmodifiableElements ) + { + result.append( " " ); + if ( element != null ) + { + int pos = element.lastIndexOf( File.separatorChar ); + if ( pos >= 0 ) + { + result.append( element.substring( pos + 1 ) ); + } + else + { + result.append( element ); + } + + } + else + { + result.append( element ); + } + } + return result.toString(); + } + + public Iterator iterator() + { + return unmodifiableElements.iterator(); } } 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 e3b8243456..5dbf018100 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 @@ -29,13 +29,13 @@ */ public class ClasspathConfiguration { - private static final String CHILD_DELEGATION = "childDelegation"; + public static final String CHILD_DELEGATION = "childDelegation"; - private static final String ENABLE_ASSERTIONS = "enableAssertions"; + public static final String ENABLE_ASSERTIONS = "enableAssertions"; - private static final String CLASSPATH = "classPathUrl."; + public static final String CLASSPATH = "classPathUrl."; - private static final String SUREFIRE_CLASSPATH = "surefireClassPathUrl."; + public static final String SUREFIRE_CLASSPATH = "surefireClassPathUrl."; private final Classpath classpathUrls; @@ -57,12 +57,13 @@ public class ClasspathConfiguration public ClasspathConfiguration( boolean enableAssertions, boolean childDelegation ) { - this( new Classpath(), new Classpath(), new Classpath(), enableAssertions, childDelegation ); + this( Classpath.emptyClasspath(), Classpath.emptyClasspath(), Classpath.emptyClasspath(), enableAssertions, childDelegation ); } ClasspathConfiguration( PropertiesWrapper properties ) { - this( properties.getClasspath( CLASSPATH ), properties.getClasspath( SUREFIRE_CLASSPATH ), new Classpath(), + this( properties.getClasspath( CLASSPATH ), properties.getClasspath( SUREFIRE_CLASSPATH ), + Classpath.emptyClasspath(), properties.getBooleanProperty( ENABLE_ASSERTIONS ), properties.getBooleanProperty( CHILD_DELEGATION ) ); } @@ -76,58 +77,38 @@ public ClasspathConfiguration( Classpath testClasspath, Classpath surefireClassP this.surefireClasspathUrls = surefireClassPathUrls; } - public void addForkProperties( PropertiesWrapper properties ) - { - properties.setClasspath( CLASSPATH, classpathUrls ); - properties.setClasspath( SUREFIRE_CLASSPATH, surefireClasspathUrls ); - properties.setProperty( ENABLE_ASSERTIONS, String.valueOf( enableAssertions ) ); - properties.setProperty( CHILD_DELEGATION, String.valueOf( childDelegation ) ); - } - - public ClassLoader createTestClassLoader( boolean childDelegation ) + public ClassLoader createMergedClassLoader() throws SurefireExecutionException { - return classpathUrls.createClassLoader( null, childDelegation, enableAssertions, "test" ); + return Classpath.join( inprocClasspath, classpathUrls) + .createClassLoader( null, this.childDelegation, enableAssertions, "test" ); } - public ClassLoader createTestClassLoader() - throws SurefireExecutionException + public Classpath getProviderClasspath() { - return classpathUrls.createClassLoader( null, this.childDelegation, enableAssertions, "test" ); + return surefireClasspathUrls; } - public ClassLoader createSurefireClassLoader( ClassLoader parent ) - throws SurefireExecutionException + + public Classpath getTestClasspath() { - return surefireClasspathUrls.createClassLoader( parent, false, enableAssertions, "provider" ); + return classpathUrls; } - public ClassLoader createInprocSurefireClassLoader( ClassLoader parent ) + public void trickClassPathWhenManifestOnlyClasspath() throws SurefireExecutionException { - return inprocClasspath.createClassLoader( parent, false, enableAssertions, "provider" ); + System.setProperty( "surefire.real.class.path", System.getProperty( "java.class.path" ) ); + getTestClasspath().writeToSystemProperty( "java.class.path" ); } - public Classpath getTestClasspath() + public boolean isEnableAssertions() { - return classpathUrls; + return enableAssertions; } - public ClassLoader createForkingTestClassLoader( boolean manifestOnlyJarRequestedAndUsable ) - throws SurefireExecutionException + public boolean isChildDelegation() { - if ( manifestOnlyJarRequestedAndUsable ) - { - System.setProperty( "surefire.real.class.path", System.getProperty( "java.class.path" ) ); - getTestClasspath().writeToSystemProperty( "java.class.path" ); - // this.getClass.getClassLoader() is always loaded in system classloader if forking - // this.getClass().getClassLoader() is plugin classloder if in-process - // "this" must refer to a class within the booter module - return this.getClass().getClassLoader(); // SUREFIRE-459, trick the app under test into thinking its classpath was conventional; - } - else - { - return createTestClassLoader(); - } + return childDelegation; } } 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 72e6d536ae..aed05317ae 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 @@ -24,10 +24,15 @@ import java.io.InputStream; import java.io.PrintStream; import java.lang.reflect.InvocationTargetException; -import org.apache.maven.surefire.report.PojoStackTraceWriter; + +import org.apache.maven.surefire.providerapi.ProviderParameters; +import org.apache.maven.surefire.providerapi.SurefireProvider; +import org.apache.maven.surefire.report.LegacyPojoStackTraceWriter; +import org.apache.maven.surefire.report.ReporterFactory; +import org.apache.maven.surefire.report.StackTraceWriter; import org.apache.maven.surefire.suite.RunResult; import org.apache.maven.surefire.testset.TestSetFailedException; -import org.apache.maven.surefire.util.LazyTestsToRun; +import org.apache.maven.surefire.util.ReflectionUtils; /** * The part of the booter that is unique to a forked vm. @@ -70,19 +75,23 @@ public static void main( String[] args ) boolean readTestsFromInputStream = providerConfiguration.isReadTestsFromInStream(); final ClasspathConfiguration classpathConfiguration = startupConfiguration.getClasspathConfiguration(); - final ClassLoader testClassLoader = classpathConfiguration.createForkingTestClassLoader( - startupConfiguration.isManifestOnlyJarRequestedAndUsable() ); + if ( startupConfiguration.isManifestOnlyJarRequestedAndUsable() ) + { + classpathConfiguration.trickClassPathWhenManifestOnlyClasspath(); + } + Thread.currentThread().getContextClassLoader().setDefaultAssertionStatus( + classpathConfiguration.isEnableAssertions() ); startupConfiguration.writeSurefireTestClasspathProperty(); Object testSet; if ( forkedTestSet != null ) { - testSet = forkedTestSet.getDecodedValue( testClassLoader ); + testSet = forkedTestSet.getDecodedValue( Thread.currentThread().getContextClassLoader() ); } else if ( readTestsFromInputStream ) { - testSet = new LazyTestsToRun( System.in, testClassLoader, originalOut ); + testSet = new LazyTestsToRun( System.in, originalOut ); } else { @@ -91,22 +100,20 @@ else if ( readTestsFromInputStream ) try { - runSuitesInProcess( testSet, testClassLoader, startupConfiguration, providerConfiguration, - originalOut ); + runSuitesInProcess( testSet, startupConfiguration, providerConfiguration, originalOut ); } catch ( InvocationTargetException t ) { - PojoStackTraceWriter stackTraceWriter = - new PojoStackTraceWriter( "test subystem", "no method", t.getTargetException() ); + LegacyPojoStackTraceWriter stackTraceWriter = + new LegacyPojoStackTraceWriter( "test subystem", "no method", t.getTargetException() ); StringBuffer stringBuffer = new StringBuffer(); ForkingRunListener.encode( stringBuffer, stackTraceWriter, false ); originalOut.println( ( (char) ForkingRunListener.BOOTERCODE_ERROR ) + ",0," + stringBuffer.toString() ); } catch ( Throwable t ) { - - PojoStackTraceWriter stackTraceWriter = new PojoStackTraceWriter( "test subystem", "no method", t ); + StackTraceWriter stackTraceWriter = new LegacyPojoStackTraceWriter( "test subystem", "no method", t ); StringBuffer stringBuffer = new StringBuffer(); ForkingRunListener.encode( stringBuffer, stackTraceWriter, false ); originalOut.println( ( (char) ForkingRunListener.BOOTERCODE_ERROR ) + ",0," + stringBuffer.toString() ); @@ -136,30 +143,22 @@ private static void exit( final int returnCode ) } - private static RunResult runSuitesInProcess( Object testSet, ClassLoader testsClassLoader, - StartupConfiguration startupConfiguration, + private static RunResult runSuitesInProcess( Object testSet, StartupConfiguration startupConfiguration, ProviderConfiguration providerConfiguration, PrintStream originalSystemOut ) throws SurefireExecutionException, TestSetFailedException, InvocationTargetException { - final ClasspathConfiguration classpathConfiguration = startupConfiguration.getClasspathConfiguration(); - ClassLoader surefireClassLoader = classpathConfiguration.createSurefireClassLoader( testsClassLoader ); - - SurefireReflector surefireReflector = new SurefireReflector( surefireClassLoader ); + final ReporterFactory factory = createForkingReporterFactory( providerConfiguration, originalSystemOut ); - final Object factory = - createForkingReporterFactory( surefireReflector, providerConfiguration, originalSystemOut ); - - return ProviderFactory.invokeProvider( testSet, testsClassLoader, surefireClassLoader, factory, - providerConfiguration, true, startupConfiguration, false ); + return invokeProviderInSameClassLoader( testSet, factory, providerConfiguration, true, startupConfiguration, + false ); } - private static Object createForkingReporterFactory( SurefireReflector surefireReflector, - ProviderConfiguration providerConfiguration, - PrintStream originalSystemOut ) + private static ReporterFactory createForkingReporterFactory( ProviderConfiguration providerConfiguration, + PrintStream originalSystemOut ) { final Boolean trimStackTrace = providerConfiguration.getReporterConfiguration().isTrimStackTrace(); - return surefireReflector.createForkingReporterFactory( trimStackTrace, originalSystemOut ); + return SurefireReflector.createForkingReporterFactoryInCurrentClassLoader( trimStackTrace, originalSystemOut ); } private static void launchLastDitchDaemonShutdownThread( final int returnCode ) @@ -182,4 +181,51 @@ public void run() lastExit.start(); } + public static RunResult invokeProviderInSameClassLoader( Object testSet, Object factory, + ProviderConfiguration providerConfiguration, + boolean insideFork, + StartupConfiguration startupConfiguration1, + 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" instatiation + // in createProvider below. These are the same values as here. + + final SurefireProvider provider = + createProviderInCurrentClassloader( startupConfiguration1, insideFork, providerConfiguration, factory ); + try + { + return provider.invoke( testSet ); + } + finally + { + if ( restoreStreams && System.getSecurityManager() == null ) + { + System.setOut( orgSystemOut ); + System.setErr( orgSystemErr ); + } + } + } + + public static SurefireProvider createProviderInCurrentClassloader( StartupConfiguration startupConfiguration1, + boolean isInsideFork, + ProviderConfiguration providerConfiguration, + Object reporterManagerFactory1 ) + { + + BaseProviderFactory bpf = new BaseProviderFactory( (ReporterFactory) reporterManagerFactory1, isInsideFork ); + bpf.setTestRequest( providerConfiguration.getTestSuiteDefinition() ); + bpf.setReporterConfiguration( providerConfiguration.getReporterConfiguration() ); + ClassLoader clasLoader = Thread.currentThread().getContextClassLoader(); + bpf.setClassLoaders( clasLoader ); + bpf.setTestArtifactInfo( providerConfiguration.getTestArtifact() ); + bpf.setProviderProperties( providerConfiguration.getProviderProperties() ); + bpf.setRunOrderParameters( providerConfiguration.getRunOrderParameters() ); + bpf.setDirectoryScannerParameters( providerConfiguration.getDirScannerParams() ); + return (SurefireProvider) ReflectionUtils.instantiateOneArg( clasLoader, + startupConfiguration1.getActualClassName(), + ProviderParameters.class, bpf ); + } } 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 ee46e4bb5b..393dd05f98 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 @@ -32,7 +32,7 @@ public class IsolatedClassLoader { private final ClassLoader parent = ClassLoader.getSystemClassLoader(); - private final Set urls = new HashSet(); + private final Set urls = new HashSet(); private final String roleName; diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/util/LazyTestsToRun.java b/surefire-booter/src/main/java/org/apache/maven/surefire/booter/LazyTestsToRun.java similarity index 75% rename from surefire-api/src/main/java/org/apache/maven/surefire/util/LazyTestsToRun.java rename to surefire-booter/src/main/java/org/apache/maven/surefire/booter/LazyTestsToRun.java index 874c971c6a..ff0f18482d 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/util/LazyTestsToRun.java +++ b/surefire-booter/src/main/java/org/apache/maven/surefire/booter/LazyTestsToRun.java @@ -1,195 +1,181 @@ -package org.apache.maven.surefire.util; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES 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.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.PrintStream; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import org.apache.maven.surefire.booter.ForkingRunListener; - -/** - * A variant of TestsToRun that is provided with test class names - * from an {@link InputStream} (e.g. {@code System.in}). The method - * {@link #iterator()} returns an Iterator that blocks on calls to - * {@link Iterator#hasNext()} until new classes are available, or no more - * classes will be available. - *

- * The methods {@link #getLocatedClasses()} and {@link #size()} will throw an - * {@link UnsupportedOperationException}. - * - * @author Andreas Gudian - */ -public class LazyTestsToRun - extends TestsToRun -{ - private List workQueue = new ArrayList(); - - private BufferedReader inputReader; - - private boolean streamClosed = false; - - private ClassLoader testClassLoader; - - private PrintStream originalOutStream; - - /** - * C'tor - * - * @param testSource source to read the tests from - * @param testClassLoader class loader to load the test classes - * @param originalOutStream the output stream to use when requesting new new tests - */ - public LazyTestsToRun( InputStream testSource, ClassLoader testClassLoader, PrintStream originalOutStream ) - { - super( Collections.emptyList() ); - - this.testClassLoader = testClassLoader; - this.originalOutStream = originalOutStream; - - inputReader = new BufferedReader( new InputStreamReader( testSource ) ); - } - - protected void addWorkItem( String className ) - { - synchronized ( workQueue ) - { - workQueue.add( ReflectionUtils.loadClass( testClassLoader, className ) ); - } - } - - protected void requestNextTest() - { - StringBuffer sb = new StringBuffer(); - sb.append( (char) ForkingRunListener.BOOTERCODE_NEXT_TEST ).append( ",0,want more!\n" ); - originalOutStream.print( sb.toString() ); - } - - private class BlockingIterator - implements Iterator - { - private int lastPos = -1; - - public boolean hasNext() - { - int nextPos = lastPos + 1; - synchronized ( workQueue ) - { - if ( workQueue.size() > nextPos ) - { - return true; - } - else - { - if ( needsToWaitForInput( nextPos ) ) - { - requestNextTest(); - - String nextClassName; - try - { - nextClassName = inputReader.readLine(); - } - catch ( IOException e ) - { - streamClosed = true; - return false; - } - - if ( null == nextClassName ) - { - streamClosed = true; - } - else - { - addWorkItem( nextClassName ); - } - } - - return ( workQueue.size() > nextPos ); - } - } - } - - private boolean needsToWaitForInput( int nextPos ) - { - return workQueue.size() == nextPos && !streamClosed; - } - - public Object next() - { - synchronized ( workQueue ) - { - return workQueue.get( ++lastPos ); - } - } - - public void remove() - { - throw new UnsupportedOperationException(); - } - - } - - /* (non-Javadoc) - * @see org.apache.maven.surefire.util.TestsToRun#iterator() - */ - public Iterator iterator() - { - return new BlockingIterator(); - } - - /** - * Unsupported. Use {@link #iterator()} instead. - */ - public int size() - { - throw new UnsupportedOperationException( "use method iterator()" ); - } - - /** - * Unsupported. Use {@link #iterator()} instead. - */ - public Class[] getLocatedClasses() - { - throw new UnsupportedOperationException( "use method iterator()" ); - } - - /* (non-Javadoc) - * @see org.apache.maven.surefire.util.TestsToRun#toString() - */ - public String toString() - { - StringBuffer sb = new StringBuffer( "LazyTestsToRun " ); - synchronized ( workQueue ) - { - sb.append( "(more items expected: " ).append( !streamClosed ).append( "): " ); - sb.append( workQueue ); - } - - return sb.toString(); - } - -} +package org.apache.maven.surefire.booter; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES 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.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.PrintStream; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; + +import org.apache.maven.surefire.util.ReflectionUtils; +import org.apache.maven.surefire.util.TestsToRun; + +/** + * A variant of TestsToRun that is provided with test class names + * from an {@link InputStream} (e.g. {@code System.in}). The method + * {@link #iterator()} returns an Iterator that blocks on calls to + * {@link Iterator#hasNext()} until new classes are available, or no more + * classes will be available. + * + * @author Andreas Gudian + */ +class LazyTestsToRun + extends TestsToRun +{ + private final List workQueue = new ArrayList(); + + private BufferedReader inputReader; + + private boolean streamClosed = false; + + private PrintStream originalOutStream; + + /** + * C'tor + * + * @param testSource source to read the tests from + * @param originalOutStream the output stream to use when requesting new new tests + */ + public LazyTestsToRun( InputStream testSource, PrintStream originalOutStream ) + { + super( Collections.emptyList() ); + + this.originalOutStream = originalOutStream; + + inputReader = new BufferedReader( new InputStreamReader( testSource ) ); + } + + protected void addWorkItem( String className ) + { + synchronized ( workQueue ) + { + workQueue.add( ReflectionUtils.loadClass( Thread.currentThread().getContextClassLoader(), className ) ); + } + } + + protected void requestNextTest() + { + StringBuilder sb = new StringBuilder(); + sb.append( (char) ForkingRunListener.BOOTERCODE_NEXT_TEST ).append( ",0,want more!\n" ); + originalOutStream.print( sb.toString() ); + } + + private class BlockingIterator + implements Iterator + { + private int lastPos = -1; + + public boolean hasNext() + { + int nextPos = lastPos + 1; + synchronized ( workQueue ) + { + if ( workQueue.size() > nextPos ) + { + return true; + } + else + { + if ( needsToWaitForInput( nextPos ) ) + { + requestNextTest(); + + String nextClassName; + try + { + nextClassName = inputReader.readLine(); + } + catch ( IOException e ) + { + streamClosed = true; + return false; + } + + if ( null == nextClassName ) + { + streamClosed = true; + } + else + { + addWorkItem( nextClassName ); + } + } + + return ( workQueue.size() > nextPos ); + } + } + } + + private boolean needsToWaitForInput( int nextPos ) + { + return workQueue.size() == nextPos && !streamClosed; + } + + public Class next() + { + synchronized ( workQueue ) + { + return workQueue.get( ++lastPos ); + } + } + + public void remove() + { + throw new UnsupportedOperationException(); + } + + } + + /* (non-Javadoc) + * @see org.apache.maven.surefire.util.TestsToRun#iterator() + */ + public Iterator iterator() + { + return new BlockingIterator(); + } + + /* (non-Javadoc) + * @see org.apache.maven.surefire.util.TestsToRun#toString() + */ + public String toString() + { + StringBuilder sb = new StringBuilder( "LazyTestsToRun " ); + synchronized ( workQueue ) + { + sb.append( "(more items expected: " ).append( !streamClosed ).append( "): " ); + sb.append( workQueue ); + } + + return sb.toString(); + } + + /* (non-Javadoc) + * @see org.apache.maven.surefire.util.TestsToRun#allowEagerReading() + */ + public boolean allowEagerReading() { + return false; + } + +} 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 8c0dd756b4..8a40c63a6b 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 @@ -28,6 +28,8 @@ import org.apache.maven.surefire.util.internal.StringUtils; /** + * Makes java.util.Properties behave like it's 2013 + * * @author Kristian Rosenvold */ public class PropertiesWrapper @@ -51,9 +53,9 @@ public Properties getProperties() public void setAsSystemProperties() { - for ( Iterator i = properties.keySet().iterator(); i.hasNext(); ) + for ( Object o : properties.keySet() ) { - String key = (String) i.next(); + String key = (String) o; System.setProperty( key, properties.getProperty( key ) ); } @@ -66,8 +68,7 @@ public String getProperty( String key ) public boolean getBooleanProperty( String propertyName ) { - final Boolean aBoolean = Boolean.valueOf( properties.getProperty( propertyName ) ); - return aBoolean.booleanValue(); + return Boolean.valueOf( properties.getProperty( propertyName ) ); } public Boolean getBooleanObjectProperty( String propertyName ) @@ -86,10 +87,10 @@ public File getFileProperty( String key ) return (File) typeEncodedValue.getDecodedValue(); } - public List getStringList( String propertyPrefix ) + public List getStringList( String propertyPrefix ) { String value; - List result = new ArrayList(); + List result = new ArrayList(); // Whoa, C !! for ( int i = 0; ( value = getProperty( propertyPrefix + i ) ) != null; i++ ) { @@ -118,25 +119,9 @@ public TypeEncodedValue getTypeEncodedValue( String key ) } - 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() ); - } - } - Classpath getClasspath( String prefix ) { - List elements = getStringList( prefix ); + List elements = getStringList( prefix ); return new Classpath( elements ); } @@ -166,9 +151,8 @@ public void addList( List items, String propertyPrefix ) return; } int i = 0; - for ( Iterator iterator = items.iterator(); iterator.hasNext(); ) + for ( Object item : items ) { - Object item = iterator.next(); if ( item == null ) { throw new NullPointerException( propertyPrefix + i + " has null value" ); @@ -176,9 +160,9 @@ public void addList( List items, String propertyPrefix ) String[] stringArray = StringUtils.split( item.toString(), "," ); - for ( int j = 0; j < stringArray.length; j++ ) + for ( String aStringArray : stringArray ) { - properties.setProperty( propertyPrefix + i, stringArray[j] ); + properties.setProperty( propertyPrefix + i, aStringArray ); i++; } @@ -192,6 +176,7 @@ public void copyTo( Map target ) while ( iter.hasNext() ) { key = iter.next(); + //noinspection unchecked target.put( key, properties.get( key ) ); } } 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 cd29916ac6..67747f566f 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 @@ -44,10 +44,6 @@ public class ProviderConfiguration */ public static final int TESTS_SUCCEEDED_EXIT_CODE = 0; - public static final int TESTS_FAILED_EXIT_CODE = 255; - - public static final int NO_TESTS_EXIT_CODE = 254; - private final DirectoryScannerParameters dirScannerParams; private final ReporterConfiguration reporterConfiguration; 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 abef1c6b1e..e0c88bc415 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 @@ -23,6 +23,7 @@ import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Iterator; + import org.apache.maven.surefire.providerapi.SurefireProvider; import org.apache.maven.surefire.report.ReporterException; import org.apache.maven.surefire.suite.RunResult; @@ -42,9 +43,7 @@ public class ProviderFactory private final ProviderConfiguration providerConfiguration; - private final ClassLoader surefireClassLoader; - - private final ClassLoader testsClassLoader; + private final ClassLoader classLoader; private final SurefireReflector surefireReflector; @@ -54,19 +53,16 @@ public class ProviderFactory public ProviderFactory( StartupConfiguration startupConfiguration, ProviderConfiguration providerConfiguration, - ClassLoader surefireClassLoader, ClassLoader testsClassLoader, - Object reporterManagerFactory ) + ClassLoader testsClassLoader, Object reporterManagerFactory ) { this.providerConfiguration = providerConfiguration; - this.surefireClassLoader = surefireClassLoader; this.startupConfiguration = startupConfiguration; - this.surefireReflector = new SurefireReflector( surefireClassLoader ); - this.testsClassLoader = testsClassLoader; + this.surefireReflector = new SurefireReflector( testsClassLoader ); + this.classLoader = testsClassLoader; this.reporterManagerFactory = reporterManagerFactory; } - public static RunResult invokeProvider( Object testSet, ClassLoader testsClassLoader, - ClassLoader surefireClassLoader, Object factory, + public static RunResult invokeProvider( Object testSet, ClassLoader testsClassLoader, Object factory, ProviderConfiguration providerConfiguration, boolean insideFork, StartupConfiguration startupConfiguration1, boolean restoreStreams ) throws TestSetFailedException, InvocationTargetException @@ -77,7 +73,7 @@ public static RunResult invokeProvider( Object testSet, ClassLoader testsClassLo // in createProvider below. These are the same values as here. ProviderFactory providerFactory = - new ProviderFactory( startupConfiguration1, providerConfiguration, surefireClassLoader, testsClassLoader, + new ProviderFactory( startupConfiguration1, providerConfiguration, testsClassLoader, factory ); final SurefireProvider provider = providerFactory.createProvider( insideFork ); @@ -95,27 +91,29 @@ public static RunResult invokeProvider( Object testSet, ClassLoader testsClassLo } } + public SurefireProvider createProvider( boolean isInsideFork ) { - ClassLoader context = java.lang.Thread.currentThread().getContextClassLoader(); - Thread.currentThread().setContextClassLoader( surefireClassLoader ); + ClassLoader systemClassLoader = java.lang.Thread.currentThread().getContextClassLoader(); + Thread.currentThread().setContextClassLoader( classLoader ); StartupConfiguration starterConfiguration = startupConfiguration; + // Note: Duplicated in ForkedBooter#createProviderInCurrentClassloader final Object o = - surefireReflector.createBooterConfiguration( surefireClassLoader, reporterManagerFactory, isInsideFork ); + surefireReflector.createBooterConfiguration( classLoader, reporterManagerFactory, isInsideFork ); surefireReflector.setTestSuiteDefinitionAware( o, providerConfiguration.getTestSuiteDefinition() ); surefireReflector.setProviderPropertiesAware( o, providerConfiguration.getProviderProperties() ); surefireReflector.setReporterConfigurationAware( o, providerConfiguration.getReporterConfiguration() ); - surefireReflector.setTestClassLoaderAware( o, surefireClassLoader, testsClassLoader ); + surefireReflector.setTestClassLoaderAware( o, classLoader ); surefireReflector.setTestArtifactInfoAware( o, providerConfiguration.getTestArtifact() ); surefireReflector.setRunOrderParameters( o, providerConfiguration.getRunOrderParameters() ); surefireReflector.setIfDirScannerAware( o, providerConfiguration.getDirScannerParams() ); - Object provider = surefireReflector.instantiateProvider( starterConfiguration.getProviderClassName(), o ); - Thread.currentThread().setContextClassLoader( context ); + Object provider = surefireReflector.instantiateProvider( starterConfiguration.getActualClassName(), o ); + Thread.currentThread().setContextClassLoader( systemClassLoader ); - return new ProviderProxy( provider, testsClassLoader ); + return new ProviderProxy( provider, classLoader ); } 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 32d3f79a84..1c454dbfdc 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 @@ -43,13 +43,18 @@ public StartupConfiguration( String providerClassName, ClasspathConfiguration cl ClassLoaderConfiguration classLoaderConfiguration, boolean isForkRequested, boolean inForkedVm ) { - this.providerClassName = providerClassName; this.classpathConfiguration = classpathConfiguration; this.classLoaderConfiguration = classLoaderConfiguration; this.isForkRequested = isForkRequested; + this.providerClassName = providerClassName; isInForkedVm = inForkedVm; } + public boolean isProviderMainClass() + { + return providerClassName.endsWith( "#main" ); + } + public static StartupConfiguration inForkedVm( String providerClassName, ClasspathConfiguration classpathConfiguration, ClassLoaderConfiguration classLoaderConfiguration ) @@ -79,6 +84,50 @@ public String getProviderClassName() return providerClassName; } + public String getActualClassName() + { + if ( isProviderMainClass() ) + { + return stripEnd( providerClassName, "#main" ); + } + return providerClassName; + } + + /** + *

Strip any of a supplied String from the end of a String.

+ *

+ *

If the strip String is null, whitespace is + * stripped.

+ * + * @param str the String to remove characters from + * @param strip the String to remove + * @return the stripped String + */ + public 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 ) ) ) + { + end--; + } + } + else + { + while ( ( end != 0 ) && ( strip.indexOf( str.charAt( end - 1 ) ) != -1 ) ) + { + end--; + } + } + return str.substring( 0, end ); + } + public ClassLoaderConfiguration getClassLoaderConfiguration() { return classLoaderConfiguration; 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 92514224d6..a71d40bc07 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 @@ -96,6 +96,7 @@ else if ( type.equals( Properties.class.getName() ) ) } } + @SuppressWarnings( "SimplifiableIfStatement" ) public boolean equals( Object o ) { if ( this == o ) 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 e142164829..78a180b84d 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 @@ -24,6 +24,8 @@ import junit.framework.TestCase; +import static org.apache.maven.surefire.booter.Classpath.emptyClasspath; + /** * @author Kristian Rosenvold */ @@ -39,7 +41,7 @@ public class ClasspathTest public void testShouldWriteEmptyPropertyForEmptyClasspath() throws Exception { - Classpath classpath = new Classpath(); + Classpath classpath = Classpath.emptyClasspath(); classpath.writeToSystemProperty( DUMMY_PROPERTY_NAME ); assertEquals( "", System.getProperty( DUMMY_PROPERTY_NAME ) ); } @@ -47,9 +49,7 @@ public void testShouldWriteEmptyPropertyForEmptyClasspath() public void testShouldWriteSeparatedElementsAsSystemProperty() throws Exception { - Classpath classpath = new Classpath(); - classpath.addClassPathElementUrl( DUMMY_URL_1 ); - classpath.addClassPathElementUrl( DUMMY_URL_2 ); + 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 ) ); @@ -57,9 +57,8 @@ public void testShouldWriteSeparatedElementsAsSystemProperty() public void testShouldAddNoDuplicateElements() { - Classpath classpath = new Classpath(); - classpath.addClassPathElementUrl( DUMMY_URL_1 ); - classpath.addClassPathElementUrl( DUMMY_URL_1 ); + Classpath classpath = + emptyClasspath().addClassPathElementUrl( DUMMY_URL_1 ).addClassPathElementUrl( DUMMY_URL_1 ); assertClasspathConsistsOfElements( classpath, new String[]{ DUMMY_URL_1 } ); } @@ -81,10 +80,8 @@ public void testShouldJoinTwoNullClasspaths() public void testShouldHaveAllElementsAfterJoiningTwoDifferentClasspaths() throws Exception { - Classpath firstClasspath = new Classpath(); - firstClasspath.addClassPathElementUrl( DUMMY_URL_1 ); - Classpath secondClasspath = new Classpath(); - secondClasspath.addClassPathElementUrl( DUMMY_URL_2 ); + 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 } ); } @@ -92,10 +89,8 @@ public void testShouldHaveAllElementsAfterJoiningTwoDifferentClasspaths() public void testShouldNotHaveDuplicatesAfterJoiningTowClasspathsWithEqualElements() throws Exception { - Classpath firstClasspath = new Classpath(); - firstClasspath.addClassPathElementUrl( DUMMY_URL_1 ); - Classpath secondClasspath = new Classpath(); - secondClasspath.addClassPathElementUrl( DUMMY_URL_1 ); + 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 } ); } @@ -117,9 +112,9 @@ public void testShouldNotBeAbleToRemoveElement() private void assertClasspathConsistsOfElements( Classpath classpath, String[] elements ) { List classpathElements = classpath.getClassPath(); - for ( int i = 0; i < elements.length; ++i ) + for ( String element : elements ) { - assertTrue( "The element '" + elements[i] + " is missing.", classpathElements.contains( elements[i] ) ); + assertTrue( "The element '" + element + " is missing.", classpathElements.contains( element ) ); } assertEquals( "Wrong number of classpath elements.", elements.length, classpathElements.size() ); } @@ -132,16 +127,14 @@ private void assertEmptyClasspath( Classpath classpath ) private Classpath createClasspathWithTwoElements() { - Classpath classpath = new Classpath(); - classpath.addClassPathElementUrl( DUMMY_URL_1 ); - classpath.addClassPathElementUrl( DUMMY_URL_2 ); - return classpath; + Classpath classpath = Classpath.emptyClasspath(); + return classpath.addClassPathElementUrl( DUMMY_URL_1 ).addClassPathElementUrl( DUMMY_URL_2 ); } public void testShouldThrowIllegalArgumentExceptionWhenNullIsAddedAsClassPathElementUrl() throws Exception { - Classpath classpath = new Classpath(); + Classpath classpath = Classpath.emptyClasspath(); try { classpath.addClassPathElementUrl( null ); @@ -155,7 +148,7 @@ public void testShouldThrowIllegalArgumentExceptionWhenNullIsAddedAsClassPathEle public void testShouldNotAddNullAsClassPathElementUrl() throws Exception { - Classpath classpath = new Classpath(); + Classpath classpath = Classpath.emptyClasspath(); try { classpath.addClassPathElementUrl( null ); 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 9d3bf49753..82248b561d 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 @@ -36,8 +36,6 @@ public class Foo { DirectoryScannerParameters directoryScannerParameters; - TestRequest testSuiteDefinition; - Properties providerProperties; ReporterConfiguration reporterConfiguration; @@ -67,7 +65,7 @@ public void setDirectoryScannerParameters( DirectoryScannerParameters directoryS */ public Boolean isCalled() { - return Boolean.valueOf( called ); + return called; } public void setProviderProperties( Properties providerProperties ) @@ -82,7 +80,7 @@ public void setReporterConfiguration( ReporterConfiguration reporterConfiguratio this.called = true; } - public void setClassLoaders( ClassLoader surefireClassLoader, ClassLoader testClassLoader ) + public void setClassLoaders( ClassLoader testClassLoader ) { this.testClassLoader = testClassLoader; this.surefireClassLoader = surefireClassLoader; 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 47d413fbad..bda705ba18 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 @@ -37,7 +37,7 @@ public void testAddList() Properties props = new Properties(); PropertiesWrapper propertiesWrapper = new PropertiesWrapper( props ); - List items = new ArrayList(); + List items = new ArrayList(); items.add( "String1" ); items.add( "String2,String3" ); items.add( "String4" ); @@ -99,10 +99,7 @@ public void testRoundtrip() private Classpath createClasspathWithTwoElements() { - Classpath classpath = new Classpath(); - classpath.addClassPathElementUrl( FIRST_ELEMENT ); - classpath.addClassPathElementUrl( SECOND_ELEMENT ); - return classpath; + return Classpath.emptyClasspath().addClassPathElementUrl( FIRST_ELEMENT ).addClassPathElementUrl( SECOND_ELEMENT ); } private Classpath readClasspathFromProperties() 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 28e367f121..72d7da65b3 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 @@ -52,7 +52,7 @@ public void testSetDirectoryScannerParameters() new DirectoryScannerParameters( new File( "ABC" ), new ArrayList(), new ArrayList(), new ArrayList(), Boolean.FALSE, "hourly" ); surefireReflector.setDirectoryScannerParameters( foo, directoryScannerParameters ); - assertTrue( isCalled( foo ).booleanValue() ); + assertTrue( isCalled( foo ) ); } @@ -64,7 +64,7 @@ public void testRunOrderParameters() RunOrderParameters runOrderParameters = new RunOrderParameters( RunOrder.DEFAULT, new File( "." ) ); surefireReflector.setRunOrderParameters( foo, runOrderParameters ); - assertTrue( isCalled( foo ).booleanValue() ); + assertTrue( isCalled( foo ) ); } @@ -75,10 +75,10 @@ public void testTestSuiteDefinition() Object foo = getFoo(); TestRequest testSuiteDefinition = - new TestRequest( Arrays.asList( new File[]{ new File( "file1" ), new File( "file2" ) } ), + new TestRequest( Arrays.asList( new File( "file1" ), new File( "file2" ) ), new File( "TestSOurce" ), "aUserRequestedTest", "aMethodRequested" ); surefireReflector.setTestSuiteDefinition( foo, testSuiteDefinition ); - assertTrue( isCalled( foo ).booleanValue() ); + assertTrue( isCalled( foo ) ); } public void testProviderProperties() @@ -88,7 +88,7 @@ public void testProviderProperties() Object foo = getFoo(); surefireReflector.setProviderProperties( foo, new Properties() ); - assertTrue( isCalled( foo ).booleanValue() ); + assertTrue( isCalled( foo ) ); } public void testReporterConfiguration() @@ -99,7 +99,7 @@ public void testReporterConfiguration() ReporterConfiguration reporterConfiguration = getReporterConfiguration(); surefireReflector.setReporterConfigurationAware( foo, reporterConfiguration ); - assertTrue( isCalled( foo ).booleanValue() ); + assertTrue( isCalled( foo ) ); } private ReporterConfiguration getReporterConfiguration() @@ -113,8 +113,8 @@ public void testTestClassLoaderAware() SurefireReflector surefireReflector = getReflector(); Object foo = getFoo(); - surefireReflector.setTestClassLoader( foo, getClass().getClassLoader(), getClass().getClassLoader() ); - assertTrue( isCalled( foo ).booleanValue() ); + surefireReflector.setTestClassLoader( foo, getClass().getClassLoader() ); + assertTrue( isCalled( foo ) ); } public void testArtifactInfoAware() @@ -125,7 +125,7 @@ public void testArtifactInfoAware() TestArtifactInfo testArtifactInfo = new TestArtifactInfo( "12.3", "test" ); surefireReflector.setTestArtifactInfo( foo, testArtifactInfo ); - assertTrue( isCalled( foo ).booleanValue() ); + assertTrue( isCalled( foo ) ); } private SurefireReflector getReflector() @@ -145,7 +145,7 @@ private Boolean isCalled( Object foo ) try { isCalled = foo.getClass().getMethod( "isCalled", new Class[0] ); - return (Boolean) isCalled.invoke( foo, new Object[0] ); + return (Boolean) isCalled.invoke( foo ); } catch ( IllegalAccessException e ) { diff --git a/surefire-grouper/pom.xml b/surefire-grouper/pom.xml index 5b42486518..762f1df674 100644 --- a/surefire-grouper/pom.xml +++ b/surefire-grouper/pom.xml @@ -18,14 +18,13 @@ ~ under the License. --> - + 4.0.0 org.apache.maven.surefire surefire - 2.13-SNAPSHOT + 2.16-SNAPSHOT ../pom.xml @@ -58,7 +57,7 @@ org.apache.maven.surefire surefire-shadefire - ${project.version} + ${shadedVersion}
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 474dbae184..9fbfcf27cc 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 @@ -113,11 +113,7 @@ public boolean equals( Object obj ) return false; } AndGroupMatcher other = (AndGroupMatcher) obj; - if ( !getMatchers().equals( other.getMatchers() ) ) - { - return false; - } - return true; + return getMatchers().equals( other.getMatchers() ); } } 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 24f57db4bc..567c32871a 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 @@ -32,12 +32,12 @@ public InverseGroupMatcher( GroupMatcher matcher ) public boolean enabled( Class... cats ) { - return cats == null ? true : !matcher.enabled( cats ); + return cats == null || !matcher.enabled( cats ); } public boolean enabled( String... cats ) { - return cats == null ? true : !matcher.enabled( cats ); + return cats == null || !matcher.enabled( cats ); } @Override 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 9bfce9a4b4..6073b041fb 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 @@ -113,10 +113,6 @@ public boolean equals( Object obj ) return false; } AndGroupMatcher other = (AndGroupMatcher) obj; - if ( !getMatchers().equals( other.getMatchers() ) ) - { - return false; - } - return true; + return getMatchers().equals( other.getMatchers() ); } } diff --git a/surefire-integration-tests/pom.xml b/surefire-integration-tests/pom.xml index 431eab31eb..d32401908f 100644 --- a/surefire-integration-tests/pom.xml +++ b/surefire-integration-tests/pom.xml @@ -18,14 +18,13 @@ ~ under the License. --> - + 4.0.0 org.apache.maven.surefire surefire - 2.13-SNAPSHOT + 2.16-SNAPSHOT ../pom.xml @@ -43,10 +42,15 @@ + + org.apache.maven.surefire + surefire-report-parser + ${project.version} + test + org.apache.maven.shared maven-verifier - 1.4-SNAPSHOT org.apache.maven @@ -66,11 +70,6 @@ 2.8 test - - commons-io - commons-io - 2.0.1 - org.apache.maven maven-artifact @@ -79,6 +78,10 @@ org.apache.maven.shared maven-shared-utils + + commons-io + commons-io + @@ -96,7 +99,10 @@ 1 false never - -Xmx512m -XX:MaxPermSize=256m + -Xmx512m -XX:MaxPermSize=356m + + org/apache/**/*IT*.java + @@ -188,13 +194,19 @@ embedded + + + + ${basedir} + + auto - maven-2.2.1 + maven-2.2.1 ${project.build.directory}/maven-extract/apache-maven-2.2.1 diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/AbstractTestCaseIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/AbstractTestCaseIT.java index ee84d45154..0260ba0a2f 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/AbstractTestCaseIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/AbstractTestCaseIT.java @@ -19,7 +19,8 @@ * under the License. */ -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; +import org.junit.Test; /** * Test files with "Abstract" in their name that aren't really abstract, @@ -29,10 +30,10 @@ * @author Kristian Rosenvold */ public class AbstractTestCaseIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { - - public void testAbstractTestCase() + @Test + public void abstractTestCase() { unpack( "/default-configuration-abstract" ).executeTest().verifyErrorFree( 1 ); } diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/AdditionalClasspathIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/AdditionalClasspathIT.java index c9f5cfbe2b..08191961d8 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/AdditionalClasspathIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/AdditionalClasspathIT.java @@ -19,7 +19,8 @@ * under the License. */ -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; +import org.junit.Test; /** * Test additionalClasspathElements @@ -28,9 +29,10 @@ * @author Kristian Rosenvold */ public class AdditionalClasspathIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { - public void testAdditionalClasspath() + @Test + public void additionalClasspath() { unpack( "/additional-classpath" ).executeTest().verifyErrorFree( 1 ); } diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/AggregateReportIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/AggregateReportIT.java index b747165f49..ee167df523 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/AggregateReportIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/AggregateReportIT.java @@ -20,11 +20,11 @@ */ import java.io.File; -import org.apache.maven.surefire.its.fixture.HelperAssertions; -import org.apache.maven.surefire.its.fixture.IntegrationTestSuiteResults; -import org.apache.maven.surefire.its.fixture.OutputValidator; -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; -import org.apache.maven.surefire.its.fixture.TestFile; + +import org.apache.maven.surefire.its.fixture.*; +import org.junit.Test; + +import static org.junit.Assert.assertTrue; /** * Test report aggregation @@ -33,10 +33,11 @@ * @author Kristian Rosenvold */ public class AggregateReportIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { - public void testAggregateReport() + @Test + public void aggregateReport() { final OutputValidator outputValidator = unpack( "/aggregate-report" ).addSurefireReportGoal().executeCurrentGoals(); diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/ArgLineIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/ArgLineIT.java index 36d0d9e5fb..c1ad8f7a9c 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/ArgLineIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/ArgLineIT.java @@ -19,7 +19,8 @@ * under the License. */ -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; +import org.junit.Test; /** * Test passing an argLine parameter @@ -28,9 +29,10 @@ * @author Kristian Rosenvold */ public class ArgLineIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { - public void testArgLine() + @Test + public void argLine() { unpack( "/argLine-parameter" ).executeTest().verifyErrorFree( 1 ); } diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/CheckSingleTestIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/CheckSingleTestIT.java index 5e34e0f29b..85d0f951f0 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/CheckSingleTestIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/CheckSingleTestIT.java @@ -19,10 +19,10 @@ * under the License. */ -import org.apache.maven.surefire.its.fixture.OutputValidator; -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; -import org.apache.maven.surefire.its.fixture.SurefireLauncher; -import org.apache.maven.surefire.its.fixture.TestFile; +import org.apache.maven.surefire.its.fixture.*; +import org.junit.Test; + +import static org.junit.Assert.assertFalse; /** * Test running a single test with -Dtest=BasicTest @@ -31,26 +31,30 @@ * @author Kristian Rosenvold */ public class CheckSingleTestIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { - public void testSingleTest() + @Test + public void singleTest() { unpack().setTestToRun( "BasicTest" ).executeTest().verifyErrorFree( 1 ); } - public void testSingleTestDotJava() + @Test + public void singleTestDotJava() { unpack().setTestToRun( "BasicTest.java" ).executeTest().verifyErrorFree( 1 ); } - public void testSingleTestNonExistent() + @Test + public void singleTestNonExistent() { - final OutputValidator output = unpack().setTestToRun( "DoesNotExist" ).executeTestWithFailure(); + final OutputValidator output = unpack().setTestToRun( "DoesNotExist" ).maven().withFailure().executeTest(); TestFile reportsDir = output.getTargetFile( "surefire-reports" ); assertFalse( "Unexpected reports directory", reportsDir.exists() ); } - public void testSingleTestNonExistentOverride() + @Test + public void singleTestNonExistentOverride() { final OutputValidator output = unpack().setTestToRun( "DoesNotExist" ).failIfNoTests( false ).executeTest().verifyErrorFreeLog(); diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/CheckTestFailIfNoTestsForkModeIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/CheckTestFailIfNoTestsForkModeIT.java index 9c46e0d480..6e2a67aa18 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/CheckTestFailIfNoTestsForkModeIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/CheckTestFailIfNoTestsForkModeIT.java @@ -19,8 +19,9 @@ * under the License. */ -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; import org.apache.maven.surefire.its.fixture.SurefireLauncher; +import org.junit.Test; /** * Test failIfNoTests with various forkModes. @@ -29,48 +30,47 @@ * @author Kristian Rosenvold */ public class CheckTestFailIfNoTestsForkModeIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { - public void testFailIfNoTestsForkModeAlways() + @Test + public void failIfNoTestsForkModeAlways() { - doTest( unpack().forkAlways().failIfNoTests( true ) ); + unpack().forkAlways().failIfNoTests( true ).maven().withFailure().executeTest(); } - public void testFailIfNoTestsForkModeNever() + @Test + public void failIfNoTestsForkModeNever() { - doTest( unpack().forkNever().failIfNoTests( true ) ); + unpack().forkNever().failIfNoTests( true ).maven().withFailure().executeTest(); } - public void testFailIfNoTestsForkModeOnce() + @Test + public void failIfNoTestsForkModeOnce() { - doTest( unpack().forkOnce().failIfNoTests( true ) ); + unpack().forkOnce().failIfNoTests( true ).maven().withFailure().executeTest(); } - public void testDontFailIfNoTestsForkModeAlways() + @Test + public void dontFailIfNoTestsForkModeAlways() { doTest( unpack().forkAlways().failIfNoTests( false ) ); } - public void testDontFailIfNoTestsForkModeNever() + @Test + public void dontFailIfNoTestsForkModeNever() { doTest( unpack().forkNever().failIfNoTests( false ) ); } - public void testDontFailIfNoTestsForkModeOnce() + @Test + public void dontFailIfNoTestsForkModeOnce() { doTest( unpack().forkOnce().failIfNoTests( false ) ); } private void doTest( SurefireLauncher launcher ) { - if ( launcher.isFailIfNoTests() ) - { - launcher.executeTestWithFailure(); - } - else - { launcher.executeTest().verifyErrorFreeLog().assertTestSuiteResults( 0, 0, 0, 0 ); - } } private SurefireLauncher unpack() diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/CheckTestFailIfNoTestsIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/CheckTestFailIfNoTestsIT.java index 9e896b6415..787037c217 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/CheckTestFailIfNoTestsIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/CheckTestFailIfNoTestsIT.java @@ -19,10 +19,10 @@ * under the License. */ -import org.apache.maven.surefire.its.fixture.OutputValidator; -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; -import org.apache.maven.surefire.its.fixture.SurefireLauncher; -import org.apache.maven.surefire.its.fixture.TestFile; +import org.apache.maven.surefire.its.fixture.*; +import org.junit.Test; + +import static org.junit.Assert.assertFalse; /** * Test failIfNoTests @@ -31,19 +31,21 @@ * @author Kristian Rosenvold */ public class CheckTestFailIfNoTestsIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { private SurefireLauncher unpack() { return unpack( "/default-configuration-noTests" ); } - public void testFailIfNoTests() + @Test + public void failIfNoTests() { - unpack().failIfNoTests( true ).executeTestWithFailure(); + unpack().failIfNoTests( true ).maven().withFailure().executeTest(); } - public void testDontFailIfNoTests() + @Test + public void dontFailIfNoTests() { final OutputValidator outputValidator = unpack().failIfNoTests( false ).executeTest(); outputValidator.verifyErrorFreeLog(); @@ -51,7 +53,8 @@ public void testDontFailIfNoTests() assertFalse( "Unexpected reports directory", reportsDir.exists() ); } - public void test48CategoriesFailWhenNoTests() + @Test + public void jUnit48CategoriesFailWhenNoTests() { unpack().failIfNoTests( false ).activateProfile( "junit47" ).setJUnitVersion( "4.8.1" ).executeTest().verifyErrorFreeLog(); diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/CheckTestNgBeforeMethodFailureIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/CheckTestNgBeforeMethodFailureIT.java index 2f2668630b..9e9d688695 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/CheckTestNgBeforeMethodFailureIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/CheckTestNgBeforeMethodFailureIT.java @@ -19,7 +19,8 @@ * under the License. */ -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; +import org.junit.Test; /** * Test failures in @BeforeMethod annotation on TestNg suite @@ -28,12 +29,13 @@ * @author Kristian Rosenvold */ public class CheckTestNgBeforeMethodFailureIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { - public void testTestNgBeforeMethodFailure() + @Test + public void TestNgBeforeMethodFailure() throws Exception { - unpack( "/testng-beforeMethodFailure" ).executeTestWithFailure().assertTestSuiteResults( 2, 0, 1, 1 ); + unpack( "/testng-beforeMethodFailure" ).maven().withFailure().executeTest().assertTestSuiteResults( 2, 0, 1, 1 ); } } diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/CheckTestNgBeforeMethodIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/CheckTestNgBeforeMethodIT.java index c86ab1b686..ab252795bc 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/CheckTestNgBeforeMethodIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/CheckTestNgBeforeMethodIT.java @@ -19,7 +19,8 @@ * under the License. */ -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; +import org.junit.Test; /** * Test @BeforeMethod annotation on TestNg suite @@ -28,9 +29,10 @@ * @author Kristian Rosenvold */ public class CheckTestNgBeforeMethodIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { - public void testTestNgBeforeMethod() + @Test + public void TestNgBeforeMethod() throws Exception { unpack( "/testng-beforeMethod" ).executeTest().verifyErrorFree( 1 ); diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/CheckTestNgExecuteErrorIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/CheckTestNgExecuteErrorIT.java index 659110d0f5..ce90b3bc6e 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/CheckTestNgExecuteErrorIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/CheckTestNgExecuteErrorIT.java @@ -37,7 +37,7 @@ public class CheckTestNgExecuteErrorIT public void executionError() throws Exception { - OutputValidator outputValidator = unpack( "/testng-execute-error" ).executeTestWithFailure(); + OutputValidator outputValidator = unpack( "/testng-execute-error" ).maven().withFailure().executeTest(); outputValidator.verifyTextInLog( "at org.apache.maven.surefire.testng.TestNGExecutor.run" ); } } diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/CheckTestNgGroupThreadParallelIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/CheckTestNgGroupThreadParallelIT.java index a7bdddb70f..36ef57ea83 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/CheckTestNgGroupThreadParallelIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/CheckTestNgGroupThreadParallelIT.java @@ -19,7 +19,8 @@ * under the License. */ -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; +import org.junit.Test; /** * Test TestNG groups, together with TestNG parallelism @@ -28,9 +29,10 @@ * @author Kristian Rosenvold */ public class CheckTestNgGroupThreadParallelIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { - public void testTestNgGroupThreadParallel() + @Test + public void TestNgGroupThreadParallel() { unpack( "testng-group-thread-parallel" ).executeTest().verifyErrorFree( 3 ); } diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/CheckTestNgJdk14IT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/CheckTestNgJdk14IT.java index 9be6a1820c..9cabd7e731 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/CheckTestNgJdk14IT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/CheckTestNgJdk14IT.java @@ -19,7 +19,8 @@ * under the License. */ -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; +import org.junit.Test; /** * Test TestNG running in the JDK 1.4 JavaDoc style @@ -27,15 +28,11 @@ * @author Dan Fabulich */ public class CheckTestNgJdk14IT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { - public CheckTestNgJdk14IT() - { - unpack( "/testng-jdk14" ); - } - - public void testTestNgJdk14() + @Test + public void TestNgJdk14() throws Exception { unpack( "/testng-jdk14" ).executeTest().verifyErrorFree( 1 ); diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/CheckTestNgListenerReporterIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/CheckTestNgListenerReporterIT.java index d7a20fc442..af469065ab 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/CheckTestNgListenerReporterIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/CheckTestNgListenerReporterIT.java @@ -19,8 +19,9 @@ * under the License. */ -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; import org.apache.maven.surefire.its.fixture.SurefireLauncher; +import org.junit.Test; /** * Test simple TestNG listener and reporter @@ -29,9 +30,10 @@ * @author Kristian Rosenvold */ public class CheckTestNgListenerReporterIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { - public void testTestNgListenerReporter() + @Test + public void TestNgListenerReporter() { final SurefireLauncher verifierStarter = unpack( "testng-listener-reporter" ); verifierStarter.executeTest().verifyErrorFree( 1 ).getTargetFile( diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/CheckTestNgPathWithSpacesIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/CheckTestNgPathWithSpacesIT.java index fcb879891c..bf713d35c9 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/CheckTestNgPathWithSpacesIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/CheckTestNgPathWithSpacesIT.java @@ -19,7 +19,8 @@ * under the License. */ -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; +import org.junit.Test; /** * Test TestNG test in a directory with spaces @@ -27,9 +28,10 @@ * @author Dan Fabulich */ public class CheckTestNgPathWithSpacesIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { - public void testTestNgTestWithSpaces() + @Test + public void TestWithSpaces() { unpack( "testng-path with spaces" ).executeTest().verifyErrorFree( 1 ); } diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/CheckTestNgReportTestIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/CheckTestNgReportTestIT.java index 83e580a7b1..6453003d77 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/CheckTestNgReportTestIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/CheckTestNgReportTestIT.java @@ -20,7 +20,8 @@ */ import org.apache.maven.surefire.its.fixture.OutputValidator; -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; +import org.junit.Test; /** * Test surefire-report on TestNG test @@ -28,9 +29,10 @@ * @author Dan Fabulich */ public class CheckTestNgReportTestIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { - public void testTestNgReport() + @Test + public void testNgReport() throws Exception { final OutputValidator outputValidator = diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/CheckTestNgSuiteXmlIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/CheckTestNgSuiteXmlIT.java index 6702b7ee8e..d0d30bccd9 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/CheckTestNgSuiteXmlIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/CheckTestNgSuiteXmlIT.java @@ -19,8 +19,9 @@ * under the License. */ -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; import org.apache.maven.surefire.its.fixture.SurefireLauncher; +import org.junit.Test; /** * Test simple TestNG suite XML file @@ -28,14 +29,16 @@ * @author Dan Fabulich */ public class CheckTestNgSuiteXmlIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { - public void testTestNgSuiteXml() + @Test + public void suiteXml() { unpack().executeTest().verifyErrorFree( 1 ); } - public void testTestNgSuiteXmlForkModeAlways() + @Test + public void suiteXmlForkModeAlways() { unpack().forkAlways().executeTest().verifyErrorFree( 1 ); } diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/CheckTestNgSuiteXmlSingleIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/CheckTestNgSuiteXmlSingleIT.java index 3d600fb007..903c14a0a8 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/CheckTestNgSuiteXmlSingleIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/CheckTestNgSuiteXmlSingleIT.java @@ -19,7 +19,8 @@ * under the License. */ -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; +import org.junit.Test; /** * Use -Dtest to run a single TestNG test, overriding the suite XML parameter. @@ -27,9 +28,10 @@ * @author Dan Fabulich */ public class CheckTestNgSuiteXmlSingleIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { - public void testTestNGSuite() + @Test + public void TestNgSuite() { unpack( "/testng-twoTestCaseSuite" ).setTestToRun( "TestNGTestTwo" ).executeTest().verifyErrorFree( 1 ); } diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/CheckTestNgVersionsIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/CheckTestNgVersionsIT.java index 707e31e49a..025b4550d1 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/CheckTestNgVersionsIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/CheckTestNgVersionsIT.java @@ -20,7 +20,9 @@ */ import org.apache.maven.surefire.its.fixture.OutputValidator; -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; +import org.junit.Ignore; +import org.junit.Test; /** * Basic suite test using all known versions of TestNG. Used for regression testing Surefire against old versions. @@ -31,120 +33,138 @@ * @author Kristian Rosenvold */ public class CheckTestNgVersionsIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { + @Test public void test47() throws Exception { runTestNgTest( "4.7" ); } - // DGF SUREFIRE-375 + MAVENUPLOAD-1024 - // The 5.0 and 5.0.1 jars on central are malformed - + @Test + @Ignore("5.0 and 5.0.1 jars on central are malformed SUREFIRE-375 + MAVENUPLOAD-1024") public void XXXtest50() throws Exception { runTestNgTest( "5.0" ); } + @Test + @Ignore("5.0 and 5.0.1 jars on central are malformed SUREFIRE-375 + MAVENUPLOAD-1024") public void XXXtest501() throws Exception { runTestNgTest( "5.0.1" ); } + @Test public void test502() throws Exception { runTestNgTest( "5.0.2" ); } + @Test public void test51() throws Exception { runTestNgTest( "5.1" ); } + @Test public void test55() throws Exception { runTestNgTest( "5.5" ); } + @Test public void test56() throws Exception { runTestNgTest( "5.6" ); } + @Test public void test57() throws Exception { runTestNgTest( "5.7" ); } + @Test public void test58() throws Exception { runTestNgTest( "5.8" ); } + @Test public void test59() throws Exception { runTestNgTest( "5.9" ); } + @Test public void test510() throws Exception { runTestNgTest( "5.10" ); } + @Test public void test511() throws Exception { runTestNgTest( "5.11" ); } + @Test public void test512() throws Exception { runTestNgTest( "5.12.1" ); } + @Test public void test513() throws Exception { runTestNgTest( "5.13" ); } + @Test public void test5131() throws Exception { runTestNgTest( "5.13.1" ); } + @Test public void test514() throws Exception { runTestNgTest( "5.14" ); } + @Test public void test5141() throws Exception { runTestNgTest( "5.14.1" ); } + @Test public void test5142() throws Exception { runTestNgTest( "5.14.2" ); } + @Test public void test60() throws Exception { diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/ClassPathOrderIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/ClassPathOrderIT.java index ecb53b13e4..dfea90a922 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/ClassPathOrderIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/ClassPathOrderIT.java @@ -19,7 +19,8 @@ * under the License. */ -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; +import org.junit.Test; /** * Test for checking the order of class path elements @@ -28,9 +29,10 @@ * @author Kristian Rosenvold */ public class ClassPathOrderIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { - public void testClassPathOrder() + @Test + public void classPathOrder() { unpack( "/classpath-order" ).executeTest().verifyErrorFree( 2 ); } diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/ClasspathFilteringIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/ClasspathFilteringIT.java index 86817b8130..89aada7b6c 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/ClasspathFilteringIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/ClasspathFilteringIT.java @@ -19,7 +19,8 @@ * under the License. */ -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; +import org.junit.Test; /** * Test additionalClasspathElements @@ -27,9 +28,10 @@ * @author pgier */ public class ClasspathFilteringIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { - public void testAdditionalClasspath() + @Test + public void additionalClasspath() throws Exception { unpack( "classpath-filtering" ).debugLogging().executeTest().verifyErrorFree( 1 ); diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/ClasspathScopeFilteringIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/ClasspathScopeFilteringIT.java index be766ccb26..ca64d874db 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/ClasspathScopeFilteringIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/ClasspathScopeFilteringIT.java @@ -19,7 +19,8 @@ * under the License. */ -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; +import org.junit.Test; /** * Test additionalClasspathElements @@ -28,9 +29,10 @@ * @author Kristian Rosenvold */ public class ClasspathScopeFilteringIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { - public void testAdditionalClasspath() + @Test + public void additionalClasspath() { unpack( "classpath-scope-filtering" ).executeTest().verifyErrorFree( 1 ); } diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/ConsoleOutputIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/ConsoleOutputIT.java index 9b4b0489ff..cfce4814f0 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/ConsoleOutputIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/ConsoleOutputIT.java @@ -20,8 +20,9 @@ */ import org.apache.maven.surefire.its.fixture.OutputValidator; -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; import org.apache.maven.surefire.its.fixture.TestFile; +import org.junit.Test; /** * Basic suite test using all known versions of JUnit 4.x @@ -29,9 +30,10 @@ * @author Kristian Rosenvold */ public class ConsoleOutputIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { - public void testProperNewlines() + @Test + public void properNewlines() { final OutputValidator outputValidator = unpack( "/consoleOutput" ).redirectToFile( true ).setJUnitVersion( "4.7" ).executeTest(); @@ -40,4 +42,12 @@ public void testProperNewlines() surefireReportsFile.assertContainsText( "Printline in shutdown hook" ); } + @Test + public void largerSoutThanMemory() + throws Exception + { + unpack( "consoleoutput-noisy" ).setMavenOpts( "-Xmx64m" ).sysProp( "thousand", "100000" ).executeTest(); + } + + } \ No newline at end of file diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/CrashDetectionIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/CrashDetectionIT.java index 9dc5920a92..90c46306ec 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/CrashDetectionIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/CrashDetectionIT.java @@ -19,16 +19,30 @@ * under the License. */ -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; +import org.junit.Test; /** * @author Kristian Rosenvold */ public class CrashDetectionIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { - public void testArgLine() + @Test + public void crashInFork() { - unpack( "crash-detection" ).executeTestWithFailure(); + unpack( "crash-detection" ).maven().withFailure().executeTest(); + } + + @Test + public void crashInReusableFork() + { + unpack( "crash-detection" ).forkOncePerThread().threadCount( 1 ).maven().withFailure().executeTest(); + } + + @Test + public void hardCrashInReusableFork() + { + unpack( "crash-detection" ).forkOncePerThread().threadCount( 1 ).addGoal( "-DkillHard=true" ).maven().withFailure().executeTest(); } } diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/DefaultConfigurationIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/DefaultConfigurationIT.java index 61e4cfc6f8..b0907b87d8 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/DefaultConfigurationIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/DefaultConfigurationIT.java @@ -19,7 +19,8 @@ * under the License. */ -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; +import org.junit.Test; /** * Test basic default configuration, runs the JUnit 3 test in the src/test directory. @@ -27,9 +28,10 @@ * @author Dan Fabulich */ public class DefaultConfigurationIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { - public void testDefaultConfiguration() + @Test + public void defaultConfiguration() { executeErrorFreeTest( "default-configuration", 1 ); } diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/EnvironmentVariableIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/EnvironmentVariableIT.java index f68f558fe2..7f38a73d71 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/EnvironmentVariableIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/EnvironmentVariableIT.java @@ -19,7 +19,8 @@ * under the License. */ -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; +import org.junit.Test; /** * Test basic default configuration, runs the JUnit 3 test in the src/test directory. @@ -27,10 +28,11 @@ * @author Dan Fabulich */ public class EnvironmentVariableIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { - public void testEnvironmentVariable() + @Test + public void environmentVariable() { executeErrorFreeTest( "junit44-environment", 1 ); diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/ForkConsoleOutputIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/ForkConsoleOutputIT.java index 2fc0fcf347..7ec0039c58 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/ForkConsoleOutputIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/ForkConsoleOutputIT.java @@ -20,8 +20,9 @@ */ import org.apache.maven.surefire.its.fixture.OutputValidator; -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; import org.apache.maven.surefire.its.fixture.SurefireLauncher; +import org.junit.Test; /** * Asserts proper behaviour of console output when forking @@ -31,37 +32,40 @@ * @author Kristian Rosenvold */ public class ForkConsoleOutputIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { - - private SurefireLauncher unpack() - { - return unpack( "/fork-consoleOutput" ); - } - - public void testPrintSummaryTrueWithRedirect() + @Test + public void printSummaryTrueWithRedirect() { final OutputValidator outputValidator = unpack().redirectToFile( true ).printSummary( true ).executeTest(); outputValidator.getSurefireReportsFile( "forkConsoleOutput.Test1-output.txt" ).assertFileExists(); } - public void testPrintSummaryTrueWithoutRedirect() + @Test + public void printSummaryTrueWithoutRedirect() { final OutputValidator outputValidator = unpack().redirectToFile( false ).printSummary( true ).executeTest(); outputValidator.getSurefireReportsFile( "forkConsoleOutput.Test1-output.txt" ).assertFileNotExists(); } - public void testPrintSummaryFalseWithRedirect() + @Test + public void printSummaryFalseWithRedirect() { final OutputValidator outputValidator = unpack().redirectToFile( true ).printSummary( false ).debugLogging().showErrorStackTraces().executeTest(); outputValidator.getSurefireReportsFile( "forkConsoleOutput.Test1-output.txt" ).assertFileExists(); } - public void testPrintSummaryFalseWithoutRedirect() + @Test + public void printSummaryFalseWithoutRedirect() { final OutputValidator outputValidator = unpack().redirectToFile( false ).printSummary( false ).executeTest(); outputValidator.getSurefireReportsFile( "forkConsoleOutput.Test1-output.txt" ).assertFileNotExists(); } + + private SurefireLauncher unpack() + { + return unpack( "/fork-consoleOutput" ); + } } diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/ForkConsoleOutputWithErrorsIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/ForkConsoleOutputWithErrorsIT.java index fa32bee453..af4a6e67eb 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/ForkConsoleOutputWithErrorsIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/ForkConsoleOutputWithErrorsIT.java @@ -20,8 +20,9 @@ */ import org.apache.maven.surefire.its.fixture.OutputValidator; -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; import org.apache.maven.surefire.its.fixture.TestFile; +import org.junit.Test; /** * Asserts proper behaviour of console output when forking @@ -31,14 +32,15 @@ * @author Kristian Rosenvold */ public class ForkConsoleOutputWithErrorsIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { - public void testXmlFileContainsConsoleOutput() + @Test + public void xmlFileContainsConsoleOutput() { final OutputValidator outputValidator = unpack( "/fork-consoleOutputWithErrors" ). failNever().redirectToFile( true ).executeTest(); final TestFile surefireReportsFile = - outputValidator.getSurefireReportsFile( "TEST-forkConsoleOutput.Test2.xml" ); + outputValidator.getSurefireReportsXmlFile( "TEST-forkConsoleOutput.Test2.xml" ); surefireReportsFile.assertContainsText( "sout: Will Fail soon" ); surefireReportsFile.assertContainsText( "serr: Will Fail now" ); } diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/ForkModeIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/ForkModeIT.java index 7001cfdbae..061c5a6026 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/ForkModeIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/ForkModeIT.java @@ -19,56 +19,150 @@ * under the License. */ +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.fail; + import java.util.Arrays; import java.util.HashSet; import java.util.Set; + import org.apache.maven.surefire.its.fixture.OutputValidator; -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +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.BeforeClass; +import org.junit.Test; /** * Test forkMode - * + * * @author Dan Fabulich */ public class ForkModeIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { + + private OutputValidator outputValidator; + + @BeforeClass + public static void installDumpPidPlugin() + throws Exception + { + unpack( ForkModeIT.class, "test-helper-dump-pid-plugin", "plugin" ).executeInstall(); + } + + @Test public void testForkModeAlways() { - String[] pids = doTest( unpack( getProject() ).debugLogging().forkAlways() ); + String[] pids = doTest( unpack( getProject() ).setForkJvm().forkAlways() ); assertDifferentPids( pids ); + assertEndWith( pids, "_1_1", 3 ); + assertFalse( "pid 1 is not the same as the main process' pid", pids[0].equals( getMainPID() ) ); } + @Test public void testForkModePerTest() { - String[] pids = doTest( unpack( getProject() ).debugLogging().forkPerTest() ); + String[] pids = doTest( unpack( getProject() ).setForkJvm().forkPerTest() ); assertDifferentPids( pids ); + assertEndWith( pids, "_1_1", 3 ); + assertFalse( "pid 1 is not the same as the main process' pid", pids[0].equals( getMainPID() ) ); } + @Test public void testForkModeNever() { - String[] pids = doTest( unpack( getProject() ).debugLogging().forkNever() ); + 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 testForkModeNone() { - String[] pids = doTest( unpack( getProject() ).debugLogging().forkMode( "none" ) ); + String[] pids = doTest( unpack( getProject() ).forkMode( "none" ) ); assertSamePids( pids ); + assertEndWith( pids, "_1_1", 3 ); + assertEquals( "my pid is equal to pid 1 of the test", getMainPID(), pids[0] ); } + @Test public void testForkModeOncePerThreadSingleThread() { - String[] pids = doTest( unpack( getProject() ).debugLogging().forkOncePerThread().threadCount( 1 ) ); + String[] pids = doTest( unpack( getProject() ).setForkJvm().forkOncePerThread().threadCount( 1 ) ); assertSamePids( pids ); + assertEndWith( pids, "_1_1", 3 ); + assertFalse( "pid 1 is not the same as the main process' pid", pids[0].equals( getMainPID() ) ); } + @Test public void testForkModeOncePerThreadTwoThreads() { - String[] pids = doTest( unpack( getProject() ).debugLogging().forkOncePerThread().threadCount( 2 ) ); + String[] pids = + doTest( unpack( getProject() ).forkOncePerThread().threadCount( 2 ).addGoal( "-DsleepLength=1200" ) ); assertDifferentPids( pids, 2 ); + assertFalse( "pid 1 is not the same as the main process' pid", pids[0].equals( getMainPID() ) ); + } + + @Test + public void testForkCountZero() + { + String[] pids = doTest( unpack( getProject() ).forkCount( 0 ) ); + assertSamePids( pids ); + assertEndWith( pids, "_1_1", 3 ); + assertEquals( "my pid is equal to pid 1 of the test", getMainPID(), pids[0] ); + } + + @Test + public void testForkCountOneNoReuse() + { + String[] pids = doTest( unpack( getProject() ).setForkJvm().forkCount( 1 ).reuseForks( false ) ); + assertDifferentPids( pids ); + assertEndWith( pids, "_1_1", 3 ); + assertFalse( "pid 1 is not the same as the main process' pid", pids[0].equals( getMainPID() ) ); + } + + @Test + public void testForkCountOneReuse() + { + String[] pids = doTest( unpack( getProject() ).setForkJvm().forkCount( 1 ).reuseForks( true ) ); + assertSamePids( pids ); + assertEndWith( pids, "_1_1", 3 ); + assertFalse( "pid 1 is not the same as the main process' pid", pids[0].equals( getMainPID() ) ); + } + + @Test + public void testForkCountTwoNoReuse() + { + String[] pids = + doTest( unpack( getProject() ).forkCount( 2 ).reuseForks( false ).addGoal( "-DsleepLength=1200" ) ); + assertDifferentPids( pids ); + assertFalse( "pid 1 is not the same as the main process' pid", pids[0].equals( getMainPID() ) ); + } + + @Test + public void testForkCountTwoReuse() + { + String[] pids = + doTest( unpack( getProject() ).forkCount( 2 ).reuseForks( true ).addGoal( "-DsleepLength=1200" ) ); + assertDifferentPids( pids, 2 ); + assertFalse( "pid 1 is not the same as the main process' pid", pids[0].equals( getMainPID() ) ); + } + + private void assertEndWith( String[] pids, String suffix, int expectedMatches ) + { + int matches = 0; + for ( String pid : pids ) + { + if ( pid.endsWith( suffix ) ) + { + matches++; + } + } + + assertEquals( "suffix " + suffix + " matched the correct number of pids", expectedMatches, matches ); } private void assertDifferentPids( String[] pids, int numOfDifferentPids ) @@ -77,14 +171,19 @@ private void assertDifferentPids( String[] pids, int numOfDifferentPids ) assertEquals( "number of different pids is not as expected", numOfDifferentPids, pidSet.size() ); } + @Test public void testForkModeOnce() { String[] pids = doTest( unpack( getProject() ).forkOnce() ); - // DGF It would be nice to assert that "once" was different - // from "never" ... but there's no way to check the PID of - // Maven itself. No matter, "once" is tested by setting - // argLine, which can't be done except by forking. assertSamePids( pids ); + assertFalse( "pid 1 is not the same as the main process' pid", pids[0].equals( getMainPID() ) ); + } + + private String getMainPID() + { + final TestFile targetFile = outputValidator.getTargetFile( "maven.pid" ); + String pid = targetFile.slurpFile(); + return pid + " testValue_1_1"; } private void assertSamePids( String[] pids ) @@ -113,8 +212,9 @@ private void assertDifferentPids( String[] pids ) private String[] doTest( SurefireLauncher forkMode ) { - forkMode.addD( "testProperty", "testValue_${surefire.threadNumber}" ); - final OutputValidator outputValidator = forkMode.executeTest(); + forkMode.sysProp( "testProperty", "testValue_${surefire.threadNumber}_${surefire.forkNumber}" ); + forkMode.addGoal( "org.apache.maven.plugins.surefire:maven-dump-pid-plugin:dump-pid" ); + outputValidator = forkMode.executeTest(); outputValidator.verifyErrorFreeLog().assertTestSuiteResults( 3, 0, 0, 0 ); String[] pids = new String[3]; for ( int i = 1; i <= pids.length; i++ ) diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/ForkModeMultiModuleIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/ForkModeMultiModuleIT.java new file mode 100644 index 0000000000..f4c5dd53ab --- /dev/null +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/ForkModeMultiModuleIT.java @@ -0,0 +1,164 @@ +package org.apache.maven.surefire.its; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR 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.its.fixture.*; +import org.junit.Test; +import org.junit.experimental.categories.Category; + +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; + +/** + * Test forkMode in a multi module project with parallel maven builds + * + * @author Andreas Gudian + */ +@Category( Not2xCompatible.class ) +public class ForkModeMultiModuleIT + 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); + } + + + @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 ); + } + + @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 ); + } + + @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 ); + } + + 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 ); + } + + private int countSuffixMatches( List pids, String suffix ) + { + int matches = 0; + 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 assertAllDifferentPids( List pids ) + { + assertDifferentPids( pids, pids.size() ); + } + + private List doTest( SurefireLauncher forkMode ) + { + forkMode.addGoal( "-T 2" ); + forkMode.sysProp( "testProperty", "testValue_${surefire.threadNumber}_${surefire.forkNumber}" ); + final OutputValidator outputValidator = forkMode.setForkJvm().executeTest(); + 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 ) ); + + 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 ); + } + + return pids; + } + + protected String getProject() + { + return "fork-mode-multimodule"; + } + + +} diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/IncludesExcludesFromFileIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/IncludesExcludesFromFileIT.java index 42fd8335b3..58d270a243 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/IncludesExcludesFromFileIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/IncludesExcludesFromFileIT.java @@ -20,8 +20,9 @@ */ import org.apache.maven.surefire.its.fixture.OutputValidator; -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; import org.apache.maven.surefire.its.fixture.SurefireLauncher; +import org.junit.Test; /** * Test include/exclude from files. @@ -29,56 +30,62 @@ * Based on {@link IncludesExcludesIT}. */ public class IncludesExcludesFromFileIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { private SurefireLauncher unpack() { return unpack( "/includes-excludes-from-file" ); } + @Test public void testSimple() { - testWithProfile( "-Psimple" ); + testWithProfile( "simple" ); } + @Test public void testSimpleMixed() { - testWithProfile( "-Psimple-mixed" ); + testWithProfile( "simple-mixed" ); } + @Test public void testRegex() { - testWithProfile( "-Pregex" ); + testWithProfile( "regex" ); } + @Test public void testPath() { - testWithProfile( "-Ppath" ); + testWithProfile( "path" ); } - private void testWithProfile( String profile ) + @Test + public void testMissingExcludes() { - final OutputValidator outputValidator = unpack(). - addGoal( profile ).executeTest().verifyErrorFree( 2 ); - - outputValidator.getTargetFile( "testTouchFile.txt" ).assertFileExists(); - outputValidator.getTargetFile( "defaultTestTouchFile.txt" ).assertFileExists(); + expectBuildFailure("missing-excludes-file", "Failed to load list from file", "no-such-excludes-file"); } - public void testMissingExcludes() + @Test + public void testMissingIncludes() { - expectBuildFailure( "-Pmissing-excludes-file", "Failed to load list from file", "no-such-excludes-file" ); + expectBuildFailure( "missing-includes-file", "Failed to load list from file", "no-such-includes-file" ); } - public void testMissingIncludes() + private void testWithProfile( String profile ) { - expectBuildFailure( "-Pmissing-includes-file", "Failed to load list from file", "no-such-includes-file" ); + final OutputValidator outputValidator = unpack(). + activateProfile( profile ).executeTest().verifyErrorFree( 2 ); + + outputValidator.getTargetFile( "testTouchFile.txt" ).assertFileExists(); + outputValidator.getTargetFile( "defaultTestTouchFile.txt" ).assertFileExists(); } private void expectBuildFailure( final String profile, final String... messages ) { - final OutputValidator outputValidator = unpack(). - addGoal( profile ).executeTestWithFailure(); + final OutputValidator outputValidator = unpack().activateProfile( profile ) + .maven().withFailure().executeTest(); for ( String message : messages ) { diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/IncludesExcludesIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/IncludesExcludesIT.java index d8da28f9dd..46bdeb6916 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/IncludesExcludesIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/IncludesExcludesIT.java @@ -20,8 +20,9 @@ */ import org.apache.maven.surefire.its.fixture.OutputValidator; -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; import org.apache.maven.surefire.its.fixture.SurefireLauncher; +import org.junit.Test; /** * Test include/exclude patterns. @@ -29,7 +30,7 @@ * @author Benjamin Bentmann */ public class IncludesExcludesIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { private SurefireLauncher unpack() { @@ -39,27 +40,29 @@ private SurefireLauncher unpack() /** * Test surefire inclusions/exclusions */ + @Test public void testIncludesExcludes() { - testWithProfile( "-Psimple" ); + testWithProfile( "simple" ); } + @Test public void testRegexIncludesExcludes() { - testWithProfile( "-Pregex" ); + testWithProfile( "regex" ); } + @Test public void testPathBasedIncludesExcludes() { - testWithProfile( "-Ppath" ); + testWithProfile( "path" ); } private void testWithProfile( String profile ) { final OutputValidator outputValidator = unpack(). - addGoal( profile ).executeTest().verifyErrorFree( 2 ); + activateProfile( profile ).executeTest().verifyErrorFree( 2 ); outputValidator.getTargetFile( "testTouchFile.txt" ).assertFileExists(); outputValidator.getTargetFile( "defaultTestTouchFile.txt" ).assertFileExists(); } - } diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/JUnit44HamcrestIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/JUnit44HamcrestIT.java index 80b597d01b..7bf90f038b 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/JUnit44HamcrestIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/JUnit44HamcrestIT.java @@ -19,7 +19,8 @@ * under the License. */ -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; +import org.junit.Test; /** * Test project using JUnit4.4 (including Hamcrest extensions) @@ -27,8 +28,9 @@ * @author Dan Fabulich */ public class JUnit44HamcrestIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { + @Test public void testJUnit44Hamcrest() { executeErrorFreeTest( "junit44-hamcrest", 1 ); diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/JUnit47RedirectOutputIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/JUnit47RedirectOutputIT.java index 651d6596db..aa38dac5af 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/JUnit47RedirectOutputIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/JUnit47RedirectOutputIT.java @@ -19,15 +19,21 @@ * under the License. */ -import java.io.IOException; import org.apache.commons.lang.StringUtils; import org.apache.maven.surefire.its.fixture.OutputValidator; -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; import org.apache.maven.surefire.its.fixture.SurefireLauncher; +import org.junit.Test; + +import java.io.IOException; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; public class JUnit47RedirectOutputIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { + @Test public void testPrintSummaryTrueWithRedirect() throws Exception { @@ -35,11 +41,12 @@ public void testPrintSummaryTrueWithRedirect() checkReports( clean ); } + @Test public void testClassesParallel() throws Exception { final OutputValidator clean = - unpack().redirectToFile( true ).addGoal( "clean" ).parallelClasses().executeTest(); + unpack().redirectToFile( true ).parallelClasses().addGoal( "clean" ).executeTest(); checkReports( clean ); } diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/JUnit48TestCategoriesIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/JUnit48TestCategoriesIT.java index d60aa8c04f..70b614fc11 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/JUnit48TestCategoriesIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/JUnit48TestCategoriesIT.java @@ -19,10 +19,12 @@ * under the License. */ -import java.io.IOException; import org.apache.maven.it.VerificationException; -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; import org.apache.maven.surefire.its.fixture.SurefireLauncher; +import org.junit.Test; + +import java.io.IOException; /** * Test project using "groups" support @@ -31,8 +33,9 @@ * @author Kristian Rosenvold */ public class JUnit48TestCategoriesIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { + @Test public void testCategoriesAB() throws Exception { @@ -40,25 +43,28 @@ public void testCategoriesAB() } + @Test public void testCategoriesABForkAlways() throws Exception { runAB( unpacked() ); } - private void runAB( SurefireLauncher unpacked ) - throws VerificationException - { - unpacked.executeTest().verifyErrorFreeLog().assertTestSuiteResults( 3, 0, 0, 0 ).verifyTextInLog( - "catA: 1" ).verifyTextInLog( "catB: 1" ).verifyTextInLog( "catC: 0" ).verifyTextInLog( "catNone: 0" ); - } - + @Test public void testCategoriesAC() throws Exception { runAC( unpacked() ); } + private void runAB( SurefireLauncher unpacked ) + throws VerificationException + { + unpacked.executeTest().verifyErrorFreeLog().assertTestSuiteResults( 3, 0, 0, 0 ).verifyTextInLog( + "catA: 1" ).verifyTextInLog( "catB: 1" ).verifyTextInLog( "catC: 0" ).verifyTextInLog( "catNone: 0" ); + } + + @Test public void testCategoriesACForkAlways() throws Exception { diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/JUnit4ForkAlwaysStaticInitPollutionIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/JUnit4ForkAlwaysStaticInitPollutionIT.java index 1cfa910e36..19b937d47d 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/JUnit4ForkAlwaysStaticInitPollutionIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/JUnit4ForkAlwaysStaticInitPollutionIT.java @@ -19,7 +19,8 @@ * under the License. */ -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; +import org.junit.Test; /** * Test JUnit 4 tests marked with "Ignore" attribute @@ -27,8 +28,9 @@ * @author Dan Fabulich */ public class JUnit4ForkAlwaysStaticInitPollutionIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { + @Test public void testJunit4Ignore() { executeErrorFreeTest( "junit4-forkAlways-staticInit", 2 ); diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/JUnit4RunListenerIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/JUnit4RunListenerIT.java index c315b3139c..433863e64a 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/JUnit4RunListenerIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/JUnit4RunListenerIT.java @@ -20,8 +20,9 @@ */ import org.apache.maven.surefire.its.fixture.OutputValidator; -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; import org.apache.maven.surefire.its.fixture.SurefireLauncher; +import org.junit.Test; /** * JUnit4 RunListener Integration Test. @@ -29,18 +30,14 @@ * @author Matthew Gilliard */ public class JUnit4RunListenerIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { - public JUnit4RunListenerIT() - { - unpack(); - } - private SurefireLauncher unpack() { return unpack( "/junit4-runlistener" ); } + @Test public void testJUnit4RunListener() throws Exception { @@ -52,6 +49,7 @@ public void testJUnit4RunListener() outputValidator.verifyTextInLog( "testRunFinished org.junit.runner.Result" ); } + @Test public void testRunlistenerJunitCoreProvider() throws Exception { diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/JUnitDepIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/JUnitDepIT.java index 62f4e37a0b..0757a17ec9 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/JUnitDepIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/JUnitDepIT.java @@ -19,8 +19,9 @@ * under the License. */ -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; import org.apache.maven.surefire.its.fixture.SurefireLauncher; +import org.junit.Test; /** * Test project using JUnit4.4 -dep. junit-dep includes only junit.* classes, and depends explicitly on hamcrest-core @@ -28,38 +29,42 @@ * @author Dan Fabulich */ public class JUnitDepIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { public SurefireLauncher unpack() { return unpack( "/junit44-dep" ); } + @Test public void testJUnit44Dep() throws Exception { - unpack().debugLogging().addGoal( "-Djunit-dep.version=4.4" ).executeTest().verifyErrorFree( 1 ).verifyTextInLog( + 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() throws Exception { - unpack().debugLogging().addGoal( "-Djunit-dep.version=4.4" ).activateProfile( + unpack().debugLogging().sysProp( "junit-dep.version", "4.4" ).activateProfile( "provided381" ).executeTest().verifyErrorFree( 1 ); } + @Test public void testJUnit47Dep() throws Exception { - unpack().debugLogging().addGoal( "-Djunit-dep.version=4.7" ).executeTest().verifyErrorFree( 1 ).verifyTextInLog( + unpack().debugLogging().sysProp( "junit-dep.version", "4.7" ).executeTest().verifyErrorFree( 1 ).verifyTextInLog( "surefire-junit47" ); } + @Test public void testJUnit48Dep() throws Exception { - unpack().debugLogging().addGoal( "-Djunit-dep.version=4.8" ).executeTest().verifyErrorFree( 1 ).verifyTextInLog( + unpack().debugLogging().sysProp( "junit-dep.version", "4.8" ).executeTest().verifyErrorFree( 1 ).verifyTextInLog( "surefire-junit47" ); } } diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/Junit47StaticInnerClassTestsIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/Junit47StaticInnerClassTestsIT.java new file mode 100644 index 0000000000..5bdc29f9c6 --- /dev/null +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/Junit47StaticInnerClassTestsIT.java @@ -0,0 +1,13 @@ +package org.apache.maven.surefire.its; + +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; +import org.junit.Test; + +public class Junit47StaticInnerClassTestsIT extends SurefireJUnit4IntegrationTestCase +{ + + @Test + public void testStaticInnerClassTests() { + executeErrorFreeTest( "junit47-static-inner-class-tests", 3 ); + } +} diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/Junit47WithCucumberIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/Junit47WithCucumberIT.java new file mode 100644 index 0000000000..08f6f6c976 --- /dev/null +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/Junit47WithCucumberIT.java @@ -0,0 +1,66 @@ +package org.apache.maven.surefire.its; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR 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.its.fixture.SurefireJUnit4IntegrationTestCase; +import org.junit.Assume; +import org.junit.Before; +import org.junit.Test; + +/** + * Tests the JUnit 47 provider with the cucumber runner. At the moment, they don't play along that perfectly (minor + * 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 + */ +public class Junit47WithCucumberIT + extends SurefireJUnit4IntegrationTestCase +{ + + @Before + public void assumeJdk16() + { + Assume.assumeTrue( System.getProperty( "java.version" ).compareTo( "1.6" ) > 0 ); + } + + @Test + public void testWithoutParallel() + { + // 8 tests in total is what's probably correct + doTest( "none", 8 ); + } + + @Test + public void testWithParallelClasses() + { + // with parallel=classes, we get 9 tests in total, + // as the dummy "scenario" test entry is reported twice: once as success, and once with the failure from the + // failing test step + doTest( "classes", 9 ); + } + + private void doTest( String parallel, int total ) + { + unpack( "junit47-cucumber" ).sysProp( "parallel", parallel ).executeTest().assertTestSuiteResults( total, 0, 2, + 0 ); + } +} diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/Junit47concurrencyIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/Junit47concurrencyIT.java index 33c9526dac..ba3ecf59d5 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/Junit47concurrencyIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/Junit47concurrencyIT.java @@ -19,7 +19,8 @@ * under the License. */ -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; +import org.junit.Test; /** * Basic suite test using all known versions of JUnit 4.x @@ -27,13 +28,14 @@ * @author Kristian Rosenvold */ public class Junit47concurrencyIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { + @Test public void test47() throws Exception { // todo: Align with others - unpack( "concurrentjunit47" ).addD( "junitVersion", "4.7" ).setJUnitVersion( + unpack( "concurrentjunit47" ).sysProp( "junitVersion", "4.7" ).setJUnitVersion( "4.7" ).executeTest().verifyErrorFree( 1 ); } diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/Junit4IgnoreIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/Junit4IgnoreIT.java index 781cdfb793..0e050ce38e 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/Junit4IgnoreIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/Junit4IgnoreIT.java @@ -19,8 +19,9 @@ * under the License. */ -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; import org.apache.maven.surefire.its.fixture.SurefireLauncher; +import org.junit.Test; /** * Test JUnit 4 tests marked with "Ignore" attribute @@ -28,14 +29,16 @@ * @author Dan Fabulich */ public class Junit4IgnoreIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { + @Test public void testJunit4Ignore() { // Todo: Support assumption failure == ignore for junit4 unpack().executeTest().verifyErrorFreeLog().assertTestSuiteResults( 7, 0, 0, 6 ); } + @Test public void testJunit47ParallelIgnore() { unpack().setJUnitVersion( "4.8.1" ).parallelClasses().executeTest().verifyErrorFreeLog().assertTestSuiteResults( diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/Junit4VersionsIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/Junit4VersionsIT.java index eac579ed52..cf82e64335 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/Junit4VersionsIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/Junit4VersionsIT.java @@ -19,8 +19,9 @@ * under the License. */ -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; import org.apache.maven.surefire.its.fixture.SurefireLauncher; +import org.junit.Test; /** * Basic suite test using all known versions of JUnit 4.x @@ -28,67 +29,71 @@ * @author Dan Fabulich */ public class Junit4VersionsIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { - public Junit4VersionsIT() - { - unpack(); - } - private SurefireLauncher unpack() { return unpack( "/junit4" ); } + @Test public void test40() throws Exception { runJUnitTest( "4.0" ); } + @Test public void test41() throws Exception { runJUnitTest( "4.1" ); } + @Test public void test42() throws Exception { runJUnitTest( "4.2" ); } + @Test public void test43() throws Exception { runJUnitTest( "4.3" ); } + @Test public void test431() throws Exception { runJUnitTest( "4.3.1" ); } + @Test public void test44() throws Exception { runJUnitTest( "4.4" ); } + @Test public void test45() throws Exception { runJUnitTest( "4.5" ); } + @Test public void test46() throws Exception { runJUnitTest( "4.6" ); } + @Test public void test47() throws Exception { diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/NoRunnableTestsInClassIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/NoRunnableTestsInClassIT.java index 67457a8fee..1be88b7319 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/NoRunnableTestsInClassIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/NoRunnableTestsInClassIT.java @@ -19,7 +19,8 @@ * under the License. */ -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; +import org.junit.Test; /** * SUREFIRE-621 Asserts proper test counts when running junit 3 tests in parallel @@ -27,8 +28,9 @@ * @author Kristian Rosenvold */ public class NoRunnableTestsInClassIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { + @Test public void testJunit3ParallelBuildResultCount() { unpack( "norunnableTests" ).failNever().executeTest().verifyTextInLog( diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/PlainOldJavaClasspathIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/PlainOldJavaClasspathIT.java index 7bbca3c2c9..71bccd62c8 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/PlainOldJavaClasspathIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/PlainOldJavaClasspathIT.java @@ -19,7 +19,8 @@ * under the License. */ -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; +import org.junit.Test; /** * Test useManifestOnlyJar option @@ -27,8 +28,9 @@ * @author Dan Fabulich */ public class PlainOldJavaClasspathIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { + @Test public void testPlainOldJavaClasspath() { executeErrorFreeTest( "plain-old-java-classpath", 1 ); diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/PlexusConflictIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/PlexusConflictIT.java index 8c099f61f8..bec3e9972b 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/PlexusConflictIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/PlexusConflictIT.java @@ -19,8 +19,9 @@ * under the License. */ -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; import org.apache.maven.surefire.its.fixture.SurefireLauncher; +import org.junit.Test; /** * Test library using a conflicting version of plexus-utils @@ -28,16 +29,18 @@ * @author Dan Fabulich */ public class PlexusConflictIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { + @Test public void testPlexusConflict() { unpack().executeTest().verifyErrorFree( 1 ); } + @Test public void testPlexusConflictIsolatedClassLoader() { - unpack().addD( "surefire.useSystemClassLoader", "false" ).executeTest().verifyErrorFree( 1 ); + unpack().useSystemClassLoader(false).executeTest().verifyErrorFree( 1 ); } private SurefireLauncher unpack() diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/PojoSimpleIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/PojoSimpleIT.java index bda3cf1ebd..03902ef77d 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/PojoSimpleIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/PojoSimpleIT.java @@ -19,7 +19,8 @@ * under the License. */ -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; +import org.junit.Test; /** * Test support for POJO tests. @@ -27,8 +28,9 @@ * @author Benjamin Bentmann */ public class PojoSimpleIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { + @Test public void testit() { unpack( "pojo-simple" ).executeTest().assertTestSuiteResults( 2, 0, 1, 0 ); diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/ReportersIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/ReportersIT.java index b6342c15c2..b1c68f05b9 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/ReportersIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/ReportersIT.java @@ -20,7 +20,8 @@ */ import org.apache.maven.surefire.its.fixture.OutputValidator; -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; +import org.junit.Test; /** * Asserts proper behaviour of console output when forking @@ -29,14 +30,15 @@ * @author Kristian Rosenvold */ public class ReportersIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { + @Test public void testRedirectOutputTestNg() { OutputValidator reporters = unpack( "reporters" ).redirectToFile( true ).printSummary( true ).executeTest(); reporters.getSurefireReportsFile( "TestSuite-output.txt" ).assertFileExists(); - reporters.getSurefireReportsFile( "TEST-TestSuite.xml" ).assertFileExists(); + reporters.getSurefireReportsXmlFile( "TEST-TestSuite.xml" ).assertFileExists(); reporters.getSurefireReportsFile( "TestSuite.txt" ).assertFileExists(); } } diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/ResultCountingIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/ResultCountingIT.java index cf21313f09..714d0c4527 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/ResultCountingIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/ResultCountingIT.java @@ -19,10 +19,12 @@ * under the License. */ -import java.io.IOException; import org.apache.maven.it.VerificationException; import org.apache.maven.surefire.its.fixture.OutputValidator; -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; +import org.junit.Test; + +import java.io.IOException; /** * Verifies that the providers get the result summary at the bottom of the run correctly, in different forkmodes @@ -31,20 +33,23 @@ * @author Kristian Rosenvold */ public class ResultCountingIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { + @Test public void testCountingWithJunit481ForkNever() throws Exception { assertForkMode( "never" ); } + @Test public void testCountingWithJunit481ForkOnce() throws Exception { assertForkMode( "once" ); } + @Test public void testCountingWithJunit481ForkAlways() throws Exception { diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/RunOrderIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/RunOrderIT.java index 31e5e1ba2f..c71e5d654d 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/RunOrderIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/RunOrderIT.java @@ -23,8 +23,9 @@ 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.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; import org.apache.maven.surefire.its.fixture.SurefireLauncher; +import org.junit.Test; /** * Verifies the runOrder setting and its effect @@ -32,7 +33,7 @@ * @author Kristian Rosenvold */ public class RunOrderIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { private static final String[] TESTS_IN_ALPHABETICAL_ORDER = { "TA", "TB", "TC" }; @@ -40,6 +41,7 @@ public class RunOrderIT // testing random is left as an exercise to the reader. Patches welcome + @Test public void testAlphabetical() throws Exception { @@ -47,6 +49,7 @@ public void testAlphabetical() assertTestnamesAppearInSpecificOrder( validator, TESTS_IN_ALPHABETICAL_ORDER ); } + @Test public void testReverseAlphabetical() throws Exception { @@ -54,6 +57,7 @@ public void testReverseAlphabetical() assertTestnamesAppearInSpecificOrder( validator, TESTS_IN_REVERSE_ALPHABETICAL_ORDER ); } + @Test public void testHourly() throws Exception { @@ -70,10 +74,11 @@ public void testHourly() assertTestnamesAppearInSpecificOrder( validator, testnames ); } + @Test public void testNonExistingRunOrder() throws Exception { - unpack().forkMode( getForkMode() ).runOrder( "nonExistingRunOrder" ).executeTestWithFailure().verifyTextInLog( + unpack().forkMode( getForkMode() ).runOrder( "nonExistingRunOrder" ).maven().withFailure().executeTest().verifyTextInLog( "There's no RunOrder with the name nonExistingRunOrder." ); } diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/SiblingAggregatorIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/SiblingAggregatorIT.java index f7bbd9deac..69c9e4c157 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/SiblingAggregatorIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/SiblingAggregatorIT.java @@ -19,8 +19,10 @@ * under the License. */ -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +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; /** * Test aggregator as a sibling to child modules; invokes modules as "../child" @@ -29,14 +31,17 @@ * @author Kristian Rosenvold */ public class SiblingAggregatorIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { + @Test public void testSiblingAggregator() throws Exception { final SurefireLauncher unpack = unpack( "sibling-aggregator" ); - unpack.getSubProjectLauncher( "aggregator" ).executeTest().verifyErrorFreeLog(); - unpack.getSubProjectValidator( "child2" ).assertTestSuiteResults( 1, 0, 0, 0 ); + SurefireLauncher aggregator = unpack.getSubProjectLauncher( "aggregator" ); + aggregator.executeTest().verifyErrorFreeLog(); + OutputValidator child2 = unpack.getSubProjectValidator( "child2" ); + child2.assertTestSuiteResults( 1, 0, 0, 0 ); } } diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/SmartStackTraceIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/SmartStackTraceIT.java new file mode 100644 index 0000000000..b98155e0fb --- /dev/null +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/SmartStackTraceIT.java @@ -0,0 +1,44 @@ +package org.apache.maven.surefire.its; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR 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.its.fixture.OutputValidator; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; +import org.junit.Test; + +/** + * IT of smart stack trace parser + * + * @author Kristian Rosenvold + */ +public class SmartStackTraceIT + extends SurefireJUnit4IntegrationTestCase +{ + + @Test + public void misg() + throws Exception + { + 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" ); + + } +} diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/SystemPropertiesTestIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/SystemPropertiesTestIT.java index 652a4475b8..121b8fcac6 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/SystemPropertiesTestIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/SystemPropertiesTestIT.java @@ -19,8 +19,9 @@ * under the License. */ -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; import org.apache.maven.surefire.its.fixture.SurefireLauncher; +import org.junit.Test; /** * Test system properties @@ -28,15 +29,17 @@ * @author Dan Fabulich */ public class SystemPropertiesTestIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { + @Test public void testSystemProperties() { unpack().addGoal( "-DsetOnMavenCommandLine=baz" ).addGoal( "-DsetOnArgLineWorkAround=baz" ).executeTest().verifyErrorFree( 8 ); } + @Test public void testSystemPropertiesNoFork() { diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/TestMethodPatternIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/TestMethodPatternIT.java index e175f9239d..8438dd22fe 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/TestMethodPatternIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/TestMethodPatternIT.java @@ -19,7 +19,8 @@ * under the License. */ -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; +import org.junit.Test; /** * Test project using -Dtest=mtClass#myMethod @@ -27,33 +28,44 @@ * @author Olivier Lamy */ public class TestMethodPatternIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { public void runMethodPattern( String projectName ) { unpack( projectName ).executeTest().assertTestSuiteResults( 2, 0, 0, 0 ); } + @Test public void testJUnit44() { runMethodPattern( "junit44-method-pattern" ); } + @Test public void testJUnit48() { runMethodPattern( "junit48-method-pattern" ); } + @Test + public void testJUnit48WithCategoryFilter() + { + unpack( "junit48-method-pattern" ).addGoal( "-Dgroups=junit4.SampleCategory" ).executeTest().assertTestSuiteResults( 1, 0, 0, 0 );; + } + + @Test public void testTestNgMethodBefore() { runMethodPattern( "testng-method-pattern-before" ); } + @Test public void testTestNGMethodPattern() { runMethodPattern( "/testng-method-pattern" ); } + @Test public void testMethodPatternAfter() { unpack( "testng-method-pattern-after" ).executeTest().verifyErrorFree( 2 ).verifyTextInLog( "Called tearDown" ); diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/TestMultipleMethodsIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/TestMultipleMethodsIT.java index 6805603458..1544fe057e 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/TestMultipleMethodsIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/TestMultipleMethodsIT.java @@ -1,6 +1,7 @@ package org.apache.maven.surefire.its; -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; +import org.junit.Test; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -27,7 +28,7 @@ * @author rainLee */ public class TestMultipleMethodsIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { public void multipleMethod( String projectName ) throws Exception @@ -35,12 +36,14 @@ public void multipleMethod( String projectName ) unpack( projectName ).executeTest().verifyErrorFreeLog().assertTestSuiteResults( 3, 0, 0, 0 ); } + @Test public void testJunit44() throws Exception { multipleMethod( "junit44-multiple-methods" ); } + @Test public void testJunit48() throws Exception { diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/TestNgParallelWithAnnotationsIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/TestNgParallelWithAnnotationsIT.java index 7096721855..1e6044e283 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/TestNgParallelWithAnnotationsIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/TestNgParallelWithAnnotationsIT.java @@ -19,7 +19,8 @@ * under the License. */ -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; +import org.junit.Test; /** * Test that TestNG's @Test(threadPoolSize = n, invocationCount=n) causes tests to be run in parallel. @@ -27,8 +28,9 @@ * @author Haikal Saadh */ public class TestNgParallelWithAnnotationsIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { + @Test public void testTestNgGroupThreadParallel() { executeErrorFreeTest( "/testng-parallel-with-annotations", 3 ); diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/TestSingleMethodIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/TestSingleMethodIT.java index 9d523144c7..d96f4804e5 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/TestSingleMethodIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/TestSingleMethodIT.java @@ -19,7 +19,8 @@ * under the License. */ -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; +import org.junit.Test; /** * Test project using -Dtest=mtClass#myMethod @@ -27,7 +28,7 @@ * @author Olivier Lamy */ public class TestSingleMethodIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { public void singleMethod( String projectName ) throws Exception @@ -35,18 +36,21 @@ public void singleMethod( String projectName ) unpack( projectName ).executeTest().verifyErrorFreeLog().assertTestSuiteResults( 1, 0, 0, 0 ); } + @Test public void testJunit44() throws Exception { singleMethod( "junit44-single-method" ); } + @Test public void testJunit48() throws Exception { singleMethod( "junit48-single-method" ); } + @Test public void testJunit48parallel() throws Exception { @@ -54,12 +58,14 @@ public void testJunit48parallel() 1, 0, 0, 0 ); } + @Test public void testTestNg() throws Exception { singleMethod( "testng-single-method" ); } + @Test public void testTestNg5149() throws Exception { diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/TimeoutForkedTestIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/TimeoutForkedTestIT.java index 339ea5b0f1..fdcea20d00 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/TimeoutForkedTestIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/TimeoutForkedTestIT.java @@ -19,7 +19,8 @@ * under the License. */ -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; +import org.junit.Test; /** * Test @@ -27,13 +28,14 @@ * @author Dan Fabulich */ public class TimeoutForkedTestIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { + @Test public void testTimeoutForked() throws Exception { unpack( "/timeout-forked" ).addGoal( "-DsleepLength=10000" ).addGoal( - "-DforkTimeout=1" ).executeTestWithFailure(); + "-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-integration-tests/src/test/java/org/apache/maven/surefire/its/TwoTestCasesIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/TwoTestCasesIT.java index 38368fc0cd..758c506378 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/TwoTestCasesIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/TwoTestCasesIT.java @@ -23,11 +23,12 @@ 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.IntegrationTestSuiteResults; -import org.apache.maven.surefire.its.fixture.OutputValidator; -import org.apache.maven.surefire.its.fixture.ReportTestSuite; -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.plugins.surefire.report.ReportTestSuite; +import org.apache.maven.surefire.its.fixture.*; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; /** * Test running two test cases; confirms reporting works correctly @@ -35,8 +36,9 @@ * @author Dan Fabulich */ public class TwoTestCasesIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { + @Test public void testTwoTestCases() throws Exception { @@ -46,6 +48,7 @@ public void testTwoTestCases() /** * Runs two tests encapsulated in a suite */ + @Test public void testTwoTestCaseSuite() throws Exception { @@ -79,6 +82,7 @@ private Set extractClassNames( List reports ) return classNames; } + @Test public void testJunit4Suite() throws Exception { @@ -95,6 +99,7 @@ public void testJunit4Suite() HelperAssertions.assertTestSuiteResults( 2, 0, 0, 0, results ); } + @Test public void testTestNGSuite() throws Exception { diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/UmlautDirIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/UmlautDirIT.java index f7ccdf7e5a..8848dc2e01 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/UmlautDirIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/UmlautDirIT.java @@ -19,13 +19,14 @@ * under the License. */ -import java.io.File; -import java.io.IOException; import org.apache.maven.it.VerificationException; -import org.apache.maven.it.Verifier; -import org.apache.maven.shared.utils.io.FileUtils; -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.MavenLauncher; +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; /** * Test a directory with an umlaut @@ -33,14 +34,16 @@ * @author Dan Fabulich */ public class UmlautDirIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { + @Test public void testUmlaut() throws Exception { specialUnpack().executeTest().verifyErrorFreeLog().assertTestSuiteResults( 1, 0, 0, 0 ); } + @Test public void testUmlautIsolatedClassLoader() throws Exception { @@ -50,11 +53,12 @@ public void testUmlautIsolatedClassLoader() SurefireLauncher specialUnpack() throws VerificationException, IOException { - final File unpackLocation = unpack( "junit-pathWithUmlaut" ).getUnpackLocation(); - File dest = new File( unpackLocation.getParentFile().getPath(), "/junit-pathWith\u00DCmlaut" ); - FileUtils.deleteDirectory( dest ); - unpackLocation.renameTo( dest ); - return new SurefireLauncher( new Verifier( dest.getAbsolutePath() ) ); + SurefireLauncher unpack = unpack( "junit-pathWithUmlaut" ); + MavenLauncher maven = unpack.maven(); + + File dest = new File( maven.getUnpackedAt().getParentFile().getPath(), "/junit-pathWith\u00DCmlaut" ); + maven.moveUnpackTo( dest ); + return unpack; } } diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/UnicodeTestNamesIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/UnicodeTestNamesIT.java index 8868699f7f..a99c142372 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/UnicodeTestNamesIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/UnicodeTestNamesIT.java @@ -41,15 +41,15 @@ public class UnicodeTestNamesIT public void checkFileNamesWithUnicode() { SurefireLauncher unpacked = unpack( "unicode-testnames" ); - File xxyz = new File( unpacked.getUnpackLocation(), "src/test/java/junit/twoTestCases/XXYZTest.java" ); + File xxyz = new File( unpacked.getUnpackedAt(), "src/test/java/junit/twoTestCases/XXYZTest.java" ); - File dest = new File( unpacked.getUnpackLocation(), + File dest = new File( unpacked.getUnpackedAt(), "src/test/java/junit/twoTestCases/\u800C\u7D22\u5176\u60C5Test.java" ); Assume.assumeTrue( xxyz.renameTo( dest ) ); Assume.assumeTrue( dest.exists() ); Assume.assumeTrue( - !new File( unpacked.getUnpackLocation(), "src/test/java/junit/twoTestCases/????Test.java" ).exists() ); + !new File( unpacked.getUnpackedAt(), "src/test/java/junit/twoTestCases/????Test.java" ).exists() ); OutputValidator outputValidator = unpacked.executeTest().assertTestSuiteResults( 2, 0, 0, 0 ); TestFile surefireReportsFile = outputValidator.getSurefireReportsFile( "junit.twoTestCases.而索其情Test.txt" ); diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/UseIsolatedClassLoaderIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/UseIsolatedClassLoaderIT.java index e2fcb65c42..b87f6039bb 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/UseIsolatedClassLoaderIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/UseIsolatedClassLoaderIT.java @@ -19,7 +19,8 @@ * under the License. */ -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; +import org.junit.Test; /** * Test useSystemClassLoader option @@ -27,8 +28,9 @@ * @author Dan Fabulich */ public class UseIsolatedClassLoaderIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { + @Test public void testUseSystemClassLoader() { executeErrorFreeTest( "/isolated-classloader", 1 ); diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/WorkingDirectoryIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/WorkingDirectoryIT.java index cba2069796..66fa3dfdd9 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/WorkingDirectoryIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/WorkingDirectoryIT.java @@ -24,10 +24,12 @@ 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.SurefireIntegrationTestCase; -import org.apache.maven.surefire.its.fixture.SurefireLauncher; -import org.apache.maven.surefire.its.fixture.TestFile; +import org.apache.maven.surefire.its.fixture.*; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; /** * Test working directory configuration, SUREFIRE-416 @@ -36,9 +38,10 @@ * @author Kristian Rosenvold */ public class WorkingDirectoryIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { + @Test public void testWorkingDirectory() throws Exception { @@ -49,6 +52,7 @@ public void testWorkingDirectory() verifyOutputDirectory( child ); } + @Test public void testWorkingDirectoryNoFork() throws Exception { @@ -59,6 +63,7 @@ public void testWorkingDirectoryNoFork() verifyOutputDirectory( child ); } + @Test public void testWorkingDirectoryChildOnly() throws Exception { @@ -69,6 +74,7 @@ public void testWorkingDirectoryChildOnly() verifyOutputDirectory( outputValidator ); } + @Test public void testWorkingDirectoryChildOnlyNoFork() throws Exception { diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/WorkingDirectoryIsInvalidPropertyIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/WorkingDirectoryIsInvalidPropertyIT.java index 022aef94e6..1415b6ef9e 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/WorkingDirectoryIsInvalidPropertyIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/WorkingDirectoryIsInvalidPropertyIT.java @@ -18,7 +18,8 @@ * under the License. */ -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; +import org.junit.Test; /** * Test when the configured working directory is an invalid property, SUREFIRE-715 @@ -26,12 +27,13 @@ * @author Kristian Rosenvold */ public class WorkingDirectoryIsInvalidPropertyIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { + @Test public void testWorkingDirectory() throws Exception { - unpack( "working-directory-is-invalid-property" ).executeTestWithFailure().verifyTextInLog( + unpack( "working-directory-is-invalid-property" ).maven().withFailure().executeTest().verifyTextInLog( "workingDirectory cannot be null" ); } } \ No newline at end of file diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/WorkingDirectoryMissingIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/WorkingDirectoryMissingIT.java index 7ddb8ccc42..5247160969 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/WorkingDirectoryMissingIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/WorkingDirectoryMissingIT.java @@ -19,7 +19,8 @@ * under the License. */ -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; +import org.junit.Test; /** * Test when the configured working directory does not exist, SUREFIRE-607 @@ -27,11 +28,11 @@ * @author Stephen Connolly */ public class WorkingDirectoryMissingIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { + @Test public void testWorkingDirectory() { - unpack( "working-directory-missing" ).executeTest().verifyErrorFreeLog(); } diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/XmlReporterRunTimeIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/XmlReporterRunTimeIT.java index b5d5b7e796..56cfc4373e 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/XmlReporterRunTimeIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/XmlReporterRunTimeIT.java @@ -19,12 +19,16 @@ * under the License. */ -import java.io.File; -import java.util.List; +import org.apache.maven.plugins.surefire.report.ReportTestSuite; import org.apache.maven.surefire.its.fixture.HelperAssertions; import org.apache.maven.surefire.its.fixture.OutputValidator; -import org.apache.maven.surefire.its.fixture.ReportTestSuite; -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; +import org.junit.Test; + +import java.io.File; +import java.util.List; + +import static org.junit.Assert.assertTrue; /** * Test reported runtime @@ -32,8 +36,9 @@ * @author Kristian Rosenvold */ public class XmlReporterRunTimeIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { + @Test public void testForkModeAlways() throws Exception { @@ -59,5 +64,4 @@ else if ( "runorder.parallel.Test2".equals( report.getFullClassName() ) ) } } - } diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/fixture/FailsafeOutputValidator.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/fixture/FailsafeOutputValidator.java index 26bfbf2c13..fcfcc9f614 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/fixture/FailsafeOutputValidator.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/fixture/FailsafeOutputValidator.java @@ -20,14 +20,13 @@ */ import org.apache.maven.it.VerificationException; -import org.apache.maven.it.Verifier; public class FailsafeOutputValidator extends OutputValidator { - public FailsafeOutputValidator( Verifier verifier ) + public FailsafeOutputValidator( OutputValidator source ) { - super( verifier ); + super( source.verifier ); } public OutputValidator verifyErrorFree( int total ) diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/fixture/HelperAssertions.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/fixture/HelperAssertions.java index 22de7584ac..7c8740a5f6 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/fixture/HelperAssertions.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/fixture/HelperAssertions.java @@ -21,6 +21,10 @@ import java.io.File; import java.util.ArrayList; import java.util.List; +import java.util.Locale; + +import org.apache.maven.plugins.surefire.report.ReportTestSuite; +import org.apache.maven.plugins.surefire.report.SurefireReportParser; import junit.framework.Assert; @@ -55,11 +59,6 @@ public static void assertTestSuiteResults( int total, int errors, int failures, Assert.assertEquals( "wrong number of skipped", skipped, actualSuite.getSkipped() ); } - public static IntegrationTestSuiteResults parseTestResults( File testDir ) - { - return parseTestResults( new File[]{ testDir } ); - } - public static IntegrationTestSuiteResults parseTestResults( File[] testDirs ) { List reports = extractReports( testDirs ); @@ -98,7 +97,7 @@ public static List extractReports( File[] testDirs ) Assert.assertTrue( "Reports directory is missing: " + reportsDir.getAbsolutePath(), reportsDir.exists() ); reportsDirs.add( reportsDir ); } - SurefireReportParser parser = new SurefireReportParser( reportsDirs ); + SurefireReportParser parser = new SurefireReportParser( reportsDirs, Locale.getDefault() ); List reports; try { @@ -120,7 +119,7 @@ public static List extractITReports( File[] testDirs ) Assert.assertTrue( "Reports directory is missing: " + reportsDir.getAbsolutePath(), reportsDir.exists() ); reportsDirs.add( reportsDir ); } - SurefireReportParser parser = new SurefireReportParser( reportsDirs ); + SurefireReportParser parser = new SurefireReportParser( reportsDirs, Locale.getDefault() ); List reports; try { diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/fixture/MavenLauncher.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/fixture/MavenLauncher.java new file mode 100644 index 0000000000..e0befccafa --- /dev/null +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/fixture/MavenLauncher.java @@ -0,0 +1,446 @@ +package org.apache.maven.surefire.its.fixture; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES 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.IOException; +import java.net.URL; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.apache.commons.lang.text.StrSubstitutor; +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; + +/** + * Encapsulate all needed features to start a maven run + *

+ * + * @author Kristian Rosenvold + */ +public class MavenLauncher +{ + private final List cliOptions = new ArrayList(); + + private final List goals = new ArrayList(); + + private final Map envvars = new HashMap(); + + private File unpackedAt; + + private Verifier verifier; + + private OutputValidator validator; + + private final Class testCaseBeingRun; + + private final String resourceName; + + private final String suffix; + + private boolean expectFailure; + + public MavenLauncher( Class testClass, String resourceName, String suffix ) + { + this.testCaseBeingRun = testClass; + this.resourceName = resourceName; + this.suffix = suffix != null ? suffix : ""; + resetGoals(); + resetCliOptions(); + } + + public File getUnpackedAt() + { + return ensureUnpacked(); + } + + private File ensureUnpacked() + { + if ( unpackedAt == null ) + { + unpackedAt = simpleExtractResources( testCaseBeingRun, resourceName ); + } + return unpackedAt; + } + + public void moveUnpackTo( File dest ) + throws IOException + { + FileUtils.deleteDirectory( dest ); + //noinspection ResultOfMethodCallIgnored + getUnpackedAt().renameTo( dest ); + unpackedAt = dest; + } + + public void resetGoals() + { + goals.clear(); + } + + void addCliOption( String cliOption ) + { + cliOptions.add( cliOption ); + } + + + + private StackTraceElement findTopElemenent( StackTraceElement[] stackTrace, Class testClassToLookFor ) + { + StackTraceElement bestmatch = null; + for ( StackTraceElement stackTraceElement : stackTrace ) + { + if ( stackTraceElement.getClassName().equals( testClassToLookFor.getName() ) ) + { + bestmatch = stackTraceElement; + } + } + return bestmatch; + } + + StackTraceElement[] getStackTraceElements() + { + try + { + throw new RuntimeException(); + } + catch ( RuntimeException e ) + { + return e.getStackTrace(); + } + } + + public void reset() + { + resetGoals(); + resetCliOptions(); + } + + private void resetCliOptions() + { + cliOptions.clear(); + } + + public MavenLauncher getSubProjectLauncher( String subProject ) + throws VerificationException + { + MavenLauncher mavenLauncher = + new MavenLauncher( testCaseBeingRun, resourceName + File.separator + subProject, suffix ); + mavenLauncher.unpackedAt = new File( ensureUnpacked(), subProject ); + return mavenLauncher; + } + + public OutputValidator getSubProjectValidator( String subProject ) + throws VerificationException + { + final File subFile = getValidator().getSubFile( subProject ); + return new OutputValidator( new Verifier( subFile.getAbsolutePath() ) ); + } + + + public MavenLauncher addEnvVar( String key, String value ) + { + envvars.put( key, value ); + return this; + } + + public MavenLauncher assertNotPresent( String subFile ) + { + getVerifier().assertFileNotPresent( getValidator().getSubFile( subFile ).getAbsolutePath() ); + return this; + } + + public MavenLauncher showErrorStackTraces() + { + addCliOption( "-e" ); + return this; + } + + public MavenLauncher debugLogging() + { + addCliOption( "-X" ); + return this; + } + + public MavenLauncher failNever() + { + addCliOption( "-fn" ); + return this; + } + + public MavenLauncher offline() + { + addCliOption( "-o" ); + return this; + } + + public MavenLauncher skipClean() + { + goals.add( "-Dclean.skip=true" ); + return this; + } + + public MavenLauncher addGoal( String goal ) + { + goals.add( goal ); + return this; + } + + public FailsafeOutputValidator executeVerify() + { + return new FailsafeOutputValidator( conditionalExec( "verify" ) ); + } + + public OutputValidator executeTest() + { + return conditionalExec( "test" ); + } + + private OutputValidator conditionalExec(String goal) + { + OutputValidator verify; + try + { + verify = execute( goal ); + } + catch ( SurefireVerifierException exc ) + { + if ( expectFailure ) + { + return getValidator(); + } + else + { + throw exc; + } + } + if ( expectFailure ) + { + throw new RuntimeException( "Expecting build failure, got none!" ); + } + return verify; + + } + + public MavenLauncher withFailure() + { + this.expectFailure = true; + return this; + } + + + public OutputValidator execute( String goal ) + { + addGoal( goal ); + return executeCurrentGoals(); + } + + public OutputValidator executeCurrentGoals() + { + + String userLocalRepo = System.getProperty( "user.localRepository" ); + String testBuildDirectory = System.getProperty( "testBuildDirectory" ); + boolean useInterpolatedSettings = Boolean.getBoolean( "useInterpolatedSettings" ); + + try + { + if ( useInterpolatedSettings ) + { + File interpolatedSettings = new File( testBuildDirectory, "interpolated-settings" ); + + if ( !interpolatedSettings.exists() ) + { + // hack "a la" invoker plugin to download dependencies from local repo + // and not download from central + + Map values = new HashMap( 1 ); + values.put( "localRepositoryUrl", toUrl( userLocalRepo ) ); + StrSubstitutor strSubstitutor = new StrSubstitutor( values ); + + String fileContent = FileUtils.fileRead( new File( testBuildDirectory, "settings.xml" ) ); + + String filtered = strSubstitutor.replace( fileContent ); + + FileUtils.fileWrite( interpolatedSettings.getAbsolutePath(), filtered ); + + } + + addCliOption( "-s " + interpolatedSettings.getCanonicalPath() ); + } + getVerifier().setCliOptions( cliOptions ); + + getVerifier().executeGoals( goals, envvars ); + return getValidator(); + } + catch ( IOException e ) + { + throw new SurefireVerifierException( e.getMessage(), e ); + } + catch ( VerificationException e ) + { + throw new SurefireVerifierException( e.getMessage(), e ); + } + finally + { + getVerifier().resetStreams(); + } + } + + private static String toUrl( String filename ) + { + /* + * NOTE: Maven fails to properly handle percent-encoded "file:" URLs (WAGON-111) so don't use File.toURI() here + * as-is but use the decoded path component in the URL. + */ + String url = "file://" + new File( filename ).toURI().getPath(); + if ( url.endsWith( "/" ) ) + { + url = url.substring( 0, url.length() - 1 ); + } + return url; + } + + public MavenLauncher activateProfile( String profile ) + { + return addGoal( "-P" + profile ); + } + + public MavenLauncher sysProp( String variable, String value ) + { + return addGoal( "-D" + variable + "=" + value ); + } + + public MavenLauncher sysProp( String variable, boolean value ) + { + return addGoal( "-D" + variable + "=" + value ); + } + + public MavenLauncher sysProp( String variable, int value ) + { + return addGoal( "-D" + variable + "=" + value ); + } + + public MavenLauncher showExceptionMessages() + { + addCliOption( "-e" ); + return this; + } + + public MavenLauncher deleteSiteDir() + { + try + { + FileUtils.deleteDirectory( getValidator().getSubFile( "site" ) ); + } + catch ( IOException e ) + { + throw new SurefireVerifierException( e ); + } + return this; + } + + public OutputValidator getValidator() + { + if ( validator == null ) + { + this.validator = new OutputValidator( getVerifier() ); + } + return validator; + } + + public void setForkJvm( boolean forkJvm ) { + getVerifier().setForkJvm( forkJvm ); + } + + private Verifier getVerifier() + { + if ( verifier == null ) + { + try + { + this.verifier = new Verifier( ensureUnpacked().getAbsolutePath() ); + } + catch ( VerificationException e ) + { + throw new RuntimeException( e ); + } + } + return verifier; + } + + 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 ); + } + + FileUtils.deleteDirectory( testDir ); + File file = ResourceExtractor.extractResourceToDestination( cl, resourcePath, tempDir, true ); + return file.getCanonicalFile(); + } + catch ( IOException e ) + { + throw new RuntimeException( e ); + } + + } + + 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 ) ); + } + + 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 ) + { + // Look in superclass... + topInTestClass = findTopElemenent( stackTrace, testCaseBeingRun.getSuperclass() ); + } + if ( topInTestClass != null ) + { + return topInTestClass.getMethodName(); + } + throw new IllegalStateException( "Cannot find " + testCaseBeingRun.getName() + "in stacktrace" ); + } +} diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/fixture/OutputValidator.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/fixture/OutputValidator.java index 7208ae3093..2671879fbb 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/fixture/OutputValidator.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/fixture/OutputValidator.java @@ -20,7 +20,11 @@ */ import java.io.File; +import java.io.IOException; +import java.nio.charset.Charset; import java.util.List; + +import org.apache.commons.io.FileUtils; import org.apache.maven.it.VerificationException; import org.apache.maven.it.Verifier; @@ -83,35 +87,21 @@ public OutputValidator verifyErrorFree( int total ) } } - public OutputValidator verifyErrorFreeIntegrationTests( int total ) - { - try - { - verifier.verifyErrorFreeLog(); - this.assertIntegrationTestSuiteResults( total, 0, 0, 0 ); - return this; - } - catch ( VerificationException e ) - { - throw new SurefireVerifierException( e ); - } - } - - public List loadFile( File file, boolean hasCommand ) + public List loadFile( File file, Charset charset ) { //noinspection unchecked try { - //noinspection unchecked - return verifier.loadFile( file, hasCommand ); + return FileUtils.readLines( file, charset.name() ); } - catch ( VerificationException e ) + catch ( IOException e ) { throw new SurefireVerifierException( e ); } } + public String getBasedir() { return verifier.getBasedir(); @@ -129,12 +119,6 @@ public File getSubFile( String path ) } - public String getArtifactPath( String org, String name, String version, String ext ) - { - return verifier.getArtifactPath( org, name, version, ext ); - } - - public OutputValidator assertTestSuiteResults( int total, int errors, int failures, int skipped ) { HelperAssertions.assertTestSuiteResults( total, errors, failures, skipped, baseDir ); @@ -147,6 +131,12 @@ public OutputValidator assertIntegrationTestSuiteResults( int total, int errors, 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 fileName ) { File targetDir = getSubFile( "target" ); @@ -160,6 +150,12 @@ public TestFile getSurefireReportsFile( String fileName ) return new TestFile( new File( targetDir, fileName ), this ); } + public TestFile getSurefireReportsXmlFile( String fileName ) + { + File targetDir = getSubFile( "target/surefire-reports" ); + return new TestFile( new File( targetDir, fileName ), Charset.forName("UTF-8"), this ); + } + public TestFile getSiteFile( String fileName ) { File targetDir = getSubFile( "target/site" ); @@ -196,9 +192,4 @@ public boolean stringsAppearInSpecificOrderInLog( String[] strings ) } return false; } - - Verifier getVerifier() - { - return verifier; - } } diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/fixture/SurefireIntegrationTestCase.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/fixture/SurefireIntegrationTestCase.java deleted file mode 100644 index e6a0deeb83..0000000000 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/fixture/SurefireIntegrationTestCase.java +++ /dev/null @@ -1,76 +0,0 @@ -package org.apache.maven.surefire.its.fixture; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES 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.apache.maven.it.VerificationException; - -import junit.framework.TestCase; - -/** - * Contains commonly used features for most tests, encapsulating - * common use cases. - *

- * Also includes thread-safe access to the extracted resource - * files, which AbstractSurefireIntegrationTestClass does not. - * Thread safe only for running in "classes" mode. - * - * @author Kristian Rosenvold - */ -public abstract class SurefireIntegrationTestCase - extends TestCase -{ - public OutputValidator executeErrorFreeTest( String sourceName, int total ) - { - return unpack( sourceName ).executeTest().verifyErrorFree( total ); - } - - public SurefireLauncher unpack( String sourceName ) - { - try - { - return new SurefireLauncher( this.getClass(), sourceName, "" ); - } - catch ( VerificationException e ) - { - throw new SurefireVerifierException( e ); - } - catch ( IOException e ) - { - throw new SurefireVerifierException( e ); - } - } - - public SurefireLauncher unpack( String sourceName, String suffix ) - { - try - { - return new SurefireLauncher( this.getClass(), sourceName, suffix ); - } - catch ( VerificationException e ) - { - throw new SurefireVerifierException( e ); - } - catch ( IOException e ) - { - throw new SurefireVerifierException( e ); - } - } -} diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/fixture/SurefireJUnit4IntegrationTestCase.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/fixture/SurefireJUnit4IntegrationTestCase.java index 06bea6243c..599d916b7f 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/fixture/SurefireJUnit4IntegrationTestCase.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/fixture/SurefireJUnit4IntegrationTestCase.java @@ -19,9 +19,6 @@ * under the License. */ -import java.io.IOException; -import org.apache.maven.it.VerificationException; - /** * Contains commonly used features for most tests, encapsulating * common use cases. @@ -41,34 +38,14 @@ public OutputValidator executeErrorFreeTest( String sourceName, int total ) public SurefireLauncher unpack( String sourceName ) { - try - { - return new SurefireLauncher( this.getClass(), sourceName, "" ); - } - catch ( VerificationException e ) - { - throw new SurefireVerifierException( e ); - } - catch ( IOException e ) - { - throw new SurefireVerifierException( e ); - } + MavenLauncher mavenLauncher = new MavenLauncher( this.getClass(), sourceName, "" ); + return new SurefireLauncher( mavenLauncher ); } public static SurefireLauncher unpack( Class testClass, String sourceName, String suffix ) { - try - { - return new SurefireLauncher( testClass, sourceName, suffix ); - } - catch ( VerificationException e ) - { - throw new SurefireVerifierException( e ); - } - catch ( IOException e ) - { - throw new SurefireVerifierException( e ); - } + MavenLauncher mavenLauncher = new MavenLauncher( testClass, sourceName, suffix ); + return new SurefireLauncher( mavenLauncher ); } } diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/fixture/SurefireLauncher.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/fixture/SurefireLauncher.java index 0e4cedb1cf..fffde85262 100755 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/fixture/SurefireLauncher.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/fixture/SurefireLauncher.java @@ -20,180 +20,86 @@ */ import java.io.File; -import java.io.IOException; import java.util.ArrayList; -import java.util.HashMap; import java.util.List; -import java.util.Map; -import org.apache.commons.lang.text.StrSubstitutor; 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.it.VerificationException; -import org.apache.maven.it.Verifier; -import org.apache.maven.it.util.ResourceExtractor; -import org.apache.maven.shared.utils.io.FileUtils; /** * Encapsulate all needed features to start a surefire run *

* Also includes thread-safe access to the extracted resource - * files, which AbstractSurefireIntegrationTestClass does not. - * Thread safe only for running in "classes" mode. + * files * - * @author Kristian Rosenvold + * @author Kristian Rosenvold - */ public class SurefireLauncher { - private final List cliOptions = new ArrayList(); - private final List goals = getInitialGoals(); - - private final Map envvars = new HashMap(); + private final MavenLauncher mavenLauncher; private final String testNgVersion = System.getProperty( "testng.version" ); private final String surefireVersion = System.getProperty( "surefire.version" ); - private Verifier verifier; - - private OutputValidator validator; - - private boolean failIfNoTests; - - private final Class testClass; - - private final String resourceName; - - private final String suffix; - - - public SurefireLauncher( Class testClass, String resourceName, String suffix ) - throws VerificationException, IOException - { - this.testClass = testClass; - this.resourceName = resourceName; - this.suffix = suffix != null ? suffix : ""; - goals.clear(); - goals.addAll( getInitialGoals() ); - cliOptions.clear(); - } - - public SurefireLauncher( Verifier verifier ) - { - this.testClass = null; - this.resourceName = null; - this.suffix = ""; - this.verifier = verifier; - goals.clear(); - goals.addAll( getInitialGoals() ); - cliOptions.clear(); - } - - private Verifier createVerifier( Class testClass, String resourceName ) - throws IOException, VerificationException - { - return new Verifier( simpleExtractResources( testClass, resourceName ).getAbsolutePath() ); - } - - private File simpleExtractResources( Class cl, String resourcePath ) - throws IOException + public SurefireLauncher( MavenLauncher mavenLauncher ) { - if ( !resourcePath.startsWith( "/" ) ) - { - resourcePath = "/" + resourcePath; - } - File tempDir = getUnpackDir(); - File testDir = new File( tempDir, resourcePath ); - FileUtils.deleteDirectory( testDir ); - - File file = ResourceExtractor.extractResourceToDestination( cl, resourcePath, tempDir, true ); - return file.getCanonicalFile(); + this.mavenLauncher = mavenLauncher; + reset(); } - private File getUnpackDir() + public MavenLauncher maven() { - String tempDirPath = System.getProperty( "maven.test.tmpdir", System.getProperty( "java.io.tmpdir" ) ); - return new File( tempDirPath, testClass.getSimpleName() + File.separator + getTestMethodName() + suffix ); + return mavenLauncher; } String getTestMethodName() { - // dirty. Im sure we can use junit4 rules to attach testname to thread instead - StackTraceElement[] stackTrace = getStackTraceElements(); - StackTraceElement topInTestClass = null; - topInTestClass = findTopElemenent( stackTrace, testClass ); - if ( topInTestClass == null ) - { - // Look in superclass... - topInTestClass = findTopElemenent( stackTrace, testClass.getSuperclass() ); - } - if ( topInTestClass != null ) - { - return topInTestClass.getMethodName(); - } - throw new IllegalStateException( "Cannot find " + testClass.getName() + "in stacktrace" ); - } - - private StackTraceElement findTopElemenent( StackTraceElement[] stackTrace, Class testClassToLookFor ) - { - StackTraceElement bestmatch = null; - for ( StackTraceElement stackTraceElement : stackTrace ) - { - if ( stackTraceElement.getClassName().equals( testClassToLookFor.getName() ) ) - { - bestmatch = stackTraceElement; - } - } - return bestmatch; + return mavenLauncher.getTestMethodName(); } - StackTraceElement[] getStackTraceElements() + public void reset() { - try + mavenLauncher.reset(); + for ( String s : getInitialGoals( testNgVersion ) ) { - throw new RuntimeException(); - } - catch ( RuntimeException e ) - { - return e.getStackTrace(); + mavenLauncher.addGoal( s ); } } - public void reset() - { - goals.clear(); - goals.addAll( getInitialGoals() ); - cliOptions.clear(); - } public SurefireLauncher getSubProjectLauncher( String subProject ) throws VerificationException { - final File subFile = getValidator().getSubFile( subProject ); - return new SurefireLauncher( new Verifier( subFile.getAbsolutePath() ) ); + return new SurefireLauncher( mavenLauncher.getSubProjectLauncher( subProject ) ); } public OutputValidator getSubProjectValidator( String subProject ) throws VerificationException { - final File subFile = getValidator().getSubFile( subProject ); - return new OutputValidator( new Verifier( subFile.getAbsolutePath() ) ); + return mavenLauncher.getSubProjectValidator( subProject ); } public SurefireLauncher addEnvVar( String key, String value ) { - envvars.put( key, value ); + mavenLauncher.addEnvVar( key, value ); + return this; + } + + public SurefireLauncher setMavenOpts(String opts){ + addEnvVar( "MAVEN_OPTS", opts ); return this; } - private List getInitialGoals() + private List getInitialGoals( String testNgVersion ) { List goals1 = new ArrayList(); goals1.add( "-Dsurefire.version=" + surefireVersion ); - if ( testNgVersion != null ) + if ( this.testNgVersion != null ) { goals1.add( "-DtestNgVersion=" + testNgVersion ); @@ -214,216 +120,100 @@ private List getInitialGoals() return goals1; } - // Todo remove duplication between this and getInitialGoals public SurefireLauncher resetInitialGoals( String testNgVersion ) { - List goals = new ArrayList(); - goals.add( "-Dsurefire.version=" + surefireVersion ); - - if ( testNgVersion != null ) + mavenLauncher.resetGoals(); + for ( String s : getInitialGoals( testNgVersion ) ) { - goals.add( "-DtestNgVersion=" + testNgVersion ); - - ArtifactVersion v = new DefaultArtifactVersion( testNgVersion ); - try - { - if ( VersionRange.createFromVersionSpec( "(,5.12.1)" ).containsVersion( v ) ) - { - goals.add( "-DtestNgClassifier=jdk15" ); - } - } - catch ( InvalidVersionSpecificationException e ) - { - throw new RuntimeException( e.getMessage(), e ); - } + mavenLauncher.addGoal( s ); } - - this.goals.clear(); - this.goals.addAll( goals ); return this; } - public SurefireLauncher assertNotPresent( String subFile ) - { - getVerifier().assertFileNotPresent( getValidator().getSubFile( subFile ).getAbsolutePath() ); - return this; - } - public SurefireLauncher showErrorStackTraces() { - cliOptions.add( "-e" ); + mavenLauncher.showErrorStackTraces(); return this; } public SurefireLauncher debugLogging() { - cliOptions.add( "-X" ); + mavenLauncher.debugLogging(); return this; } + @SuppressWarnings( "UnusedDeclaration" ) public SurefireLauncher debugSurefireFork() { - addD( "maven.surefire.debug", "true" ); + mavenLauncher.sysProp( "maven.surefire.debug", "true" ); return this; } public SurefireLauncher failNever() { - cliOptions.add( "-fn" ); - return this; - - } - - public SurefireLauncher skipClean() - { - goals.add( "-Dclean.skip=true" ); + mavenLauncher.failNever(); return this; } public SurefireLauncher groups( String groups ) { - goals.add( "-Dgroups=" + groups ); + mavenLauncher.sysProp( "groups", groups ); return this; } public SurefireLauncher addGoal( String goal ) { - goals.add( goal ); + mavenLauncher.addGoal( goal ); return this; } public OutputValidator executeTest() { - return execute( "test" ); + return mavenLauncher.execute( "test" ); } public OutputValidator executeInstall() throws VerificationException { - return execute( "install" ); - } - - public OutputValidator executeTestWithFailure() - { - try - { - execute( "test" ); - } - catch ( SurefireVerifierException ignore ) - { - return getValidator(); - } - throw new RuntimeException( "Expecting build failure, got none!" ); - } - - public OutputValidator executeVerifyWithFailure() - { - try - { - executeVerify(); - } - catch ( SurefireVerifierException ignore ) - { - return getValidator(); - } - throw new RuntimeException( "Expecting build failure, got none!" ); + return mavenLauncher.execute( "install" ); } public FailsafeOutputValidator executeVerify() { OutputValidator verify = execute( "verify" ); - return new FailsafeOutputValidator( verify.getVerifier() ); + return new FailsafeOutputValidator( verify ); } public OutputValidator execute( String goal ) { - addGoal( goal ); - return executeCurrentGoals(); + return mavenLauncher.execute( goal ); } - public OutputValidator executeCurrentGoals() + public OutputValidator executeSurefireReport() { - - String userLocalRepo = System.getProperty( "user.localRepository" ); - String testBuildDirectory = System.getProperty( "testBuildDirectory" ); - boolean useInterpolatedSettings = Boolean.getBoolean( "useInterpolatedSettings" ); - - try - { - if ( useInterpolatedSettings ) - { - File interpolatedSettings = new File( testBuildDirectory, "interpolated-settings" ); - - if ( !interpolatedSettings.exists() ) - { - // hack "a la" invoker plugin to download dependencies from local repo - // and not download from central - - Map values = new HashMap( 1 ); - values.put( "localRepositoryUrl", toUrl( userLocalRepo ) ); - StrSubstitutor strSubstitutor = new StrSubstitutor( values ); - - String fileContent = FileUtils.fileRead( new File( testBuildDirectory, "settings.xml" ) ); - - String filtered = strSubstitutor.replace( fileContent ); - - FileUtils.fileWrite( interpolatedSettings.getAbsolutePath(), filtered ); - - } - - cliOptions.add( "-s " + interpolatedSettings.getCanonicalPath() ); - } - getVerifier().setCliOptions( cliOptions ); - - getVerifier().executeGoals( goals, envvars ); - return getValidator(); - } - catch ( IOException e ) - { - throw new SurefireVerifierException( e.getMessage(), e ); - } - catch ( VerificationException e ) - { - throw new SurefireVerifierException( e.getMessage(), e ); - } - finally - { - getVerifier().resetStreams(); - } + return mavenLauncher.execute( "surefire-report:report" ); } - private static String toUrl( String filename ) + + public OutputValidator executeCurrentGoals() { - /* - * NOTE: Maven fails to properly handle percent-encoded "file:" URLs (WAGON-111) so don't use File.toURI() here - * as-is but use the decoded path component in the URL. - */ - String url = "file://" + new File( filename ).toURI().getPath(); - if ( url.endsWith( "/" ) ) - { - url = url.substring( 0, url.length() - 1 ); - } - return url; + return mavenLauncher.executeCurrentGoals(); } public SurefireLauncher printSummary( boolean printsummary ) { - return addGoal( "-DprintSummary=" + printsummary ); - } - - public SurefireLauncher redirectToFileReally( boolean redirect ) - { - return addGoal( "-Dmaven.test.redirectTestOutputToFile=" + redirect ); + mavenLauncher.sysProp( "printSummary", printsummary ); + return this; } public SurefireLauncher redirectToFile( boolean redirect ) { - return redirectToFileReally( redirect ); - //addGoal( "-Dredirect.to.file=" + redirect ); + mavenLauncher.sysProp( "maven.test.redirectTestOutputToFile", redirect ); + return this; } public SurefireLauncher forkOnce() @@ -448,49 +238,73 @@ public SurefireLauncher forkPerTest() public SurefireLauncher forkPerThread() { - return forkMode( "perthread" ); + return forkMode( "perthread" ).reuseForks( false ); } public SurefireLauncher forkOncePerThread() { - return forkMode( "onceperthread" ); + return forkPerThread().reuseForks( true ); } public SurefireLauncher threadCount( int threadCount ) { - return addGoal( "-DthreadCount=" + threadCount ); + mavenLauncher.sysProp( "threadCount", threadCount ); + return this; + } + + public SurefireLauncher forkCount( int forkCount ) + { + mavenLauncher.sysProp( "forkCount", forkCount ); + return this; + } + + public SurefireLauncher reuseForks( boolean reuseForks ) + { + mavenLauncher.sysProp( "reuseForks", reuseForks ); + return this; } public SurefireLauncher forkMode( String forkMode ) { - return addGoal( "-DforkMode=" + forkMode ); + mavenLauncher.sysProp( "forkMode", forkMode ); + return this; } public SurefireLauncher runOrder( String runOrder ) { - return addGoal( "-DrunOrder=" + runOrder ); + mavenLauncher.sysProp( "runOrder", runOrder ); + return this; } public SurefireLauncher failIfNoTests( boolean fail ) { - this.failIfNoTests = fail; - return addGoal( "-DfailIfNoTests=" + fail ); + mavenLauncher.sysProp( "failIfNoTests", fail ); + return this; + } + + + public SurefireLauncher mavenTestFailureIgnore( boolean fail ) + { + mavenLauncher.sysProp( "maven.test.failure.ignore", fail ); + return this; } public SurefireLauncher failIfNoSpecifiedTests( boolean fail ) { - this.failIfNoTests = fail; - return addGoal( "-Dsurefire.failIfNoSpecifiedTests=" + fail ); + mavenLauncher.sysProp( "surefire.failIfNoSpecifiedTests", fail ); + return this; } public SurefireLauncher useSystemClassLoader( boolean useSystemClassLoader ) { - return addGoal( "-DuseSystemClassLoader=" + useSystemClassLoader ); + mavenLauncher.sysProp( "useSystemClassLoader", useSystemClassLoader ); + return this; } public SurefireLauncher activateProfile( String profile ) { - return addGoal( "-P" + profile ); + mavenLauncher.activateProfile( profile ); + return this; } @@ -501,7 +315,9 @@ protected String getSurefireVersion() public SurefireLauncher parallel( String parallel ) { - return addD( "parallel", parallel ); + + mavenLauncher.sysProp( "parallel", parallel ); + return this; } @@ -516,110 +332,68 @@ public SurefireLauncher parallelMethods() } - public SurefireLauncher addD( String variable, String value ) + public SurefireLauncher sysProp( String variable, String value ) { - return addGoal( "-D" + variable + "=" + value ); + mavenLauncher.sysProp( variable, value ); + return this; } public SurefireLauncher setJUnitVersion( String version ) { - addD( "junit.version", version ); + mavenLauncher.sysProp( "junit.version", version ); return this; } public SurefireLauncher setGroups( String groups ) { - return addD( "groups", groups ); + mavenLauncher.sysProp( "groups", groups ); + return this; } public SurefireLauncher setExcludedGroups( String excludedGroups ) { - return addD( "excludedGroups", excludedGroups ); - } - - public SurefireLauncher setEOption() - { - cliOptions.add( "-e" ); + mavenLauncher.sysProp( "excludedGroups", excludedGroups ); return this; } - public boolean isFailIfNoTests() + public File getUnpackedAt() { - return failIfNoTests; - } - - public File getUnpackLocation() - { - getVerifier(); // Make sure we have unpacked - return getUnpackDir(); + return mavenLauncher.getUnpackedAt(); } public SurefireLauncher addFailsafeReportOnlyGoal() { - goals.add( - "org.apache.maven.plugins:maven-surefire-report-plugin:" + getSurefireVersion() + ":failsafe-report-only" ); + mavenLauncher.addGoal( getReportPluginGoal( ":failsafe-report-only" ) ); return this; } public SurefireLauncher addSurefireReportGoal() { - goals.add( "org.apache.maven.plugins:maven-surefire-report-plugin:" + getSurefireVersion() + ":report" ); + mavenLauncher.addGoal( getReportPluginGoal( "report" ) ); return this; } public SurefireLauncher addSurefireReportOnlyGoal() { - goals.add( "org.apache.maven.plugins:maven-surefire-report-plugin:" + getSurefireVersion() + ":report-only" ); + mavenLauncher.addGoal( getReportPluginGoal( "report-only" ) ); return this; } - - public SurefireLauncher deleteSiteDir() + private String getReportPluginGoal( String goal ) { - try - { - FileUtils.deleteDirectory( getValidator().getSubFile( "site" ) ); - } - catch ( IOException e ) - { - throw new SurefireVerifierException( e ); - } - return this; + return "org.apache.maven.plugins:maven-surefire-report-plugin:" + getSurefireVersion() + ":" + goal; } public SurefireLauncher setTestToRun( String basicTest ) { - addD( "test", basicTest ); + mavenLauncher.sysProp( "test", basicTest ); return this; } - public OutputValidator getValidator() - { - if ( validator == null ) - { - this.validator = new OutputValidator( getVerifier() ); - } - return validator; - } - - private Verifier getVerifier() + public SurefireLauncher setForkJvm() { - if ( verifier == null ) - { - try - { - this.verifier = createVerifier( testClass, resourceName ); - } - catch ( IOException e ) - { - throw new RuntimeException( e ); - } - catch ( VerificationException e ) - { - throw new RuntimeException( e ); - } - } - return verifier; + mavenLauncher.setForkJvm( true ); + return this; } } diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/fixture/SurefireLauncherTest.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/fixture/SurefireLauncherTest.java index 6d3429b816..def9d8be11 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/fixture/SurefireLauncherTest.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/fixture/SurefireLauncherTest.java @@ -16,7 +16,8 @@ public class SurefireLauncherTest public void launcherGetsProperMethodName() throws IOException, VerificationException { - String method = new SurefireLauncher( SurefireLauncherTest.class, "foo", "" ).getTestMethodName(); + MavenLauncher mavenLauncher = new MavenLauncher( SurefireLauncherTest.class, "foo", "" ); + String method = new SurefireLauncher( mavenLauncher ).getTestMethodName(); assertEquals( "launcherGetsProperMethodName", method ); } diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/fixture/SurefireReportParser.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/fixture/SurefireReportParser.java deleted file mode 100644 index 82c19b7534..0000000000 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/fixture/SurefireReportParser.java +++ /dev/null @@ -1,109 +0,0 @@ -package org.apache.maven.surefire.its.fixture; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES 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.IOException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import org.apache.maven.shared.utils.StringUtils; -import org.apache.maven.shared.utils.io.DirectoryScanner; - -import javax.xml.parsers.ParserConfigurationException; - -import org.xml.sax.SAXException; - -/** - * - */ -public class SurefireReportParser -{ - - private final List reportsDirectories; - - private final List testSuites = new ArrayList(); - - public SurefireReportParser( List reportsDirectoriesFiles ) - { - this.reportsDirectories = reportsDirectoriesFiles; - - } - - public List parseXMLReportFiles() - { - List xmlReportFileList = new ArrayList(); - for ( File reportsDirectory : reportsDirectories ) - { - if ( !reportsDirectory.exists() ) - { - continue; - } - String[] xmlReportFiles = getIncludedFiles( reportsDirectory, "*.xml", - "*.txt, testng-failed.xml, testng-failures.xml, testng-results.xml, failsafe-summary.xml" ); - for ( String xmlReportFile : xmlReportFiles ) - { - File xmlReport = new File( reportsDirectory, xmlReportFile ); - xmlReportFileList.add( xmlReport ); - } - } - TestSuiteXmlParser parser = new TestSuiteXmlParser(); - for ( File aXmlReportFileList : xmlReportFileList ) - { - Collection suites; - - try - { - suites = parser.parse( aXmlReportFileList.getAbsolutePath() ); - } - catch ( ParserConfigurationException e ) - { - throw new RuntimeException( "Error setting up parser for JUnit XML report", e ); - } - catch ( SAXException e ) - { - throw new RuntimeException( "Error parsing JUnit XML report " + aXmlReportFileList, e ); - } - catch ( IOException e ) - { - throw new RuntimeException( "Error reading JUnit XML report " + aXmlReportFileList, e ); - } - - testSuites.addAll( suites ); - } - - return testSuites; - } - - private String[] getIncludedFiles( File directory, String includes, String excludes ) - { - DirectoryScanner scanner = new DirectoryScanner(); - - scanner.setBasedir( directory ); - - scanner.setIncludes( StringUtils.split( includes, "," ) ); - - scanner.setExcludes( StringUtils.split( excludes, "," ) ); - - scanner.scan(); - - return scanner.getIncludedFiles(); - } -} diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/fixture/TestFile.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/fixture/TestFile.java index 9a62d64e2e..3c76c62611 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/fixture/TestFile.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/fixture/TestFile.java @@ -26,6 +26,7 @@ import java.io.FileReader; import java.io.IOException; import java.net.URI; +import java.nio.charset.Charset; import java.util.List; import org.apache.commons.io.FileUtils; @@ -41,11 +42,19 @@ public class TestFile private final File file; + private final Charset encoding; + private final OutputValidator surefireVerifier; public TestFile( File file, OutputValidator surefireVerifier ) + { + this( file, Charset.defaultCharset(), surefireVerifier); + } + + public TestFile( File file, Charset charset,OutputValidator surefireVerifier ) { this.file = file; + this.encoding = charset; this.surefireVerifier = surefireVerifier; } @@ -123,7 +132,7 @@ public boolean isFile() public TestFile assertContainsText( String text ) { - final List list = surefireVerifier.loadFile( file, false ); + final List list = surefireVerifier.loadFile( file, encoding ); for ( String line : list ) { if ( line.contains( text ) ) diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/fixture/TestSuiteXmlParserTest.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/fixture/TestSuiteXmlParserTest.java deleted file mode 100644 index 55419de863..0000000000 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/fixture/TestSuiteXmlParserTest.java +++ /dev/null @@ -1,36 +0,0 @@ -package org.apache.maven.surefire.its.fixture; - -import java.io.IOException; -import java.util.Collection; - -import javax.xml.parsers.ParserConfigurationException; - -import org.junit.Test; -import org.xml.sax.SAXException; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -/** - * @author Kristian Rosenvold - */ -public class TestSuiteXmlParserTest -{ - @Test - public void testParser() - throws IOException, SAXException, ParserConfigurationException - { - TestSuiteXmlParser parser = new TestSuiteXmlParser(); - - Collection oldResult = parser.parse( - "src/test/resources/fixture/testsuitexmlparser/TEST-org.apache.maven.surefire.test.FailingTest.xml" ); - - assertNotNull( oldResult ); - - assertEquals( 1, oldResult.size() ); - ReportTestSuite next = oldResult.iterator().next(); - assertEquals( 2, next.getNumberOfTests() ); - - - } -} diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire141PluggableProvidersIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire141PluggableProvidersIT.java index 1cdfe56367..48ed05022f 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire141PluggableProvidersIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire141PluggableProvidersIT.java @@ -20,8 +20,6 @@ */ import org.apache.maven.it.VerificationException; -import org.apache.maven.surefire.its.fixture.OutputValidator; -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; import org.junit.BeforeClass; @@ -46,7 +44,7 @@ public static void installProvider() public void pluggableProviderPresent() throws Exception { - unpack( "surefire-141-pluggableproviders" ).setEOption().executeTest().verifyTextInLog( + unpack( "surefire-141-pluggableproviders" ).maven().showExceptionMessages().executeTest().verifyTextInLog( "Using configured provider org.apache.maven.surefire.testprovider.TestProvider" ).verifyTextInLog( "Using configured provider org.apache.maven.surefire.junit.JUnit3Provider" ).verifyErrorFreeLog(); } @@ -55,7 +53,8 @@ public void pluggableProviderPresent() public void invokeRuntimeException() throws Exception { - unpack( "surefire-141-pluggableproviders" ).addD( "invokeCrash", "runtimeException" ).executeTestWithFailure().verifyTextInLog( + unpack( "surefire-141-pluggableproviders" ).sysProp( "invokeCrash", + "runtimeException" ).maven().withFailure().executeTest().verifyTextInLog( "Let's fail with a runtimeException" ); } @@ -63,7 +62,8 @@ public void invokeRuntimeException() public void invokeReporterException() throws Exception { - unpack( "surefire-141-pluggableproviders" ).addD( "invokeCrash", "reporterException" ).executeTestWithFailure().verifyTextInLog( + unpack( "surefire-141-pluggableproviders" ).sysProp( "invokeCrash", + "reporterException" ).maven().withFailure().executeTest().verifyTextInLog( "Let's fail with a reporterexception" ); } @@ -71,7 +71,8 @@ public void invokeReporterException() public void constructorReuntimeException() throws Exception { - unpack( "surefire-141-pluggableproviders" ).addD( "constructorCrash", "runtimeException" ).executeTestWithFailure().verifyTextInLog( + unpack( "surefire-141-pluggableproviders" ).sysProp( "constructorCrash", + "runtimeException" ).maven().withFailure().executeTest().verifyTextInLog( "Let's fail with a runtimeException" ); } diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire146ForkPerTestNoSetupIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire146ForkPerTestNoSetupIT.java index b4673f55ab..7e50f2569e 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire146ForkPerTestNoSetupIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire146ForkPerTestNoSetupIT.java @@ -19,7 +19,8 @@ * under the License. */ -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; +import org.junit.Test; /** * Test Surefire-146 (forkMode=pertest fails to call setUp) @@ -27,8 +28,9 @@ * @author Dan Fabulich */ public class Surefire146ForkPerTestNoSetupIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { + @Test public void testForkPerTestNoSetup() { executeErrorFreeTest( "surefire-146-forkPerTestNoSetup", 1 ); diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire162CharsetProviderIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire162CharsetProviderIT.java index b593976f38..e13483ac0e 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire162CharsetProviderIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire162CharsetProviderIT.java @@ -20,10 +20,10 @@ */ import java.io.File; -import org.apache.maven.surefire.its.fixture.OutputValidator; -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; -import org.apache.maven.surefire.its.fixture.SurefireLauncher; + +import org.apache.maven.surefire.its.fixture.*; import org.codehaus.plexus.util.FileUtils; +import org.junit.Test; /** * Test charset provider (SUREFIRE-162) @@ -31,19 +31,21 @@ * @author Dan Fabulich */ public class Surefire162CharsetProviderIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { @SuppressWarnings( { "ResultOfMethodCallIgnored" } ) + @Test public void testCharsetProvider() throws Exception { SurefireLauncher unpack = unpack( "/surefire-162-charsetProvider" ); - OutputValidator verifier = unpack.getValidator(); - File jarFile = new File( verifier.getArtifactPath( "jcharset", "jcharset", "1.2.1", "jar" ) ); + 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" ); 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" ), - new File( verifier.getArtifactPath( "jcharset", "jcharset", "1.2.1", "pom" ) ) ); + FileUtils.copyFile( verifier.getSubFile( "repo/jcharset/jcharset/1.2.1/jcharset-1.2.1.pom" ), pomFile ); unpack.executeTest().verifyErrorFree( 1 ); } } diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire224WellFormedXmlFailuresIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire224WellFormedXmlFailuresIT.java index 01d91258fd..5a6312b895 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire224WellFormedXmlFailuresIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire224WellFormedXmlFailuresIT.java @@ -19,13 +19,17 @@ * under the License. */ -import java.io.File; -import java.util.List; +import org.apache.maven.plugins.surefire.report.ReportTestCase; +import org.apache.maven.plugins.surefire.report.ReportTestSuite; import org.apache.maven.surefire.its.fixture.HelperAssertions; import org.apache.maven.surefire.its.fixture.OutputValidator; -import org.apache.maven.surefire.its.fixture.ReportTestCase; -import org.apache.maven.surefire.its.fixture.ReportTestSuite; -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; +import org.junit.Test; + +import java.io.File; +import java.util.List; + +import static org.junit.Assert.assertEquals; /** * Test Surefire-224 (XML test reports are not well-formed when failure message contains quotes) @@ -33,8 +37,10 @@ * @author Dan Fabulich */ public class Surefire224WellFormedXmlFailuresIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { + @SuppressWarnings("ConstantConditions") + @Test public void testWellFormedXmlFailures() { OutputValidator outputValidator = unpack( "/surefire-224-wellFormedXmlFailures" ).executeTest(); @@ -43,7 +49,7 @@ public void testWellFormedXmlFailures() ReportTestSuite suite = HelperAssertions.extractReports( ( new File[]{ outputValidator.getBaseDir() } ) ).get( 0 ); - List testCases = suite.getTestCases(); + List testCases = suite.getTestCases(); assertEquals( "Wrong number of test case objects", 4, testCases.size() ); ReportTestCase testQuote = null, testLower = null, testGreater = null, testU0000 = null; for ( ReportTestCase current : testCases ) diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire257NotRerunningTestsIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire257NotRerunningTestsIT.java index 6d6235ace4..2796b92c56 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire257NotRerunningTestsIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire257NotRerunningTestsIT.java @@ -19,7 +19,8 @@ * under the License. */ -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; +import org.junit.Test; /** * Test Surefire-257 Verifies that surefire does not re-run tests in site build @@ -27,9 +28,10 @@ * @author Kristian Rosenvold */ public class Surefire257NotRerunningTestsIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { - public void testShouldNotRerun() + @Test + public void shouldNotRerun() throws Exception { unpack( diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire260TestWithIdenticalNamesIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire260TestWithIdenticalNamesIT.java index 6b78d8faf4..85d7dfcc97 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire260TestWithIdenticalNamesIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire260TestWithIdenticalNamesIT.java @@ -21,15 +21,17 @@ import java.io.IOException; import java.net.URI; -import org.apache.maven.surefire.its.fixture.OutputValidator; -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; -import org.apache.maven.surefire.its.fixture.SurefireLauncher; -import org.apache.maven.surefire.its.fixture.TestFile; + +import org.apache.maven.surefire.its.fixture.*; 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.junit.Test; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; /** * Test Surefire-570 Multiple report directories @@ -37,9 +39,10 @@ * @author Kristian Rosenvold */ public class Surefire260TestWithIdenticalNamesIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { + @Test public void testWithIdenticalNames() throws IOException { diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire34SecurityManagerIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire34SecurityManagerIT.java index 7aea2c72f6..bb80aecdf5 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire34SecurityManagerIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire34SecurityManagerIT.java @@ -19,8 +19,9 @@ * under the License. */ -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; import org.apache.maven.surefire.its.fixture.SurefireLauncher; +import org.junit.Test; /** * SUREFIRE-621 Asserts proper test counts when running junit 3 tests in parallel @@ -28,14 +29,16 @@ * @author Kristian Rosenvold */ public class Surefire34SecurityManagerIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { + @Test public void testSecurityManager() { SurefireLauncher surefireLauncher = unpack( "surefire-34-securityManager" ).failNever(); surefireLauncher.executeTest().assertTestSuiteResults( 2, 1, 0, 0 ); } + @Test public void testSecurityManagerSuccessful() { SurefireLauncher surefireLauncher = unpack( "surefire-34-securityManager-success" ); diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire376TestNgAfterSuiteFailureIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire376TestNgAfterSuiteFailureIT.java index c91c33b8f8..ee85b2bbc6 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire376TestNgAfterSuiteFailureIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire376TestNgAfterSuiteFailureIT.java @@ -19,7 +19,8 @@ * under the License. */ -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; +import org.junit.Test; /** * Test Surefire-376 (TestNG @AfterSuite failures are ignored) @@ -27,11 +28,12 @@ * @author Dan Fabulich */ public class Surefire376TestNgAfterSuiteFailureIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { + @Test public void testAfterSuiteFailure() { - unpack( "/testng-afterSuiteFailure" ).executeTestWithFailure(). + unpack( "/testng-afterSuiteFailure" ).maven().withFailure().executeTest(). assertTestSuiteResults( 2, 0, 1, 0 ); } } diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire377TestNgAndJUnitTogetherIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire377TestNgAndJUnitTogetherIT.java index e1e895eb12..ea0a5df901 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire377TestNgAndJUnitTogetherIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire377TestNgAndJUnitTogetherIT.java @@ -19,7 +19,8 @@ * under the License. */ -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; +import org.junit.Test; /** * SUREFIRE-377 (When JUnit and TestNG tests are in same project, only one set gets run). @@ -27,8 +28,9 @@ * @author Dan Fabulich */ public class Surefire377TestNgAndJUnitTogetherIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { + @Test public void testTestNgAndJUnitTogether() { executeErrorFreeTest( "/testng-junit-together", 2 ); diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire408ManualProviderSelectionIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire408ManualProviderSelectionIT.java index b13e286cf4..a847b00aff 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire408ManualProviderSelectionIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire408ManualProviderSelectionIT.java @@ -19,7 +19,8 @@ * under the License. */ -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; +import org.junit.Test; /** * SUREFIRE-613 Asserts proper test counts when running in parallel @@ -27,8 +28,9 @@ * @author Kristian Rosenvold */ public class Surefire408ManualProviderSelectionIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { + @Test public void testPaallelBuildResultCount() { unpack( "/surefire-408-manual-provider-selection" ).showErrorStackTraces().executeTest().verifyTextInLog( diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire42NotExtendingTestCaseIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire42NotExtendingTestCaseIT.java index a18eec48d4..00c2aeefb0 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire42NotExtendingTestCaseIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire42NotExtendingTestCaseIT.java @@ -19,7 +19,8 @@ * under the License. */ -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; +import org.junit.Test; /** * Test JUnit test that contains inner classes @@ -27,8 +28,9 @@ * @author Dan Fabulich */ public class Surefire42NotExtendingTestCaseIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { + @Test public void testInnerClass() { executeErrorFreeTest( "junit-notExtendingTestCase", 1 ); diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire44InnerClassTestIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire44InnerClassTestIT.java index b181a75358..928019a2ea 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire44InnerClassTestIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire44InnerClassTestIT.java @@ -19,7 +19,8 @@ * under the License. */ -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; +import org.junit.Test; /** * Test JUnit test that contains inner classes @@ -27,8 +28,9 @@ * @author Dan Fabulich */ public class Surefire44InnerClassTestIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { + @Test public void testInnerClass() { executeErrorFreeTest( "/junit-innerClass", 1 ); diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire500PuzzlingErrorIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire500PuzzlingErrorIT.java index 782d6f004b..9356f687bc 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire500PuzzlingErrorIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire500PuzzlingErrorIT.java @@ -20,8 +20,9 @@ */ import org.apache.maven.surefire.its.fixture.OutputValidator; -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; import org.apache.maven.surefire.its.fixture.TestFile; +import org.junit.Test; /** * SUREFIRE-500 Asserts correct error handling for the "odd" surefire-500 (and 625) issues. @@ -29,8 +30,9 @@ * @author Kristian Rosenvold */ public class Surefire500PuzzlingErrorIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { + @Test public void testBuildFailingWhenErrors() { OutputValidator outputValidator = unpack( "/surefire-500-puzzling-error" ).failNever().executeTest(); diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire510TestClassPathForkModesIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire510TestClassPathForkModesIT.java index d59313b604..4e4fd13983 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire510TestClassPathForkModesIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire510TestClassPathForkModesIT.java @@ -19,8 +19,9 @@ * under the License. */ -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; import org.apache.maven.surefire.its.fixture.SurefireLauncher; +import org.junit.Test; /** * SUREFIRE-621 Asserts proper test counts when running junit 3 tests in parallel @@ -28,15 +29,17 @@ * @author Kristian Rosenvold */ public class Surefire510TestClassPathForkModesIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { + @Test public void testForkAlways() { unpack().forkAlways().executeTest(). verifyTextInLog( "tcp is set" ); } + @Test public void testForkOnce() { unpack().forkOnce().executeTest(). diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire569RunTestFromDependencyJarsIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire569RunTestFromDependencyJarsIT.java new file mode 100644 index 0000000000..cb9c92d491 --- /dev/null +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire569RunTestFromDependencyJarsIT.java @@ -0,0 +1,25 @@ +package org.apache.maven.surefire.its.jiras; + +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; + +/** + * SUREFIRE-569 Add support for scanning Dependencies for TestClasses + * + * @author Aslak Knutsen + */ +public class Surefire569RunTestFromDependencyJarsIT + extends SurefireJUnit4IntegrationTestCase { + + @Test + 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); + } +} diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire570MultipleReportDirectoriesIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire570MultipleReportDirectoriesIT.java index 580fd92372..a9b437ebae 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire570MultipleReportDirectoriesIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire570MultipleReportDirectoriesIT.java @@ -19,10 +19,8 @@ * under the License. */ -import org.apache.maven.surefire.its.fixture.OutputValidator; -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; -import org.apache.maven.surefire.its.fixture.SurefireLauncher; -import org.apache.maven.surefire.its.fixture.TestFile; +import org.apache.maven.surefire.its.fixture.*; +import org.junit.Test; /** * Test Surefire-570 Multiple report directories @@ -30,9 +28,10 @@ * @author Kristian Rosenvold */ public class Surefire570MultipleReportDirectoriesIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { + @Test public void testReportWithAggregate() throws Exception { @@ -40,20 +39,21 @@ public void testReportWithAggregate() SurefireLauncher surefireLauncher = unpack().failNever(); surefireLauncher.executeTest(); surefireLauncher.addGoal( "-Daggregate=true" ); - OutputValidator validator = surefireLauncher.execute( "surefire-report:report" ); + 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 { SurefireLauncher surefireLauncher = unpack().failNever(); surefireLauncher.executeTest(); surefireLauncher.reset(); - surefireLauncher.execute( "surefire-report:report" ); + surefireLauncher.executeSurefireReport( ); OutputValidator module1 = surefireLauncher.getSubProjectValidator( "module1" ); TestFile siteFile = module1.getSiteFile( "surefire-report.html" ); siteFile.assertContainsText( "MyModule1ClassTest" ); diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire613TestCountInParallelIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire613TestCountInParallelIT.java index 710fc41dc9..7b74409a9d 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire613TestCountInParallelIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire613TestCountInParallelIT.java @@ -20,7 +20,8 @@ */ import org.apache.maven.surefire.its.fixture.OutputValidator; -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; +import org.junit.Test; /** * SUREFIRE-613 Asserts proper test counts when running in parallel @@ -28,9 +29,10 @@ * @author Kristian Rosenvold */ public class Surefire613TestCountInParallelIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { - public void testPaallelBuildResultCount() + @Test + public void testParallelBuildResultCount() { OutputValidator validator = unpack( "/surefire-613-testCount-in-parallel" ).failNever().executeTest(); diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire621TestCountingJunit3InParallelIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire621TestCountingJunit3InParallelIT.java index 9da3b6f1f2..d67de4f945 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire621TestCountingJunit3InParallelIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire621TestCountingJunit3InParallelIT.java @@ -19,7 +19,8 @@ * under the License. */ -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; +import org.junit.Test; /** * SUREFIRE-621 Asserts proper test counts when running junit 3 tests in parallel @@ -27,8 +28,9 @@ * @author Kristian Rosenvold */ public class Surefire621TestCountingJunit3InParallelIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { + @Test public void testJunit3ParallelBuildResultCount() { unpack( "surefire-621-testCounting-junit3-in-parallel" ).failNever().execute( diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire628ConsoleOutputBeforeAndAfterClassIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire628ConsoleOutputBeforeAndAfterClassIT.java index f18945d847..27f9572286 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire628ConsoleOutputBeforeAndAfterClassIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire628ConsoleOutputBeforeAndAfterClassIT.java @@ -20,7 +20,8 @@ */ import org.apache.maven.surefire.its.fixture.OutputValidator; -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; +import org.junit.Test; /** * Asserts that console output always goes somewhere ;) @@ -28,9 +29,10 @@ * @author Kristian Rosenvold assertContainsText */ public class Surefire628ConsoleOutputBeforeAndAfterClassIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { + @Test public void testJunit3ParallelBuildResultCount() { OutputValidator validator = diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire634UnsettableSystemPropertiesWarningIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire634UnsettableSystemPropertiesWarningIT.java index d36667d5eb..778e776be5 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire634UnsettableSystemPropertiesWarningIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire634UnsettableSystemPropertiesWarningIT.java @@ -19,7 +19,8 @@ * under the License. */ -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; +import org.junit.Test; /** * SUREFIRE-634 Verifies error message on unsettable system properties @@ -27,8 +28,9 @@ * @author Kristian Rosenvold */ public class Surefire634UnsettableSystemPropertiesWarningIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { + @Test public void testJunit3ParallelBuildResultCount() { unpack( "/surefire-634-systemPropertiesWarning" ).executeTest().verifyTextInLog( diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire673MockitoIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire673MockitoIT.java index af392b1fd8..7f3e2ca82c 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire673MockitoIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire673MockitoIT.java @@ -19,7 +19,8 @@ * under the License. */ -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; +import org.junit.Test; /** * SUREFIRE-673 Asserts that a given mockito build works as it should (classloader problem in 2.7) @@ -27,8 +28,9 @@ * @author Kristian Rosenvold */ public class Surefire673MockitoIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { + @Test public void testBuildFailingWhenErrors() { unpack( "/surefire-673-mockito" ).executeTest().verifyErrorFreeLog(); diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire674BuildFailingWhenErrorsIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire674BuildFailingWhenErrorsIT.java index 6e3b2a102c..5aa342f077 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire674BuildFailingWhenErrorsIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire674BuildFailingWhenErrorsIT.java @@ -19,7 +19,8 @@ * under the License. */ -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; +import org.junit.Test; /** * SUREFIRE-674 Asserts that the build fails when tests have errors @@ -27,10 +28,12 @@ * @author Kristian Rosenvold */ public class Surefire674BuildFailingWhenErrorsIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { + @Test public void testBuildFailingWhenErrors() { - unpack( "/surefire-674-buildFailingWhenErrors" ).executeTestWithFailure().verifyTextInLog( "BUILD FAILURE" ); + unpack( "/surefire-674-buildFailingWhenErrors" ).maven().withFailure().executeTest().verifyTextInLog( + "BUILD FAILURE" ); } } \ No newline at end of file diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire674BuildFailingWhenFailsafeErrorsIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire674BuildFailingWhenFailsafeErrorsIT.java index feacdbf5a1..57c8648899 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire674BuildFailingWhenFailsafeErrorsIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire674BuildFailingWhenFailsafeErrorsIT.java @@ -19,7 +19,8 @@ * under the License. */ -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; +import org.junit.Test; /** * SUREFIRE-674 Asserts that the build fails when tests have errors @@ -27,10 +28,11 @@ * @author Kristian Rosenvold */ public class Surefire674BuildFailingWhenFailsafeErrorsIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { + @Test public void testBuildFailingWhenErrors() { - unpack( "/failsafe-buildfail" ).executeVerifyWithFailure().verifyTextInLog( "BUILD FAILURE" ); + unpack( "/failsafe-buildfail" ).maven().withFailure().executeVerify().verifyTextInLog( "BUILD FAILURE" ); } } \ No newline at end of file diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire685CommaSeparatedIncludesIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire685CommaSeparatedIncludesIT.java index c58a34d0aa..3d7a684c3f 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire685CommaSeparatedIncludesIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire685CommaSeparatedIncludesIT.java @@ -19,7 +19,8 @@ * under the License. */ -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; +import org.junit.Test; /** * SUREFIRE-685 Asserts that only the specified tests are run with comma separated includes @@ -27,8 +28,9 @@ * @author Kristian Rosenvold */ public class Surefire685CommaSeparatedIncludesIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { + @Test public void testBuildFailingWhenErrors() { executeErrorFreeTest( "/surefire-685-commaseparatedIncludes", 2 ); diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire697NiceSummaryIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire697NiceSummaryIT.java index bc9e62fc98..31751969b6 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire697NiceSummaryIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire697NiceSummaryIT.java @@ -19,7 +19,8 @@ * under the License. */ -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; +import org.junit.Test; /** * SUREFIRE-697 Asserts proper truncation of long exception messages Some say testing this is a bit over the top. @@ -27,11 +28,12 @@ * @author Kristian Rosenvold */ public class Surefire697NiceSummaryIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { + @Test public void testBuildFailingWhenErrors() { unpack( "/surefire-697-niceSummary" ).failNever().executeTest().verifyTextInLog( - "testShortMultiline(junit.surefire697.BasicTest): A very short multiline message" ); + "junit.surefire697.BasicTest#testShortMultiline RuntimeException A very short m" ); } } diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire705ParallelForkTimeoutIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire705ParallelForkTimeoutIT.java index 58f35a9c78..f10c3b73b7 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire705ParallelForkTimeoutIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire705ParallelForkTimeoutIT.java @@ -19,7 +19,8 @@ * under the License. */ -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; +import org.junit.Test; /** * Test @@ -27,11 +28,12 @@ * @author Kristian Rosenvold */ public class Surefire705ParallelForkTimeoutIT - extends SurefireIntegrationTestCase + 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" ).executeTestWithFailure(); + "-Djunit.parallel=classes" ).addGoal( "-DtimeOut=1" ).maven().withFailure().executeTest(); } } diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire733AllOverrridesCapturedIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire733AllOverrridesCapturedIT.java index a35c5d0a56..aabb05da45 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire733AllOverrridesCapturedIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire733AllOverrridesCapturedIT.java @@ -19,14 +19,16 @@ * under the License. */ -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; +import org.junit.Test; /** * @author Kristian Rosenvold */ public class Surefire733AllOverrridesCapturedIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { + @Test public void testLogOutput() { unpack( "surefire-733-allOverridesCaptured" ).executeTest().verifyTextInLog( "abc" ); diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire735ForkFailWithRedirectConsoleOutputIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire735ForkFailWithRedirectConsoleOutputIT.java index a0d8b07932..1d1d2aa340 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire735ForkFailWithRedirectConsoleOutputIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire735ForkFailWithRedirectConsoleOutputIT.java @@ -45,7 +45,7 @@ public void vmStartFail() public void vmStartFailShouldFailBuildk() throws Exception { - unpack().executeTestWithFailure(); + unpack().maven().withFailure().executeTest(); } public SurefireLauncher unpack() diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire740TruncatedCommaIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire740TruncatedCommaIT.java index fa8c9a34a7..e05cee77ef 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire740TruncatedCommaIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire740TruncatedCommaIT.java @@ -20,8 +20,11 @@ */ import org.apache.maven.surefire.its.fixture.OutputValidator; -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +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.assertTrue; /** * Test Surefire-740 Truncated comma with non us locale @@ -29,15 +32,15 @@ * @author Kristian Rosenvold */ public class Surefire740TruncatedCommaIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { + @Test public void testRussianLocaleReport() { - OutputValidator validator = unpack( "/surefire-740-comma-truncated" ).addEnvVar( "MAVEN_OPTS", + OutputValidator validator = unpack( "/surefire-740-comma-truncated" ).setMavenOpts( "-Duser.language=ru -Duser.country=RU" ).failNever().addSurefireReportGoal().executeCurrentGoals(); TestFile siteFile = validator.getSiteFile( "surefire-report.html" ); - System.out.println( "siteFile.getAbsolutePath() = " + siteFile.getAbsolutePath() ); assertTrue( "Expecting file", siteFile.exists() ); siteFile.assertContainsText( "027" ); // Avoid asserting with the "," or "." ;) } diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire747MethodParallelWithSuiteCountIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire747MethodParallelWithSuiteCountIT.java index 3b63983172..35fc601330 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire747MethodParallelWithSuiteCountIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire747MethodParallelWithSuiteCountIT.java @@ -19,21 +19,24 @@ * under the License. */ -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; import org.apache.maven.surefire.its.fixture.SurefireLauncher; +import org.junit.Test; /** * @author Kristian Rosenvold */ public class Surefire747MethodParallelWithSuiteCountIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { + @Test public void testMethodsParallelWithSuite() { unpack().executeTest().verifyErrorFree( 6 ); } + @Test public void testClassesParallelWithSuite() { unpack().parallelClasses().executeTest().verifyErrorFree( 6 ); diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire763EnvironmentForkModeIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire763EnvironmentForkModeIT.java index 2e6d7743c2..37a569cfd1 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire763EnvironmentForkModeIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire763EnvironmentForkModeIT.java @@ -19,7 +19,8 @@ * under the License. */ -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; +import org.junit.Test; /** * SUREFIRE-674 Asserts that the build fails when tests have errors @@ -27,13 +28,15 @@ * @author Kristian Rosenvold */ public class Surefire763EnvironmentForkModeIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { + @Test public void testWhenUseSystemClassLoader() { unpack( "/environment-variables" ).addGoal( "-DuseSystemClassLoader=true" ).executeTest(); } + @Test public void testWhenDontUseSystemClassLoader() { unpack( "/environment-variables" ).addGoal( "-DuseSystemClassLoader=false" ).executeTest(); diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire772BothReportsIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire772BothReportsIT.java index 1c830d1008..96d31c104f 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire772BothReportsIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire772BothReportsIT.java @@ -19,10 +19,11 @@ * under the License. */ -import org.apache.maven.surefire.its.fixture.OutputValidator; -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; -import org.apache.maven.surefire.its.fixture.SurefireLauncher; -import org.apache.maven.surefire.its.fixture.TestFile; +import org.apache.maven.surefire.its.fixture.*; +import org.junit.Test; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; /** * Test Surefire-740 Truncated comma with non us locale @@ -30,14 +31,17 @@ * @author Kristian Rosenvold */ public class Surefire772BothReportsIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { public SurefireLauncher unpack() { - return unpack( "/surefire-772-both-reports" ).deleteSiteDir().addGoal( "-Dclean.skip=true" ).failNever(); + SurefireLauncher unpack = unpack( "/surefire-772-both-reports" ); + unpack.maven().deleteSiteDir().skipClean().failNever(); + return unpack; } + @Test public void testReportGeneration() throws Exception { @@ -45,14 +49,13 @@ public void testReportGeneration() unpack().addFailsafeReportOnlyGoal().addSurefireReportOnlyGoal().executeCurrentGoals(); TestFile siteFile = outputValidator.getSiteFile( "surefire-report.html" ); - System.out.println( "siteFile.getAbsolutePath() = " + siteFile.getAbsolutePath() ); assertTrue( "Expecting surefire report file", siteFile.isFile() ); siteFile = outputValidator.getSiteFile( "failsafe-report.html" ); - System.out.println( "siteFile.getAbsolutePath() = " + siteFile.getAbsolutePath() ); assertTrue( "Expecting failsafe report file", siteFile.isFile() ); } + @Test public void testSkippedFailsafeReportGeneration() throws Exception { @@ -61,14 +64,13 @@ public void testSkippedFailsafeReportGeneration() "skipFailsafe" ).addFailsafeReportOnlyGoal().addSurefireReportOnlyGoal().executeCurrentGoals(); TestFile siteFile = validator.getSiteFile( "surefire-report.html" ); - System.out.println( "siteFile.getAbsolutePath() = " + siteFile.getAbsolutePath() ); assertTrue( "Expecting surefire report file", siteFile.isFile() ); siteFile = validator.getSiteFile( "failsafe-report.html" ); - System.out.println( "siteFile.getAbsolutePath() = " + siteFile.getAbsolutePath() ); assertFalse( "Expecting no failsafe report file", siteFile.isFile() ); } + @Test public void testSkippedSurefireReportGeneration() throws Exception { @@ -77,12 +79,9 @@ public void testSkippedSurefireReportGeneration() "skipSurefire" ).addFailsafeReportOnlyGoal().addSurefireReportOnlyGoal().executeCurrentGoals(); TestFile siteFile = validator.getSiteFile( "surefire-report.html" ); - System.out.println( "siteFile.getAbsolutePath() = " + siteFile.getAbsolutePath() ); assertFalse( "Expecting no surefire report file", siteFile.isFile() ); siteFile = validator.getSiteFile( "failsafe-report.html" ); - System.out.println( "siteFile.getAbsolutePath() = " + siteFile.getAbsolutePath() ); assertTrue( "Expecting failsafe report file", siteFile.isFile() ); } - } diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire772NoFailsafeReportsIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire772NoFailsafeReportsIT.java index 3930133c65..af18336999 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire772NoFailsafeReportsIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire772NoFailsafeReportsIT.java @@ -21,10 +21,11 @@ import java.io.IOException; import org.apache.maven.it.VerificationException; -import org.apache.maven.surefire.its.fixture.OutputValidator; -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; -import org.apache.maven.surefire.its.fixture.SurefireLauncher; -import org.apache.maven.surefire.its.fixture.TestFile; +import org.apache.maven.surefire.its.fixture.*; +import org.junit.Test; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; /** * Test Surefire-740 Truncated comma with non us locale @@ -32,9 +33,10 @@ * @author Kristian Rosenvold */ public class Surefire772NoFailsafeReportsIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { + @Test public void testReportGeneration() throws Exception { @@ -45,6 +47,7 @@ public void testReportGeneration() assertNoFailsefeReport( site ); } + @Test public void testSkippedFailsafeReportGeneration() throws Exception { @@ -55,6 +58,7 @@ public void testSkippedFailsafeReportGeneration() } + @Test public void testForcedFailsafeReportGeneration() throws Exception { @@ -64,6 +68,7 @@ public void testForcedFailsafeReportGeneration() assertFailsafeReport( validator ); } + @Test public void testSkipForcedFailsafeReportGeneration() throws Exception { @@ -96,8 +101,8 @@ private SurefireLauncher unpack() throws VerificationException, IOException { final SurefireLauncher unpack = unpack( "surefire-772-no-failsafe-reports" ); - unpack.deleteSiteDir(); - return unpack.skipClean().failNever().assertNotPresent( "site" ); + unpack.maven().deleteSiteDir().skipClean().failNever().assertNotPresent( "site" ); + return unpack; } } diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire772NoSurefireReportsIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire772NoSurefireReportsIT.java index 89b8ef4bbf..6b59ba2aaf 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire772NoSurefireReportsIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire772NoSurefireReportsIT.java @@ -20,9 +20,13 @@ */ import org.apache.maven.surefire.its.fixture.OutputValidator; -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +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 static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; /** * Test Surefire-740 Truncated comma with non us locale @@ -30,67 +34,65 @@ * @author Kristian Rosenvold */ public class Surefire772NoSurefireReportsIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { + @Test public void testReportGeneration() { OutputValidator validator = unpack().addFailsafeReportOnlyGoal().addSurefireReportOnlyGoal().executeCurrentGoals(); TestFile siteFile = validator.getSiteFile( "surefire-report.html" ); - System.out.println( "siteFile.getAbsolutePath() = " + siteFile.getAbsolutePath() ); assertTrue( "Expecting surefire report file", siteFile.isFile() ); siteFile = validator.getSiteFile( "failsafe-report.html" ); - System.out.println( "siteFile.getAbsolutePath() = " + siteFile.getAbsolutePath() ); assertTrue( "Expecting failsafe report file", siteFile.isFile() ); } + @Test public void testSkippedSurefireReportGeneration() { OutputValidator validator = unpack().activateProfile( "skipSurefire" ).addFailsafeReportOnlyGoal().addSurefireReportOnlyGoal().executeCurrentGoals(); TestFile siteFile = validator.getSiteFile( "surefire-report.html" ); - System.out.println( "siteFile.getAbsolutePath() = " + siteFile.getAbsolutePath() ); assertFalse( "Expecting no surefire report file", siteFile.isFile() ); siteFile = validator.getSiteFile( "failsafe-report.html" ); - System.out.println( "siteFile.getAbsolutePath() = " + siteFile.getAbsolutePath() ); assertTrue( "Expecting failsafe report file", siteFile.isFile() ); } + @Test public void testOptionalSurefireReportGeneration() { OutputValidator validator = unpack().activateProfile( "optionalSurefire" ).addFailsafeReportOnlyGoal().addSurefireReportOnlyGoal().executeCurrentGoals(); TestFile siteFile = validator.getSiteFile( "surefire-report.html" ); - System.out.println( "siteFile.getAbsolutePath() = " + siteFile.getAbsolutePath() ); assertFalse( "Expecting no surefire report file", siteFile.isFile() ); siteFile = validator.getSiteFile( "failsafe-report.html" ); - System.out.println( "siteFile.getAbsolutePath() = " + siteFile.getAbsolutePath() ); 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" ); - System.out.println( "siteFile.getAbsolutePath() = " + siteFile.getAbsolutePath() ); assertFalse( "Expecting no surefire report file", siteFile.isFile() ); siteFile = validator.getSiteFile( "failsafe-report.html" ); - System.out.println( "siteFile.getAbsolutePath() = " + siteFile.getAbsolutePath() ); assertTrue( "Expecting failsafe report file", siteFile.isFile() ); } public SurefireLauncher unpack() { - return unpack( "/surefire-772-no-surefire-reports" ).failNever().deleteSiteDir().addGoal( "-Dclean.skip=true" ); + SurefireLauncher unpack = unpack( "/surefire-772-no-surefire-reports" ); + unpack.maven().failNever().deleteSiteDir().skipClean( ); + return unpack; } } diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire772SpecifiedReportsIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire772SpecifiedReportsIT.java index 00aaa3ed33..a709f7df54 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire772SpecifiedReportsIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire772SpecifiedReportsIT.java @@ -19,10 +19,11 @@ * under the License. */ -import org.apache.maven.surefire.its.fixture.OutputValidator; -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; -import org.apache.maven.surefire.its.fixture.SurefireLauncher; -import org.apache.maven.surefire.its.fixture.TestFile; +import org.apache.maven.surefire.its.fixture.*; +import org.junit.Test; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; /** * Test Surefire-740 Truncated comma with non us locale @@ -30,53 +31,52 @@ * @author Kristian Rosenvold */ public class Surefire772SpecifiedReportsIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { + @Test public void testReportGeneration() { OutputValidator validator = unpack().addFailsafeReportOnlyGoal().addSurefireReportOnlyGoal().executeCurrentGoals(); TestFile siteFile = validator.getSiteFile( "surefire-report.html" ); - System.out.println( "siteFile.getAbsolutePath() = " + siteFile.getAbsolutePath() ); assertTrue( "Expecting surefire report file", siteFile.isFile() ); siteFile = validator.getSiteFile( "failsafe-report.html" ); - System.out.println( "siteFile.getAbsolutePath() = " + siteFile.getAbsolutePath() ); assertTrue( "Expecting failsafe report file", siteFile.isFile() ); } + @Test public void testSkippedFailsafeReportGeneration() { OutputValidator validator = unpack().activateProfile( "skipFailsafe" ).addFailsafeReportOnlyGoal().addSurefireReportOnlyGoal().executeCurrentGoals(); TestFile siteFile = validator.getSiteFile( "surefire-report.html" ); - System.out.println( "siteFile.getAbsolutePath() = " + siteFile.getAbsolutePath() ); assertTrue( "Expecting surefire report file", siteFile.isFile() ); siteFile = validator.getSiteFile( "failsafe-report.html" ); - System.out.println( "siteFile.getAbsolutePath() = " + siteFile.getAbsolutePath() ); assertFalse( "Expecting no failsafe report file", siteFile.isFile() ); } + @Test public void testSkippedSurefireReportGeneration() { OutputValidator validator = unpack().activateProfile( "skipSurefire" ).addFailsafeReportOnlyGoal().addSurefireReportOnlyGoal().executeCurrentGoals(); TestFile siteFile = validator.getSiteFile( "surefire-report.html" ); - System.out.println( "siteFile.getAbsolutePath() = " + siteFile.getAbsolutePath() ); assertFalse( "Expecting no surefire report file", siteFile.isFile() ); siteFile = validator.getSiteFile( "failsafe-report.html" ); - System.out.println( "siteFile.getAbsolutePath() = " + siteFile.getAbsolutePath() ); assertTrue( "Expecting failsafe report file", siteFile.isFile() ); } public SurefireLauncher unpack() { - return unpack( "/surefire-772-specified-reports" ).deleteSiteDir().addGoal( "-Dclean.skip=true" ).failNever(); + SurefireLauncher unpack = unpack( "/surefire-772-specified-reports" ); + unpack.maven().deleteSiteDir().skipClean().failNever(); + return unpack; } } diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire801ForkModeNoneClassLoaderIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire801ForkModeNoneClassLoaderIT.java index 52e6a12490..910cfc5927 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire801ForkModeNoneClassLoaderIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire801ForkModeNoneClassLoaderIT.java @@ -19,7 +19,8 @@ * under the License. */ -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; +import org.junit.Test; /** * Test @@ -27,8 +28,9 @@ * @author Kristian Rosenvold */ public class Surefire801ForkModeNoneClassLoaderIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { + @Test public void testSHouldBeOkWithForkNever() { unpack( "fork-mode-resource-loading" ).forkNever().executeTest(); diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire803MultiFailsafeExecsIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire803MultiFailsafeExecsIT.java index bf4d836e7e..658befd04d 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire803MultiFailsafeExecsIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire803MultiFailsafeExecsIT.java @@ -18,26 +18,30 @@ * under the License. */ -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; import org.apache.maven.surefire.its.fixture.SurefireLauncher; +import org.junit.Test; public class Surefire803MultiFailsafeExecsIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { + @Test public void testSecondExecutionRunsAfterFirstExecutionFails() { unpack( - "/surefire-803-multiFailsafeExec-failureInFirst" ).executeVerifyWithFailure().assertIntegrationTestSuiteResults( + "/surefire-803-multiFailsafeExec-failureInFirst" ).maven().withFailure().executeVerify().assertIntegrationTestSuiteResults( 4, 0, 2, 0 ); } + @Test public void testOneExecutionRunInTwoBuilds() { SurefireLauncher launcher = unpack( "/surefire-803-multiFailsafeExec-rebuildOverwrites" ); - launcher.addD( "success", "false" ).executeVerifyWithFailure().assertIntegrationTestSuiteResults( 1, 0, 1, 0 ); + launcher.sysProp( "success", "false" ).maven().withFailure().executeVerify().assertIntegrationTestSuiteResults( + 1, 0, 1, 0 ); launcher.reset(); - launcher.addD( "success", "true" ).executeVerify().assertIntegrationTestSuiteResults( 1, 0, 0, 0 ); + launcher.sysProp( "success", "true" ).executeVerify().assertIntegrationTestSuiteResults( 1, 0, 0, 0 ); } } diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire809GroupExpressionsIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire809GroupExpressionsIT.java index 679b266297..5ab103bfbc 100755 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire809GroupExpressionsIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire809GroupExpressionsIT.java @@ -46,7 +46,7 @@ public void categoryAB() public void incorrectJUnitVersions() { unpackJUnit().setJUnitVersion( "4.5" ).groups( - "junit4.CategoryA AND junit4.CategoryB" ).executeTestWithFailure(); + "junit4.CategoryA AND junit4.CategoryB" ).maven().withFailure().executeTest(); } @Test diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire812Log4JClassLoaderIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire812Log4JClassLoaderIT.java index fc49322000..065ec19f9d 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire812Log4JClassLoaderIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire812Log4JClassLoaderIT.java @@ -19,14 +19,16 @@ * under the License. */ -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; +import org.junit.Test; /** * @author Kristian Rosenvold */ public class Surefire812Log4JClassLoaderIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { + @Test public void testJunit3ParallelBuildResultCount() { executeErrorFreeTest( "surefire-812-log4j-classloader", 1 ); diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire818NpeIgnoresTestsIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire818NpeIgnoresTestsIT.java index c8221c78d8..1bf4c8dcc1 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire818NpeIgnoresTestsIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire818NpeIgnoresTestsIT.java @@ -19,7 +19,8 @@ * under the License. */ -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; +import org.junit.Test; /** * SUREFIRE-818 @@ -27,10 +28,12 @@ * @author Kristian Rosenvold */ public class Surefire818NpeIgnoresTestsIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { + @Test public void testBuildFailingWhenErrors() { - unpack( "surefire-818-ignored-tests-on-npe" ).executeTestWithFailure().assertTestSuiteResults( 2, 0, 1, 0 ); + unpack( "surefire-818-ignored-tests-on-npe" ).maven().withFailure().executeTest().assertTestSuiteResults( 2, 0, + 1, 0 ); } } diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire828EmptyGroupExprIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire828EmptyGroupExprIT.java index 60f73e6d5c..b59bc6a7b9 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire828EmptyGroupExprIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire828EmptyGroupExprIT.java @@ -19,16 +19,18 @@ */ import org.apache.maven.surefire.its.fixture.OutputValidator; -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; import org.apache.maven.surefire.its.fixture.SurefireLauncher; +import org.junit.Test; public class Surefire828EmptyGroupExprIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { // !CategoryC + @Test public void testJUnitRunEmptyGroups() { - OutputValidator validator = unpackJUnit().addD( "profile", "emptyGroups" ).executeTest(); + OutputValidator validator = unpackJUnit().sysProp( "profile", "emptyGroups" ).executeTest(); validator.verifyErrorFreeLog(); validator.assertTestSuiteResults( 5, 0, 0, 0 ); validator.verifyTextInLog( "catA: 2" ); @@ -39,9 +41,10 @@ public void testJUnitRunEmptyGroups() } // CategoryA && CategoryB + @Test public void testJUnitRunEmptyExcludeGroups() { - OutputValidator validator = unpackJUnit().addD( "profile", "emptyExcludedGroups" ).executeTest(); + OutputValidator validator = unpackJUnit().sysProp( "profile", "emptyExcludedGroups" ).executeTest(); validator.verifyErrorFreeLog(); validator.assertTestSuiteResults( 2, 0, 0, 0 ); validator.verifyTextInLog( "catA: 1" ); @@ -54,9 +57,10 @@ public void testJUnitRunEmptyExcludeGroups() } // CategoryA && CategoryB + @Test public void testTestNGRunEmptyExcludeGroups() { - OutputValidator validator = unpackTestNG().addD( "profile", "emptyExcludedGroups" ).executeTest(); + OutputValidator validator = unpackTestNG().sysProp( "profile", "emptyExcludedGroups" ).executeTest(); validator.verifyErrorFreeLog(); validator.assertTestSuiteResults( 2, 0, 0, 0 ); validator.verifyTextInLog( "BasicTest.testInCategoriesAB()" ); @@ -64,9 +68,10 @@ public void testTestNGRunEmptyExcludeGroups() } // !CategoryC + @Test public void testTestNGRunEmptyGroups() { - OutputValidator validator = unpackTestNG().addD( "profile", "emptyGroups" ).executeTest(); + OutputValidator validator = unpackTestNG().sysProp( "profile", "emptyGroups" ).executeTest(); validator.verifyErrorFreeLog(); validator.assertTestSuiteResults( 8, 0, 0, 0 ); validator.verifyTextInLog( "catA: 2" ); diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire832ProviderSelectionIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire832ProviderSelectionIT.java index d5b05502c3..c694a3d223 100755 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire832ProviderSelectionIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire832ProviderSelectionIT.java @@ -19,12 +19,14 @@ */ import org.apache.maven.surefire.its.fixture.OutputValidator; -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; import org.apache.maven.surefire.its.fixture.SurefireLauncher; +import org.junit.Test; public class Surefire832ProviderSelectionIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { + @Test public void testJUnitRunCategoryAB() { OutputValidator validator = unpackJUnit().groups( "junit4.CategoryA AND junit4.CategoryB" ).executeTest(); diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire847AdditionalFailureIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire847AdditionalFailureIT.java index 85d035b205..f267ee87c4 100755 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire847AdditionalFailureIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire847AdditionalFailureIT.java @@ -18,11 +18,13 @@ * under the License. */ -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; +import org.junit.Test; public class Surefire847AdditionalFailureIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { + @Test public void testJUnitRunCategoryAB() { unpack( "surefire-847-testngfail" ).setTestToRun( diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire907PerThreadWithoutThreadCountIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire907PerThreadWithoutThreadCountIT.java index 1fd9ea8a7a..96e913c06c 100755 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire907PerThreadWithoutThreadCountIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire907PerThreadWithoutThreadCountIT.java @@ -29,8 +29,8 @@ public class Surefire907PerThreadWithoutThreadCountIT @Test public void categoryAB() { - OutputValidator validator = unpack( "fork-mode" ).forkPerThread().executeTestWithFailure(); - validator.verifyTextInLog( "Fork modes perthread and onceperthread require a thread count" ); + OutputValidator validator = unpack( "fork-mode" ).forkPerThread().maven().withFailure().executeTest(); + validator.verifyTextInLog( "Fork mode perthread requires a thread count" ); } } diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire920TestFailureIgnoreWithTimeoutIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire920TestFailureIgnoreWithTimeoutIT.java index 2b9d661942..4f608950a9 100755 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire920TestFailureIgnoreWithTimeoutIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire920TestFailureIgnoreWithTimeoutIT.java @@ -29,7 +29,8 @@ public class Surefire920TestFailureIgnoreWithTimeoutIT @Test public void timeoutInForkWithBuildFail() { - OutputValidator validator = unpack( "fork-timeout" ).addD( "junit.parallel", "none" ).executeTestWithFailure(); + OutputValidator validator = + unpack( "fork-timeout" ).sysProp( "junit.parallel", "none" ).maven().withFailure().executeTest(); validator.verifyTextInLog( "There was a timeout or other error in the fork" ); } @@ -37,8 +38,7 @@ public void timeoutInForkWithBuildFail() public void timeoutInForkWithNoBuildFail() { OutputValidator validator = - unpack( "fork-timeout" ).addD( "junit.parallel", "none" ).addD( "maven.test.failure.ignore", - "true" ).executeTest(); + unpack( "fork-timeout" ).sysProp( "junit.parallel", "none" ).mavenTestFailureIgnore( true ).executeTest(); validator.verifyTextInLog( "[ERROR] There was a timeout or other error in the fork" ); } diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire926FailureWith2ProvidersIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire926FailureWith2ProvidersIT.java index 7b3371d77d..e6f9dc6436 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire926FailureWith2ProvidersIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire926FailureWith2ProvidersIT.java @@ -19,16 +19,18 @@ * under the License. */ -import org.apache.maven.surefire.its.fixture.SurefireIntegrationTestCase; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; +import org.junit.Test; /** * @author Kristian Rosenvold */ public class Surefire926FailureWith2ProvidersIT - extends SurefireIntegrationTestCase + extends SurefireJUnit4IntegrationTestCase { + @Test public void testBuildFailingWhenErrors() { - unpack( "surefire-926-2-provider-failure" ).executeTestWithFailure(); + unpack( "surefire-926-2-provider-failure" ).maven().withFailure().executeTest(); } } \ No newline at end of file diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire930TestNgSuiteXmlIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire930TestNgSuiteXmlIT.java index 69fe428dfd..5963662b2e 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire930TestNgSuiteXmlIT.java +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire930TestNgSuiteXmlIT.java @@ -29,8 +29,9 @@ public class Surefire930TestNgSuiteXmlIT @Test public void suiteXmlRun() { - unpack( "surefire-930-failsafe-runtests" ).executeVerifyWithFailure().assertIntegrationTestSuiteResults( 1, 0, - 1, 0 ); + unpack( + "surefire-930-failsafe-runtests" ).maven().withFailure().executeVerify().assertIntegrationTestSuiteResults( + 1, 0, 1, 0 ); } } diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire943ReportContentIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire943ReportContentIT.java new file mode 100644 index 0000000000..fe72087211 --- /dev/null +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire943ReportContentIT.java @@ -0,0 +1,131 @@ +package org.apache.maven.surefire.its.jiras; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES 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.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; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; + +import org.junit.Assert; +import org.junit.Test; + +public class Surefire943ReportContentIT + extends SurefireJUnit4IntegrationTestCase +{ + + @Test + public void test_noParallel() + throws Exception + { + doTest( "none" ); + } + + @Test + 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 ).withFailure().executeTest(); + validator.assertTestSuiteResults( 9, 0, 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" ); + } + + private void validateSkipped( OutputValidator validator, String className ) + throws FileNotFoundException + { + Xpp3Dom[] children = readTests( validator, className ); + + Assert.assertEquals( 1, children.length ); + + Xpp3Dom child = children[0]; + + Assert.assertEquals( className, child.getAttribute( "classname" ) ); + Assert.assertEquals( className, child.getAttribute( "name" ) ); + + Assert.assertEquals( "Expected skipped tag for ignored method for " + className, 1, + child.getChildren( "skipped" ).length ); + + Assert.assertTrue( "time for ignored test is expected to be zero", + 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.assertTrue( "time for ignored test is expected to be zero", + Double.compare( Double.parseDouble( child.getAttribute( "time" ) ), 0.0d ) == 0 ); + + } + 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" ); + Xpp3Dom[] children = testResult.getChildren( "testcase" ); + return children; + } + +} diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire946KillMainProcessInReusableForkIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire946KillMainProcessInReusableForkIT.java new file mode 100644 index 0000000000..bef2378fad --- /dev/null +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire946KillMainProcessInReusableForkIT.java @@ -0,0 +1,71 @@ +package org.apache.maven.surefire.its.jiras; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR 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.its.fixture.SurefireJUnit4IntegrationTestCase; +import org.junit.BeforeClass; +import org.junit.Test; + +public class Surefire946KillMainProcessInReusableForkIT + extends SurefireJUnit4IntegrationTestCase +{ + + // there are 10 test classes that each would wait 2 seconds. + private static final int TEST_SLEEP_TIME = 2000; + + @BeforeClass + public static void installSelfdestructPlugin() + throws Exception + { + unpack( Surefire946KillMainProcessInReusableForkIT.class, "surefire-946-self-destruct-plugin", "plugin" ).executeInstall(); + } + + @Test( timeout = 30000 ) + public void testHalt() + throws Exception + { + doTest( "halt" ); + } + + @Test( timeout = 30000 ) + public void testExit() + throws Exception + { + doTest( "exit" ); + } + + @Test( timeout = 30000 ) + public void testInterrupt() + throws Exception + { + doTest( "interrupt" ); + } + + private void doTest( String method ) + { + unpack( "surefire-946-killMainProcessInReusableFork" ) + .sysProp( "selfdestruct.timeoutInMillis", "5000" ) + .sysProp( "selfdestruct.method", method ) + .sysProp( "testSleepTime", String.valueOf( TEST_SLEEP_TIME ) ) + .addGoal( "org.apache.maven.plugins.surefire:maven-selfdestruct-plugin:selfdestruct" ) + .setForkJvm() + .forkOncePerThread().threadCount( 1 ).maven().withFailure().executeTest(); + } +} diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire972BizarreNoClassDefIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire972BizarreNoClassDefIT.java new file mode 100644 index 0000000000..94db9f89ed --- /dev/null +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire972BizarreNoClassDefIT.java @@ -0,0 +1,32 @@ +package org.apache.maven.surefire.its.jiras; + +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; +import org.junit.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. + */ +public class Surefire972BizarreNoClassDefIT + extends SurefireJUnit4IntegrationTestCase +{ + @Test + public void testJunit3ParallelBuildResultCount() + { + unpack( "surefire-972-bizarre-noclassdef" ).maven().withFailure().executeVerify(); + } +} diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire975DefaultVMEncodingIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire975DefaultVMEncodingIT.java new file mode 100644 index 0000000000..0f30dbc77c --- /dev/null +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire975DefaultVMEncodingIT.java @@ -0,0 +1,40 @@ +package org.apache.maven.surefire.its.jiras; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR 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.its.fixture.OutputValidator; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; +import org.junit.Test; + +public class Surefire975DefaultVMEncodingIT + extends SurefireJUnit4IntegrationTestCase +{ + + @Test + public void runWithRussian1251() + throws Exception + { + OutputValidator outputValidator = + unpack( "surefire-975-wrong-encoding" ).setMavenOpts( "-Dfile.encoding=windows-1251" ).executeTest(); + outputValidator.getSurefireReportsXmlFile( "TEST-EncodingInReportTest.xml" ).assertContainsText( + "\u043A\u0438\u0440\u0438\u043B\u043B\u0438\u0446\u0435" ); + } + +} diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire979WrongClassLoaderIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire979WrongClassLoaderIT.java new file mode 100644 index 0000000000..d6485769cc --- /dev/null +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire979WrongClassLoaderIT.java @@ -0,0 +1,39 @@ +package org.apache.maven.surefire.its.jiras; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR 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.its.fixture.OutputValidator; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; +import org.junit.Test; + +public class Surefire979WrongClassLoaderIT + extends SurefireJUnit4IntegrationTestCase +{ + + @Test + public void wrongClassloaderUSedInSmartStacktraceparser() + throws Exception + { + OutputValidator outputValidator = + unpack( "surefire-979-smartStackTrace-wrongClassloader" ).failNever().executeTest(); + outputValidator.verifyTextInLog( "java.lang.NoClassDefFoundError: org/apache/commons/io/input/AutoCloseInputStream" ); + } + +} diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire985ParameterizedRunnerAndCategoriesIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire985ParameterizedRunnerAndCategoriesIT.java new file mode 100644 index 0000000000..b86b2918b8 --- /dev/null +++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/jiras/Surefire985ParameterizedRunnerAndCategoriesIT.java @@ -0,0 +1,68 @@ +package org.apache.maven.surefire.its.jiras; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES 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.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; +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.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +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 ); + + 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 ); + + } + + 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-integration-tests/src/test/resources/additional-classpath/pom.xml b/surefire-integration-tests/src/test/resources/additional-classpath/pom.xml index 6356b9be82..f383597049 100644 --- a/surefire-integration-tests/src/test/resources/additional-classpath/pom.xml +++ b/surefire-integration-tests/src/test/resources/additional-classpath/pom.xml @@ -23,6 +23,14 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 + + + org.apache.maven.surefire + it-parent + 1.0 + ../pom.xml + + org.apache.maven.plugins.surefire additional-classpath 1.0-SNAPSHOT @@ -32,12 +40,13 @@ maven-surefire-plugin - ${surefire.version} ${basedir}/extraResource - ${abc} - + ${abc} + + + diff --git a/surefire-integration-tests/src/test/resources/aggregate-report/child1/pom.xml b/surefire-integration-tests/src/test/resources/aggregate-report/child1/pom.xml index db5f4f546d..b28ab6476e 100644 --- a/surefire-integration-tests/src/test/resources/aggregate-report/child1/pom.xml +++ b/surefire-integration-tests/src/test/resources/aggregate-report/child1/pom.xml @@ -22,10 +22,14 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 - - org.apache.maven.plugins.surefire + + + org.apache.maven.plugins.surefire + aggregate-report + 1.0-SNAPSHOT + + aggregate-child1 - 1.0-SNAPSHOT child1 for aggregate-reports diff --git a/surefire-integration-tests/src/test/resources/aggregate-report/child2/pom.xml b/surefire-integration-tests/src/test/resources/aggregate-report/child2/pom.xml index bf09d15b2d..35dee50e20 100644 --- a/surefire-integration-tests/src/test/resources/aggregate-report/child2/pom.xml +++ b/surefire-integration-tests/src/test/resources/aggregate-report/child2/pom.xml @@ -23,9 +23,13 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 - org.apache.maven.plugins.surefire + + org.apache.maven.plugins.surefire + aggregate-report + 1.0-SNAPSHOT + + aggregate-child2 - 1.0-SNAPSHOT child2 for aggregate-reports diff --git a/surefire-integration-tests/src/test/resources/aggregate-report/pom.xml b/surefire-integration-tests/src/test/resources/aggregate-report/pom.xml index 7b659128a9..631ca7cc23 100644 --- a/surefire-integration-tests/src/test/resources/aggregate-report/pom.xml +++ b/surefire-integration-tests/src/test/resources/aggregate-report/pom.xml @@ -23,6 +23,13 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 + + org.apache.maven.surefire + it-parent + 1.0 + ../pom.xml + + org.apache.maven.plugins.surefire aggregate-report 1.0-SNAPSHOT @@ -32,24 +39,25 @@ child1 child2 - + - - - maven-surefire-plugin - ${surefire.version} - - true - - - + + + + maven-surefire-plugin + ${surefire.version} + + true + + + + maven-surefire-report-plugin - ${surefire.version} true diff --git a/surefire-integration-tests/src/test/resources/ant-ignore/.gitignore b/surefire-integration-tests/src/test/resources/ant-ignore/.gitignore index 1f82a8b6e4..2d7276b9ef 100644 --- a/surefire-integration-tests/src/test/resources/ant-ignore/.gitignore +++ b/surefire-integration-tests/src/test/resources/ant-ignore/.gitignore @@ -1,3 +1,3 @@ -*.jar -TEST* - +*.jar +TEST* + diff --git a/surefire-integration-tests/src/test/resources/ant-ignore/build.xml b/surefire-integration-tests/src/test/resources/ant-ignore/build.xml index 0ef0cfee4e..69795d002d 100644 --- a/surefire-integration-tests/src/test/resources/ant-ignore/build.xml +++ b/surefire-integration-tests/src/test/resources/ant-ignore/build.xml @@ -1,52 +1,52 @@ - - - simple example build file - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + simple example build file + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/surefire-integration-tests/src/test/resources/ant-ignore/ivy.xml b/surefire-integration-tests/src/test/resources/ant-ignore/ivy.xml index d350225f6d..64df19cf19 100644 --- a/surefire-integration-tests/src/test/resources/ant-ignore/ivy.xml +++ b/surefire-integration-tests/src/test/resources/ant-ignore/ivy.xml @@ -1,6 +1,6 @@ - - - - - - + + + + + + diff --git a/surefire-integration-tests/src/test/resources/ant-ignore/pom.xml b/surefire-integration-tests/src/test/resources/ant-ignore/pom.xml index cc9643f84e..3cc74a17d2 100644 --- a/surefire-integration-tests/src/test/resources/ant-ignore/pom.xml +++ b/surefire-integration-tests/src/test/resources/ant-ignore/pom.xml @@ -23,6 +23,14 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 + + + org.apache.maven.surefire + it-parent + 1.0 + ../pom.xml + + org.apache.maven.plugins.surefire ant-ignore 1.0-SNAPSHOT @@ -36,23 +44,4 @@ test - - - - - org.apache.maven.plugins - maven-compiler-plugin - - 1.5 - 1.5 - - - - maven-surefire-plugin - ${surefire.version} - - - - - diff --git a/surefire-integration-tests/src/test/resources/ant-ignore/src/ivy.xml b/surefire-integration-tests/src/test/resources/ant-ignore/src/ivy.xml index d350225f6d..64df19cf19 100644 --- a/surefire-integration-tests/src/test/resources/ant-ignore/src/ivy.xml +++ b/surefire-integration-tests/src/test/resources/ant-ignore/src/ivy.xml @@ -1,6 +1,6 @@ - - - - - - + + + + + + diff --git a/surefire-integration-tests/src/test/resources/ant-ignore/src/test/java/antignore/BasicTest.java b/surefire-integration-tests/src/test/resources/ant-ignore/src/test/java/antignore/BasicTest.java index 8a703085f5..487427a07a 100644 --- a/surefire-integration-tests/src/test/resources/ant-ignore/src/test/java/antignore/BasicTest.java +++ b/surefire-integration-tests/src/test/resources/ant-ignore/src/test/java/antignore/BasicTest.java @@ -1,13 +1,13 @@ package antignore; -import junit.framework.TestCase; import org.junit.Assert; -import org.junit.Test; import org.junit.Ignore; +import org.junit.Test; public class BasicTest { + @Test @Ignore public void testIgnorable() { diff --git a/surefire-integration-tests/src/test/resources/argLine-parameter/pom.xml b/surefire-integration-tests/src/test/resources/argLine-parameter/pom.xml index 82734b1dc5..2eed551052 100644 --- a/surefire-integration-tests/src/test/resources/argLine-parameter/pom.xml +++ b/surefire-integration-tests/src/test/resources/argLine-parameter/pom.xml @@ -23,6 +23,14 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 + + + org.apache.maven.surefire + it-parent + 1.0 + ../pom.xml + + org.apache.maven.plugins.surefire testArgLine 1.0-SNAPSHOT @@ -42,8 +50,8 @@ org.apache.maven.plugins maven-surefire-plugin - ${surefire.version} + once -Dfoo.property="foo foo/foo/bar/1.0" -Dbar.property="bar bar/foo/bar/2.0" diff --git a/surefire-integration-tests/src/test/resources/classpath-filtering/pom.xml b/surefire-integration-tests/src/test/resources/classpath-filtering/pom.xml index 50bd6866ca..6b16431bd6 100644 --- a/surefire-integration-tests/src/test/resources/classpath-filtering/pom.xml +++ b/surefire-integration-tests/src/test/resources/classpath-filtering/pom.xml @@ -23,6 +23,13 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 + + org.apache.maven.surefire + it-parent + 1.0 + ../pom.xml + + org.apache.maven.plugins.surefire classpath-dependency-filter 1.0-SNAPSHOT @@ -32,7 +39,6 @@ maven-surefire-plugin - ${surefire.version} org.apache.commons:* diff --git a/surefire-integration-tests/src/test/resources/classpath-order/pom.xml b/surefire-integration-tests/src/test/resources/classpath-order/pom.xml index 8209e6e8bc..a72c2f52d4 100644 --- a/surefire-integration-tests/src/test/resources/classpath-order/pom.xml +++ b/surefire-integration-tests/src/test/resources/classpath-order/pom.xml @@ -23,6 +23,14 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 + + + org.apache.maven.surefire + it-parent + 1.0 + ../pom.xml + + org.apache.maven.plugins.surefire classpath-order 1.0-SNAPSHOT @@ -32,7 +40,6 @@ maven-surefire-plugin - ${surefire.version} true diff --git a/surefire-integration-tests/src/test/resources/classpath-scope-filtering/pom.xml b/surefire-integration-tests/src/test/resources/classpath-scope-filtering/pom.xml index 97f9961b27..84789c5c3e 100644 --- a/surefire-integration-tests/src/test/resources/classpath-scope-filtering/pom.xml +++ b/surefire-integration-tests/src/test/resources/classpath-scope-filtering/pom.xml @@ -23,6 +23,13 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 + + org.apache.maven.surefire + it-parent + 1.0 + ../pom.xml + + org.apache.maven.plugins.surefire classpath-scope-filter 1.0-SNAPSHOT @@ -32,7 +39,6 @@ maven-surefire-plugin - ${surefire.version} compile diff --git a/surefire-integration-tests/src/test/resources/concurrentjunit47/pom.xml b/surefire-integration-tests/src/test/resources/concurrentjunit47/pom.xml index bbc65d0c95..ab4a7fb9c5 100644 --- a/surefire-integration-tests/src/test/resources/concurrentjunit47/pom.xml +++ b/surefire-integration-tests/src/test/resources/concurrentjunit47/pom.xml @@ -23,6 +23,14 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 + + + org.apache.maven.surefire + it-parent + 1.0 + ../pom.xml + + org.apache.maven.plugins.surefire junit47 1.0-SNAPSHOT @@ -44,18 +52,9 @@ - - org.apache.maven.plugins - maven-compiler-plugin - - 1.5 - 1.5 - - org.apache.maven.plugins maven-surefire-plugin - ${surefire.version} methods 2 diff --git a/surefire-integration-tests/src/test/resources/consoleOutput/pom.xml b/surefire-integration-tests/src/test/resources/consoleOutput/pom.xml index 69e4e28354..b19dbd2438 100644 --- a/surefire-integration-tests/src/test/resources/consoleOutput/pom.xml +++ b/surefire-integration-tests/src/test/resources/consoleOutput/pom.xml @@ -1,5 +1,13 @@ + + + org.apache.maven.surefire + it-parent + 1.0 + ../pom.xml + + 4.0.0 org.apache.maven.plugins.surefire consoleOutputTest @@ -17,18 +25,9 @@ - - org.apache.maven.plugins - maven-compiler-plugin - - 1.5 - 1.5 - - org.apache.maven.plugins maven-surefire-plugin - ${surefire.version} ${forkMode} ${printSummary} diff --git a/surefire-integration-tests/src/test/resources/consoleoutput-noisy/pom.xml b/surefire-integration-tests/src/test/resources/consoleoutput-noisy/pom.xml index 46382e8c11..192134a0fb 100644 --- a/surefire-integration-tests/src/test/resources/consoleoutput-noisy/pom.xml +++ b/surefire-integration-tests/src/test/resources/consoleoutput-noisy/pom.xml @@ -1,5 +1,14 @@ + + + + org.apache.maven.surefire + it-parent + 1.0 + ../pom.xml + + 4.0.0 org.apache.maven.plugins.surefire fork-consoleOutput-noisy @@ -17,18 +26,9 @@ - - org.apache.maven.plugins - maven-compiler-plugin - - 1.5 - 1.5 - - org.apache.maven.plugins maven-surefire-plugin - ${surefire.version} ${forkMode} ${printSummary} diff --git a/surefire-integration-tests/src/test/resources/consoleoutput-noisy/src/test/java/consoleoutput_noisy/Test1.java b/surefire-integration-tests/src/test/resources/consoleoutput-noisy/src/test/java/consoleoutput_noisy/Test1.java index 8f43d530e1..4b5a21f2fe 100644 --- a/surefire-integration-tests/src/test/resources/consoleoutput-noisy/src/test/java/consoleoutput_noisy/Test1.java +++ b/surefire-integration-tests/src/test/resources/consoleoutput-noisy/src/test/java/consoleoutput_noisy/Test1.java @@ -20,15 +20,16 @@ */ import junit.framework.TestCase; -import org.junit.AfterClass; -import org.junit.BeforeClass; public class Test1 extends TestCase { + + public static final int thousand = Integer.parseInt( System.getProperty( "thousand", "1000" ) ); + public void test1MillionBytes() { - for ( int i = 0; i < 10000; i++ ) + for ( int i = 0; i < ( 10 * thousand ); i++ ) { System.out.println( "0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789" ); @@ -37,7 +38,7 @@ public void test1MillionBytes() public static void testHundredThousand() { - for ( int i = 0; i < 1000; i++ ) + for ( int i = 0; i < thousand; i++ ) { System.out.println( "AAAAAAAAAABBBBBBBBBBCCCCCCCCCCDDDDDDDDDDEEEEEEEEEEFFFFFFFFFFGGGGGGGGGGHHHHHHHHHHIIIIIIIIIIJJJJJJJJJJ" ); @@ -46,7 +47,7 @@ public static void testHundredThousand() public static void testAnotherHundredThousand() { - for ( int i = 0; i < 1000; i++ ) + for ( int i = 0; i < thousand; i++ ) { System.out.println( "AAAAAAAAAABBBBBBBBBBCCCCCCCCCCDDDDDDDDDDEEEEEEEEEEFFFFFFFFFFGGGGGGGGGGHHHHHHHHHHIIIIIIIIIIJJJJJJJJJJ" ); diff --git a/surefire-integration-tests/src/test/resources/consoleoutput-noisy/src/test/java/consoleoutput_noisy/Test2.java b/surefire-integration-tests/src/test/resources/consoleoutput-noisy/src/test/java/consoleoutput_noisy/Test2.java index 06b7418858..10f607fe6b 100644 --- a/surefire-integration-tests/src/test/resources/consoleoutput-noisy/src/test/java/consoleoutput_noisy/Test2.java +++ b/surefire-integration-tests/src/test/resources/consoleoutput-noisy/src/test/java/consoleoutput_noisy/Test2.java @@ -20,15 +20,13 @@ */ import junit.framework.TestCase; -import org.junit.AfterClass; -import org.junit.BeforeClass; public class Test2 extends TestCase { public void test2MillionBytes() { - for ( int i = 0; i < 10000; i++ ) + for ( int i = 0; i < 20 * Test1.thousand; i++ ) { System.out.println( "0-2-3-6-8-012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789" ); @@ -37,7 +35,7 @@ public void test2MillionBytes() public static void testHundredThousand() { - for ( int i = 0; i < 1000; i++ ) + for ( int i = 0; i < Test1.thousand; i++ ) { System.out.println( "A-A-3-A-A-BBBBBBBBBBCCCCCCCCCCDDDDDDDDDDEEEEEEEEEEFFFFFFFFFFGGGGGGGGGGHHHHHHHHHHIIIIIIIIIIJJJJJJJJJJ" ); @@ -46,7 +44,7 @@ public static void testHundredThousand() public static void testAnotherHundredThousand() { - for ( int i = 0; i < 1000; i++ ) + for ( int i = 0; i < Test1.thousand; i++ ) { System.out.println( "A-A-A-3-3-ABBBBBBBBBCCCCCCCCCCDDDDDDDDDDEEEEEEEEEEFFFFFFFFFFGGGGGGGGGGHHHHHHHHHHIIIIIIIIIIJJJJJJJJJJ" ); diff --git a/surefire-integration-tests/src/test/resources/crash-detection/pom.xml b/surefire-integration-tests/src/test/resources/crash-detection/pom.xml index e6c22f0bcd..92a1e5f3de 100644 --- a/surefire-integration-tests/src/test/resources/crash-detection/pom.xml +++ b/surefire-integration-tests/src/test/resources/crash-detection/pom.xml @@ -21,8 +21,14 @@ - 4.0.0 + + org.apache.maven.surefire + it-parent + 1.0 + ../pom.xml + + 4.0.0 org.apache.maven.plugins.surefire crash-detection 1.0-SNAPSHOT @@ -36,19 +42,14 @@ test - + maven-surefire-plugin ${surefire.version} - - - org.apache.maven.plugins - maven-compiler-plugin - 1.5 - 1.5 + once diff --git a/surefire-integration-tests/src/test/resources/crash-detection/src/test/java/junit44/environment/BasicTest.java b/surefire-integration-tests/src/test/resources/crash-detection/src/test/java/junit44/environment/BasicTest.java index d6f0155f8f..c2157dcda0 100644 --- a/surefire-integration-tests/src/test/resources/crash-detection/src/test/java/junit44/environment/BasicTest.java +++ b/surefire-integration-tests/src/test/resources/crash-detection/src/test/java/junit44/environment/BasicTest.java @@ -15,7 +15,13 @@ public void testNothing() @AfterClass public static void killTheVm(){ - System.exit( 0 ); + if ( Boolean.getBoolean( "killHard" )) + { + Runtime.getRuntime().halt( 0 ); + } + else { + System.exit( 0 ); + } } } diff --git a/surefire-integration-tests/src/test/resources/default-configuration-abstract/pom.xml b/surefire-integration-tests/src/test/resources/default-configuration-abstract/pom.xml index d4a2de7385..2d24d313d9 100644 --- a/surefire-integration-tests/src/test/resources/default-configuration-abstract/pom.xml +++ b/surefire-integration-tests/src/test/resources/default-configuration-abstract/pom.xml @@ -23,6 +23,14 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 + + + org.apache.maven.surefire + it-parent + 1.0 + ../pom.xml + + org.apache.maven.plugins.surefire default-configuration-abstract 1.0-SNAPSHOT @@ -36,14 +44,4 @@ test - - - - - maven-surefire-plugin - ${surefire.version} - - - - diff --git a/surefire-integration-tests/src/test/resources/default-configuration-classWithNoTests/pom.xml b/surefire-integration-tests/src/test/resources/default-configuration-classWithNoTests/pom.xml index 54d1bb27f8..9d2f6824f6 100644 --- a/surefire-integration-tests/src/test/resources/default-configuration-classWithNoTests/pom.xml +++ b/surefire-integration-tests/src/test/resources/default-configuration-classWithNoTests/pom.xml @@ -23,6 +23,14 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 + + + org.apache.maven.surefire + it-parent + 1.0 + ../pom.xml + + org.apache.maven.plugins.surefire default-configuration-classWithNoTests 1.0-SNAPSHOT @@ -36,14 +44,4 @@ test - - - - - maven-surefire-plugin - ${surefire.version} - - - - diff --git a/surefire-integration-tests/src/test/resources/default-configuration-noTests/pom.xml b/surefire-integration-tests/src/test/resources/default-configuration-noTests/pom.xml index f51da5a59f..453130ffa5 100644 --- a/surefire-integration-tests/src/test/resources/default-configuration-noTests/pom.xml +++ b/surefire-integration-tests/src/test/resources/default-configuration-noTests/pom.xml @@ -23,6 +23,14 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 + + + org.apache.maven.surefire + it-parent + 1.0 + ../pom.xml + + org.apache.maven.plugins.surefire default-configuration-noTests 1.0-SNAPSHOT @@ -40,14 +48,6 @@ - - - - maven-surefire-plugin - ${surefire.version} - - - junit47 @@ -55,7 +55,6 @@ maven-surefire-plugin - ${surefire.version} org.apache.maven.surefire @@ -63,6 +62,7 @@ ${surefire.version} + diff --git a/surefire-integration-tests/src/test/resources/default-configuration/pom.xml b/surefire-integration-tests/src/test/resources/default-configuration/pom.xml index 38f4956295..b5b1686b99 100644 --- a/surefire-integration-tests/src/test/resources/default-configuration/pom.xml +++ b/surefire-integration-tests/src/test/resources/default-configuration/pom.xml @@ -23,6 +23,14 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 + + + org.apache.maven.surefire + it-parent + 1.0 + ../pom.xml + + org.apache.maven.plugins.surefire default-configuration 1.0-SNAPSHOT @@ -36,14 +44,4 @@ test - - - - - maven-surefire-plugin - ${surefire.version} - - - - diff --git a/surefire-integration-tests/src/test/resources/failingBuilds/src/test/java/failingbuilds/ExceptionsTest.java b/surefire-integration-tests/src/test/resources/failingBuilds/src/test/java/failingbuilds/ExceptionsTest.java index 1cfdd9199c..ede031b491 100644 --- a/surefire-integration-tests/src/test/resources/failingBuilds/src/test/java/failingbuilds/ExceptionsTest.java +++ b/surefire-integration-tests/src/test/resources/failingBuilds/src/test/java/failingbuilds/ExceptionsTest.java @@ -1,19 +1,19 @@ -package failingbuilds; - -import org.junit.Test; - -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.hamcrest.CoreMatchers.*; -import static org.junit.Assume.*; - -import junit.framework.TestCase; - -public class ExceptionsTest - extends TestCase -{ - 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" ); - } +package failingbuilds; + +import org.junit.Test; + +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.hamcrest.CoreMatchers.*; +import static org.junit.Assume.*; + +import junit.framework.TestCase; + +public class ExceptionsTest + extends TestCase +{ + 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-integration-tests/src/test/resources/failsafe-regular/invoker.properties b/surefire-integration-tests/src/test/resources/failsafe-regular/invoker.properties new file mode 100644 index 0000000000..ab6608feb9 --- /dev/null +++ b/surefire-integration-tests/src/test/resources/failsafe-regular/invoker.properties @@ -0,0 +1,19 @@ +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# +invoker.buildResult=failure diff --git a/surefire-integration-tests/src/test/resources/failsafe-regular/pom.xml b/surefire-integration-tests/src/test/resources/failsafe-regular/pom.xml new file mode 100644 index 0000000000..4755cb4534 --- /dev/null +++ b/surefire-integration-tests/src/test/resources/failsafe-regular/pom.xml @@ -0,0 +1,83 @@ + + + + + 4.0.0 + localhost + working-directory-test + 1.0 + Run tests multiple times + + + junit + junit + 3.8.2 + test + + + + + + org.apache.maven.plugins + maven-failsafe-plugin + ${surefire.version} + + + integration-test + + integration-test + + + ${project.build.directory}/failsafe-reports/Xfailsafe-summary-1.xml + + + + acceptance-test + + integration-test + + + + **/AT*.java + **/*AT.java + **/*ATCase.java + + ${project.build.directory}/failsafe-reports/Xfailsafe-summary-2.xml + + + + verify + + verify + + + + ${project.build.directory}/failsafe-reports/Xfailsafe-summary-1.xml + ${project.build.directory}/failsafe-reports/Xfailsafe-summary-2.xml + + + + + + + + + diff --git a/surefire-integration-tests/src/test/resources/failsafe-regular/src/test/java/MyAT.java b/surefire-integration-tests/src/test/resources/failsafe-regular/src/test/java/MyAT.java new file mode 100644 index 0000000000..615ee76808 --- /dev/null +++ b/surefire-integration-tests/src/test/resources/failsafe-regular/src/test/java/MyAT.java @@ -0,0 +1,26 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES 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 MyAT extends TestCase { + public void testSomething() { + assertTrue(true); + } +} diff --git a/surefire-integration-tests/src/test/resources/failsafe-regular/src/test/java/MyIT.java b/surefire-integration-tests/src/test/resources/failsafe-regular/src/test/java/MyIT.java new file mode 100644 index 0000000000..c74feb1e7d --- /dev/null +++ b/surefire-integration-tests/src/test/resources/failsafe-regular/src/test/java/MyIT.java @@ -0,0 +1,26 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES 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 MyIT extends TestCase { + public void testSomething() { + assertTrue(true); + } +} diff --git a/surefire-integration-tests/src/test/resources/failure-result-counting/src/test/java/failureresultcounting/BeforeClassError.java b/surefire-integration-tests/src/test/resources/failure-result-counting/src/test/java/failureresultcounting/BeforeClassError.java index 7791734292..0e80332ea3 100644 --- a/surefire-integration-tests/src/test/resources/failure-result-counting/src/test/java/failureresultcounting/BeforeClassError.java +++ b/surefire-integration-tests/src/test/resources/failure-result-counting/src/test/java/failureresultcounting/BeforeClassError.java @@ -1,43 +1,43 @@ -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.BeforeClass; -import org.junit.Test; - -/** - * @author Kristian Rosenvold - */ -public class BeforeClassError -{ - - @BeforeClass - public static void beforeClassError() - { - throw new RuntimeException( "Exception in beforeclass" ); - } - - @Test - public void ok() - { - System.out.println( "beforeClassError run !!" ); - } - +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.BeforeClass; +import org.junit.Test; + +/** + * @author Kristian Rosenvold + */ +public class BeforeClassError +{ + + @BeforeClass + public static void beforeClassError() + { + throw new RuntimeException( "Exception in beforeclass" ); + } + + @Test + public void ok() + { + System.out.println( "beforeClassError run !!" ); + } + } \ No newline at end of file diff --git a/surefire-integration-tests/src/test/resources/failure-result-counting/src/test/java/failureresultcounting/BeforeClassFailure.java b/surefire-integration-tests/src/test/resources/failure-result-counting/src/test/java/failureresultcounting/BeforeClassFailure.java index 5ef3f16db5..62d51acc20 100644 --- a/surefire-integration-tests/src/test/resources/failure-result-counting/src/test/java/failureresultcounting/BeforeClassFailure.java +++ b/surefire-integration-tests/src/test/resources/failure-result-counting/src/test/java/failureresultcounting/BeforeClassFailure.java @@ -1,43 +1,43 @@ -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; - -/** - * @author Kristian Rosenvold - */ -public class BeforeClassFailure -{ - - @BeforeClass - public static void failInBeforeClass() - { - Assert.fail( "Failing in @BeforeClass" ); - } - - @Test - public void ok() - { - System.out.println( "failInBeforeClass run !!"); - } - +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; + +/** + * @author Kristian Rosenvold + */ +public class BeforeClassFailure +{ + + @BeforeClass + public static void failInBeforeClass() + { + Assert.fail( "Failing in @BeforeClass" ); + } + + @Test + public void ok() + { + System.out.println( "failInBeforeClass run !!"); + } + } \ No newline at end of file diff --git a/surefire-integration-tests/src/test/resources/failure-result-counting/src/test/java/failureresultcounting/BeforeError.java b/surefire-integration-tests/src/test/resources/failure-result-counting/src/test/java/failureresultcounting/BeforeError.java index 1422580b49..0798c80c51 100644 --- a/surefire-integration-tests/src/test/resources/failure-result-counting/src/test/java/failureresultcounting/BeforeError.java +++ b/surefire-integration-tests/src/test/resources/failure-result-counting/src/test/java/failureresultcounting/BeforeError.java @@ -1,48 +1,48 @@ -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; - -/** - * @author Kristian Rosenvold - */ -public class BeforeError -{ - - @Before - public void exceptionInBefore() - { - throw new RuntimeException( "Exception in @before" ); - } - - @Test - public void ok() - { - System.out.println( "exceptionInBefore run!!"); - } - - /*@Test - public void ok2() - { - System.out.println( "exceptionInBefore2 run!!"); - } */ - +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; + +/** + * @author Kristian Rosenvold + */ +public class BeforeError +{ + + @Before + public void exceptionInBefore() + { + throw new RuntimeException( "Exception in @before" ); + } + + @Test + public void ok() + { + System.out.println( "exceptionInBefore run!!"); + } + + /*@Test + public void ok2() + { + System.out.println( "exceptionInBefore2 run!!"); + } */ + } \ No newline at end of file diff --git a/surefire-integration-tests/src/test/resources/failure-result-counting/src/test/java/failureresultcounting/BeforeFailure.java b/surefire-integration-tests/src/test/resources/failure-result-counting/src/test/java/failureresultcounting/BeforeFailure.java index 379827f9d1..174a448928 100644 --- a/surefire-integration-tests/src/test/resources/failure-result-counting/src/test/java/failureresultcounting/BeforeFailure.java +++ b/surefire-integration-tests/src/test/resources/failure-result-counting/src/test/java/failureresultcounting/BeforeFailure.java @@ -1,43 +1,43 @@ -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; - -/** - * @author Kristian Rosenvold - */ -public class BeforeFailure -{ - - @Before - public void failInBEfore() - { - Assert.fail( "Failing in @before" ); - } - - @Test - public void ok() - { - System.out.println( "failInBEfore run !!"); - } - +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; + +/** + * @author Kristian Rosenvold + */ +public class BeforeFailure +{ + + @Before + public void failInBEfore() + { + Assert.fail( "Failing in @before" ); + } + + @Test + public void ok() + { + System.out.println( "failInBEfore run !!"); + } + } \ No newline at end of file diff --git a/surefire-integration-tests/src/test/resources/failure-result-counting/src/test/java/failureresultcounting/NoErrors.java b/surefire-integration-tests/src/test/resources/failure-result-counting/src/test/java/failureresultcounting/NoErrors.java index dd6f79ae13..245c9a65b6 100644 --- a/surefire-integration-tests/src/test/resources/failure-result-counting/src/test/java/failureresultcounting/NoErrors.java +++ b/surefire-integration-tests/src/test/resources/failure-result-counting/src/test/java/failureresultcounting/NoErrors.java @@ -1,43 +1,43 @@ -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; - -/** - * @author Kristian Rosenvold - */ -public class NoErrors -{ - - @Test - @Ignore - public void allOk1() - { - } - - @Test - @Ignore - public void allOk2() - { - } - +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; + +/** + * @author Kristian Rosenvold + */ +public class NoErrors +{ + + @Test + @Ignore + public void allOk1() + { + } + + @Test + @Ignore + public void allOk2() + { + } + } \ No newline at end of file diff --git a/surefire-integration-tests/src/test/resources/failure-result-counting/src/test/java/failureresultcounting/OrdinaryError.java b/surefire-integration-tests/src/test/resources/failure-result-counting/src/test/java/failureresultcounting/OrdinaryError.java index d79d145105..7e6387aa8b 100644 --- a/surefire-integration-tests/src/test/resources/failure-result-counting/src/test/java/failureresultcounting/OrdinaryError.java +++ b/surefire-integration-tests/src/test/resources/failure-result-counting/src/test/java/failureresultcounting/OrdinaryError.java @@ -1,42 +1,42 @@ -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; - -/** - * @author Kristian Rosenvold - */ -public class OrdinaryError -{ - - @Test - public void ordinaryEror() - { - throw new RuntimeException( "Exception in @before" ); - } - - @Test - public void ordinaryFailure() - { - Assert.fail(); - } - +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; + +/** + * @author Kristian Rosenvold + */ +public class OrdinaryError +{ + + @Test + public void ordinaryEror() + { + throw new RuntimeException( "Exception in @before" ); + } + + @Test + public void ordinaryFailure() + { + Assert.fail(); + } + } \ No newline at end of file diff --git a/surefire-integration-tests/src/test/resources/failureOutput/pom.xml b/surefire-integration-tests/src/test/resources/failureOutput/pom.xml new file mode 100644 index 0000000000..5be8fc406f --- /dev/null +++ b/surefire-integration-tests/src/test/resources/failureOutput/pom.xml @@ -0,0 +1,56 @@ + + 4.0.0 + org.apache.maven.plugins.surefire + failureOutput + jar + 1.0-SNAPSHOT + failureOutput + http://maven.apache.org + + + + junit + junit + ${junit.version} + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.5 + 1.5 + + + + org.apache.maven.plugins + maven-surefire-plugin + ${surefire.version} + + ${forkMode} + ${printSummary} + ${userFile} + ${reportFormat} + ${redirect.to.file} + + **/Test*.java + + + + + + + + + 4.8.1 + true + once + true + true + brief + + + diff --git a/surefire-integration-tests/src/test/resources/failureOutput/src/test/java/forkConsoleOutput/Test1.java b/surefire-integration-tests/src/test/resources/failureOutput/src/test/java/forkConsoleOutput/Test1.java new file mode 100644 index 0000000000..af929523fd --- /dev/null +++ b/surefire-integration-tests/src/test/resources/failureOutput/src/test/java/forkConsoleOutput/Test1.java @@ -0,0 +1,85 @@ +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; +import org.junit.Test; + +import java.io.File; + +public class Test1 +{ + @Test + public void test6281() { + System.out.println( "Test1 on" + Thread.currentThread().getName()); + } + + @Test + public void nullPointerInLibrary() { + new File((String)null); + } + + @Test + public void failInMethod() { + innerFailure(); + } + + @Test + public void failInLibInMethod() { + new File((String)null); + } + + + @Test + public void failInNestedLibInMethod() { + nestedLibFailure(); + } + + @Test + public void assertion1() { + Assert.assertEquals("Bending maths", "123", "312"); + } + + @Test + public void assertion2() { + Assert.assertFalse("True is false", true); + } + + private void innerFailure(){ + throw new NullPointerException("Fail here"); + } + + private void nestedLibFailure(){ + new File((String) null); + } + + @BeforeClass + public static void testWithFailingAssumption2() { + System.out.println( "BeforeTest1 on" + Thread.currentThread().getName()); + } + + @AfterClass + public static void testWithFailingAssumption3() { + System.out.println( "AfterTest1 on" + Thread.currentThread().getName()); + } + +} diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/util/internal/Java15BlockingQueue.java b/surefire-integration-tests/src/test/resources/failureOutput/src/test/java/forkConsoleOutput/Test2.java similarity index 62% rename from maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/util/internal/Java15BlockingQueue.java rename to surefire-integration-tests/src/test/resources/failureOutput/src/test/java/forkConsoleOutput/Test2.java index 1b3f8396ba..f5c825eb82 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/util/internal/Java15BlockingQueue.java +++ b/surefire-integration-tests/src/test/resources/failureOutput/src/test/java/forkConsoleOutput/Test2.java @@ -1,4 +1,4 @@ -package org.apache.maven.plugin.surefire.util.internal; +package forkConsoleOutput; /* * Licensed to the Apache Software Foundation (ASF) under one @@ -19,26 +19,17 @@ * under the License. */ +import org.junit.Test; -import java.util.concurrent.LinkedBlockingQueue; - -/** - * @author Kristian Rosenvold - */ -public class Java15BlockingQueue - implements BlockingQueue +public class Test2 { - private final java.util.concurrent.BlockingQueue blockingQueue = new LinkedBlockingQueue(); - - public void add( String object ) + @Test + public void test6281() { - blockingQueue.add( object ); - } - - public String take() - throws InterruptedException - { - return blockingQueue.take(); + System.out.println( "sout: I am talking to you" ); + System.out.println( "sout: Will Fail soon" ); + System.err.println( "serr: And you too" ); + System.err.println( "serr: Will Fail now" ); + throw new RuntimeException( "FailHere" ); } } - diff --git a/surefire-integration-tests/src/test/resources/failureOutput/test b/surefire-integration-tests/src/test/resources/failureOutput/test new file mode 100644 index 0000000000..873a7bfc76 --- /dev/null +++ b/surefire-integration-tests/src/test/resources/failureOutput/test @@ -0,0 +1,15 @@ +[INFO] Scanning for projects... +[WARNING] +[WARNING] Some problems were encountered while building the effective model for org.apache.maven.plugins.surefire:failureOutput:jar:1.0-SNAPSHOT +[WARNING] 'build.plugins.plugin.version' for org.apache.maven.plugins:maven-compiler-plugin is missing. @ line 20, column 17 +[WARNING] +[WARNING] It is highly recommended to fix these problems because they threaten the stability of your build. +[WARNING] +[WARNING] For this reason, future Maven versions might no longer support building such malformed projects. +[WARNING] +[INFO] +[INFO] ------------------------------------------------------------------------ +[INFO] Building failureOutput 1.0-SNAPSHOT +[INFO] ------------------------------------------------------------------------ +[INFO] +[INFO] --- maven-resources-plugin:2.5:resources (default-resources) @ failureOutput --- diff --git a/surefire-integration-tests/src/test/resources/fork-mode-multimodule/module-a/pom.xml b/surefire-integration-tests/src/test/resources/fork-mode-multimodule/module-a/pom.xml new file mode 100644 index 0000000000..cbaf407bfe --- /dev/null +++ b/surefire-integration-tests/src/test/resources/fork-mode-multimodule/module-a/pom.xml @@ -0,0 +1,36 @@ + + + + + 4.0.0 + + + org.apache.maven.plugins.surefire + fork-mode-multimodule + 1.0-SNAPSHOT + + + org.apache.maven.plugins.surefire + fork-mode-multimodule.module-a + Test for forkMode Module A + + diff --git a/surefire-integration-tests/src/test/resources/fork-mode-multimodule/module-a/src/test/java/forkMode/Test1.java b/surefire-integration-tests/src/test/resources/fork-mode-multimodule/module-a/src/test/java/forkMode/Test1.java new file mode 100644 index 0000000000..08ac31d9ec --- /dev/null +++ b/surefire-integration-tests/src/test/resources/fork-mode-multimodule/module-a/src/test/java/forkMode/Test1.java @@ -0,0 +1,48 @@ +package forkMode; + +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.lang.management.ManagementFactory; +import java.util.Random; + +import junit.framework.TestCase; + +public class Test1 + extends TestCase +{ + + private static final Random RANDOM = new Random(); + + public void test1() + throws IOException, InterruptedException + { + int sleepLength = Integer.valueOf( System.getProperty( "sleepLength", "1500" )); + Thread.sleep(sleepLength); + dumpPidFile( this ); + } + + public static void dumpPidFile( TestCase test ) + throws IOException + { + String fileName = test.getName() + "-pid"; + File target = new File( "target" ).getCanonicalFile(); // getCanonicalFile required for embedded mode + if ( !( target.exists() && target.isDirectory() ) ) + { + target = new File( "." ); + } + File pidFile = new File( target, fileName ); + FileWriter fw = new FileWriter( pidFile ); + // DGF little known trick... this is guaranteed to be unique to the PID + // In fact, it usually contains the pid and the local host name! + String pid = ManagementFactory.getRuntimeMXBean().getName(); + fw.write( pid ); + fw.write( " " ); + fw.write( System.getProperty( "testProperty", String.valueOf( RANDOM.nextLong() ) ) ); + fw.flush(); + fw.close(); + System.out.println( "Done Writing pid file" + pidFile.getAbsolutePath() ); + } + + +} diff --git a/surefire-integration-tests/src/test/resources/fork-mode-multimodule/module-a/src/test/java/forkMode/Test2.java b/surefire-integration-tests/src/test/resources/fork-mode-multimodule/module-a/src/test/java/forkMode/Test2.java new file mode 100644 index 0000000000..ce30de9b48 --- /dev/null +++ b/surefire-integration-tests/src/test/resources/fork-mode-multimodule/module-a/src/test/java/forkMode/Test2.java @@ -0,0 +1,17 @@ +package forkMode; + +import java.io.IOException; + +import junit.framework.TestCase; + +public class Test2 + extends TestCase +{ + + public void test2() throws IOException, InterruptedException { + int sleepLength = Integer.valueOf( System.getProperty( "sleepLength", "1500" )); + Thread.sleep(sleepLength); + Test1.dumpPidFile(this); + } + +} diff --git a/surefire-integration-tests/src/test/resources/fork-mode-multimodule/module-a/src/test/java/forkMode/Test3.java b/surefire-integration-tests/src/test/resources/fork-mode-multimodule/module-a/src/test/java/forkMode/Test3.java new file mode 100644 index 0000000000..deb9296b5d --- /dev/null +++ b/surefire-integration-tests/src/test/resources/fork-mode-multimodule/module-a/src/test/java/forkMode/Test3.java @@ -0,0 +1,15 @@ +package forkMode; + +import java.io.IOException; + +import junit.framework.TestCase; + +public class Test3 + extends TestCase +{ + + public void test3() throws IOException { + Test1.dumpPidFile(this); + } + +} diff --git a/surefire-integration-tests/src/test/resources/fork-mode-multimodule/module-b/pom.xml b/surefire-integration-tests/src/test/resources/fork-mode-multimodule/module-b/pom.xml new file mode 100644 index 0000000000..ba076ce6d8 --- /dev/null +++ b/surefire-integration-tests/src/test/resources/fork-mode-multimodule/module-b/pom.xml @@ -0,0 +1,36 @@ + + + + + 4.0.0 + + + org.apache.maven.plugins.surefire + fork-mode-multimodule + 1.0-SNAPSHOT + + + org.apache.maven.plugins.surefire + fork-mode-multimodule.module-b + Test for forkMode Module B + + diff --git a/surefire-integration-tests/src/test/resources/fork-mode-multimodule/module-b/src/test/java/forkMode/Test1.java b/surefire-integration-tests/src/test/resources/fork-mode-multimodule/module-b/src/test/java/forkMode/Test1.java new file mode 100644 index 0000000000..08ac31d9ec --- /dev/null +++ b/surefire-integration-tests/src/test/resources/fork-mode-multimodule/module-b/src/test/java/forkMode/Test1.java @@ -0,0 +1,48 @@ +package forkMode; + +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.lang.management.ManagementFactory; +import java.util.Random; + +import junit.framework.TestCase; + +public class Test1 + extends TestCase +{ + + private static final Random RANDOM = new Random(); + + public void test1() + throws IOException, InterruptedException + { + int sleepLength = Integer.valueOf( System.getProperty( "sleepLength", "1500" )); + Thread.sleep(sleepLength); + dumpPidFile( this ); + } + + public static void dumpPidFile( TestCase test ) + throws IOException + { + String fileName = test.getName() + "-pid"; + File target = new File( "target" ).getCanonicalFile(); // getCanonicalFile required for embedded mode + if ( !( target.exists() && target.isDirectory() ) ) + { + target = new File( "." ); + } + File pidFile = new File( target, fileName ); + FileWriter fw = new FileWriter( pidFile ); + // DGF little known trick... this is guaranteed to be unique to the PID + // In fact, it usually contains the pid and the local host name! + String pid = ManagementFactory.getRuntimeMXBean().getName(); + fw.write( pid ); + fw.write( " " ); + fw.write( System.getProperty( "testProperty", String.valueOf( RANDOM.nextLong() ) ) ); + fw.flush(); + fw.close(); + System.out.println( "Done Writing pid file" + pidFile.getAbsolutePath() ); + } + + +} diff --git a/surefire-integration-tests/src/test/resources/fork-mode-multimodule/module-b/src/test/java/forkMode/Test2.java b/surefire-integration-tests/src/test/resources/fork-mode-multimodule/module-b/src/test/java/forkMode/Test2.java new file mode 100644 index 0000000000..ce30de9b48 --- /dev/null +++ b/surefire-integration-tests/src/test/resources/fork-mode-multimodule/module-b/src/test/java/forkMode/Test2.java @@ -0,0 +1,17 @@ +package forkMode; + +import java.io.IOException; + +import junit.framework.TestCase; + +public class Test2 + extends TestCase +{ + + public void test2() throws IOException, InterruptedException { + int sleepLength = Integer.valueOf( System.getProperty( "sleepLength", "1500" )); + Thread.sleep(sleepLength); + Test1.dumpPidFile(this); + } + +} diff --git a/surefire-integration-tests/src/test/resources/fork-mode-multimodule/module-b/src/test/java/forkMode/Test3.java b/surefire-integration-tests/src/test/resources/fork-mode-multimodule/module-b/src/test/java/forkMode/Test3.java new file mode 100644 index 0000000000..deb9296b5d --- /dev/null +++ b/surefire-integration-tests/src/test/resources/fork-mode-multimodule/module-b/src/test/java/forkMode/Test3.java @@ -0,0 +1,15 @@ +package forkMode; + +import java.io.IOException; + +import junit.framework.TestCase; + +public class Test3 + extends TestCase +{ + + public void test3() throws IOException { + Test1.dumpPidFile(this); + } + +} diff --git a/surefire-integration-tests/src/test/resources/fork-mode-multimodule/pom.xml b/surefire-integration-tests/src/test/resources/fork-mode-multimodule/pom.xml new file mode 100644 index 0000000000..98e073f720 --- /dev/null +++ b/surefire-integration-tests/src/test/resources/fork-mode-multimodule/pom.xml @@ -0,0 +1,69 @@ + + + + + 4.0.0 + + org.apache.maven.plugins.surefire + fork-mode-multimodule + 1.0-SNAPSHOT + Test for forkMode Multimodule + + pom + + + module-a + module-b + + + + + + maven-compiler-plugin + 2.3.2 + + 1.5 + 1.5 + + + + maven-surefire-plugin + ${surefire.version} + + ${forkMode} + ${threadCount} + alphabetical + + + + + + + + junit + junit + 3.8.1 + test + + + + diff --git a/surefire-integration-tests/src/test/resources/fork-mode/pom.xml b/surefire-integration-tests/src/test/resources/fork-mode/pom.xml index aa37e2cd6f..ca7d365c59 100644 --- a/surefire-integration-tests/src/test/resources/fork-mode/pom.xml +++ b/surefire-integration-tests/src/test/resources/fork-mode/pom.xml @@ -43,6 +43,7 @@ ${forkMode} ${threadCount} + alphabetical diff --git a/surefire-integration-tests/src/test/resources/fork-mode/src/test/java/forkMode/Test1.java b/surefire-integration-tests/src/test/resources/fork-mode/src/test/java/forkMode/Test1.java index 01f1151afb..8dd33075ed 100644 --- a/surefire-integration-tests/src/test/resources/fork-mode/src/test/java/forkMode/Test1.java +++ b/surefire-integration-tests/src/test/resources/fork-mode/src/test/java/forkMode/Test1.java @@ -15,8 +15,10 @@ public class Test1 private static final Random RANDOM = new Random(); public void test1() - throws IOException + throws IOException, InterruptedException { + int sleepLength = Integer.valueOf( System.getProperty( "sleepLength", "750" )); + Thread.sleep(sleepLength); dumpPidFile( this ); } diff --git a/surefire-integration-tests/src/test/resources/includes-excludes/pom.xml b/surefire-integration-tests/src/test/resources/includes-excludes/pom.xml index e6a831b217..504171e97a 100644 --- a/surefire-integration-tests/src/test/resources/includes-excludes/pom.xml +++ b/surefire-integration-tests/src/test/resources/includes-excludes/pom.xml @@ -64,6 +64,8 @@ under the License. **/DontRunTest.* + + **/NotIncludedByDefault.java diff --git a/surefire-integration-tests/src/test/resources/junit-ignore/pom.xml b/surefire-integration-tests/src/test/resources/junit-ignore/pom.xml index c62fabdec1..a40b9869f0 100644 --- a/surefire-integration-tests/src/test/resources/junit-ignore/pom.xml +++ b/surefire-integration-tests/src/test/resources/junit-ignore/pom.xml @@ -31,6 +31,7 @@ 4.4 + 3 @@ -57,7 +58,8 @@ ${surefire.version} ${surefire.parallel} - 3 + false + ${surefire.threadcount} diff --git a/surefire-integration-tests/src/test/resources/junit-ignore/src/test/java/junit/ignore/BasicTest.java b/surefire-integration-tests/src/test/resources/junit-ignore/src/test/java/junit/ignore/ClassAndMethodIgnoreNothingToRunTest.java similarity index 84% rename from surefire-integration-tests/src/test/resources/junit-ignore/src/test/java/junit/ignore/BasicTest.java rename to surefire-integration-tests/src/test/resources/junit-ignore/src/test/java/junit/ignore/ClassAndMethodIgnoreNothingToRunTest.java index b7d55b2d67..15f05f97cb 100644 --- a/surefire-integration-tests/src/test/resources/junit-ignore/src/test/java/junit/ignore/BasicTest.java +++ b/surefire-integration-tests/src/test/resources/junit-ignore/src/test/java/junit/ignore/ClassAndMethodIgnoreNothingToRunTest.java @@ -5,7 +5,7 @@ import org.junit.Test; @Ignore( "ignore this test" ) -public class BasicTest +public class ClassAndMethodIgnoreNothingToRunTest { @Ignore( "ignore this test" ) diff --git a/surefire-integration-tests/src/test/resources/junit-ignore/src/test/java/junit/ignore/ClassLevelIgnore1Test.java b/surefire-integration-tests/src/test/resources/junit-ignore/src/test/java/junit/ignore/ClassLevelIgnore1WithMethodThatIsNormalTest.java similarity index 80% rename from surefire-integration-tests/src/test/resources/junit-ignore/src/test/java/junit/ignore/ClassLevelIgnore1Test.java rename to surefire-integration-tests/src/test/resources/junit-ignore/src/test/java/junit/ignore/ClassLevelIgnore1WithMethodThatIsNormalTest.java index ca006094a3..7570f7f88e 100644 --- a/surefire-integration-tests/src/test/resources/junit-ignore/src/test/java/junit/ignore/ClassLevelIgnore1Test.java +++ b/surefire-integration-tests/src/test/resources/junit-ignore/src/test/java/junit/ignore/ClassLevelIgnore1WithMethodThatIsNormalTest.java @@ -5,7 +5,7 @@ import org.junit.Test; @Ignore( "ignore this test" ) -public class ClassLevelIgnore1Test +public class ClassLevelIgnore1WithMethodThatIsNormalTest { @Test diff --git a/surefire-integration-tests/src/test/resources/junit-ignore/src/test/java/junit/ignore/ClassLevelIgnore2Test.java b/surefire-integration-tests/src/test/resources/junit-ignore/src/test/java/junit/ignore/ClassLevelIgnore2WithMethodThatIsNormalTest.java similarity index 80% rename from surefire-integration-tests/src/test/resources/junit-ignore/src/test/java/junit/ignore/ClassLevelIgnore2Test.java rename to surefire-integration-tests/src/test/resources/junit-ignore/src/test/java/junit/ignore/ClassLevelIgnore2WithMethodThatIsNormalTest.java index c460f49f5d..b6cbcf63df 100644 --- a/surefire-integration-tests/src/test/resources/junit-ignore/src/test/java/junit/ignore/ClassLevelIgnore2Test.java +++ b/surefire-integration-tests/src/test/resources/junit-ignore/src/test/java/junit/ignore/ClassLevelIgnore2WithMethodThatIsNormalTest.java @@ -5,7 +5,7 @@ import org.junit.Test; @Ignore( "ignore this test" ) -public class ClassLevelIgnore2Test +public class ClassLevelIgnore2WithMethodThatIsNormalTest { @Test diff --git a/surefire-integration-tests/src/test/resources/junit-ignore/src/test/java/junit/ignore/IgnoreWithMessagesTest.java b/surefire-integration-tests/src/test/resources/junit-ignore/src/test/java/junit/ignore/NormalClassWithThreeIgnoredMethodsAnd1AssumptionFailureTest.java similarity index 87% rename from surefire-integration-tests/src/test/resources/junit-ignore/src/test/java/junit/ignore/IgnoreWithMessagesTest.java rename to surefire-integration-tests/src/test/resources/junit-ignore/src/test/java/junit/ignore/NormalClassWithThreeIgnoredMethodsAnd1AssumptionFailureTest.java index 06c18f3032..765eb8a120 100644 --- a/surefire-integration-tests/src/test/resources/junit-ignore/src/test/java/junit/ignore/IgnoreWithMessagesTest.java +++ b/surefire-integration-tests/src/test/resources/junit-ignore/src/test/java/junit/ignore/NormalClassWithThreeIgnoredMethodsAnd1AssumptionFailureTest.java @@ -7,7 +7,7 @@ /** * @author Kristian Rosenvold */ -public class IgnoreWithMessagesTest +public class NormalClassWithThreeIgnoredMethodsAnd1AssumptionFailureTest { @Ignore diff --git a/surefire-integration-tests/src/test/resources/junit47-cucumber/pom.xml b/surefire-integration-tests/src/test/resources/junit47-cucumber/pom.xml new file mode 100644 index 0000000000..a57d3c4cf0 --- /dev/null +++ b/surefire-integration-tests/src/test/resources/junit47-cucumber/pom.xml @@ -0,0 +1,81 @@ + + + + + 4.0.0 + + + org.apache.maven.surefire + it-parent + 1.0 + + + junit47-cucumber + jar + + Tests cucumber with JUnit47 provider + + + 1.1.3 + 4.11 + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + 0 + true + + + + org.apache.maven.surefire + surefire-junit47 + ${surefire.version} + + + + + + + + + junit + junit + ${junit.version} + test + + + info.cukes + cucumber-java + ${cucumber.version} + test + + + info.cukes + cucumber-junit + ${cucumber.version} + test + + + diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/util/internal/BlockingQueue.java b/surefire-integration-tests/src/test/resources/junit47-cucumber/src/test/java/org/sample/cucumber/FailingCucumberTest.java similarity index 71% rename from maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/util/internal/BlockingQueue.java rename to surefire-integration-tests/src/test/resources/junit47-cucumber/src/test/java/org/sample/cucumber/FailingCucumberTest.java index a0de80be8c..ed86734ca4 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/util/internal/BlockingQueue.java +++ b/surefire-integration-tests/src/test/resources/junit47-cucumber/src/test/java/org/sample/cucumber/FailingCucumberTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.util.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -19,15 +17,15 @@ * under the License. */ -/** - * A very simple blocking queue that might have stricter constraints than the standard jdk1.5 blockingqueues. - * - * @author Kristian Rosenvold - */ -public interface BlockingQueue +package org.sample.cucumber; + +import org.junit.runner.RunWith; + +import cucumber.api.junit.Cucumber; + +@RunWith( Cucumber.class ) +@Cucumber.Options( features = { "classpath:failing" } ) +public class FailingCucumberTest { - void add( String object ); - String take() - throws InterruptedException; } diff --git a/surefire-integration-tests/src/test/resources/junit47-cucumber/src/test/java/org/sample/cucumber/StepDefs.java b/surefire-integration-tests/src/test/resources/junit47-cucumber/src/test/java/org/sample/cucumber/StepDefs.java new file mode 100644 index 0000000000..ba25f69998 --- /dev/null +++ b/surefire-integration-tests/src/test/resources/junit47-cucumber/src/test/java/org/sample/cucumber/StepDefs.java @@ -0,0 +1,57 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.sample.cucumber; + +import cucumber.api.java.en.Given; +import cucumber.api.java.en.Then; +import cucumber.api.java.en.When; + +import static org.junit.Assert.fail; + +public class StepDefs +{ + @Given( "^I have some code$" ) + public void I_have_some_code() + throws Throwable + { + // do nothing + } + + @When( "^I run test$" ) + public void I_run_test() + throws Throwable + { + // do nothing + } + + @Then( "^I get no failures$" ) + public void I_get_no_failures() + throws Throwable + { + // do nothing + } + + @Then( "^I get a failure$" ) + public void I_get_a_failure() + throws Throwable + { + fail( "failing the test on purpose." ); + } +} diff --git a/surefire-integration-tests/src/test/resources/junit47-cucumber/src/test/java/org/sample/cucumber/SuccessCucumberTest.java b/surefire-integration-tests/src/test/resources/junit47-cucumber/src/test/java/org/sample/cucumber/SuccessCucumberTest.java new file mode 100644 index 0000000000..318f5e60df --- /dev/null +++ b/surefire-integration-tests/src/test/resources/junit47-cucumber/src/test/java/org/sample/cucumber/SuccessCucumberTest.java @@ -0,0 +1,31 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.sample.cucumber; + +import org.junit.runner.RunWith; + +import cucumber.api.junit.Cucumber; + +@RunWith( Cucumber.class ) +@Cucumber.Options( features = { "classpath:success" } ) +public class SuccessCucumberTest +{ + +} diff --git a/surefire-integration-tests/src/test/resources/junit47-cucumber/src/test/resources/failing/Sample.feature b/surefire-integration-tests/src/test/resources/junit47-cucumber/src/test/resources/failing/Sample.feature new file mode 100644 index 0000000000..e8ac94555f --- /dev/null +++ b/surefire-integration-tests/src/test/resources/junit47-cucumber/src/test/resources/failing/Sample.feature @@ -0,0 +1,10 @@ +Feature: Sample + + In order to use Maven + As a user + I want to do tests. + + Scenario: Do a failing test + Given I have some code + When I run test + Then I get a failure diff --git a/surefire-integration-tests/src/test/resources/junit47-cucumber/src/test/resources/success/Sample.feature b/surefire-integration-tests/src/test/resources/junit47-cucumber/src/test/resources/success/Sample.feature new file mode 100644 index 0000000000..26f0d2dea4 --- /dev/null +++ b/surefire-integration-tests/src/test/resources/junit47-cucumber/src/test/resources/success/Sample.feature @@ -0,0 +1,10 @@ +Feature: Sample + + In order to use Maven + As a user + I want to do tests. + + Scenario: Do a successful test + Given I have some code + When I run test + Then I get no failures diff --git a/surefire-integration-tests/src/test/resources/junit47-redirect-output/pom.xml b/surefire-integration-tests/src/test/resources/junit47-redirect-output/pom.xml index 289b2dc217..7cdb0a1705 100644 --- a/surefire-integration-tests/src/test/resources/junit47-redirect-output/pom.xml +++ b/surefire-integration-tests/src/test/resources/junit47-redirect-output/pom.xml @@ -43,6 +43,7 @@ ${redirect.to.file} 2 ${parallel} + alphabetical **/Test*.java diff --git a/surefire-integration-tests/src/test/resources/junit47-redirect-output/src/test/java/junit47ConsoleOutput/Test0.java b/surefire-integration-tests/src/test/resources/junit47-redirect-output/src/test/java/junit47ConsoleOutput/Test0.java new file mode 100644 index 0000000000..102faaa5b7 --- /dev/null +++ b/surefire-integration-tests/src/test/resources/junit47-redirect-output/src/test/java/junit47ConsoleOutput/Test0.java @@ -0,0 +1,63 @@ +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; +import org.junit.BeforeClass; +import org.junit.Test; + +public class Test0 { + + public Test0(){ + System.out.println("Constructor"); + } + + @Test + public void testT0() throws Exception { + System.out.println("testT0"); + } + + @Test + public void testT1() throws Exception { + System.out.println("testT1"); + } + + @BeforeClass + public static void setUpBeforeClass() throws Exception { + System.out.println("setUpBeforeClass"); + } + + @AfterClass + public static void tearDownAfterClass() throws Exception { + System.out.println("tearDownAfterClass"); + } + + @Before + public void setUp() throws Exception { + System.out.println("setUp"); + } + + @After + public void tearDown() throws Exception { + System.out.println("tearDown"); + } +} \ No newline at end of file diff --git a/surefire-integration-tests/src/test/resources/junit47-static-inner-class-tests/pom.xml b/surefire-integration-tests/src/test/resources/junit47-static-inner-class-tests/pom.xml new file mode 100644 index 0000000000..a7ac0555d5 --- /dev/null +++ b/surefire-integration-tests/src/test/resources/junit47-static-inner-class-tests/pom.xml @@ -0,0 +1,44 @@ + + 4.0.0 + org.apache.maven.plugins.surefire + junit4-test + jar + 1.0-SNAPSHOT + junit47-static-inner-class-tests + http://maven.apache.org + + + junit + junit + 4.8.1 + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.5 + 1.5 + + + + org.apache.maven.plugins + maven-surefire-plugin + ${surefire.version} + + never + + + + org.apache.maven.surefire + surefire-junit47 + ${surefire.version} + + + + + + diff --git a/surefire-integration-tests/src/test/resources/junit47-static-inner-class-tests/src/test/java/junit4/BasicTest.java b/surefire-integration-tests/src/test/resources/junit47-static-inner-class-tests/src/test/java/junit4/BasicTest.java new file mode 100644 index 0000000000..20d8785696 --- /dev/null +++ b/surefire-integration-tests/src/test/resources/junit47-static-inner-class-tests/src/test/java/junit4/BasicTest.java @@ -0,0 +1,13 @@ +package junit4; +import org.junit.Test; +import org.junit.experimental.runners.Enclosed; +import org.junit.runner.RunWith; + +@RunWith(Enclosed.class) +public class BasicTest { + public static class InnerTest { + @Test + public void testSomething() { + } + } +} diff --git a/surefire-integration-tests/src/test/resources/junit47-static-inner-class-tests/src/test/java/junit4/TopLevelAbstractClassTest.java b/surefire-integration-tests/src/test/resources/junit47-static-inner-class-tests/src/test/java/junit4/TopLevelAbstractClassTest.java new file mode 100644 index 0000000000..6193586b96 --- /dev/null +++ b/surefire-integration-tests/src/test/resources/junit47-static-inner-class-tests/src/test/java/junit4/TopLevelAbstractClassTest.java @@ -0,0 +1,13 @@ +package junit4; +import org.junit.Test; +import org.junit.experimental.runners.Enclosed; +import org.junit.runner.RunWith; + +@RunWith(Enclosed.class) +public abstract class TopLevelAbstractClassTest { + public static class InnerTest { + @Test + public void testSomething() { + } + } +} diff --git a/surefire-integration-tests/src/test/resources/junit47-static-inner-class-tests/src/test/java/junit4/TopLevelInterfaceTest.java b/surefire-integration-tests/src/test/resources/junit47-static-inner-class-tests/src/test/java/junit4/TopLevelInterfaceTest.java new file mode 100644 index 0000000000..2f777e347a --- /dev/null +++ b/surefire-integration-tests/src/test/resources/junit47-static-inner-class-tests/src/test/java/junit4/TopLevelInterfaceTest.java @@ -0,0 +1,13 @@ +package junit4; +import org.junit.Test; +import org.junit.experimental.runners.Enclosed; +import org.junit.runner.RunWith; + +@RunWith(Enclosed.class) +public interface TopLevelInterfaceTest { + public static class InnerTest { + @Test + public void testSomething() { + } + } +} diff --git a/surefire-integration-tests/src/test/resources/junit48-method-pattern/src/test/java/junit4/BasicTest.java b/surefire-integration-tests/src/test/resources/junit48-method-pattern/src/test/java/junit4/BasicTest.java index f5d0b9fb2e..6d883afb76 100644 --- a/surefire-integration-tests/src/test/resources/junit48-method-pattern/src/test/java/junit4/BasicTest.java +++ b/surefire-integration-tests/src/test/resources/junit48-method-pattern/src/test/java/junit4/BasicTest.java @@ -4,6 +4,7 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; +import org.junit.experimental.categories.Category; public class BasicTest @@ -43,6 +44,7 @@ public void testSuccessOne() } @Test + @Category(SampleCategory.class) public void testSuccessTwo() { Assert.assertTrue( true ); diff --git a/surefire-integration-tests/src/test/resources/junit48-method-pattern/src/test/java/junit4/SampleCategory.java b/surefire-integration-tests/src/test/resources/junit48-method-pattern/src/test/java/junit4/SampleCategory.java new file mode 100644 index 0000000000..9a8c4fe242 --- /dev/null +++ b/surefire-integration-tests/src/test/resources/junit48-method-pattern/src/test/java/junit4/SampleCategory.java @@ -0,0 +1,6 @@ +package junit4; + +public interface SampleCategory +{ + +} diff --git a/surefire-integration-tests/src/test/resources/junit48-smartStackTrace/pom.xml b/surefire-integration-tests/src/test/resources/junit48-smartStackTrace/pom.xml new file mode 100644 index 0000000000..ef0c85487f --- /dev/null +++ b/surefire-integration-tests/src/test/resources/junit48-smartStackTrace/pom.xml @@ -0,0 +1,63 @@ + + + + + 4.0.0 + + org.apache.maven.plugins.surefire + junit4-smartstacktrace + 1.0-SNAPSHOT + Test for smart stack trace parser + + + + 4.8.1 + + + + + junit + junit + ${junitVersion} + test + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.5 + 1.5 + + + + org.apache.maven.plugins + maven-surefire-plugin + ${surefire.version} + + + + + diff --git a/surefire-integration-tests/src/test/resources/junit48-smartStackTrace/src/test/java/junit4/SmartStackTraceTest.java b/surefire-integration-tests/src/test/resources/junit48-smartStackTrace/src/test/java/junit4/SmartStackTraceTest.java new file mode 100644 index 0000000000..326775e107 --- /dev/null +++ b/surefire-integration-tests/src/test/resources/junit48-smartStackTrace/src/test/java/junit4/SmartStackTraceTest.java @@ -0,0 +1,30 @@ +package junit4; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import java.io.IOException; + + +public class SmartStackTraceTest +{ + + @Test(expected = RuntimeException.class) + public void shouldFailInMethodButDoesnt() + { + } + + @Test(expected = IOException.class) + public void incorrectExceptionThrown() + { + throw new RuntimeException("We fail here"); + } + + @Test(expected = IOException.class) + public void shortName() + { + } + +} diff --git a/surefire-integration-tests/src/test/resources/pom.xml b/surefire-integration-tests/src/test/resources/pom.xml new file mode 100644 index 0000000000..a5a9341330 --- /dev/null +++ b/surefire-integration-tests/src/test/resources/pom.xml @@ -0,0 +1,40 @@ + + 4.0.0 + org.apache.maven.surefire + it-parent + pom + + 1.0 + It parent + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.5.1 + + + maven-surefire-plugin + ${surefire.version} + + never + + + + maven-failsafe-plugin + ${surefire.version} + + never + + + + maven-surefire-report-plugin + ${surefire.version} + + + + + diff --git a/surefire-integration-tests/src/test/resources/result-counting/src/test/java/resultcounting/MySuiteTest1.java b/surefire-integration-tests/src/test/resources/result-counting/src/test/java/resultcounting/MySuiteTest1.java index cab285eafe..0e0794598e 100644 --- a/surefire-integration-tests/src/test/resources/result-counting/src/test/java/resultcounting/MySuiteTest1.java +++ b/surefire-integration-tests/src/test/resources/result-counting/src/test/java/resultcounting/MySuiteTest1.java @@ -1,24 +1,24 @@ -package resultcounting; - -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - -public class MySuiteTest1 extends TestCase { - - public static Test suite () { - TestSuite suite = new TestSuite(); - - suite.addTest (new MySuiteTest1("testMe" )); - - return suite; - } - - public MySuiteTest1( String name ) { - super (name); - } - - public void testMe() { - assertTrue (true); - } -} +package resultcounting; + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; + +public class MySuiteTest1 extends TestCase { + + public static Test suite () { + TestSuite suite = new TestSuite(); + + suite.addTest (new MySuiteTest1("testMe" )); + + return suite; + } + + public MySuiteTest1( String name ) { + super (name); + } + + public void testMe() { + assertTrue (true); + } +} diff --git a/surefire-integration-tests/src/test/resources/result-counting/src/test/java/resultcounting/MySuiteTest2.java b/surefire-integration-tests/src/test/resources/result-counting/src/test/java/resultcounting/MySuiteTest2.java index ae71b47425..0c44f044c7 100644 --- a/surefire-integration-tests/src/test/resources/result-counting/src/test/java/resultcounting/MySuiteTest2.java +++ b/surefire-integration-tests/src/test/resources/result-counting/src/test/java/resultcounting/MySuiteTest2.java @@ -1,25 +1,25 @@ -package resultcounting; - -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - -public class MySuiteTest2 extends TestCase { - - public static Test suite () { - TestSuite suite = new TestSuite(); - - suite.addTest (new MySuiteTest2("testMe" )); - suite.addTest (new MySuiteTest2("testMe" )); - - return suite; - } - - public MySuiteTest2( String name ) { - super (name); - } - - public void testMe() { - assertTrue (true); - } -} +package resultcounting; + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; + +public class MySuiteTest2 extends TestCase { + + public static Test suite () { + TestSuite suite = new TestSuite(); + + suite.addTest (new MySuiteTest2("testMe" )); + suite.addTest (new MySuiteTest2("testMe" )); + + return suite; + } + + public MySuiteTest2( String name ) { + super (name); + } + + public void testMe() { + assertTrue (true); + } +} diff --git a/surefire-integration-tests/src/test/resources/result-counting/src/test/java/resultcounting/MySuiteTest3.java b/surefire-integration-tests/src/test/resources/result-counting/src/test/java/resultcounting/MySuiteTest3.java index a60993adaf..4c08224661 100644 --- a/surefire-integration-tests/src/test/resources/result-counting/src/test/java/resultcounting/MySuiteTest3.java +++ b/surefire-integration-tests/src/test/resources/result-counting/src/test/java/resultcounting/MySuiteTest3.java @@ -1,26 +1,26 @@ -package resultcounting; - -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - -public class MySuiteTest3 extends TestCase { - - public static Test suite () { - TestSuite suite = new TestSuite(); - - suite.addTest (new MySuiteTest3("testMe" )); - suite.addTest (new MySuiteTest3("testMe" )); - suite.addTest (new MySuiteTest3("testMe" )); - - return suite; - } - - public MySuiteTest3( String name ) { - super (name); - } - - public void testMe() { - assertTrue (true); - } -} +package resultcounting; + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; + +public class MySuiteTest3 extends TestCase { + + public static Test suite () { + TestSuite suite = new TestSuite(); + + suite.addTest (new MySuiteTest3("testMe" )); + suite.addTest (new MySuiteTest3("testMe" )); + suite.addTest (new MySuiteTest3("testMe" )); + + return suite; + } + + public MySuiteTest3( String name ) { + super (name); + } + + public void testMe() { + assertTrue (true); + } +} diff --git a/surefire-integration-tests/src/test/resources/result-counting/src/test/java/resultcounting/Test1.java b/surefire-integration-tests/src/test/resources/result-counting/src/test/java/resultcounting/Test1.java index 6833e0ecdc..c3283d2be6 100644 --- a/surefire-integration-tests/src/test/resources/result-counting/src/test/java/resultcounting/Test1.java +++ b/surefire-integration-tests/src/test/resources/result-counting/src/test/java/resultcounting/Test1.java @@ -1,76 +1,76 @@ -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; -import static org.junit.Assert.fail; -import static org.hamcrest.CoreMatchers.*; -import static org.junit.Assume.*; -import junit.framework.TestCase; - -public class Test1 extends TestCase -{ - public void testWithFailingAssumption1() { - assumeThat( 2, is(3)); - } - public void testWithFailingAssumption2() { - assumeThat( 2, is(3)); - } - public void testWithFailingAssumption3() { - assumeThat( 2, is(3)); - } - public void testWithFailingAssumption4() { - assumeThat( 2, is(3)); - } - public void testWithFailingAssumption5() { - assumeThat( 2, is(3)); - } - public void testWithFailingAssumption6() { - assumeThat( 2, is(3)); - } - public void testWithFailingAssumption7() { - assumeThat( 2, is(3)); - } - public void testWithFailingAssumption8() { - assumeThat( 2, is(3)); - } - public void testWithFailingAssumption9() { - assumeThat( 2, is(3)); - } - public void testWithFailingAssumption10() { - assumeThat( 2, is(3)); - } - public void testWithFailingAssumption11() { - assumeThat( 2, is(3)); - } - public void testWithFailingAssumption12() { - assumeThat( 2, is(3)); - } - public void testWithFailingAssumption13() { - assumeThat( 2, is(3)); - } - public void testWithFailingAssumption14() { - assumeThat( 2, is(3)); - } - public void testWithFailingAssumption15() { - assumeThat( 2, is(3)); - } +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; +import static org.junit.Assert.fail; +import static org.hamcrest.CoreMatchers.*; +import static org.junit.Assume.*; +import junit.framework.TestCase; + +public class Test1 extends TestCase +{ + public void testWithFailingAssumption1() { + assumeThat( 2, is(3)); + } + public void testWithFailingAssumption2() { + assumeThat( 2, is(3)); + } + public void testWithFailingAssumption3() { + assumeThat( 2, is(3)); + } + public void testWithFailingAssumption4() { + assumeThat( 2, is(3)); + } + public void testWithFailingAssumption5() { + assumeThat( 2, is(3)); + } + public void testWithFailingAssumption6() { + assumeThat( 2, is(3)); + } + public void testWithFailingAssumption7() { + assumeThat( 2, is(3)); + } + public void testWithFailingAssumption8() { + assumeThat( 2, is(3)); + } + public void testWithFailingAssumption9() { + assumeThat( 2, is(3)); + } + public void testWithFailingAssumption10() { + assumeThat( 2, is(3)); + } + public void testWithFailingAssumption11() { + assumeThat( 2, is(3)); + } + public void testWithFailingAssumption12() { + assumeThat( 2, is(3)); + } + public void testWithFailingAssumption13() { + assumeThat( 2, is(3)); + } + public void testWithFailingAssumption14() { + assumeThat( 2, is(3)); + } + public void testWithFailingAssumption15() { + assumeThat( 2, is(3)); + } } \ No newline at end of file diff --git a/surefire-integration-tests/src/test/resources/small-result-counting/src/test/java/smallresultcounting/Test1.java b/surefire-integration-tests/src/test/resources/small-result-counting/src/test/java/smallresultcounting/Test1.java index 8a0fd3d521..66c7337dc3 100644 --- a/surefire-integration-tests/src/test/resources/small-result-counting/src/test/java/smallresultcounting/Test1.java +++ b/surefire-integration-tests/src/test/resources/small-result-counting/src/test/java/smallresultcounting/Test1.java @@ -1,47 +1,47 @@ -package smallresultcounting; - -import org.junit.Test; - -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assume.assumeThat; - -public class Test1 -{ - @Test - public void testWithFailingAssumption1() - { - assumeThat( 2, is( 3 ) ); - } - - @Test - public void testWithFailingAssumption2() - { - try - { - Thread.sleep( 150 ); - } - catch ( InterruptedException ignore ) - { - } - - assumeThat( 2, is( 3 ) ); - } - - @Test - public void testWithFailingAssumption3() - { - assumeThat( 2, is( 3 ) ); - } - - @Test - public void testWithFailingAssumption4() - { - assumeThat( 2, is( 3 ) ); - } - - @Test - public void testWithFailingAssumption5() - { - assumeThat( 2, is( 3 ) ); - } +package smallresultcounting; + +import org.junit.Test; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assume.assumeThat; + +public class Test1 +{ + @Test + public void testWithFailingAssumption1() + { + assumeThat( 2, is( 3 ) ); + } + + @Test + public void testWithFailingAssumption2() + { + try + { + Thread.sleep( 150 ); + } + catch ( InterruptedException ignore ) + { + } + + assumeThat( 2, is( 3 ) ); + } + + @Test + public void testWithFailingAssumption3() + { + assumeThat( 2, is( 3 ) ); + } + + @Test + public void testWithFailingAssumption4() + { + assumeThat( 2, is( 3 ) ); + } + + @Test + public void testWithFailingAssumption5() + { + assumeThat( 2, is( 3 ) ); + } } \ No newline at end of file diff --git a/surefire-integration-tests/src/test/resources/small-result-counting/src/test/java/smallresultcounting/Test2.java b/surefire-integration-tests/src/test/resources/small-result-counting/src/test/java/smallresultcounting/Test2.java index 5f7459f944..dbacce7d84 100644 --- a/surefire-integration-tests/src/test/resources/small-result-counting/src/test/java/smallresultcounting/Test2.java +++ b/surefire-integration-tests/src/test/resources/small-result-counting/src/test/java/smallresultcounting/Test2.java @@ -1,88 +1,88 @@ -package smallresultcounting; - -import org.junit.Ignore; -import org.junit.Test; - -import static junit.framework.Assert.fail; - -/** - * @author Kristian Rosenvold - */ -public class Test2 -{ - @Test - public void testiWithFail1() - { - fail( "We excpect this1" ); - } - - @Test - public void testWithException1() - { - System.out.println( "testWithException1 to stdout" ); - System.err.println( "testWithException1 to stderr" ); - throw new RuntimeException( "We expect this1-1" ); - } - - @Test - public void testWithException2() - { - throw new RuntimeException( "We expect this1-2" ); - } - - - @Ignore( "We do this for a reason1" ) - @Test - public void testWithIgnore1() - { - } - - @Ignore( "We do this for a reason2" ) - @Test - public void testWithIgnore2() - { - } - - @Ignore - @Test - public void testWithIgnore3() - { - } - - @Test - public void testAllok1() - { - System.out.println( "testAllok1 to stdout" ); - System.err.println( "testAllok1 to stderr" ); - try - { - Thread.sleep( 100 ); - } - catch ( InterruptedException ignore ) - { - } - } - - @Test - public void testAllok2() - { - } - - @Test - public void testAllok3() - { - try - { - Thread.sleep( 250 ); - } - catch ( InterruptedException ignore ) - { - } - } - - @Test - public void testAllok4() - { - } - +package smallresultcounting; + +import org.junit.Ignore; +import org.junit.Test; + +import static junit.framework.Assert.fail; + +/** + * @author Kristian Rosenvold + */ +public class Test2 +{ + @Test + public void testiWithFail1() + { + fail( "We excpect this1" ); + } + + @Test + public void testWithException1() + { + System.out.println( "testWithException1 to stdout" ); + System.err.println( "testWithException1 to stderr" ); + throw new RuntimeException( "We expect this1-1" ); + } + + @Test + public void testWithException2() + { + throw new RuntimeException( "We expect this1-2" ); + } + + + @Ignore( "We do this for a reason1" ) + @Test + public void testWithIgnore1() + { + } + + @Ignore( "We do this for a reason2" ) + @Test + public void testWithIgnore2() + { + } + + @Ignore + @Test + public void testWithIgnore3() + { + } + + @Test + public void testAllok1() + { + System.out.println( "testAllok1 to stdout" ); + System.err.println( "testAllok1 to stderr" ); + try + { + Thread.sleep( 100 ); + } + catch ( InterruptedException ignore ) + { + } + } + + @Test + public void testAllok2() + { + } + + @Test + public void testAllok3() + { + try + { + Thread.sleep( 250 ); + } + catch ( InterruptedException ignore ) + { + } + } + + @Test + public void testAllok4() + { + } + } \ No newline at end of file diff --git a/surefire-integration-tests/src/test/resources/surefire-500-puzzling-error/src/test/java/surefire500/PassingTest.java b/surefire-integration-tests/src/test/resources/surefire-500-puzzling-error/src/test/java/surefire500/PassingTest.java index a87f46d2b6..ea15f449da 100644 --- a/surefire-integration-tests/src/test/resources/surefire-500-puzzling-error/src/test/java/surefire500/PassingTest.java +++ b/surefire-integration-tests/src/test/resources/surefire-500-puzzling-error/src/test/java/surefire500/PassingTest.java @@ -1,33 +1,33 @@ -package surefire500; - -import org.junit.Test; - -import static org.junit.Assert.assertTrue; - -public class PassingTest { - - @Test - public void testOne() - { - assertTrue(true); - } - - @Test - public void testTwo() - { - assertTrue(true); - } - - @Test - public void testThree() - { - assertTrue(true); - } - - @Test - public void testFour() - { - assertTrue(true); - } - -} +package surefire500; + +import org.junit.Test; + +import static org.junit.Assert.assertTrue; + +public class PassingTest { + + @Test + public void testOne() + { + assertTrue(true); + } + + @Test + public void testTwo() + { + assertTrue(true); + } + + @Test + public void testThree() + { + assertTrue(true); + } + + @Test + public void testFour() + { + assertTrue(true); + } + +} diff --git a/surefire-integration-tests/src/test/resources/surefire-500-puzzling-error/src/test/java/surefire500/Suite.java b/surefire-integration-tests/src/test/resources/surefire-500-puzzling-error/src/test/java/surefire500/Suite.java index d039713487..59e5a428d6 100644 --- a/surefire-integration-tests/src/test/resources/surefire-500-puzzling-error/src/test/java/surefire500/Suite.java +++ b/surefire-integration-tests/src/test/resources/surefire-500-puzzling-error/src/test/java/surefire500/Suite.java @@ -1,10 +1,10 @@ -package surefire500; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite.SuiteClasses; - -@RunWith(org.junit.runners.Suite.class) -@SuiteClasses(value={ExplodingTest.class, PassingTest.class}) -public class Suite { - -} +package surefire500; + +import org.junit.runner.RunWith; +import org.junit.runners.Suite.SuiteClasses; + +@RunWith(org.junit.runners.Suite.class) +@SuiteClasses(value={ExplodingTest.class, PassingTest.class}) +public class Suite { + +} diff --git a/surefire-integration-tests/src/test/resources/surefire-569-RunTestFromDependencyJars/module1/pom.xml b/surefire-integration-tests/src/test/resources/surefire-569-RunTestFromDependencyJars/module1/pom.xml new file mode 100644 index 0000000000..9b4847c4b8 --- /dev/null +++ b/surefire-integration-tests/src/test/resources/surefire-569-RunTestFromDependencyJars/module1/pom.xml @@ -0,0 +1,50 @@ + + 4.0.0 + + + org.apache.maven.surefire + surefire-569-RunTestFromDependencyJars + 0.0.1-SNAPSHOT + ../ + + + org.apache.maven.plugins.surefire.dependency-jar + module1 + 0.0.1-SNAPSHOT + + + + junit + junit + 4.8.1 + jar + test + + + + org.apache.maven.plugins.surefire.dependency-jar + testjar + ${project.version} + tests + test + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*A*.java + + + org.apache.maven.plugins.surefire.dependency-jar:testjar + + + + + + \ No newline at end of file diff --git a/surefire-integration-tests/src/test/resources/surefire-569-RunTestFromDependencyJars/pom.xml b/surefire-integration-tests/src/test/resources/surefire-569-RunTestFromDependencyJars/pom.xml new file mode 100644 index 0000000000..d2574fce27 --- /dev/null +++ b/surefire-integration-tests/src/test/resources/surefire-569-RunTestFromDependencyJars/pom.xml @@ -0,0 +1,17 @@ + + 4.0.0 + + org.apache.maven.surefire + it-parent + 1.0 + + surefire-569-RunTestFromDependencyJars + 0.0.1-SNAPSHOT + pom + + + testjar + module1 + + diff --git a/surefire-integration-tests/src/test/resources/surefire-569-RunTestFromDependencyJars/testjar/pom.xml b/surefire-integration-tests/src/test/resources/surefire-569-RunTestFromDependencyJars/testjar/pom.xml new file mode 100644 index 0000000000..f13be52164 --- /dev/null +++ b/surefire-integration-tests/src/test/resources/surefire-569-RunTestFromDependencyJars/testjar/pom.xml @@ -0,0 +1,47 @@ + + 4.0.0 + + + org.apache.maven.surefire + surefire-569-RunTestFromDependencyJars + 0.0.1-SNAPSHOT + ../ + + + org.apache.maven.plugins.surefire.dependency-jar + testjar + 0.0.1-SNAPSHOT + + + + junit + junit + 4.8.1 + jar + test + + + + + + + maven-jar-plugin + + + + test-jar + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + true + + + + + \ No newline at end of file diff --git a/surefire-integration-tests/src/test/resources/surefire-569-RunTestFromDependencyJars/testjar/src/test/java/org/test/TestA.java b/surefire-integration-tests/src/test/resources/surefire-569-RunTestFromDependencyJars/testjar/src/test/java/org/test/TestA.java new file mode 100644 index 0000000000..6f432d1f4a --- /dev/null +++ b/surefire-integration-tests/src/test/resources/surefire-569-RunTestFromDependencyJars/testjar/src/test/java/org/test/TestA.java @@ -0,0 +1,10 @@ +package org.test; + +import org.junit.Test; + +public class TestA { + + @Test + public void shouldRun() { + } +} \ No newline at end of file diff --git a/surefire-integration-tests/src/test/resources/surefire-569-RunTestFromDependencyJars/testjar/src/test/java/org/test/TestB.java b/surefire-integration-tests/src/test/resources/surefire-569-RunTestFromDependencyJars/testjar/src/test/java/org/test/TestB.java new file mode 100644 index 0000000000..7e91ddda72 --- /dev/null +++ b/surefire-integration-tests/src/test/resources/surefire-569-RunTestFromDependencyJars/testjar/src/test/java/org/test/TestB.java @@ -0,0 +1,10 @@ +package org.test; + +import org.junit.Test; + +public class TestB { + + @Test + public void shouldRun() { + } +} \ No newline at end of file diff --git a/surefire-integration-tests/src/test/resources/surefire-570-multipleReportDirectories/module1/src/test/resources/surefire-reports/TEST-org.apache.maven.surefireReport.surefireReportTest.MyClassTest.xml b/surefire-integration-tests/src/test/resources/surefire-570-multipleReportDirectories/module1/src/test/resources/surefire-reports/TEST-org.apache.maven.surefireReport.surefireReportTest.MyClassTest.xml deleted file mode 100644 index 6f7c3c5665..0000000000 --- a/surefire-integration-tests/src/test/resources/surefire-570-multipleReportDirectories/module1/src/test/resources/surefire-reports/TEST-org.apache.maven.surefireReport.surefireReportTest.MyClassTest.xml +++ /dev/null @@ -1,71 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - junit.framework.AssertionFailedError: expected:<18> but was:<42> - at junit.framework.Assert.fail(Assert.java:47) - at junit.framework.Assert.failNotEquals(Assert.java:280) - at junit.framework.Assert.assertEquals(Assert.java:64) - at junit.framework.Assert.assertEquals(Assert.java:198) - at junit.framework.Assert.assertEquals(Assert.java:204) - at org.apache.maven.surefireReport.surefireReportTest.module1.MyDummyClassTest.testGetFooKO(MyClassTest.java:10) - - - - diff --git a/surefire-integration-tests/src/test/resources/surefire-570-multipleReportDirectories/module1/src/test/resources/surefire-reports/org.apache.maven.surefireReport.surefireReportTest.MyClassTest.txt b/surefire-integration-tests/src/test/resources/surefire-570-multipleReportDirectories/module1/src/test/resources/surefire-reports/org.apache.maven.surefireReport.surefireReportTest.MyClassTest.txt deleted file mode 100644 index 9964f13275..0000000000 --- a/surefire-integration-tests/src/test/resources/surefire-570-multipleReportDirectories/module1/src/test/resources/surefire-reports/org.apache.maven.surefireReport.surefireReportTest.MyClassTest.txt +++ /dev/null @@ -1,13 +0,0 @@ -------------------------------------------------------------------------------- -Test set: org.apache.maven.surefireReport.surefireReportTest.module1.MyDummyClassTest -------------------------------------------------------------------------------- -Tests run: 2, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 0.049 sec <<< FAILURE! -testGetFooKO(org.apache.maven.surefireReport.surefireReportTest.module1.MyDummyClassTest) Time elapsed: 0.01 sec <<< FAILURE! -junit.framework.AssertionFailedError: expected:<18> but was:<42> - at junit.framework.Assert.fail(Assert.java:47) - at junit.framework.Assert.failNotEquals(Assert.java:280) - at junit.framework.Assert.assertEquals(Assert.java:64) - at junit.framework.Assert.assertEquals(Assert.java:198) - at junit.framework.Assert.assertEquals(Assert.java:204) - at org.apache.maven.surefireReport.surefireReportTest.module1.MyDummyClassTest.testGetFooKO(MyClassTest.java:10) - diff --git a/surefire-integration-tests/src/test/resources/surefire-570-multipleReportDirectories/module2/src/test/resources/surefire-reports/TEST-org.apache.maven.surefireReport.surefireReportTest.MyClassTest.xml b/surefire-integration-tests/src/test/resources/surefire-570-multipleReportDirectories/module2/src/test/resources/surefire-reports/TEST-org.apache.maven.surefireReport.surefireReportTest.MyClassTest.xml deleted file mode 100644 index 2c9cbed200..0000000000 --- a/surefire-integration-tests/src/test/resources/surefire-570-multipleReportDirectories/module2/src/test/resources/surefire-reports/TEST-org.apache.maven.surefireReport.surefireReportTest.MyClassTest.xml +++ /dev/null @@ -1,71 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - junit.framework.AssertionFailedError: expected:<18> but was:<42> - at junit.framework.Assert.fail(Assert.java:47) - at junit.framework.Assert.failNotEquals(Assert.java:280) - at junit.framework.Assert.assertEquals(Assert.java:64) - at junit.framework.Assert.assertEquals(va:198) - at junit.framework.Assert.assertEquals(Assert.java:204) - at org.apache.maven.surefireReport.surefireReportTest.module1.MyDummyClassTest.testGetFooKO(MyClassTest.java:10) - - - - diff --git a/surefire-integration-tests/src/test/resources/surefire-570-multipleReportDirectories/module2/src/test/resources/surefire-reports/org.apache.maven.surefireReport.surefireReportTest.MyClassTest.txt b/surefire-integration-tests/src/test/resources/surefire-570-multipleReportDirectories/module2/src/test/resources/surefire-reports/org.apache.maven.surefireReport.surefireReportTest.MyClassTest.txt deleted file mode 100644 index 9964f13275..0000000000 --- a/surefire-integration-tests/src/test/resources/surefire-570-multipleReportDirectories/module2/src/test/resources/surefire-reports/org.apache.maven.surefireReport.surefireReportTest.MyClassTest.txt +++ /dev/null @@ -1,13 +0,0 @@ -------------------------------------------------------------------------------- -Test set: org.apache.maven.surefireReport.surefireReportTest.module1.MyDummyClassTest -------------------------------------------------------------------------------- -Tests run: 2, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 0.049 sec <<< FAILURE! -testGetFooKO(org.apache.maven.surefireReport.surefireReportTest.module1.MyDummyClassTest) Time elapsed: 0.01 sec <<< FAILURE! -junit.framework.AssertionFailedError: expected:<18> but was:<42> - at junit.framework.Assert.fail(Assert.java:47) - at junit.framework.Assert.failNotEquals(Assert.java:280) - at junit.framework.Assert.assertEquals(Assert.java:64) - at junit.framework.Assert.assertEquals(Assert.java:198) - at junit.framework.Assert.assertEquals(Assert.java:204) - at org.apache.maven.surefireReport.surefireReportTest.module1.MyDummyClassTest.testGetFooKO(MyClassTest.java:10) - diff --git a/surefire-integration-tests/src/test/resources/surefire-621-testCounting-junit3-in-parallel/src/it/java/mho/MySuiteTest1.java b/surefire-integration-tests/src/test/resources/surefire-621-testCounting-junit3-in-parallel/src/it/java/mho/MySuiteTest1.java index a3fde44977..f836baaa43 100644 --- a/surefire-integration-tests/src/test/resources/surefire-621-testCounting-junit3-in-parallel/src/it/java/mho/MySuiteTest1.java +++ b/surefire-integration-tests/src/test/resources/surefire-621-testCounting-junit3-in-parallel/src/it/java/mho/MySuiteTest1.java @@ -1,29 +1,29 @@ -package mho; - -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - - -public class MySuiteTest1 extends TestCase { - - public static Test suite () { - TestSuite suite = new TestSuite(); - - suite.addTest (new MySuiteTest1("testMe", 1)); - - return suite; - } - - private final int number; - - public MySuiteTest1(String name, int number) { - super (name); - this.number = number; - } - - public void testMe() { - System.out.println ("### "+ this.getClass().getName()+":"+this.getName()+" - number "+number); - assertTrue (true); - } -} +package mho; + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; + + +public class MySuiteTest1 extends TestCase { + + public static Test suite () { + TestSuite suite = new TestSuite(); + + suite.addTest (new MySuiteTest1("testMe", 1)); + + return suite; + } + + private final int number; + + public MySuiteTest1(String name, int number) { + super (name); + this.number = number; + } + + public void testMe() { + System.out.println ("### "+ this.getClass().getName()+":"+this.getName()+" - number "+number); + assertTrue (true); + } +} diff --git a/surefire-integration-tests/src/test/resources/surefire-621-testCounting-junit3-in-parallel/src/it/java/mho/MySuiteTest2.java b/surefire-integration-tests/src/test/resources/surefire-621-testCounting-junit3-in-parallel/src/it/java/mho/MySuiteTest2.java index 79875694f9..09644db32c 100644 --- a/surefire-integration-tests/src/test/resources/surefire-621-testCounting-junit3-in-parallel/src/it/java/mho/MySuiteTest2.java +++ b/surefire-integration-tests/src/test/resources/surefire-621-testCounting-junit3-in-parallel/src/it/java/mho/MySuiteTest2.java @@ -1,30 +1,30 @@ -package mho; - -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - - -public class MySuiteTest2 extends TestCase { - - public static Test suite () { - TestSuite suite = new TestSuite(); - - suite.addTest (new MySuiteTest2("testMe", 1)); - suite.addTest (new MySuiteTest2("testMe", 2)); - - return suite; - } - - private final int number; - - public MySuiteTest2(String name, int number) { - super (name); - this.number = number; - } - - public void testMe() { - System.out.println ("### "+ this.getClass().getName()+":"+this.getName()+" - number "+number); - assertTrue (true); - } -} +package mho; + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; + + +public class MySuiteTest2 extends TestCase { + + public static Test suite () { + TestSuite suite = new TestSuite(); + + suite.addTest (new MySuiteTest2("testMe", 1)); + suite.addTest (new MySuiteTest2("testMe", 2)); + + return suite; + } + + private final int number; + + public MySuiteTest2(String name, int number) { + super (name); + this.number = number; + } + + public void testMe() { + System.out.println ("### "+ this.getClass().getName()+":"+this.getName()+" - number "+number); + assertTrue (true); + } +} diff --git a/surefire-integration-tests/src/test/resources/surefire-621-testCounting-junit3-in-parallel/src/it/java/mho/MySuiteTest3.java b/surefire-integration-tests/src/test/resources/surefire-621-testCounting-junit3-in-parallel/src/it/java/mho/MySuiteTest3.java index aa979b492e..39ca6e323f 100644 --- a/surefire-integration-tests/src/test/resources/surefire-621-testCounting-junit3-in-parallel/src/it/java/mho/MySuiteTest3.java +++ b/surefire-integration-tests/src/test/resources/surefire-621-testCounting-junit3-in-parallel/src/it/java/mho/MySuiteTest3.java @@ -1,30 +1,30 @@ -package mho; - -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - -public class MySuiteTest3 extends TestCase { - - public static Test suite () { - TestSuite suite = new TestSuite(); - - suite.addTest (new MySuiteTest3("testMe", 1)); - suite.addTest (new MySuiteTest3("testMe", 2)); - suite.addTest (new MySuiteTest3("testMe", 3)); - - return suite; - } - - private final int number; - - public MySuiteTest3(String name, int number) { - super (name); - this.number = number; - } - - public void testMe() { - System.out.println ("### "+ this.getClass().getName()+":"+this.getName()+" - number "+number); - assertTrue (true); - } -} +package mho; + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; + +public class MySuiteTest3 extends TestCase { + + public static Test suite () { + TestSuite suite = new TestSuite(); + + suite.addTest (new MySuiteTest3("testMe", 1)); + suite.addTest (new MySuiteTest3("testMe", 2)); + suite.addTest (new MySuiteTest3("testMe", 3)); + + return suite; + } + + private final int number; + + public MySuiteTest3(String name, int number) { + super (name); + this.number = number; + } + + public void testMe() { + System.out.println ("### "+ this.getClass().getName()+":"+this.getName()+" - number "+number); + assertTrue (true); + } +} diff --git a/surefire-integration-tests/src/test/resources/surefire-685-commaseparatedIncludes/src/test/java/surefire685/TestA.java b/surefire-integration-tests/src/test/resources/surefire-685-commaseparatedIncludes/src/test/java/surefire685/TestA.java index aaee6f7289..b34e4100a0 100644 --- a/surefire-integration-tests/src/test/resources/surefire-685-commaseparatedIncludes/src/test/java/surefire685/TestA.java +++ b/surefire-integration-tests/src/test/resources/surefire-685-commaseparatedIncludes/src/test/java/surefire685/TestA.java @@ -1,29 +1,29 @@ -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; - - -public class TestA - extends TestCase -{ - public void testTwo() { - } -} +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; + + +public class TestA + extends TestCase +{ + public void testTwo() { + } +} diff --git a/surefire-integration-tests/src/test/resources/surefire-685-commaseparatedIncludes/src/test/java/surefire685/TestB.java b/surefire-integration-tests/src/test/resources/surefire-685-commaseparatedIncludes/src/test/java/surefire685/TestB.java index 43cf56d98e..6e272d709d 100644 --- a/surefire-integration-tests/src/test/resources/surefire-685-commaseparatedIncludes/src/test/java/surefire685/TestB.java +++ b/surefire-integration-tests/src/test/resources/surefire-685-commaseparatedIncludes/src/test/java/surefire685/TestB.java @@ -1,29 +1,29 @@ -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; - - -public class TestB - extends TestCase -{ - public void testTwo() { - } -} +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; + + +public class TestB + extends TestCase +{ + public void testTwo() { + } +} diff --git a/surefire-integration-tests/src/test/resources/surefire-685-commaseparatedIncludes/src/test/java/surefire685/TestC.java b/surefire-integration-tests/src/test/resources/surefire-685-commaseparatedIncludes/src/test/java/surefire685/TestC.java index 35e246d6ef..68bd647eae 100644 --- a/surefire-integration-tests/src/test/resources/surefire-685-commaseparatedIncludes/src/test/java/surefire685/TestC.java +++ b/surefire-integration-tests/src/test/resources/surefire-685-commaseparatedIncludes/src/test/java/surefire685/TestC.java @@ -1,29 +1,29 @@ -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; - - -public class TestC - extends TestCase -{ - public void testTwo() { - } -} +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; + + +public class TestC + extends TestCase +{ + public void testTwo() { + } +} diff --git a/surefire-integration-tests/src/test/resources/surefire-818-ignored-tests-on-npe/pom.xml b/surefire-integration-tests/src/test/resources/surefire-818-ignored-tests-on-npe/pom.xml index 6a5dde5340..08768f7575 100644 --- a/surefire-integration-tests/src/test/resources/surefire-818-ignored-tests-on-npe/pom.xml +++ b/surefire-integration-tests/src/test/resources/surefire-818-ignored-tests-on-npe/pom.xml @@ -1,37 +1,37 @@ - - 4.0.0 - test - cyril - 0.0.1-SNAPSHOT - cyril - - - - junit - junit - 4.4 - test - - - jmock - jmock - 1.1.0 - test - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 2.5.1 - - - maven-surefire-plugin - ${surefire.version} - - - - + + 4.0.0 + test + cyril + 0.0.1-SNAPSHOT + cyril + + + + junit + junit + 4.4 + test + + + jmock + jmock + 1.1.0 + test + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.5.1 + + + maven-surefire-plugin + ${surefire.version} + + + + diff --git a/surefire-integration-tests/src/test/resources/surefire-818-ignored-tests-on-npe/src/test/java/cyril/test/FirstTest.java b/surefire-integration-tests/src/test/resources/surefire-818-ignored-tests-on-npe/src/test/java/cyril/test/FirstTest.java index 12d305c919..12cb23efed 100644 --- a/surefire-integration-tests/src/test/resources/surefire-818-ignored-tests-on-npe/src/test/java/cyril/test/FirstTest.java +++ b/surefire-integration-tests/src/test/resources/surefire-818-ignored-tests-on-npe/src/test/java/cyril/test/FirstTest.java @@ -1,36 +1,36 @@ -package cyril.test; - - -import org.jmock.Mock; -import org.jmock.MockObjectTestCase; -import org.junit.Test; - - -public class FirstTest - extends MockObjectTestCase -{ - - private Mock myServiceMock; - - @Override - protected void setUp() - throws Exception - { - myServiceMock = mock( MyService.class ); - } - - - @Test - public void test() - { - - Message myMessage = new Message( "MyMessage" ); - // Expectations - myServiceMock.expects( once() ).method( "writeMessage" ).with( eq( myMessage ) ).will( - returnValue( myMessage ) ); - - ( (MyService) myServiceMock.proxy() ).writeMessage( null ); - - } - -} +package cyril.test; + + +import org.jmock.Mock; +import org.jmock.MockObjectTestCase; +import org.junit.Test; + + +public class FirstTest + extends MockObjectTestCase +{ + + private Mock myServiceMock; + + @Override + protected void setUp() + throws Exception + { + myServiceMock = mock( MyService.class ); + } + + + @Test + public void test() + { + + Message myMessage = new Message( "MyMessage" ); + // Expectations + myServiceMock.expects( once() ).method( "writeMessage" ).with( eq( myMessage ) ).will( + returnValue( myMessage ) ); + + ( (MyService) myServiceMock.proxy() ).writeMessage( null ); + + } + +} diff --git a/surefire-integration-tests/src/test/resources/surefire-818-ignored-tests-on-npe/src/test/java/cyril/test/IgnoredTest.java b/surefire-integration-tests/src/test/resources/surefire-818-ignored-tests-on-npe/src/test/java/cyril/test/IgnoredTest.java index 80ff3120a2..02250ee924 100644 --- a/surefire-integration-tests/src/test/resources/surefire-818-ignored-tests-on-npe/src/test/java/cyril/test/IgnoredTest.java +++ b/surefire-integration-tests/src/test/resources/surefire-818-ignored-tests-on-npe/src/test/java/cyril/test/IgnoredTest.java @@ -1,16 +1,16 @@ -package cyril.test; - -import org.junit.Test; - - -public class IgnoredTest -{ - - - @Test - public void test() - { - System.out.println( "My test is running fine" ); - } - -} +package cyril.test; + +import org.junit.Test; + + +public class IgnoredTest +{ + + + @Test + public void test() + { + System.out.println( "My test is running fine" ); + } + +} diff --git a/surefire-integration-tests/src/test/resources/surefire-818-ignored-tests-on-npe/src/test/java/cyril/test/Message.java b/surefire-integration-tests/src/test/resources/surefire-818-ignored-tests-on-npe/src/test/java/cyril/test/Message.java index c3e4249ae1..0c08805154 100644 --- a/surefire-integration-tests/src/test/resources/surefire-818-ignored-tests-on-npe/src/test/java/cyril/test/Message.java +++ b/surefire-integration-tests/src/test/resources/surefire-818-ignored-tests-on-npe/src/test/java/cyril/test/Message.java @@ -1,18 +1,18 @@ -package cyril.test; - -public class Message -{ - - private String content; - - public Message( String content ) - { - this.content = content; - } - - public int hashCode() - { - throw new NullPointerException(); - } - -} +package cyril.test; + +public class Message +{ + + private String content; + + public Message( String content ) + { + this.content = content; + } + + public int hashCode() + { + throw new NullPointerException(); + } + +} diff --git a/surefire-integration-tests/src/test/resources/surefire-818-ignored-tests-on-npe/src/test/java/cyril/test/MyService.java b/surefire-integration-tests/src/test/resources/surefire-818-ignored-tests-on-npe/src/test/java/cyril/test/MyService.java index 892351f8d8..8fa59f709c 100644 --- a/surefire-integration-tests/src/test/resources/surefire-818-ignored-tests-on-npe/src/test/java/cyril/test/MyService.java +++ b/surefire-integration-tests/src/test/resources/surefire-818-ignored-tests-on-npe/src/test/java/cyril/test/MyService.java @@ -1,8 +1,8 @@ -package cyril.test; - -public interface MyService -{ - - public Message writeMessage( Message aMessage ); - -} +package cyril.test; + +public interface MyService +{ + + public Message writeMessage( Message aMessage ); + +} diff --git a/surefire-integration-tests/src/test/resources/surefire-818-ignored-tests-on-npe/src/test/java/cyril/test/MyServiceImpl.java b/surefire-integration-tests/src/test/resources/surefire-818-ignored-tests-on-npe/src/test/java/cyril/test/MyServiceImpl.java index fc7f2b9ef1..f390ade5a3 100644 --- a/surefire-integration-tests/src/test/resources/surefire-818-ignored-tests-on-npe/src/test/java/cyril/test/MyServiceImpl.java +++ b/surefire-integration-tests/src/test/resources/surefire-818-ignored-tests-on-npe/src/test/java/cyril/test/MyServiceImpl.java @@ -1,12 +1,12 @@ -package cyril.test; - -public class MyServiceImpl - implements MyService -{ - - public Message writeMessage( Message aMessage ) - { - return aMessage; - } - -} +package cyril.test; + +public class MyServiceImpl + implements MyService +{ + + public Message writeMessage( Message aMessage ) + { + return aMessage; + } + +} diff --git a/surefire-integration-tests/src/test/resources/surefire-822-legal-JUnit4-descriptions/src/test/java/surefire/testcase/JunitParamsTest.java b/surefire-integration-tests/src/test/resources/surefire-822-legal-JUnit4-descriptions/src/test/java/surefire/testcase/JunitParamsTest.java index 42f59519ba..3ccd814296 100644 --- a/surefire-integration-tests/src/test/resources/surefire-822-legal-JUnit4-descriptions/src/test/java/surefire/testcase/JunitParamsTest.java +++ b/surefire-integration-tests/src/test/resources/surefire-822-legal-JUnit4-descriptions/src/test/java/surefire/testcase/JunitParamsTest.java @@ -1,51 +1,51 @@ -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; - -import junitparams.JUnitParamsRunner; -import junitparams.Parameters; -import org.junit.Test; -import org.junit.runner.RunWith; - -import static org.hamcrest.CoreMatchers.equalTo; -import static org.junit.Assert.assertThat; - -/** - * Surefire JunitParams test. - */ -@RunWith( JUnitParamsRunner.class ) -public class JunitParamsTest -{ - - @Parameters( method = "parameters" ) - @Test - public void testSum( int a, int b, int expected ) - { - assertThat( a + b, equalTo( expected ) ); - } - - public Collection parameters() - { - Integer[][] parameters = { { 1, 2, 3 }, { 2, 3, 5 }, { 3, 4, 7 }, }; - return Arrays.asList( parameters ); - } -} +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; + +import junitparams.JUnitParamsRunner; +import junitparams.Parameters; +import org.junit.Test; +import org.junit.runner.RunWith; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.junit.Assert.assertThat; + +/** + * Surefire JunitParams test. + */ +@RunWith( JUnitParamsRunner.class ) +public class JunitParamsTest +{ + + @Parameters( method = "parameters" ) + @Test + public void testSum( int a, int b, int expected ) + { + assertThat( a + b, equalTo( expected ) ); + } + + public Collection parameters() + { + Integer[][] parameters = { { 1, 2, 3 }, { 2, 3, 5 }, { 3, 4, 7 }, }; + return Arrays.asList( parameters ); + } +} diff --git a/surefire-integration-tests/src/test/resources/surefire-822-legal-JUnit4-descriptions/src/test/java/surefire/testcase/NonJunitParamsTest.java b/surefire-integration-tests/src/test/resources/surefire-822-legal-JUnit4-descriptions/src/test/java/surefire/testcase/NonJunitParamsTest.java index fc70b2e44c..6cffeeb6a8 100644 --- a/surefire-integration-tests/src/test/resources/surefire-822-legal-JUnit4-descriptions/src/test/java/surefire/testcase/NonJunitParamsTest.java +++ b/surefire-integration-tests/src/test/resources/surefire-822-legal-JUnit4-descriptions/src/test/java/surefire/testcase/NonJunitParamsTest.java @@ -1,37 +1,37 @@ -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; -import static org.junit.Assert.assertThat; - -/** - * Surefire non-JunitParams test. - */ -public class NonJunitParamsTest -{ - - @Test - public void testSum() - { - assertThat( 1 + 2, equalTo( 3 ) ); - } -} +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; +import static org.junit.Assert.assertThat; + +/** + * Surefire non-JunitParams test. + */ +public class NonJunitParamsTest +{ + + @Test + public void testSum() + { + assertThat( 1 + 2, equalTo( 3 ) ); + } +} diff --git a/surefire-integration-tests/src/test/resources/surefire-847-testngfail/pom.xml b/surefire-integration-tests/src/test/resources/surefire-847-testngfail/pom.xml index 0b9b8826b5..c321c6ecb5 100644 --- a/surefire-integration-tests/src/test/resources/surefire-847-testngfail/pom.xml +++ b/surefire-integration-tests/src/test/resources/surefire-847-testngfail/pom.xml @@ -1,67 +1,67 @@ - - - - 4.0.0 - org.codehaus.jira - surefire-847 - 0.0.1-SNAPSHOT - - - com.google.inject - guice - 3.0 - no_aop - test - - - org.testng - testng - 6.5.1 - test - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 2.3.2 - - 1.5 - 1.5 - - - - org.apache.maven.plugins - maven-surefire-plugin - ${surefire.version} - - false - ${project.build.directory}/test-classes - - - - - - - ${basedir}/src/test/resources/suite.xml - - + + + + 4.0.0 + org.codehaus.jira + surefire-847 + 0.0.1-SNAPSHOT + + + com.google.inject + guice + 3.0 + no_aop + test + + + org.testng + testng + 6.5.1 + test + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.3.2 + + 1.5 + 1.5 + + + + org.apache.maven.plugins + maven-surefire-plugin + ${surefire.version} + + false + ${project.build.directory}/test-classes + + + + + + + ${basedir}/src/test/resources/suite.xml + + diff --git a/surefire-integration-tests/src/test/resources/surefire-926-2-provider-failure/pom.xml b/surefire-integration-tests/src/test/resources/surefire-926-2-provider-failure/pom.xml index eb634e723d..ecafe113e2 100644 --- a/surefire-integration-tests/src/test/resources/surefire-926-2-provider-failure/pom.xml +++ b/surefire-integration-tests/src/test/resources/surefire-926-2-provider-failure/pom.xml @@ -1,41 +1,41 @@ - - 4.0.0 - groupId - artifactId - 1.0-SNAPSHOT - - - - org.apache.maven.plugins - maven-surefire-plugin - ${surefire.version} - - - org.apache.maven.surefire - surefire-testng - ${surefire.version} - - - org.apache.maven.surefire - surefire-junit47 - ${surefire.version} - - - - - - - - junit - junit - 4.10 - test - - - org.testng - testng - 6.8 - test - - - + + 4.0.0 + groupId + artifactId + 1.0-SNAPSHOT + + + + org.apache.maven.plugins + maven-surefire-plugin + ${surefire.version} + + + org.apache.maven.surefire + surefire-testng + ${surefire.version} + + + org.apache.maven.surefire + surefire-junit47 + ${surefire.version} + + + + + + + + junit + junit + 4.10 + test + + + org.testng + testng + 6.8 + test + + + diff --git a/surefire-integration-tests/src/test/resources/surefire-926-2-provider-failure/src/test/java/com/company/JUnitTest.java b/surefire-integration-tests/src/test/resources/surefire-926-2-provider-failure/src/test/java/com/company/JUnitTest.java index 434a95c438..29d84a0756 100644 --- a/surefire-integration-tests/src/test/resources/surefire-926-2-provider-failure/src/test/java/com/company/JUnitTest.java +++ b/surefire-integration-tests/src/test/resources/surefire-926-2-provider-failure/src/test/java/com/company/JUnitTest.java @@ -1,12 +1,12 @@ -package com.company; - -import org.junit.Assert; -import org.junit.Test; - -public class JUnitTest { - @Test - public void test() { - //Assert.assertTrue(true); - Assert.assertTrue(false); - } -} +package com.company; + +import org.junit.Assert; +import org.junit.Test; + +public class JUnitTest { + @Test + public void test() { + //Assert.assertTrue(true); + Assert.assertTrue(false); + } +} diff --git a/surefire-integration-tests/src/test/resources/surefire-926-2-provider-failure/src/test/java/com/company/TestNGTest.java b/surefire-integration-tests/src/test/resources/surefire-926-2-provider-failure/src/test/java/com/company/TestNGTest.java index 480372d451..5d70f9f3ea 100644 --- a/surefire-integration-tests/src/test/resources/surefire-926-2-provider-failure/src/test/java/com/company/TestNGTest.java +++ b/surefire-integration-tests/src/test/resources/surefire-926-2-provider-failure/src/test/java/com/company/TestNGTest.java @@ -1,12 +1,12 @@ -package com.company; - -import org.testng.Assert; -import org.testng.annotations.Test; - -public class TestNGTest { - @Test - public void test() { - Assert.assertTrue(true); - //Assert.assertTrue(false); - } -} +package com.company; + +import org.testng.Assert; +import org.testng.annotations.Test; + +public class TestNGTest { + @Test + public void test() { + Assert.assertTrue(true); + //Assert.assertTrue(false); + } +} diff --git a/surefire-integration-tests/src/test/resources/surefire-931-provider-failure/pom.xml b/surefire-integration-tests/src/test/resources/surefire-931-provider-failure/pom.xml index baff4b4f03..8f34a4302f 100644 --- a/surefire-integration-tests/src/test/resources/surefire-931-provider-failure/pom.xml +++ b/surefire-integration-tests/src/test/resources/surefire-931-provider-failure/pom.xml @@ -1,48 +1,48 @@ - - 4.0.0 - - com.mycompany - TestFailed - 1.0-SNAPSHOT - jar - - TestFailed - http://maven.apache.org - - - UTF-8 - - - - - org.apache.maven.plugins - maven-compiler-plugin - 2.3.2 - - 1.7 - 1.7 - - - - org.apache.maven.plugins - maven-surefire-plugin - ${surefire.version} - - - - - - - junit - junit - 3.8.1 - test - - - org.testng - testng - 6.8 - - - + + 4.0.0 + + com.mycompany + TestFailed + 1.0-SNAPSHOT + jar + + TestFailed + http://maven.apache.org + + + UTF-8 + + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.3.2 + + 1.7 + 1.7 + + + + org.apache.maven.plugins + maven-surefire-plugin + ${surefire.version} + + + + + + + junit + junit + 3.8.1 + test + + + org.testng + testng + 6.8 + + + diff --git a/surefire-integration-tests/src/test/resources/surefire-931-provider-failure/src/main/java/com/mycompany/testfailed/App.java b/surefire-integration-tests/src/test/resources/surefire-931-provider-failure/src/main/java/com/mycompany/testfailed/App.java index 4562c1afdb..f5544af47b 100644 --- a/surefire-integration-tests/src/test/resources/surefire-931-provider-failure/src/main/java/com/mycompany/testfailed/App.java +++ b/surefire-integration-tests/src/test/resources/surefire-931-provider-failure/src/main/java/com/mycompany/testfailed/App.java @@ -1,13 +1,13 @@ -package com.mycompany.testfailed; - -/** - * Hello world! - * - */ -public class App -{ - public static void main( String[] args ) - { - System.out.println( "Hello World!" ); - } -} +package com.mycompany.testfailed; + +/** + * Hello world! + * + */ +public class App +{ + public static void main( String[] args ) + { + System.out.println( "Hello World!" ); + } +} diff --git a/surefire-integration-tests/src/test/resources/surefire-931-provider-failure/src/test/java/com/mycompany/testfailed/AppTest.java b/surefire-integration-tests/src/test/resources/surefire-931-provider-failure/src/test/java/com/mycompany/testfailed/AppTest.java index 492f8333fc..57c0d927ae 100644 --- a/surefire-integration-tests/src/test/resources/surefire-931-provider-failure/src/test/java/com/mycompany/testfailed/AppTest.java +++ b/surefire-integration-tests/src/test/resources/surefire-931-provider-failure/src/test/java/com/mycompany/testfailed/AppTest.java @@ -1,18 +1,18 @@ -package com.mycompany.testfailed; - -import junit.framework.TestCase; -import org.testng.annotations.Test; - - -/** - * Unit test for simple App. - */ -public class AppTest - extends TestCase -{ - @Test(groups = "deleteLocation", dependsOnGroups = - { - "postLocation", "getLocation" - }) - public void removeNonExistentLocation() {} -} +package com.mycompany.testfailed; + +import junit.framework.TestCase; +import org.testng.annotations.Test; + + +/** + * Unit test for simple App. + */ +public class AppTest + extends TestCase +{ + @Test(groups = "deleteLocation", dependsOnGroups = + { + "postLocation", "getLocation" + }) + public void removeNonExistentLocation() {} +} diff --git a/surefire-integration-tests/src/test/resources/surefire-942-testngSuite/pom.xml b/surefire-integration-tests/src/test/resources/surefire-942-testngSuite/pom.xml new file mode 100644 index 0000000000..2a0fac5d65 --- /dev/null +++ b/surefire-integration-tests/src/test/resources/surefire-942-testngSuite/pom.xml @@ -0,0 +1,37 @@ + + + 4.0.0 + + surefire-testng + surefire-testng + 1.0-SNAPSHOT + + + 2.12.4 + + + + + org.testng + testng + 5.14 + test + + + + + + + maven-surefire-plugin + ${surefire.version} + + + src/test/resources/config.xml + + + + + + diff --git a/surefire-integration-tests/src/test/resources/surefire-942-testngSuite/src/test/java/org/BasicTest.java b/surefire-integration-tests/src/test/resources/surefire-942-testngSuite/src/test/java/org/BasicTest.java new file mode 100644 index 0000000000..a663ac5a31 --- /dev/null +++ b/surefire-integration-tests/src/test/resources/surefire-942-testngSuite/src/test/java/org/BasicTest.java @@ -0,0 +1,48 @@ +package org; + +import org.testng.annotations.*; +import org.testng.Assert; + +public class BasicTest +{ + + private boolean setUpCalled = false; + + + @BeforeTest + public void setUp() + { + setUpCalled = true; + } + + @AfterTest + public void tearDown() + { + setUpCalled = false; + } + + @Test + public void testSetUp() + { + Assert.assertTrue( setUpCalled ); + } + + @Test + public void testSuccessOne() + { + Assert.assertTrue( true ); + } + + @Test + public void testSuccessTwo() + { + Assert.assertTrue( true ); + } + + @AfterClass + public static void oneTimeTearDown() + { + + } + +} diff --git a/surefire-integration-tests/src/test/resources/surefire-942-testngSuite/src/test/resources/config.xml b/surefire-integration-tests/src/test/resources/surefire-942-testngSuite/src/test/resources/config.xml new file mode 100644 index 0000000000..a92872ba00 --- /dev/null +++ b/surefire-integration-tests/src/test/resources/surefire-942-testngSuite/src/test/resources/config.xml @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/surefire-integration-tests/src/test/resources/surefire-943-report-content/pom.xml b/surefire-integration-tests/src/test/resources/surefire-943-report-content/pom.xml new file mode 100644 index 0000000000..01fb7b3d73 --- /dev/null +++ b/surefire-integration-tests/src/test/resources/surefire-943-report-content/pom.xml @@ -0,0 +1,47 @@ + + + 4.0.0 + + dummy + 1.0-SNAPSHOT + dummy + surefire-943-report-content + + + 2.13 + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + ${surefire.version} + + + org.apache.maven.surefire + surefire-junit47 + ${surefire.version} + + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.5.1 + + + + + + + + junit + junit + test + 4.11 + + + diff --git a/surefire-integration-tests/src/test/resources/surefire-943-report-content/src/test/java/org/sample/module/My1Test.java b/surefire-integration-tests/src/test/resources/surefire-943-report-content/src/test/java/org/sample/module/My1Test.java new file mode 100644 index 0000000000..a5b5b619a3 --- /dev/null +++ b/surefire-integration-tests/src/test/resources/surefire-943-report-content/src/test/java/org/sample/module/My1Test.java @@ -0,0 +1,34 @@ +package org.sample.module; + +import static org.junit.Assert.fail; + +import java.lang.management.ManagementFactory; + +import org.junit.Before; +import org.junit.Test; +import org.junit.Ignore; + +public class My1Test +{ + @Test + public void fails() + throws Exception + { + Thread.sleep( 100 ); + fail( "Always fails" ); + } + + @Test + public void alwaysSuccessful() + throws Exception + { + Thread.sleep( 100 ); + } + + @Test + @Ignore( "Ignore-Message" ) + public void alwaysIgnored() + { + + } +} diff --git a/surefire-integration-tests/src/test/resources/surefire-943-report-content/src/test/java/org/sample/module/My2Test.java b/surefire-integration-tests/src/test/resources/surefire-943-report-content/src/test/java/org/sample/module/My2Test.java new file mode 100644 index 0000000000..a9b6a0ad3b --- /dev/null +++ b/surefire-integration-tests/src/test/resources/surefire-943-report-content/src/test/java/org/sample/module/My2Test.java @@ -0,0 +1,33 @@ +package org.sample.module; + +import static org.junit.Assert.fail; + +import java.lang.management.ManagementFactory; + +import org.junit.Before; +import org.junit.Test; +import org.junit.Ignore; + +public class My2Test { + @Test + public void fails() + throws Exception + { + Thread.sleep( 100 ); + fail( "Always fails" ); + } + + @Test + public void alwaysSuccessful() + throws Exception + { + Thread.sleep( 100 ); + } + + @Test + @Ignore + public void alwaysIgnored() + { + + } +} diff --git a/surefire-integration-tests/src/test/resources/surefire-943-report-content/src/test/java/org/sample/module/My3Test.java b/surefire-integration-tests/src/test/resources/surefire-943-report-content/src/test/java/org/sample/module/My3Test.java new file mode 100644 index 0000000000..5f5b2cd704 --- /dev/null +++ b/surefire-integration-tests/src/test/resources/surefire-943-report-content/src/test/java/org/sample/module/My3Test.java @@ -0,0 +1,25 @@ +package org.sample.module; + +import static org.junit.Assert.fail; + +import java.lang.management.ManagementFactory; + +import org.junit.Before; +import org.junit.Test; + +public class My3Test { + @Test + public void fails() + throws Exception + { + Thread.sleep( 100 ); + fail( "Always fails" ); + } + + @Test + public void alwaysSuccessful() + throws Exception + { + Thread.sleep( 100 ); + } +} diff --git a/surefire-integration-tests/src/test/resources/surefire-943-report-content/src/test/java/org/sample/module/My4Test.java b/surefire-integration-tests/src/test/resources/surefire-943-report-content/src/test/java/org/sample/module/My4Test.java new file mode 100644 index 0000000000..7124d61322 --- /dev/null +++ b/surefire-integration-tests/src/test/resources/surefire-943-report-content/src/test/java/org/sample/module/My4Test.java @@ -0,0 +1,27 @@ +package org.sample.module; + +import static org.junit.Assert.fail; + +import java.lang.management.ManagementFactory; + +import org.junit.Before; +import org.junit.Test; +import org.junit.Ignore; + +@Ignore( "Ignore-Message" ) +public class My4Test +{ + + @Test + public void alsoIgnored() + { + + } + + @Test + @Ignore + public void alwaysIgnored() + { + + } +} diff --git a/surefire-integration-tests/src/test/resources/surefire-946-killMainProcessInReusableFork/pom.xml b/surefire-integration-tests/src/test/resources/surefire-946-killMainProcessInReusableFork/pom.xml new file mode 100644 index 0000000000..eb0fe599d9 --- /dev/null +++ b/surefire-integration-tests/src/test/resources/surefire-946-killMainProcessInReusableFork/pom.xml @@ -0,0 +1,64 @@ + + + + 4.0.0 + + org.apache.maven.plugins.surefire + surefire-946 + 1.0-SNAPSHOT + Tests killing the main maven process when using reusable forks + + + + junit + junit + 4.4 + test + + + + + + + org.apache.maven.plugins.surefire + maven-selfdestruct-plugin + 0.1 + + ${selfdestruct.timeoutInMillis} + ${selfdestruct.method} + + + + maven-surefire-plugin + ${surefire.version} + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.5 + 1.5 + + + + + + diff --git a/surefire-integration-tests/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic01Test.java b/surefire-integration-tests/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic01Test.java new file mode 100644 index 0000000000..efc294f286 --- /dev/null +++ b/surefire-integration-tests/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic01Test.java @@ -0,0 +1,26 @@ +package junit44.environment; + +import org.junit.AfterClass; +import org.junit.Test; + +public class Basic01Test +{ + + @Test + public void testNothing() + { + } + + @AfterClass + public static void waitSomeTimeAround() + { + try + { + Thread.sleep( Integer.getInteger( "testSleepTime", 2000 ) ); + } + catch ( InterruptedException ignored ) + { + } + } + +} diff --git a/surefire-integration-tests/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic02Test.java b/surefire-integration-tests/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic02Test.java new file mode 100644 index 0000000000..6bc29c7df8 --- /dev/null +++ b/surefire-integration-tests/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic02Test.java @@ -0,0 +1,26 @@ +package junit44.environment; + +import org.junit.AfterClass; +import org.junit.Test; + +public class Basic02Test +{ + + @Test + public void testNothing() + { + } + + @AfterClass + public static void waitSomeTimeAround() + { + try + { + Thread.sleep( Integer.getInteger( "testSleepTime", 2000 ) ); + } + catch ( InterruptedException ignored ) + { + } + } + +} diff --git a/surefire-integration-tests/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic03Test.java b/surefire-integration-tests/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic03Test.java new file mode 100644 index 0000000000..6d4941be2c --- /dev/null +++ b/surefire-integration-tests/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic03Test.java @@ -0,0 +1,26 @@ +package junit44.environment; + +import org.junit.AfterClass; +import org.junit.Test; + +public class Basic03Test +{ + + @Test + public void testNothing() + { + } + + @AfterClass + public static void waitSomeTimeAround() + { + try + { + Thread.sleep( Integer.getInteger( "testSleepTime", 2000 ) ); + } + catch ( InterruptedException ignored ) + { + } + } + +} diff --git a/surefire-integration-tests/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic04Test.java b/surefire-integration-tests/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic04Test.java new file mode 100644 index 0000000000..d3b947c3ad --- /dev/null +++ b/surefire-integration-tests/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic04Test.java @@ -0,0 +1,26 @@ +package junit44.environment; + +import org.junit.AfterClass; +import org.junit.Test; + +public class Basic04Test +{ + + @Test + public void testNothing() + { + } + + @AfterClass + public static void waitSomeTimeAround() + { + try + { + Thread.sleep( Integer.getInteger( "testSleepTime", 2000 ) ); + } + catch ( InterruptedException ignored ) + { + } + } + +} diff --git a/surefire-integration-tests/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic05Test.java b/surefire-integration-tests/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic05Test.java new file mode 100644 index 0000000000..a3b604e689 --- /dev/null +++ b/surefire-integration-tests/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic05Test.java @@ -0,0 +1,26 @@ +package junit44.environment; + +import org.junit.AfterClass; +import org.junit.Test; + +public class Basic05Test +{ + + @Test + public void testNothing() + { + } + + @AfterClass + public static void waitSomeTimeAround() + { + try + { + Thread.sleep( Integer.getInteger( "testSleepTime", 2000 ) ); + } + catch ( InterruptedException ignored ) + { + } + } + +} diff --git a/surefire-integration-tests/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic06Test.java b/surefire-integration-tests/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic06Test.java new file mode 100644 index 0000000000..ea5b951030 --- /dev/null +++ b/surefire-integration-tests/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic06Test.java @@ -0,0 +1,26 @@ +package junit44.environment; + +import org.junit.AfterClass; +import org.junit.Test; + +public class Basic06Test +{ + + @Test + public void testNothing() + { + } + + @AfterClass + public static void waitSomeTimeAround() + { + try + { + Thread.sleep( Integer.getInteger( "testSleepTime", 2000 ) ); + } + catch ( InterruptedException ignored ) + { + } + } + +} diff --git a/surefire-integration-tests/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic07Test.java b/surefire-integration-tests/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic07Test.java new file mode 100644 index 0000000000..715bc9356a --- /dev/null +++ b/surefire-integration-tests/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic07Test.java @@ -0,0 +1,26 @@ +package junit44.environment; + +import org.junit.AfterClass; +import org.junit.Test; + +public class Basic07Test +{ + + @Test + public void testNothing() + { + } + + @AfterClass + public static void waitSomeTimeAround() + { + try + { + Thread.sleep( Integer.getInteger( "testSleepTime", 2000 ) ); + } + catch ( InterruptedException ignored ) + { + } + } + +} diff --git a/surefire-integration-tests/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic08Test.java b/surefire-integration-tests/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic08Test.java new file mode 100644 index 0000000000..fbb8e005c2 --- /dev/null +++ b/surefire-integration-tests/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic08Test.java @@ -0,0 +1,26 @@ +package junit44.environment; + +import org.junit.AfterClass; +import org.junit.Test; + +public class Basic08Test +{ + + @Test + public void testNothing() + { + } + + @AfterClass + public static void waitSomeTimeAround() + { + try + { + Thread.sleep( Integer.getInteger( "testSleepTime", 2000 ) ); + } + catch ( InterruptedException ignored ) + { + } + } + +} diff --git a/surefire-integration-tests/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic09Test.java b/surefire-integration-tests/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic09Test.java new file mode 100644 index 0000000000..89fb37bdfd --- /dev/null +++ b/surefire-integration-tests/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic09Test.java @@ -0,0 +1,26 @@ +package junit44.environment; + +import org.junit.AfterClass; +import org.junit.Test; + +public class Basic09Test +{ + + @Test + public void testNothing() + { + } + + @AfterClass + public static void waitSomeTimeAround() + { + try + { + Thread.sleep( Integer.getInteger( "testSleepTime", 2000 ) ); + } + catch ( InterruptedException ignored ) + { + } + } + +} diff --git a/surefire-integration-tests/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic10Test.java b/surefire-integration-tests/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic10Test.java new file mode 100644 index 0000000000..e54edf00dc --- /dev/null +++ b/surefire-integration-tests/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic10Test.java @@ -0,0 +1,26 @@ +package junit44.environment; + +import org.junit.AfterClass; +import org.junit.Test; + +public class Basic10Test +{ + + @Test + public void testNothing() + { + } + + @AfterClass + public static void waitSomeTimeAround() + { + try + { + Thread.sleep( Integer.getInteger( "testSleepTime", 2000 ) ); + } + catch ( InterruptedException ignored ) + { + } + } + +} diff --git a/surefire-integration-tests/src/test/resources/surefire-946-self-destruct-plugin/pom.xml b/surefire-integration-tests/src/test/resources/surefire-946-self-destruct-plugin/pom.xml new file mode 100644 index 0000000000..8994838dbd --- /dev/null +++ b/surefire-integration-tests/src/test/resources/surefire-946-self-destruct-plugin/pom.xml @@ -0,0 +1,56 @@ + + 4.0.0 + + org.apache.maven.plugins.surefire + maven-selfdestruct-plugin + 0.1 + maven-plugin + + maven-selfdestruct-plugin Maven Plugin + http://maven.apache.org + + + UTF-8 + + + + + org.apache.maven + maven-plugin-api + 2.0 + + + junit + junit + 3.8.1 + test + + + + + + + org.apache.maven.plugins + maven-plugin-plugin + 2.9 + + maven-selfdestruct-plugin + + + + generated-helpmojo + + helpmojo + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.5.1 + + + + diff --git a/surefire-integration-tests/src/test/resources/surefire-946-self-destruct-plugin/src/main/java/org/apache/maven/plugins/surefire/selfdestruct/SelfDestructMojo.java b/surefire-integration-tests/src/test/resources/surefire-946-self-destruct-plugin/src/main/java/org/apache/maven/plugins/surefire/selfdestruct/SelfDestructMojo.java new file mode 100644 index 0000000000..33cd5880ca --- /dev/null +++ b/surefire-integration-tests/src/test/resources/surefire-946-self-destruct-plugin/src/main/java/org/apache/maven/plugins/surefire/selfdestruct/SelfDestructMojo.java @@ -0,0 +1,142 @@ +package org.apache.maven.plugins.surefire.selfdestruct; + +/* + * Copyright 2001-2005 The Apache Software Foundation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES 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.lang.management.ManagementFactory; +import java.util.ArrayList; +import java.util.List; +import java.util.Timer; +import java.util.TimerTask; + +import org.apache.maven.plugin.AbstractMojo; +import org.apache.maven.plugin.MojoExecutionException; + +/** + * Goal which terminates the maven process it is executed in after a timeout. + * + * @goal selfdestruct + * @phase test + */ +public class SelfDestructMojo + extends AbstractMojo +{ + private enum DestructMethod + { + exit, halt, interrupt; + } + + /** + * Timeout in milliseconds + * + * @parameter + */ + private long timeoutInMillis = 0; + + /** + * Method of self-destruction: 'exit' will use System.exit (default), 'halt' will use Runtime.halt, 'interrupt' will + * try to call 'taskkill' (windows) or 'kill -INT' (others) + * + * @parameter + */ + private String method = "exit"; + + public void execute() + throws MojoExecutionException + { + + DestructMethod destructMethod = DestructMethod.valueOf( method ); + + if ( timeoutInMillis > 0 ) + { + getLog().warn( "Self-Destruct in " + timeoutInMillis + " millis using " + destructMethod ); + Timer timer = new Timer( "", true ); + timer.schedule( new SelfDestructionTask( destructMethod ), timeoutInMillis ); + } + else + { + new SelfDestructionTask( destructMethod ).run(); + } + } + + private void selfDestruct( DestructMethod destructMethod ) + { + getLog().warn( "Self-Destructing NOW." ); + switch ( destructMethod ) + { + case exit: + System.exit( 1 ); + case halt: + Runtime.getRuntime().halt( 1 ); + case interrupt: + String name = ManagementFactory.getRuntimeMXBean().getName(); + int indexOfAt = name.indexOf( '@' ); + if ( indexOfAt > 0 ) + { + String pid = name.substring( 0, indexOfAt ); + getLog().warn( "Going to kill process with PID " + pid ); + + List args = new ArrayList(); + if ( System.getProperty( "os.name" ).startsWith( "Windows" ) ) + { + args.add( "taskkill" ); + args.add( "/PID" ); + } + else + { + args.add( "kill" ); + args.add( "-INT" ); + } + args.add( pid ); + + try + { + new ProcessBuilder( args ).start(); + } + catch ( IOException e ) + { + getLog().error( "Unable to spawn process. Killing with System.exit.", e ); + } + } + else + { + getLog().warn( "Unable to determine my PID... Using System.exit" ); + } + } + + System.exit( 1 ); + } + + private class SelfDestructionTask + extends TimerTask + { + + private DestructMethod destructMethod; + + public SelfDestructionTask( DestructMethod destructMethod ) + { + this.destructMethod = destructMethod; + } + + @Override + public void run() + { + selfDestruct( destructMethod ); + } + + } +} diff --git a/surefire-integration-tests/src/test/resources/surefire-972-bizarre-noclassdef/boom/pom.xml b/surefire-integration-tests/src/test/resources/surefire-972-bizarre-noclassdef/boom/pom.xml new file mode 100644 index 0000000000..d5e9fbcf8e --- /dev/null +++ b/surefire-integration-tests/src/test/resources/surefire-972-bizarre-noclassdef/boom/pom.xml @@ -0,0 +1,51 @@ + + 4.0.0 + class-rule-boom-boom + + org.apache.maven.surefire + class-rule-boom + 1.0-SNAPSHOT + + + + junit + junit + 4.11 + test + + + org.apache.maven.surefire + class-rule + 1.0-SNAPSHOT + test + + + + + + org.apache.maven.plugins + maven-failsafe-plugin + ${surefire.version} + + + + integration-test + verify + + + always + + + + + + org.apache.maven.surefire + surefire-junit47 + ${surefire.version} + + + + + + diff --git a/surefire-integration-tests/src/test/resources/surefire-972-bizarre-noclassdef/boom/src/test/java/org/apache/maven/surefire/crb/ClassRuleIT.java b/surefire-integration-tests/src/test/resources/surefire-972-bizarre-noclassdef/boom/src/test/java/org/apache/maven/surefire/crb/ClassRuleIT.java new file mode 100644 index 0000000000..5554fd90f5 --- /dev/null +++ b/surefire-integration-tests/src/test/resources/surefire-972-bizarre-noclassdef/boom/src/test/java/org/apache/maven/surefire/crb/ClassRuleIT.java @@ -0,0 +1,24 @@ +package org.apache.maven.surefire.crb; + +import org.junit.Assert; +import org.junit.ClassRule; +import org.junit.Test; + +/** + * Created with IntelliJ IDEA. + * User: benson + * Date: 3/16/13 + * Time: 11:00 AM + * To change this template use File | Settings | File Templates. + */ +public class ClassRuleIT extends Assert { + + @ClassRule + public static ExampleClassRule rule = new ExampleClassRule(ExampleClassRule.someStaticFunction()); + + @Test + public void dummyTest() { + + } + +} diff --git a/surefire-integration-tests/src/test/resources/surefire-972-bizarre-noclassdef/class-rule/pom.xml b/surefire-integration-tests/src/test/resources/surefire-972-bizarre-noclassdef/class-rule/pom.xml new file mode 100644 index 0000000000..e9f44e3e6e --- /dev/null +++ b/surefire-integration-tests/src/test/resources/surefire-972-bizarre-noclassdef/class-rule/pom.xml @@ -0,0 +1,17 @@ + + 4.0.0 + class-rule + + org.apache.maven.surefire + class-rule-boom + 1.0-SNAPSHOT + + + + junit + junit + 4.11 + + + diff --git a/surefire-integration-tests/src/test/resources/surefire-972-bizarre-noclassdef/class-rule/src/main/java/org.apache.maven.surefire.crb/ExampleClassRule.java b/surefire-integration-tests/src/test/resources/surefire-972-bizarre-noclassdef/class-rule/src/main/java/org.apache.maven.surefire.crb/ExampleClassRule.java new file mode 100644 index 0000000000..430f7d2a3c --- /dev/null +++ b/surefire-integration-tests/src/test/resources/surefire-972-bizarre-noclassdef/class-rule/src/main/java/org.apache.maven.surefire.crb/ExampleClassRule.java @@ -0,0 +1,29 @@ +package org.apache.maven.surefire.crb; + +import org.junit.rules.ExternalResource; + +/** + * Created with IntelliJ IDEA. + * User: benson + * Date: 3/16/13 + * Time: 10:52 AM + * To change this template use File | Settings | File Templates. + */ +public class ExampleClassRule extends ExternalResource { + + public ExampleClassRule(String dummy) { + // + } + + protected void before() throws Throwable { + System.err.println("ExampleClassRule.before()"); + } + + protected void after() { + System.err.println("ExampleClassRule.after()"); + } + + public static String someStaticFunction() { + throw new RuntimeException("Surprise!"); + } +} diff --git a/surefire-integration-tests/src/test/resources/surefire-972-bizarre-noclassdef/pom.xml b/surefire-integration-tests/src/test/resources/surefire-972-bizarre-noclassdef/pom.xml new file mode 100644 index 0000000000..be4df33902 --- /dev/null +++ b/surefire-integration-tests/src/test/resources/surefire-972-bizarre-noclassdef/pom.xml @@ -0,0 +1,32 @@ + + 4.0.0 + org.apache.maven.surefire + class-rule-boom + pom + 1.0-SNAPSHOT + + class-rule + boom + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.5.1 + + true + true + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.14 + + + + + diff --git a/surefire-integration-tests/src/test/resources/surefire-975-wrong-encoding/pom.xml b/surefire-integration-tests/src/test/resources/surefire-975-wrong-encoding/pom.xml new file mode 100644 index 0000000000..705d388533 --- /dev/null +++ b/surefire-integration-tests/src/test/resources/surefire-975-wrong-encoding/pom.xml @@ -0,0 +1,37 @@ + + 4.0.0 + + encoding-bug + ru.fors.encoding + 1.0-SNAPSHOT + + + UTF-8 + UTF-8 + + + + + junit + junit + 4.11 + test + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + ${surefire.version} + + + org.apache.maven.plugins + maven-compiler-plugin + 2.5.1 + + + + diff --git a/surefire-integration-tests/src/test/resources/surefire-975-wrong-encoding/src/test/java/EncodingInReportTest.java b/surefire-integration-tests/src/test/resources/surefire-975-wrong-encoding/src/test/java/EncodingInReportTest.java new file mode 100644 index 0000000000..81b6cacd82 --- /dev/null +++ b/surefire-integration-tests/src/test/resources/surefire-975-wrong-encoding/src/test/java/EncodingInReportTest.java @@ -0,0 +1,14 @@ +import org.junit.Test; + +public class EncodingInReportTest { + + @Test + public void test1() { + + } + + @Test + public void кириллице() { + + } +} \ No newline at end of file diff --git a/surefire-integration-tests/src/test/resources/surefire-979-smartStackTrace-wrongClassloader/module1/pom.xml b/surefire-integration-tests/src/test/resources/surefire-979-smartStackTrace-wrongClassloader/module1/pom.xml new file mode 100644 index 0000000000..ccd8a051c4 --- /dev/null +++ b/surefire-integration-tests/src/test/resources/surefire-979-smartStackTrace-wrongClassloader/module1/pom.xml @@ -0,0 +1,36 @@ + + 4.0.0 + surefire-979 + module1 + 1.0 + surefire-979-base + + + + junit + junit + 4.10 + + + commons-io + commons-io + 2.2 + provided + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.5.1 + + + maven-surefire-plugin + ${surefire.version} + + + + diff --git a/surefire-integration-tests/src/test/resources/surefire-979-smartStackTrace-wrongClassloader/module1/src/main/java/surefire979/TestBase.java b/surefire-integration-tests/src/test/resources/surefire-979-smartStackTrace-wrongClassloader/module1/src/main/java/surefire979/TestBase.java new file mode 100644 index 0000000000..4cba8527d1 --- /dev/null +++ b/surefire-integration-tests/src/test/resources/surefire-979-smartStackTrace-wrongClassloader/module1/src/main/java/surefire979/TestBase.java @@ -0,0 +1,17 @@ +package surefire979; + + +import org.apache.commons.io.input.AutoCloseInputStream; +import org.junit.Test; + +import java.io.ByteArrayInputStream; + + +public class TestBase +{ + + static { + AutoCloseInputStream directoryWalker = new AutoCloseInputStream(new ByteArrayInputStream(new byte[200])); + } + +} diff --git a/surefire-integration-tests/src/test/resources/surefire-979-smartStackTrace-wrongClassloader/module2/pom.xml b/surefire-integration-tests/src/test/resources/surefire-979-smartStackTrace-wrongClassloader/module2/pom.xml new file mode 100644 index 0000000000..a0c12a9cc1 --- /dev/null +++ b/surefire-integration-tests/src/test/resources/surefire-979-smartStackTrace-wrongClassloader/module2/pom.xml @@ -0,0 +1,37 @@ + + 4.0.0 + surefire-979 + module2 + 1.0 + surefire-979 + + + + junit + junit + 4.10 + test + + + surefire-979 + module1 + 1.0 + test + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.5.1 + + + maven-surefire-plugin + ${surefire.version} + + + + diff --git a/surefire-integration-tests/src/test/resources/surefire-979-smartStackTrace-wrongClassloader/module2/src/test/java/surefire979/FailingStaticInitializerTest.java b/surefire-integration-tests/src/test/resources/surefire-979-smartStackTrace-wrongClassloader/module2/src/test/java/surefire979/FailingStaticInitializerTest.java new file mode 100644 index 0000000000..dd37362b9e --- /dev/null +++ b/surefire-integration-tests/src/test/resources/surefire-979-smartStackTrace-wrongClassloader/module2/src/test/java/surefire979/FailingStaticInitializerTest.java @@ -0,0 +1,17 @@ +package surefire979; + + +import org.junit.Test; + + +public class FailingStaticInitializerTest extends TestBase +{ + + @Test + public void test() + { + throw new IllegalStateException("This test will never run"); + + } + +} diff --git a/surefire-integration-tests/src/test/resources/surefire-979-smartStackTrace-wrongClassloader/pom.xml b/surefire-integration-tests/src/test/resources/surefire-979-smartStackTrace-wrongClassloader/pom.xml new file mode 100644 index 0000000000..d540d1ba8e --- /dev/null +++ b/surefire-integration-tests/src/test/resources/surefire-979-smartStackTrace-wrongClassloader/pom.xml @@ -0,0 +1,28 @@ + + 4.0.0 + test + surefire-979 + 0.0.1-SNAPSHOT + surefire-979 + pom + + + module1 + module2 + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.5.1 + + + maven-surefire-plugin + ${surefire.version} + + + + diff --git a/surefire-integration-tests/src/test/resources/surefire-985-parameterized-and-categories/pom.xml b/surefire-integration-tests/src/test/resources/surefire-985-parameterized-and-categories/pom.xml new file mode 100644 index 0000000000..71d26cd58e --- /dev/null +++ b/surefire-integration-tests/src/test/resources/surefire-985-parameterized-and-categories/pom.xml @@ -0,0 +1,55 @@ + + + + 4.0.0 + + org.apache.maven.surefire + it-parent + 1.0 + + + surefire-985 + Tests Parameterized runner together with @Categories + + + + junit + junit + 4.11 + test + + + + + + + maven-surefire-plugin + ${surefire.version} + + alphabetical + sample.CategoryActivated + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.5 + 1.5 + + + + + + diff --git a/surefire-integration-tests/src/test/resources/surefire-985-parameterized-and-categories/src/test/java/sample/CategoryActivated.java b/surefire-integration-tests/src/test/resources/surefire-985-parameterized-and-categories/src/test/java/sample/CategoryActivated.java new file mode 100644 index 0000000000..14603e5c92 --- /dev/null +++ b/surefire-integration-tests/src/test/resources/surefire-985-parameterized-and-categories/src/test/java/sample/CategoryActivated.java @@ -0,0 +1,6 @@ +package sample; + +public interface CategoryActivated +{ + +} diff --git a/surefire-integration-tests/src/test/resources/surefire-985-parameterized-and-categories/src/test/java/sample/CategoryNotSelected.java b/surefire-integration-tests/src/test/resources/surefire-985-parameterized-and-categories/src/test/java/sample/CategoryNotSelected.java new file mode 100644 index 0000000000..bcaad5f050 --- /dev/null +++ b/surefire-integration-tests/src/test/resources/surefire-985-parameterized-and-categories/src/test/java/sample/CategoryNotSelected.java @@ -0,0 +1,6 @@ +package sample; + +public interface CategoryNotSelected +{ + +} diff --git a/surefire-integration-tests/src/test/resources/surefire-985-parameterized-and-categories/src/test/java/sample/parameterized/Parameterized01Test.java b/surefire-integration-tests/src/test/resources/surefire-985-parameterized-and-categories/src/test/java/sample/parameterized/Parameterized01Test.java new file mode 100644 index 0000000000..7c34e952b9 --- /dev/null +++ b/surefire-integration-tests/src/test/resources/surefire-985-parameterized-and-categories/src/test/java/sample/parameterized/Parameterized01Test.java @@ -0,0 +1,42 @@ +package sample.parameterized; + +import java.util.Arrays; +import java.util.Collection; + +import org.junit.Test; +import org.junit.experimental.categories.Category; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.junit.runners.Parameterized.Parameters; + +import sample.CategoryNotSelected; + +@RunWith( Parameterized.class ) +@Category( CategoryNotSelected.class ) +public class Parameterized01Test +{ + static + { + System.out.println( "Initializing Parameterized01Test" ); + } + + @Parameters + public static Collection getParams() + { + return Arrays.asList( new Integer[] { 1 }, new Integer[] { 2 }, new Integer[] { 3 }, new Integer[] { 4 } ); + } + + public Parameterized01Test( Integer param ) + { + } + + @Test + public void testNothing() + { + } + + @Test + public void testNothingEither() + { + } +} diff --git a/surefire-integration-tests/src/test/resources/surefire-985-parameterized-and-categories/src/test/java/sample/parameterized/Parameterized02Test.java b/surefire-integration-tests/src/test/resources/surefire-985-parameterized-and-categories/src/test/java/sample/parameterized/Parameterized02Test.java new file mode 100644 index 0000000000..f1b3ff59b4 --- /dev/null +++ b/surefire-integration-tests/src/test/resources/surefire-985-parameterized-and-categories/src/test/java/sample/parameterized/Parameterized02Test.java @@ -0,0 +1,42 @@ +package sample.parameterized; + +import java.util.Arrays; +import java.util.Collection; + +import org.junit.Test; +import org.junit.experimental.categories.Category; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.junit.runners.Parameterized.Parameters; + +import sample.CategoryActivated; + +@RunWith( Parameterized.class ) +public class Parameterized02Test +{ + static + { + System.out.println( "Initializing Parameterized02Test" ); + } + + @Parameters + public static Collection getParams() + { + return Arrays.asList( new Integer[] { 1 }, new Integer[] { 2 }, new Integer[] { 3 }, new Integer[] { 4 } ); + } + + public Parameterized02Test( Integer param ) + { + } + + @Test + @Category( CategoryActivated.class ) + public void testNothing() + { + } + + @Test + public void testNothingEither() + { + } +} diff --git a/surefire-integration-tests/src/test/resources/surefire-985-parameterized-and-categories/src/test/java/sample/parameterized/Parameterized03Test.java b/surefire-integration-tests/src/test/resources/surefire-985-parameterized-and-categories/src/test/java/sample/parameterized/Parameterized03Test.java new file mode 100644 index 0000000000..7aa9bc6dc7 --- /dev/null +++ b/surefire-integration-tests/src/test/resources/surefire-985-parameterized-and-categories/src/test/java/sample/parameterized/Parameterized03Test.java @@ -0,0 +1,42 @@ +package sample.parameterized; + +import java.util.Arrays; +import java.util.Collection; + +import org.junit.Test; +import org.junit.experimental.categories.Category; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.junit.runners.Parameterized.Parameters; + +import sample.CategoryActivated; + +@Category( CategoryActivated.class ) +@RunWith( Parameterized.class ) +public class Parameterized03Test +{ + static + { + System.out.println( "Initializing Parameterized03Test" ); + } + + @Parameters + public static Collection getParams() + { + return Arrays.asList( new Integer[] { 1 }, new Integer[] { 2 }, new Integer[] { 3 }, new Integer[] { 4 } ); + } + + public Parameterized03Test( Integer param ) + { + } + + @Test + public void testNothing() + { + } + + @Test + public void testNothingEither() + { + } +} diff --git a/surefire-integration-tests/src/test/resources/test-helper-dump-pid-plugin/pom.xml b/surefire-integration-tests/src/test/resources/test-helper-dump-pid-plugin/pom.xml new file mode 100644 index 0000000000..26af45b02e --- /dev/null +++ b/surefire-integration-tests/src/test/resources/test-helper-dump-pid-plugin/pom.xml @@ -0,0 +1,62 @@ + + 4.0.0 + + org.apache.maven.plugins.surefire + maven-dump-pid-plugin + 0.1 + maven-plugin + + maven-dump-pid-plugin Maven Plugin + http://maven.apache.org + + + UTF-8 + + + + + org.apache.maven + maven-plugin-api + 2.0.9 + + + org.apache.maven.plugin-tools + maven-plugin-annotations + 3.2 + + + junit + junit + 3.8.1 + test + + + + + + + org.apache.maven.plugins + maven-plugin-plugin + 3.2 + + + true + + + + mojo-descriptor + + descriptor + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.5.1 + + + + diff --git a/surefire-integration-tests/src/test/resources/test-helper-dump-pid-plugin/src/main/java/org/apache/maven/plugins/surefire/dumppid/DumpPidMojo.java b/surefire-integration-tests/src/test/resources/test-helper-dump-pid-plugin/src/main/java/org/apache/maven/plugins/surefire/dumppid/DumpPidMojo.java new file mode 100644 index 0000000000..035976b403 --- /dev/null +++ b/surefire-integration-tests/src/test/resources/test-helper-dump-pid-plugin/src/main/java/org/apache/maven/plugins/surefire/dumppid/DumpPidMojo.java @@ -0,0 +1,70 @@ +package org.apache.maven.plugins.surefire.dumppid; + +/* + * Copyright 2001-2005 The Apache Software Foundation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES 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; +import java.lang.management.ManagementFactory; + +import org.apache.maven.plugin.AbstractMojo; +import org.apache.maven.plugin.MojoExecutionException; +import org.apache.maven.plugins.annotations.LifecyclePhase; +import org.apache.maven.plugins.annotations.Mojo; +import org.apache.maven.plugins.annotations.Parameter; + +/** + * Goal dumps the PID of the maven process + */ +@Mojo( name = "dump-pid", defaultPhase = LifecyclePhase.GENERATE_TEST_RESOURCES ) +public class DumpPidMojo + extends AbstractMojo +{ + + @Parameter( defaultValue = "${project.build.directory}", property = "dumpPid.targetDir" ) + private File targetDir; + + public void execute() + throws MojoExecutionException + { + File target; + try + { + getLog().info( "Dumping PID to " + targetDir ); + + if ( !targetDir.exists() ) + { + targetDir.mkdirs(); + } + + target = new File( targetDir, "maven.pid" ).getCanonicalFile(); + + FileWriter fw = new FileWriter( target ); + String pid = ManagementFactory.getRuntimeMXBean().getName(); + fw.write( pid ); + fw.flush(); + fw.close(); + + getLog().info( "Wrote " + pid + " to " + target ); + + } + catch ( IOException e ) + { + throw new MojoExecutionException( "Unable to create pid file", e ); + } + } +} diff --git a/surefire-integration-tests/src/test/resources/unicode-testnames/pom.xml b/surefire-integration-tests/src/test/resources/unicode-testnames/pom.xml index f42d50595d..1056c79212 100644 --- a/surefire-integration-tests/src/test/resources/unicode-testnames/pom.xml +++ b/surefire-integration-tests/src/test/resources/unicode-testnames/pom.xml @@ -48,6 +48,11 @@ maven-surefire-plugin ${surefire.version} + + org.apache.maven.plugins + maven-compiler-plugin + 2.5.1 + diff --git a/surefire-integration-tests/src/test/resources/working-directory/child/pom.xml b/surefire-integration-tests/src/test/resources/working-directory/child/pom.xml index 6f2288089a..bca882c7d5 100644 --- a/surefire-integration-tests/src/test/resources/working-directory/child/pom.xml +++ b/surefire-integration-tests/src/test/resources/working-directory/child/pom.xml @@ -23,9 +23,13 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 - org.apache.maven.plugins.surefire + + org.apache.maven.plugins.surefire + working-directory + 1.0-SNAPSHOT + + working-directory-child - 1.0-SNAPSHOT Test for working directory configuration diff --git a/surefire-integration-tests/src/test/resources/working-directory/pom.xml b/surefire-integration-tests/src/test/resources/working-directory/pom.xml index 6b2706033c..80e97b3afb 100644 --- a/surefire-integration-tests/src/test/resources/working-directory/pom.xml +++ b/surefire-integration-tests/src/test/resources/working-directory/pom.xml @@ -33,13 +33,14 @@ - - - org.apache.maven.plugins - maven-surefire-plugin - ${surefire.version} - - - + + + + org.apache.maven.plugins + maven-surefire-plugin + ${surefire.version} + + + \ No newline at end of file diff --git a/surefire-providers/common-java5/pom.xml b/surefire-providers/common-java5/pom.xml new file mode 100644 index 0000000000..2b98f91ec4 --- /dev/null +++ b/surefire-providers/common-java5/pom.xml @@ -0,0 +1,74 @@ + + + + 4.0.0 + + + org.apache.maven.surefire + surefire-providers + 2.16-SNAPSHOT + ../pom.xml + + + common-java5 + + Shared java5 code for all providers. + + + + org.apache.maven.shared + maven-shared-utils + + + + + + + org.apache.maven.plugins + maven-shade-plugin + + + package + + shade + + + true + + + org.codehaus.plexus.util + org.apache.maven.surefire.commonjunit48.org.codehaus.plexus.util + + + + + + + + maven-surefire-plugin + + + **/fixture/** + + + + + + diff --git a/surefire-api/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 similarity index 61% rename from surefire-api/src/main/java/org/apache/maven/surefire/report/PojoStackTraceWriter.java rename to surefire-providers/common-java5/src/main/java/org/apache/maven/surefire/report/PojoStackTraceWriter.java index 9638ca42fd..8e52d68387 100644 --- a/surefire-api/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 @@ -22,7 +22,6 @@ import java.io.PrintWriter; import java.io.StringWriter; -import org.apache.maven.surefire.util.internal.StringUtils; /** * Write the trace out for a POJO test. @@ -56,46 +55,15 @@ public String writeTraceToString() return w.toString(); } - public String writeTrimmedTraceToString() + public String smartTrimmedStackTrace() { - String text = writeTraceToString(); - - String marker = "at " + testClass + "." + testMethod; - - String[] lines = StringUtils.split( text, "\n" ); - int lastLine = lines.length - 1; - int causedByLine = -1; - // skip first - for ( int i = 1; i < lines.length; i++ ) - { - String line = lines[i].trim(); - if ( line.startsWith( marker ) ) - { - lastLine = i; - } - else if ( line.startsWith( "Caused by" ) ) - { - causedByLine = i; - break; - } - } - - StringBuffer trace = new StringBuffer(); - for ( int i = 0; i <= lastLine; i++ ) - { - trace.append( lines[i] ); - trace.append( "\n" ); - } + SmartStackTraceParser parser = new SmartStackTraceParser( testClass, t, testMethod ); + return parser.getString(); + } - if ( causedByLine != -1 ) - { - for ( int i = causedByLine; i < lines.length; i++ ) - { - trace.append( lines[i] ); - trace.append( "\n" ); - } - } - return trace.toString(); + public String writeTrimmedTraceToString() + { + return SmartStackTraceParser.innerMostWithFocusOnClass( t, testClass ); } public SafeThrowable getThrowable() 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 new file mode 100644 index 0000000000..d1b3ff23f6 --- /dev/null +++ b/surefire-providers/common-java5/src/main/java/org/apache/maven/surefire/report/SmartStackTraceParser.java @@ -0,0 +1,318 @@ +package org.apache.maven.surefire.report; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES 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.Arrays; +import java.util.Collections; +import java.util.List; + +import org.apache.maven.shared.utils.StringUtils; + +/** + * @author Kristian Rosenvold + */ +@SuppressWarnings( "ThrowableResultOfMethodCallIgnored" ) +public class SmartStackTraceParser +{ + + private final SafeThrowable throwable; + + private final StackTraceElement[] stackTrace; + + private final String simpleName; + + private String testClassName; + + private final Class testClass; + + private String testMethodName; + + public SmartStackTraceParser( Class testClass, Throwable throwable ) + { + this( testClass.getName(), throwable, null ); + } + + public SmartStackTraceParser( String testClassName, Throwable throwable, String testMethodName ) + { + this.testMethodName = testMethodName; + this.testClassName = testClassName; + this.testClass = getClass( testClassName ); + this.simpleName = this.testClassName.substring( this.testClassName.lastIndexOf( "." ) + 1 ); + this.throwable = new SafeThrowable( throwable ); + stackTrace = throwable.getStackTrace(); + } + + private static Class getClass( String name ) + { + try + { + return Thread.currentThread().getContextClassLoader().loadClass( name ); + } + catch ( ClassNotFoundException e ) + { + return null; + } + } + + private static String getSimpleName( String className ) + { + int i = className.lastIndexOf( "." ); + return className.substring( i + 1 ); + } + + @SuppressWarnings( "ThrowableResultOfMethodCallIgnored" ) + public String getString() + { + if ( testClass == null ) + { + return throwable.getLocalizedMessage(); + } + + StringBuilder result = new StringBuilder(); + List stackTraceElements = focusOnClass( stackTrace, testClass ); + Collections.reverse( stackTraceElements ); + StackTraceElement stackTraceElement; + if ( stackTraceElements.isEmpty() ) + { + result.append( simpleName ); + if (StringUtils.isNotEmpty( testMethodName )) + { + result.append( "." ).append( testMethodName ); + } + } + else + { + for ( int i = 0; i < stackTraceElements.size(); i++ ) + { + stackTraceElement = stackTraceElements.get( i ); + if ( i == 0 ) + { + result.append( simpleName ); + if ( !stackTraceElement.getClassName().equals( testClassName ) ) + { + result.append( ">" ); + } + else + { + result.append( "." ); + } + + } + if ( !stackTraceElement.getClassName().equals( testClassName ) ) + { + result.append( getSimpleName( stackTraceElement.getClassName() ) ); // Add the name of the superclas + result.append( "." ); + } + result.append( stackTraceElement.getMethodName() ).append( ":" ).append( + stackTraceElement.getLineNumber() ); + result.append( "->" ); + } + + if ( result.length() >= 2 ) + { + result.deleteCharAt( result.length() - 1 ); + result.deleteCharAt( result.length() - 1 ); + } + } + + Throwable target = throwable.getTarget(); + if ( target instanceof AssertionError ) + { + result.append( " " ); + result.append( throwable.getMessage() ); + } + else if ( "junit.framework.AssertionFailedError".equals( target.getClass().getName() ) + || "junit.framework.ComparisonFailure".equals( target.getClass().getName() ) ) + { + result.append( " " ); + result.append( throwable.getMessage() ); + } + else + { + result.append( rootIsInclass() ? " " : " » " ); + result.append( getMinimalThrowableMiniMessage( target ) ); + result.append( getTruncatedMessage( 77 - result.length() ) ); + } + return result.toString(); + } + + private String getMinimalThrowableMiniMessage( Throwable throwable ) + { + String name = throwable.getClass().getSimpleName(); + if ( name.endsWith( "Exception" ) ) + { + return StringUtils.chompLast( name, "Exception" ); + } + if ( name.endsWith( "Error" ) ) + { + return StringUtils.chompLast( name, "Error" ); + } + return name; + } + + private String getTruncatedMessage( int i ) + { + if ( i < 0 ) + { + return ""; + } + String msg = throwable.getMessage(); + if ( msg == null ) + { + return ""; + } + String substring = msg.substring( 0, Math.min( i, msg.length() ) ); + if ( i < msg.length() ) + { + return " " + substring + "..."; + } + else + { + return " " + substring; + } + } + + private boolean rootIsInclass() + { + return stackTrace.length > 0 && stackTrace[0].getClassName().equals( testClassName ); + } + + static List focusOnClass( StackTraceElement[] stackTrace, Class clazz ) + { + List result = new ArrayList(); + 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." ) ) + { + return false; + } + while ( !testClass.getName().equals( lookFor ) && testClass.getSuperclass() != null ) + { + testClass = testClass.getSuperclass(); + } + return testClass.getName().equals( lookFor ); + } + + static Throwable findInnermostWithClass( Throwable t, String className ) + { + Throwable match = t; + do + { + if ( containsClassName( t.getStackTrace(), className ) ) + { + match = t; + } + + t = t.getCause(); + + } + while ( t != null ); + return match; + } + + public static String innerMostWithFocusOnClass( Throwable t, String className ) + { + Throwable innermost = findInnermostWithClass( t, className ); + List stackTraceElements = focusInsideClass( innermost.getStackTrace(), className ); + String s = causeToString( innermost.getCause() ); + return toString( t, stackTraceElements ) + s; + } + + static List focusInsideClass( StackTraceElement[] stackTrace, String className ) + { + List result = new ArrayList(); + boolean found = false; + for ( StackTraceElement element : stackTrace ) + { + if ( !found ) + { + result.add( element ); + } + + if ( className.equals( element.getClassName() ) ) + { + if ( found ) + { + result.add( element ); + } + found = true; + } + else + { + if ( found ) + { + break; + } + } + } + return result; + } + + static boolean containsClassName( StackTraceElement[] stackTrace, String className ) + { + for ( StackTraceElement element : stackTrace ) + { + if ( className.equals( element.getClassName() ) ) + { + return true; + } + } + return false; + } + + public static String causeToString( Throwable cause ) + { + StringBuilder resp = new StringBuilder(); + while ( cause != null ) + { + resp.append( "Caused by: " ); + resp.append( toString( cause, Arrays.asList( cause.getStackTrace() ) ) ); + cause = cause.getCause(); + } + return resp.toString(); + } + + public static String toString( Throwable t, Iterable elements ) + { + StringBuilder result = new StringBuilder(); + result.append( t.getClass().getName() ); + result.append( ": " ); + result.append( t.getMessage() ); + result.append( "\n" ); + + for ( StackTraceElement element : elements ) + { + result.append( "\tat " ).append( element.toString() ); + result.append( "\n" ); + } + return result.toString(); + } +} 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 new file mode 100644 index 0000000000..c4387d2d46 --- /dev/null +++ b/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/ABaseClass.java @@ -0,0 +1,29 @@ +package org.apache.maven.surefire.report; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + + +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 new file mode 100644 index 0000000000..3b58a81ddd --- /dev/null +++ b/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/ADifferen0tTestClass.java @@ -0,0 +1,25 @@ +package org.apache.maven.surefire.report; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + + +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 new file mode 100644 index 0000000000..985447e865 --- /dev/null +++ b/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/ASubClass.java @@ -0,0 +1,24 @@ +package org.apache.maven.surefire.report; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +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 new file mode 100644 index 0000000000..baff162e15 --- /dev/null +++ b/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/ATestClass.java @@ -0,0 +1,63 @@ +package org.apache.maven.surefire.report; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES 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; + +@SuppressWarnings( "UnusedDeclaration" ) +public class ATestClass +{ + + public void failInAssert() + { + throw new AssertionError( "X is not Z" ); + } + + public void nestedFailInAssert() + { + failInAssert(); + } + + public void npe() + { + throw new NullPointerException( "It was null" ); + } + + public void nestedNpe() + { + npe(); + } + + public void npeOutsideTest() + { + File file = new File( (String) null ); + } + + public void nestedNpeOutsideTest() + { + npeOutsideTest(); + } + + public void aLongTestErrorMessage() + { + throw new RuntimeException( "This message will be truncated, somewhere over the rainbow. " + + "Gangnam style, Gangnam style, Gangnam style, , Gangnam style, Gangnam style" ); + } +} 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 new file mode 100644 index 0000000000..7c1e3a3c2b --- /dev/null +++ b/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/AssertionNoMessage.java @@ -0,0 +1,31 @@ +package org.apache.maven.surefire.report; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES 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; + +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 new file mode 100644 index 0000000000..dc31fbb3c3 --- /dev/null +++ b/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/CaseThatWillFail.java @@ -0,0 +1,31 @@ +package org.apache.maven.surefire.report; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES 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; + +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/FailWithFail.java b/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/FailWithFail.java new file mode 100644 index 0000000000..4acfe1b028 --- /dev/null +++ b/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/FailWithFail.java @@ -0,0 +1,31 @@ +package org.apache.maven.surefire.report; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES 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; + +class FailWithFail + extends TestCase +{ + public void testThatWillFail() + { + fail( "abc" ); + } +} diff --git a/surefire-providers/surefire-junit3/src/main/java/org/apache/maven/surefire/junit/JUnitStackTraceWriter.java b/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/InnerATestClass.java similarity index 66% rename from surefire-providers/surefire-junit3/src/main/java/org/apache/maven/surefire/junit/JUnitStackTraceWriter.java rename to surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/InnerATestClass.java index 476b56df0a..c85d230d03 100644 --- a/surefire-providers/surefire-junit3/src/main/java/org/apache/maven/surefire/junit/JUnitStackTraceWriter.java +++ b/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/InnerATestClass.java @@ -1,4 +1,4 @@ -package org.apache.maven.surefire.junit; +package org.apache.maven.surefire.report; /* * Licensed to the Apache Software Foundation (ASF) under one @@ -19,18 +19,24 @@ * under the License. */ -import org.apache.maven.surefire.report.PojoStackTraceWriter; +import junit.framework.Assert; /** - * Stack trace writer for JUnit tests. - * - * @author Brett Porter - */ -public class JUnitStackTraceWriter - extends PojoStackTraceWriter +* 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 JUnitStackTraceWriter( String testClass, String testName, Throwable throwable ) + public static void testFake() + { + innerMethod(); + } + + private static void innerMethod() { - super( testClass, testName, throwable ); + Assert.assertTrue( false ); } } 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 new file mode 100644 index 0000000000..5c3495dc57 --- /dev/null +++ b/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/PojoStackTraceWriterTest.java @@ -0,0 +1,63 @@ +package org.apache.maven.surefire.report; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES 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 PojoStackTraceWriterTest + extends TestCase +{ + + public void testTrimmedThrowableReal() + { + PojoStackTraceWriter w = + 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 ) ); + + } + + + 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() + { + 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 new file mode 100644 index 0000000000..58ed78d4a1 --- /dev/null +++ b/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/RunnableTestClass1.java @@ -0,0 +1,52 @@ +package org.apache.maven.surefire.report; + +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.FutureTask; + +/* +* Licensed to the Apache Software Foundation (ASF) under one +* or more contributor license agreements. See the NOTICE file +* distributed with this work for additional information +* regarding copyright ownership. The ASF licenses this file +* to you under the Apache License, Version 2.0 (the +* "License"); you may not use this file except in compliance +* with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, +* software distributed under the License is distributed on an +* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +* KIND, either express or implied. See the License for the +* specific language governing permissions and limitations +* under the License. +*/ +class RunnableTestClass1 + implements Callable + +{ + public Object call() + throws Exception + { + doSomethingThatThrows(); + return "yo"; + } + + private void doSomethingThatThrows() + throws ExecutionException + { + RunnableTestClass2 rt2 = new RunnableTestClass2(); + FutureTask futureTask = new FutureTask( rt2 ); + new Thread( futureTask ).start(); + try + { + futureTask.get(); + } + 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 new file mode 100644 index 0000000000..8a13b0ebf1 --- /dev/null +++ b/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/RunnableTestClass2.java @@ -0,0 +1,43 @@ +package org.apache.maven.surefire.report; + +import java.util.concurrent.Callable; + +/* +* Licensed to the Apache Software Foundation (ASF) under one +* or more contributor license agreements. See the NOTICE file +* distributed with this work for additional information +* regarding copyright ownership. The ASF licenses this file +* to you under the Apache License, Version 2.0 (the +* "License"); you may not use this file except in compliance +* with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, +* software distributed under the License is distributed on an +* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +* KIND, either express or implied. See the License for the +* specific language governing permissions and limitations +* under the License. +*/ +class RunnableTestClass2 + implements Callable + +{ + + public Object call() + throws Exception + { + InnerRunnableTestClass.cThrows(); + return null; //To change body of implemented methods use File | Settings | File Templates. + } + + 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 new file mode 100644 index 0000000000..78cd31c765 --- /dev/null +++ b/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/SmartStackTraceParserTest.java @@ -0,0 +1,324 @@ +package org.apache.maven.surefire.report; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES 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.Field; +import java.util.List; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.FutureTask; + +import junit.framework.Assert; +import junit.framework.AssertionFailedError; +import junit.framework.ComparisonFailure; +import junit.framework.TestCase; + +import static org.apache.maven.surefire.report.SmartStackTraceParser.findInnermostWithClass; +import static org.apache.maven.surefire.report.SmartStackTraceParser.focusInsideClass; + +@SuppressWarnings( "ThrowableResultOfMethodCallIgnored" ) +public class SmartStackTraceParserTest + extends TestCase +{ + + public void testGetString() + throws Exception + { + ATestClass aTestClass = new ATestClass(); + try + { + aTestClass.failInAssert(); + } + catch ( AssertionError e ) + { + SmartStackTraceParser smartStackTraceParser = new SmartStackTraceParser( ATestClass.class, e ); + String res = smartStackTraceParser.getString(); + assertEquals( "ATestClass.failInAssert:30 X is not Z", res ); + + } + + } + + public void testNestedFailure() + throws Exception + { + ATestClass aTestClass = new ATestClass(); + try + { + aTestClass.nestedFailInAssert(); + } + catch ( AssertionError e ) + { + SmartStackTraceParser smartStackTraceParser = new SmartStackTraceParser( ATestClass.class, e ); + String res = smartStackTraceParser.getString(); + assertEquals( "ATestClass.nestedFailInAssert:35->failInAssert:30 X is not Z", res ); + } + } + + public void testNestedNpe() + throws Exception + { + ATestClass aTestClass = new ATestClass(); + try + { + aTestClass.nestedNpe(); + } + catch ( NullPointerException e ) + { + SmartStackTraceParser smartStackTraceParser = new SmartStackTraceParser( ATestClass.class, e ); + String res = smartStackTraceParser.getString(); + assertEquals( "ATestClass.nestedNpe:45->npe:40 NullPointer It was null", res ); + + } + } + + public void testNestedNpeOutsideTest() + throws Exception + { + ATestClass aTestClass = new ATestClass(); + try + { + aTestClass.nestedNpeOutsideTest(); + } + catch ( NullPointerException e ) + { + SmartStackTraceParser smartStackTraceParser = new SmartStackTraceParser( ATestClass.class, e ); + String res = smartStackTraceParser.getString(); + assertEquals( "ATestClass.nestedNpeOutsideTest:55->npeOutsideTest:50 » NullPointer", res ); + + } + } + + public void testLongMessageTruncation() + throws Exception + { + ATestClass aTestClass = new ATestClass(); + try + { + aTestClass.aLongTestErrorMessage(); + } + catch ( RuntimeException e ) + { + SmartStackTraceParser smartStackTraceParser = new SmartStackTraceParser( ATestClass.class, e ); + String res = smartStackTraceParser.getString(); + assertEquals( "ATestClass.aLongTestErrorMessage:60 Runtime This message will be truncated, so...", res ); + + } + } + + public void testFailureInBaseClass() + throws Exception + { + ASubClass aTestClass = new ASubClass(); + try + { + aTestClass.npe(); + } + catch ( NullPointerException e ) + { + SmartStackTraceParser smartStackTraceParser = new SmartStackTraceParser( ASubClass.class, e ); + String res = smartStackTraceParser.getString(); + assertEquals( "ASubClass>ABaseClass.npe:27 » NullPointer It was null", res ); + } + } + + public void testClassThatWillFail() + throws Exception + { + CaseThatWillFail aTestClass = new CaseThatWillFail(); + try + { + aTestClass.testThatWillFail(); + } + catch ( ComparisonFailure e ) + { + SmartStackTraceParser smartStackTraceParser = new SmartStackTraceParser( CaseThatWillFail.class, e ); + String res = smartStackTraceParser.getString(); + assertEquals( "CaseThatWillFail.testThatWillFail:29 expected: but was:", res ); + } + } + + public Throwable getAThrownException() + { + try + { + TestClass1.InnerBTestClass.throwSomething(); + } + catch ( Throwable t ) + { + return t; + } + return null; + } + + public void testCollections() + { + Throwable aThrownException = getAThrownException(); + + List innerMost = + focusInsideClass( aThrownException.getCause().getStackTrace(), TestClass1.InnerBTestClass.class.getName() ); + assertEquals( 3, innerMost.size() ); + StackTraceElement inner = innerMost.get( 0 ); + assertEquals( TestClass2.InnerCTestClass.class.getName(), inner.getClassName() ); + StackTraceElement outer = innerMost.get( 2 ); + assertEquals( TestClass1.InnerBTestClass.class.getName(), outer.getClassName() ); + } + + public void testAssertionWithNoMessage() + { + try + { + new AssertionNoMessage().testThrowSomething(); + } + catch ( ComparisonFailure e ) + { + SmartStackTraceParser smartStackTraceParser = new SmartStackTraceParser( AssertionNoMessage.class, e ); + String res = smartStackTraceParser.getString(); + assertEquals( "AssertionNoMessage.testThrowSomething:29 expected: but was:", res ); + } + } + + public void testFailWithFail() + { + try + { + new FailWithFail().testThatWillFail(); + } + catch ( AssertionFailedError e ) + { + SmartStackTraceParser smartStackTraceParser = new SmartStackTraceParser( FailWithFail.class, e ); + String res = smartStackTraceParser.getString(); + assertEquals( "FailWithFail.testThatWillFail:29 abc", res ); + } + } + + public void testCollectorWithNested() + { + try + { + InnerATestClass.testFake(); + } + catch ( Throwable t ) + { + List stackTraceElements = + focusInsideClass( t.getStackTrace(), InnerATestClass.class.getName() ); + assertNotNull( stackTraceElements ); + assertEquals( 5, stackTraceElements.size() ); + StackTraceElement innerMost = stackTraceElements.get( 0 ); + assertEquals( Assert.class.getName(), innerMost.getClassName() ); + StackTraceElement outer = stackTraceElements.get( 4 ); + assertEquals( InnerATestClass.class.getName(), outer.getClassName() ); + } + } + + public void testNonClassNameStacktrace() + { + SmartStackTraceParser smartStackTraceParser = + new SmartStackTraceParser( "Not a class name", new Throwable( "my message" ), null ); + assertEquals( "my message", smartStackTraceParser.getString() ); + } + + public void testNullElementInStackTrace() + throws Exception + { + ATestClass aTestClass = new ATestClass(); + try + { + aTestClass.failInAssert(); + } + catch ( AssertionError e ) + { + SmartStackTraceParser smartStackTraceParser = new SmartStackTraceParser( ATestClass.class, e ); + 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 ); + } + + } + + public void testSingleNestedWithThread() + { + ExecutionException e = getSingleNested(); + String name = this.getClass().getName(); + Throwable focus = findInnermostWithClass( e, name ); + assertEquals( e, focus ); + List stackTraceElements = focusInsideClass( focus.getStackTrace(), name ); + assertEquals( stackTraceElements.get( stackTraceElements.size() - 1 ).getClassName(), name ); + } + + + public void testDoubleNestedWithThread() + { + ExecutionException e = getDoubleNestedException(); + + String name = this.getClass().getName(); + Throwable focus = findInnermostWithClass( e, name ); + assertEquals( e, focus ); + List stackTraceElements = focusInsideClass( focus.getStackTrace(), name ); + assertEquals( stackTraceElements.get( stackTraceElements.size() - 1 ).getClassName(), name ); + + name = "org.apache.maven.surefire.report.RunnableTestClass1"; + focus = findInnermostWithClass( e, name ); + assertEquals( e.getCause(), focus ); + stackTraceElements = focusInsideClass( focus.getStackTrace(), name ); + assertEquals( stackTraceElements.get( stackTraceElements.size() - 1 ).getClassName(), name ); + + } + + public ExecutionException getSingleNested() + { + FutureTask futureTask = new FutureTask( new RunnableTestClass2() ); + new Thread( futureTask ).start(); + try + { + futureTask.get(); + } + catch ( InterruptedException e ) + { + fail(); + } + catch ( ExecutionException e ) + { + return e; + } + fail(); + return null; + } + + private ExecutionException getDoubleNestedException() + { + FutureTask futureTask = new FutureTask( new RunnableTestClass1() ); + new Thread( futureTask ).start(); + try + { + futureTask.get(); + } + catch ( InterruptedException e ) + { + fail(); + } + catch ( ExecutionException e ) + { + return e; + } + return null; + } +} 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 new file mode 100644 index 0000000000..5b34f67a97 --- /dev/null +++ b/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/TestClass1.java @@ -0,0 +1,42 @@ +package org.apache.maven.surefire.report; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +class TestClass1 +{ + static class InnerBTestClass + { + public static void throwSomething() + { + innerThrowSomething(); + } + + public static void innerThrowSomething() + { + try + { + TestClass2.InnerCTestClass.cThrows(); + } + 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 new file mode 100644 index 0000000000..ae55026f9c --- /dev/null +++ b/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/TestClass2.java @@ -0,0 +1,31 @@ +package org.apache.maven.surefire.report; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * 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!" ); + } + } +} diff --git a/surefire-providers/common-junit3/pom.xml b/surefire-providers/common-junit3/pom.xml index bd4dcde949..5654db6fac 100644 --- a/surefire-providers/common-junit3/pom.xml +++ b/surefire-providers/common-junit3/pom.xml @@ -17,14 +17,13 @@ ~ under the License. --> - + 4.0.0 org.apache.maven.surefire surefire-providers - 2.13-SNAPSHOT + 2.16-SNAPSHOT ../pom.xml 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 1dd5b6485b..3ffec88c9b 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 @@ -137,7 +137,7 @@ public Object constructTestObject( Class testClass ) } else { - testObject = testConstructor.newInstance( new Object[]{ testClass.getName() } ); + testObject = testConstructor.newInstance( testClass.getName() ); } } return testObject; diff --git a/surefire-providers/common-junit4/pom.xml b/surefire-providers/common-junit4/pom.xml index 471d088b1f..102b19fd9d 100644 --- a/surefire-providers/common-junit4/pom.xml +++ b/surefire-providers/common-junit4/pom.xml @@ -17,14 +17,13 @@ ~ under the License. --> - + 4.0.0 org.apache.maven.surefire surefire-providers - 2.13-SNAPSHOT + 2.16-SNAPSHOT ../pom.xml @@ -44,6 +43,11 @@ common-junit3 ${project.version} + + org.apache.maven.surefire + common-java5 + ${project.version} + org.apache.maven.shared maven-shared-utils 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 785cdea300..c4b5b576a2 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 @@ -19,17 +19,18 @@ * under the License. */ -import java.util.regex.Matcher; -import java.util.regex.Pattern; import org.apache.maven.surefire.report.ReportEntry; import org.apache.maven.surefire.report.RunListener; import org.apache.maven.surefire.report.SimpleReportEntry; +import org.apache.maven.surefire.report.StackTraceWriter; import org.apache.maven.surefire.testset.TestSetFailedException; - import org.junit.runner.Description; import org.junit.runner.Result; import org.junit.runner.notification.Failure; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + public class JUnit4RunListener extends org.junit.runner.notification.RunListener { @@ -38,7 +39,6 @@ public class JUnit4RunListener // then an open-paren (start matching a group) + "[^\\\\(\\\\)]+" //non-parens + ")\\)" + "$" ); - // then a close-paren (end group match) protected final RunListener reporter; @@ -72,7 +72,7 @@ public void testIgnored( Description description ) { final String reason = jUnit4Reflector.getAnnotatedIgnoreValue( description ); final SimpleReportEntry report = - SimpleReportEntry.ignored( extractClassName( description ), description.getDisplayName(), reason ); + SimpleReportEntry.ignored( getClassName( description ), description.getDisplayName(), reason ); reporter.testSkipped( report ); } @@ -97,9 +97,13 @@ public void testStarted( Description description ) public void testFailure( Failure failure ) throws Exception { - ReportEntry report = - SimpleReportEntry.withException( extractClassName( failure.getDescription() ), failure.getTestHeader(), - new JUnit4StackTraceWriter( failure ) ); + String testHeader = failure.getTestHeader(); + if ( isInsaneJunitNullString( testHeader ) ) + { + testHeader = "Failure when constructing test"; + } + ReportEntry report = SimpleReportEntry.withException( getClassName( failure.getDescription() ), testHeader, + createStackTraceWriter( failure ) ); if ( failure.getException() instanceof AssertionError ) { @@ -112,6 +116,11 @@ public void testFailure( Failure failure ) failureFlag.set( Boolean.TRUE ); } + protected StackTraceWriter createStackTraceWriter( Failure failure ) + { + return new JUnit4StackTraceWriter( failure ); + } + @SuppressWarnings( { "UnusedDeclaration" } ) public void testAssumptionFailure( Failure failure ) { @@ -135,13 +144,36 @@ public void testFinished( Description description ) } } - private SimpleReportEntry createReportEntry( Description description ) + protected SimpleReportEntry createReportEntry( Description description ) + { + return new SimpleReportEntry( getClassName( description ), description.getDisplayName() ); + } + + public String getClassName( Description description ) { - return new SimpleReportEntry( extractClassName( description ), description.getDisplayName() ); + String name = extractClassName( description ); + if ( name == null || isInsaneJunitNullString( name ) ) + { + // This can happen upon early failures (class instantiation error etc) + Description subDescription = description.getChildren().get( 0 ); + if ( subDescription != null ) + { + name = extractClassName( subDescription ); + } + if ( name == null ) + { + name = "Test Instantiation Error"; + } + } + return name; } + private boolean isInsaneJunitNullString( String value ) + { + return "null".equals( value ); + } - String extractClassName( Description description ) + public static String extractClassName( Description description ) { String displayName = description.getDisplayName(); Matcher m = PARENS.matcher( displayName ); @@ -152,6 +184,14 @@ String extractClassName( Description description ) return m.group( 1 ); } + public static String extractMethodName( Description description ) + { + String displayName = description.getDisplayName(); + int i = displayName.indexOf( "(" ); + if (i >= 0 ) return displayName.substring( 0, i ); + return displayName; + } + public static void rethrowAnyTestMechanismFailures( Result run ) throws TestSetFailedException 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 15357271df..8e469ad801 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 @@ -19,8 +19,8 @@ * under the License. */ -import org.apache.maven.surefire.report.PojoStackTraceWriter; import org.apache.maven.surefire.report.SafeThrowable; +import org.apache.maven.surefire.report.SmartStackTraceParser; import org.apache.maven.surefire.report.StackTraceWriter; import org.junit.runner.notification.Failure; @@ -35,7 +35,7 @@ public class JUnit4StackTraceWriter implements StackTraceWriter { // Member Variables - private final Failure junitFailure; + protected final Failure junitFailure; /** * Constructor. @@ -57,6 +57,33 @@ public String writeTraceToString() return junitFailure.getTrace(); } + + protected String getTestClassName() + { + return JUnit4RunListener.extractClassName( junitFailure.getDescription() ); + } + + protected String getTestMethodName() + { + return JUnit4RunListener.extractMethodName( junitFailure.getDescription() ); + } + + @SuppressWarnings( "ThrowableResultOfMethodCallIgnored" ) + public String smartTrimmedStackTrace() + { + Throwable exception = junitFailure.getException(); + if ( exception != null ) + { + SmartStackTraceParser smartStackTraceParser = new SmartStackTraceParser( getTestClassName(), exception, + getTestMethodName() ); + return smartStackTraceParser.getString(); + } + else + { + return junitFailure.getMessage(); + } + } + /** * At the moment, returns the same as {@link #writeTraceToString()}. * @@ -64,13 +91,14 @@ public String writeTraceToString() */ public String writeTrimmedTraceToString() { + String testClass = getTestClassName(); try { - return junitFailure.getTrace(); + return SmartStackTraceParser.innerMostWithFocusOnClass( junitFailure.getException(), testClass ); } catch ( Throwable t ) { - return new PojoStackTraceWriter( "", "", t ).writeTrimmedTraceToString(); + return SmartStackTraceParser.innerMostWithFocusOnClass( t, testClass ); } } 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 d121d3c7d9..4996f64c92 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 @@ -23,9 +23,10 @@ import java.lang.reflect.Method; import org.apache.maven.surefire.NonAbstractClassFilter; import org.apache.maven.surefire.common.junit3.JUnit3TestChecker; -import org.apache.maven.surefire.util.ReflectionUtils; import org.apache.maven.surefire.util.ScannerFilter; +import static org.apache.maven.surefire.util.ReflectionUtils.tryLoadClass; + /** * @author Kristian Rosenvold */ @@ -42,7 +43,7 @@ public class JUnit4TestChecker public JUnit4TestChecker( ClassLoader testClassLoader ) { this.jUnit3TestChecker = new JUnit3TestChecker( testClassLoader ); - this.runWith = getJUnitClass( testClassLoader, org.junit.runner.RunWith.class.getName() ); + this.runWith = tryLoadClass( testClassLoader, org.junit.runner.RunWith.class.getName() ); this.nonAbstractClassFilter = new NonAbstractClassFilter(); } @@ -59,7 +60,7 @@ private boolean isValidJUnit4Test( Class testClass ) return false; } - if ( runWith != null ) + if ( isRunWithPresentInClassLoader() ) { Annotation runWithAnnotation = testClass.getAnnotation( runWith ); if ( runWithAnnotation != null ) @@ -68,6 +69,11 @@ private boolean isValidJUnit4Test( Class testClass ) } } + return lookForTestAnnotatedMethods( testClass ); + } + + private boolean lookForTestAnnotatedMethods( Class testClass ) + { Class classToCheck = testClass; while ( classToCheck != null ) { @@ -80,7 +86,7 @@ private boolean isValidJUnit4Test( Class testClass ) return false; } - private boolean checkforTestAnnotatedMethod( Class testClass ) + public boolean checkforTestAnnotatedMethod( Class testClass ) { for ( Method lMethod : testClass.getDeclaredMethods() ) { @@ -95,9 +101,8 @@ private boolean checkforTestAnnotatedMethod( Class testClass ) return false; } - private Class getJUnitClass( ClassLoader classLoader, String className ) + public boolean isRunWithPresentInClassLoader() { - return ReflectionUtils.tryLoadClass( classLoader, className ); + return runWith != null; } - } diff --git a/surefire-providers/common-junit48/pom.xml b/surefire-providers/common-junit48/pom.xml index 0ad0f77f7a..a9d114a733 100644 --- a/surefire-providers/common-junit48/pom.xml +++ b/surefire-providers/common-junit48/pom.xml @@ -17,14 +17,13 @@ ~ under the License. --> - + 4.0.0 org.apache.maven.surefire surefire-providers - 2.13-SNAPSHOT + 2.16-SNAPSHOT ../pom.xml @@ -52,6 +51,11 @@ org.apache.maven.shared maven-shared-utils + + org.apache.maven.surefire + common-java5 + ${project.version} + 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 ed770f6655..f3fcc0b37f 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 @@ -21,12 +21,13 @@ import java.util.ArrayList; import java.util.Arrays; -import java.util.HashMap; +import java.util.Collection; +import java.util.Collections; import java.util.HashSet; import java.util.List; -import java.util.Map; import java.util.Properties; import java.util.Set; + import org.apache.maven.shared.utils.io.SelectorUtils; import org.apache.maven.surefire.booter.ProviderParameterNames; import org.apache.maven.surefire.group.match.AndGroupMatcher; @@ -34,7 +35,6 @@ import org.apache.maven.surefire.group.match.InverseGroupMatcher; import org.apache.maven.surefire.group.parse.GroupMatcherParser; import org.apache.maven.surefire.group.parse.ParseException; - import org.junit.experimental.categories.Category; import org.junit.runner.Description; import org.junit.runner.manipulation.Filter; @@ -65,8 +65,8 @@ public Filter createGroupFilter( Properties providerProperties ) } catch ( ParseException e ) { - throw new IllegalArgumentException( - "Invalid group expression: '" + groups + "'. Reason: " + e.getMessage(), e ); + throw new IllegalArgumentException( "Invalid group expression: '" + groups + "'. Reason: " + + e.getMessage(), e ); } } @@ -79,14 +79,11 @@ public Filter createGroupFilter( Properties providerProperties ) } catch ( ParseException e ) { - throw new IllegalArgumentException( - "Invalid group expression: '" + excludedGroups + "'. Reason: " + e.getMessage(), e ); + throw new IllegalArgumentException( "Invalid group expression: '" + excludedGroups + "'. Reason: " + + e.getMessage(), e ); } } - // GroupMatcher included = commaSeparatedListToFilters( groups ); - // GroupMatcher excluded = commaSeparatedListToFilters( excludedGroups ); - if ( included != null && testClassLoader != null ) { included.loadGroupClasses( testClassLoader ); @@ -100,43 +97,16 @@ public Filter createGroupFilter( Properties providerProperties ) return new GroupMatcherCategoryFilter( included, excluded ); } - // private GroupMatcher commaSeparatedListToFilters( String str ) - // { - // List included = new ArrayList(); - // if ( str != null ) - // { - // for ( String group : str.split( "," ) ) - // { - // group = group.trim(); - // if ( group == null || group.length() == 0) - // { - // continue; - // } - // - // try - // { - // GroupMatcher matcher = new GroupMatcherParser( group ).parse(); - // included.add( matcher ); - // } - // catch ( ParseException e ) - // { - // throw new IllegalArgumentException( "Invalid group expression: '" + group + "'. Reason: " - // + e.getMessage(), e ); - // } - // - // // Class categoryType = classloadCategory( group ); - // // included.add( Categories.CategoryFilter.include( categoryType ) ); - // } - // } - // - // return included.isEmpty() ? null : new OrGroupMatcher( included ); - // } - public Filter createMethodFilter( String requestedTestMethod ) { return new MethodFilter( requestedTestMethod ); } + public Filter and( Filter filter1, Filter filter2 ) + { + return new AndFilter( filter1, filter2 ); + } + private static class MethodFilter extends Filter { @@ -163,11 +133,10 @@ public boolean shouldRun( Description description ) private boolean isDescriptionMatch( Description description ) { - return description.getMethodName() != null && SelectorUtils.match( requestedTestMethod, - description.getMethodName() ); + return description.getMethodName() != null + && SelectorUtils.match( requestedTestMethod, description.getMethodName() ); } - @Override public String describe() { @@ -181,8 +150,6 @@ private static class GroupMatcherCategoryFilter private AndGroupMatcher matcher; - private Map shouldRunAnswers = new HashMap(); - public GroupMatcherCategoryFilter( GroupMatcher included, GroupMatcher excluded ) { GroupMatcher invertedExclude = excluded == null ? null : new InverseGroupMatcher( excluded ); @@ -204,33 +171,46 @@ public GroupMatcherCategoryFilter( GroupMatcher included, GroupMatcher excluded @Override public boolean shouldRun( Description description ) { - return shouldRun( description, ( description.getMethodName() == null - ? null - : Description.createSuiteDescription( description.getTestClass() ) ) ); + if ( description.getMethodName() == null || description.getTestClass() == null ) + { + return shouldRun( description, null, null ); + } + else + { + return shouldRun( description, Description.createSuiteDescription( description.getTestClass() ), + description.getTestClass() ); + } } - private boolean shouldRun( Description description, Description parent ) + private Collection> findSuperclassCategories( Class clazz ) { - Boolean result = shouldRunAnswers.get( description ); - if ( result != null ) + if ( clazz != null && clazz.getSuperclass() != null ) { - return result; + Category cat = clazz.getSuperclass().getAnnotation( Category.class ); + if ( cat != null ) + { + return new HashSet>( Arrays.asList( cat.value() ) ); + } + else + { + return findSuperclassCategories( clazz.getSuperclass() ); + } } + return Collections.emptySet(); + } + + private boolean shouldRun( Description description, Description parent, Class parentClass ) + { if ( matcher == null ) { return true; } - // System.out.println( "\n\nMatcher: " + matcher ); - // System.out.println( "Checking: " + description.getClassName() - // + ( parent == null ? "" : "#" + description.getMethodName() ) ); - Set> cats = new HashSet>(); Category cat = description.getAnnotation( Category.class ); if ( cat != null ) { - // System.out.println( "Adding categories: " + Arrays.toString( cat.value() ) ); cats.addAll( Arrays.asList( cat.value() ) ); } @@ -239,21 +219,21 @@ private boolean shouldRun( Description description, Description parent ) cat = parent.getAnnotation( Category.class ); if ( cat != null ) { - // System.out.println( "Adding class-level categories: " + Arrays.toString( cat.value() ) ); cats.addAll( Arrays.asList( cat.value() ) ); } } - // System.out.println( "Checking " + cats.size() + " categories..." ); - // - // System.out.println( "Enabled? " + ( matcher.enabled( cats.toArray( new Class[] {} ) ) ) + "\n\n" ); - result = matcher.enabled( cats.toArray( new Class[]{ } ) ); + if ( parentClass != null ) + { + cats.addAll( findSuperclassCategories( parentClass ) ); + } + + boolean result = matcher.enabled( cats.toArray( new Class[] {} ) ); if ( parent == null ) { if ( cats.size() == 0 ) { - // System.out.println( "Allow method-level filtering by PASSing class-level shouldRun() test..." ); result = true; } else if ( !result ) @@ -263,7 +243,7 @@ else if ( !result ) { for ( Description child : children ) { - if ( shouldRun( child, description ) ) + if ( shouldRun( child, description, null ) ) { result = true; break; @@ -273,8 +253,7 @@ else if ( !result ) } } - shouldRunAnswers.put( description, result ); - return result == null ? false : result; + return result; } @Override @@ -285,6 +264,31 @@ public String describe() } + private static class AndFilter + extends Filter + { + private final Filter filter1; + + private final Filter filter2; + + public AndFilter( Filter filter1, Filter filter2 ) + { + this.filter1 = filter1; + this.filter2 = filter2; + } + + @Override + public boolean shouldRun( Description description ) + { + return filter1.shouldRun( description ) && filter2.shouldRun( description ); + } + + @Override + public String describe() + { + return filter1.describe() + " AND " + filter2.describe(); + } + } @SuppressWarnings( "unused" ) private static class CombinedCategoryFilter @@ -303,8 +307,8 @@ public CombinedCategoryFilter( List includedFilters, List exclud @Override public boolean shouldRun( Description description ) { - return ( includedFilters.isEmpty() || inOneOfFilters( includedFilters, description ) ) && ( - excludedFilters.isEmpty() || !inOneOfFilters( excludedFilters, description ) ); + return ( includedFilters.isEmpty() || inOneOfFilters( includedFilters, description ) ) + && ( excludedFilters.isEmpty() || !inOneOfFilters( excludedFilters, description ) ); } private boolean inOneOfFilters( List filters, Description description ) diff --git a/surefire-providers/common-junit48/src/main/java/org/apache/maven/surefire/common/junit48/JUnit46StackTraceWriter.java b/surefire-providers/common-junit48/src/main/java/org/apache/maven/surefire/common/junit48/JUnit46StackTraceWriter.java new file mode 100644 index 0000000000..72f0b007c8 --- /dev/null +++ b/surefire-providers/common-junit48/src/main/java/org/apache/maven/surefire/common/junit48/JUnit46StackTraceWriter.java @@ -0,0 +1,55 @@ +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 + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR 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.common.junit4.JUnit4RunListener; +import org.apache.maven.surefire.common.junit4.JUnit4StackTraceWriter; + +import org.junit.runner.notification.Failure; + +/** + * A stacktrace writer that requires at least junit 4.6 to run. Note that we only use this for 4.8 and higher + *

+ * Writes out a specific {@link org.junit.runner.notification.Failure} for + * surefire as a stacktrace. + * + * @author Karl M. Davis + * @author Kristian Rosenvold + */ +public class JUnit46StackTraceWriter + extends JUnit4StackTraceWriter +{ + + /** + * Constructor. + * + * @param junitFailure the {@link org.junit.runner.notification.Failure} that this will be operating on + */ + public JUnit46StackTraceWriter( Failure junitFailure ) + { + super( junitFailure ); + } + + + protected final String getTestClassName() + { + return JUnit4RunListener.extractClassName( junitFailure.getDescription() ); + } +} 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 cb7f159c15..44b12c2880 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 @@ -47,6 +47,8 @@ public boolean isJUnit48Available() public boolean isCategoryAnnotationPresent( Class clazz ) { - return category != null && clazz.getAnnotation( category ) != null; + return ( category != null && + ( clazz.getAnnotation( category ) != null + || ( clazz.getSuperclass() != 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 new file mode 100644 index 0000000000..914c5875dd --- /dev/null +++ b/surefire-providers/common-junit48/src/main/java/org/apache/maven/surefire/common/junit48/JUnit48TestChecker.java @@ -0,0 +1,70 @@ +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 + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR 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.NonAbstractClassFilter; +import org.apache.maven.surefire.common.junit4.JUnit4TestChecker; +import org.apache.maven.surefire.util.ScannerFilter; +import org.junit.experimental.runners.Enclosed; + + +/** + * Looks for additional junit48-like features + * @author Geoff Denning + * @author Kristian Rosenvold + */ +public class JUnit48TestChecker + implements ScannerFilter +{ + private final NonAbstractClassFilter nonAbstractClassFilter; + + private final JUnit4TestChecker jUnit4TestChecker; + + + public JUnit48TestChecker( ClassLoader testClassLoader ) + { + this.jUnit4TestChecker = new JUnit4TestChecker( testClassLoader ); + this.nonAbstractClassFilter = new NonAbstractClassFilter(); + } + + public boolean accept( Class testClass ) + { + return jUnit4TestChecker.accept( testClass ) || isAbstractWithEnclosedRunner( testClass ); + } + + @SuppressWarnings( { "unchecked" } ) + private boolean isAbstractWithEnclosedRunner( Class testClass ) + { + return jUnit4TestChecker.isRunWithPresentInClassLoader() && 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 isAbstract( Class testClass ) + { + return !nonAbstractClassFilter.accept( testClass ); + } +} 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 465b4c972a..fe4a88490b 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 @@ -40,6 +40,7 @@ public void testCategoryAnnotation() { JUnit48Reflector jUnit48Reflector = new JUnit48Reflector( this.getClass().getClassLoader() ); assertTrue( jUnit48Reflector.isCategoryAnnotationPresent( Test1.class ) ); + assertTrue( jUnit48Reflector.isCategoryAnnotationPresent( Test3.class ) ); assertFalse( jUnit48Reflector.isCategoryAnnotationPresent( Test2.class ) ); } @@ -59,4 +60,9 @@ private class Test2 } + 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 new file mode 100644 index 0000000000..9ea0829c7b --- /dev/null +++ b/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/JUnit48TestCheckerTest.java @@ -0,0 +1,75 @@ +package org.apache.maven.surefire.common.junit48; + +import org.junit.Test; +import org.junit.experimental.runners.Enclosed; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +/** + * @author Kristian Rosenvold + */ +public class JUnit48TestCheckerTest +{ + @Test + public void valid48Class() + throws Exception + { + JUnit48TestChecker tc = new JUnit48TestChecker( this.getClass().getClassLoader() ); + assertTrue( tc.accept( BasicTest.class ) ); + } + + @Test + public void notValid48Class() + throws Exception + { + JUnit48TestChecker tc = new JUnit48TestChecker( this.getClass().getClassLoader() ); + assertFalse( tc.accept( BasicTest2.class ) ); + } + + + @RunWith( Enclosed.class ) + public abstract static class BasicTest + { + public static class InnerTest + { + @Test + public void testSomething() + { + } + } + } + + @RunWith( Parameterized.class ) + public abstract static class BasicTest2 + { + public static class InnerTest + { + @Test + public void testSomething() + { + } + } + } +} diff --git a/surefire-providers/pom.xml b/surefire-providers/pom.xml index 151b2e5128..783b84992e 100644 --- a/surefire-providers/pom.xml +++ b/surefire-providers/pom.xml @@ -18,14 +18,13 @@ ~ under the License. --> - + 4.0.0 org.apache.maven.surefire surefire - 2.13-SNAPSHOT + 2.16-SNAPSHOT ../pom.xml @@ -36,6 +35,7 @@ common-junit3 + common-java5 common-junit4 common-junit48 surefire-junit3 @@ -61,7 +61,7 @@ org.apache.maven.surefire surefire-shadefire - ${project.version} + ${shadedVersion} diff --git a/surefire-providers/surefire-junit3/pom.xml b/surefire-providers/surefire-junit3/pom.xml index 26de1204b1..0a9fc9b854 100644 --- a/surefire-providers/surefire-junit3/pom.xml +++ b/surefire-providers/surefire-junit3/pom.xml @@ -17,14 +17,13 @@ ~ under the License. --> - + 4.0.0 org.apache.maven.surefire surefire-providers - 2.13-SNAPSHOT + 2.16-SNAPSHOT ../pom.xml 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 448ba5a75a..22e7069354 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 @@ -102,9 +102,8 @@ else if ( forkTestSet instanceof Class ) System.setSecurityManager( securityManager ); } - for ( Iterator iter = testsToRun.iterator(); iter.hasNext(); ) + for ( Class clazz : testsToRun ) { - Class clazz = (Class) iter.next(); SurefireTestSet surefireTestSet = createTestSet( clazz ); executeTestSet( surefireTestSet, reporter, testClassLoader ); } diff --git a/surefire-providers/surefire-junit3/src/main/java/org/apache/maven/surefire/junit/PojoTestSet.java b/surefire-providers/surefire-junit3/src/main/java/org/apache/maven/surefire/junit/PojoTestSet.java index 787b8320f3..1fe381aeb3 100644 --- a/surefire-providers/surefire-junit3/src/main/java/org/apache/maven/surefire/junit/PojoTestSet.java +++ b/surefire-providers/surefire-junit3/src/main/java/org/apache/maven/surefire/junit/PojoTestSet.java @@ -24,7 +24,7 @@ import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.List; -import org.apache.maven.surefire.report.PojoStackTraceWriter; +import org.apache.maven.surefire.report.LegacyPojoStackTraceWriter; import org.apache.maven.surefire.report.ReportEntry; import org.apache.maven.surefire.report.RunListener; import org.apache.maven.surefire.report.SimpleReportEntry; @@ -40,7 +40,7 @@ public class PojoTestSet private final Object testObject; - private List testMethods; + private List testMethods; private Method setUpMethod; @@ -99,7 +99,7 @@ private void executeTestMethods( RunListener reportManager ) for ( int i = 0; i < testMethods.size() && !abort; ++i ) { - abort = executeTestMethod( (Method) testMethods.get( i ), EMPTY_OBJECT_ARRAY, reportManager ); + abort = executeTestMethod( testMethods.get( i ), EMPTY_OBJECT_ARRAY, reportManager ); } } @@ -132,8 +132,8 @@ private boolean executeTestMethod( Method method, Object[] args, RunListener rep { report = SimpleReportEntry.withException( testObject.getClass().getName(), getTestName( userFriendlyMethodName ), - new PojoStackTraceWriter( testObject.getClass().getName(), - method.getName(), e ) ); + new LegacyPojoStackTraceWriter( testObject.getClass().getName(), + method.getName(), e ) ); reportManager.testFailed( report ); @@ -160,8 +160,8 @@ private boolean executeTestMethod( Method method, Object[] args, RunListener rep report = SimpleReportEntry.withException( testObject.getClass().getName(), getTestName( userFriendlyMethodName ), - new PojoStackTraceWriter( testObject.getClass().getName(), - method.getName(), t ) ); + new LegacyPojoStackTraceWriter( testObject.getClass().getName(), + method.getName(), t ) ); reportManager.testFailed( report ); // Don't return here, because tearDownFixture should be called even @@ -171,8 +171,8 @@ private boolean executeTestMethod( Method method, Object[] args, RunListener rep { report = SimpleReportEntry.withException( testObject.getClass().getName(), getTestName( userFriendlyMethodName ), - new PojoStackTraceWriter( testObject.getClass().getName(), - method.getName(), t ) ); + new LegacyPojoStackTraceWriter( testObject.getClass().getName(), + method.getName(), t ) ); reportManager.testFailed( report ); // Don't return here, because tearDownFixture should be called even @@ -188,8 +188,8 @@ private boolean executeTestMethod( Method method, Object[] args, RunListener rep // Treat any exception from tearDownFixture as a failure of the test. report = SimpleReportEntry.withException( testObject.getClass().getName(), getTestName( userFriendlyMethodName ), - new PojoStackTraceWriter( testObject.getClass().getName(), - method.getName(), t ) ); + new LegacyPojoStackTraceWriter( testObject.getClass().getName(), + method.getName(), t ) ); reportManager.testFailed( report ); @@ -224,7 +224,7 @@ private void setUpFixture() { if ( setUpMethod != null ) { - setUpMethod.invoke( testObject, new Object[0] ); + setUpMethod.invoke( testObject ); } } @@ -233,7 +233,7 @@ private void tearDownFixture() { if ( tearDownMethod != null ) { - tearDownMethod.invoke( testObject, new Object[0] ); + tearDownMethod.invoke( testObject ); } } @@ -241,14 +241,12 @@ private void discoverTestMethods() { if ( testMethods == null ) { - testMethods = new ArrayList(); + testMethods = new ArrayList(); Method[] methods = getTestClass().getMethods(); - for ( int i = 0; i < methods.length; ++i ) + for ( Method m : methods ) { - Method m = methods[i]; - if ( isValidTestMethod( m ) ) { String simpleName = m.getName(); 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 5c4c2fd2d8..01e564b4cd 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 @@ -24,6 +24,7 @@ import java.lang.reflect.Method; import java.util.HashSet; import java.util.Set; +import org.apache.maven.surefire.report.LegacyPojoStackTraceWriter; import org.apache.maven.surefire.report.ReportEntry; import org.apache.maven.surefire.report.RunListener; import org.apache.maven.surefire.report.SimpleReportEntry; @@ -40,7 +41,7 @@ public class TestListenerInvocationHandler private static final String END_TEST = "endTest"; - private final Set failedTestsSet = new HashSet(); + private final Set failedTestsSet = new HashSet(); private RunListener reporter; @@ -157,7 +158,7 @@ private void handleAddError( Object[] args ) failedTestsSet.add( new FailedTest( args[0], Thread.currentThread() ) ); } - private JUnitStackTraceWriter getStackTraceWriter( Object[] args ) + private LegacyPojoStackTraceWriter getStackTraceWriter( Object[] args ) throws IllegalAccessException, InvocationTargetException { String testName; @@ -172,7 +173,7 @@ private JUnitStackTraceWriter getStackTraceWriter( Object[] args ) testName = "UNKNOWN"; } - return new JUnitStackTraceWriter( args[0].getClass().getName(), testName, (Throwable) args[1] ); + return new LegacyPojoStackTraceWriter( args[0].getClass().getName(), testName, (Throwable) args[1] ); } private void handleAddFailure( Object[] args ) 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 4265116314..aac365500e 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,120 +1,120 @@ -package org.apache.maven.surefire.junit; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES 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; -import org.apache.maven.surefire.common.junit3.JUnit3Reflector; -import org.apache.maven.surefire.report.ReportEntry; -import org.apache.maven.surefire.report.RunListener; -import org.apache.maven.surefire.testset.TestSetFailedException; - -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - -public class JUnitTestSetTest - extends TestCase -{ - - public void testExecuteSuiteClass() - throws TestSetFailedException - { - ClassLoader testClassLoader = this.getClass().getClassLoader(); - JUnit3Reflector reflector = new JUnit3Reflector( testClassLoader ); - JUnitTestSet testSet = new JUnitTestSet( Suite.class, reflector ); - SuccessListener listener = new SuccessListener(); - testSet.execute( listener, testClassLoader ); - List succeededTests = listener.getSucceededTests(); - assertEquals( 1, succeededTests.size() ); - assertEquals( "testSuccess(org.apache.maven.surefire.junit.JUnitTestSetTest$AlwaysSucceeds)", - ( (ReportEntry) succeededTests.get( 0 ) ).getName() ); - } - - public static final class AlwaysSucceeds - extends TestCase - { - public void testSuccess() - { - assertTrue( true ); - } - } - - public static class SuccessListener - implements RunListener - { - - private List succeededTests = new ArrayList(); - - public void testSetStarting( ReportEntry report ) - { - } - - public void testSetCompleted( ReportEntry report ) - { - } - - public void testStarting( ReportEntry report ) - { - } - - public void testSucceeded( ReportEntry report ) - { - this.succeededTests.add( report ); - } - - public void testAssumptionFailure( ReportEntry report ) - { - throw new IllegalStateException(); - } - - public void testError( ReportEntry report ) - { - throw new IllegalStateException(); - } - - public void testFailed( ReportEntry report ) - { - throw new IllegalStateException(); - } - - public void testSkipped( ReportEntry report ) - { - throw new IllegalStateException(); - } - - public List getSucceededTests() - { - return succeededTests; - } - - } - - public static class Suite - { - - public static Test suite() - { - TestSuite suite = new TestSuite(); - suite.addTestSuite( AlwaysSucceeds.class ); - return suite; - } - } -} +package org.apache.maven.surefire.junit; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES 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; +import org.apache.maven.surefire.common.junit3.JUnit3Reflector; +import org.apache.maven.surefire.report.ReportEntry; +import org.apache.maven.surefire.report.RunListener; +import org.apache.maven.surefire.testset.TestSetFailedException; + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; + +public class JUnitTestSetTest + extends TestCase +{ + + public void testExecuteSuiteClass() + throws TestSetFailedException + { + ClassLoader testClassLoader = this.getClass().getClassLoader(); + JUnit3Reflector reflector = new JUnit3Reflector( testClassLoader ); + JUnitTestSet testSet = new JUnitTestSet( Suite.class, reflector ); + SuccessListener listener = new SuccessListener(); + testSet.execute( listener, testClassLoader ); + List succeededTests = listener.getSucceededTests(); + assertEquals( 1, succeededTests.size() ); + assertEquals( "testSuccess(org.apache.maven.surefire.junit.JUnitTestSetTest$AlwaysSucceeds)", + ( (ReportEntry) succeededTests.get( 0 ) ).getName() ); + } + + public static final class AlwaysSucceeds + extends TestCase + { + public void testSuccess() + { + assertTrue( true ); + } + } + + public static class SuccessListener + implements RunListener + { + + private List succeededTests = new ArrayList(); + + public void testSetStarting( ReportEntry report ) + { + } + + public void testSetCompleted( ReportEntry report ) + { + } + + public void testStarting( ReportEntry report ) + { + } + + public void testSucceeded( ReportEntry report ) + { + this.succeededTests.add( report ); + } + + public void testAssumptionFailure( ReportEntry report ) + { + throw new IllegalStateException(); + } + + public void testError( ReportEntry report ) + { + throw new IllegalStateException(); + } + + public void testFailed( ReportEntry report ) + { + throw new IllegalStateException(); + } + + public void testSkipped( ReportEntry report ) + { + throw new IllegalStateException(); + } + + public List getSucceededTests() + { + return succeededTests; + } + + } + + public static class Suite + { + + public static Test suite() + { + TestSuite suite = new TestSuite(); + suite.addTestSuite( AlwaysSucceeds.class ); + return suite; + } + } +} diff --git a/surefire-providers/surefire-junit4/pom.xml b/surefire-providers/surefire-junit4/pom.xml index 077bdd3391..65a181648e 100644 --- a/surefire-providers/surefire-junit4/pom.xml +++ b/surefire-providers/surefire-junit4/pom.xml @@ -17,14 +17,13 @@ ~ under the License. --> - + 4.0.0 org.apache.maven.surefire surefire-providers - 2.13-SNAPSHOT + 2.16-SNAPSHOT ../pom.xml @@ -44,6 +43,12 @@ common-junit4 ${project.version} + + org.apache.maven.surefire + common-java5 + ${project.version} + + @@ -77,6 +82,7 @@ org.apache.maven.surefire:common-junit3 org.apache.maven.surefire:common-junit4 + org.apache.maven.surefire:common-java5 org.apache.maven.shared:maven-shared-utils 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 d2cc117369..a03c7d269d 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 @@ -22,6 +22,7 @@ import java.lang.reflect.Method; import java.util.Iterator; import java.util.List; + import org.apache.maven.shared.utils.io.SelectorUtils; import org.apache.maven.surefire.common.junit4.JUnit4RunListener; import org.apache.maven.surefire.common.junit4.JUnit4RunListenerFactory; @@ -118,9 +119,9 @@ else if ( forkTestSet instanceof Class ) runNotifer.fireTestRunStarted( null ); - for ( Iterator> iter = testsToRun.iterator(); iter.hasNext(); ) + for ( Class aTestsToRun : testsToRun ) { - executeTestSet( iter.next(), reporter, runNotifer ); + executeTestSet( aTestsToRun, reporter, runNotifer ); } runNotifer.fireTestRunFinished( result ); @@ -206,23 +207,23 @@ private TestsToRun scanClassPath() return runOrderCalculator.orderTestClasses( scannedClasses ); } - @SuppressWarnings( "unchecked" ) + @SuppressWarnings("unchecked") private void upgradeCheck() throws TestSetFailedException { if ( isJunit4UpgradeCheck() ) { - List classesSkippedByValidation = + List classesSkippedByValidation = 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 ( String testClass : classesSkippedByValidation ) + for ( Class testClass : classesSkippedByValidation ) { reason.append( " " ); - reason.append( testClass ); + reason.append( testClass.getName() ); reason.append( "\n" ); } throw new TestSetFailedException( reason.toString() ); diff --git a/surefire-providers/surefire-junit4/src/main/java/org/apache/maven/surefire/junit4/JUnit4Provider.java.orig b/surefire-providers/surefire-junit4/src/main/java/org/apache/maven/surefire/junit4/JUnit4Provider.java.orig new file mode 100644 index 0000000000..44cdb40479 --- /dev/null +++ b/surefire-providers/surefire-junit4/src/main/java/org/apache/maven/surefire/junit4/JUnit4Provider.java.orig @@ -0,0 +1,297 @@ +package org.apache.maven.surefire.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.lang.reflect.Method; +import java.util.Iterator; +import java.util.List; + +import org.apache.maven.shared.utils.io.SelectorUtils; +import org.apache.maven.surefire.common.junit4.JUnit4RunListener; +import org.apache.maven.surefire.common.junit4.JUnit4RunListenerFactory; +import org.apache.maven.surefire.common.junit4.JUnit4TestChecker; +import org.apache.maven.surefire.providerapi.AbstractProvider; +import org.apache.maven.surefire.providerapi.ProviderParameters; +import org.apache.maven.surefire.report.ConsoleOutputCapture; +import org.apache.maven.surefire.report.ConsoleOutputReceiver; +import org.apache.maven.surefire.report.PojoStackTraceWriter; +import org.apache.maven.surefire.report.ReportEntry; +import org.apache.maven.surefire.report.ReporterException; +import org.apache.maven.surefire.report.ReporterFactory; +import org.apache.maven.surefire.report.RunListener; +import org.apache.maven.surefire.report.SimpleReportEntry; +import org.apache.maven.surefire.suite.RunResult; +import org.apache.maven.surefire.testset.TestSetFailedException; +import org.apache.maven.surefire.util.RunOrderCalculator; +import org.apache.maven.surefire.util.ScanResult; +import org.apache.maven.surefire.util.TestsToRun; +import org.apache.maven.surefire.util.internal.StringUtils; + +import org.junit.runner.Request; +import org.junit.runner.Result; +import org.junit.runner.Runner; +import org.junit.runner.notification.RunNotifier; + +/** + * @author Kristian Rosenvold + */ +public class JUnit4Provider + extends AbstractProvider +{ + private final ClassLoader testClassLoader; + + private final List customRunListeners; + + private final JUnit4TestChecker jUnit4TestChecker; + + private final String requestedTestMethod; + + private TestsToRun testsToRun; + + private final ProviderParameters providerParameters; + + private final RunOrderCalculator runOrderCalculator; + + private final ScanResult scanResult; + + + public JUnit4Provider( ProviderParameters booterParameters ) + { + this.providerParameters = booterParameters; + this.testClassLoader = booterParameters.getTestClassLoader(); + this.scanResult = booterParameters.getScanResult(); + this.runOrderCalculator = booterParameters.getRunOrderCalculator(); + customRunListeners = JUnit4RunListenerFactory. + createCustomListeners( booterParameters.getProviderProperties().getProperty( "listener" ) ); + jUnit4TestChecker = new JUnit4TestChecker( testClassLoader ); + requestedTestMethod = booterParameters.getTestRequest().getRequestedTestMethod(); + + } + + public RunResult invoke( Object forkTestSet ) + throws TestSetFailedException, ReporterException + { + if ( testsToRun == null ) + { + if ( forkTestSet instanceof TestsToRun ) + { + testsToRun = (TestsToRun) forkTestSet; + } + else if ( forkTestSet instanceof Class ) + { + testsToRun = TestsToRun.fromClass( (Class) forkTestSet ); + } + else + { + testsToRun = scanClassPath(); + } + } + + upgradeCheck(); + + final ReporterFactory reporterFactory = providerParameters.getReporterFactory(); + + final RunListener reporter = reporterFactory.createReporter(); + + ConsoleOutputCapture.startCapture( (ConsoleOutputReceiver) reporter ); + + JUnit4RunListener jUnit4TestSetReporter = new JUnit4RunListener( reporter ); + + Result result = new Result(); + RunNotifier runNotifer = getRunNotifer( jUnit4TestSetReporter, result, customRunListeners ); + + runNotifer.fireTestRunStarted( null ); + + for ( @SuppressWarnings( "unchecked" ) Iterator> iter = testsToRun.iterator(); iter.hasNext(); ) + { + executeTestSet( iter.next(), reporter, runNotifer ); + } + + runNotifer.fireTestRunFinished( result ); + + JUnit4RunListener.rethrowAnyTestMechanismFailures( result ); + + closeRunNotifer( jUnit4TestSetReporter, customRunListeners ); + + return reporterFactory.close(); + } + + private void executeTestSet( Class clazz, RunListener reporter, RunNotifier listeners ) + throws ReporterException, TestSetFailedException + { + final ReportEntry report = new SimpleReportEntry( this.getClass().getName(), clazz.getName() ); + + reporter.testSetStarting( report ); + + try + { + if ( !StringUtils.isBlank( this.requestedTestMethod ) ) + { + String actualTestMethod = getMethod( clazz, this.requestedTestMethod );//add by rainLee + String[] testMethods = StringUtils.split( actualTestMethod, "+" ); + execute( clazz, listeners, testMethods ); + } + else + {//the original way + execute( clazz, listeners, null ); + } + } + catch ( TestSetFailedException e ) + { + throw e; + } + catch ( Throwable e ) + { + reporter.testError( SimpleReportEntry.withException( report.getSourceName(), report.getName(), + new PojoStackTraceWriter( report.getSourceName(), + report.getName(), e ) ) ); + } + finally + { + reporter.testSetCompleted( report ); + } + } + + private RunNotifier getRunNotifer( org.junit.runner.notification.RunListener main, Result result, + List others ) + { + RunNotifier fNotifier = new RunNotifier(); + fNotifier.addListener( main ); + fNotifier.addListener( result.createListener() ); + for ( org.junit.runner.notification.RunListener listener : others ) + { + fNotifier.addListener( listener ); + } + return fNotifier; + } + + // I am not entierly sure as to why we do this explicit freeing, it's one of those + // pieces of code that just seem to linger on in here ;) + private void closeRunNotifer( org.junit.runner.notification.RunListener main, + List others ) + { + RunNotifier fNotifier = new RunNotifier(); + fNotifier.removeListener( main ); + for ( org.junit.runner.notification.RunListener listener : others ) + { + fNotifier.removeListener( listener ); + } + } + + public Iterator getSuites() + { + testsToRun = scanClassPath(); + return testsToRun.iterator(); + } + + private TestsToRun scanClassPath() + { + final TestsToRun scannedClasses = scanResult.applyFilter( jUnit4TestChecker, testClassLoader ); + return runOrderCalculator.orderTestClasses( scannedClasses ); + } + + @SuppressWarnings("unchecked") + private void upgradeCheck() + throws TestSetFailedException + { + if ( isJunit4UpgradeCheck() ) + { + List classesSkippedByValidation = + 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 ( String testClass : classesSkippedByValidation ) + { + reason.append( " " ); + reason.append( testClass ); + reason.append( "\n" ); + } + throw new TestSetFailedException( reason.toString() ); + } + } + } + + private boolean isJunit4UpgradeCheck() + { + final String property = System.getProperty( "surefire.junit4.upgradecheck" ); + return property != null; + } + + + private static void execute( Class testClass, RunNotifier fNotifier, String[] testMethods ) + throws TestSetFailedException + { + if ( null != testMethods ) + { + Method[] methods = testClass.getMethods(); + for ( Method method : methods ) + { + for ( String testMethod : testMethods ) + { + if ( SelectorUtils.match( testMethod, method.getName() ) ) + { + Runner junitTestRunner = Request.method( testClass, method.getName() ).getRunner(); + junitTestRunner.run( fNotifier ); + } + + } + } + return; + } + + Runner junitTestRunner = Request.aClass( testClass ).getRunner(); + + junitTestRunner.run( fNotifier ); + } + + /** + * this method retrive testMethods from String like "com.xx.ImmutablePairTest#testBasic,com.xx.StopWatchTest#testLang315+testStopWatchSimpleGet" + *
+ * and we need to think about cases that 2 or more method in 1 class. we should choose the correct method + * + * @param testClass the testclass + * @param testMethodStr the test method string + * @return a string ;) + */ + private static String getMethod( Class testClass, String testMethodStr ) + { + String className = testClass.getName(); + + if ( !testMethodStr.contains( "#" ) && !testMethodStr.contains( "," ) ) + {//the original way + return testMethodStr; + } + testMethodStr += ",";//for the bellow split code + int beginIndex = testMethodStr.indexOf( className ); + int endIndex = testMethodStr.indexOf( ",", beginIndex ); + String classMethodStr = + testMethodStr.substring( beginIndex, endIndex );//String like "StopWatchTest#testLang315" + + int index = classMethodStr.indexOf( '#' ); + if ( index >= 0 ) + { + return classMethodStr.substring( index + 1, classMethodStr.length() ); + } + return null; + } +} 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 93f1114a10..147a5c1d63 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 @@ -35,7 +35,7 @@ public void testCreateProvider() { BaseProviderFactory providerParameters = new BaseProviderFactory( null, Boolean.TRUE ); providerParameters.setProviderProperties( new Properties() ); - providerParameters.setClassLoaders( this.getClass().getClassLoader(), this.getClass().getClassLoader() ); + providerParameters.setClassLoaders( this.getClass().getClassLoader() ); providerParameters.setTestRequest( new TestRequest( null, null, null ) ); assertNotNull( new JUnit4Provider( providerParameters ) ); } diff --git a/surefire-providers/surefire-junit47/pom.xml b/surefire-providers/surefire-junit47/pom.xml index ddfb73d33c..2edb2e5470 100644 --- a/surefire-providers/surefire-junit47/pom.xml +++ b/surefire-providers/surefire-junit47/pom.xml @@ -17,14 +17,13 @@ ~ under the License. --> - + 4.0.0 org.apache.maven.surefire surefire-providers - 2.13-SNAPSHOT + 2.16-SNAPSHOT ../pom.xml @@ -39,12 +38,6 @@ 4.8.1 provided - - org.mockito - mockito-all - 1.7 - test - org.apache.maven.surefire common-junit4 @@ -60,6 +53,11 @@ common-junit48 ${project.version} + + org.apache.maven.surefire + common-java5 + ${project.version} + @@ -92,8 +90,19 @@ org.apache.maven.surefire:common-junit3 org.apache.maven.surefire:common-junit4 + org.apache.maven.surefire:common-java5 + + + javax.annotation + org.apache.maven.surefire.javax.annotation + + + org.apache.maven.shared + org.apache.maven.surefire.org.apache.maven.shared + + 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 fe6ef7568e..4d14d31810 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,81 +1,81 @@ -package org.apache.maven.surefire.junitcore; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES 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.Collections; -import java.util.List; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import org.apache.maven.surefire.util.NestedRuntimeException; - -import org.junit.runners.model.RunnerScheduler; - -/** - * @author Kristian Rosenvold - */ -public class AsynchronousRunner - implements RunnerScheduler -{ - private final List> futures = Collections.synchronizedList( new ArrayList>() ); - - private final ExecutorService fService; - - public AsynchronousRunner( ExecutorService fService ) - { - this.fService = fService; - } - - public void schedule( final Runnable childStatement ) - { - futures.add( fService.submit( Executors.callable( childStatement ) ) ); - } - - - public void finished() - { - try - { - waitForCompletion(); - } - catch ( ExecutionException e ) - { - throw new NestedRuntimeException( e ); - } - } - - public void waitForCompletion() - throws ExecutionException - { - for ( Future each : futures ) - { - try - { - each.get(); - } - catch ( InterruptedException e ) - { - throw new NestedRuntimeException( e ); - } - } - } -} +package org.apache.maven.surefire.junitcore; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES 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.Collections; +import java.util.List; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import org.apache.maven.surefire.util.NestedRuntimeException; + +import org.junit.runners.model.RunnerScheduler; + +/** + * @author Kristian Rosenvold + */ +public class AsynchronousRunner + implements RunnerScheduler +{ + private final List> futures = Collections.synchronizedList( new ArrayList>() ); + + private final ExecutorService fService; + + public AsynchronousRunner( ExecutorService fService ) + { + this.fService = fService; + } + + public void schedule( final Runnable childStatement ) + { + futures.add( fService.submit( Executors.callable( childStatement ) ) ); + } + + + public void finished() + { + try + { + waitForCompletion(); + } + catch ( ExecutionException e ) + { + throw new NestedRuntimeException( e ); + } + } + + public void waitForCompletion() + throws ExecutionException + { + for ( Future each : futures ) + { + try + { + each.get(); + } + catch ( InterruptedException e ) + { + throw new NestedRuntimeException( 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 018da2d098..518dd0d35b 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 @@ -28,7 +28,7 @@ * @author Kristian Rosenvold */ public class ClassesParallelRunListener - extends ConcurrentReporterManager + extends ConcurrentRunListener { public ClassesParallelRunListener( Map classMethodCounts, ReporterFactory reporterFactory, ConsoleLogger consoleLogger ) diff --git a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/ConcurrentReporterManager.java b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/ConcurrentRunListener.java similarity index 75% rename from surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/ConcurrentReporterManager.java rename to surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/ConcurrentRunListener.java index fc1dde122b..72543649ea 100644 --- a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/ConcurrentReporterManager.java +++ b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/ConcurrentRunListener.java @@ -35,14 +35,15 @@ * parallel=methods; beforeClass/afterClass run on main thread, constructor + each test method run on same thread * parallel=both; same as parallel=methods * + * @see org.apache.maven.surefire.junitcore.JUnitCoreRunListener for details about regular junit run listening * @author Kristian Rosenvold */ -public abstract class ConcurrentReporterManager +public abstract class ConcurrentRunListener implements RunListener, ConsoleOutputReceiver { private final Map classMethodCounts; - private final ThreadLocal reporterManagerThreadLocal = new ThreadLocal(); + private final ThreadLocal reporterManagerThreadLocal; private final boolean reportImmediately; @@ -50,14 +51,23 @@ public abstract class ConcurrentReporterManager private final ConsoleLogger consoleLogger; - ConcurrentReporterManager( ReporterFactory reporterFactory, ConsoleLogger consoleLogger, boolean reportImmediately, - Map classMethodCounts ) + ConcurrentRunListener( ReporterFactory reporterFactory, ConsoleLogger consoleLogger, boolean reportImmediately, + Map classMethodCounts ) throws TestSetFailedException { this.reportImmediately = reportImmediately; this.reporterFactory = reporterFactory; this.classMethodCounts = classMethodCounts; this.consoleLogger = consoleLogger; + + this.reporterManagerThreadLocal = new ThreadLocal() + { + @Override + protected RunListener initialValue() + { + return ConcurrentRunListener.this.reporterFactory.createReporter(); + } + }; } public void testSetStarting( ReportEntry description ) @@ -71,48 +81,52 @@ public void testSetCompleted( ReportEntry result ) { testSet.replay( reporterManager ); } + reporterManagerThreadLocal.remove(); } public void testFailed( ReportEntry failure ) { - final TestMethod testMethod = getOrCreateTestMethod( failure ); + final TestMethod testMethod = getOrCreateThreadAttachedTestMethod( failure ); if ( testMethod != null ) { testMethod.testFailure( failure ); + testMethod.detachFromCurrentThread(); } } public void testError( ReportEntry failure ) { - final TestMethod testMethod = getOrCreateTestMethod( failure ); + final TestMethod testMethod = getOrCreateThreadAttachedTestMethod( failure ); if ( testMethod != null ) { testMethod.testError( failure ); + testMethod.detachFromCurrentThread(); } } public void testSkipped( ReportEntry description ) { TestSet testSet = getTestSet( description ); - TestMethod testMethod = getTestSet( description ).createTestMethod( description ); + TestMethod testMethod = testSet.createThreadAttachedTestMethod( description ); testMethod.testIgnored( description ); testSet.incrementFinishedTests( getRunListener(), reportImmediately ); + testMethod.detachFromCurrentThread(); } public void testAssumptionFailure( ReportEntry failure ) { - final TestMethod testMethod = getOrCreateTestMethod( failure ); + final TestMethod testMethod = getOrCreateThreadAttachedTestMethod( failure ); if ( testMethod != null ) { testMethod.testIgnored( failure ); + testMethod.detachFromCurrentThread(); } } public void testStarting( ReportEntry description ) { TestSet testSet = getTestSet( description ); - final TestMethod testMethod = testSet.createTestMethod( description ); - testMethod.attachToThread(); + testSet.createThreadAttachedTestMethod( description ); checkIfTestSetCanBeReported( testSet ); testSet.attachToThread(); @@ -120,12 +134,16 @@ public void testStarting( ReportEntry description ) public void testSucceeded( ReportEntry report ) { - getTestMethod().testFinished(); - TestSet.getThreadTestSet().incrementFinishedTests( getRunListener(), reportImmediately ); - detachTestMethodFromThread(); + TestMethod testMethod = getTestMethod(); + if ( null != testMethod ) + { + testMethod.testFinished(); + testMethod.getTestSet().incrementFinishedTests( getRunListener(), reportImmediately ); + testMethod.detachFromCurrentThread(); + } } - private TestMethod getOrCreateTestMethod( ReportEntry description ) + private TestMethod getOrCreateThreadAttachedTestMethod( ReportEntry description ) { TestMethod threadTestMethod = TestMethod.getThreadTestMethod(); if ( threadTestMethod != null ) @@ -141,7 +159,7 @@ private TestMethod getOrCreateTestMethod( ReportEntry description ) } else { - return testSet.createTestMethod( description ); + return testSet.createThreadAttachedTestMethod( description ); } } @@ -152,11 +170,6 @@ TestMethod getTestMethod() return TestMethod.getThreadTestMethod(); } - void detachTestMethodFromThread() - { - TestMethod.detachFromCurrentThread(); - } - TestSet getTestSet( ReportEntry description ) { return classMethodCounts.get( description.getSourceName() ); @@ -164,16 +177,11 @@ TestSet getTestSet( ReportEntry description ) RunListener getRunListener() { - RunListener runListener = reporterManagerThreadLocal.get(); - if ( runListener == null ) - { - runListener = reporterFactory.createReporter(); - reporterManagerThreadLocal.set( runListener ); - } - return runListener; + return reporterManagerThreadLocal.get(); } - public static ConcurrentReporterManager createInstance( Map classMethodCounts, + + public static ConcurrentRunListener createInstance( Map classMethodCounts, ReporterFactory reporterManagerFactory, boolean parallelClasses, boolean parallelBoth, ConsoleLogger consoleLogger ) 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 91a954f6f6..a2dcea2d32 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 @@ -43,7 +43,6 @@ class JUnitCoreParameters public static final String USEUNLIMITEDTHREADS_KEY = "useUnlimitedThreads"; - public JUnitCoreParameters( Properties properties ) { this.parallel = properties.getProperty( PARALLEL_KEY, "none" ).toLowerCase(); 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 d857aff7ad..14af56cf45 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 @@ -23,10 +23,11 @@ import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; + import org.apache.maven.surefire.common.junit4.JUnit4RunListenerFactory; -import org.apache.maven.surefire.common.junit4.JUnit4TestChecker; import org.apache.maven.surefire.common.junit48.FilterFactory; import org.apache.maven.surefire.common.junit48.JUnit48Reflector; +import org.apache.maven.surefire.common.junit48.JUnit48TestChecker; import org.apache.maven.surefire.providerapi.AbstractProvider; import org.apache.maven.surefire.providerapi.ProviderParameters; import org.apache.maven.surefire.report.ConsoleLogger; @@ -42,7 +43,6 @@ import org.apache.maven.surefire.util.ScannerFilter; import org.apache.maven.surefire.util.TestsToRun; import org.apache.maven.surefire.util.internal.StringUtils; - import org.junit.runner.manipulation.Filter; /** @@ -62,7 +62,6 @@ public class JUnitCoreProvider private final ProviderParameters providerParameters; - private TestsToRun testsToRun; private JUnit48Reflector jUnit48Reflector; @@ -80,11 +79,11 @@ public JUnitCoreProvider( ProviderParameters providerParameters ) this.scanResult = providerParameters.getScanResult(); this.runOrderCalculator = providerParameters.getRunOrderCalculator(); this.jUnitCoreParameters = new JUnitCoreParameters( providerParameters.getProviderProperties() ); - this.scannerFilter = new JUnit4TestChecker( testClassLoader ); + this.scannerFilter = new JUnit48TestChecker( testClassLoader ); this.requestedTestMethod = providerParameters.getTestRequest().getRequestedTestMethod(); - customRunListeners = JUnit4RunListenerFactory. - createCustomListeners( providerParameters.getProviderProperties().getProperty( "listener" ) ); + customRunListeners = + JUnit4RunListenerFactory.createCustomListeners( providerParameters.getProviderProperties().getProperty( "listener" ) ); jUnit48Reflector = new JUnit48Reflector( testClassLoader ); } @@ -95,19 +94,22 @@ public Boolean isRunnable() public Iterator getSuites() { - final Filter filter = jUnit48Reflector.isJUnit48Available() ? createJUnit48Filter() : null; testsToRun = scanClassPath(); return testsToRun.iterator(); } + private boolean isSingleThreaded() + { + return !jUnitCoreParameters.isAnyParallelitySelected() + || ( testsToRun.containsExactly( 1 ) && !jUnitCoreParameters.isParallelMethod() ); + } + public RunResult invoke( Object forkTestSet ) throws TestSetFailedException, ReporterException { - final String message = "Concurrency config is " + jUnitCoreParameters.toString() + "\n"; final ReporterFactory reporterFactory = providerParameters.getReporterFactory(); final ConsoleLogger consoleLogger = providerParameters.getConsoleLogger(); - consoleLogger.info( message ); Filter filter = jUnit48Reflector.isJUnit48Available() ? createJUnit48Filter() : null; @@ -128,28 +130,45 @@ else if ( forkTestSet instanceof Class ) } } - final Map testSetMap = new ConcurrentHashMap(); - - RunListener listener = ConcurrentReporterManager.createInstance( testSetMap, reporterFactory, - jUnitCoreParameters.isParallelClasses(), - jUnitCoreParameters.isParallelBoth(), - consoleLogger ); - - ConsoleOutputCapture.startCapture( (ConsoleOutputReceiver) listener ); - - org.junit.runner.notification.RunListener jUnit4RunListener = new JUnitCoreRunListener( listener, testSetMap ); + org.junit.runner.notification.RunListener jUnit4RunListener = getRunListener( reporterFactory, consoleLogger ); customRunListeners.add( 0, jUnit4RunListener ); - JUnitCoreWrapper.execute( testsToRun, jUnitCoreParameters, customRunListeners, filter ); return reporterFactory.close(); } + private org.junit.runner.notification.RunListener getRunListener( ReporterFactory reporterFactory, + ConsoleLogger consoleLogger ) + throws TestSetFailedException + { + org.junit.runner.notification.RunListener jUnit4RunListener; + if ( isSingleThreaded() ) + { + NonConcurrentRunListener rm = new NonConcurrentRunListener( reporterFactory.createReporter() ); + ConsoleOutputCapture.startCapture( rm ); + jUnit4RunListener = rm; + } + else + { + final Map testSetMap = new ConcurrentHashMap(); + + RunListener listener = + ConcurrentRunListener.createInstance( testSetMap, reporterFactory, + jUnitCoreParameters.isParallelClasses(), + jUnitCoreParameters.isParallelBoth(), consoleLogger ); + ConsoleOutputCapture.startCapture( (ConsoleOutputReceiver) listener ); + + jUnit4RunListener = new JUnitCoreRunListener( listener, testSetMap ); + } + return jUnit4RunListener; + } + private Filter createJUnit48Filter() { final FilterFactory filterFactory = new FilterFactory( testClassLoader ); - return isMethodFilterSpecified() - ? filterFactory.createMethodFilter( requestedTestMethod ) - : filterFactory.createGroupFilter( providerParameters.getProviderProperties() ); + Filter groupFilter = filterFactory.createGroupFilter( providerParameters.getProviderProperties() ); + return isMethodFilterSpecified() ? filterFactory.and( groupFilter, + filterFactory.createMethodFilter( requestedTestMethod ) ) + : groupFilter; } private TestsToRun scanClassPath() 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 abce8ce308..5d76c39b2c 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 @@ -22,11 +22,23 @@ import java.util.ArrayList; import java.util.Map; import org.apache.maven.surefire.common.junit4.JUnit4RunListener; +import org.apache.maven.surefire.common.junit48.JUnit46StackTraceWriter; import org.apache.maven.surefire.report.RunListener; +import org.apache.maven.surefire.report.StackTraceWriter; import org.junit.runner.Description; import org.junit.runner.Result; +import org.junit.runner.notification.Failure; +/** + * Noteworthy things about JUnit4 listening: + *

+ * A class that is annotated with @Ignore will have one invocation of "testSkipped" with source==name + * A method that is annotated with @Ignore will have a invocation of testSkipped with source and name distinct + * Methods annotated with @Ignore trigger no further events. + * + * @see org.apache.maven.surefire.junitcore.ConcurrentRunListener for details about parallel running + */ public class JUnitCoreRunListener extends JUnit4RunListener { @@ -69,21 +81,24 @@ private void fillTestCountMap( Description description ) String itemTestClassName = null; for ( Description item : children ) { - if ( item.isTest() && item.getMethodName() != null ) - { - testSet.incrementTestMethodCount(); - if ( itemTestClassName == null ) - { - itemTestClassName = item.getClassName(); - } - } - else if ( item.getChildren().size() > 0 ) + if ( !item.isTest() ) { fillTestCountMap( item ); } else { - classMethodCounts.put( item.getClassName(), testSet ); + if ( item.getMethodName() != null ) + { + testSet.incrementTestMethodCount(); + if ( itemTestClassName == null ) + { + itemTestClassName = item.getClassName(); + } + } + else + { + classMethodCounts.put( item.getClassName(), new TestSet( item ) ); + } } } if ( itemTestClassName != null ) @@ -92,4 +107,9 @@ else if ( item.getChildren().size() > 0 ) } } + @Override + protected StackTraceWriter createStackTraceWriter( Failure failure ) + { + return new JUnit46StackTraceWriter( 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 99bf6dc6be..4473063fc1 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 @@ -74,40 +74,70 @@ public static void execute( TestsToRun testsToRun, JUnitCoreParameters jUnitCore throws TestSetFailedException { Computer computer = getComputer( jUnitCoreParameters ); - JUnitCore junitCore = new JUnitCore(); - for ( RunListener runListener : listeners ) - { - junitCore.addListener( runListener ); - } + + JUnitCore junitCore = createJUnitCore( listeners ); try { - // in order to support LazyTestsToRun, the iterator must be used - Iterator classIter = testsToRun.iterator(); - while ( classIter.hasNext() ) + if ( testsToRun.allowEagerReading() ) + { + executeEager( testsToRun, filter, computer, junitCore ); + } + else { - Request req = Request.classes( computer, new Class[]{ (Class) classIter.next() } ); - if ( filter != null ) - { - req = new FilteringRequest( req, filter ); - if ( req.getRunner() == null ) - { - continue; - } - } - - final Result run = junitCore.run( req ); - JUnit4RunListener.rethrowAnyTestMechanismFailures( run ); + exeuteLazy( testsToRun, filter, computer, junitCore ); } } finally { closeIfConfigurable( computer ); - for ( RunListener runListener : listeners ) + } + } + + private static JUnitCore createJUnitCore( List listeners ) + { + JUnitCore junitCore = new JUnitCore(); + for ( RunListener runListener : listeners ) + { + junitCore.addListener( runListener ); + } + return junitCore; + } + + private static void executeEager(TestsToRun testsToRun, Filter filter, Computer computer, JUnitCore junitCore) + throws TestSetFailedException + { + Class[] tests = testsToRun.getLocatedClasses(); + createReqestAndRun( filter, computer, junitCore, tests ); + } + + private static void exeuteLazy(TestsToRun testsToRun, Filter filter, Computer computer, JUnitCore junitCore) + throws TestSetFailedException + { + // in order to support LazyTestsToRun, the iterator must be used + Iterator classIter = testsToRun.iterator(); + while ( classIter.hasNext() ) + { + createReqestAndRun( filter, computer, junitCore, new Class[]{ (Class) classIter.next() } ); + } + } + + private static void createReqestAndRun( Filter filter, Computer computer, JUnitCore junitCore, Class[] classesToRun ) + throws TestSetFailedException + { + Request req = Request.classes( computer, classesToRun ); + if ( filter != null ) + { + req = new FilteringRequest( req, filter ); + if ( req.getRunner() == null ) { - junitCore.removeListener( runListener ); + // nothing to run + return; } } + + final Result run = junitCore.run( req ); + JUnit4RunListener.rethrowAnyTestMechanismFailures( run ); } private static void closeIfConfigurable( Computer computer ) @@ -151,4 +181,5 @@ private static Computer getConfigurableParallelComputer( JUnitCoreParameters jUn jUnitCoreParameters.getThreadCount(), jUnitCoreParameters.isPerCoreThreadCount() ); } } + } diff --git a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/JUnitUtils.java b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/JUnitUtils.java new file mode 100644 index 0000000000..ce3ba55450 --- /dev/null +++ b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/JUnitUtils.java @@ -0,0 +1,99 @@ +package org.apache.maven.surefire.junitcore; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES 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.Iterator; +import java.util.List; +import java.util.StringTokenizer; +import junit.runner.Version; +import org.apache.maven.surefire.util.NestedRuntimeException; + +/** + * @author Tibor Digana (tibor17) + * @since 2.13 + */ +final class JUnitUtils +{ + private JUnitUtils() + { + } + + private static List parseVersion( String version ) + { + ArrayList versions = new ArrayList( 3 ); + StringTokenizer tokens = new StringTokenizer( version, "." ); + try + { + while ( tokens.hasMoreTokens() ) + { + versions.add( Integer.valueOf( tokens.nextToken() ) ); + } + } + catch ( NumberFormatException e ) + { + throw new NestedRuntimeException( "JUnit version has not numbers " + version, e ); + } + return versions; + } + + /** + * @return Maven versions ordered as follows (if exist): + *

    + *
  • Major at index 0 + *
  • Minor at index 1 + *
  • Incremental at index 2 + *
+ * @throws NestedRuntimeException if cannot parse the version; or the version is null + */ + static List versions() + { + String version = Version.id();System.out.println("tibor " + version); + + if ( version == null ) + { + throw new NestedRuntimeException( new NullPointerException( "junit.runner.Version#id returns null" ) ); + } + + if ( version.contains( "-" ) ) + { + version = version.substring( 0, version.indexOf( '-' ) ); + } + + return parseVersion( version ); + } + + static boolean isCompatibleVersionWith( int expectedMajor, int minor ) + { + Iterator currentVersions = versions().iterator(); + + if ( !currentVersions.hasNext() || currentVersions.next() != expectedMajor ) + { + return false; + } + + if ( !currentVersions.hasNext() || currentVersions.next() < minor ) + { + return false; + } + + return true; + } +} 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 0aa531a46c..5e27669365 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 @@ -28,7 +28,7 @@ * @author Kristian Rosenvold */ public class MethodsParallelRunListener - extends ConcurrentReporterManager + extends ConcurrentRunListener { private volatile TestSet lastStarted; 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 new file mode 100644 index 0000000000..dcf861512e --- /dev/null +++ b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/NonConcurrentRunListener.java @@ -0,0 +1,165 @@ +package org.apache.maven.surefire.junitcore; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR 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.common.junit4.JUnit4RunListener; +import org.apache.maven.surefire.report.ConsoleOutputReceiver; +import org.apache.maven.surefire.report.RunListener; +import org.apache.maven.surefire.report.SimpleReportEntry; +import org.apache.maven.surefire.testset.TestSetFailedException; +import org.junit.runner.Description; +import org.junit.runner.Result; +import org.junit.runner.notification.Failure; + +/** + * A class to be used when there is no JUnit parallelism (methods or/and class). This allow to workaround JUnit + * limitation a la Junit4 provider. Specifically, we can redirect properly the output even if we don't have class + * demarcation in JUnit. It works when if there is a JVM instance per test run, i.e. with forkMode=always or perthread. + */ +public class NonConcurrentRunListener + extends JUnit4RunListener + implements ConsoleOutputReceiver +{ + + private Description currentTestSetDescription; + + private Description lastFinishedDescription; + + public NonConcurrentRunListener( RunListener reporter ) + throws TestSetFailedException + { + super( reporter ); + } + + public synchronized void writeTestOutput( byte[] buf, int off, int len, boolean stdout ) + { + // We can write immediately: no parallelism and a single class. + ( (ConsoleOutputReceiver) reporter ).writeTestOutput( buf, off, len, stdout ); + } + + protected SimpleReportEntry createReportEntry( Description description ) + { + return new SimpleReportEntry( description.getClassName(), description.getDisplayName()/* + * , (int) ( + * System.currentTimeMillis + * () - startTime ) + */); + } + + protected SimpleReportEntry createReportEntryForTestSet( Description description ) + { + return new SimpleReportEntry( description.getClassName(), description.getClassName() /* + * , (int) ( + * System.currentTimeMillis + * () - startTime ) + */); + } + + @Override + public void testStarted( Description description ) + throws Exception + { + finishLastTestSetIfNeccessary( description ); + super.testStarted( description ); + } + + private void finishLastTestSetIfNeccessary( Description description ) + { + if ( describesNewTestSet( description ) ) + { + currentTestSetDescription = description; + if ( lastFinishedDescription != null ) + { + reporter.testSetCompleted( createReportEntryForTestSet( lastFinishedDescription ) ); + lastFinishedDescription = null; + } + reporter.testSetStarting( createReportEntryForTestSet( 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() ); + } + + return false; + } + + return true; + } + + @Override + public void testFinished( Description description ) + throws Exception + { + super.testFinished( description ); + this.lastFinishedDescription = description; + } + + @Override + public void testIgnored( Description description ) + throws Exception + { + finishLastTestSetIfNeccessary( description ); + + super.testIgnored( description ); + this.lastFinishedDescription = description; + } + + @Override + public void testFailure( Failure failure ) + throws Exception + { + super.testFailure( failure ); + this.lastFinishedDescription = failure.getDescription(); + } + + @Override + public void testAssumptionFailure( Failure failure ) + { + super.testAssumptionFailure( failure ); + this.lastFinishedDescription = failure.getDescription(); + } + + @Override + public void testRunStarted( Description description ) + throws Exception + { + } + + @Override + public void testRunFinished( Result result ) + throws Exception + { + if ( lastFinishedDescription != null ) + { + reporter.testSetCompleted( createReportEntryForTestSet( 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 1abd7f74a4..5c14bfbd1b 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,37 +1,37 @@ -package org.apache.maven.surefire.junitcore; -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR 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.runners.model.RunnerScheduler; - -/** - * @author Kristian Rosenvold - */ -class SynchronousRunner - implements RunnerScheduler -{ - public void schedule( final Runnable childStatement ) - { - childStatement.run(); - } - - public void finished() - { - } -} +package org.apache.maven.surefire.junitcore; +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR 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.runners.model.RunnerScheduler; + +/** + * @author Kristian Rosenvold + */ +class SynchronousRunner + implements RunnerScheduler +{ + public void schedule( final Runnable childStatement ) + { + childStatement.run(); + } + + 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 3ade771e35..dc1ae27934 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 @@ -36,6 +36,8 @@ class TestMethod { private final ReportEntry description; + private final TestSet testSet; + private final long startTime; private long endTime; @@ -50,9 +52,10 @@ class TestMethod private volatile LogicalStream output; - public TestMethod( ReportEntry description ) + public TestMethod( ReportEntry description, TestSet testSet ) { this.description = description; + this.testSet = testSet; startTime = System.currentTimeMillis(); } @@ -86,7 +89,7 @@ private void setEndTime() public int getElapsed() { - return (int) ( endTime - startTime ); + return endTime > 0 ? (int) ( endTime - startTime ) : 0; } @@ -95,11 +98,12 @@ public void replay( RunListener reporter ) if ( ignored != null ) { - reporter.testSkipped( createReportEntry() ); + reporter.testSkipped( createReportEntry( ignored ) ); return; } - reporter.testStarting( createReportEntry() ); + ReportEntry descriptionReport = createReportEntry( description ); + reporter.testStarting( descriptionReport ); if ( output != null ) { output.writeDetails( ( (ConsoleOutputReceiver) reporter ) ); @@ -107,23 +111,22 @@ public void replay( RunListener reporter ) if ( testFailure != null ) { - reporter.testFailed( testFailure ); + reporter.testFailed( createReportEntry( testFailure ) ); } else if ( testError != null ) { - reporter.testError( testError ); + reporter.testError( createReportEntry( testError ) ); } else { - reporter.testSucceeded( createReportEntry() ); + reporter.testSucceeded( descriptionReport ); } } - private ReportEntry createReportEntry() + private ReportEntry createReportEntry( ReportEntry reportEntry ) { - int elapsed = (int) ( endTime - startTime ); - return new CategorizedReportEntry( description.getSourceName(), description.getName(), description.getGroup(), - description.getStackTraceWriter(), elapsed, description.getMessage() ); + return new CategorizedReportEntry( reportEntry.getSourceName(), reportEntry.getName(), reportEntry.getGroup(), + reportEntry.getStackTraceWriter(), getElapsed(), reportEntry.getMessage() ); } public void attachToThread() @@ -133,7 +136,7 @@ public void attachToThread() } - public static void detachFromCurrentThread() + public void detachFromCurrentThread() { TEST_METHOD.remove(); ConsoleOutputReceiverForCurrentThread.remove(); @@ -158,4 +161,8 @@ public void writeTestOutput( byte[] buf, int off, int len, boolean stdout ) getLogicalStream().write( stdout, buf, off, len ); } + public 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 33f36ed3f6..8b0283c2ba 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 @@ -72,11 +72,6 @@ public void replay( RunListener target ) try { - int elapsed = 0; - for ( TestMethod testMethod : testMethods ) - { - elapsed += testMethod.getElapsed(); - } ReportEntry report = createReportEntry( null ); target.testSetStarting( report ); @@ -86,8 +81,10 @@ public void replay( RunListener target ) beforeClass.writeDetails( ( (ConsoleOutputReceiver) target ) ); } + int elapsed = 0; for ( TestMethod testMethod : testMethods ) { + elapsed += testMethod.getElapsed(); testMethod.replay( target ); } @@ -105,10 +102,11 @@ public void replay( RunListener target ) } } - public TestMethod createTestMethod( ReportEntry description ) + public TestMethod createThreadAttachedTestMethod( ReportEntry description ) { - TestMethod testMethod = new TestMethod( description ); + TestMethod testMethod = new TestMethod( description, this ); addTestMethod( testMethod ); + testMethod.attachToThread(); return testMethod; } diff --git a/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/ConcurrentReporterManagerTest.java b/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/ConcurrentRunListenerTest.java similarity index 99% rename from surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/ConcurrentReporterManagerTest.java rename to surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/ConcurrentRunListenerTest.java index f978293443..f41554d99e 100644 --- a/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/ConcurrentReporterManagerTest.java +++ b/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/ConcurrentRunListenerTest.java @@ -41,7 +41,7 @@ /* * @author Kristian Rosenvold */ -public class ConcurrentReporterManagerTest +public class ConcurrentRunListenerTest extends TestCase { // Tests are in order of increasing complexity 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 c63b78a2ae..9d3d4c11ac 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 @@ -20,6 +20,7 @@ */ import java.util.HashMap; +import java.util.Iterator; import java.util.Map; import org.apache.maven.surefire.junit4.MockReporter; @@ -62,6 +63,27 @@ public void testFailedAssumption() 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); +// st1.addChild( Description.createSuiteDescription( STest1.class ) ); + testDescription.addChild( st1 ); + Description st2 = Description.createSuiteDescription( STest2.class); + // st2.addChild( Description.createSuiteDescription( STest2.class ) ); + testDescription.addChild( st2 ); + + Map classMethodCounts = new HashMap(); + 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() )); + + } + public void testTestClassNotLoadableFromJUnitClassLoader() throws Exception { 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 80146fd7b4..c805037a2c 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 @@ -58,8 +58,8 @@ public Result run( boolean parallelClasses, Class... classes ) final HashMap classMethodCounts = new HashMap(); RunListener reporter = - ConcurrentReporterManager.createInstance( classMethodCounts, reporterManagerFactory, parallelClasses, false, - new DefaultConsoleReporter( System.out ) ); + ConcurrentRunListener.createInstance( classMethodCounts, reporterManagerFactory, parallelClasses, false, + new DefaultConsoleReporter( System.out ) ); ConsoleOutputCapture.startCapture( (ConsoleOutputReceiver) reporter ); JUnitCoreRunListener runListener = new JUnitCoreRunListener( reporter, classMethodCounts ); 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 0992e9965f..190a280896 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 @@ -95,9 +95,9 @@ public void surefireIsConfused_ByMultipleIgnore_OnClassLevel() final Map testSetMap = new ConcurrentHashMap(); RunListener listener = - ConcurrentReporterManager.createInstance( testSetMap, reporterFactory, false, false, consoleLogger ); + ConcurrentRunListener.createInstance( testSetMap, reporterFactory, false, false, consoleLogger ); - TestsToRun testsToRun = new TestsToRun( Arrays.>asList( TestClassTest.class ) ); + TestsToRun testsToRun = new TestsToRun( Arrays.asList( TestClassTest.class ) ); org.junit.runner.notification.RunListener jUnit4RunListener = new JUnitCoreRunListener( listener, testSetMap ); 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 a1b549f58e..efb40b3cd2 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 @@ -23,6 +23,7 @@ import org.apache.maven.surefire.report.SimpleReportEntry; import junit.framework.TestCase; +import org.junit.runner.Description; /** * @author Kristian Rosenvold @@ -34,7 +35,8 @@ public void testTestFailure() throws Exception { ReportEntry reportEntry = new SimpleReportEntry( "a", "b" ); - TestMethod testMethod = new TestMethod( reportEntry ); + TestMethod testMethod = new TestMethod( reportEntry, new TestSet( + Description.createTestDescription( TestMethodTest.class, "testeEthodTest" ) ) ); testMethod.testFailure( reportEntry ); final int elapsed = testMethod.getElapsed(); assertTrue( elapsed >= 0 ); diff --git a/surefire-providers/surefire-testng-utils/pom.xml b/surefire-providers/surefire-testng-utils/pom.xml index 344a5f8afa..ef2ff76f8d 100644 --- a/surefire-providers/surefire-testng-utils/pom.xml +++ b/surefire-providers/surefire-testng-utils/pom.xml @@ -17,14 +17,13 @@ ~ specific language governing permissions and limitations ~ under the License. --> - + 4.0.0 org.apache.maven.surefire surefire-providers - 2.13-SNAPSHOT + 2.16-SNAPSHOT ../pom.xml diff --git a/surefire-providers/surefire-testng/pom.xml b/surefire-providers/surefire-testng/pom.xml index 86023a8446..cad5828166 100644 --- a/surefire-providers/surefire-testng/pom.xml +++ b/surefire-providers/surefire-testng/pom.xml @@ -17,14 +17,13 @@ ~ under the License. --> - + 4.0.0 org.apache.maven.surefire surefire-providers - 2.13-SNAPSHOT + 2.16-SNAPSHOT ../pom.xml @@ -33,17 +32,17 @@ SureFire TestNG Runner - - org.apache.maven - maven-artifact - 2.0 - junit junit 3.8.2 provided + + org.apache.maven.surefire + common-java5 + ${project.version} + @@ -55,15 +54,6 @@ - - maven-compiler-plugin - - false - 1.4 - 1.4 - 1.4 - - maven-surefire-plugin 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 78b2e64a17..b0d46311a7 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 @@ -29,8 +29,6 @@ import java.util.Properties; import java.util.SortedMap; import java.util.TreeMap; -import org.apache.maven.artifact.versioning.ArtifactVersion; -import org.apache.maven.artifact.versioning.DefaultArtifactVersion; import org.apache.maven.surefire.NonAbstractClassFilter; import org.apache.maven.surefire.report.ConsoleOutputCapture; import org.apache.maven.surefire.report.ConsoleOutputReceiver; @@ -40,7 +38,6 @@ import org.apache.maven.surefire.report.RunListener; import org.apache.maven.surefire.report.SimpleReportEntry; import org.apache.maven.surefire.testset.TestSetFailedException; -import org.apache.maven.surefire.util.LazyTestsToRun; import org.apache.maven.surefire.util.RunOrderCalculator; import org.apache.maven.surefire.util.ScanResult; import org.apache.maven.surefire.util.TestsToRun; @@ -54,7 +51,6 @@ public class TestNGDirectoryTestSuite implements TestNgTestSuite { - private final ArtifactVersion version; private final Map options; @@ -64,7 +60,7 @@ public class TestNGDirectoryTestSuite private final File reportsDirectory; - private SortedMap testSets; + private SortedMap testSets; private final ScanResult scanResult; @@ -74,8 +70,7 @@ public class TestNGDirectoryTestSuite private final Class junitTestClass; - public TestNGDirectoryTestSuite( String testSourceDirectory, String artifactVersion, Properties confOptions, - File reportsDirectory, String testMethodPattern, + public TestNGDirectoryTestSuite( String testSourceDirectory, Properties confOptions, File reportsDirectory, String testMethodPattern, RunOrderCalculator runOrderCalculator, ScanResult scanResult ) { @@ -86,7 +81,6 @@ public TestNGDirectoryTestSuite( String testSourceDirectory, String artifactVers this.testSourceDirectory = testSourceDirectory; this.reportsDirectory = reportsDirectory; this.scanResult = scanResult; - this.version = new DefaultArtifactVersion( artifactVersion ); this.testMethodPattern = testMethodPattern; this.junitTestClass = findJUnitTestClass(); this.junitOptions = createJUnitOptions(); @@ -96,17 +90,17 @@ public void execute( TestsToRun testsToRun, ReporterFactory reporterManagerFacto throws ReporterException, TestSetFailedException { - if ( testsToRun instanceof LazyTestsToRun ) + if ( !testsToRun.allowEagerReading() ) { executeLazy( testsToRun, reporterManagerFactory ); } - else if ( testsToRun.size() > 1 ) + else if ( testsToRun.containsAtLeast( 2 ) ) { executeMulti( testsToRun, reporterManagerFactory ); } - else if ( testsToRun.size() == 1 ) + else if ( testsToRun.containsAtLeast( 1 ) ) { - Class testClass = (Class) testsToRun.iterator().next(); + Class testClass = testsToRun.iterator().next(); executeSingleClass( reporterManagerFactory, testClass ); } } @@ -123,7 +117,7 @@ private void executeSingleClass( ReporterFactory reporterManagerFactory, Class t final Map optionsToUse = isJUnitTest( testClass ) ? junitOptions : options; - TestNGExecutor.run( new Class[]{ testClass }, testSourceDirectory, optionsToUse, version, reporter, this, + TestNGExecutor.run( new Class[]{ testClass }, testSourceDirectory, optionsToUse, reporter, this, reportsDirectory, testMethodPattern ); finishTestSuite( reporter, this ); @@ -133,9 +127,8 @@ public void executeLazy( TestsToRun testsToRun, ReporterFactory reporterFactory throws ReporterException, TestSetFailedException { - for ( Iterator testClassIt = testsToRun.iterator(); testClassIt.hasNext(); ) + for ( Class c : testsToRun ) { - Class c = (Class) testClassIt.next(); executeSingleClass( reporterFactory, c ); } } @@ -157,12 +150,10 @@ private Class findJUnitTestClass() public void executeMulti( TestsToRun testsToRun, ReporterFactory reporterFactory ) throws ReporterException, TestSetFailedException { - List testNgTestClasses = new ArrayList(); - List junitTestClasses = new ArrayList(); - Class[] allClasses = testsToRun.getLocatedClasses(); - for ( int i = 0; i < allClasses.length; i++ ) + List testNgTestClasses = new ArrayList(); + List junitTestClasses = new ArrayList(); + for ( Class c : testsToRun ) { - Class c = allClasses[i]; if ( isJUnitTest( c ) ) { junitTestClasses.add( c ); @@ -181,21 +172,20 @@ public void executeMulti( TestsToRun testsToRun, ReporterFactory reporterFactory junitReportsDirectory = new File( reportsDirectory, "testng-junit-results" ); } -// RunListener reporterManager = new SynchronizedReporterManager( reporterFactory.createReporter() ); RunListener reporterManager = reporterFactory.createReporter(); ConsoleOutputCapture.startCapture( (ConsoleOutputReceiver) reporterManager ); startTestSuite( reporterManager, this ); - Class[] testClasses = (Class[]) testNgTestClasses.toArray( new Class[testNgTestClasses.size()] ); + Class[] testClasses = testNgTestClasses.toArray( new Class[testNgTestClasses.size()] ); - TestNGExecutor.run( testClasses, this.testSourceDirectory, options, version, reporterManager, this, + TestNGExecutor.run( testClasses, this.testSourceDirectory, options, reporterManager, this, testNgReportsDirectory, testMethodPattern ); if ( junitTestClasses.size() > 0 ) { - testClasses = (Class[]) junitTestClasses.toArray( new Class[junitTestClasses.size()] ); + testClasses = junitTestClasses.toArray( new Class[junitTestClasses.size()] ); - TestNGExecutor.run( testClasses, testSourceDirectory, junitOptions, version, reporterManager, this, + TestNGExecutor.run( testClasses, testSourceDirectory, junitOptions, reporterManager, this, junitReportsDirectory, testMethodPattern ); } @@ -222,7 +212,7 @@ public void execute( String testSetName, ReporterFactory reporterManagerFactory { throw new IllegalStateException( "You must call locateTestSets before calling execute" ); } - TestNGTestSet testSet = (TestNGTestSet) testSets.get( testSetName ); + TestNGTestSet testSet = testSets.get( testSetName ); if ( testSet == null ) { @@ -234,8 +224,7 @@ public void execute( String testSetName, ReporterFactory reporterManagerFactory startTestSuite( reporter, this ); - TestNGExecutor.run( new Class[]{ testSet.getTestClass() }, this.testSourceDirectory, this.options, this.version, - reporter, this, reportsDirectory, testMethodPattern ); + TestNGExecutor.run( new Class[]{ testSet.getTestClass() }, this.testSourceDirectory, this.options, reporter, this, reportsDirectory, testMethodPattern ); finishTestSuite( reporter, this ); } @@ -298,16 +287,14 @@ public Map locateTestSets( ClassLoader classLoader ) { throw new IllegalStateException( "You can't call locateTestSets twice" ); } - testSets = new TreeMap(); + testSets = new TreeMap(); final TestsToRun scanned = scanResult.applyFilter( new NonAbstractClassFilter(), classLoader ); final TestsToRun testsToRun = runOrderCalculator.orderTestClasses( scanned ); - Class[] locatedClasses = testsToRun.getLocatedClasses(); - for ( int i = 0; i < locatedClasses.length; i++ ) + for ( Class testClass : testsToRun ) { - Class testClass = locatedClasses[i]; TestNGTestSet testSet = new TestNGTestSet( testClass ); if ( testSets.containsKey( testSet.getName() ) ) 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 42f2f424d0..d4a6ac8e47 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 @@ -19,28 +19,21 @@ * under the License. */ -import java.io.File; -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.List; -import java.util.Map; -import org.apache.maven.artifact.versioning.ArtifactVersion; -import org.apache.maven.artifact.versioning.InvalidVersionSpecificationException; -import org.apache.maven.artifact.versioning.VersionRange; import org.apache.maven.surefire.booter.ProviderParameterNames; import org.apache.maven.surefire.report.RunListener; import org.apache.maven.surefire.testng.conf.Configurator; -import org.apache.maven.surefire.testng.conf.TestNG4751Configurator; -import org.apache.maven.surefire.testng.conf.TestNG52Configurator; -import org.apache.maven.surefire.testng.conf.TestNG652Configurator; -import org.apache.maven.surefire.testng.conf.TestNGMapConfigurator; import org.apache.maven.surefire.testset.TestSetFailedException; import org.apache.maven.surefire.util.NestedRuntimeException; import org.apache.maven.surefire.util.internal.StringUtils; - import org.testng.TestNG; +import java.io.File; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.List; +import java.util.Map; + /** * Contains utility methods for executing TestNG. * @@ -56,9 +49,8 @@ private TestNGExecutor() // noop } - public static void run( Class[] testClasses, String testSourceDirectory, Map options, ArtifactVersion version, - RunListener reportManager, TestNgTestSuite suite, File reportsDirectory, - final String methodNamePattern ) + public static void run( Class[] testClasses, String testSourceDirectory, Map options, RunListener reportManager, + TestNgTestSuite suite, File reportsDirectory, final String methodNamePattern ) throws TestSetFailedException { TestNG testng = new TestNG( true ); @@ -69,8 +61,8 @@ public static void run( Class[] testClasses, String testSourceDirectory, Map opt applyMethodNameFiltering( testng, methodNamePattern ); } - Configurator configurator = getConfigurator( version ); - System.out.println( "Configuring TestNG with: " + configurator ); + Configurator configurator = getConfigurator( (String) options.get("testng.configurator" ) ); + System.out.println( "Configuring TestNG with: " + configurator.getClass().getSimpleName() ); configurator.configure( testng, options ); postConfigure( testng, testSourceDirectory, reportManager, suite, reportsDirectory ); testng.setTestClasses( testClasses ); @@ -89,7 +81,7 @@ private static void applyMethodNameFiltering( TestNG testng, String methodNamePa Class clazz = Class.forName( clazzName ); Method method = clazz.getMethod( "setMethodName", new Class[]{ String.class } ); - method.invoke( null, new Object[]{ methodNamePattern } ); + method.invoke( null, methodNamePattern ); } catch ( ClassNotFoundException e ) { @@ -138,7 +130,7 @@ private static void applyGroupMatching( TestNG testng, Map options ) // HORRIBLE hack, but TNG doesn't allow us to setup a method selector instance directly. Method method = clazz.getMethod( "setGroups", new Class[]{ String.class, String.class } ); - method.invoke( null, new Object[]{ groups, excludedGroups } ); + method.invoke( null, groups, excludedGroups ); } catch ( ClassNotFoundException e ) { @@ -166,49 +158,35 @@ private static void applyGroupMatching( TestNG testng, Map options ) } } - public static void run( List suiteFiles, String testSourceDirectory, Map options, ArtifactVersion version, - RunListener reportManager, TestNgTestSuite suite, File reportsDirectory ) + public static void run( List suiteFiles, String testSourceDirectory, Map options, RunListener reportManager, + TestNgTestSuite suite, File reportsDirectory ) throws TestSetFailedException { TestNG testng = new TestNG( true ); - Configurator configurator = getConfigurator( version ); + Configurator configurator = getConfigurator( (String) options.get("testng.configurator" ) ); configurator.configure( testng, options ); postConfigure( testng, testSourceDirectory, reportManager, suite, reportsDirectory ); testng.setTestSuites( suiteFiles ); testng.run(); } - private static Configurator getConfigurator( ArtifactVersion version ) - throws TestSetFailedException + private static Configurator getConfigurator( String className ) { try { - VersionRange range = VersionRange.createFromVersionSpec( "[4.7,5.1]" ); - if ( range.containsVersion( version ) ) - { - return new TestNG4751Configurator(); - } - range = VersionRange.createFromVersionSpec( "[5.2]" ); - if ( range.containsVersion( version ) ) - { - return new TestNG52Configurator(); - } - range = VersionRange.createFromVersionSpec( "[5.3,6.4]" ); - if ( range.containsVersion( version ) ) - { - return new TestNGMapConfigurator(); - } - range = VersionRange.createFromVersionSpec( "[6.5,)" ); - if ( range.containsVersion( version ) ) - { - return new TestNG652Configurator(); - } - - throw new TestSetFailedException( "Unknown TestNG version " + version ); + return (Configurator) Class.forName( className ).newInstance(); + } + catch ( InstantiationException e ) + { + throw new RuntimeException( e ); } - catch ( InvalidVersionSpecificationException invsex ) + catch ( IllegalAccessException e ) + { + throw new RuntimeException( e ); + } + catch ( ClassNotFoundException e ) { - throw new TestSetFailedException( "Bug in plugin. Please report it with the attached stacktrace", invsex ); + throw new RuntimeException( e ); } } @@ -243,7 +221,7 @@ private static TestNGReporter createTestNGReporter( RunListener reportManager, T try { Constructor ctor = c.getConstructor( new Class[]{ RunListener.class, TestNgTestSuite.class } ); - return (TestNGReporter) ctor.newInstance( new Object[]{ reportManager, suite } ); + return (TestNGReporter) ctor.newInstance( reportManager, suite ); } catch ( Exception 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 a24e68331a..ff3eaaca78 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 @@ -27,7 +27,6 @@ import org.apache.maven.surefire.report.ReporterException; import org.apache.maven.surefire.report.ReporterFactory; import org.apache.maven.surefire.suite.RunResult; -import org.apache.maven.surefire.testset.TestArtifactInfo; import org.apache.maven.surefire.testset.TestRequest; import org.apache.maven.surefire.testset.TestSetFailedException; import org.apache.maven.surefire.util.NestedRuntimeException; @@ -44,8 +43,6 @@ public class TestNGProvider { private final Properties providerProperties; - private final TestArtifactInfo testArtifactInfo; - private final ReporterConfiguration reporterConfiguration; private final ClassLoader testClassLoader; @@ -67,7 +64,6 @@ public TestNGProvider( ProviderParameters booterParameters ) this.runOrderCalculator = booterParameters.getRunOrderCalculator(); this.providerProperties = booterParameters.getProviderProperties(); this.testRequest = booterParameters.getTestRequest(); - testArtifactInfo = booterParameters.getTestArtifactInfo(); reporterConfiguration = booterParameters.getReporterConfiguration(); this.scanResult = booterParameters.getScanResult(); } @@ -130,8 +126,7 @@ boolean isTestNGXmlTestSuite( TestRequest testSuiteDefinition ) private TestNGDirectoryTestSuite getDirectorySuite() { - return new TestNGDirectoryTestSuite( testRequest.getTestSourceDirectory().toString(), - testArtifactInfo.getVersion(), providerProperties, + return new TestNGDirectoryTestSuite( testRequest.getTestSourceDirectory().toString(), providerProperties, reporterConfiguration.getReportsDirectory(), testRequest.getRequestedTestMethod(), runOrderCalculator, scanResult ); } @@ -139,7 +134,7 @@ private TestNGDirectoryTestSuite getDirectorySuite() private TestNGXmlTestSuite getXmlSuite() { return new TestNGXmlTestSuite( testRequest.getSuiteXmlFiles(), testRequest.getTestSourceDirectory().toString(), - testArtifactInfo.getVersion(), providerProperties, + providerProperties, reporterConfiguration.getReportsDirectory() ); } 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 2e979d3064..cf3df4bcb3 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 @@ -163,7 +163,7 @@ private static String groupString( String[] groups, String defaultValue ) String retVal; if ( groups != null && groups.length > 0 ) { - StringBuffer str = new StringBuffer(); + StringBuilder str = new StringBuilder(); for ( int i = 0; i < groups.length; i++ ) { str.append( groups[i] ); 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 527b21a343..8448a2d6bf 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 @@ -22,12 +22,9 @@ import java.io.File; import java.util.ArrayList; import java.util.HashMap; -import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; -import org.apache.maven.artifact.versioning.ArtifactVersion; -import org.apache.maven.artifact.versioning.DefaultArtifactVersion; import org.apache.maven.surefire.report.ConsoleOutputCapture; import org.apache.maven.surefire.report.ConsoleOutputReceiver; import org.apache.maven.surefire.report.ReporterException; @@ -46,32 +43,27 @@ public class TestNGXmlTestSuite { private final List suiteFiles; - private List suiteFilePaths; + private List suiteFilePaths; private final String testSourceDirectory; - private final ArtifactVersion version; - private final Map options; private final File reportsDirectory; // Not really used - private Map testSets; + private Map testSets; /** * Creates a testng testset to be configured by the specified * xml file(s). The XML files are suite definitions files according to TestNG DTD. */ - public TestNGXmlTestSuite( List suiteFiles, String testSourceDirectory, String artifactVersion, - Properties confOptions, File reportsDirectory ) + public TestNGXmlTestSuite( List suiteFiles, String testSourceDirectory, Properties confOptions, File reportsDirectory ) { this.suiteFiles = suiteFiles; this.options = confOptions; - this.version = new DefaultArtifactVersion( artifactVersion ); - this.testSourceDirectory = testSourceDirectory; this.reportsDirectory = reportsDirectory; @@ -89,7 +81,7 @@ public void execute( ReporterFactory reporterManagerFactory ) ConsoleOutputCapture.startCapture( (ConsoleOutputReceiver) reporter ); TestNGDirectoryTestSuite.startTestSuite( reporter, this ); - TestNGExecutor.run( this.suiteFilePaths, this.testSourceDirectory, this.options, this.version, reporter, this, + TestNGExecutor.run( this.suiteFilePaths, this.testSourceDirectory, this.options, reporter, this, reportsDirectory ); TestNGDirectoryTestSuite.finishTestSuite( reporter, this ); } @@ -113,12 +105,12 @@ public Map locateTestSets( ClassLoader classLoader ) throw new IllegalStateException( "No suite files were specified" ); } - this.testSets = new HashMap(); - this.suiteFilePaths = new ArrayList(); + this.testSets = new HashMap(); + this.suiteFilePaths = new ArrayList(); - for ( Iterator i = suiteFiles.iterator(); i.hasNext(); ) + for ( Object suiteFile : suiteFiles ) { - File file = (File) i.next(); + File file = (File) suiteFile; if ( !file.exists() || !file.isFile() ) { throw new TestSetFailedException( "Suite file " + file + " is not a valid file" ); diff --git a/surefire-report-parser/pom.xml b/surefire-report-parser/pom.xml new file mode 100644 index 0000000000..326f9452d1 --- /dev/null +++ b/surefire-report-parser/pom.xml @@ -0,0 +1,94 @@ + + + + + 4.0.0 + + + org.apache.maven.surefire + surefire + 2.16-SNAPSHOT + ../pom.xml + + + surefire-report-parser + + Surefire Report Parser + Parses report output files from surefire + + + 2.0.9 + + + + + org.apache.maven.shared + maven-shared-utils + + + org.apache.maven.reporting + maven-reporting-api + + + + + + maven-surefire-plugin + + true + + + + org.apache.maven.surefire + surefire-shadefire + ${shadedVersion} + + + + + + org.apache.maven.plugins + maven-shade-plugin + + + package + + shade + + + true + + + org.apache.maven.shared:maven-shared-utils + + + + + org.apache.maven.shared + org.apache.maven.surefire.shade.org.apache.maven.shared + + + + + + + + + diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/fixture/ReportTestCase.java b/surefire-report-parser/src/main/java/org/apache/maven/plugins/surefire/report/ReportTestCase.java similarity index 97% rename from surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/fixture/ReportTestCase.java rename to surefire-report-parser/src/main/java/org/apache/maven/plugins/surefire/report/ReportTestCase.java index ec11e0edd8..3203f498ed 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/fixture/ReportTestCase.java +++ b/surefire-report-parser/src/main/java/org/apache/maven/plugins/surefire/report/ReportTestCase.java @@ -1,4 +1,4 @@ -package org.apache.maven.surefire.its.fixture; +package org.apache.maven.plugins.surefire.report; /* * Licensed to the Apache Software Foundation (ASF) under one diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/fixture/ReportTestSuite.java b/surefire-report-parser/src/main/java/org/apache/maven/plugins/surefire/report/ReportTestSuite.java similarity index 98% rename from surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/fixture/ReportTestSuite.java rename to surefire-report-parser/src/main/java/org/apache/maven/plugins/surefire/report/ReportTestSuite.java index 6903eda04f..2bd65136f1 100644 --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/fixture/ReportTestSuite.java +++ b/surefire-report-parser/src/main/java/org/apache/maven/plugins/surefire/report/ReportTestSuite.java @@ -1,4 +1,4 @@ -package org.apache.maven.surefire.its.fixture; +package org.apache.maven.plugins.surefire.report; /* * Licensed to the Apache Software Foundation (ASF) under one 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 new file mode 100644 index 0000000000..feba2458b5 --- /dev/null +++ b/surefire-report-parser/src/main/java/org/apache/maven/plugins/surefire/report/SurefireReportParser.java @@ -0,0 +1,274 @@ +package org.apache.maven.plugins.surefire.report; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES 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.IOException; +import java.text.NumberFormat; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import org.apache.maven.reporting.MavenReportException; +import org.apache.maven.shared.utils.StringUtils; +import org.apache.maven.shared.utils.io.DirectoryScanner; + +import javax.xml.parsers.ParserConfigurationException; + +import org.xml.sax.SAXException; + +/** + * + */ +public 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"; + + private NumberFormat numberFormat = NumberFormat.getInstance(); + + private List reportsDirectories; + + private final List testSuites = new ArrayList(); + + private static final int PCENT = 100; + + public SurefireReportParser() + { + } + + public SurefireReportParser( List reportsDirectoriesFiles, Locale locale ) + { + this.reportsDirectories = reportsDirectoriesFiles; + + setLocale( locale ); + } + + public List parseXMLReportFiles() + throws MavenReportException + { + List xmlReportFileList = new ArrayList(); + for ( File reportsDirectory : reportsDirectories ) + { + if ( !reportsDirectory.exists() ) + { + continue; + } + String[] xmlReportFiles = getIncludedFiles( reportsDirectory, INCLUDES, EXCLUDES ); + for ( String xmlReportFile : xmlReportFiles ) + { + File xmlReport = new File( reportsDirectory, xmlReportFile ); + xmlReportFileList.add( xmlReport ); + } + } + TestSuiteXmlParser parser = new TestSuiteXmlParser(); + for ( File aXmlReportFileList : xmlReportFileList ) + { + Collection suites; + + try + { + suites = 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 ); + } + + testSuites.addAll( suites ); + } + + return testSuites; + } + + protected String parseTestSuiteName( String lineString ) + { + return lineString.substring( lineString.lastIndexOf( "." ) + 1, lineString.length() ); + } + + protected String parseTestSuitePackageName( String lineString ) + { + return lineString.substring( lineString.indexOf( ":" ) + 2, lineString.lastIndexOf( "." ) ); + } + + protected String parseTestCaseName( String lineString ) + { + return lineString.substring( 0, lineString.indexOf( "(" ) ); + } + + public Map getSummary( List suites ) + { + Map totalSummary = new HashMap(); + + int totalNumberOfTests = 0; + + int totalNumberOfErrors = 0; + + int totalNumberOfFailures = 0; + + int totalNumberOfSkipped = 0; + + float totalElapsedTime = 0.0f; + + for ( ReportTestSuite suite : suites ) + { + totalNumberOfTests += suite.getNumberOfTests(); + + totalNumberOfErrors += suite.getNumberOfErrors(); + + totalNumberOfFailures += suite.getNumberOfFailures(); + + totalNumberOfSkipped += suite.getNumberOfSkipped(); + + totalElapsedTime += suite.getTimeElapsed(); + } + + String totalPercentage = + computePercentage( totalNumberOfTests, totalNumberOfErrors, totalNumberOfFailures, totalNumberOfSkipped ); + + totalSummary.put( "totalTests", Integer.toString( totalNumberOfTests ) ); + + totalSummary.put( "totalErrors", Integer.toString( totalNumberOfErrors ) ); + + totalSummary.put( "totalFailures", Integer.toString( totalNumberOfFailures ) ); + + totalSummary.put( "totalSkipped", Integer.toString( totalNumberOfSkipped ) ); + + totalSummary.put( "totalElapsedTime", numberFormat.format( totalElapsedTime ) ); + + totalSummary.put( "totalPercentage", totalPercentage ); + + return totalSummary; + } + + public void setReportsDirectory( File reportsDirectory ) + { + this.reportsDirectories = Collections.singletonList( reportsDirectory ); + } + + public final void setLocale( Locale locale ) + { + numberFormat = NumberFormat.getInstance( locale ); + } + + public NumberFormat getNumberFormat() + { + return this.numberFormat; + } + + public Map> getSuitesGroupByPackage( List testSuitesList ) + { + Map> suitePackage = new HashMap>(); + + for ( ReportTestSuite suite : testSuitesList ) + { + List suiteList = new ArrayList(); + + if ( suitePackage.get( suite.getPackageName() ) != null ) + { + suiteList = suitePackage.get( suite.getPackageName() ); + } + + suiteList.add( suite ); + + suitePackage.put( suite.getPackageName(), suiteList ); + } + + return suitePackage; + } + + public String computePercentage( int tests, int errors, int failures, int skipped ) + { + float percentage; + if ( tests == 0 ) + { + percentage = 0; + } + else + { + percentage = ( (float) ( tests - errors - failures - skipped ) / (float) tests ) * PCENT; + } + + return numberFormat.format( percentage ); + } + + public List getFailureDetails( List testSuitesList ) + { + List failureDetailList = new ArrayList(); + + for ( ReportTestSuite suite : testSuitesList ) + { + List testCaseList = suite.getTestCases(); + + if ( testCaseList != null ) + { + for ( ReportTestCase tCase : testCaseList ) + { + + if ( tCase.getFailure() != null ) + { + failureDetailList.add( tCase ); + } + } + } + } + + return failureDetailList; + } + + /** + * Returns {@code true} if the specified directory contains at least one report file. + * + * @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; + } + + private static String[] getIncludedFiles( File directory, String includes, String excludes ) + { + DirectoryScanner scanner = new DirectoryScanner(); + + scanner.setBasedir( directory ); + + scanner.setIncludes( StringUtils.split( includes, "," ) ); + + scanner.setExcludes( StringUtils.split( excludes, "," ) ); + + scanner.scan(); + + return scanner.getIncludedFiles(); + } +} diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/fixture/TestSuiteXmlParser.java b/surefire-report-parser/src/main/java/org/apache/maven/plugins/surefire/report/TestSuiteXmlParser.java old mode 100755 new mode 100644 similarity index 85% rename from surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/fixture/TestSuiteXmlParser.java rename to surefire-report-parser/src/main/java/org/apache/maven/plugins/surefire/report/TestSuiteXmlParser.java index 2cb3634daa..3f600b291a --- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/fixture/TestSuiteXmlParser.java +++ b/surefire-report-parser/src/main/java/org/apache/maven/plugins/surefire/report/TestSuiteXmlParser.java @@ -1,4 +1,4 @@ -package org.apache.maven.surefire.its.fixture; +package org.apache.maven.plugins.surefire.report; /* * Licensed to the Apache Software Foundation (ASF) under one @@ -20,7 +20,10 @@ */ import java.io.File; +import java.io.FileInputStream; import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; import java.text.NumberFormat; import java.text.ParseException; import java.util.ArrayList; @@ -36,6 +39,7 @@ import javax.xml.parsers.SAXParserFactory; import org.xml.sax.Attributes; +import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; @@ -51,7 +55,7 @@ public class TestSuiteXmlParser private Map classesToSuites; - private final NumberFormat numberFormat = NumberFormat.getInstance( Locale.US ); + private final NumberFormat numberFormat = NumberFormat.getInstance( Locale.ENGLISH ); /** * @noinspection StringBufferField @@ -60,16 +64,41 @@ public class TestSuiteXmlParser private ReportTestCase testCase; + private boolean valid; + public Collection parse( String xmlPath ) throws ParserConfigurationException, SAXException, IOException { + + File f = new File( xmlPath ); + + FileInputStream fileInputStream = new FileInputStream( f ); + + InputStreamReader inputStreamReader = new InputStreamReader( fileInputStream, "UTF-8" ); + + try + { + return parse( inputStreamReader ); + } + finally + { + inputStreamReader.close(); + fileInputStream.close(); + } + } + + public Collection parse( InputStreamReader stream ) + throws ParserConfigurationException, SAXException, IOException + { SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser saxParser = factory.newSAXParser(); + valid = true; + classesToSuites = new HashMap(); - saxParser.parse( new File( xmlPath ), this ); + saxParser.parse( new InputSource( stream ), this ); if ( currentSuite != defaultSuite ) { // omit the defaultSuite if it's empty and there are alternatives @@ -88,6 +117,10 @@ public Collection parse( String xmlPath ) public void startElement( String uri, String localName, String qName, Attributes attributes ) throws SAXException { + if ( !valid ) + { + return; + } try { if ( "testsuite".equals( qName ) ) @@ -134,7 +167,7 @@ else if ( "testcase".equals( qName ) ) // if the testcase declares its own classname, it may need to belong to its own suite if ( fullClassName != null ) { - currentSuite = (ReportTestSuite) classesToSuites.get( fullClassName ); + currentSuite = classesToSuites.get( fullClassName ); if ( currentSuite == null ) { currentSuite = new ReportTestSuite(); @@ -175,9 +208,14 @@ else if ( "error".equals( qName ) ) } else if ( "skipped".equals( qName ) ) { - testCase.addFailure( "skipped", "skipped" ); // TODO extract real reasons + final String message = attributes.getValue( "message" ); + testCase.addFailure( message != null ? message : "skipped", "skipped" ); currentSuite.setNumberOfSkipped( 1 + currentSuite.getNumberOfSkipped() ); } + else if ( "failsafe-summary".equals( qName ) ) + { + valid = false; + } } catch ( ParseException e ) { @@ -228,6 +266,10 @@ else if ( "time".equals( qName ) ) public void characters( char[] ch, int start, int length ) throws SAXException { + if ( !valid ) + { + return; + } String s = new String( ch, start, length ); if ( !"".equals( s.trim() ) ) @@ -252,7 +294,7 @@ private List parseCause( String detail, String compareTo ) { String lineString = stringTokenizer.nextToken().trim(); parsedDetail.add( lineString ); - if ( lineString.indexOf( compareTo ) >= 0 ) + if ( lineString.contains( compareTo ) ) { break; } @@ -261,4 +303,8 @@ private List parseCause( String detail, String compareTo ) return parsedDetail; } + public boolean isValid() + { + return valid; + } } 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 new file mode 100644 index 0000000000..ecf529a77d --- /dev/null +++ b/surefire-report-parser/src/test/java/org/apache/maven/plugins/surefire/report/ReportTestCaseTest.java @@ -0,0 +1,82 @@ +package org.apache.maven.plugins.surefire.report; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES 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; + +/** + * @author Jontri + */ +public class ReportTestCaseTest + extends TestCase +{ + private ReportTestCase tCase; + + /** + * {@inheritDoc} + */ + protected void setUp() + throws Exception + { + super.setUp(); + + tCase = new ReportTestCase(); + } + + /** + * {@inheritDoc} + */ + protected void tearDown() + throws Exception + { + super.tearDown(); + + tCase = null; + } + + public void testSetName() + { + tCase.setName( "Test Case Name" ); + + assertEquals( "Test Case Name", tCase.getName() ); + } + + public void testSetTime() + { + tCase.setTime( .06f ); + + assertEquals( .06f, tCase.getTime(), 0.0 ); + } + + public void testSetFailure() + { + tCase.addFailure( "messageVal", "typeVal" ); + + assertEquals( "messageVal", tCase.getFailure().get( "message" ) ); + assertEquals( "typeVal", tCase.getFailure().get( "type" ) ); + } + + public void testSetFullName() + { + tCase.setFullName( "Test Case Full Name" ); + + 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 new file mode 100644 index 0000000000..63e6eaca8f --- /dev/null +++ b/surefire-report-parser/src/test/java/org/apache/maven/plugins/surefire/report/ReportTestSuiteTest.java @@ -0,0 +1,118 @@ +package org.apache.maven.plugins.surefire.report; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES 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; + +import junit.framework.TestCase; + +/** + * + */ +public class ReportTestSuiteTest + extends TestCase +{ + private ReportTestSuite tSuite; + + /** + * {@inheritDoc} + */ + protected void setUp() + throws Exception + { + super.setUp(); + + tSuite = new ReportTestSuite(); + } + + /** + * {@inheritDoc} + */ + protected void tearDown() + throws Exception + { + super.tearDown(); + + tSuite = null; + } + + public void testSetTestCases() + { + ReportTestCase tCase = new ReportTestCase(); + + List tCaseList = new ArrayList(); + + tCaseList.add( tCase ); + + tSuite.setTestCases( tCaseList ); + + assertEquals( tCase, tSuite.getTestCases().get( 0 ) ); + } + + public void testSetNumberdOfErrors() + { + tSuite.setNumberOfErrors( 9 ); + + assertEquals( 9, tSuite.getNumberOfErrors() ); + } + + public void testSetNumberOfFailures() + { + tSuite.setNumberOfFailures( 10 ); + + assertEquals( 10, tSuite.getNumberOfFailures() ); + } + + public void testSetNumberOfSkipped() + { + tSuite.setNumberOfSkipped( 5 ); + + assertEquals( 5, tSuite.getNumberOfSkipped() ); + } + + public void testSetNumberOfTests() + { + tSuite.setNumberOfTests( 11 ); + + assertEquals( 11, tSuite.getNumberOfTests() ); + } + + public void testSetName() + { + tSuite.setName( "Suite Name" ); + + assertEquals( "Suite Name", tSuite.getName() ); + } + + public void testSetPackageName() + { + tSuite.setPackageName( "Suite Package Name" ); + + assertEquals( "Suite Package Name", tSuite.getPackageName() ); + } + + public void testSetTimeElapsed() + { + tSuite.setTimeElapsed( .06f ); + + 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 new file mode 100644 index 0000000000..2bd5248962 --- /dev/null +++ b/surefire-report-parser/src/test/java/org/apache/maven/plugins/surefire/report/SurefireReportParserTest.java @@ -0,0 +1,242 @@ +package org.apache.maven.plugins.surefire.report; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES 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.UnsupportedEncodingException; +import java.net.URL; +import java.net.URLDecoder; +import java.text.NumberFormat; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import org.apache.maven.reporting.MavenReportException; + +import junit.framework.TestCase; + +/** + * + */ +public class SurefireReportParserTest + extends TestCase +{ + private SurefireReportParser report; + + /** + * {@inheritDoc} + */ + protected void setUp() + throws Exception + { + super.setUp(); + + report = new SurefireReportParser(); + + report.setLocale( Locale.ENGLISH ); + } + + /** + * {@inheritDoc} + */ + protected void tearDown() + throws Exception + { + super.tearDown(); + + report = null; + } + + public void testParseXMLReportFiles() + throws MavenReportException, UnsupportedEncodingException + { + report.setReportsDirectory( getTestDir( "/test-reports" ) ); + + List suites = report.parseXMLReportFiles(); + + assertEquals( 8, suites.size() ); + + for ( ReportTestSuite suite : suites ) + { + assertNotNull( suite.getName() + " was not correctly parsed", suite.getTestCases() ); + assertNotNull( suite.getName() ); + assertNotNull( suite.getPackageName() ); + } + } + + private File getTestDir( String path ) + throws UnsupportedEncodingException + { + URL resource = getClass().getResource( path ); + // URLDecoder.decode necessary for JDK 1.5+, where spaces are escaped to %20 + return new File( URLDecoder.decode( resource.getPath(), "UTF-8" ) ).getAbsoluteFile(); + } + + public void testParseTestSuiteName() + { + assertEquals( "CircleTest", report.parseTestSuiteName( "Battery: com.shape.CircleTest" ) ); + } + + public void testParseTestSuitePackageName() + { + assertEquals( "com.shape", report.parseTestSuitePackageName( "Battery: com.shape.CircleTest" ) ); + } + + public void testParseTestCaseName() + { + assertEquals( "testCase", report.parseTestCaseName( "testCase(com.shape.CircleTest)" ) ); + } + + public void testGetSummary() + throws Exception + { + ReportTestSuite tSuite1 = new ReportTestSuite(); + + ReportTestSuite tSuite2 = new ReportTestSuite(); + + tSuite1.setNumberOfErrors( 10 ); + + tSuite1.setNumberOfFailures( 20 ); + + tSuite1.setNumberOfSkipped( 2 ); + + tSuite1.setTimeElapsed( 1.0f ); + + tSuite1.setNumberOfTests( 100 ); + + tSuite2.setNumberOfErrors( 10 ); + + tSuite2.setNumberOfFailures( 20 ); + + tSuite2.setNumberOfSkipped( 2 ); + + tSuite2.setTimeElapsed( 1.0f ); + + tSuite2.setNumberOfTests( 100 ); + + List suiteList = new ArrayList(); + + suiteList.add( tSuite1 ); + + suiteList.add( tSuite2 ); + + Map testMap = report.getSummary( suiteList ); + + assertEquals( 20, Integer.parseInt( testMap.get( "totalErrors" ).toString() ) ); + + assertEquals( 40, Integer.parseInt( testMap.get( "totalFailures" ).toString() ) ); + + assertEquals( 200, Integer.parseInt( testMap.get( "totalTests" ).toString() ) ); + + assertEquals( 4, Integer.parseInt( testMap.get( "totalSkipped" ).toString() ) ); + + NumberFormat numberFormat = report.getNumberFormat(); + + assertEquals( 2.0f, numberFormat.parse( testMap.get( "totalElapsedTime" ).toString() ).floatValue(), 0.0f ); + + assertEquals( 68.00f, numberFormat.parse( (String) testMap.get( "totalPercentage" ) ).floatValue(), 0 ); + } + + public void testGetSuitesGroupByPackage() + { + ReportTestSuite tSuite1 = new ReportTestSuite(); + + ReportTestSuite tSuite2 = new ReportTestSuite(); + + ReportTestSuite tSuite3 = new ReportTestSuite(); + + tSuite1.setPackageName( "Package1" ); + + tSuite2.setPackageName( "Package1" ); + + tSuite3.setPackageName( "Package2" ); + + List suiteList = new ArrayList(); + + suiteList.add( tSuite1 ); + + suiteList.add( tSuite2 ); + + suiteList.add( tSuite3 ); + + Map> groupMap = report.getSuitesGroupByPackage( suiteList ); + + assertEquals( 2, groupMap.size() ); + + assertEquals( tSuite1, groupMap.get( "Package1" ).get( 0 ) ); + + assertEquals( tSuite2, groupMap.get( "Package1" ).get( 1 ) ); + + assertEquals( tSuite3, groupMap.get( "Package2" ).get( 0 ) ); + } + + public void testComputePercentage() + throws Exception + { + NumberFormat numberFormat = report.getNumberFormat(); + + assertEquals( 70.00f, numberFormat.parse( report.computePercentage( 100, 20, 10, 0 ) ).floatValue(), 0 ); + } + + public void testGetFailureDetails() + { + ReportTestSuite tSuite1 = new ReportTestSuite(); + + ReportTestSuite tSuite2 = new ReportTestSuite(); + + ReportTestCase tCase1 = new ReportTestCase(); + + ReportTestCase tCase2 = new ReportTestCase(); + + ReportTestCase tCase3 = new ReportTestCase(); + + tCase1.addFailure( null, null ); + + tCase3.addFailure( null, null ); + + List tCaseList = new ArrayList(); + + List tCaseList2 = new ArrayList(); + + tCaseList.add( tCase1 ); + + tCaseList.add( tCase2 ); + + tCaseList2.add( tCase3 ); + + tSuite1.setTestCases( tCaseList ); + + tSuite2.setTestCases( tCaseList2 ); + + List suiteList = new ArrayList(); + + suiteList.add( tSuite1 ); + + suiteList.add( tSuite2 ); + + List failList = report.getFailureDetails( suiteList ); + + assertEquals( 2, failList.size() ); + + assertEquals( tCase1, failList.get( 0 ) ); + + assertEquals( tCase3, failList.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 new file mode 100644 index 0000000000..beaf1b2dcc --- /dev/null +++ b/surefire-report-parser/src/test/java/org/apache/maven/plugins/surefire/report/TestSuiteXmlParserTest.java @@ -0,0 +1,136 @@ +package org.apache.maven.plugins.surefire.report; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES 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.ByteArrayInputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.Collection; + +import javax.xml.parsers.ParserConfigurationException; + +import junit.framework.TestCase; +import org.xml.sax.SAXException; + +/** + * @author Kristian Rosenvold + */ +public class TestSuiteXmlParserTest + extends TestCase +{ + public void testParse() + throws Exception + { + TestSuiteXmlParser testSuiteXmlParser = new TestSuiteXmlParser(); + String xml = "\n" + + "\n" + + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " junit.framework.AssertionFailedError: \n" + + + "\tat junit.framework.Assert.fail(Assert.java:47)\n" + + "\tat wellFormedXmlFailures.TestSurefire3.testU0000(TestSurefire3.java:40)\n" + + "\n" + + " \n" + + " \n" + + " junit.framework.AssertionFailedError: >\n" + + + "\tat junit.framework.Assert.fail(Assert.java:47)\n" + + "\tat wellFormedXmlFailures.TestSurefire3.testGreater(TestSurefire3.java:35)\n" + + "\n" + + " \n" + + " \n" + + " junit.framework.AssertionFailedError: \"\n" + + + "\tat junit.framework.Assert.fail(Assert.java:47)\n" + + "\tat wellFormedXmlFailures.TestSurefire3.testQuote(TestSurefire3.java:25)\n" + + "\n" + + " \n" + + ""; + InputStream byteArrayIs = new ByteArrayInputStream( xml.getBytes() ); + Collection parse = testSuiteXmlParser.parse( new InputStreamReader(byteArrayIs, "UTF-8") ); + } + + public void testParser() + throws IOException, SAXException, ParserConfigurationException + { + TestSuiteXmlParser parser = new TestSuiteXmlParser(); + + Collection oldResult = parser.parse( + "src/test/resources/fixture/testsuitexmlparser/TEST-org.apache.maven.surefire.test.FailingTest.xml" ); + + assertNotNull( oldResult ); + + assertEquals( 1, oldResult.size() ); + ReportTestSuite next = oldResult.iterator().next(); + assertEquals( 2, next.getNumberOfTests() ); + + + } + + public void noTestParserBadFile() // Determine problem with xml file. + throws IOException, SAXException, ParserConfigurationException + { + TestSuiteXmlParser parser = new TestSuiteXmlParser(); + + File file = new File( "../surefire-integration-tests/target/UmlautDirIT/junit-pathWith\u00DCmlaut/target/surefire-reports/TEST-umlautTest.BasicTest.xml" ); + assertTrue(file.exists()); + Collection oldResult = parser.parse( + "..\\surefire-integration-tests\\target\\UmlautDirIT\\junit-pathWith\u00DCmlaut\\target\\surefire-reports\\TEST-umlautTest.BasicTest.xml" ); + + assertNotNull( oldResult ); + + assertEquals( 1, oldResult.size() ); + ReportTestSuite next = oldResult.iterator().next(); + assertEquals( 2, next.getNumberOfTests() ); + + + } + + public void testParserHitsFailsafeSummary() + throws IOException, SAXException, ParserConfigurationException + { + TestSuiteXmlParser parser = new TestSuiteXmlParser(); + + parser.parse( "src/test/resources/fixture/testsuitexmlparser/failsafe-summary.xml" ); + + assertFalse( parser.isValid() ); + + parser.parse( + "src/test/resources/fixture/testsuitexmlparser/TEST-org.apache.maven.surefire.test.FailingTest.xml" ); + + assertTrue( parser.isValid() ); + } + + +} diff --git a/surefire-report-parser/src/test/resources/fixture/testsuitexmlparser/TEST-org.apache.maven.surefire.test.FailingTest.xml b/surefire-report-parser/src/test/resources/fixture/testsuitexmlparser/TEST-org.apache.maven.surefire.test.FailingTest.xml new file mode 100644 index 0000000000..09c9c6dade --- /dev/null +++ b/surefire-report-parser/src/test/resources/fixture/testsuitexmlparser/TEST-org.apache.maven.surefire.test.FailingTest.xml @@ -0,0 +1,154 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + java.lang.AssertionError: +Expected: "wrong" + got: "value" + + at org.junit.Assert.assertThat(Assert.java:778) + at org.junit.Assert.assertThat(Assert.java:736) + at org.apache.maven.surefire.test.FailingTest.defaultTestValueIs_Value(FailingTest.java:23) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) + at java.lang.reflect.Method.invoke(Method.java:601) + at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44) + at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15) + at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41) + at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20) + at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31) + at org.junit.rules.TestWatchman$1.evaluate(TestWatchman.java:48) + at org.junit.runners.BlockJUnit4ClassRunner.runNotIgnored(BlockJUnit4ClassRunner.java:79) + at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:71) + at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49) + at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193) + at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52) + at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191) + at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42) + at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184) + at org.junit.runners.ParentRunner.run(ParentRunner.java:236) + at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:262) + at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:151) + at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:122) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) + at java.lang.reflect.Method.invoke(Method.java:601) + at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189) + at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165) + at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85) + at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:128) + at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:88) + + + + java.lang.AssertionError: +Expected: "bar" + got: "foo" + + at org.junit.Assert.assertThat(Assert.java:778) + at org.junit.Assert.assertThat(Assert.java:736) + at org.apache.maven.surefire.test.FailingTest.setTestAndRetrieveValue(FailingTest.java:34) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) + at java.lang.reflect.Method.invoke(Method.java:601) + at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44) + at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15) + at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41) + at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20) + at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31) + at org.junit.rules.TestWatchman$1.evaluate(TestWatchman.java:48) + at org.junit.runners.BlockJUnit4ClassRunner.runNotIgnored(BlockJUnit4ClassRunner.java:79) + at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:71) + at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49) + at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193) + at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52) + at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191) + at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42) + at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184) + at org.junit.runners.ParentRunner.run(ParentRunner.java:236) + at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:262) + at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:151) + at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:122) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) + at java.lang.reflect.Method.invoke(Method.java:601) + at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189) + at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165) + at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85) + at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:128) + at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:88) + + + \ No newline at end of file diff --git a/surefire-report-parser/src/test/resources/fixture/testsuitexmlparser/failsafe-summary-old.xml b/surefire-report-parser/src/test/resources/fixture/testsuitexmlparser/failsafe-summary-old.xml new file mode 100644 index 0000000000..6839aa98c6 --- /dev/null +++ b/surefire-report-parser/src/test/resources/fixture/testsuitexmlparser/failsafe-summary-old.xml @@ -0,0 +1,8 @@ + + + 1 + 0 + 1 + 0 + + \ No newline at end of file diff --git a/surefire-report-parser/src/test/resources/fixture/testsuitexmlparser/failsafe-summary.xml b/surefire-report-parser/src/test/resources/fixture/testsuitexmlparser/failsafe-summary.xml new file mode 100644 index 0000000000..1bc82d9031 --- /dev/null +++ b/surefire-report-parser/src/test/resources/fixture/testsuitexmlparser/failsafe-summary.xml @@ -0,0 +1,8 @@ + + + 4 + 0 + 2 + 0 + + \ No newline at end of file diff --git a/surefire-report-parser/src/test/resources/test-reports/TEST-AntUnit.xml b/surefire-report-parser/src/test/resources/test-reports/TEST-AntUnit.xml new file mode 100644 index 0000000000..71e5342e1c --- /dev/null +++ b/surefire-report-parser/src/test/resources/test-reports/TEST-AntUnit.xml @@ -0,0 +1,11 @@ + + + + + + 1 + 0 + 0 + + diff --git a/surefire-report-parser/src/test/resources/test-reports/TEST-NoPackageTest.xml b/surefire-report-parser/src/test/resources/test-reports/TEST-NoPackageTest.xml new file mode 100644 index 0000000000..4c0f831ab4 --- /dev/null +++ b/surefire-report-parser/src/test/resources/test-reports/TEST-NoPackageTest.xml @@ -0,0 +1,256 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + junit.framework.AssertionFailedError: " + at junit.framework.Assert.fail(Assert.java:47) + at NoPackageTest.testQuote(NoPackageTest.java:23) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) + at java.lang.reflect.Method.invoke(Method.java:585) + at junit.framework.TestCase.runTest(TestCase.java:154) + at junit.framework.TestCase.runBare(TestCase.java:127) + at junit.framework.TestResult$1.protect(TestResult.java:106) + at junit.framework.TestResult.runProtected(TestResult.java:124) + at junit.framework.TestResult.run(TestResult.java:109) + at junit.framework.TestCase.run(TestCase.java:118) + at junit.framework.TestSuite.runTest(TestSuite.java:208) + at junit.framework.TestSuite.run(TestSuite.java:203) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) + at java.lang.reflect.Method.invoke(Method.java:585) + at org.apache.maven.surefire.battery.JUnitBattery.executeJUnit(JUnitBattery.java:242) + at org.apache.maven.surefire.battery.JUnitBattery.execute(JUnitBattery.java:216) + at org.apache.maven.surefire.Surefire.executeBattery(Surefire.java:215) + at org.apache.maven.surefire.Surefire.run(Surefire.java:163) + at org.apache.maven.surefire.Surefire.run(Surefire.java:87) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) + at java.lang.reflect.Method.invoke(Method.java:585) + at org.apache.maven.surefire.SurefireBooter.runTestsInProcess(SurefireBooter.java:300) + at org.apache.maven.surefire.SurefireBooter.run(SurefireBooter.java:216) + at org.apache.maven.test.SurefirePlugin.execute(SurefirePlugin.java:369) + at org.apache.maven.plugin.DefaultPluginManager.executeMojo(DefaultPluginManager.java:415) + at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:539) + at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalWithLifecycle(DefaultLifecycleExecutor.java:480) + at org.apache.maven.lifecycle.DefaultLifecycleExecutor.forkProjectLifecycle(DefaultLifecycleExecutor.java:867) + at org.apache.maven.lifecycle.DefaultLifecycleExecutor.forkLifecycle(DefaultLifecycleExecutor.java:739) + at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:510) + at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeStandaloneGoal(DefaultLifecycleExecutor.java:493) + at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoal(DefaultLifecycleExecutor.java:463) + at + org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalAndHandleFailures(DefaultLifecycleExecutor.java:311) + at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeTaskSegments(DefaultLifecycleExecutor.java:274) + at org.apache.maven.lifecycle.DefaultLifecycleExecutor.execute(DefaultLifecycleExecutor.java:140) + at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:322) + at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:115) + at org.apache.maven.cli.MavenCli.main(MavenCli.java:249) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) + at java.lang.reflect.Method.invoke(Method.java:585) + at org.codehaus.classworlds.Launcher.launchEnhanced(Launcher.java:315) + at org.codehaus.classworlds.Launcher.launch(Launcher.java:255) + at org.codehaus.classworlds.Launcher.mainWithExitCode(Launcher.java:430) + at org.codehaus.classworlds.Launcher.main(Launcher.java:375) + + + + junit.framework.AssertionFailedError: < + at junit.framework.Assert.fail(Assert.java:47) + at NoPackageTest.testLower(NoPackageTest.java:28) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) + at java.lang.reflect.Method.invoke(Method.java:585) + at junit.framework.TestCase.runTest(TestCase.java:154) + at junit.framework.TestCase.runBare(TestCase.java:127) + at junit.framework.TestResult$1.protect(TestResult.java:106) + at junit.framework.TestResult.runProtected(TestResult.java:124) + at junit.framework.TestResult.run(TestResult.java:109) + at junit.framework.TestCase.run(TestCase.java:118) + at junit.framework.TestSuite.runTest(TestSuite.java:208) + at junit.framework.TestSuite.run(TestSuite.java:203) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) + at java.lang.reflect.Method.invoke(Method.java:585) + at org.apache.maven.surefire.battery.JUnitBattery.executeJUnit(JUnitBattery.java:242) + at org.apache.maven.surefire.battery.JUnitBattery.execute(JUnitBattery.java:216) + at org.apache.maven.surefire.Surefire.executeBattery(Surefire.java:215) + at org.apache.maven.surefire.Surefire.run(Surefire.java:163) + at org.apache.maven.surefire.Surefire.run(Surefire.java:87) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) + at java.lang.reflect.Method.invoke(Method.java:585) + at org.apache.maven.surefire.SurefireBooter.runTestsInProcess(SurefireBooter.java:300) + at org.apache.maven.surefire.SurefireBooter.run(SurefireBooter.java:216) + at org.apache.maven.test.SurefirePlugin.execute(SurefirePlugin.java:369) + at org.apache.maven.plugin.DefaultPluginManager.executeMojo(DefaultPluginManager.java:415) + at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:539) + at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalWithLifecycle(DefaultLifecycleExecutor.java:480) + at org.apache.maven.lifecycle.DefaultLifecycleExecutor.forkProjectLifecycle(DefaultLifecycleExecutor.java:867) + at org.apache.maven.lifecycle.DefaultLifecycleExecutor.forkLifecycle(DefaultLifecycleExecutor.java:739) + at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:510) + at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeStandaloneGoal(DefaultLifecycleExecutor.java:493) + at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoal(DefaultLifecycleExecutor.java:463) + at + org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalAndHandleFailures(DefaultLifecycleExecutor.java:311) + at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeTaskSegments(DefaultLifecycleExecutor.java:274) + at org.apache.maven.lifecycle.DefaultLifecycleExecutor.execute(DefaultLifecycleExecutor.java:140) + at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:322) + at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:115) + at org.apache.maven.cli.MavenCli.main(MavenCli.java:249) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) + at java.lang.reflect.Method.invoke(Method.java:585) + at org.codehaus.classworlds.Launcher.launchEnhanced(Launcher.java:315) + at org.codehaus.classworlds.Launcher.launch(Launcher.java:255) + at org.codehaus.classworlds.Launcher.mainWithExitCode(Launcher.java:430) + at org.codehaus.classworlds.Launcher.main(Launcher.java:375) + + + + junit.framework.AssertionFailedError: > + at junit.framework.Assert.fail(Assert.java:47) + at NoPackageTest.testGreater(NoPackageTest.java:33) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) + at java.lang.reflect.Method.invoke(Method.java:585) + at junit.framework.TestCase.runTest(TestCase.java:154) + at junit.framework.TestCase.runBare(TestCase.java:127) + at junit.framework.TestResult$1.protect(TestResult.java:106) + at junit.framework.TestResult.runProtected(TestResult.java:124) + at junit.framework.TestResult.run(TestResult.java:109) + at junit.framework.TestCase.run(TestCase.java:118) + at junit.framework.TestSuite.runTest(TestSuite.java:208) + at junit.framework.TestSuite.run(TestSuite.java:203) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) + at java.lang.reflect.Method.invoke(Method.java:585) + at org.apache.maven.surefire.battery.JUnitBattery.executeJUnit(JUnitBattery.java:242) + at org.apache.maven.surefire.battery.JUnitBattery.execute(JUnitBattery.java:216) + at org.apache.maven.surefire.Surefire.executeBattery(Surefire.java:215) + at org.apache.maven.surefire.Surefire.run(Surefire.java:163) + at org.apache.maven.surefire.Surefire.run(Surefire.java:87) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) + at java.lang.reflect.Method.invoke(Method.java:585) + at org.apache.maven.surefire.SurefireBooter.runTestsInProcess(SurefireBooter.java:300) + at org.apache.maven.surefire.SurefireBooter.run(SurefireBooter.java:216) + at org.apache.maven.test.SurefirePlugin.execute(SurefirePlugin.java:369) + at org.apache.maven.plugin.DefaultPluginManager.executeMojo(DefaultPluginManager.java:415) + at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:539) + at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalWithLifecycle(DefaultLifecycleExecutor.java:480) + at org.apache.maven.lifecycle.DefaultLifecycleExecutor.forkProjectLifecycle(DefaultLifecycleExecutor.java:867) + at org.apache.maven.lifecycle.DefaultLifecycleExecutor.forkLifecycle(DefaultLifecycleExecutor.java:739) + at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:510) + at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeStandaloneGoal(DefaultLifecycleExecutor.java:493) + at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoal(DefaultLifecycleExecutor.java:463) + at + org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalAndHandleFailures(DefaultLifecycleExecutor.java:311) + at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeTaskSegments(DefaultLifecycleExecutor.java:274) + at org.apache.maven.lifecycle.DefaultLifecycleExecutor.execute(DefaultLifecycleExecutor.java:140) + at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:322) + at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:115) + at org.apache.maven.cli.MavenCli.main(MavenCli.java:249) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) + at java.lang.reflect.Method.invoke(Method.java:585) + at org.codehaus.classworlds.Launcher.launchEnhanced(Launcher.java:315) + at org.codehaus.classworlds.Launcher.launch(Launcher.java:255) + at org.codehaus.classworlds.Launcher.mainWithExitCode(Launcher.java:430) + at org.codehaus.classworlds.Launcher.main(Launcher.java:375) + + + \ No newline at end of file diff --git a/surefire-report-parser/src/test/resources/test-reports/TEST-NoTimeTestCaseTest.xml b/surefire-report-parser/src/test/resources/test-reports/TEST-NoTimeTestCaseTest.xml new file mode 100644 index 0000000000..a36a19a605 --- /dev/null +++ b/surefire-report-parser/src/test/resources/test-reports/TEST-NoTimeTestCaseTest.xml @@ -0,0 +1,92 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/surefire-report-parser/src/test/resources/test-reports/TEST-classWithNoTests.NoMethodsTestCase.xml b/surefire-report-parser/src/test/resources/test-reports/TEST-classWithNoTests.NoMethodsTestCase.xml new file mode 100644 index 0000000000..31f7ea56f8 --- /dev/null +++ b/surefire-report-parser/src/test/resources/test-reports/TEST-classWithNoTests.NoMethodsTestCase.xml @@ -0,0 +1,73 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/surefire-report-parser/src/test/resources/test-reports/TEST-com.shape.CircleTest.xml b/surefire-report-parser/src/test/resources/test-reports/TEST-com.shape.CircleTest.xml new file mode 100644 index 0000000000..1ce1d3dd13 --- /dev/null +++ b/surefire-report-parser/src/test/resources/test-reports/TEST-com.shape.CircleTest.xml @@ -0,0 +1,200 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + junit.framework.AssertionFailedError: expected:<20> but was:<10> + at junit.framework.Assert.fail(Assert.java:47) + at junit.framework.Assert.failNotEquals(Assert.java:282) + at junit.framework.Assert.assertEquals(Assert.java:64) + at junit.framework.Assert.assertEquals(Assert.java:201) + at junit.framework.Assert.assertEquals(Assert.java:207) + at com.shape.CircleTest.testRadius(CircleTest.java:34) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) + at java.lang.reflect.Method.invoke(Method.java:585) + at junit.framework.TestCase.runTest(TestCase.java:154) + at junit.framework.TestCase.runBare(TestCase.java:127) + at junit.framework.TestResult$1.protect(TestResult.java:106) + at junit.framework.TestResult.runProtected(TestResult.java:124) + at junit.framework.TestResult.run(TestResult.java:109) + at junit.framework.TestCase.run(TestCase.java:118) + at junit.framework.TestSuite.runTest(TestSuite.java:208) + at junit.framework.TestSuite.run(TestSuite.java:203) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) + at java.lang.reflect.Method.invoke(Method.java:585) + at org.codehaus.surefire.battery.JUnitBattery.executeJUnit(JUnitBattery.java:246) + at org.codehaus.surefire.battery.JUnitBattery.execute(JUnitBattery.java:220) + at org.codehaus.surefire.Surefire.executeBattery(Surefire.java:203) + at org.codehaus.surefire.Surefire.run(Surefire.java:152) + at org.codehaus.surefire.Surefire.run(Surefire.java:76) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) + at java.lang.reflect.Method.invoke(Method.java:585) + at org.codehaus.surefire.SurefireBooter.run(SurefireBooter.java:104) + at org.apache.maven.test.SurefirePlugin.execute(SurefirePlugin.java:241) + at org.apache.maven.plugin.DefaultPluginManager.executeMojo(DefaultPluginManager.java:357) + at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:479) + at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalWithLifecycle(DefaultLifecycleExecutor.java:452) + at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoal(DefaultLifecycleExecutor.java:438) + at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeTaskSegments(DefaultLifecycleExecutor.java:273) + at org.apache.maven.lifecycle.DefaultLifecycleExecutor.execute(DefaultLifecycleExecutor.java:131) + at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:186) + at org.apache.maven.cli.MavenCli.main(MavenCli.java:316) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) + at java.lang.reflect.Method.invoke(Method.java:585) + at org.codehaus.classworlds.Launcher.launchEnhanced(Launcher.java:315) + at org.codehaus.classworlds.Launcher.launch(Launcher.java:255) + at org.codehaus.classworlds.Launcher.mainWithExitCode(Launcher.java:430) + at org.codehaus.classworlds.Launcher.main(Launcher.java:375) + + [OUT] : Getting the diameter + + [ERR] : Getting the Circumference + + + + java.lang.ArithmeticException: / by zero + at com.shape.CircleTest.testProperties(CircleTest.java:44) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) + at java.lang.reflect.Method.invoke(Method.java:585) + at junit.framework.TestCase.runTest(TestCase.java:154) + at junit.framework.TestCase.runBare(TestCase.java:127) + at junit.framework.TestResult$1.protect(TestResult.java:106) + at junit.framework.TestResult.runProtected(TestResult.java:124) + at junit.framework.TestResult.run(TestResult.java:109) + at junit.framework.TestCase.run(TestCase.java:118) + at junit.framework.TestSuite.runTest(TestSuite.java:208) + at junit.framework.TestSuite.run(TestSuite.java:203) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) + at java.lang.reflect.Method.invoke(Method.java:585) + at org.codehaus.surefire.battery.JUnitBattery.executeJUnit(JUnitBattery.java:246) + at org.codehaus.surefire.battery.JUnitBattery.execute(JUnitBattery.java:220) + at org.codehaus.surefire.Surefire.executeBattery(Surefire.java:203) + at org.codehaus.surefire.Surefire.run(Surefire.java:152) + at org.codehaus.surefire.Surefire.run(Surefire.java:76) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) + at java.lang.reflect.Method.invoke(Method.java:585) + at org.codehaus.surefire.SurefireBooter.run(SurefireBooter.java:104) + at org.apache.maven.test.SurefirePlugin.execute(SurefirePlugin.java:241) + at org.apache.maven.plugin.DefaultPluginManager.executeMojo(DefaultPluginManager.java:357) + at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:479) + at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalWithLifecycle(DefaultLifecycleExecutor.java:452) + at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoal(DefaultLifecycleExecutor.java:438) + at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeTaskSegments(DefaultLifecycleExecutor.java:273) + at org.apache.maven.lifecycle.DefaultLifecycleExecutor.execute(DefaultLifecycleExecutor.java:131) + at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:186) + at org.apache.maven.cli.MavenCli.main(MavenCli.java:316) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) + at java.lang.reflect.Method.invoke(Method.java:585) + at org.codehaus.classworlds.Launcher.launchEnhanced(Launcher.java:315) + at org.codehaus.classworlds.Launcher.launch(Launcher.java:255) + at org.codehaus.classworlds.Launcher.mainWithExitCode(Launcher.java:430) + at org.codehaus.classworlds.Launcher.main(Launcher.java:375) + + [OUT] : Getting the diameter + + [ERR] : Getting the Circumference + + + + + + \ No newline at end of file diff --git a/surefire-report-parser/src/test/resources/test-reports/TEST-com.shape.PointTest.xml b/surefire-report-parser/src/test/resources/test-reports/TEST-com.shape.PointTest.xml new file mode 100644 index 0000000000..7dda584c02 --- /dev/null +++ b/surefire-report-parser/src/test/resources/test-reports/TEST-com.shape.PointTest.xml @@ -0,0 +1,142 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + junit.framework.AssertionFailedError: expected:<0> but was:<1> + at junit.framework.Assert.fail(Assert.java:47) + at junit.framework.Assert.failNotEquals(Assert.java:282) + at junit.framework.Assert.assertEquals(Assert.java:64) + at junit.framework.Assert.assertEquals(Assert.java:201) + at junit.framework.Assert.assertEquals(Assert.java:207) + at com.shape.PointTest.testXY(PointTest.java:28) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) + at java.lang.reflect.Method.invoke(Method.java:585) + at junit.framework.TestCase.runTest(TestCase.java:154) + at junit.framework.TestCase.runBare(TestCase.java:127) + at junit.framework.TestResult$1.protect(TestResult.java:106) + at junit.framework.TestResult.runProtected(TestResult.java:124) + at junit.framework.TestResult.run(TestResult.java:109) + at junit.framework.TestCase.run(TestCase.java:118) + at junit.framework.TestSuite.runTest(TestSuite.java:208) + at junit.framework.TestSuite.run(TestSuite.java:203) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) + at java.lang.reflect.Method.invoke(Method.java:585) + at org.codehaus.surefire.battery.JUnitBattery.executeJUnit(JUnitBattery.java:246) + at org.codehaus.surefire.battery.JUnitBattery.execute(JUnitBattery.java:220) + at org.codehaus.surefire.Surefire.executeBattery(Surefire.java:203) + at org.codehaus.surefire.Surefire.run(Surefire.java:152) + at org.codehaus.surefire.Surefire.run(Surefire.java:76) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) + at java.lang.reflect.Method.invoke(Method.java:585) + at org.codehaus.surefire.SurefireBooter.run(SurefireBooter.java:104) + at org.apache.maven.test.SurefirePlugin.execute(SurefirePlugin.java:241) + at org.apache.maven.plugin.DefaultPluginManager.executeMojo(DefaultPluginManager.java:357) + at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:479) + at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalWithLifecycle(DefaultLifecycleExecutor.java:452) + at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoal(DefaultLifecycleExecutor.java:438) + at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeTaskSegments(DefaultLifecycleExecutor.java:273) + at org.apache.maven.lifecycle.DefaultLifecycleExecutor.execute(DefaultLifecycleExecutor.java:131) + at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:186) + at org.apache.maven.cli.MavenCli.main(MavenCli.java:316) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) + at java.lang.reflect.Method.invoke(Method.java:585) + at org.codehaus.classworlds.Launcher.launchEnhanced(Launcher.java:315) + at org.codehaus.classworlds.Launcher.launch(Launcher.java:255) + at org.codehaus.classworlds.Launcher.mainWithExitCode(Launcher.java:430) + at org.codehaus.classworlds.Launcher.main(Launcher.java:375) + + + + + \ No newline at end of file diff --git a/surefire-report-parser/src/test/resources/test-reports/TEST-junit.twoTestCaseSuite.WrapperTestSuite.xml b/surefire-report-parser/src/test/resources/test-reports/TEST-junit.twoTestCaseSuite.WrapperTestSuite.xml new file mode 100644 index 0000000000..cd94387a6a --- /dev/null +++ b/surefire-report-parser/src/test/resources/test-reports/TEST-junit.twoTestCaseSuite.WrapperTestSuite.xml @@ -0,0 +1,73 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/surefire-report-parser/src/test/resources/test-reports/com.shape.CircleTest.txt b/surefire-report-parser/src/test/resources/test-reports/com.shape.CircleTest.txt new file mode 100644 index 0000000000..5030dee18c --- /dev/null +++ b/surefire-report-parser/src/test/resources/test-reports/com.shape.CircleTest.txt @@ -0,0 +1,122 @@ +------------------------------------------------------------------------------- +Battery: com.shape.CircleTest +------------------------------------------------------------------------------- +testX(com.shape.CircleTest) +testY(com.shape.CircleTest) +testXY(com.shape.CircleTest) +testRadius(com.shape.CircleTest) + +[ stdout ] --------------------------------------------------------------- + + +[ stderr ] --------------------------------------------------------------- + + +[ stacktrace ] ----------------------------------------------------------- + +junit.framework.AssertionFailedError: expected:<20> but was:<10> + at junit.framework.Assert.fail(Assert.java:47) + at junit.framework.Assert.failNotEquals(Assert.java:282) + at junit.framework.Assert.assertEquals(Assert.java:64) + at junit.framework.Assert.assertEquals(Assert.java:201) + at junit.framework.Assert.assertEquals(Assert.java:207) + at com.shape.CircleTest.testRadius(CircleTest.java:34) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) + at java.lang.reflect.Method.invoke(Method.java:585) + at junit.framework.TestCase.runTest(TestCase.java:154) + at junit.framework.TestCase.runBare(TestCase.java:127) + at junit.framework.TestResult$1.protect(TestResult.java:106) + at junit.framework.TestResult.runProtected(TestResult.java:124) + at junit.framework.TestResult.run(TestResult.java:109) + at junit.framework.TestCase.run(TestCase.java:118) + at junit.framework.TestSuite.runTest(TestSuite.java:208) + at junit.framework.TestSuite.run(TestSuite.java:203) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) + at java.lang.reflect.Method.invoke(Method.java:585) + at org.codehaus.surefire.battery.JUnitBattery.execute(JUnitBattery.java:190) + at org.codehaus.surefire.Surefire.executeBattery(Surefire.java:155) + at org.codehaus.surefire.Surefire.run(Surefire.java:105) + at org.codehaus.surefire.Surefire.run(Surefire.java:59) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) + at java.lang.reflect.Method.invoke(Method.java:585) + at org.codehaus.surefire.SurefireBooter.run(SurefireBooter.java:83) + at org.apache.maven.test.SurefirePlugin.execute(SurefirePlugin.java:218) + at org.apache.maven.plugin.DefaultPluginManager.executeMojo(DefaultPluginManager.java:361) + at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:472) + at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalWithLifecycle(DefaultLifecycleExecutor.java:445) + at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoal(DefaultLifecycleExecutor.java:431) + at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeTaskSegments(DefaultLifecycleExecutor.java:268) + at org.apache.maven.lifecycle.DefaultLifecycleExecutor.execute(DefaultLifecycleExecutor.java:127) + at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:186) + at org.apache.maven.cli.MavenCli.main(MavenCli.java:292) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) + at java.lang.reflect.Method.invoke(Method.java:585) + at org.codehaus.classworlds.Launcher.launchEnhanced(Launcher.java:315) + at org.codehaus.classworlds.Launcher.launch(Launcher.java:255) + at org.codehaus.classworlds.Launcher.mainWithExitCode(Launcher.java:430) + at org.codehaus.classworlds.Launcher.main(Launcher.java:375) +testProperties(com.shape.CircleTest) + +[ stdout ] --------------------------------------------------------------- + + +[ stderr ] --------------------------------------------------------------- + + +[ stacktrace ] ----------------------------------------------------------- + +java.lang.ArithmeticException: / by zero + at com.shape.CircleTest.testProperties(CircleTest.java:44) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) + at java.lang.reflect.Method.invoke(Method.java:585) + at junit.framework.TestCase.runTest(TestCase.java:154) + at junit.framework.TestCase.runBare(TestCase.java:127) + at junit.framework.TestResult$1.protect(TestResult.java:106) + at junit.framework.TestResult.runProtected(TestResult.java:124) + at junit.framework.TestResult.run(TestResult.java:109) + at junit.framework.TestCase.run(TestCase.java:118) + at junit.framework.TestSuite.runTest(TestSuite.java:208) + at junit.framework.TestSuite.run(TestSuite.java:203) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) + at java.lang.reflect.Method.invoke(Method.java:585) + at org.codehaus.surefire.battery.JUnitBattery.execute(JUnitBattery.java:190) + at org.codehaus.surefire.Surefire.executeBattery(Surefire.java:155) + at org.codehaus.surefire.Surefire.run(Surefire.java:105) + at org.codehaus.surefire.Surefire.run(Surefire.java:59) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) + at java.lang.reflect.Method.invoke(Method.java:585) + at org.codehaus.surefire.SurefireBooter.run(SurefireBooter.java:83) + at org.apache.maven.test.SurefirePlugin.execute(SurefirePlugin.java:218) + at org.apache.maven.plugin.DefaultPluginManager.executeMojo(DefaultPluginManager.java:361) + at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:472) + at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalWithLifecycle(DefaultLifecycleExecutor.java:445) + at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoal(DefaultLifecycleExecutor.java:431) + at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeTaskSegments(DefaultLifecycleExecutor.java:268) + at org.apache.maven.lifecycle.DefaultLifecycleExecutor.execute(DefaultLifecycleExecutor.java:127) + at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:186) + at org.apache.maven.cli.MavenCli.main(MavenCli.java:292) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) + at java.lang.reflect.Method.invoke(Method.java:585) + at org.codehaus.classworlds.Launcher.launchEnhanced(Launcher.java:315) + at org.codehaus.classworlds.Launcher.launch(Launcher.java:255) + at org.codehaus.classworlds.Launcher.mainWithExitCode(Launcher.java:430) + at org.codehaus.classworlds.Launcher.main(Launcher.java:375) +testPI(com.shape.CircleTest) +testCircumference(com.shape.CircleTest) +testDiameter(com.shape.CircleTest) diff --git a/surefire-report-parser/src/test/resources/test-reports/com.shapeclone.CircleTest.txt b/surefire-report-parser/src/test/resources/test-reports/com.shapeclone.CircleTest.txt new file mode 100644 index 0000000000..90e323991c --- /dev/null +++ b/surefire-report-parser/src/test/resources/test-reports/com.shapeclone.CircleTest.txt @@ -0,0 +1,122 @@ +------------------------------------------------------------------------------- +Battery: com.shapeclone.CircleTest +------------------------------------------------------------------------------- +testX(com.shapeclone.CircleTest) +testY(com.shapeclone.CircleTest) +testXY(com.shapeclone.CircleTest) +testRadius(com.shapeclone.CircleTest) + +[ stdout ] --------------------------------------------------------------- + + +[ stderr ] --------------------------------------------------------------- + + +[ stacktrace ] ----------------------------------------------------------- + +junit.framework.AssertionFailedError: expected:<20> but was:<10> + at junit.framework.Assert.fail(Assert.java:47) + at junit.framework.Assert.failNotEquals(Assert.java:282) + at junit.framework.Assert.assertEquals(Assert.java:64) + at junit.framework.Assert.assertEquals(Assert.java:201) + at junit.framework.Assert.assertEquals(Assert.java:207) + at com.shapeclone.CircleTest.testRadius(CircleTest.java:34) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) + at java.lang.reflect.Method.invoke(Method.java:585) + at junit.framework.TestCase.runTest(TestCase.java:154) + at junit.framework.TestCase.runBare(TestCase.java:127) + at junit.framework.TestResult$1.protect(TestResult.java:106) + at junit.framework.TestResult.runProtected(TestResult.java:124) + at junit.framework.TestResult.run(TestResult.java:109) + at junit.framework.TestCase.run(TestCase.java:118) + at junit.framework.TestSuite.runTest(TestSuite.java:208) + at junit.framework.TestSuite.run(TestSuite.java:203) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) + at java.lang.reflect.Method.invoke(Method.java:585) + at org.codehaus.surefire.battery.JUnitBattery.execute(JUnitBattery.java:190) + at org.codehaus.surefire.Surefire.executeBattery(Surefire.java:155) + at org.codehaus.surefire.Surefire.run(Surefire.java:105) + at org.codehaus.surefire.Surefire.run(Surefire.java:59) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) + at java.lang.reflect.Method.invoke(Method.java:585) + at org.codehaus.surefire.SurefireBooter.run(SurefireBooter.java:83) + at org.apache.maven.test.SurefirePlugin.execute(SurefirePlugin.java:218) + at org.apache.maven.plugin.DefaultPluginManager.executeMojo(DefaultPluginManager.java:361) + at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:472) + at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalWithLifecycle(DefaultLifecycleExecutor.java:445) + at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoal(DefaultLifecycleExecutor.java:431) + at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeTaskSegments(DefaultLifecycleExecutor.java:268) + at org.apache.maven.lifecycle.DefaultLifecycleExecutor.execute(DefaultLifecycleExecutor.java:127) + at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:186) + at org.apache.maven.cli.MavenCli.main(MavenCli.java:292) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) + at java.lang.reflect.Method.invoke(Method.java:585) + at org.codehaus.classworlds.Launcher.launchEnhanced(Launcher.java:315) + at org.codehaus.classworlds.Launcher.launch(Launcher.java:255) + at org.codehaus.classworlds.Launcher.mainWithExitCode(Launcher.java:430) + at org.codehaus.classworlds.Launcher.main(Launcher.java:375) +testProperties(com.shapeclone.CircleTest) + +[ stdout ] --------------------------------------------------------------- + + +[ stderr ] --------------------------------------------------------------- + + +[ stacktrace ] ----------------------------------------------------------- + +java.lang.ArithmeticException: / by zero + at com.shapeclone.CircleTest.testProperties(CircleTest.java:44) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) + at java.lang.reflect.Method.invoke(Method.java:585) + at junit.framework.TestCase.runTest(TestCase.java:154) + at junit.framework.TestCase.runBare(TestCase.java:127) + at junit.framework.TestResult$1.protect(TestResult.java:106) + at junit.framework.TestResult.runProtected(TestResult.java:124) + at junit.framework.TestResult.run(TestResult.java:109) + at junit.framework.TestCase.run(TestCase.java:118) + at junit.framework.TestSuite.runTest(TestSuite.java:208) + at junit.framework.TestSuite.run(TestSuite.java:203) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) + at java.lang.reflect.Method.invoke(Method.java:585) + at org.codehaus.surefire.battery.JUnitBattery.execute(JUnitBattery.java:190) + at org.codehaus.surefire.Surefire.executeBattery(Surefire.java:155) + at org.codehaus.surefire.Surefire.run(Surefire.java:105) + at org.codehaus.surefire.Surefire.run(Surefire.java:59) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) + at java.lang.reflect.Method.invoke(Method.java:585) + at org.codehaus.surefire.SurefireBooter.run(SurefireBooter.java:83) + at org.apache.maven.test.SurefirePlugin.execute(SurefirePlugin.java:218) + at org.apache.maven.plugin.DefaultPluginManager.executeMojo(DefaultPluginManager.java:361) + at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:472) + at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalWithLifecycle(DefaultLifecycleExecutor.java:445) + at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoal(DefaultLifecycleExecutor.java:431) + at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeTaskSegments(DefaultLifecycleExecutor.java:268) + at org.apache.maven.lifecycle.DefaultLifecycleExecutor.execute(DefaultLifecycleExecutor.java:127) + at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:186) + at org.apache.maven.cli.MavenCli.main(MavenCli.java:292) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) + at java.lang.reflect.Method.invoke(Method.java:585) + at org.codehaus.classworlds.Launcher.launchEnhanced(Launcher.java:315) + at org.codehaus.classworlds.Launcher.launch(Launcher.java:255) + at org.codehaus.classworlds.Launcher.mainWithExitCode(Launcher.java:430) + at org.codehaus.classworlds.Launcher.main(Launcher.java:375) +testPI(com.shapeclone.CircleTest) +testCircumference(com.shapeclone.CircleTest) +testDiameter(com.shapeclone.CircleTest) diff --git a/surefire-setup-integration-tests/pom.xml b/surefire-setup-integration-tests/pom.xml index 543afa96d3..86ddbcf1a7 100644 --- a/surefire-setup-integration-tests/pom.xml +++ b/surefire-setup-integration-tests/pom.xml @@ -18,14 +18,13 @@ ~ under the License. --> - + 4.0.0 org.apache.maven.surefire surefire - 2.13-SNAPSHOT + 2.16-SNAPSHOT ../pom.xml @@ -66,7 +65,7 @@ surefire-testng ${project.version} - + org.testng testng @@ -88,11 +87,11 @@ surefire-junit47 ${project.version} - + org.apache.maven maven-settings @@ -139,6 +138,61 @@ org.apache.maven.surefire:surefire-testng-utils:${project.version} ${project.build.directory}/it-repo + + org.testng:testng:4.7:jar:jdk15 + org.testng:testng:5.0.2:jar:jdk15 + org.testng:testng:5.1:jar:jdk15 + org.testng:testng:5.5:jar:jdk15 + org.testng:testng:5.6:jar:jdk15 + org.testng:testng:5.7:jar:jdk14 + org.testng:testng:5.7:jar:jdk15 + org.testng:testng:5.8:jar:jdk15 + org.testng:testng:5.9:jar:jdk15 + org.testng:testng:5.10:jar:jdk15 + org.testng:testng:5.12.1 + org.testng:testng:5.13 + org.testng:testng:5.13.1 + org.testng:testng:5.14 + org.testng:testng:5.14.1 + org.testng:testng:5.14.2 + org.testng:testng:5.14.9 + org.testng:testng:6.0 + org.testng:testng:6.5.1 + com.google.inject:guice:3.0:jar:no_aop + log4j:log4j:1.2.16 + org.apache.maven.plugins:maven-clean-plugin:2.4.1 + org.apache.maven.plugins:maven-compiler-plugin:2.3.2 + org.apache.maven.plugins:maven-compiler-plugin:2.5.1 + org.apache.maven.plugins:maven-install-plugin:2.3.1 + org.apache.maven.plugins:maven-compiler-plugin:2.0.2 + org.apache.maven.plugins:maven-resources-plugin:2.5 + org.apache.maven.plugins:maven-jar-plugin:2.3.2 + org.apache.commons:commons-email:1.2 + org.codehaus.mojo:build-helper-maven-plugin:1.2 + org.apache.maven.reporting:maven-reporting-api:2.0.9 + commons-collections:commons-collections:3.2 + commons-logging:commons-logging:1.0.4 + xml-apis:xml-apis:1.0.b2 + org.apache.httpcomponents:httpclient:4.0.2 + junit:junit:4.4 + junit:junit:4.5 + junit:junit:4.7 + junit:junit:4.8.1 + junit:junit:4.8.2 + junit:junit:4.11 + junit:junit-dep:4.8 + junit:junit-dep:4.7 + junit:junit-dep:4.4 + org.apache.maven.plugins:maven-surefire-plugin:2.10 + org.apache.maven.surefire:surefire-junit3:2.10 + org.codehaus.plexus:plexus-utils:1.0.4 + org.codehaus.plexus:plexus-utils:1.4.1 + org.codehaus.plexus:plexus-utils:1.5.1 + org.codehaus.plexus:plexus-utils:1.5.8 + org.codehaus.plexus:plexus-utils:1.5.15 + org.mockito:mockito-core:1.8.5 + org.codehaus.plexus:plexus-interpolation:1.12 + @@ -166,7 +220,7 @@ org.apache.maven.surefire surefire-shadefire - ${project.version} + ${shadedVersion} diff --git a/surefire-shadefire/pom.xml b/surefire-shadefire/pom.xml index dcab5575b1..e2df2cbe7f 100644 --- a/surefire-shadefire/pom.xml +++ b/surefire-shadefire/pom.xml @@ -17,14 +17,13 @@ ~ under the License. --> - + 4.0.0 org.apache.maven.surefire surefire - 2.13-SNAPSHOT + 2.16-SNAPSHOT ../pom.xml From bc11f4a349405810db116d86f69686fd21a7fca3 Mon Sep 17 00:00:00 2001 From: Tibor Digana Date: Mon, 1 Jul 2013 01:52:09 +0200 Subject: [PATCH 2/2] pc --- .../pc/AbstractThreadPoolStrategy.java | 111 ++++++ .../maven/surefire/junitcore/pc/Balancer.java | 98 +++++ .../junitcore/pc/InvokerStrategy.java | 61 +++ .../pc/NonSharedThreadPoolStrategy.java | 54 +++ .../junitcore/pc/ParallelComputerBuilder.java | 350 ++++++++++++++++++ .../surefire/junitcore/pc/Scheduler.java | 335 +++++++++++++++++ .../junitcore/pc/SchedulingStrategies.java | 73 ++++ .../junitcore/pc/SchedulingStrategy.java | 105 ++++++ .../pc/SharedThreadPoolStrategy.java | 84 +++++ 9 files changed, 1271 insertions(+) create mode 100644 surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/AbstractThreadPoolStrategy.java create mode 100644 surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/Balancer.java create mode 100644 surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/InvokerStrategy.java create mode 100644 surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/NonSharedThreadPoolStrategy.java create mode 100644 surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/ParallelComputerBuilder.java create mode 100644 surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/Scheduler.java create mode 100644 surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/SchedulingStrategies.java create mode 100644 surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/SchedulingStrategy.java create mode 100644 surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/SharedThreadPoolStrategy.java 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 new file mode 100644 index 0000000000..fea07013ab --- /dev/null +++ b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/AbstractThreadPoolStrategy.java @@ -0,0 +1,111 @@ +package org.apache.maven.surefire.junitcore.pc; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES 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.Collection; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Future; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.atomic.AtomicBoolean; + +/** + * Abstract parallel scheduling strategy in private package. + * The remaining abstract methods have to be implemented differently + * depending if the thread pool is shared with other strategies or not. + * + * @author Tibor Digana (tibor17) + * @since 2.16 + * + * @see SchedulingStrategy + * @see SharedThreadPoolStrategy + * @see NonSharedThreadPoolStrategy + */ +abstract class AbstractThreadPoolStrategy extends SchedulingStrategy { + private final ExecutorService threadPool; + private final Collection> futureResults; + private final AtomicBoolean canSchedule = new AtomicBoolean(true); + + AbstractThreadPoolStrategy(ExecutorService threadPool) { + this(threadPool, null); + } + + AbstractThreadPoolStrategy(ExecutorService threadPool, Collection> futureResults) { + this.threadPool = threadPool; + this.futureResults = futureResults; + } + + protected final ExecutorService getThreadPool() { + return threadPool; + } + + protected final Collection> getFutureResults() { + return futureResults; + } + + protected final void disable() { + canSchedule.set(false); + } + + @Override + public void schedule(Runnable task) { + if (canSchedule()) { + Future futureResult = threadPool.submit(task); + if (futureResults != null) { + futureResults.add(futureResult); + } + } + } + + @Override + protected boolean stop() { + boolean wasRunning = canSchedule.getAndSet(false); + if (threadPool.isShutdown()) { + wasRunning = false; + } else { + threadPool.shutdown(); + } + return wasRunning; + } + + @Override + protected boolean stopNow() { + boolean wasRunning = canSchedule.getAndSet(false); + if (threadPool.isShutdown()) { + wasRunning = false; + } else { + threadPool.shutdownNow(); + } + return wasRunning; + } + + @Override + protected void setDefaultShutdownHandler(Scheduler.ShutdownHandler handler) { + if (threadPool instanceof ThreadPoolExecutor) { + ThreadPoolExecutor pool = (ThreadPoolExecutor) threadPool; + handler.setRejectedExecutionHandler(pool.getRejectedExecutionHandler()); + pool.setRejectedExecutionHandler(handler); + } + } + + @Override + public final boolean canSchedule() { + return canSchedule.get(); + } +} \ No newline at end of file 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 new file mode 100644 index 0000000000..59eed26c53 --- /dev/null +++ b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/Balancer.java @@ -0,0 +1,98 @@ +package org.apache.maven.surefire.junitcore.pc; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES 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.Semaphore; + +/** + * The Balancer controls the maximum of concurrent threads in the current Scheduler(s) and prevents + * from own thread resources exhaustion if other group of schedulers share the same pool of threads. + *

+ * If a permit is available, {@link #acquirePermit()} simply returns and a new test is scheduled + * by {@link Scheduler#schedule(Runnable)} in the current runner. Otherwise waiting for a release. + * One permit is released as soon as the child thread has finished. + * + * @author Tibor Digana (tibor17) + * @since 2.16 + */ +public class Balancer { + private final Semaphore balancer; + private final int maxPermits; + + /** + * Infinite permits. + */ + protected Balancer() { + this(0); + } + + /** + * fair set to false. + * @see #Balancer(int, boolean) + */ + public Balancer(int numPermits) { + this(numPermits, false); + } + + /** + * @param numPermits number of permits to acquire when maintaining concurrency on tests + * @param fair true guarantees the waiting schedulers to wake up in order they acquired a permit + */ + public Balancer(int numPermits, boolean fair) { + boolean maintainTests = numPermits > 0 && numPermits < Integer.MAX_VALUE; + balancer = maintainTests ? new Semaphore(numPermits, fair) : null; + maxPermits = numPermits; + } + + /** + * Acquires a permit from this balancer, blocking until one is available. + * + * @return true if current thread is NOT interrupted + * while waiting for a permit. + */ + public boolean acquirePermit() { + Semaphore balancer = this.balancer; + if (balancer != null) { + try { + balancer.acquire(); + } catch (InterruptedException e) { + return false; + } + } + return true; + } + + /** + * Releases a permit, returning it to the balancer. + */ + public void releasePermit() { + Semaphore balancer = this.balancer; + if (balancer != null) { + balancer.release(); + } + } + + public void releaseAllPermits() { + Semaphore balancer = this.balancer; + if (balancer != null) { + balancer.release(maxPermits); + } + } +} 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 new file mode 100644 index 0000000000..dc1e5b3fe4 --- /dev/null +++ b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/InvokerStrategy.java @@ -0,0 +1,61 @@ +package org.apache.maven.surefire.junitcore.pc; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES 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.atomic.AtomicBoolean; + +/** + * The sequentially executing strategy in private package. + * + * @author Tibor Digana (tibor17) + * @since 2.16 + * + * @see SchedulingStrategy + */ +final class InvokerStrategy extends SchedulingStrategy { + private final AtomicBoolean canSchedule = new AtomicBoolean(true); + + @Override + public void schedule(Runnable task) { + if (canSchedule()) { + task.run(); + } + } + + @Override + protected boolean stop() { + return canSchedule.getAndSet(false); + } + + @Override + public boolean hasSharedThreadPool() { + return false; + } + + @Override + public boolean canSchedule() { + return canSchedule.get(); + } + + @Override + public boolean finished() throws InterruptedException { + 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 new file mode 100644 index 0000000000..b463605f84 --- /dev/null +++ b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/NonSharedThreadPoolStrategy.java @@ -0,0 +1,54 @@ +package org.apache.maven.surefire.junitcore.pc; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES 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.ExecutorService; +import java.util.concurrent.TimeUnit; + +/** + * Parallel strategy for non-shared thread pool in private package. + * + * @author Tibor Digana (tibor17) + * @since 2.16 + * + * @see AbstractThreadPoolStrategy + */ +final class NonSharedThreadPoolStrategy extends AbstractThreadPoolStrategy { + NonSharedThreadPoolStrategy(ExecutorService threadPool) { + super(threadPool); + } + + @Override + public boolean hasSharedThreadPool() { + return false; + } + + @Override + public boolean finished() throws InterruptedException { + boolean wasRunning = canSchedule(); + getThreadPool().shutdown(); + try { + getThreadPool().awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS); + return wasRunning; + } finally { + disable(); + } + } +} 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 new file mode 100644 index 0000000000..67a6d0c0bc --- /dev/null +++ b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/ParallelComputerBuilder.java @@ -0,0 +1,350 @@ +package org.apache.maven.surefire.junitcore.pc; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR 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.internal.runners.ErrorReportingRunner; +import org.junit.runner.Computer; +import org.junit.runner.Description; +import org.junit.runner.Runner; +import org.junit.runner.manipulation.Filter; +import org.junit.runner.manipulation.NoTestsRemainException; +import org.junit.runners.ParentRunner; +import org.junit.runners.Suite; +import org.junit.runners.model.InitializationError; +import org.junit.runners.model.RunnerBuilder; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +/** + * 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. + *

+ * ParallelComputerBuilder builder = new ParallelComputerBuilder();
+ * builder.useOnePool(8).parallelSuites(2).parallelClasses(4).parallelMethods();
+ * ParallelComputerBuilder.ParallelComputer computer = builder.buildComputer();
+ * Class[] tests = {...};
+ * new JUnitCore().run(computer, tests);
+ * 
+ * Note that the type has always at least one thread even if unspecified. The capacity in + * {@link ParallelComputerBuilder#useOnePool(int)} must be greater than the number of concurrent suites and classes altogether. + *

+ * The Computer can be shutdown in a separate thread. Pending tests will be interrupted if the argument is true. + *

+ * computer.shutdown(true);
+ * 
+ * + * @author Tibor Digana (tibor17) + * @since 2.16 + */ +public class ParallelComputerBuilder { + private static enum Type { + SUITES, CLASSES, METHODS + } + + static final int TOTAL_POOL_SIZE_UNDEFINED = 0; + private final Map parallelGroups = new HashMap(3); + private boolean useSeparatePools; + private int totalPoolSize; + + /** + * Calling {@link #useSeparatePools()}. + */ + public ParallelComputerBuilder() { + useSeparatePools(); + parallelGroups.put(Type.SUITES, 0); + parallelGroups.put(Type.CLASSES, 0); + parallelGroups.put(Type.METHODS, 0); + } + + public ParallelComputerBuilder useSeparatePools() { + totalPoolSize = TOTAL_POOL_SIZE_UNDEFINED; + useSeparatePools = true; + return this; + } + + public ParallelComputerBuilder useOnePool() { + totalPoolSize = TOTAL_POOL_SIZE_UNDEFINED; + useSeparatePools = false; + return this; + } + + /** + * @param totalPoolSize Pool size where suites, classes and methods are executed in parallel. + * @throws IllegalArgumentException If totalPoolSize is < 1. + */ + public 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; + } + + public ParallelComputerBuilder parallelSuites() { + return parallel(Type.SUITES); + } + + public ParallelComputerBuilder parallelSuites(int nThreads) { + return parallel(nThreads, Type.SUITES); + } + + public ParallelComputerBuilder parallelClasses() { + return parallel(Type.CLASSES); + } + + public ParallelComputerBuilder parallelClasses(int nThreads) { + return parallel(nThreads, Type.CLASSES); + } + + public ParallelComputerBuilder parallelMethods() { + return parallel(Type.METHODS); + } + + public ParallelComputerBuilder parallelMethods(int nThreads) { + return parallel(nThreads, Type.METHODS); + } + + private ParallelComputerBuilder parallel(int nThreads, Type parallelType) { + if (nThreads < 0) { + throw new IllegalArgumentException("negative nThreads " + nThreads); + } + + if (parallelType == null) { + throw new NullPointerException("null parallelType"); + } + + parallelGroups.put(parallelType, nThreads); + return this; + } + + private ParallelComputerBuilder parallel(Type parallelType) { + return parallel(Integer.MAX_VALUE, parallelType); + } + + public ParallelComputer buildComputer() { + return new ParallelComputer(); + } + + private static class RunnersSuite extends Suite { + protected RunnersSuite(Collection runners) throws InitializationError { + super(null, new ArrayList(runners)); + } + + protected RunnersSuite(Runner... runners) throws InitializationError { + super(null, Arrays.asList(runners)); + } + } + + public final class ParallelComputer extends Computer { + final Collection suites = new ArrayList(); + final Collection nestedSuites = new ArrayList(); + final Collection classes = new ArrayList(); + final Collection nestedClasses = new ArrayList(); + final int poolCapacity; + final boolean splitPool; + private final Map allGroups; + private volatile Scheduler master; + + private ParallelComputer() { + allGroups = new HashMap(ParallelComputerBuilder.this.parallelGroups); + poolCapacity = ParallelComputerBuilder.this.totalPoolSize; + splitPool = ParallelComputerBuilder.this.useSeparatePools; + } + + public Collection shutdown(boolean shutdownNow) { + final Scheduler master = this.master; + return master == null ? Collections.emptyList() : master.shutdown(shutdownNow); + } + + @Override + public Runner getSuite(RunnerBuilder builder, Class[] cls) throws InitializationError { + super.getSuite(builder, cls); + populateChildrenFromSuites(); + return setSchedulers(); + } + + @Override + protected Runner getRunner(RunnerBuilder builder, Class testClass) throws Throwable { + Runner runner = super.getRunner(builder, testClass); + if (canUse(runner)) { + if (runner instanceof Suite) { + suites.add((Suite) runner); + } else { + classes.add((ParentRunner) runner); + } + } + return runner; + } + + private class SuiteFilter extends Filter { + @Override + public boolean shouldRun(Description description) { + return true; + } + + @Override + public void apply(Object child) throws NoTestsRemainException { + super.apply(child); + if (child instanceof Suite) { + nestedSuites.add((Suite) child); + } else if (child instanceof ParentRunner) { + nestedClasses.add((ParentRunner) child); + } + } + + @Override + public String describe() { + return ""; + } + } + + private ExecutorService createPool(int poolSize) { + return poolSize < Integer.MAX_VALUE ? Executors.newFixedThreadPool(poolSize) : Executors.newCachedThreadPool(); + } + + private Scheduler createMaster(ExecutorService pool, int poolSize) { + if (!areSuitesAndClassesParallel() || poolSize <= 1) { + return new Scheduler(null, new InvokerStrategy()); + } else if (pool != null && poolSize == Integer.MAX_VALUE) { + return new Scheduler(null, new SharedThreadPoolStrategy(pool)); + } else { + return new Scheduler(null, SchedulingStrategies.createParallelStrategy(2)); + } + } + + private boolean areSuitesAndClassesParallel() { + return !suites.isEmpty() && allGroups.get(Type.SUITES) > 0 && !classes.isEmpty() && allGroups.get(Type.CLASSES) > 0; + } + + private void populateChildrenFromSuites() { + Filter filter = new SuiteFilter(); + for (Iterator it = suites.iterator(); it.hasNext();) { + Suite suite = it.next(); + try { + suite.filter(filter); + } catch (NoTestsRemainException e) { + it.remove(); + } + } + } + + private int totalPoolSize() { + if (poolCapacity == TOTAL_POOL_SIZE_UNDEFINED) { + int total = 0; + for (int nThreads : allGroups.values()) { + total += nThreads; + if (total < 0) { + total = Integer.MAX_VALUE; + break; + } + } + return total; + } else { + return poolCapacity; + } + } + + private Runner setSchedulers() throws InitializationError { + int parallelSuites = allGroups.get(Type.SUITES); + int parallelClasses = allGroups.get(Type.CLASSES); + int parallelMethods = allGroups.get(Type.METHODS); + int poolSize = totalPoolSize(); + ExecutorService commonPool = splitPool || poolSize == 0 ? null : createPool(poolSize); + master = createMaster(commonPool, poolSize); + + // a scheduler for parallel suites + final Scheduler suitesScheduler; + if (commonPool != null && parallelSuites > 0) { + suitesScheduler = createScheduler(null, commonPool, true, new Balancer(parallelSuites, true)); + } else { + suitesScheduler = createScheduler(parallelSuites); + } + Suite suiteSuites = new RunnersSuite(suites); + suiteSuites.setScheduler(suitesScheduler); + + // schedulers for parallel classes + Suite suiteClasses = new RunnersSuite(classes); + ArrayList allSuites = new ArrayList(suites); + allSuites.addAll(nestedSuites); + allSuites.add(suiteClasses); + setSchedulers(allSuites, parallelClasses, commonPool); + + // schedulers for parallel methods + ArrayList allClasses = new ArrayList(classes); + allClasses.addAll(nestedClasses); + setSchedulers(allClasses, parallelMethods, commonPool); + + // resulting runner for Computer#getSuite() scheduled by master scheduler + Suite all = new RunnersSuite(suiteSuites, suiteClasses); + all.setScheduler(master); + return all; + } + + private void setSchedulers(Iterable runners, int poolSize, ExecutorService commonPool) { + if (commonPool != null) { + Balancer concurrencyLimit = new Balancer(poolSize, true); + boolean doParallel = poolSize > 0; + for (ParentRunner runner : runners) { + runner.setScheduler(createScheduler(runner.getDescription(), commonPool, doParallel, concurrencyLimit)); + } + } else { + ExecutorService pool = null; + if (poolSize == Integer.MAX_VALUE) { + pool = Executors.newCachedThreadPool(); + } else if (poolSize > 0) { + pool = Executors.newFixedThreadPool(poolSize); + } + boolean doParallel = pool != null; + for (ParentRunner runner : runners) { + runner.setScheduler(createScheduler(runner.getDescription(), pool, doParallel, new Balancer())); + } + } + } + + private Scheduler createScheduler(Description desc, ExecutorService pool, boolean doParallel, Balancer concurrency) { + doParallel &= pool != null; + SchedulingStrategy strategy = doParallel ? new SharedThreadPoolStrategy(pool) : new InvokerStrategy(); + return new Scheduler(desc, master, strategy, concurrency); + } + + private Scheduler createScheduler(int poolSize) { + if (poolSize == Integer.MAX_VALUE) { + return new Scheduler(null, master, SchedulingStrategies.createParallelStrategyUnbounded()); + } else if (poolSize == 0) { + return new Scheduler(null, master, new InvokerStrategy()); + } else { + return new Scheduler(null, master, SchedulingStrategies.createParallelStrategy(poolSize)); + } + } + + private boolean canUse(Runner runner) { + return !(runner instanceof ErrorReportingRunner) && runner instanceof ParentRunner; + } + } +} 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 new file mode 100644 index 0000000000..241c71bd97 --- /dev/null +++ b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/Scheduler.java @@ -0,0 +1,335 @@ +package org.apache.maven.surefire.junitcore.pc; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR 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.runners.model.RunnerScheduler; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Set; +import java.util.concurrent.CopyOnWriteArraySet; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.RejectedExecutionHandler; +import java.util.concurrent.ThreadPoolExecutor; + +/** + * + * Schedules tests, controls thread resources, awaiting tests and other schedulers finished, and + * a master scheduler can shutdown slaves. + *

+ * The scheduler objects should be first created (and wired) and set in runners + * {@link org.junit.runners.ParentRunner#setScheduler(org.junit.runners.model.RunnerScheduler)}. + *

+ * A new instance of scheduling strategy should be passed to the constructor of this scheduler. + * + * @author Tibor Digana (tibor17) + * @since 2.16 + */ +public class Scheduler implements RunnerScheduler { + private final Balancer balancer; + private final SchedulingStrategy strategy; + private final Set slaves = new CopyOnWriteArraySet(); + private final Description description; + private volatile boolean shutdown = false; + private volatile boolean started = false; + private volatile Controller masterController; + + /** + * Use e.g. parallel classes have own non-shared thread pool, and methods another pool. + *

+ * You can use it with one infinite thread pool shared in strategies across all + * suites, class runners, etc. + */ + public Scheduler(Description description, SchedulingStrategy strategy) { + this(description, strategy, -1); + } + + /** + * Should be used if schedulers in parallel children and parent use one instance of bounded thread pool. + *

+ * Set this scheduler in a e.g. one suite of classes, then every individual class runner should reference + * {@link #Scheduler(org.junit.runner.Description, Scheduler, SchedulingStrategy)} + * or {@link #Scheduler(org.junit.runner.Description, Scheduler, SchedulingStrategy, int)}. + * + * @param description description of current runner + * @param strategy scheduling strategy with a shared thread pool + * @param concurrency determines maximum concurrent children scheduled a time via {@link #schedule(Runnable)} + * @throws NullPointerException if null strategy + */ + public Scheduler(Description description, SchedulingStrategy strategy, int concurrency) { + this(description, strategy, new Balancer(concurrency)); + } + + /** + * New instances should be used by schedulers with limited concurrency by balancer + * against other groups of schedulers. The schedulers share one pool. + *

+ * Unlike in {@link #Scheduler(org.junit.runner.Description, SchedulingStrategy, int)} which was limiting + * the concurrency of children of a runner where this scheduler was set, this balancer + * is limiting the concurrency of all children in runners having schedulers created by this constructor. + * + * @param description description of current runner + * @param strategy scheduling strategy which may share threads with other strategy + * @param balancer determines maximum concurrent children scheduled a time via {@link #schedule(Runnable)} + * @throws NullPointerException if null strategy or balancer + */ + public Scheduler(Description description, SchedulingStrategy strategy, Balancer balancer) { + strategy.setDefaultShutdownHandler(newShutdownHandler()); + this.description = description; + this.strategy = strategy; + this.balancer = balancer; + masterController = null; + } + /** + * Can be used by e.g. a runner having parallel classes in use case with parallel + * suites, classes and methods sharing the same thread pool. + * + * @param description description of current runner + * @param masterScheduler scheduler sharing own threads with this slave + * @param strategy scheduling strategy for this scheduler + * @param balancer determines maximum concurrent children scheduled a time via {@link #schedule(Runnable)} + * @throws NullPointerException if null masterScheduler, strategy or balancer + */ + public Scheduler(Description description, Scheduler masterScheduler, SchedulingStrategy strategy, Balancer balancer) { + this(description, strategy, balancer); + strategy.setDefaultShutdownHandler(newShutdownHandler()); + masterScheduler.register(this); + } + + /** + * @param masterScheduler a reference to {@link #Scheduler(org.junit.runner.Description, SchedulingStrategy, int)} + * or {@link #Scheduler(org.junit.runner.Description, SchedulingStrategy)} + * @see #Scheduler(org.junit.runner.Description, SchedulingStrategy) + * @see #Scheduler(org.junit.runner.Description, SchedulingStrategy, int) + */ + public Scheduler(Description description, Scheduler masterScheduler, SchedulingStrategy strategy, int concurrency) { + this(description, strategy, concurrency); + strategy.setDefaultShutdownHandler(newShutdownHandler()); + masterScheduler.register(this); + } + + /** + * Should be used with individual pools on suites, classes and methods, see + * {@link org.apache.maven.surefire.junitcore.pc.ParallelComputerBuilder#useSeparatePools()}. + *

+ * Cached thread pool is infinite and can be always shared. + */ + public Scheduler(Description description, Scheduler masterScheduler, SchedulingStrategy strategy) { + this(description, masterScheduler, strategy, 0); + } + + private void setController(Controller masterController) { + if (masterController == null) { + throw new NullPointerException("null ExecutionController"); + } + this.masterController = masterController; + } + + /** + * @param slave a slave scheduler to register + * @return true if successfully registered the 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); + } + } + return canRegister; + } + + /** + * @return true if new tasks can be scheduled. + */ + private boolean canSchedule() { + return !shutdown && (masterController == null || masterController.canSchedule()); + } + + protected void logQuietly(Throwable t) { + t.printStackTrace(System.err); + } + + protected void logQuietly(String msg) { + System.err.println(msg); + } + + /** + * Attempts to stop all actively executing tasks and immediately returns a collection + * of descriptions of those tasks which have started prior to this call. + *

+ * This scheduler and other registered schedulers will shutdown, see {@link #register(Scheduler)}. + * If shutdownNow is set, waiting methods will cancel via {@link Thread#interrupt}. + * + * @param shutdownNow if true interrupts waiting methods + * @return collection of descriptions started before shutting down + */ + public Collection shutdown(boolean shutdownNow) { + shutdown = true; + ArrayList activeChildren = new ArrayList(); + + if (started && description != null) { + activeChildren.add(description); + } + + for (Controller slave : slaves) { + try { + activeChildren.addAll(slave.shutdown(shutdownNow)); + } catch (Throwable t) { + logQuietly(t); + } + } + + try { + balancer.releaseAllPermits(); + } finally { + if (shutdownNow) { + strategy.stopNow(); + } else { + strategy.stop(); + } + } + + return activeChildren; + } + + protected void beforeExecute() { + } + + protected void afterExecute() { + } + + public void schedule(Runnable childStatement) { + if (childStatement == null) { + logQuietly("cannot schedule null"); + } else if (canSchedule() && strategy.canSchedule()) { + try { + balancer.acquirePermit(); + Runnable task = wrapTask(childStatement); + strategy.schedule(task); + started = true; + } catch (RejectedExecutionException e) { + shutdown(false); + } catch (Throwable t) { + balancer.releasePermit(); + logQuietly(t); + } + } + } + + public void finished() { + try { + strategy.finished(); + } catch (InterruptedException e) { + logQuietly(e); + } finally { + for (Controller slave : slaves) { + slave.awaitFinishedQuietly(); + } + } + } + + private Runnable wrapTask(final Runnable task) { + return new Runnable() { + public void run() { + try { + beforeExecute(); + task.run(); + } finally { + try { + afterExecute(); + } finally { + balancer.releasePermit(); + } + } + } + }; + } + + 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 Scheduler slave; + + private Controller(Scheduler slave) { + this.slave = slave; + } + + /** + * @return true if new children can be scheduled. + */ + boolean canSchedule() { + return Scheduler.this.canSchedule(); + } + + void awaitFinishedQuietly() { + try { + slave.finished(); + } catch(Throwable t) { + slave.logQuietly(t); + } + } + + Collection shutdown(boolean shutdownNow) { + return slave.shutdown(shutdownNow); + } + + @Override + public int hashCode() { + return slave.hashCode(); + } + + @Override + public boolean equals(Object o) { + return o == this || (o instanceof Controller) && slave.equals(((Controller) o).slave); + } + } + + public class ShutdownHandler implements RejectedExecutionHandler { + private volatile RejectedExecutionHandler poolHandler; + + protected ShutdownHandler() { + poolHandler = null; + } + + public void setRejectedExecutionHandler(RejectedExecutionHandler poolHandler) { + this.poolHandler = poolHandler; + } + + public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { + if (executor.isShutdown()) { + shutdown(false); + } + final RejectedExecutionHandler poolHandler = this.poolHandler; + 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 new file mode 100644 index 0000000000..4d3c6a6484 --- /dev/null +++ b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/SchedulingStrategies.java @@ -0,0 +1,73 @@ +package org.apache.maven.surefire.junitcore.pc; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES 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.ExecutorService; +import java.util.concurrent.Executors; + +/** + * The factory of {@link SchedulingStrategy}. + * + * @author Tibor Digana (tibor17) + * @since 2.16 + */ +public class SchedulingStrategies { + + /** + * @return sequentially executing strategy + */ + public static SchedulingStrategy createInvokerStrategy() { + return new InvokerStrategy(); + } + + /** + * @param nThreads fixed pool capacity + * @return parallel scheduling strategy + */ + public static SchedulingStrategy createParallelStrategy(int nThreads) { + return new NonSharedThreadPoolStrategy(Executors.newFixedThreadPool(nThreads)); + } + + /** + * @return parallel scheduling strategy with unbounded capacity + */ + public static SchedulingStrategy createParallelStrategyUnbounded() { + return new NonSharedThreadPoolStrategy(Executors.newCachedThreadPool()); + } + + /** + * The threadPool passed to this strategy can be shared in other strategies. + *

+ * The call {@link SchedulingStrategy#finished()} is waiting until own tasks have finished. + * New tasks will not be scheduled by this call in this strategy. This strategy is not + * waiting for other strategies to finish. The {@link org.junit.runners.model.RunnerScheduler#finished()} may + * freely use {@link SchedulingStrategy#finished()}. + * + * @param threadPool thread pool possibly shared with other strategies + * @return parallel strategy with shared thread pool + * @throws NullPointerException if threadPool is null + */ + public static SchedulingStrategy createParallelSharedStrategy(ExecutorService threadPool) { + if (threadPool == null) { + throw new NullPointerException("null threadPool in #createParallelSharedStrategy"); + } + return new SharedThreadPoolStrategy(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 new file mode 100644 index 0000000000..c9da764b68 --- /dev/null +++ b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/SchedulingStrategy.java @@ -0,0 +1,105 @@ +package org.apache.maven.surefire.junitcore.pc; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR 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.runners.model.RunnerScheduler; + +import java.util.concurrent.RejectedExecutionException; + +/** + * Specifies the strategy of scheduling whether sequential, or parallel. + * The strategy may use a thread pool shared with other strategies. + *

+ * One instance of strategy can be used just by one {@link Scheduler}. + *

+ * The strategy is scheduling tasks in {@link #schedule(Runnable)} and awaiting them + * completed in {@link #finished()}. Both methods should be used in one thread. + * + * @author Tibor Digana (tibor17) + * @since 2.16 + */ +public abstract class SchedulingStrategy { + + /** + * Schedules tasks if {@link #canSchedule()}. + * + * @param task runnable to schedule in a thread pool or invoke + * @throws RejectedExecutionException if task + * cannot be scheduled for execution + * @throws NullPointerException if task is null + * @see RunnerScheduler#schedule(Runnable) + * @see java.util.concurrent.Executor#execute(Runnable) + */ + protected abstract void schedule(Runnable task); + + /** + * Waiting for scheduled tasks to finish. + * New tasks will not be scheduled by calling this method. + * + * @return true if successfully stopped the scheduler, else + * false if already stopped (a shared thread + * pool was shutdown externally). + * @throws InterruptedException if interrupted while waiting + * for scheduled tasks to finish + * @see RunnerScheduler#finished() + */ + protected abstract boolean finished() throws InterruptedException; + + /** + * Stops scheduling new tasks (e.g. by {@link java.util.concurrent.ExecutorService#shutdown()} + * on a private thread pool which cannot be shared with other strategy). + * + * @return true if successfully stopped the scheduler, else + * false if already stopped (a shared thread + * pool was shutdown externally). + * @see java.util.concurrent.ExecutorService#shutdown() + */ + protected abstract boolean stop(); + + /** + * Stops scheduling new tasks and interrupts running tasks + * (e.g. by {@link java.util.concurrent.ExecutorService#shutdownNow()} on a private thread pool + * which cannot be shared with other strategy). + *

+ * This method calls {@link #stop()} by default. + * + * @return true if successfully stopped the scheduler, else + * false if already stopped (a shared thread + * pool was shutdown externally). + * @see java.util.concurrent.ExecutorService#shutdownNow() + */ + protected boolean stopNow() { + return stop(); + } + + protected void setDefaultShutdownHandler(Scheduler.ShutdownHandler handler) { + } + + /** + * @return true if a thread pool associated with this strategy + * can be shared with other strategies. + */ + protected abstract boolean hasSharedThreadPool(); + + /** + * @return true unless stopped or finished. + */ + protected abstract boolean canSchedule(); +} 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 new file mode 100644 index 0000000000..53082c424e --- /dev/null +++ b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/SharedThreadPoolStrategy.java @@ -0,0 +1,84 @@ +package org.apache.maven.surefire.junitcore.pc; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES 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.CancellationException; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Future; + +/** + * Parallel strategy for shared thread pool in private package. + * + * @author Tibor Digana (tibor17) + * @since 2.16 + * + * @see AbstractThreadPoolStrategy + */ +final class SharedThreadPoolStrategy extends AbstractThreadPoolStrategy { + SharedThreadPoolStrategy(ExecutorService threadPool) { + super(threadPool, new ConcurrentLinkedQueue>()); + } + + @Override + public boolean hasSharedThreadPool() { + return true; + } + + @Override + public boolean finished() throws InterruptedException { + boolean wasRunningAll = canSchedule(); + for (Future futureResult : getFutureResults()) { + try { + futureResult.get(); + } catch (InterruptedException e) { + // after called external ExecutorService#shutdownNow() + // or ExecutorService#shutdown() + wasRunningAll = false; + } catch (ExecutionException e) { + // test throws exception + } catch (CancellationException e) { + // cannot happen because not calling Future#cancel() + } + } + disable(); + return wasRunningAll; + } + + @Override + protected final boolean stop() { + return stop(false); + } + + @Override + protected final boolean stopNow() { + return stop(true); + } + + private boolean stop(boolean interrupt) { + final boolean wasRunning = canSchedule(); + for (Future futureResult : getFutureResults()) { + futureResult.cancel(interrupt); + } + disable(); + return wasRunning; + } +} \ No newline at end of file