diff --git a/.editorconfig b/.editorconfig deleted file mode 100644 index 5835e01f..00000000 --- a/.editorconfig +++ /dev/null @@ -1,17 +0,0 @@ -# -# This is a generic editor configuration file, supported -# by many editors (directly or via plugins). -# -# See http://editorconfig.org for more information. -# - -root = true - -[*] -charset = UTF-8 - -[*.{java}] -charset = UTF-8 -end_of_line = lf -indent_style = space -indent_size = 2 diff --git a/.gitignore b/.gitignore index 8a70852c..41683ecd 100644 --- a/.gitignore +++ b/.gitignore @@ -1,14 +1,10 @@ -# Eclipse -target/ -.project -.classpath -.settings - -# IntelliJ -.idea -*.iml - -# Maven -*.versionsBackup -*.swp -*~ +# Ignore Gradle project-specific cache directory +.gradle + +# Ignore Gradle build output directory +build/ + +# Intellij +.idea/ +*.iml +out/ diff --git a/CHANGES.txt b/CHANGES.txt deleted file mode 100644 index 39694337..00000000 --- a/CHANGES.txt +++ /dev/null @@ -1,406 +0,0 @@ - -RandomizedTesting, Change Log -============================= - -For an up-to-date CHANGES file see -https://github.com/randomizedtesting/randomizedtesting/blob/master/CHANGES - -======================= randomizedtesting 2.7.9-SNAPSHOT ==================== - -Other: - - * Update JUnit dependency to 4.13.1. - - * Update Ant dependency to 1.9.15. - -======================= randomizedtesting 2.7.8 ==================== - -Improvements - - * GH-289: Bump asm to 8.0.1. - - * PR-287: Bump dom4j from 2.1.1 to 2.1.3. - -======================= randomizedtesting 2.7.7 ==================== - -Bug Fixes - - * GH-283: RandomizedRunner throws `NoTestsRemainException` from the - constructor when method filter is supplied and no methods match - (Mark Vieira). - -======================= randomizedtesting 2.7.6 ==================== - -Improvements - - * Use thread join internally to wait for forked timeouting test thread - instead of a hardcoded sleep (dumb!). - -======================= randomizedtesting 2.7.5 ==================== - -Improvements - - * Switch to simple-xml-safe. - - * throw NoTestsRemainException if Filterable.filter removes all tests. - -======================= randomizedtesting 2.7.4 ==================== - -Bug Fixes - - * GH-280: Potential race condition in global temp folder generation. - - -======================= randomizedtesting 2.7.3 ==================== - -Bug Fixes - - * GH-276: Annotations on overriden methods are not picked up (annotations - on overrides of @Test methods are not picked up). - -======================= randomizedtesting 2.7.2 ==================== - -Bug Fixes - - * GH-275: Timeouts can deadlock on trying to interrupt leaked threads. - -Improvements - - * GH-274: PrintEventListener should emit display name if method name - is not available in testIgnored callback. - -======================= randomizedtesting 2.7.1 ==================== - -Bug Fixes - - * GH-271: Methods with ( or ) in them can't be selected directly using - glob filters. - -======================= randomizedtesting 2.7.0 ==================== - -Bug Fixes - - * GH-269: 2.6.x runners and junit 4.12 show much noise for a single - test method in IntellJ Idea (thanks Vladimir Dolzhenko). - -Changes in Backwards Compatibility - - * GH-270: Upgrade to support JUnit 4.12. This also means that Hamcrest - is required (as JUnit 4.12 uses it). - -======================= randomizedtesting 2.6.4 ==================== - -Bug Fixes - - * GH-247: Allow java.io.tmpdir to be placed under cwd with isolated - directories and nonEmptyWorkDirAction=wipe. - - * GH-255: Invalid event nesting on security logging crashes the runner. - - * GH-266: QUIT event may not be read from the event log on slow machines. - - * GH-267: Project does not build/ test on Java 11. - -Improvements - - * An additional property 'junit4.tempDir' is passed to forked JVMs to allow - easier configuration of security policy files. This folder must have - read/ write file policy. - - * Added a test case that runs with a security manager enabled. - - * GH-253: IntelliJ only recognizes proper test methods for re-runs - when descriptions have " [...]" instead of " {...}. This fix uses square - brackets on IntelliJ runner. - -Changes in Backwards Compatibility - - * GH-265: Deprecate RandomizedTest.randomInt(v) and RandomizedTest.randomLong(v). - -======================= randomizedtesting 2.6.3 ==================== - -Bug Fixes - - * GH-263: event bus dispatch error (covariant incompatibility due to - jdk 9 compilation to java 8 bytecode). - -======================= randomizedtesting 2.6.2 ==================== - -New Features - - * GH-261: Ant and Maven runner can specify external JUnit 4 RunListeners. - (Steven Zaluk) - -======================= randomizedtesting 2.6.1 ==================== - -Bug Fixes - - * GH-260: maven plugin should use dom4j 2.0.2 (avoids illegal access warnings - under Java 9 and later). - -======================= randomizedtesting 2.6.0 ==================== - -Changes in Backwards Compatibility - - * GH-259: Java 1.8 is now the minimum supported JRE. - - * GH-258: add support for parsing class files compiled into Java 9 or - Java 10 bytecode. - -======================= randomizedtesting 2.5.3 ==================== - -Bug Fixes - - * GH-251: Fixes test case filtering in IDEs (IntelliJ, Eclipse). The tests - are now filtered out eagerly from the returned suite's Description and - don't show in the user interface at all. This also applies to - -Dtests.method=... patterns. (Mike Sokolov via Dawid Weiss) - -======================= randomizedtesting 2.5.2 ==================== - -Bug Fixes - - * GH-250: Non-bootstrapped ForkedJvmInfo causes NullPointerExceptions - (can happen on slow machines with low heartbeat setting). - (Doug Turnbull via Dawid Weiss). - -======================= randomizedtesting 2.5.1 ==================== - -Changes in Backwards Compatibility - - * GH-248: Cleaning up some confusion on RandomizedTest.randomAscii* and - RandomStrings.randomAscii* methods. These methods generated - random strings based on letters from the Unicode basic latin block (C0). - All these methods are now deprecated and will be removed in favor of - more explicit methods that tell exactly (?) what kind of letters are - involved (Ryan Ernst, Dawid Weiss). For details, see: - - RandomStrings.randomAsciiLettersOfLength(..) - RandomStrings.randomAsciiLettersOfLengthBetween(..) - RandomStrings.randomAsciiAlphanumOfLength(..) - RandomStrings.randomAsciiAlphanumOfLengthBetween(..) - -======================= randomizedtesting 2.5.0 ==================== - -Changes in Backwards Compatibility - - * GH-243: Switches from File to NIO (Path) APIs in a few places may result - in slightly different runner's behavior (on exceptional conditions). - - * GH-244: the new onNonEmptyWorkDirectory attribute's default value is - 'fail' which may break existing builds that have garbage in work directories - of forked JVMs. Change explicitly to any of the alternatives ('ignore' or - 'wipe') or fix your build to wipe the temporary folders yourself. - - * GH-246: RequireAssertionsRule enforcement optional (consistent with - "-Dtests.asserts"); explicit target class is also required. (Dawid Weiss) - -New Features - - * GH-244: A new attribute "onNonEmptyWorkDirectory" controls the action to - take on non-empty initial work directory (for isolated JVMs). (Dawid Weiss) - -Bug Fixes - -Other Changes - - * GH-246: RequireAssertionsRule enforcement optional (consistent with - "-Dtests.asserts"); explicit target class is also required. (Dawid Weiss) - - * GH-243: Switches from File to NIO (Path) APIs in a few places in the ANT - runner. Improved messages concerning non-empty temporary JVM folder - (both initially and at the end of the tests' run). (Dawid Weiss) - - * GH-245: Integrate Forbidden-APIs check and fix follow-up issues. - (Dawid Weiss) - -======================= randomizedtesting 2.4.1 ==================== - -New Features - - * GH-240: Add RandomPicks.randomFrom on primitive arrays. (Dawid Weiss) - -Bug Fixes - - * GH-242: RandomizedTest.nextTempName uses locale-sensitive String.format. - (Dawid Weiss) - -======================= randomizedtesting 2.4.0 ==================== - -Changes in Backwards Compatibility - - * GH-237: Methods previously found in RandomInts have been moved to - RandomNumbers. (Dawid Weiss) - - * GH-234: Run strict validation (thread-ownership, lifecycle) in - AssertingRandom only with assertions enabled. This change means that running - without -ea will from now on ignore the fact that random context's Random - instance is shared where it shouldn't be. On the other hand, any - additional memory barriers can be now avoided, in particular when used in - conjunction with @TestContextRandomSupplier (see GH-235 below). - - To enable consistent checking, enable assertions selectively (for - com.carrotsearch.randomizedtesting package only). (Dawid Weiss) - - * GH-229: The default implementation of the Random instance returned from - the randomization context has been changed to Xoroshiro128P, details here: - http://xoroshiro.di.unimi.it/ - - The returned Random isn't synchronized and should yield much better - pseudo-random sequences than the default Java's Random. (Dawid Weiss) - -New Features - - * GH-238: Add BiasedNumbers (random selection with bias towards "evil" - numbers, in particular floats) as an alternative to RandomNumbers. - (Dawid Weiss) - - * GH-237: Rename RandomInts to RandomNumbers and add methods operating - on longs. (Dawid Weiss). - - * GH-235: A new class annotation was added: @TestContextRandomSupplier allows - declaring a custom class (RandomSupplier) that supplies a Random for the given - seed. This supplier can return any Random instance for the given initial - seed (secure random, faster-than-jdk random, non-random random...). - (Dawid Weiss) - -Bug Fixes - - * GH-233: some adjustments and refactorings in an attempt to avoid deadlocks - on suite timeouts. Very hard to reproduce (i.e., impossible) and some very - odd stack traces too. (Dawid Weiss) - -Other Changes - - * GH-232: Rework reporting of ignored, assumption-ignored, - filtering-expression ignored tests. (Dawid Weiss) - - * GH-218: There are some internal changes in handling @Nightly annotation. - The support for @Nightly is now provided via GroupEvaluator (and this - class is now public, with methods allowing inspection of whether a test - would be filtered out or not). (Dawid Weiss) - -======================= randomizedtesting 2.3.4 ==================== - -Bug Fixes - - * GH-227: Static leak detector should print the "original" field in the - test class that lead to ram usage tester failure (PR #227, Uwe Schindler) - -======================= randomizedtesting 2.3.3 ==================== - -Bug Fixes - - * GH-225: Maven mojo's additionalClasspathElements option only adds - empty strings to classpath. (@Anaros via Dawid Weiss). - -======================= randomizedtesting 2.3.2 ==================== - -Changes in Backwards Compatibility - - * GH-222: Make unexpected JVM output available to listeners. This issue - makes JVM output available to ANT JUnit4's listeners so that they can - log it properly. Previously the JVM output was copied to System.out - which could be hard to work with. See TextReport.onJvmOutput for - an example. The default value of 'jvmOutputAction' has been changed - from 'pipe, warn' to 'listeners, warn' so that listeners get - notified about JVM output instead of it being copied directly to - sysout. (Dawid Weiss, Ryan Ernst). - -Other Changes - - * GH-220: Add an indication of the number of failed suites so far to text - report. (Dawid Weiss, Chris Hostetter). - - * GH-224: Remove excess use of Guava's collections. (Dawid Weiss) - - * GH-221: Upgrade to Guava 19.0-rc3. (Dawid Weiss, Ryan Ernst) - -Bug Fixes - - * PR #223: Access private fields within doPrivileged (Robert Muir) - -======================= randomizedtesting 2.3.1 ==================== - -New Features - - * GH-219: Add randomBytes generator utility. (Dawid Weiss) - - * GH-190: RandomizedContext should provide the current test - case method (via RandomizedContext.current().getTargetMethod()). - (Dawid Weiss) - - * GH-217: Permit running tests on the same instance of the suite - class via TestCaseInstanceProvider annotation. See - Test018TestCaseInstanceProviders example. (Dawid Weiss). - -======================= randomizedtesting 2.3.0 ==================== - -New Features - - * GH-216: Custom test case argument formatters in parameter factories. - See ParametersFactory.argumentFormatting and Test007ParameterizedTests - example. (Dawid Weiss). - - * GH-194: Flexible test case ordering via the new annotation - (TestCaseOrdering). (Dawid Weiss) - -Bug Fixes - - * GH-215: In certain cases test case names could be duplicated (be - identical), which could confuse IDEs. (Dawid Weiss) - -======================= randomizedtesting 2.2.0 ==================== - -Changes in Backwards Compatibility - - * PR #178: Move to Java 1.7 and use the java NIO 2 API for temp files. - (Simon Willnauer) - - * GH-184: RandomizedTest should not extend Assert. This permits easier use - of other frameworks (like assertj) via static imports without naming conflicts. - (Olivier Bourgain, Dawid Weiss) - -New Features - - * GH-191: "Tests with failures" should repeat the master seed at the end - of the report. (Dawid Weiss) - -Bug Fixes - - * GH-192: Reworked json streaming to get rid of gson and permit dumping - JVM-related diagnostics (security manager policy dumps, etc.). - (Dawid Weiss) - - * GH-206: Potential NPE in checking getDefaultUncaughtExceptionHandler. - (Dawid Weiss) - -Other Changes - - * GH-210: Make RR compilable/ testable under Java 1.9. (Dawid Weiss) - - * GH-209: Remove dependency on commons-io. (Dawid Weiss) - - * GH-204: modernize and clean up project layout. (Dawid Weiss) - -======================= randomizedtesting 2.1.17 ============================ - -Bug Fixes - - * GH-201: Tests still running (and zombified) after suite timeout occurred. - (Dawid Weiss) - -Other Changes - - * GH-205: Report test seed in halt on failure message. (Dawid Weiss) - - * GH-203: report the number of completely ignored suites - in the summary. (Dawid Weiss) - - * PR #202: support running with security manager and limit the required - permissions. (Robert Muir) - -======================= randomizedtesting (pre 2.2.0) ======================= - -No separate changelog was maintained. See git commit history or issues at -GitHub. diff --git a/CONTRIBUTING.txt b/CONTRIBUTING.txt deleted file mode 100644 index aecc89d4..00000000 --- a/CONTRIBUTING.txt +++ /dev/null @@ -1,9 +0,0 @@ -Contributions are welcome! - -If you use Eclipse, set up project formatting and -validation with: - -mvn -Peclipse - -If you don't use Eclipse, try to adhere to the -existing coding standard. diff --git a/LICENSE.txt b/LICENSE.txt deleted file mode 100644 index be012db7..00000000 --- a/LICENSE.txt +++ /dev/null @@ -1,202 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright 2011--, Carrot Search s.c. - - 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. \ No newline at end of file diff --git a/README.txt b/README.txt deleted file mode 100644 index 03be9fe4..00000000 --- a/README.txt +++ /dev/null @@ -1,15 +0,0 @@ - -RANDOMIZED TESTING -================== - -JUnit test runner and plugins for running JUnit tests -with pseudo-randomness. - -See the following for more information: - Docs: https://github.com/randomizedtesting/randomizedtesting/wiki - Bugs: https://github.com/randomizedtesting/randomizedtesting/issues - CI: http://builds.carrot2.org/browse/RNDTEST - -See LICENSE.txt to make your company's lawyer happy. - -See CHANGES.txt for API changes and updates. diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 00000000..c02cb26c --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,31 @@ +plugins { + id("base") + + id("com.diffplug.spotless").version("5.14.2").apply(false) + id("de.thetaphi.forbiddenapis").version("3.1").apply(false) + + id("com.carrotsearch.gradle.randomizedtesting").version("0.0.5").apply(false) +} + +allprojects { + repositories { + mavenLocal() + mavenCentral() + } +} + +with(rootProject) { + version = "3.0.0-SNAPSHOT" + description = "RandomizedTesting JUnit5 framework" + + apply(from = "gradle/ide/idea.gradle") +} + +subprojects { + plugins.withType { + configure { + sourceCompatibility = JavaVersion.VERSION_11 + targetCompatibility = sourceCompatibility + } + } +} diff --git a/core/build.gradle.kts b/core/build.gradle.kts new file mode 100644 index 00000000..c8ab96ba --- /dev/null +++ b/core/build.gradle.kts @@ -0,0 +1,16 @@ + +plugins { + id("java-library") +} + +dependencies { + api("org.junit.platform:junit-platform-engine:1.7.2") + api("org.junit.jupiter:junit-jupiter-api:5.7.2") + implementation("org.junit.jupiter:junit-jupiter-engine:5.7.2") + + // testRuntimeOnly("org.junit.platform:junit-platform-launcher:1.7.2") +} + +tasks.withType { + useJUnitPlatform() +} \ No newline at end of file diff --git a/core/src/main/java/com/carrotsearch/randomizedtesting/api/Randomized.java b/core/src/main/java/com/carrotsearch/randomizedtesting/api/Randomized.java new file mode 100644 index 00000000..1fbf20fe --- /dev/null +++ b/core/src/main/java/com/carrotsearch/randomizedtesting/api/Randomized.java @@ -0,0 +1,12 @@ +package com.carrotsearch.randomizedtesting.api; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Inherited; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.METHOD, ElementType.TYPE}) +@Inherited +public @interface Randomized {} diff --git a/core/src/main/java/com/carrotsearch/randomizedtesting/api/RandomizedContext.java b/core/src/main/java/com/carrotsearch/randomizedtesting/api/RandomizedContext.java new file mode 100644 index 00000000..11b4304d --- /dev/null +++ b/core/src/main/java/com/carrotsearch/randomizedtesting/api/RandomizedContext.java @@ -0,0 +1,69 @@ +package com.carrotsearch.randomizedtesting.api; + +import com.carrotsearch.randomizedtesting.extensions.RandomSeed; +import com.carrotsearch.randomizedtesting.extensions.SeedChain; +import com.carrotsearch.randomizedtesting.internal.Threads; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Locale; +import java.util.Random; +import java.util.function.LongUnaryOperator; + +public class RandomizedContext { + private final Thread owner; + private final RandomSeed seed; + private final RandomizedContext parent; + private final Random random; + + public RandomizedContext(Thread owner, RandomSeed seed) { + this(null, owner, seed); + } + + private RandomizedContext(RandomizedContext parent, Thread owner, RandomSeed seed) { + this.owner = owner; + this.seed = seed; + this.random = new Random(seed.value); + this.parent = parent; + } + + @Override + public String toString() { + return "Randomized context [" + + ("seedChain=" + getSeedChain()) + + "," + + ("thread=" + Threads.threadName(owner)) + + "]"; + } + + public SeedChain getSeedChain() { + ArrayList seeds = new ArrayList<>(); + for (RandomizedContext c = this; c != null; c = c.getParent()) { + seeds.add(c.seed); + } + Collections.reverse(seeds); + return new SeedChain(seeds); + } + + private RandomizedContext getParent() { + return parent; + } + + public RandomizedContext fork(Thread forThread, LongUnaryOperator initialSeedFunction) { + long initSeed = initialSeedFunction.applyAsLong(getRandom().nextLong()); + return new RandomizedContext(this, forThread, new RandomSeed(initSeed)); + } + + public Random getRandom() { + if (Thread.currentThread() != owner) { + throw new RuntimeException( + String.format( + Locale.ROOT, + "%s instance is bound to thread %s, can't access it from thread: %s", + RandomizedContext.class.getName(), + owner, + Thread.currentThread())); + } + return random; + } +} diff --git a/core/src/main/java/com/carrotsearch/randomizedtesting/extensions/ExtensionExecutionContext.java b/core/src/main/java/com/carrotsearch/randomizedtesting/extensions/ExtensionExecutionContext.java new file mode 100644 index 00000000..d2858870 --- /dev/null +++ b/core/src/main/java/com/carrotsearch/randomizedtesting/extensions/ExtensionExecutionContext.java @@ -0,0 +1,80 @@ +package com.carrotsearch.randomizedtesting.extensions; + +import com.carrotsearch.randomizedtesting.api.RandomizedContext; +import org.junit.jupiter.api.extension.ExtensionContext; + +import java.util.ArrayDeque; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.atomic.AtomicLong; + +public class ExtensionExecutionContext { + /** + * A sequencer for affecting the initial seed in case of rapid succession of this class instance + * creations. Not likely, but can happen two could get the same seed. + */ + private static final AtomicLong sequencer = new AtomicLong(); + + private final List seedList; + private final ArrayDeque> contextStack = new ArrayDeque<>(); + + public ExtensionExecutionContext(List seedList) { + assert seedList.size() >= 1; + this.seedList = seedList; + } + + public void pop(ExtensionContext ctx) { + var key = getKey(ctx); + if (contextStack.isEmpty() || !contextStack.peekLast().getKey().equals(key)) { + throw new AssertionError("No context or incorrect context for key: " + key); + } + contextStack.removeLast(); + } + + private String getKey(ExtensionContext ctx) { + return ctx.getUniqueId(); + } + + public RandomizedContext getContext(ExtensionContext ctx) { + var key = getKey(ctx); + if (contextStack.isEmpty() || !contextStack.peekLast().getKey().equals(key)) { + throw new AssertionError("No context or incorrect context for key: " + key); + } + return contextStack.peekLast().getValue(); + } + + public void push(ExtensionContext extensionContext) { + RandomizedContext ctx; + var forThread = Thread.currentThread(); + var key = getKey(extensionContext); + + if (contextStack.isEmpty()) { + ctx = + new RandomizedContext( + forThread, Objects.requireNonNull(seedAtLevel(extensionContext, 0))); + } else { + var forcedSeed = seedAtLevel(extensionContext, contextStack.size()); + var last = contextStack.peekLast(); + + ctx = + last.getValue() + .fork( + forThread, + seed -> forcedSeed != null ? forcedSeed.value : seed ^ Hashing.longHash(key)); + } + + contextStack.addLast(Map.entry(key, ctx)); + } + + private RandomSeed seedAtLevel(ExtensionContext context, int index) { + if (index >= seedList.size()) { + return null; + } + var seed = seedList.get(index); + if (seed == SeedChain.WILDCARD) { + seed = new RandomSeed(Hashing.mix64(sequencer.incrementAndGet() + System.nanoTime())); + } + return seed; + } +} diff --git a/core/src/main/java/com/carrotsearch/randomizedtesting/extensions/Hashing.java b/core/src/main/java/com/carrotsearch/randomizedtesting/extensions/Hashing.java new file mode 100644 index 00000000..321b983b --- /dev/null +++ b/core/src/main/java/com/carrotsearch/randomizedtesting/extensions/Hashing.java @@ -0,0 +1,22 @@ +package com.carrotsearch.randomizedtesting.extensions; + +public class Hashing { + public static long mix64(long k) { + k ^= k >>> 33; + k *= 0xff51afd7ed558ccdL; + k ^= k >>> 33; + k *= 0xc4ceb9fe1a85ec53L; + k ^= k >>> 33; + return k; + } + + /** String hash function redistributing over a long range. */ + public static long longHash(String v) { + long h = 0; + int length = v.length(); + for (int i = 0; i < length; i++) { + h = 31 * h + v.charAt(i); + } + return mix64(h); + } +} diff --git a/core/src/main/java/com/carrotsearch/randomizedtesting/extensions/InitialSeed.java b/core/src/main/java/com/carrotsearch/randomizedtesting/extensions/InitialSeed.java new file mode 100644 index 00000000..d26f71b9 --- /dev/null +++ b/core/src/main/java/com/carrotsearch/randomizedtesting/extensions/InitialSeed.java @@ -0,0 +1,14 @@ +package com.carrotsearch.randomizedtesting.extensions; + +import java.util.List; + +public class InitialSeed { + public static List compute() { + final String propertySeed = System.getProperties().getProperty(SysProps.TESTS_SEED); + if (propertySeed != null) { + return SeedChain.parse(propertySeed); + } else { + return List.of(SeedChain.WILDCARD); + } + } +} diff --git a/core/src/main/java/com/carrotsearch/randomizedtesting/extensions/RandomSeed.java b/core/src/main/java/com/carrotsearch/randomizedtesting/extensions/RandomSeed.java new file mode 100644 index 00000000..950f88ef --- /dev/null +++ b/core/src/main/java/com/carrotsearch/randomizedtesting/extensions/RandomSeed.java @@ -0,0 +1,22 @@ +package com.carrotsearch.randomizedtesting.extensions; + +public class RandomSeed { + private static final char[] HEX = "0123456789ABCDEF".toCharArray(); + + public final long value; + + public RandomSeed(long seed) { + this.value = seed; + } + + @Override + public String toString() { + long seed = value; + StringBuilder b = new StringBuilder(); + do { + b.append(HEX[(int) (seed & 0xF)]); + seed = seed >>> 4; + } while (seed != 0); + return b.reverse().toString(); + } +} diff --git a/core/src/main/java/com/carrotsearch/randomizedtesting/extensions/RandomizedContextProviderExtension.java b/core/src/main/java/com/carrotsearch/randomizedtesting/extensions/RandomizedContextProviderExtension.java new file mode 100644 index 00000000..13afa9a3 --- /dev/null +++ b/core/src/main/java/com/carrotsearch/randomizedtesting/extensions/RandomizedContextProviderExtension.java @@ -0,0 +1,110 @@ +package com.carrotsearch.randomizedtesting.extensions; + +import com.carrotsearch.randomizedtesting.api.RandomizedContext; +import org.junit.jupiter.api.extension.AfterAllCallback; +import org.junit.jupiter.api.extension.AfterEachCallback; +import org.junit.jupiter.api.extension.BeforeAllCallback; +import org.junit.jupiter.api.extension.BeforeEachCallback; +import org.junit.jupiter.api.extension.ExtensionContext; +import org.junit.jupiter.api.extension.ParameterContext; +import org.junit.jupiter.api.extension.ParameterResolutionException; +import org.junit.jupiter.api.extension.ParameterResolver; +import org.junit.jupiter.api.extension.TestInstanceFactory; +import org.junit.jupiter.api.extension.TestInstanceFactoryContext; +import org.junit.jupiter.api.extension.TestInstancePreDestroyCallback; +import org.junit.jupiter.api.extension.TestInstantiationException; +import org.junit.platform.commons.util.ReflectionUtils; + +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; + +public class RandomizedContextProviderExtension + implements TestInstanceFactory, + TestInstancePreDestroyCallback, + // InvocationInterceptor, + ParameterResolver, + BeforeAllCallback, + BeforeEachCallback, + AfterEachCallback, + AfterAllCallback { + private static final String KEY_EXECUTION_CONTEXT = ExtensionExecutionContext.class.getName(); + + @Override + public Object createTestInstance( + TestInstanceFactoryContext tiCtx, ExtensionContext extensionContext) + throws TestInstantiationException { + Constructor constructor = ReflectionUtils.getDeclaredConstructor(tiCtx.getTestClass()); + try { + getExecutionContext(extensionContext).push(extensionContext); + return constructor.newInstance(); + } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) { + throw new TestInstantiationException( + "Could not instantiate class: " + tiCtx.getTestClass().getName(), e); + } + } + + @Override + public void preDestroyTestInstance(ExtensionContext extensionContext) throws Exception { + getExecutionContext(extensionContext).pop(extensionContext); + } + + @Override + public void beforeAll(ExtensionContext extensionContext) { + var classStore = getClassExtensionStore(extensionContext); + assert classStore.get(KEY_EXECUTION_CONTEXT) == null; + + var executionContext = new ExtensionExecutionContext(InitialSeed.compute()); + classStore.put(KEY_EXECUTION_CONTEXT, executionContext); + + executionContext.push(extensionContext); + } + + @Override + public void afterAll(ExtensionContext extensionContext) { + var classStore = getClassExtensionStore(extensionContext); + assert classStore.get(KEY_EXECUTION_CONTEXT) != null; + var executionContext = + classStore.remove(KEY_EXECUTION_CONTEXT, ExtensionExecutionContext.class); + executionContext.pop(extensionContext); + } + + @Override + public void beforeEach(ExtensionContext extensionContext) { + getExecutionContext(extensionContext).push(extensionContext); + } + + @Override + public void afterEach(ExtensionContext extensionContext) { + getExecutionContext(extensionContext).pop(extensionContext); + } + + @Override + public boolean supportsParameter( + ParameterContext parameterContext, ExtensionContext extensionContext) + throws ParameterResolutionException { + return parameterContext.getParameter().getType().equals(RandomizedContext.class) + && getExecutionContext(extensionContext) != null; + } + + @Override + public RandomizedContext resolveParameter( + ParameterContext parameterContext, ExtensionContext extensionContext) + throws ParameterResolutionException { + return getRandomizedContext(extensionContext); + } + + private RandomizedContext getRandomizedContext(ExtensionContext extensionContext) { + return getExecutionContext(extensionContext).getContext(extensionContext); + } + + private ExtensionContext.Store getClassExtensionStore(ExtensionContext extensionContext) { + return extensionContext.getStore( + ExtensionContext.Namespace.create( + RandomizedContextProviderExtension.class, extensionContext.getRequiredTestClass())); + } + + private ExtensionExecutionContext getExecutionContext(ExtensionContext extensionContext) { + var classStore = getClassExtensionStore(extensionContext); + return classStore.get(KEY_EXECUTION_CONTEXT, ExtensionExecutionContext.class); + } +} diff --git a/core/src/main/java/com/carrotsearch/randomizedtesting/extensions/SeedChain.java b/core/src/main/java/com/carrotsearch/randomizedtesting/extensions/SeedChain.java new file mode 100644 index 00000000..989ef0c1 --- /dev/null +++ b/core/src/main/java/com/carrotsearch/randomizedtesting/extensions/SeedChain.java @@ -0,0 +1,57 @@ +package com.carrotsearch.randomizedtesting.extensions; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +public class SeedChain { + static final RandomSeed WILDCARD = new RandomSeed(0L); + + private final ArrayList seeds; + + public SeedChain(ArrayList seeds) { + this.seeds = seeds; + } + + public static List parse(String chain) { + chain = chain.replaceAll("[\\[\\]]", ""); + + String[] splits = chain.split("[:]"); + + RandomSeed[] seeds = new RandomSeed[splits.length]; + for (int i = 0; i < splits.length; i++) { + if (!splits[i].matches("[0-9A-Fa-f]+|[*]")) { + throw new IllegalArgumentException( + "Invalid component \"" + splits[i] + "\" in seed chain: " + chain); + } + seeds[i] = parseSeed(splits[i]); + } + return Arrays.asList(seeds); + } + + private static RandomSeed parseSeed(String component) { + if (component.equals("*")) { + return WILDCARD; + } else { + long result = 0; + for (char chr : component.toCharArray()) { + chr = Character.toLowerCase(chr); + result = result << 4; + if (chr >= '0' && chr <= '9') result |= (chr - '0'); + else if (chr >= 'a' && chr <= 'f') result |= (chr - 'a' + 10); + else throw new IllegalArgumentException("Expected hexadecimal seed: " + component); + } + return new RandomSeed(result); + } + } + + @Override + public String toString() { + return "[" + + seeds.stream() + .map(v -> v == WILDCARD ? "*" : v.toString()) + .collect(Collectors.joining(":")) + + "]"; + } +} diff --git a/core/src/main/java/com/carrotsearch/randomizedtesting/extensions/SysProps.java b/core/src/main/java/com/carrotsearch/randomizedtesting/extensions/SysProps.java new file mode 100644 index 00000000..a44e70d6 --- /dev/null +++ b/core/src/main/java/com/carrotsearch/randomizedtesting/extensions/SysProps.java @@ -0,0 +1,5 @@ +package com.carrotsearch.randomizedtesting.extensions; + +public class SysProps { + public static final String TESTS_SEED = "tests.seed"; +} diff --git a/core/src/main/java/com/carrotsearch/randomizedtesting/internal/Threads.java b/core/src/main/java/com/carrotsearch/randomizedtesting/internal/Threads.java new file mode 100644 index 00000000..fa2c21a9 --- /dev/null +++ b/core/src/main/java/com/carrotsearch/randomizedtesting/internal/Threads.java @@ -0,0 +1,19 @@ +package com.carrotsearch.randomizedtesting.internal; + +public final class Threads { + Threads() {} + + /** Collect thread information, JVM vendor insensitive. */ + public static String threadName(Thread t) { + return "Thread[" + + ("id=" + t.getId()) + + (", name=" + t.getName()) + + (", state=" + t.getState()) + + (", group=" + groupName(t.getThreadGroup())) + + "]"; + } + + private static String groupName(ThreadGroup threadGroup) { + return threadGroup == null ? "{null group}" : threadGroup.getName(); + } +} diff --git a/etc/eclipse/settings/org.eclipse.jdt.core.prefs b/etc/eclipse/settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index 01ade8bf..00000000 --- a/etc/eclipse/settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,286 +0,0 @@ -#Thu Jan 26 09:50:07 CET 2012 -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7 -org.eclipse.jdt.core.compiler.compliance=1.7 -org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning -org.eclipse.jdt.core.compiler.source=1.7 -org.eclipse.jdt.core.formatter.align_type_members_on_columns=false -org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=16 -org.eclipse.jdt.core.formatter.alignment_for_arguments_in_annotation=0 -org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant=16 -org.eclipse.jdt.core.formatter.alignment_for_arguments_in_explicit_constructor_call=16 -org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation=16 -org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression=16 -org.eclipse.jdt.core.formatter.alignment_for_assignment=0 -org.eclipse.jdt.core.formatter.alignment_for_binary_expression=16 -org.eclipse.jdt.core.formatter.alignment_for_compact_if=16 -org.eclipse.jdt.core.formatter.alignment_for_conditional_expression=80 -org.eclipse.jdt.core.formatter.alignment_for_enum_constants=0 -org.eclipse.jdt.core.formatter.alignment_for_expressions_in_array_initializer=16 -org.eclipse.jdt.core.formatter.alignment_for_method_declaration=0 -org.eclipse.jdt.core.formatter.alignment_for_multiple_fields=16 -org.eclipse.jdt.core.formatter.alignment_for_parameters_in_constructor_declaration=16 -org.eclipse.jdt.core.formatter.alignment_for_parameters_in_method_declaration=16 -org.eclipse.jdt.core.formatter.alignment_for_resources_in_try=80 -org.eclipse.jdt.core.formatter.alignment_for_selector_in_method_invocation=16 -org.eclipse.jdt.core.formatter.alignment_for_superclass_in_type_declaration=16 -org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_enum_declaration=16 -org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_type_declaration=16 -org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_constructor_declaration=16 -org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_method_declaration=16 -org.eclipse.jdt.core.formatter.alignment_for_union_type_in_multicatch=16 -org.eclipse.jdt.core.formatter.blank_lines_after_imports=1 -org.eclipse.jdt.core.formatter.blank_lines_after_package=1 -org.eclipse.jdt.core.formatter.blank_lines_before_field=0 -org.eclipse.jdt.core.formatter.blank_lines_before_first_class_body_declaration=0 -org.eclipse.jdt.core.formatter.blank_lines_before_imports=1 -org.eclipse.jdt.core.formatter.blank_lines_before_member_type=1 -org.eclipse.jdt.core.formatter.blank_lines_before_method=1 -org.eclipse.jdt.core.formatter.blank_lines_before_new_chunk=1 -org.eclipse.jdt.core.formatter.blank_lines_before_package=0 -org.eclipse.jdt.core.formatter.blank_lines_between_import_groups=1 -org.eclipse.jdt.core.formatter.blank_lines_between_type_declarations=1 -org.eclipse.jdt.core.formatter.brace_position_for_annotation_type_declaration=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_anonymous_type_declaration=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_array_initializer=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_block=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_block_in_case=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_constructor_declaration=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_enum_constant=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_enum_declaration=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_method_declaration=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_switch=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_type_declaration=end_of_line -org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_block_comment=false -org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_javadoc_comment=false -org.eclipse.jdt.core.formatter.comment.format_block_comments=true -org.eclipse.jdt.core.formatter.comment.format_header=false -org.eclipse.jdt.core.formatter.comment.format_html=true -org.eclipse.jdt.core.formatter.comment.format_javadoc_comments=true -org.eclipse.jdt.core.formatter.comment.format_line_comments=true -org.eclipse.jdt.core.formatter.comment.format_source_code=true -org.eclipse.jdt.core.formatter.comment.indent_parameter_description=true -org.eclipse.jdt.core.formatter.comment.indent_root_tags=true -org.eclipse.jdt.core.formatter.comment.insert_new_line_before_root_tags=insert -org.eclipse.jdt.core.formatter.comment.insert_new_line_for_parameter=insert -org.eclipse.jdt.core.formatter.comment.line_length=80 -org.eclipse.jdt.core.formatter.comment.new_lines_at_block_boundaries=true -org.eclipse.jdt.core.formatter.comment.new_lines_at_javadoc_boundaries=true -org.eclipse.jdt.core.formatter.comment.preserve_white_space_between_code_and_line_comments=false -org.eclipse.jdt.core.formatter.compact_else_if=true -org.eclipse.jdt.core.formatter.continuation_indentation=2 -org.eclipse.jdt.core.formatter.continuation_indentation_for_array_initializer=2 -org.eclipse.jdt.core.formatter.disabling_tag=@formatter\:off -org.eclipse.jdt.core.formatter.enabling_tag=@formatter\:on -org.eclipse.jdt.core.formatter.format_guardian_clause_on_one_line=false -org.eclipse.jdt.core.formatter.format_line_comment_starting_on_first_column=true -org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_annotation_declaration_header=true -org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_constant_header=true -org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_declaration_header=true -org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_type_header=true -org.eclipse.jdt.core.formatter.indent_breaks_compare_to_cases=true -org.eclipse.jdt.core.formatter.indent_empty_lines=true -org.eclipse.jdt.core.formatter.indent_statements_compare_to_block=true -org.eclipse.jdt.core.formatter.indent_statements_compare_to_body=true -org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_cases=true -org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_switch=true -org.eclipse.jdt.core.formatter.indentation.size=2 -org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_field=insert -org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_local_variable=insert -org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_method=insert -org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_package=insert -org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_parameter=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_type=insert -org.eclipse.jdt.core.formatter.insert_new_line_after_label=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_before_catch_in_try_statement=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_before_closing_brace_in_array_initializer=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_before_else_in_if_statement=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_before_finally_in_try_statement=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_before_while_in_do_statement=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_annotation_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_anonymous_type_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_block=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_constant=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_method_body=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_type_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_and_in_type_parameter=insert -org.eclipse.jdt.core.formatter.insert_space_after_assignment_operator=insert -org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation_type_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_binary_operator=insert -org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_arguments=insert -org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_parameters=insert -org.eclipse.jdt.core.formatter.insert_space_after_closing_brace_in_block=insert -org.eclipse.jdt.core.formatter.insert_space_after_closing_paren_in_cast=insert -org.eclipse.jdt.core.formatter.insert_space_after_colon_in_assert=insert -org.eclipse.jdt.core.formatter.insert_space_after_colon_in_case=insert -org.eclipse.jdt.core.formatter.insert_space_after_colon_in_conditional=insert -org.eclipse.jdt.core.formatter.insert_space_after_colon_in_for=insert -org.eclipse.jdt.core.formatter.insert_space_after_colon_in_labeled_statement=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_allocation_expression=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_annotation=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_array_initializer=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_parameters=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_throws=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_constant_arguments=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_declarations=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_explicitconstructorcall_arguments=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_increments=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_inits=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_parameters=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_throws=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_invocation_arguments=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_field_declarations=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_local_declarations=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_parameterized_type_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_superinterfaces=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_arguments=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_parameters=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_ellipsis=insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_parameterized_type_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_arguments=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_parameters=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_brace_in_array_initializer=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_allocation_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_annotation=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_cast=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_catch=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_constructor_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_enum_constant=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_for=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_if=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_invocation=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_parenthesized_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_switch=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_synchronized=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_try=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_while=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_postfix_operator=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_prefix_operator=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_question_in_conditional=insert -org.eclipse.jdt.core.formatter.insert_space_after_question_in_wildcard=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_for=insert -org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_try_resources=insert -org.eclipse.jdt.core.formatter.insert_space_after_unary_operator=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_and_in_type_parameter=insert -org.eclipse.jdt.core.formatter.insert_space_before_assignment_operator=insert -org.eclipse.jdt.core.formatter.insert_space_before_at_in_annotation_type_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_before_binary_operator=insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_parameterized_type_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_arguments=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_parameters=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_brace_in_array_initializer=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_allocation_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_annotation=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_cast=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_catch=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_constructor_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_enum_constant=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_for=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_if=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_invocation=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_parenthesized_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_switch=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_synchronized=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_try=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_while=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_colon_in_assert=insert -org.eclipse.jdt.core.formatter.insert_space_before_colon_in_case=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_colon_in_conditional=insert -org.eclipse.jdt.core.formatter.insert_space_before_colon_in_default=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_colon_in_for=insert -org.eclipse.jdt.core.formatter.insert_space_before_colon_in_labeled_statement=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_allocation_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_annotation=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_array_initializer=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_parameters=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_throws=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_constant_arguments=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_declarations=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_explicitconstructorcall_arguments=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_increments=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_inits=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_parameters=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_throws=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_invocation_arguments=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_field_declarations=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_local_declarations=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_parameterized_type_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_superinterfaces=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_arguments=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_parameters=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_ellipsis=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_parameterized_type_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_arguments=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_parameters=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_annotation_type_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_anonymous_type_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_array_initializer=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_block=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_constructor_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_constant=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_method_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_switch=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_type_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_allocation_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_type_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation_type_member_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_catch=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_constructor_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_enum_constant=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_for=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_if=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_invocation=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_switch=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_synchronized=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_try=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_while=insert -org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_return=insert -org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_throw=insert -org.eclipse.jdt.core.formatter.insert_space_before_postfix_operator=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_prefix_operator=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_question_in_conditional=insert -org.eclipse.jdt.core.formatter.insert_space_before_question_in_wildcard=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_semicolon=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_for=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_try_resources=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_unary_operator=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_brackets_in_array_type_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_braces_in_array_initializer=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_brackets_in_array_allocation_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_annotation_type_member_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_constructor_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_enum_constant=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_invocation=do not insert -org.eclipse.jdt.core.formatter.join_lines_in_comments=true -org.eclipse.jdt.core.formatter.join_wrapped_lines=true -org.eclipse.jdt.core.formatter.keep_else_statement_on_same_line=true -org.eclipse.jdt.core.formatter.keep_empty_array_initializer_on_one_line=false -org.eclipse.jdt.core.formatter.keep_imple_if_on_one_line=false -org.eclipse.jdt.core.formatter.keep_then_statement_on_same_line=true -org.eclipse.jdt.core.formatter.lineSplit=100 -org.eclipse.jdt.core.formatter.never_indent_block_comments_on_first_column=false -org.eclipse.jdt.core.formatter.never_indent_line_comments_on_first_column=false -org.eclipse.jdt.core.formatter.number_of_blank_lines_at_beginning_of_method_body=0 -org.eclipse.jdt.core.formatter.number_of_empty_lines_to_preserve=1 -org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line=true -org.eclipse.jdt.core.formatter.tabulation.char=space -org.eclipse.jdt.core.formatter.tabulation.size=2 -org.eclipse.jdt.core.formatter.use_on_off_tags=true -org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations=true -org.eclipse.jdt.core.formatter.wrap_before_binary_operator=true -org.eclipse.jdt.core.formatter.wrap_before_or_operator_multicatch=true -org.eclipse.jdt.core.formatter.wrap_outer_expressions_when_nested=true diff --git a/etc/eclipse/settings/org.eclipse.jdt.ui.prefs b/etc/eclipse/settings/org.eclipse.jdt.ui.prefs deleted file mode 100644 index e812d3d7..00000000 --- a/etc/eclipse/settings/org.eclipse.jdt.ui.prefs +++ /dev/null @@ -1,4 +0,0 @@ -#Thu Jan 26 09:50:07 CET 2012 -eclipse.preferences.version=1 -formatter_profile=org.eclipse.jdt.ui.default.eclipse_profile -formatter_settings_version=12 diff --git a/etc/forbidden-apis/signatures.txt b/etc/forbidden-apis/signatures.txt deleted file mode 100644 index 2f70d305..00000000 --- a/etc/forbidden-apis/signatures.txt +++ /dev/null @@ -1,38 +0,0 @@ -@defaultMessage Convert to URI -java.net.URL#getPath() -java.net.URL#getFile() - -@defaultMessage spawns threads with vague names; use a custom thread factory and name threads so that you can tell (by its name) which executor it is associated with -java.util.concurrent.Executors#newFixedThreadPool(int) -java.util.concurrent.Executors#newSingleThreadExecutor() -java.util.concurrent.Executors#newCachedThreadPool() -java.util.concurrent.Executors#newSingleThreadScheduledExecutor() -java.util.concurrent.Executors#newScheduledThreadPool(int) -java.util.concurrent.Executors#defaultThreadFactory() -java.util.concurrent.Executors#privilegedThreadFactory() - -java.lang.Character#codePointBefore(char[],int) @ Implicit start offset is error-prone when the char[] is a buffer and the first chars are random chars -java.lang.Character#codePointAt(char[],int) @ Implicit end offset is error-prone when the char[] is a buffer and the last chars are random chars - -@defaultMessage Please do not try to stop the world -java.lang.System#gc() - -@defaultMessage Use Channels.* methods to write to channels. Do not write directly. -java.nio.channels.WritableByteChannel#write(java.nio.ByteBuffer) -java.nio.channels.FileChannel#write(java.nio.ByteBuffer, long) -java.nio.channels.GatheringByteChannel#write(java.nio.ByteBuffer[], int, int) -java.nio.channels.GatheringByteChannel#write(java.nio.ByteBuffer[]) -java.nio.channels.ReadableByteChannel#read(java.nio.ByteBuffer) -java.nio.channels.ScatteringByteChannel#read(java.nio.ByteBuffer[]) -java.nio.channels.ScatteringByteChannel#read(java.nio.ByteBuffer[], int, int) -java.nio.channels.FileChannel#read(java.nio.ByteBuffer, long) - -@defaultMessage Filters are trappy (add suppression or make sure all read methods are redelegated). -java.io.FilterInputStream#(java.io.InputStream) -java.io.FilterOutputStream#(java.io.OutputStream) -java.io.FilterReader#(java.io.Reader) -java.io.FilterWriter#(java.io.Writer) - -#@defaultMessage Do not use context class loaders, prefer explicit ClassLoader argument. -java.lang.Thread@getContextClassLoader() -java.lang.Thread@setContextClassLoader() diff --git a/examples/ant/build.xml b/examples/ant/build.xml deleted file mode 100644 index 93a12a9b..00000000 --- a/examples/ant/build.xml +++ /dev/null @@ -1,165 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Done. See reports under target/. - - - - diff --git a/examples/ant/pom.xml b/examples/ant/pom.xml deleted file mode 100644 index 5de40335..00000000 --- a/examples/ant/pom.xml +++ /dev/null @@ -1,140 +0,0 @@ - - 4.0.0 - - - com.carrotsearch.randomizedtesting - randomizedtesting-parent - 2.7.9-SNAPSHOT - ../../pom.xml - - - randomizedtesting-examples-ant - RandomizedTesting ANT Examples - - - Simple use-case examples meant to be included in some - end-user documentation if it's ever going to be written... - - - - true - - - - - - com.carrotsearch.randomizedtesting - randomizedtesting-examples - ${project.version} - compile - - - - - com.carrotsearch.randomizedtesting - junit4-ant - ${project.version} - compile - - - - - - - - org.eclipse.m2e - lifecycle-mapping - 1.0.0 - - - - - - org.apache.maven.plugins - maven-dependency-plugin - [1.0.0,) - - copy-dependencies - - - - - - - - - - - - - - - - - org.apache.maven.plugins - maven-dependency-plugin - - - copy-dependencies - integration-test - - copy-dependencies - - - ${basedir}/target/lib - - - - - - - org.apache.maven.plugins - maven-antrun-plugin - - - ant-run-tests - integration-test - - - - - - - run - - - - - - - - - - - tools.jar - - - ${java.home}/../lib/tools.jar - - - - - - org.apache.maven.plugins - maven-antrun-plugin - - - com.sun - tools - 1.5.0 - system - ${java.home}/../lib/tools.jar - - - - - - - - diff --git a/examples/build.gradle.kts b/examples/build.gradle.kts new file mode 100644 index 00000000..a88309ef --- /dev/null +++ b/examples/build.gradle.kts @@ -0,0 +1,8 @@ +plugins { + id("java-library") +} + +dependencies { + testImplementation(project(":core")) + testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:5.7.2") +} \ No newline at end of file diff --git a/examples/maven/pom.xml b/examples/maven/pom.xml deleted file mode 100644 index 502ddfb1..00000000 --- a/examples/maven/pom.xml +++ /dev/null @@ -1,103 +0,0 @@ - - 4.0.0 - - - com.carrotsearch.randomizedtesting - randomizedtesting-parent - 2.7.9-SNAPSHOT - ../../pom.xml - - - randomizedtesting-examples - RandomizedTesting Examples - - - Simple use-case examples meant to be included in some - end-user documentation if it's ever going to be written... - - - - true - - - - - com.carrotsearch.randomizedtesting - randomizedtesting-runner - ${project.version} - compile - - - - junit - junit - compile - - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - - default-test - none - - - - - - - com.carrotsearch.randomizedtesting - junit4-maven-plugin - ${project.version} - - - junit4-tests - - junit4 - - test - - - false - - - ${project.build.outputDirectory} - - - - - - - - - - - - - - - - - - - diff --git a/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/Test001SimpleUseCase.java b/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/Test001SimpleUseCase.java deleted file mode 100644 index 6ece9fbb..00000000 --- a/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/Test001SimpleUseCase.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.carrotsearch.examples.randomizedrunner; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; - -import com.carrotsearch.randomizedtesting.RandomizedRunner; - -/** - * This is a test-based tutorial introducing to randomized JUnit testing using - * {@link RandomizedRunner}. Follow test cases in their alphabetic order. - * - *

One way to start using {@link RandomizedRunner} is to declare - * your suite class as being executed by {@link RandomizedRunner} (using - * {@link RunWith} annotation). The {@link #success()} method doesn't do anything - * useful but runs under {@link RandomizedRunner}. We know this for sure because we - * can hide a hook (before()) method to be private - * (normal JUnit doesn't allow this). - */ -@RunWith(RandomizedRunner.class) -public class Test001SimpleUseCase { - @Before - private void before() { - // This won't work under the default JUnit runner. - } - - @Test - public void success() { - // Do nothing. - } -} diff --git a/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/Test002ExtendingRandomizedTest.java b/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/Test002ExtendingRandomizedTest.java deleted file mode 100644 index 98e3eec4..00000000 --- a/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/Test002ExtendingRandomizedTest.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.carrotsearch.examples.randomizedrunner; - -import java.util.Random; - -import org.junit.Test; - -import com.carrotsearch.randomizedtesting.RandomizedContext; -import com.carrotsearch.randomizedtesting.RandomizedTest; - -/** - * To start using pseudo-randomization we need to get hold of the - * {@link RandomizedContext} instance associated with the test. This can be done - * manually, as shown in {@link #getContextByHand()} method or (better) we can - * extend {@link RandomizedTest} and have a superclass method to handle this - * (and more) for us as shown in {#link #getContextFromSuper()} - * - *

Note that {@link Random} instances acquired from the context are - * preinitialized with a repeatable seed (we'll get to that) so tests - * can be re-run with the same random sequence if something fails. - */ -public class Test002ExtendingRandomizedTest extends RandomizedTest { - @Test - public void getContextByHand() { - RandomizedContext context = RandomizedContext.current(); - Random rnd = context.getRandom(); - System.out.println("Random, next int: " + rnd.nextInt()); - } - - @Test - public void getContextFromSuper() { - Random rnd = super.getRandom(); - System.out.println("Random, next int: " + rnd.nextInt()); - } -} diff --git a/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/Test003UsingRandomness.java b/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/Test003UsingRandomness.java deleted file mode 100644 index 0e6f5801..00000000 --- a/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/Test003UsingRandomness.java +++ /dev/null @@ -1,92 +0,0 @@ -package com.carrotsearch.examples.randomizedrunner; - -import java.util.Random; - -import org.junit.Test; - -import com.carrotsearch.randomizedtesting.RandomizedRunner; -import com.carrotsearch.randomizedtesting.RandomizedTest; - -import static org.junit.Assert.*; - -/** - * So far we haven't really used the {@link Random} provided by - * {@link RandomizedRunner}. The idea behind randomized tests is to, for each - * test execution: - *

    - *
  • cover a possibly different execution path of the tested component,
  • - *
  • cover a different data (input) passed to the tested component, - *
  • - *
  • execute in a different "environment" if there is environment variability. - *
  • - *
- * - *

- * Let's see this on a simple example of a method that adds two - * integers ({@link Adder#add(int, int)}). We can test this method using a "fixed" test - * case as shown in {@link #fixedTesting} but this test will always execute in - * an identical way (which is good if you're looking for regression coverage but - * bad if you want to expand your tested domain). - * - *

- * A randomized test, on the other hand, will pick parameters from a larger - * spectrum of values and assert on the method's contract. Here, we can make - * sure the sum is always larger or equal than the arguments given two positive - * arguments. This assertion will fail quite often because of integer overflows as shown - * in {@link #randomizedTesting()} (re-run the test a few times if it doesn't - * fail the first time). - * - *

- * While the above example is trivial most of the bugs in code stem from similar - * subtleties (possibly resulting from more complex interactions). In many cases - * the "contract" that we can assert on can be stated as "throw no-exception" given - * valid arguments. An example of that is in method {@link #expectNoException()}. - * At first glance this method will work most of the time, but try passing - * {@link Integer#MIN_VALUE} as a random number and see what will happen. - */ -public class Test003UsingRandomness extends RandomizedTest { - public static class Adder { - //[[[start:adder]]] - /** - * This method adds a and b and returns their sum. - */ - public static int add(int a, int b) { - return a + b; - } - //[[[end:adder]]] - } - - //[[[start:adder-fixed]]] - @Test - public void fixedTesting() { - // Note how we use superclass methods, RandomizedTest extends from - // Assert so these methods are readily available. - assertEquals( 4, Adder.add(2, 2)); - assertEquals(-1, Adder.add(0, -1)); - assertEquals( 0, Adder.add(0, 0)); - } - //[[[end:adder-fixed]]] - - //[[[start:adder-randomized]]] - @Test - public void randomizedTesting() { - // Here we pick two positive integers. Note superclass utility methods. - int a = randomIntBetween(0, Integer.MAX_VALUE); - int b = randomIntBetween(0, Integer.MAX_VALUE); - int result = Adder.add(a, b); - assertTrue(result + " < (" + a + " or " + b + ")?", result >= a && result >= b); - } - //[[[end:adder-randomized]]] - - @Test - public void expectNoException() { - String [] words = {"oh", "my", "this", "is", "bad."}; - - // This will pick a random word from the array above... - System.out.println(words[Math.abs(randomInt()) % words.length]); - - // .. unless the random picked happens to be this number (fixed to get - // a reproducible example, but you get the idea); - System.out.println(words[Math.abs(Integer.MIN_VALUE) % words.length]); - } -} diff --git a/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/Test004MoreRandomness.java b/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/Test004MoreRandomness.java deleted file mode 100644 index ee4a4b60..00000000 --- a/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/Test004MoreRandomness.java +++ /dev/null @@ -1,87 +0,0 @@ -package com.carrotsearch.examples.randomizedrunner; - -import java.util.Random; - -import org.junit.AfterClass; -import org.junit.Test; -import org.junit.runner.Description; -import org.junit.runner.RunWith; -import org.junit.runners.Suite; -import org.junit.runners.Suite.SuiteClasses; - -import com.carrotsearch.randomizedtesting.RandomizedContext; -import com.carrotsearch.randomizedtesting.RandomizedRunner; -import com.carrotsearch.randomizedtesting.RandomizedTest; -import com.carrotsearch.randomizedtesting.SysGlobals; -import com.carrotsearch.randomizedtesting.annotations.Seed; -import com.carrotsearch.randomizedtesting.annotations.Seeds; - -/** - * Randomness is entwined everywhere in {@link RandomizedRunner}. An instance of - * {@link Random} is of course available from a {@link RandomizedContext}, but - * even tests themselves are randomized, or to be more precise: their order of - * execution is shuffled. - * - *

- * In this example we have two classes that contain three methods (they're nested - * under a single suite class for simplicity). Every execution of class - * {@link Test004MoreRandomness.OrderRandomized} will be different, shuffling - * test methods around (and the random numbers written to the output). - * We can "pin" the execution order by forcing the master random - * seed using {@link Seed} annotation on the class (or a system property - * {@link SysGlobals#SYSPROP_RANDOM_SEED}). Doing so also fixes all derivative random - * generators in all tests - this is shown in - * {@link Test004MoreRandomness.OrderRandomizedButFixed}, every execution of this - * class will be identical (and will emit identical pseudo-random numbers). - * - *

- * All this is meant for one purpose: help in reproducing a failed randomized test - * case. Once a test case fails, make sure you write down the random seed number - * that caused the failure and add appropriate {@link Seeds} annotation on the method - * that failed like so: - *

- * {@literal @}{@link Seeds}({
- *   {@literal @}{@link Seed}("012345"),
- *   {@literal @}{@link Seed}()
- * })
- * 
- * where 012345 is the replaced by the seed that caused the failure. This makes - * the test methods run with a fixed seed once and then with a random seed again, - * easily creating a new regression test so that the bug does not reoccur in the - * future. An example of that is shown in - * {@link Test004MoreRandomness.OrderRegression#regression()}. Also note - * how {@link RandomizedRunner} modifies test method names for such "expanded" methods, appending - * the random seed as a parameter. This is needed to avoid duplicate - * test {@link Description} objects (a design flaw in JUnit). We will see these parameters - * again in the example concerning parameterized tests. - */ -@RunWith(Suite.class) -@SuiteClasses({ - Test004MoreRandomness.OrderRandomized.class, - Test004MoreRandomness.OrderRandomizedButFixed.class, - Test004MoreRandomness.OrderRegression.class -}) -public class Test004MoreRandomness { - public static class OrderRandomized extends RandomizedTest { - @Test public void method1() { System.out.println("method1, " + randomInt()); } - @Test public void method2() { System.out.println("method2, " + randomInt()); } - @Test public void method3() { System.out.println("method3, " + randomInt()); } - - @AfterClass - public static void empty() { - System.out.println("--"); - } - } - - @Seed("deadbeef") - public static class OrderRandomizedButFixed extends OrderRandomized { - } - - public static class OrderRegression extends RandomizedTest { - @Seeds({ - @Seed("deadbeef"), - @Seed() - }) - @Test public void regression() { System.out.println("regression, " + randomInt()); } - } -} diff --git a/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/Test005RecoveringRandomSeed.java b/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/Test005RecoveringRandomSeed.java deleted file mode 100644 index f28a2b1b..00000000 --- a/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/Test005RecoveringRandomSeed.java +++ /dev/null @@ -1,83 +0,0 @@ -package com.carrotsearch.examples.randomizedrunner; - -import java.util.Random; - -import org.junit.*; - -import com.carrotsearch.randomizedtesting.*; -import com.carrotsearch.randomizedtesting.annotations.Repeat; -import com.carrotsearch.randomizedtesting.annotations.Seed; - -/** - * {@link RandomizedRunner} uses several "contexts", each of which is assigned a - * predictable {@link Random} and is modeled using a {@link Randomness} - * instance. The "suite" or "master" context is available from - * {@link BeforeClass} or {@link AfterClass} hooks, for example. Each test - * method has a nested context with a random seed derived from the master. This - * way even though the order of tests is shuffled and each test can make a - * random number of calls to its own context's {@link Random} instance, the - * global execution paths can always be repeated from the same master seed. The - * question is: how do we know what master seed was used? There are at least two - * ways to find out. - * - *

The master seed is always available from - * {@link RandomizedContext#getRunnerSeedAsString()} so one can simply print it to the - * console. The current context's {@link Randomness} itself can be printed to the - * console. In two methods in this class {@link #printMasterContext()} and {@link #printContext()} - * we print the master seed and current context's {@link Randomness}, note how the static - * context's {@link Randomness} is identical with the runner's but the test context - * is a derived value. - *

- * # Static context ({@literal @}BeforeClass)
- * AF567B2B9F8A8F1C
- * [Randomness, seed=[AF567B2B9F8A8F1C]]
- * # Test context ({@literal @}Test)
- * AF567B2B9F8A8F1C
- * [Randomness, seed=[EE581D5EC61D6BCF]]
- * 
- * In {@link Test006RepeatingTests} we will see how this derived - * seed is used with {@link Repeat} annotation. - * - *

Normally we will not be interested in a random seed if a test case passes. But if a test - * case fails we will want to know the seed to be able to repeat the test. {@link RandomizedRunner} - * augments the stack trace of all exceptions that cross the context boundary (this includes - * assertion errors, assumption failures and any other exceptions). In method {@link #failure()} - * we demonstrate this by failing on a constant condition. If you run this test suite, you'll note - * the stack trace of the failing method to be something like this: - *

- * java.lang.AssertionError
- *   at __randomizedtesting.SeedInfo.seed([AF567B2B9F8A8F1C:44E2D1A039274F2A]:0)
- *   at org.junit.Assert.fail(Assert.java:92)
- * 
- * - * The first line of the stack trace is a synthetic (non-existing) class with "source file" - * entry containing all contexts' seeds on the stack (from master to the current test method). - * In this case, you can see the master context first (AF567B2B9F8A8F1C), followed - * by the test's context (44E2D1A039274F2A). The entire class has a fixed master seed - * so that the result will always be the same here: - *
- * {@literal @}{@link Seed}("AF567B2B9F8A8F1C")
- * public class Test005RecoveringRandomSeed extends RandomizedTest { // ...
- * 
- */ -@Seed("AF567B2B9F8A8F1C") -public class Test005RecoveringRandomSeed extends RandomizedTest { - @BeforeClass - public static void printMasterContext() { - System.out.println("# Static context (@BeforeClass)"); - System.out.println(getContext().getRunnerSeedAsString()); - System.out.println(RandomizedContext.current().getRandomness()); - } - - @Test - public void printContext() { - System.out.println("# Test context (@Test)"); - System.out.println(getContext().getRunnerSeedAsString()); - System.out.println(RandomizedContext.current().getRandomness()); - } - - @Test - public void failure() { - Assert.assertTrue(false); - } -} diff --git a/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/Test006RepeatingTests.java b/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/Test006RepeatingTests.java deleted file mode 100644 index dc93be2a..00000000 --- a/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/Test006RepeatingTests.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.carrotsearch.examples.randomizedrunner; - -import org.junit.*; - -import com.carrotsearch.randomizedtesting.*; -import com.carrotsearch.randomizedtesting.annotations.Repeat; -import com.carrotsearch.randomizedtesting.annotations.Seed; - -import static org.junit.Assert.*; - -/** - * In example {@link Test005RecoveringRandomSeed} we presented - * {@link Randomness} contexts and how they are derived from a master seed. Once - * you know a certain test case fails it is usually beneficial to immediately - * check if it always fails on a given seed (which means there is a - * deterministic failure scenario). A simple way to do so would be to re-run a - * test case a few times. The same effect can be achieved by adding a - * {@link Repeat} annotation with {@link Repeat#useConstantSeed()} set to - * false attribute as shown in the method {@link #repeatFailure()} - * below. - *
- * {@literal @}{@link Repeat}(iterations = 5, useConstantSeed = true)
- * {@literal @}{@link Seed}("f00ddead")
- * {@literal @}{@link Test}
- * public void repeatFailure() { //...
- * 
- * Note how the seed is fixed using {@link Seed} annotation (on the - * method) rather than on the master. This ensures the method's context is - * pinned to that value, but the master is still random. If you have - * {@link BeforeClass} hooks that depend on randomness you should use - * suite-level {@link Seed} annotation and pin the master seed instead. - * - *

You can also set {@link Repeat#useConstantSeed()} to false and - * then every iteration of the test method will have a pseudo-random context derived - * from the first one (pinned or not). This can be useful to tell how frequently - * a given test case fails for a random seed. For {@link #halfAndHalf()} method - * about 50% of iterations will fail. - */ -public class Test006RepeatingTests extends RandomizedTest { - @Repeat(iterations = 5, useConstantSeed = true) - @Seed("f00ddead") - @Test - public void repeatFailure() { - assertTrue(randomBoolean()); - } - - @Repeat(iterations = 10, useConstantSeed = false) - @Test - public void halfAndHalf() { - assertTrue(randomBoolean()); - } -} diff --git a/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/Test007ParameterizedTests.java b/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/Test007ParameterizedTests.java deleted file mode 100644 index d42d794a..00000000 --- a/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/Test007ParameterizedTests.java +++ /dev/null @@ -1,97 +0,0 @@ -package com.carrotsearch.examples.randomizedrunner; - -import java.util.Arrays; -import java.util.Formatter; - -import org.junit.Test; -import org.junit.runners.Parameterized; - -import com.carrotsearch.randomizedtesting.RandomizedRunner; -import com.carrotsearch.randomizedtesting.RandomizedTest; -import com.carrotsearch.randomizedtesting.annotations.Name; -import com.carrotsearch.randomizedtesting.annotations.ParametersFactory; -import com.carrotsearch.randomizedtesting.annotations.Repeat; -import com.carrotsearch.randomizedtesting.annotations.Seed; -import com.carrotsearch.randomizedtesting.annotations.Seeds; - -/** - * Parameterized tests are tricky. JUnit's {@link Parameterized} runner is - * notoriously bad at giving human-readable test case names (there are several - * patch proposal on github but not applied to the trunk at the time of writing - * this). - * - *

{@link RandomizedRunner} has built-in support for parameters using a pair - * of static-parameters provider method (factory) and a matching constructor. - * The static method has to be public and annotated with {@link ParametersFactory}, - * as in {@link #parameters()} method below. Note the funky-looking $ - * and $$ method which are static varargs collector methods to avoid - * explicit array constructors. - *

- * {@literal @}{@link ParametersFactory}
- * public static Iterable<Object[]> parameters() {
- *   return Arrays.asList($$(
- *     $(1, "abc"), 
- *     $(2, "def")));
- * }
- * 
- * - *

The matching class constructor must declare type-assignable parameters. Because method - * arguments are not part of the Java reflection, they can be explicitly annotated using - * {@link Name} annotation to provide sensible names. - * The {@link #Test007ParameterizedTests(int, String)} - * constructor shows an example of how this looks. - * - *

If there is more than one set of parameters, method names will be postfixed with - * a list of parameters and their values. An additional #num identifier will - * be added to make tests unique. - * - *

{@link ParametersFactory} can be combined with other annotations such as - * {@link Repeat} or {@link Seeds} as shown in {@link #paramsWithRepeatAndSeeds()}. - * - *

Note that {@code ParametersFactory.argumentFormatting()} permits custom - * test case naming, see the example factory in this class. - */ -public class Test007ParameterizedTests extends RandomizedTest { - private int value; - private String string; - - public Test007ParameterizedTests( - @Name("value") int value, - @Name("string") String string) { - this.value = value; - this.string = string; - } - - @Test - public void simpleArgumentsConsumer() { - System.out.println(value + " " + string + " " - + getContext().getRandomness()); - } - - @Seeds({@Seed("deadbeef"), @Seed("cafebabe")}) - @Test - @Repeat(iterations = 2, useConstantSeed = true) - public void paramsWithRepeatAndSeeds() { - System.out.println(value + " " + string + " " - + getContext().getRandomness()); - } - - @ParametersFactory - public static Iterable parameters() { - return Arrays.asList($$( - $(1, "abc"), - $(2, "def"))); - } - - /** - * A factory with custom test name formatting. Note parameters - * are reversed and referenced from the formatting string via - * {@link Formatter} positional order syntax - */ - @ParametersFactory(argumentFormatting = "param2:%2$s param1:%1$04d") - public static Iterable parametersWithCustomName() { - return Arrays.asList($$( - $(3, "foo"), - $(4, "bar"))); - } -} diff --git a/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/Test008Timeouts.java b/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/Test008Timeouts.java deleted file mode 100644 index c0fd04e6..00000000 --- a/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/Test008Timeouts.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.carrotsearch.examples.randomizedrunner; - -import org.junit.Test; - -import com.carrotsearch.randomizedtesting.RandomizedRunner; -import com.carrotsearch.randomizedtesting.RandomizedTest; -import com.carrotsearch.randomizedtesting.annotations.Timeout; - -/** - * {@link RandomizedRunner} has built-in support for enforcing test timeouts. If - * a given test fails to execute in the given deadline, its thread will be - * forcibly terminated (details below) and the test case will end in a failure. - * - *

- * A timeout can be specified in two ways. First, the standard JUnit's - * {@link Test#timeout()} attribute can be used (see - * {@link #standardAnnotation()}). Alternatively, a more specific @link Timeout} - * annotation is also provided if one needs to be explicit. - * - *

- * The termination of a test thread is done in several steps ranking from subtle - * to brute-force: - *

    - *
  • First, the thread is interrupted a few times with - * {@link Thread#interrupt()}. In many situations (I/O wait, waiting on a - * monitor) this will be enough to stop the test case and return. - *
  • If interrupt doesn't work (busy-loops, interrupted exception caught and - * ignored), an attempt is made to stop the thread using {@link Thread#stop()}. - * This should cause the test thread to throw {@link ThreadDeath} exception at - * the current execution pointer and propagate up the stack. - *
  • Should {link {@link ThreadDeath} be caught and ignored as well, the - * thread is declared a zombie and other tests execution is resumed with the - * thread running in the background. - *
- * - *

- * The information about attempts to interrupt the thread are logged to the - * Java's logging system along with the information about stack traces where the - * thread resided when interrupts were sent to it. This is typically useful in - * diagnosing what the thread was doing and why it couldn't be terminated. Keeping - * Java logging system enabled is thus strongly encouraged. - */ -public class Test008Timeouts extends RandomizedTest { - @Test(timeout = 500) - public void standardAnnotation() { - sleep(10000); - } - - @Test - @Timeout(millis = 500) - public void timeoutAnnotation() { - sleep(10000); - } -} diff --git a/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/Test009ThreadLeaks.java b/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/Test009ThreadLeaks.java deleted file mode 100644 index d52b6bed..00000000 --- a/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/Test009ThreadLeaks.java +++ /dev/null @@ -1,66 +0,0 @@ -package com.carrotsearch.examples.randomizedrunner; - -import java.util.concurrent.*; - -import org.junit.*; - -import com.carrotsearch.randomizedtesting.RandomizedRunner; -import com.carrotsearch.randomizedtesting.RandomizedTest; - -/** - * Leaked background threads can crash tests randomly even if all seeds are - * known and predictable. They can also affect other test cases and so we should - * not allow any threads to "leak outside" of their scope (a single test case or - * a single suite if the thread is started in {@link BeforeClass} or - * {@link AfterClass} hooks). - * - *

- * {@link RandomizedRunner} has built-in support for detecting threads that - * escaped their current {@link ThreadGroup}'s boundary. Such threads are killed - * and make the test (or suite) fail with appropriate exception. - * {@link #leftOverThread()} method below shows a simple scenario in which a - * test leaks outside its test boundary. A correct code that calls {@link Thread#join()} - * is shown in {@link #noLeakHere()}. - * - *

- * More concepts concerning leaking threads and some workarounds for typical - * problems with them is shown in {@link Test010Lingering}. - */ -public class Test009ThreadLeaks extends RandomizedTest { - @Test - public void leftOverThread() throws Exception { - final CountDownLatch go = new CountDownLatch(1); - - Thread t = new Thread() { - public void run() { - try { - go.countDown(); - Thread.sleep(1000); - } catch (InterruptedException e) {/* ignore */} - } - }; - - // Start and wait for it to really start. - t.start(); - go.await(); - } - - @Test - public void noLeakHere() throws Exception { - final CountDownLatch go = new CountDownLatch(1); - - Thread t = new Thread() { - public void run() { - try { - go.countDown(); - Thread.sleep(1000); - } catch (InterruptedException e) {/* ignore */} - } - }; - - // Start and wait for it to really start. - t.start(); - go.await(); - t.join(); - } -} diff --git a/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/Test010Lingering.java b/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/Test010Lingering.java deleted file mode 100644 index eb9a80dd..00000000 --- a/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/Test010Lingering.java +++ /dev/null @@ -1,83 +0,0 @@ -package com.carrotsearch.examples.randomizedrunner; - -import java.util.concurrent.*; - -import org.junit.Assert; - -import org.junit.Test; - -import com.carrotsearch.randomizedtesting.RandomizedRunner; -import com.carrotsearch.randomizedtesting.RandomizedTest; -import com.carrotsearch.randomizedtesting.annotations.Repeat; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakAction; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakLingering; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakZombies; - -/** - * In many cases the creation of background threads lies beyond our control (and - * their direct termination or even awaiting for their termination) is not - * possible. A good example is the {@link Executors} framework where background - * {@link ThreadFactory} is not published if not given explicitly. - * To handle such situations {@link RandomizedRunner} needs to know if it should - * await background thread to complete (and for how long) or if it should allow - * them to "leak" safely and not complain. All this can be declared with a set - * of annotations starting with ThreadLeak* prefix. - * - *

We can use {@link ThreadLeakLingering} annotation instead of explicitly using - * {@link Thread#join()} sometimes. For example, {@link Test009ThreadLeaks#leftOverThread()} - * can be rewritten as shown in {@link #lingerForLeftOverThread()}. - * - *

The same annotation can be used to wait for background threads - * which we don't have any control on, but we know they will eventually terminate. - * For example, a terminated {@link Executor} does not wait (join) with its slave - * threads so lingering here is required. This is shown in method {@link #executorLeak()}. This - * method will fail (from time to time, it isn't guaranteed) if no lingering time is given. - * - *

There are other annotations for advanced control of thread leaks and their outcomes, check out - * the javadocs in the links below. - * - * @see ThreadLeakScope - * @see ThreadLeakLingering - * @see ThreadLeakAction - * @see ThreadLeakZombies - */ -public class Test010Lingering extends RandomizedTest { - - @Test @ThreadLeakLingering(linger = 2000) - public void lingerForLeftOverThread() throws Exception { - final CountDownLatch go = new CountDownLatch(1); - - Thread t = new Thread() { - public void run() { - try { - go.countDown(); - Thread.sleep(1000); - } catch (InterruptedException e) {/* ignore */} - } - }; - - // Start and wait for it to really start. - t.start(); - go.await(); - } - - // @ThreadLeaks(linger = 1000) // Enable me to make it pass all the time. - @Test @Repeat(iterations = 10) - public void executorLeak() throws Exception { - int numThreads = 50; - final ExecutorService executor = Executors.newFixedThreadPool(numThreads); - for (int i = 0; i < 2 * numThreads; i++) { - executor.submit(new Runnable() { - public void run() { - sleep(10); - } - }); - } - - executor.shutdown(); - executor.awaitTermination(1, TimeUnit.SECONDS); - Assert.assertTrue(executor.isShutdown()); - Assert.assertTrue(executor.isTerminated()); - } -} diff --git a/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/Test011NightlyTests.java b/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/Test011NightlyTests.java deleted file mode 100644 index a0cecf96..00000000 --- a/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/Test011NightlyTests.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.carrotsearch.examples.randomizedrunner; - -import org.junit.Assume; -import org.junit.Test; - -import com.carrotsearch.randomizedtesting.*; -import com.carrotsearch.randomizedtesting.annotations.Nightly; -import com.carrotsearch.randomizedtesting.annotations.TestGroup; - -/** - * Running tests on a developer machine is often a pain, in particular when - * certain tests are long and repetitive. If you have a dedicated continuous - * integration environment like Jenkins or - * Attlasian Bamboo then it - * is nice to be able to "stress" your tests a bit more during nightly or server - * runs compared to normal developer runs. - * - *

{@link RandomizedRunner} has a built-in {@link TestGroup} called {@link Nightly} - * for "scaling" the execution depending if is in nightly mode or not. In the simplest - * case (see {@link #nightlyOnly()} a test case is run in nightly mode and ignored in - * normal runs. This can be done by annotating a test case or suite using {@link Nightly} - * or by checking for nightly mode explicitly. - * - *

For tests whose runtime depends on the amount of input data or other varying complexity, - * one can use {@link RandomizedTest#scaledRandomIntBetween(int, int)} method or the current - * {@link RandomizedTest#multiplier()}. These methods adjust to the nightly mode picking - * larger values than in daily mode (see javadocs for details). - */ -public class Test011NightlyTests extends RandomizedTest { - @Nightly - @Test - public void nightlyOnly() throws Exception { - // Do nothing, but pretend we're long and slow. - } - - @Test - public void nightlyOnlyWithAssume() throws Exception { - // Only run if Nightly test group is explicitly enabled using -Dtests.nightly=true - Assume.assumeTrue(RandomizedContext.current().getGroupEvaluator().isGroupEnabled(Nightly.class)); - } - - @Test - public void scaling() throws Exception { - System.out.println("Mode: " + (isNightly() ? "nightly" : "daily")); - System.out.println("Multiplier: " + multiplier()); - for (int i = 0; i < 10; i++) { - System.out.println("random scaled int = " + scaledRandomIntBetween(0, 100)); - } - } -} diff --git a/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/Test012TestGroups.java b/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/Test012TestGroups.java deleted file mode 100644 index 2093ba2e..00000000 --- a/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/Test012TestGroups.java +++ /dev/null @@ -1,70 +0,0 @@ -package com.carrotsearch.examples.randomizedrunner; - -import java.lang.annotation.*; - -import org.junit.Test; - -import com.carrotsearch.randomizedtesting.RandomizedRunner; -import com.carrotsearch.randomizedtesting.RandomizedTest; -import com.carrotsearch.randomizedtesting.annotations.Nightly; -import com.carrotsearch.randomizedtesting.annotations.TestGroup; - -/** - * We introduced the notion of {@link Nightly} tests in - * {@link Test011NightlyTests}. Similar to this idea, the user can introduce any - * number of custom test groups which can be arbitrarily enabled or disabled. In - * fact, {@link Nightly} is also defined as such a {@link TestGroup}. - * - *

- * A custom test group is an annotation itself annotated with a - * {@link TestGroup}. For example, let's say we want a test group that marks all - * tests that require a physical display. An annotation for this is shown in - * {@link Test012TestGroups.RequiresDisplay}. It has no additional attributes. - * What makes it a test group is a meta-annotation: - * - *

- * {@literal @}{@link TestGroup}(name = "requiresdisplay", enabled = false, sysProperty = "display")
- * 
- * - * which states that the group's name is "requiresdisplay" and that the group is - * initially disabled unless a system property "display" is set to a boolean - * value "false", "off" or "disabled". - * - *

- * {@link Nightly} is defined in a very similar way. Note that test groups are - * real annotations so they are recognizable by IDEs, can be searched, - * manipulated etc. - * - *

- * Another feature of using {@link RandomizedRunner} with groups is the ability to specify - * complex group-based filters specified via tests.filter system property. - * These filters are boolean conditions, with optional parentheses. For example: - *

    - *
  • {@literal @}nightly - runs all tests with test group named nightly.
  • - *
  • not {@literal @}nightly - runs all tests not annotated with a test group named nightly.
  • - *
  • {@literal @}fast and not {@literal @}requiresdisplay - runs all tests annotated with fast and not annotated with requiresdisplay.
  • - *
  • not ({@literal @}slow or {@literal @}nightly) - skips any tests annotated with slow or nightly.
  • - *
- * - * Important! Note that using filtering expression has precedence over the default state of a group - * and its corresponding system property. This is intentional so that filtering expressions can be used - * independently of each group's default state. Should the default state be taken into account one - * can use a special keyword default, as in: - *
    - *
  • default and not {@literal @}slow - runs any tests that would be selected by their default - * group status (including those that do not have any test groups at all), - * excluding any tests annotated with slow.
  • - *
- */ -public class Test012TestGroups extends RandomizedTest { - @TestGroup(name = "requiresdisplay", enabled = false, sysProperty = "display") - @Retention(RetentionPolicy.RUNTIME) - @Target({ElementType.METHOD}) - public static @interface RequiresDisplay {} - - @Test - @RequiresDisplay - public void usesDisplay() { - System.out.println("Running on windows."); - } -} diff --git a/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/Test014Listeners.java b/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/Test014Listeners.java deleted file mode 100644 index 7e222532..00000000 --- a/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/Test014Listeners.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.carrotsearch.examples.randomizedrunner; - -import org.junit.Assert; - -import org.junit.Test; -import org.junit.runner.notification.RunListener; - -import com.carrotsearch.randomizedtesting.RandomizedRunner; -import com.carrotsearch.randomizedtesting.RandomizedTest; -import com.carrotsearch.randomizedtesting.annotations.Listeners; -import com.carrotsearch.randomizedtesting.listeners.ReproduceInfoPrinter; - -/** - * {@link RandomizedRunner} respects an on-suite class {@link Listeners} - * annotation and instantiates classes that implement {@link RunListener}. This - * allows custom listener hooks on the suite. - * - *

- * We honestly don't know where this would be useful. For now there are just a - * few listeners, among them {@link ReproduceInfoPrinter} which dumps failure - * information along with a preformatted JVM-options string to reproduce the - * given test case (includes seed and filters). - */ -@Listeners({ReproduceInfoPrinter.class}) -public class Test014Listeners extends RandomizedTest { - @Test - public void failure() { - Assert.assertTrue(false); - } -} diff --git a/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/Test015CustomMethodProviders.java b/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/Test015CustomMethodProviders.java deleted file mode 100644 index 10d2494c..00000000 --- a/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/Test015CustomMethodProviders.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.carrotsearch.examples.randomizedrunner; - -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import com.carrotsearch.randomizedtesting.ClassModel; -import com.carrotsearch.randomizedtesting.RandomizedRunner; -import com.carrotsearch.randomizedtesting.RandomizedTest; -import com.carrotsearch.randomizedtesting.TestMethodProvider; -import com.carrotsearch.randomizedtesting.annotations.Repeat; -import com.carrotsearch.randomizedtesting.annotations.TestMethodProviders; - -/** - * Because many people are nearly religious about how test methods - * should be annotated or structured {@link RandomizedRunner} can use - * a custom method selector for designating test methods. - * - *

This class contains a method selector that returns all methods - * that end with a substring Test. - */ -public class Test015CustomMethodProviders { - - public static class MethodEndsWithTest implements TestMethodProvider { - @Override - public Collection getTestMethods(Class clz, ClassModel suiteClassModel) { - /* - * We pick all methods with a "Test" suffix. We also skip methods belonging to - * RandomizedTest (there is a private method ending in Test there and this wouldn't - * validate). Additional validation is performed in the runner (public, non-static, - * no-args methods only allowed). - */ - List result = new ArrayList(); - for (Method m : suiteClassModel.getMethods().keySet()) { - if (m.getName().endsWith("Test") && !m.getDeclaringClass().equals(RandomizedTest.class)) { - result.add(m); - } - } - return result; - } - } - - @TestMethodProviders({ - MethodEndsWithTest.class - }) - public static class TestClass extends RandomizedTest { - public void myFirstTest() { - System.out.println("First test."); - } - - @Repeat(iterations = 5) - public void mySecondTest() { - System.out.println("Second test."); - } - } -} diff --git a/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/Test016CustomTestCaseOrdering.java b/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/Test016CustomTestCaseOrdering.java deleted file mode 100644 index 8eeef6ed..00000000 --- a/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/Test016CustomTestCaseOrdering.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.carrotsearch.examples.randomizedrunner; - -import java.util.Arrays; -import java.util.Comparator; - -import org.junit.Test; - -import com.carrotsearch.randomizedtesting.RandomizedTest; -import com.carrotsearch.randomizedtesting.TestMethodAndParams; -import com.carrotsearch.randomizedtesting.annotations.Name; -import com.carrotsearch.randomizedtesting.annotations.ParametersFactory; -import com.carrotsearch.randomizedtesting.annotations.TestCaseOrdering; - -/** - * Typically you will not want to order test cases and leave them to be - * randomly shuffled by the runner (this prevents any accidental test order - * dependencies). Sometimes, however, it is useful to have tests run in an - * predefined order. - * - * This example demonstrates how to order tests using a custom callback. The - * example uses {@link ParametersFactory} to demonstrate how this can be useful - * with custom arguments. - */ -@TestCaseOrdering(Test016CustomTestCaseOrdering.CustomOrder.class) -public class Test016CustomTestCaseOrdering extends RandomizedTest { - public static class CustomOrder implements Comparator { - public int compare(TestMethodAndParams o1, TestMethodAndParams o2) { - // Order by test method name first, - int v = o1.getTestMethod().getName().compareTo( - o2.getTestMethod().getName()); - // Secondary order: by constructor argument. - if (v == 0) { - v = ((String) o1.getInstanceArguments().get(0)).compareTo( - ((String) o2.getInstanceArguments().get(0))); - } - return v; - } - } - - public String p; - - public Test016CustomTestCaseOrdering(@Name("p") String p) { - this.p = p; - } - - @Test - public void testA() { - } - - @Test - public void testB() { - } - - @ParametersFactory - public static Iterable factory1() { - return Arrays.asList( - $("1"), - $("2"), - $("3")); - } -} diff --git a/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/Test017TestCaseNamingExtreme.java b/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/Test017TestCaseNamingExtreme.java deleted file mode 100644 index 89f86e68..00000000 --- a/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/Test017TestCaseNamingExtreme.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.carrotsearch.examples.randomizedrunner; - -import java.util.Arrays; - -import org.junit.Test; - -import com.carrotsearch.randomizedtesting.RandomizedTest; -import com.carrotsearch.randomizedtesting.annotations.Name; -import com.carrotsearch.randomizedtesting.annotations.ParametersFactory; -import com.carrotsearch.randomizedtesting.annotations.Repeat; -import com.carrotsearch.randomizedtesting.annotations.Seed; -import com.carrotsearch.randomizedtesting.annotations.Seeds; -import com.carrotsearch.randomizedtesting.annotations.TestCaseOrdering; - -/** - * When the test suite is using({@link Repeat}, {@link Seeds} - * and {@link ParametersFactory}), it may happen that a single method - * results in many actual tests. These tests have to be uniquely described - * for JUnit (otherwise there is no way to tell which test case completed, - * for example). The framework always attempts to add a unique suffix - * (repetition number) to test method's description. An extreme - * example of this is shown in this class, which - * repeats a single test with multiple seeds, repetitions and - * two parameter factories which return the same argument multiple times. - */ -@TestCaseOrdering(TestCaseOrdering.AlphabeticOrder.class) -public class Test017TestCaseNamingExtreme extends RandomizedTest { - public String p; - - public Test017TestCaseNamingExtreme(@Name("param") String p) { - this.p = p; - } - - @Test - @Repeat(iterations = 3, useConstantSeed = true) - @Seeds({ - @Seed("00000001"), - @Seed("00000002"), - @Seed("00000003") - }) - public void testMethod() {} - - @ParametersFactory - public static Iterable factory1() { - return Arrays.asList( - $("p1"), - $("p1"), - $("p1")); - } - - @ParametersFactory - public static Iterable factory2() { - return Arrays.asList( - $("p1"), - $("p1"), - $("p1")); - } -} diff --git a/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/Test018TestCaseInstanceProviders.java b/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/Test018TestCaseInstanceProviders.java deleted file mode 100644 index dbf37153..00000000 --- a/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/Test018TestCaseInstanceProviders.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.carrotsearch.examples.randomizedrunner; - -import org.junit.Before; -import org.junit.Test; - -import com.carrotsearch.randomizedtesting.RandomizedRunner; -import com.carrotsearch.randomizedtesting.RandomizedTest; -import com.carrotsearch.randomizedtesting.annotations.Repeat; -import com.carrotsearch.randomizedtesting.annotations.TestCaseInstanceProvider; -import com.carrotsearch.randomizedtesting.annotations.TestCaseInstanceProvider.Type; -import com.carrotsearch.randomizedtesting.annotations.TestCaseOrdering; - -/** - * By default JUnit (and {@link RandomizedRunner}) creates a new class instance - * for every test case it executes. This behavior makes sense to keep inter-test - * dependencies to a minimum, but sometimes it's just plain inconvenient and - * difficult to emulate (with static rules or static fields). - * - * The {@link TestCaseInstanceProvider} permits changing the default behavior so - * that each test method is executed on the same instance of the test - * suite class. - * - * The order of test case execution is still shuffled (unless overridden with - * {@link TestCaseOrdering} so ideally the instance variables should be - * stateless. - * - * Note that certain caveats apply, see the documentation of - * {@link TestCaseInstanceProvider} for details. - */ -@TestCaseInstanceProvider(Type.INSTANCE_PER_CONSTRUCTOR_ARGS) -public class Test018TestCaseInstanceProviders extends RandomizedTest { - /** - * For the sake of the example only, we'll increment the instance's counter by - * one for each test, printing the output to the console. - */ - public int counter; - - /** - * An instance context requiring some "costly" initialization. Note we could - * just add the initialization here, but {@link Before} is nicer because it's - * executed in the context of parent JUnit rules, etc. - */ - public volatile Object costly; - - @Before - public void costlySetup() throws InterruptedException { - // Initialize once. - if (costly == null) { - Thread.sleep(1000); - costly = new Object(); - } - } - - @Test - @Repeat(iterations = 3) - public void addOne() { - System.out.println("counter=" + (++counter) + ", costly=" + costly); - } -} diff --git a/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/reports/Test001AllStatuses.java b/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/reports/Test001AllStatuses.java deleted file mode 100644 index 26c24851..00000000 --- a/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/reports/Test001AllStatuses.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.carrotsearch.examples.randomizedrunner.reports; - -import org.junit.Assert; -import org.junit.Assume; -import org.junit.Ignore; -import org.junit.Test; - -public class Test001AllStatuses { - @Test - public void passed() {} - - @Test - @Ignore - public void ignored() {} - - @Test - public void ignored_assumption() { - Assume.assumeTrue(false); - } - - @Test - public void failure() { - Assert.fail(); - } - - @Test - public void error() { - throw new RuntimeException(); - } -} diff --git a/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/reports/Test002SuiteFailure.java b/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/reports/Test002SuiteFailure.java deleted file mode 100644 index 86627ec1..00000000 --- a/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/reports/Test002SuiteFailure.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.carrotsearch.examples.randomizedrunner.reports; - -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; - -/** - * Suite-level failures. - */ -public class Test002SuiteFailure { - @BeforeClass - public static void beforeClass() { - throw new RuntimeException("beforeClass"); - } - - @Test - public void testCase() {} - - @AfterClass - public static void afterClass() { - throw new RuntimeException("afterClass"); - } -} diff --git a/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/reports/Test003MultipleFailures.java b/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/reports/Test003MultipleFailures.java deleted file mode 100644 index 30ecbf29..00000000 --- a/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/reports/Test003MultipleFailures.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.carrotsearch.examples.randomizedrunner.reports; - -import java.util.Arrays; - -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TestRule; -import org.junit.runner.Description; -import org.junit.runners.model.MultipleFailureException; -import org.junit.runners.model.Statement; - -/** - * Multiple failures from a single test case (followed by a suite-failure). - */ -public class Test003MultipleFailures { - @Rule - public TestRule rule = new TestRule() { - @Override - public Statement apply(final Statement base, Description description) { - return new Statement() { - @Override - public void evaluate() throws Throwable { - try { - base.evaluate(); - } catch (Throwable t) { - throw new MultipleFailureException(Arrays.asList( - t, - new Exception("a"), - new Exception("b"))); - } - } - }; - } - }; - - @Test - public void testCase() { - throw new RuntimeException("testCase"); - } - - @After - public void after() { - throw new RuntimeException("after"); - } - - @AfterClass - public static void afterClass() { - throw new RuntimeException("afterClass"); - } -} diff --git a/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/reports/Test004SuiteOfNested.java b/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/reports/Test004SuiteOfNested.java deleted file mode 100644 index 38abfccb..00000000 --- a/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/reports/Test004SuiteOfNested.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.carrotsearch.examples.randomizedrunner.reports; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; -import org.junit.runners.Suite.SuiteClasses; - -/** - * A suite of nested test classes. - */ -@RunWith(Suite.class) -@SuiteClasses({ - Test004SuiteOfNested.Subclass1.class, - Test004SuiteOfNested.Subclass2.class, - Test004SuiteOfNested.Subclass3.class -}) -public class Test004SuiteOfNested { - public static class Subclass1 extends Test001AllStatuses { - } - - public static class Subclass2 extends Subclass1 { - } - - public static class Subclass3 extends Subclass1 { - } -} diff --git a/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/reports/Test005WithOutput.java b/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/reports/Test005WithOutput.java deleted file mode 100644 index 6d0b9f08..00000000 --- a/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/reports/Test005WithOutput.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.carrotsearch.examples.randomizedrunner.reports; - -import org.junit.Test; - - -/** - * A suite of nested test classes. - */ -public class Test005WithOutput { - @Test - public void stdout() { - System.out.print("stdout-noeol"); - } - - @Test - public void stdout_eol() { - System.out.print("stdout-witheol\n"); - } - - @Test - public void stderr() { - System.err.print("stderr-noeol"); - } - - @Test - public void stderr_eol() { - System.err.print("stderr-witheol\n"); - } - - @Test - public void stderr_stdout_interwoven() { - System.out.print("stdout-begin-"); - System.out.flush(); - System.err.print("stderr-begin-"); - System.err.flush(); - System.out.print("stdout-end"); - System.out.flush(); - System.err.print("stderr-end"); - System.err.flush(); - } - - @Test - public void longline() { - for (int i = 0; i < 1000; i++) { - System.out.print((i % 10) + '0'); - } - System.out.println("... and done."); - } -} diff --git a/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/reports/Test006BeforeClassFailure.java b/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/reports/Test006BeforeClassFailure.java deleted file mode 100644 index 2b5f376f..00000000 --- a/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/reports/Test006BeforeClassFailure.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.carrotsearch.examples.randomizedrunner.reports; - -import org.junit.Assert; - -import org.junit.BeforeClass; -import org.junit.Test; - -/** */ -public class Test006BeforeClassFailure { - @BeforeClass - public static void failOnMe() { - Assert.assertTrue(false); - } - - @Test - public void noop() { - } -} diff --git a/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/reports/Test006BeforeClassFailureRR.java b/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/reports/Test006BeforeClassFailureRR.java deleted file mode 100644 index 7deaa3eb..00000000 --- a/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/reports/Test006BeforeClassFailureRR.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.carrotsearch.examples.randomizedrunner.reports; - -import org.junit.Assert; - -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; - -import com.carrotsearch.randomizedtesting.RandomizedRunner; - -/** */ -@RunWith(RandomizedRunner.class) -public class Test006BeforeClassFailureRR { - @BeforeClass - public static void failOnMe() { - Assert.assertTrue(false); - } - - @Test - public void noop() { - } -} diff --git a/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/reports/Test007BeforeClassError.java b/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/reports/Test007BeforeClassError.java deleted file mode 100644 index 03832d81..00000000 --- a/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/reports/Test007BeforeClassError.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.carrotsearch.examples.randomizedrunner.reports; - -import org.junit.BeforeClass; -import org.junit.Test; - -/** */ -public class Test007BeforeClassError { - @BeforeClass - public static void errorOnMe() { - throw new RuntimeException(); - } - - @Test - public void noop() { - } -} diff --git a/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/reports/Test007BeforeClassErrorRR.java b/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/reports/Test007BeforeClassErrorRR.java deleted file mode 100644 index f960b992..00000000 --- a/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/reports/Test007BeforeClassErrorRR.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.carrotsearch.examples.randomizedrunner.reports; - -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; - -import com.carrotsearch.randomizedtesting.RandomizedRunner; - -/** */ -@RunWith(RandomizedRunner.class) -public class Test007BeforeClassErrorRR { - @BeforeClass - public static void errorOnMe() { - throw new RuntimeException(); - } - - @Test - public void noop() { - } -} diff --git a/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/reports/Test008BeforeClassAssumption.java b/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/reports/Test008BeforeClassAssumption.java deleted file mode 100644 index 89603f90..00000000 --- a/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/reports/Test008BeforeClassAssumption.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.carrotsearch.examples.randomizedrunner.reports; - -import org.junit.*; - -/** */ -public class Test008BeforeClassAssumption { - @BeforeClass - public static void assumeMe() { - Assume.assumeTrue(false); - } - - @Test - public void noop() { - } -} diff --git a/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/reports/Test008BeforeClassAssumptionRR.java b/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/reports/Test008BeforeClassAssumptionRR.java deleted file mode 100644 index ad4fdd4d..00000000 --- a/examples/maven/src/main/java/com/carrotsearch/examples/randomizedrunner/reports/Test008BeforeClassAssumptionRR.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.carrotsearch.examples.randomizedrunner.reports; - -import org.junit.*; -import org.junit.runner.RunWith; - -import com.carrotsearch.randomizedtesting.RandomizedRunner; - -/** */ -@RunWith(RandomizedRunner.class) -public class Test008BeforeClassAssumptionRR { - @BeforeClass - public static void assumeMe() { - Assume.assumeTrue(false); - } - - @Test - public void noop() { - } -} diff --git a/examples/security-manager/pom.xml b/examples/security-manager/pom.xml deleted file mode 100644 index 06c7a461..00000000 --- a/examples/security-manager/pom.xml +++ /dev/null @@ -1,165 +0,0 @@ - - 4.0.0 - - - com.carrotsearch.randomizedtesting - randomizedtesting-parent - 2.7.9-SNAPSHOT - ../../pom.xml - - - randomizedtesting-security-manager-example - RandomizedTesting Security Manager Example - - - Simple use-case running with security manager - - - - true - - - - - com.carrotsearch.randomizedtesting - randomizedtesting-runner - ${project.version} - compile - - - - com.carrotsearch.randomizedtesting - junit4-ant - ${project.version} - test - - - - junit - junit - compile - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - - default-test - none - - - - - - - org.apache.maven.plugins - maven-antrun-plugin - - - - run - - pre-integration-test - - true - - - - - - - - - - - - org.apache.maven.plugins - maven-enforcer-plugin - - - enforce-urls-were-set - - enforce - - pre-integration-test - - - - junit.jar.url - junit4.jar.url - randomizedtesting.jar.url - - - - - - - - - - com.carrotsearch.randomizedtesting - junit4-maven-plugin - ${project.version} - - - junit4-tests - - junit4 - - - integration-test - - false - true - - - - - - - - - - - - - - - - - - - - - -Djava.security.manager - -Djava.security.policy==${project.basedir}/security.policy - -Djava.security.debug=all - -Djunit.jar.url=${junit.jar.url} - -Djunit4.jar.url=${junit4.jar.url} - -Drandomizedtesting.jar.url=${randomizedtesting.jar.url} - - - - - - - - diff --git a/examples/security-manager/security.policy b/examples/security-manager/security.policy deleted file mode 100644 index 8ff49eaa..00000000 --- a/examples/security-manager/security.policy +++ /dev/null @@ -1,46 +0,0 @@ -// policy file for tests - -//// These permissions apply to the JDK itself -//// (actually only needed for "extensions") - -grant codeBase "file:${{java.ext.dirs}}/*" { - permission java.security.AllPermission; -}; - -//// permission for the junit4 jar -grant codeBase "${junit4.jar.url}" { - // needed for io stream handling - permission java.lang.RuntimePermission "setIO"; - // workaround for junit access control context bug in processing - // class test request. - permission java.lang.RuntimePermission "accessDeclaredMembers"; -}; - -//// permissions for the randomized runner jar -grant codeBase "${randomizedtesting.jar.url}" { - // optionally needed for access to private test methods (e.g. beforeClass) - permission java.lang.reflect.ReflectPermission "suppressAccessChecks"; - // needed to handle uncaught exceptions from other threads - permission java.lang.RuntimePermission "setDefaultUncaughtExceptionHandler"; - // needed for getTopThreads - permission java.lang.RuntimePermission "modifyThreadGroup"; - // needed for TestClass creation - permission java.lang.RuntimePermission "accessDeclaredMembers"; - // needed for ThreadLeakControl - permission java.lang.RuntimePermission "getStackTrace"; -}; - -//// permissions for the junit jar -grant codeBase "${junit.jar.url}" { - // needed for TestClass creation - permission java.lang.RuntimePermission "accessDeclaredMembers"; -}; - -//// Test class permission: we want this to be minimal! -grant { - permission java.util.PropertyPermission "*", "read"; - - //// Java7 and up. - //// permission java.io.FilePermission "<>", "read,readlink,write,delete,execute"; - permission java.io.FilePermission "<>", "read,write,delete,execute"; -}; diff --git a/examples/security-manager/src/test/java/com/carrotsearch/examples/randomizedrunner/DelegatingRunner.java b/examples/security-manager/src/test/java/com/carrotsearch/examples/randomizedrunner/DelegatingRunner.java deleted file mode 100644 index 95a14009..00000000 --- a/examples/security-manager/src/test/java/com/carrotsearch/examples/randomizedrunner/DelegatingRunner.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.carrotsearch.examples.randomizedrunner; - -import org.junit.runner.Description; -import org.junit.runner.Runner; -import org.junit.runner.manipulation.Filter; -import org.junit.runner.manipulation.Filterable; -import org.junit.runner.manipulation.NoTestsRemainException; -import org.junit.runner.notification.RunNotifier; -import org.junit.runners.model.InitializationError; - -import com.carrotsearch.randomizedtesting.RandomizedRunner; - -/** Pollutes the stack with non-RR code, so we know the AccessController - blocks are correct. */ -public class DelegatingRunner extends Runner implements Filterable { - private final RandomizedRunner delegate; - - public DelegatingRunner(Class testClass) throws InitializationError { - delegate = new RandomizedRunner(testClass); - } - - @Override - public int testCount() { - return delegate.testCount(); - } - - @Override - public void filter(Filter filter) throws NoTestsRemainException { - delegate.filter(filter); - } - - @Override - public Description getDescription() { - return delegate.getDescription(); - } - - @Override - public void run(RunNotifier notifier) { - delegate.run(notifier); - } -} diff --git a/examples/security-manager/src/test/java/com/carrotsearch/examples/randomizedrunner/TestExample.java b/examples/security-manager/src/test/java/com/carrotsearch/examples/randomizedrunner/TestExample.java deleted file mode 100644 index 435c254a..00000000 --- a/examples/security-manager/src/test/java/com/carrotsearch/examples/randomizedrunner/TestExample.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.carrotsearch.examples.randomizedrunner; - -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; - -import com.carrotsearch.randomizedtesting.JUnit4MethodProvider; -import com.carrotsearch.randomizedtesting.MixWithSuiteName; -import com.carrotsearch.randomizedtesting.annotations.SeedDecorators; -import com.carrotsearch.randomizedtesting.annotations.TestMethodProviders; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakAction.Action; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakAction; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakGroup.Group; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakGroup; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakLingering; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope.Scope; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakZombies.Consequence; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakZombies; -import com.carrotsearch.randomizedtesting.annotations.TimeoutSuite; - -@RunWith(DelegatingRunner.class) -@TestMethodProviders({ - JUnit4MethodProvider.class -}) -@SeedDecorators({MixWithSuiteName.class}) // See LUCENE-3995 for rationale. -@ThreadLeakScope(Scope.SUITE) -@ThreadLeakGroup(Group.MAIN) -@ThreadLeakAction({Action.WARN, Action.INTERRUPT}) -@ThreadLeakLingering(linger = 20000) // Wait long for leaked threads to complete before failure. zk needs this. -@ThreadLeakZombies(Consequence.IGNORE_REMAINING_TESTS) -@TimeoutSuite(millis = 200000000) -public class TestExample extends Assert { - - @BeforeClass - private static void beforeClassPrivate() { - System.out.println("beforeClassPrivate"); - } - - @Test - public void test() { - System.out.println("test"); - } - - @Test - public void noPermissions() { - System.err.println("checking permission system."); - try { - System.setProperty("foo", "bar"); - fail(); - } catch (SecurityException e) { - // Expected! - } - } -} diff --git a/examples/src/test/java/com/carrotsearch/randomizedtesting/examples/Test001SimpleUseCase.java b/examples/src/test/java/com/carrotsearch/randomizedtesting/examples/Test001SimpleUseCase.java new file mode 100644 index 00000000..a57fa5f5 --- /dev/null +++ b/examples/src/test/java/com/carrotsearch/randomizedtesting/examples/Test001SimpleUseCase.java @@ -0,0 +1,62 @@ +package com.carrotsearch.randomizedtesting.examples; + +import com.carrotsearch.randomizedtesting.api.Randomized; +import com.carrotsearch.randomizedtesting.api.RandomizedContext; +import com.carrotsearch.randomizedtesting.extensions.RandomizedContextProviderExtension; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.RepeatedTest; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; + +import java.util.Locale; + +@ExtendWith({RandomizedContextProviderExtension.class}) +public class Test001SimpleUseCase { + + @BeforeAll + public static void beforeAll1(RandomizedContext context) { + log("BeforeAll1", context); + } + + private static void log(String prefix, RandomizedContext context) { + System.out.printf( + Locale.ROOT, + "prefix: %15s, %016x %s%n", + prefix, + context.getRandom().nextLong(), + context.getSeedChain()); + } + + @BeforeAll + public static void beforeAll2(RandomizedContext context) { + log("BeforeAll2", context); + } + + public Test001SimpleUseCase() { + //log(" Constructor", context); + } + + @BeforeEach + public void beforeEach(RandomizedContext context) { + log(" BeforeEach", context); + } + + @AfterEach + public void afterEach(RandomizedContext context) { + log(" AfterEach", context); + } + + @Randomized + @Test + public void testMethod1(RandomizedContext context) { + log(" Method1", context); + } + + @Randomized + @RepeatedTest(10) + public void testMethod2(RandomizedContext context) { + log(" Method2", context); + } +} diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 00000000..a47b68a3 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,8 @@ +systemProp.file.encoding=UTF-8 + +org.gradle.parallel=true +org.gradle.priority=low +org.gradle.workers.max=4 + +systemProp.org.gradle.internal.http.connectionTimeout=300000 +systemProp.org.gradle.internal.http.socketTimeout=300000 diff --git a/gradle/ide/idea.gradle b/gradle/ide/idea.gradle new file mode 100644 index 00000000..b9101702 --- /dev/null +++ b/gradle/ide/idea.gradle @@ -0,0 +1,47 @@ + +// Try to detect IntelliJ model loader early. +rootProject.ext { + isIdea = System.getProperty("idea.active") != null || + gradle.startParameter.taskNames.contains('idea') || + gradle.startParameter.taskNames.contains('cleanIdea') + + if (isIdea) { + logger.lifecycle("IntelliJ Idea IDE detected.") + } +} + +// Apply intellij plugin to all projects. +allprojects { + apply plugin: 'idea' + + idea { + module { + outputDir file('build/idea/classes/main') + testOutputDir file('build/idea/classes/test') + downloadSources = true + } + } +} + +// GH-37: skip certain long tasks if we're building within IntelliJ. +// +// The exception is when we're launching something - then it's very likely +// we'll need to build packages from scratch. +if (rootProject.isIdea && !rootProject.properties.keySet().any {it.startsWith("intellij.launch") }) { + gradle.taskGraph.whenReady { taskGraph -> + def tasks = taskGraph.getAllTasks() + + def skipTasks = [ + // Skip WAR or ZIP assembly. + ".*:(war|zip)" + ] + + tasks.each { task -> + def taskPath = task.path + if (skipTasks.any {pattern -> taskPath ==~ pattern}) { + logger.debug("Skipping task on IntelliJ: " + taskPath) + task.enabled = false + } + } + } +} \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000..7454180f Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..a0f7639f --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-7.2-all.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 00000000..744e882e --- /dev/null +++ b/gradlew @@ -0,0 +1,185 @@ +#!/usr/bin/env sh + +# +# Copyright 2015 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 +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MSYS* | MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin or MSYS, switch paths to Windows format before running java +if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=`expr $i + 1` + done + case $i in + 0) set -- ;; + 1) set -- "$args0" ;; + 2) set -- "$args0" "$args1" ;; + 3) set -- "$args0" "$args1" "$args2" ;; + 4) set -- "$args0" "$args1" "$args2" "$args3" ;; + 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=`save "$@"` + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 00000000..ac1b06f9 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,89 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/junit4-ant/lib/junit-4.9.jar b/junit4-ant/lib/junit-4.9.jar deleted file mode 100644 index 14208156..00000000 Binary files a/junit4-ant/lib/junit-4.9.jar and /dev/null differ diff --git a/junit4-ant/lib/proguard.jar b/junit4-ant/lib/proguard.jar deleted file mode 100644 index ceedb309..00000000 Binary files a/junit4-ant/lib/proguard.jar and /dev/null differ diff --git a/junit4-ant/pom.xml b/junit4-ant/pom.xml deleted file mode 100644 index 1a257290..00000000 --- a/junit4-ant/pom.xml +++ /dev/null @@ -1,311 +0,0 @@ - - 4.0.0 - - - com.carrotsearch.randomizedtesting - randomizedtesting-parent - 2.7.9-SNAPSHOT - ../pom.xml - - - junit4-ant - - - - ${java.home} - ${proguard.java.home}/lib/rt.jar - - - - - org.apache.ant - ant - provided - - - - org.apache.ant - ant-junit - provided - - - - - - junit - junit - jar - provided - - - - - - com.google.guava - guava - provided - - - - org.ow2.asm - asm - provided - - - - com.carrotsearch.thirdparty - simple-xml-safe - provided - - - - com.carrotsearch.randomizedtesting - randomizedtesting-runner - ${project.version} - provided - - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - ${version.maven-surefire-plugin} - - - ${project.build.directory}/test-classes - - - **/tests/** - **/it/** - - - - - - - surefire-it - integration-test - - test - - - - **/it/Test*.java - - - **/tests/** - - ${project.build.directory}/dontinclude - - com.carrotsearch.randomizedtesting:randomizedtesting-runner - com.google.guava:guava - - - - - - - - org.eclipse.m2e - lifecycle-mapping - 1.0.0 - - - - - - org.apache.maven.plugins - maven-dependency-plugin - [1.0.0,) - - copy-dependencies - - - - - - - - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - ${version.maven-javadoc-plugin} - - ${basedir}/src/main/java/com/carrotsearch/ant/tasks/junit4/package.html - - - JUnit4 ANT task - com.carrotsearch.ant.tasks.junit4* - - - Listeners and report writers - com.carrotsearch.ant.tasks.junit4.listeners* - - - Load balancers - com.carrotsearch.ant.tasks.junit4.balancers* - - - Events and aggregated events for reports - com.carrotsearch.ant.tasks.junit4.events* - - -

${project.name} v${project.version}
API Documentation]]>
- com.carrotsearch.ant.tasks.junit4.slave - - - - - - - - de.thetaphi - forbiddenapis - - - - org.apache.maven.plugins - maven-dependency-plugin - - - copy-dependencies - package - - copy-dependencies - - - - - com.carrotsearch.randomizedtesting,junit,org.hamcrest,org.ow2.asm - - - - - org.apache.maven.plugins - maven-jar-plugin - - true - - - - - com.pyx4me - proguard-maven-plugin - 2.0.4 - - - package - - proguard - - - - - - - - com.google.guava - guava - !com/google/common/eventbus/SynchronizedEventHandler.class - - - org.ow2.asm - asm - !module-info.class - - - com.carrotsearch.thirdparty - simple-xml-safe - - - com.carrotsearch.randomizedtesting - randomizedtesting-runner - - - - - true - true - false - true - ${project.build.directory} - ${basedir}/src/proguard/rules.pro - - - - - ${proguard.rt.jar} - - - - - net.sf.proguard - proguard - 4.6-customized - system - ${project.basedir}/lib/proguard.jar - - - - - - - - src/main/resources - - **/*.jsonp - **/ideas.txt - - - - - - - - jdk19-compat - - [1.9,] - - - - - org.apache.maven.plugins - maven-enforcer-plugin - ${version.maven-enforcer-plugin} - false - - - enforce-proguard-java-home - validate - - enforce - - - - - - ${proguard.rt.jar} - - - IMPORTANT! You must set proguard.rt.jar or proguard.java.home manually for obfuscation. - - - - - - - - - - - - - diff --git a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/BalancersList.java b/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/BalancersList.java deleted file mode 100644 index 73dc98d1..00000000 --- a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/BalancersList.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4; - -import java.util.List; - -/** - * A nested list of {@link SuiteBalancer}s. - */ -public class BalancersList { - private List balancers; - - public BalancersList(List balancers) { - this.balancers = balancers; - } - - /** - * Adds a balancer to the balancers list. - */ - public void addConfigured(SuiteBalancer balancer) { - balancers.add(balancer); - } -} diff --git a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/DiagnosticsListener.java b/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/DiagnosticsListener.java deleted file mode 100644 index 37cda0ee..00000000 --- a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/DiagnosticsListener.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4; - -import org.apache.tools.ant.Project; -import org.apache.tools.ant.Task; - -import com.carrotsearch.ant.tasks.junit4.events.BootstrapEvent; -import com.carrotsearch.ant.tasks.junit4.events.IEvent; -import com.carrotsearch.ant.tasks.junit4.events.QuitEvent; -import com.google.common.eventbus.Subscribe; - -public class DiagnosticsListener { - private final ForkedJvmInfo slave; - - private boolean quitReceived; - private Task task; - - public DiagnosticsListener(ForkedJvmInfo slave, JUnit4 task) { - this.task = task; - this.slave = slave; - } - - @Subscribe - public void receiveAll(IEvent e) { - task.log("Packet received, slave#" + slave.id + ">" + e.getType(), Project.MSG_DEBUG); - } - - @Subscribe - public void receiveBootstrap(BootstrapEvent e) { - task.log("Default encoding: " + e.getDefaultCharsetName(), Project.MSG_VERBOSE); - } - - @Subscribe - public void receiveQuit(QuitEvent e) { - quitReceived = true; - } - - boolean quitReceived() { - return quitReceived; - } -} diff --git a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/DuplicateResources.java b/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/DuplicateResources.java deleted file mode 100644 index 08a4f72d..00000000 --- a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/DuplicateResources.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import org.apache.tools.ant.types.DataType; -import org.apache.tools.ant.types.Resource; -import org.apache.tools.ant.types.ResourceCollection; - -/** - * Duplicate nested resources N times. Useful for running - * suites multiple times with load balancing. - */ -public class DuplicateResources extends DataType implements ResourceCollection { - private final List rcs = new ArrayList(); - private int times; - - public void addConfigured(ResourceCollection rc) { - this.rcs.add(rc); - } - - /** - * Set the number of times the input resources should be duplicated. - */ - public void setTimes(int times) { - this.times = times; - } - - @Override - public Iterator iterator() { - return getElements().iterator(); - } - - private List getElements() { - List elements = new ArrayList<>(); - for (ResourceCollection rc : rcs) { - for (Resource r : rc) { - for (int t = 0; t < times; t++) { - elements.add(r); - } - } - } - return elements; - } - - @Override - public int size() { - return getElements().size(); - } - - @Override - public boolean isFilesystemOnly() { - for (Iterator i = iterator(); i.hasNext();) { - if (!((Resource) i.next()).isFilesystemOnly()) { - return false; - } - } - return true; - } -} diff --git a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/Duration.java b/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/Duration.java deleted file mode 100644 index 1ba02b72..00000000 --- a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/Duration.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4; - -import java.util.Locale; - -public final class Duration { - /** - * Format a duration in milliseconds to a human string (in English). - */ - public static CharSequence toHumanDuration(long duration) { - final long MILLIS_IN_A_SECOND = 1000; - final long MILLIS_IN_A_MINUTE = MILLIS_IN_A_SECOND * 60; - final long MILLIS_IN_AN_HOUR = MILLIS_IN_A_MINUTE * 60; - final long MILLIS_IN_A_DAY = MILLIS_IN_AN_HOUR * 24; - - boolean longTime = (duration >= MILLIS_IN_A_SECOND * 10); - - StringBuilder str = new StringBuilder(); - duration = emitOrSkip(duration, str, MILLIS_IN_A_DAY, " day", true); - duration = emitOrSkip(duration, str, MILLIS_IN_AN_HOUR, " hour", true); - duration = emitOrSkip(duration, str, MILLIS_IN_A_MINUTE, " minute", true); - if (longTime) { - duration = emitOrSkip(duration, str, MILLIS_IN_A_SECOND, " second", true); - } else { - str.append(String.format(Locale.ROOT, "%.2f sec.", (duration / 1000.0f))); - } - return str; - } - - private static long emitOrSkip(long value, StringBuilder str, long unit, String unitName, boolean skipEmpty) { - final long units = value / unit; - if (units != 0 || !skipEmpty) { - if (str.length() > 0) str.append(" "); - str.append(units) - .append(Pluralize.pluralize((int) units, unitName)); - } - - value -= units * unit; - return value; - } -} diff --git a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/ForkedJvmInfo.java b/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/ForkedJvmInfo.java deleted file mode 100644 index 09156616..00000000 --- a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/ForkedJvmInfo.java +++ /dev/null @@ -1,174 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4; - -import java.io.IOException; -import java.io.Writer; -import java.nio.charset.Charset; -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; -import java.util.Map; - -import com.carrotsearch.ant.tasks.junit4.events.BootstrapEvent; -import com.carrotsearch.ant.tasks.junit4.events.IEvent; -import com.carrotsearch.ant.tasks.junit4.events.IStreamEvent; -import com.carrotsearch.ant.tasks.junit4.gson.stream.JsonWriter; -import com.carrotsearch.randomizedtesting.WriterOutputStream; - -/** - * Static slave information. - */ -public final class ForkedJvmInfo { - /** - * Unique sequential slave identifier. - */ - public final int id; - - /** - * The number of executed slaves, total. - */ - public final int slaves; - - /** - * Bootstrap event. - */ - private BootstrapEvent bootstrapEvent; - - /** - * Timestamps for diagnostics. - */ - long start, end; - - /** - * Execute these test suites on this slave. - */ - ArrayList testSuites; - - /** - * Complete slave command line invocation string. - */ - String slaveCommandLine; - - /** - * Execution error if anything bad happened on the slave. - */ - Throwable executionError; - - /* */ - public ForkedJvmInfo(int id, int slaves) { - this.id = id; - this.slaves = slaves; - } - - /** - * Return the {@link Charset} used to encode stream bytes from the slave. - */ - public Charset getCharset() { - if (bootstrapEvent != null) { - return Charset.forName(bootstrapEvent.getDefaultCharsetName()); - } else { - return Charset.defaultCharset(); - } - } - - /** - * System properties on the slave. - */ - public Map getSystemProperties() { - if (bootstrapEvent == null) { - throw new RuntimeException("Bootstrap event not yet received."); - } - - return bootstrapEvent.getSystemProperties(); - } - - /** - * PID string of the forked JVM. May not be available or may come in an unknown format - * (Java 8 will have real PID support, supposedly). - */ - public String getPidString() { - BootstrapEvent event = this.bootstrapEvent; - if (event == null) { - return "(?)"; - } else { - return event.getPidString(); - } - } - - /** - * Command line string used to invoke the slave. - */ - public String getCommandLine() { - return slaveCommandLine; - } - - /** - * JVM name (slave). - */ - public String getJvmName() { - return getSystemProperties().get("java.vm.name") + ", " + - getSystemProperties().get("java.vm.version"); - } - - /** - * Slave execution time. - */ - long getExecutionTime() { - return end - start; - } - - /** - * Set the bootstrap event associated with this slave. - */ - void setBootstrapEvent(BootstrapEvent e) { - this.bootstrapEvent = e; - } - - /** - * Filter through events looking for sysouts and syserrs and decode them - * into a character streams. If both {@link Writer} arguments are the same object - * the streams will be combined. - */ - public void decodeStreams(List events, Writer sysout, Writer syserr) throws IOException { - int lineBuffer = 160; - WriterOutputStream stdout = new WriterOutputStream(sysout, getCharset(), lineBuffer, true); - WriterOutputStream stderr = new WriterOutputStream(syserr, getCharset(), lineBuffer, true); - for (IEvent evt : events) { - switch (evt.getType()) { - case APPEND_STDOUT: - if (sysout != null) { - ((IStreamEvent) evt).copyTo(stdout); - } - break; - - case APPEND_STDERR: - if (syserr != null) { - ((IStreamEvent) evt).copyTo(stderr); - } - break; - - default: - break; - } - } - - stdout.flush(); - stderr.flush(); - } - - public void serialize(JsonWriter w) throws IOException { - w.beginObject(); - - w.name("id").value(id); - w.name("jvmName").value(getJvmName()); - w.name("charset").value(getCharset().displayName(Locale.ROOT)); - w.name("commandLine").value(getCommandLine()); - - w.name("systemProperties").beginObject(); - for (Map.Entry e : getSystemProperties().entrySet()) { - w.name(e.getKey()).value(e.getValue()); - } - w.endObject(); - - w.endObject(); - } -} diff --git a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/FormattingUtils.java b/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/FormattingUtils.java deleted file mode 100644 index 888fc995..00000000 --- a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/FormattingUtils.java +++ /dev/null @@ -1,70 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4; - -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Locale; - -import org.junit.runner.Description; - -/** - * Formatting utilities for consistency across code. - */ -public final class FormattingUtils { - /* */ - public static String padTo(int columns, String text, String ellipsis) { - if (text.length() < columns) { - return text; - } - - text = ellipsis + text.substring(text.length() - (columns - ellipsis.length())); - return text; - } - - public static String formatTime(long timestamp) { - return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.ROOT).format(new Date(timestamp)); - } - - public static String formatTimestamp(long ts) { - return new SimpleDateFormat("HH:mm:ss.SSS", Locale.ROOT).format(new Date(ts)); - } - - public static String formatDurationInSeconds(long timeMillis) { - final int precision; - if (timeMillis >= 100 * 1000) { - precision = 0; - } else if (timeMillis >= 10 * 1000) { - precision = 1; - } else { - precision = 2; - } - return String.format(Locale.ROOT, "%4." + precision + "fs", timeMillis / 1000.0); - } - - public static String formatDescription(Description description) { - return formatDescription(description, false); - } - - public static String formatDescription(Description description, boolean fullNames) { - StringBuilder buffer = new StringBuilder(); - String className = description.getClassName(); - if (className != null) { - if (fullNames) { - buffer.append(className); - } else { - String [] components = className.split("[\\.]"); - className = components[components.length - 1]; - buffer.append(className); - } - if (description.getMethodName() != null) { - buffer.append(".").append(description.getMethodName()); - } else { - buffer.append(" (suite)"); - } - } else { - if (description.getMethodName() != null) { - buffer.append(description.getMethodName()); - } - } - return buffer.toString(); - } -} diff --git a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/JUnit4.java b/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/JUnit4.java deleted file mode 100644 index f4b3e833..00000000 --- a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/JUnit4.java +++ /dev/null @@ -1,1912 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4; - -import static com.carrotsearch.randomizedtesting.SysGlobals.*; - -import java.io.BufferedInputStream; -import java.io.BufferedOutputStream; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.PrintWriter; -import java.io.RandomAccessFile; -import java.io.Serializable; -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; -import java.nio.file.*; -import java.nio.file.attribute.BasicFileAttributes; -import java.text.SimpleDateFormat; -import java.util.ArrayDeque; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; -import java.util.Date; -import java.util.Deque; -import java.util.EnumSet; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Properties; -import java.util.Random; -import java.util.Vector; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicReference; -import java.util.regex.Pattern; -import java.util.stream.Collectors; - -import com.carrotsearch.ant.tasks.junit4.runlisteners.RunListenerClass; -import org.apache.tools.ant.AntClassLoader; -import org.apache.tools.ant.BuildException; -import org.apache.tools.ant.Project; -import org.apache.tools.ant.ProjectComponent; -import org.apache.tools.ant.Task; -import org.apache.tools.ant.taskdefs.Execute; -import org.apache.tools.ant.types.Assertions; -import org.apache.tools.ant.types.Commandline; -import org.apache.tools.ant.types.CommandlineJava; -import org.apache.tools.ant.types.Environment; -import org.apache.tools.ant.types.Environment.Variable; -import org.apache.tools.ant.types.FileSet; -import org.apache.tools.ant.types.PropertySet; -import org.apache.tools.ant.types.Resource; -import org.apache.tools.ant.types.ResourceCollection; -import org.apache.tools.ant.types.resources.Resources; -import org.apache.tools.ant.util.LoaderUtils; -import org.junit.runner.Description; -import org.objectweb.asm.AnnotationVisitor; -import org.objectweb.asm.ClassReader; -import org.objectweb.asm.ClassVisitor; -import org.objectweb.asm.Opcodes; -import org.objectweb.asm.Type; - -import com.carrotsearch.ant.tasks.junit4.SuiteBalancer.Assignment; -import com.carrotsearch.ant.tasks.junit4.balancers.RoundRobinBalancer; -import com.carrotsearch.ant.tasks.junit4.balancers.SuiteHint; -import com.carrotsearch.ant.tasks.junit4.events.BootstrapEvent; -import com.carrotsearch.ant.tasks.junit4.events.QuitEvent; -import com.carrotsearch.ant.tasks.junit4.events.aggregated.AggregatedQuitEvent; -import com.carrotsearch.ant.tasks.junit4.events.aggregated.AggregatedStartEvent; -import com.carrotsearch.ant.tasks.junit4.events.aggregated.AggregatingListener; -import com.carrotsearch.ant.tasks.junit4.events.aggregated.ChildBootstrap; -import com.carrotsearch.ant.tasks.junit4.events.aggregated.JvmOutputEvent; -import com.carrotsearch.ant.tasks.junit4.listeners.AggregatedEventListener; -import com.carrotsearch.ant.tasks.junit4.slave.SlaveMain; -import com.carrotsearch.ant.tasks.junit4.slave.SlaveMainSafe; -import com.carrotsearch.randomizedtesting.ClassGlobFilter; -import com.carrotsearch.randomizedtesting.FilterExpressionParser; -import com.carrotsearch.randomizedtesting.FilterExpressionParser.Node; -import com.carrotsearch.randomizedtesting.MethodGlobFilter; -import com.carrotsearch.randomizedtesting.RandomizedRunner; -import com.carrotsearch.randomizedtesting.SeedUtils; -import com.carrotsearch.randomizedtesting.SysGlobals; -import com.carrotsearch.randomizedtesting.TeeOutputStream; -import com.carrotsearch.randomizedtesting.annotations.SuppressForbidden; -import com.carrotsearch.randomizedtesting.generators.RandomPicks; -import com.google.common.base.Joiner; -import com.google.common.base.MoreObjects; -import com.google.common.base.Strings; -import com.google.common.base.Throwables; -import com.google.common.eventbus.EventBus; -import com.google.common.eventbus.Subscribe; -import com.google.common.io.CharStreams; -import com.google.common.io.Closeables; -import com.google.common.io.Closer; -import com.google.common.io.FileWriteMode; - -/** - * An ANT task to run JUnit4 tests. Differences (benefits?) compared to ANT's default JUnit task: - *
    - *
  • Built-in parallel test execution support (spawns multiple JVMs to avoid - * test interactions).
  • - *
  • Randomization of the order of test suites within a single JVM.
  • - *
  • Aggregates and synchronizes test events from executors. All reports run on - * the task's JVM (not on the test JVM).
  • - *
  • Fully configurable reporting via listeners (console, ANT-compliant XML, JSON). - * Report listeners use Google Guava's {@link EventBus} and receive full information - * about tests' execution (including skipped, assumption-skipped tests, streamlined - * output and error stream chunks, etc.).
  • - *
  • JUnit 4.10+ is required both for the task and for the tests classpath. - * Older versions will cause build failure.
  • - *
  • Integration with {@link RandomizedRunner} (randomization seed is passed to - * children JVMs).
  • - *
- */ -public class JUnit4 extends Task { - /** - * Welcome messages. - */ - private static String [] WELCOME_MESSAGES = { - "hello!", // en - "hi!", // en - "g'day!", // en, australia - "¡Hola!", // es - "jolly good day!", // monty python - "aloha!", // en, hawaii - "cześć!", // pl - "مرحبا!", // arabic (modern) - "kaixo!", // basque - "Привет!", // bulgarian, russian - "你好!", // cn, traditional - "ahoj!", // czech - "salut!", // french - "hallo!", // german - "שלו×!", // hebrew - "नमसà¥à¤¤à¥‡!", // hindi - "áŠáƒ!", // inuktitut - "ciao!", // italian - "今日ã¯!", // japanese - "olá!", // portuguese - // add more if your country/ place is not on the list ;) - }; - - /** Name of the antlib resource inside JUnit4 JAR. */ - public static final String ANTLIB_RESOURCE_NAME = "com/carrotsearch/junit4/antlib.xml"; - - /** @see #setParallelism(String) */ - public static final Object PARALLELISM_AUTO = "auto"; - - /** @see #setParallelism(String) */ - public static final String PARALLELISM_MAX = "max"; - - /** Default value of {@link #setShuffleOnSlave}. */ - public static final boolean DEFAULT_SHUFFLE_ON_SLAVE = true; - - /** Default value of {@link #setParallelism}. */ - public static final String DEFAULT_PARALLELISM = "1"; - - /** Default value of {@link #setPrintSummary}. */ - public static final boolean DEFAULT_PRINT_SUMMARY = true; - - /** Default value of {@link #setHaltOnFailure}. */ - public static final boolean DEFAULT_HALT_ON_FAILURE = true; - - /** Default value of {@link #setIsolateWorkingDirectories(boolean)}. */ - public static final boolean DEFAULT_ISOLATE_WORKING_DIRECTORIES = true; - - /** Default valkue of {@link #setOnNonEmptyWorkDirectory}. */ - public static final NonEmptyWorkDirectoryAction DEFAULT_NON_EMPTY_WORKDIR_ACTION = NonEmptyWorkDirectoryAction.FAIL; - - /** Default value of {@link #setDynamicAssignmentRatio(float)} */ - public static final float DEFAULT_DYNAMIC_ASSIGNMENT_RATIO = .25f; - - /** Default value of {@link #setSysouts}. */ - public static final boolean DEFAULT_SYSOUTS = false; - - /** Default value of {@link #setDebugStream}. */ - public static final boolean DEFAULT_DEBUGSTREAM = false; - - /** Default value of {@link #setUniqueSuiteNames(boolean)} */ - public static final boolean DEFAULT_UNIQUE_SUITE_NAME = true; - - /** System property passed to forked VMs: current working directory (absolute). */ - private static final String CHILDVM_SYSPROP_CWD = "junit4.childvm.cwd"; - - /** - * System property passed to forked VMs: junit4's temporary folder location - * (must have read/write access if security manager is used). - */ - private static final String SYSPROP_TEMPDIR = "junit4.tempDir"; - - /** What to do on JVM output? */ - public static enum JvmOutputAction { - PIPE, - IGNORE, - FAIL, - WARN, - LISTENERS - } - - /** What to do when there were no executed tests (all ignored or none at all?). */ - public static enum NoTestsAction { - IGNORE, - FAIL, - WARN - } - - /** - * @see #setJvmOutputAction(String) - */ - public EnumSet jvmOutputAction = EnumSet.of( - JvmOutputAction.LISTENERS, - JvmOutputAction.WARN); - - /** - * @see #setSysouts - */ - private boolean sysouts = DEFAULT_SYSOUTS; - - /** - * @see #setDebugStream - */ - private boolean debugStream = DEFAULT_DEBUGSTREAM; - - /** - * Slave VM command line. - */ - private CommandlineJava slaveCommand = new CommandlineJava(); - - /** - * Set new environment for the forked process? - */ - private boolean newEnvironment; - - /** - * @see #setUniqueSuiteNames - */ - private boolean uniqueSuiteNames = DEFAULT_UNIQUE_SUITE_NAME; - - /** - * Environment variables to use in the forked JVM. - */ - private Environment env = new Environment(); - - /** - * Directory to invoke forked VMs in. - */ - private Path dir; - - /** - * Test names. - */ - private final Resources resources; - - /** - * Stop the build process if there were errors? - */ - private boolean haltOnFailure = DEFAULT_HALT_ON_FAILURE; - - /** - * Print summary of all tests at the end. - */ - private boolean printSummary = DEFAULT_PRINT_SUMMARY; - - /** - * Property to set if there were test failures or errors. - */ - private String failureProperty; - - /** - * A folder to store temporary files in. Defaults to {@link #dir} or - * the project's basedir. - */ - private Path tempDir; - - /** - * Listeners listening on the event bus. - */ - private List listeners = new ArrayList<>(); - - /** - * User-defined {@link org.junit.runner.notification.RunListener}s. - */ - private List runListeners = new ArrayList<>(); - - /** - * Balancers scheduling tests for individual JVMs in parallel mode. - */ - private List balancers = new ArrayList<>(); - - /** - * Class loader used to resolve annotations and classes referenced from annotations - * when {@link Description}s containing them are passed from slaves. - */ - private AntClassLoader testsClassLoader; - - /** - * @see #setParallelism(String) - */ - private String parallelism = DEFAULT_PARALLELISM; - - /** - * Set to true to leave temporary files (for diagnostics). - */ - private boolean leaveTemporary; - - /** - * A list of temporary files to leave or remove if build passes. - */ - private List temporaryFiles = Collections.synchronizedList(new ArrayList()); - - /** - * @see #setSeed(String) - */ - private String random; - - /** - * @see #setIsolateWorkingDirectories(boolean) - */ - private boolean isolateWorkingDirectories = DEFAULT_ISOLATE_WORKING_DIRECTORIES; - - /** - * @see #setIsolateWorkingDirectories(boolean) - */ - private NonEmptyWorkDirectoryAction nonEmptyWorkDirAction = DEFAULT_NON_EMPTY_WORKDIR_ACTION; - - /** - * Multiple path resolution in {@link CommandlineJava#getCommandline()} is very slow - * so we construct and canonicalize paths. - */ - private org.apache.tools.ant.types.Path classpath; - private org.apache.tools.ant.types.Path bootclasspath; - - /** - * @see #setDynamicAssignmentRatio(float) - */ - private float dynamicAssignmentRatio = DEFAULT_DYNAMIC_ASSIGNMENT_RATIO; - - /** - * @see #setShuffleOnSlave(boolean) - */ - private boolean shuffleOnSlave = DEFAULT_SHUFFLE_ON_SLAVE; - - /** - * @see #setHeartbeat - */ - private long heartbeat; - - /** - * @see #setIfNoTests - */ - private NoTestsAction ifNoTests = NoTestsAction.IGNORE; - - /** - * @see #setStatsPropertyPrefix - */ - private String statsPropertyPrefix; - - /** - * - */ - public JUnit4() { - resources = new Resources(); - } - - /** - * What should be done on unexpected JVM output? JVM may write directly to the - * original descriptors, bypassing redirections of System.out and System.err. Typically, - * these messages will be important and should fail the build (permgen space exceeded, - * compiler errors, crash dumps). However, certain legitimate logs (gc activity, class loading - * logs) are also printed to these streams so sometimes the output can be ignored. - * - *

Allowed values (any comma-delimited combination of): {@link JvmOutputAction} - * constants. - */ - public void setJvmOutputAction(String jvmOutputActions) { - EnumSet actions = EnumSet.noneOf(JvmOutputAction.class); - for (String s : jvmOutputActions.split("[\\,\\ ]+")) { - s = s.trim().toUpperCase(Locale.ROOT); - actions.add(JvmOutputAction.valueOf(s)); - } - this.jvmOutputAction = actions; - } - - /** - * If set to true, any sysout and syserr calls will be written to original - * output and error streams (and in effect will appear as "jvm output". By default - * sysout and syserrs are captured and proxied to the event stream to be synchronized - * with other test events but occasionally one may want to synchronize them with direct - * JVM output (to synchronize with compiler output or GC output for example). - */ - public void setSysouts(boolean sysouts) { - this.sysouts = sysouts; - } - - /** - * Enables a debug stream from each forked JVM. This will create an additional file - * next to each events file. For debugging the framework only, not a general-purpose setting. - */ - public void setDebugStream(boolean debugStream) { - this.debugStream = debugStream; - } - - /** - * Allow or disallow duplicate suite names in resource collections. By default this option - * is true because certain ANT-compatible report types (like XML reports) - * will have a problem with duplicate suite names (will overwrite files). - */ - public void setUniqueSuiteNames(boolean uniqueSuiteNames) { - this.uniqueSuiteNames = uniqueSuiteNames; - } - - /** - * @see #setUniqueSuiteNames(boolean) - */ - public boolean isUniqueSuiteNames() { - return uniqueSuiteNames; - } - - /** - * Specifies the ratio of suites moved to dynamic assignment list. A dynamic - * assignment list dispatches suites to the first idle slave JVM. Theoretically - * this is an optimal strategy, but it is usually better to have some static assignments - * to avoid communication costs. - * - *

A ratio of 0 means only static assignments are used. A ratio of 1 means - * only dynamic assignments are used. - * - *

The list of dynamic assignments is sorted by decreasing cost (always) and - * is inherently prone to race conditions in distributing suites. Should there - * be an error based on suite-dependency it will not be directly repeatable. In such - * case use the per-slave-jvm list of suites file dumped to disk for each slave JVM. - * (see {@link #setLeaveTemporary(boolean)}). - */ - public void setDynamicAssignmentRatio(float ratio) { - if (ratio < 0 || ratio > 1) { - throw new IllegalArgumentException("Dynamic assignment ratio must be " + - "between 0 (only static assignments) to 1 (fully dynamic assignments)."); - } - this.dynamicAssignmentRatio = ratio; - } - - /** - * The number of parallel slaves. Can be set to a constant "max" for the - * number of cores returned from {@link Runtime#availableProcessors()} or - * "auto" for sensible defaults depending on the number of cores. - * The default is a single subprocess. - * - *

Note that this setting forks physical JVM processes so it multiplies the - * requirements for heap memory, IO, etc. - */ - public void setParallelism(String parallelism) { - this.parallelism = parallelism; - } - - /** - * Property to set to "true" if there is a failure in a test. - */ - public void setFailureProperty(String failureProperty) { - this.failureProperty = failureProperty; - } - - /** - * Do not propagate the old environment when new environment variables are specified. - */ - public void setNewEnvironment(boolean v) { - this.newEnvironment = v; - } - - /** - * Initial random seed used for shuffling test suites and other sources - * of pseudo-randomness. If not set, any random value is set. - * - *

The seed's format is compatible with {@link RandomizedRunner} so that - * seed can be fixed for suites and methods alike. - */ - public void setSeed(String randomSeed) { - if (!Strings.isNullOrEmpty(getProject().getUserProperty(SYSPROP_RANDOM_SEED()))) { - String userProperty = getProject().getUserProperty(SYSPROP_RANDOM_SEED()); - if (!userProperty.equals(randomSeed)) { - log("Ignoring seed attribute because it is overridden by user properties.", Project.MSG_WARN); - } - } else if (!Strings.isNullOrEmpty(randomSeed)) { - this.random = randomSeed; - } - } - - /** - * Initializes custom prefix for all junit4 properties. This must be consistent - * across all junit4 invocations if done from the same classpath. Use only when REALLY needed. - */ - public void setPrefix(String prefix) { - if (!Strings.isNullOrEmpty(getProject().getUserProperty(SYSPROP_PREFIX()))) { - log("Ignoring prefix attribute because it is overridden by user properties.", Project.MSG_WARN); - } else { - SysGlobals.initializeWith(prefix); - } - } - - /** - * @see #setSeed(String) - */ - public String getSeed() { - return random; - } - - /** - * Predictably shuffle tests order after balancing. This will help in spreading - * lighter and heavier tests over a single slave's execution timeline while - * still keeping the same tests order depending on the seed. - */ - public void setShuffleOnSlave(boolean shuffle) { - this.shuffleOnSlave = shuffle; - } - - /* - * - */ - @Override - public void setProject(Project project) { - super.setProject(project); - - this.resources.setProject(project); - this.classpath = new org.apache.tools.ant.types.Path(getProject()); - this.bootclasspath = new org.apache.tools.ant.types.Path(getProject()); - } - - /** - * Prints the summary of all executed, ignored etc. tests at the end. - */ - public void setPrintSummary(boolean printSummary) { - this.printSummary = printSummary; - } - - /** - * Stop the build process if there were failures or errors during test execution. - */ - public void setHaltOnFailure(boolean haltOnFailure) { - this.haltOnFailure = haltOnFailure; - } - - /** - * Set the maximum memory to be used by all forked JVMs. - * - * @param max - * the value as defined by -mx or -Xmx in the java - * command line options. - */ - public void setMaxmemory(String max) { - if (!Strings.isNullOrEmpty(max)) { - getCommandline().setMaxmemory(max); - } - } - - /** - * Set to true to leave temporary files for diagnostics. - */ - public void setLeaveTemporary(boolean leaveTemporary) { - this.leaveTemporary = leaveTemporary; - } - - /** - * Add an additional argument to any forked JVM. - */ - public Commandline.Argument createJvmarg() { - return getCommandline().createVmArgument(); - } - - /** - * The directory to invoke forked VMs in. - */ - public void setDir(File dir) { - this.dir = dir.toPath(); - } - - /** - * The directory to store temporary files in. - */ - public void setTempDir(File tempDir) { - this.tempDir = tempDir.toPath(); - } - - /** - * What to do when no tests were executed (all tests were ignored)? - * @see NoTestsAction - */ - public void setIfNoTests(String value) { - try { - ifNoTests = NoTestsAction.valueOf(value.toUpperCase(Locale.ROOT)); - } catch (IllegalArgumentException e) { - throw new BuildException("Invalid value (one of " - + Arrays.toString(NoTestsAction.values()) + " accepted): " + value); - } - } - - /** - * A {@link org.apache.tools.ant.types.Environment.Variable} with an additional - * attribute specifying whether or not empty values should be propagated or ignored. - */ - public static class ExtendedVariable extends Environment.Variable { - private boolean ignoreEmptyValue = false; - - public void setIgnoreEmpty(boolean ignoreEmptyValue) { - this.ignoreEmptyValue = ignoreEmptyValue; - } - - public boolean shouldIgnore() { - return ignoreEmptyValue && Strings.isNullOrEmpty(getValue()); - } - - @Override - public String toString() { - return getContent() + " (ignoreEmpty=" + ignoreEmptyValue + ")"; - } - } - - /** - * Adds a system property to any forked JVM. - */ - public void addConfiguredSysproperty(ExtendedVariable sysp) { - if (!sysp.shouldIgnore()) { - getCommandline().addSysproperty(sysp); - } - } - - /** - * A {@link PropertySet} with an additional - * attribute specifying whether or not empty values should be propagated or ignored. - */ - public static class ExtendedPropertySet extends PropertySet { - private boolean ignoreEmptyValue = false; - - public void setIgnoreEmpty(boolean ignoreEmptyValue) { - this.ignoreEmptyValue = ignoreEmptyValue; - } - - @Override - public Properties getProperties() { - Properties properties = super.getProperties(); - Properties clone = new Properties(); - for (String s : properties.stringPropertyNames()) { - String value = (String) properties.get(s); - if (ignoreEmptyValue && Strings.isNullOrEmpty(value)) { - continue; - } else { - clone.setProperty(s, value); - } - } - return clone; - } - } - - /** - * Adds a set of properties that will be used as system properties that tests - * can access. - * - * This might be useful to transfer Ant properties to the testcases. - */ - public void addConfiguredSyspropertyset(ExtendedPropertySet sysp) { - getCommandline().addSyspropertyset(sysp); - } - - /** - * The command used to invoke the Java Virtual Machine, default is 'java'. The - * command is resolved by java.lang.Runtime.exec(). - */ - public void setJvm(String jvm) { - if (!Strings.isNullOrEmpty(jvm)) { - getCommandline().setVm(jvm); - } - } - - /** - * If set to true each slave JVM gets a separate working directory - * under whatever is set in {@link #setDir(File)}. The directory naming for each slave - * follows: "Snum", where num is slave's number. Directories are created - * automatically and removed unless {@link #setLeaveTemporary(boolean)} is set to - * true. - */ - public void setIsolateWorkingDirectories(boolean isolateWorkingDirectories) { - this.isolateWorkingDirectories = isolateWorkingDirectories; - } - - /** - * Determines the behavior on detecting non-empty existing current working - * directory for a forked JVM, before the tests commence. This action is performed - * only if work directory isolation is set to true (see {@link #setIsolateWorkingDirectories(boolean)}). - */ - public void setOnNonEmptyWorkDirectory(String value) { - try { - this.nonEmptyWorkDirAction = NonEmptyWorkDirectoryAction.valueOf(value.toUpperCase(Locale.ROOT)); - } catch (IllegalArgumentException e) { - throw new IllegalArgumentException("OnNonEmptyWorkDirectory accepts any of: " - + Arrays.toString(NonEmptyWorkDirectoryAction.values()) + ", value is not valid: " + value); - } - } - - /** - * Adds an environment variable; used when forking. - */ - public void addEnv(ExtendedVariable var) { - env.addVariable(var); - } - - /** - * Adds a set of tests based on pattern matching. - */ - public void addFileSet(FileSet fs) { - add(fs); - if (fs.getProject() == null) { - fs.setProject(getProject()); - } - } - - /** - * Adds a set of tests based on pattern matching. - */ - public void add(ResourceCollection rc) { - resources.add(rc); - } - - /** - * Creates a new list of listeners. - */ - public ListenersList createListeners() { - return new ListenersList(listeners); - } - - /** - * Creates a new list of user-defined run listeners. - */ - public RunListenerList createRunListeners() { - return new RunListenerList(runListeners); - } - - /** - * Add assertions to tests execution. - */ - public void addAssertions(Assertions asserts) { - if (getCommandline().getAssertions() != null) { - throw new BuildException("Only one assertion declaration is allowed"); - } - getCommandline().setAssertions(asserts); - } - - /** - * Creates a new list of balancers. - */ - public BalancersList createBalancers() { - return new BalancersList(balancers); - } - - /** - * Adds path to classpath used for tests. - * - * @return reference to the classpath in the embedded java command line - */ - public org.apache.tools.ant.types.Path createClasspath() { - return classpath.createPath(); - } - - /** - * Adds a path to the bootclasspath. - * - * @return reference to the bootclasspath in the embedded java command line - */ - public org.apache.tools.ant.types.Path createBootclasspath() { - return bootclasspath.createPath(); - } - - /* ANT-junit compat only. */ - public void setFork(boolean fork) { - warnUnsupported("fork"); - } - - public void setForkmode(String forkMode) { - warnUnsupported("forkmode"); - } - - public void setHaltOnError(boolean haltOnError) { - warnUnsupported("haltonerror"); - } - - public void setFiltertrace(boolean filterTrace) { - warnUnsupported("filtertrace"); - log("Hint: report listeners have stack filtering options.", Project.MSG_WARN); - } - - public void setTimeout(String v) { - warnUnsupported("timeout"); - } - - public void setIncludeantruntime(String v) { - warnUnsupported("includeantruntime"); - } - - public void setShowoutput(String v) { - warnUnsupported("showoutput"); - } - - public void setOutputtoformatters(String v) { - warnUnsupported("outputtoformatters"); - } - - public void setReloading(String v) { - warnUnsupported("reloading"); - } - - public void setClonevm(String v) { - warnUnsupported("clonevm"); - } - - public void setErrorproperty(String v) { - warnUnsupported("errorproperty"); - } - - public void setLogfailedtests(String v) { - warnUnsupported("logfailedtests"); - } - - public void setEnableTestListenerEvents(String v) { - warnUnsupported("enableTestListenerEvents"); - } - - public Object createFormatter() { - throw new BuildException(" elements are not supported by . " + - "Refer to the documentation about listeners and reports."); - } - - public Object createTest() { - throw new BuildException(" elements are not supported by . " + - "Use regular ANT resource collections to point at individual tests or their groups."); - } - - public Object createBatchtest() { - throw new BuildException(" elements are not supported by . " + - "Use regular ANT resource collections to point at individual tests or their groups."); - } - - private void warnUnsupported(String attName) { - log("The '" + attName + "' attribute is not supported by .", Project.MSG_WARN); - } - - /** - * Sets the heartbeat used to detect inactive/ hung forked tests (JVMs) to the given - * number of seconds. The heartbeat detects - * no-event intervals and will report them to listeners. Notably, text report report will - * emit heartbeat information (to a file or console). - * - *

Setting the heartbeat to zero means no detection. - */ - public void setHeartbeat(long heartbeat) { - this.heartbeat = heartbeat; - } - - /** - * Sets the property prefix to which test statistics are saved. - */ - public void setStatsPropertyPrefix(String statsPropertyPrefix) { - this.statsPropertyPrefix = statsPropertyPrefix; - } - - @Override - public void execute() throws BuildException { - validateJUnit4(); - validateArguments(); - - // Initialize random if not already provided. - if (random == null) { - this.random = MoreObjects.firstNonNull( - Strings.emptyToNull(getProject().getProperty(SYSPROP_RANDOM_SEED())), - SeedUtils.formatSeed(new Random().nextLong())); - } - masterSeed(); - - // Say hello and continue. - log(" says " + - RandomPicks.randomFrom(new Random(masterSeed()), WELCOME_MESSAGES) + - " Master seed: " + getSeed(), Project.MSG_INFO); - - // Pass the random seed property. - createJvmarg().setValue("-D" + SYSPROP_PREFIX() + "=" + CURRENT_PREFIX()); - createJvmarg().setValue("-D" + SYSPROP_RANDOM_SEED() + "=" + random); - - // Resolve paths first. - this.classpath = resolveFiles(classpath); - this.bootclasspath = resolveFiles(bootclasspath); - getCommandline().createClasspath(getProject()).add(classpath); - getCommandline().createBootclasspath(getProject()).add(bootclasspath); - - // Setup a class loader over test classes. This will be used for loading annotations - // and referenced classes. This is kind of ugly, but mirroring annotation content will - // be even worse and Description carries these. - - // TODO: [GH-211] we should NOT be using any actual classes, annotations, etc. - // from client code. Everything should be a mirror. - testsClassLoader = new AntClassLoader( - this.getClass().getClassLoader(), - getProject(), - getCommandline().getClasspath(), - true); - - // Pass method filter if any. - String testMethodFilter = Strings.emptyToNull(getProject().getProperty(SYSPROP_TESTMETHOD())); - if (testMethodFilter != null) { - Environment.Variable v = new Environment.Variable(); - v.setKey(SYSPROP_TESTMETHOD()); - v.setValue(testMethodFilter); - getCommandline().addSysproperty(v); - } - - // Process test classes and resources. - long start = System.currentTimeMillis(); - final TestsCollection testCollection = processTestResources(); - - final EventBus aggregatedBus = new EventBus("aggregated"); - final TestsSummaryEventListener summaryListener = new TestsSummaryEventListener(); - aggregatedBus.register(summaryListener); - - for (Object o : listeners) { - if (o instanceof ProjectComponent) { - ((ProjectComponent) o).setProject(getProject()); - } - if (o instanceof AggregatedEventListener) { - ((AggregatedEventListener) o).setOuter(this); - } - aggregatedBus.register(o); - } - - if (testCollection.testClasses.isEmpty()) { - aggregatedBus.post(new AggregatedQuitEvent()); - } else { - start = System.currentTimeMillis(); - - // Check if we allow duplicate suite names. Some reports (ANT compatible XML - // reports) will have a problem with duplicate suite names, for example. - if (uniqueSuiteNames) { - testCollection.onlyUniqueSuiteNames(); - } - - final int jvmCount = determineForkedJvmCount(testCollection); - final List slaveInfos = new ArrayList<>(); - for (int jvmid = 0; jvmid < jvmCount; jvmid++) { - final ForkedJvmInfo slaveInfo = new ForkedJvmInfo(jvmid, jvmCount); - slaveInfos.add(slaveInfo); - } - - - if (jvmCount > 1 && uniqueSuiteNames && testCollection.hasReplicatedSuites()) { - throw new BuildException(String.format(Locale.ROOT, - "There are test suites that request JVM replication and the number of forked JVMs %d is larger than 1. Run on a single JVM.", - jvmCount)); - } - - // Prepare a pool of suites dynamically dispatched to slaves as they become idle. - final Deque stealingQueue = - new ArrayDeque(loadBalanceSuites(slaveInfos, testCollection, balancers)); - aggregatedBus.register(new Object() { - @Subscribe - public void onSlaveIdle(SlaveIdle slave) { - if (stealingQueue.isEmpty()) { - slave.finished(); - } else { - String suiteName = stealingQueue.pop(); - slave.newSuite(suiteName); - } - } - }); - - // Check for filtering expressions. - Vector vv = getCommandline().getSystemProperties().getVariablesVector(); - for (Variable v : vv) { - if (SysGlobals.SYSPROP_TESTFILTER().equals(v.getKey())) { - try { - Node root = new FilterExpressionParser().parse(v.getValue()); - log("Parsed test filtering expression: " + root.toExpression(), Project.MSG_INFO); - } catch (Exception e) { - log("Could not parse filtering expression: " + v.getValue(), e, Project.MSG_WARN); - } - } - } - - // Create callables for the executor. - final List> slaves = new ArrayList<>(); - for (int slave = 0; slave < jvmCount; slave++) { - final ForkedJvmInfo slaveInfo = slaveInfos.get(slave); - slaves.add(new Callable() { - @Override - public Void call() throws Exception { - executeSlave(slaveInfo, aggregatedBus); - return null; - } - }); - } - - ExecutorService executor = Executors.newCachedThreadPool(); - aggregatedBus.post(new AggregatedStartEvent(slaves.size(), - // TODO: this doesn't account for replicated suites. - testCollection.testClasses.size())); - - try { - List> all = executor.invokeAll(slaves); - executor.shutdown(); - - for (int i = 0; i < slaves.size(); i++) { - Future f = all.get(i); - try { - f.get(); - } catch (ExecutionException e) { - slaveInfos.get(i).executionError = e.getCause(); - } - } - } catch (InterruptedException e) { - log("Master interrupted? Weird.", Project.MSG_ERR); - } - aggregatedBus.post(new AggregatedQuitEvent()); - - for (ForkedJvmInfo si : slaveInfos) { - if (si.start > 0 && si.end > 0) { - log(String.format(Locale.ROOT, "JVM J%d: %8.2f .. %8.2f = %8.2fs", - si.id, - (si.start - start) / 1000.0f, - (si.end - start) / 1000.0f, - (si.getExecutionTime() / 1000.0f)), - Project.MSG_INFO); - } - } - log("Execution time total: " + Duration.toHumanDuration( - (System.currentTimeMillis() - start))); - - ForkedJvmInfo slaveInError = null; - for (ForkedJvmInfo i : slaveInfos) { - if (i.executionError != null) { - log("ERROR: JVM J" + i.id + " ended with an exception, command line: " + i.getCommandLine()); - log("ERROR: JVM J" + i.id + " ended with an exception: " + - Throwables.getStackTraceAsString(i.executionError), Project.MSG_ERR); - if (slaveInError == null) { - slaveInError = i; - } - } - } - - if (slaveInError != null) { - throw new BuildException("At least one slave process threw an exception, first: " - + slaveInError.executionError.getMessage(), slaveInError.executionError); - } - } - - final TestsSummary testsSummary = summaryListener.getResult(); - if (printSummary) { - log("Tests summary: " + testsSummary, Project.MSG_INFO); - } - - if (!testsSummary.isSuccessful()) { - if (!Strings.isNullOrEmpty(failureProperty)) { - getProject().setNewProperty(failureProperty, "true"); - } - if (haltOnFailure) { - throw new BuildException(String.format(Locale.ROOT, - "There were test failures: %s [seed: %s]", - testsSummary, - getSeed())); - } - } - - if (!leaveTemporary) { - for (Path f : temporaryFiles) { - try { - if (f != null) { - try { - Files.delete(f); - } catch (DirectoryNotEmptyException e) { - throw new DirectoryNotEmptyException("Remaining files: " + listFiles(f)); - } - } - } catch (IOException e) { - log("Could not remove temporary path: " + f.toAbsolutePath() + " (" + e + ")", e, Project.MSG_WARN); - } - } - } - - if (statsPropertyPrefix != null) { - Project p = getProject(); - p.setNewProperty(statsPropertyPrefix + ".tests", Integer.toString(testsSummary.tests)); - p.setNewProperty(statsPropertyPrefix + ".errors", Integer.toString(testsSummary.errors)); - p.setNewProperty(statsPropertyPrefix + ".failures", Integer.toString(testsSummary.failures)); - p.setNewProperty(statsPropertyPrefix + ".ignores", Integer.toString(testsSummary.ignores)); - p.setNewProperty(statsPropertyPrefix + ".suites", Integer.toString(testsSummary.suites)); - p.setNewProperty(statsPropertyPrefix + ".assumptions", Integer.toString(testsSummary.assumptions)); - p.setNewProperty(statsPropertyPrefix + ".suiteErrors", Integer.toString(testsSummary.suiteErrors)); - - p.setNewProperty(statsPropertyPrefix + ".nonIgnored", Integer.toString(testsSummary.getNonIgnoredTestsCount())); - p.setNewProperty(statsPropertyPrefix + ".successful", Boolean.toString(testsSummary.isSuccessful())); - } - - int executedTests = testsSummary.getNonIgnoredTestsCount(); - if (executedTests == 0) { - String message = "There were no executed tests: " + testsSummary; - switch (ifNoTests) { - case FAIL: - throw new BuildException(message); - case WARN: - log(message, Project.MSG_WARN); - break; - case IGNORE: - break; - default: - throw new RuntimeException("Unreachable case clause: " + ifNoTests); - } - } - } - - private static List listFiles(Path f) throws IOException { - List remainingFiles = new ArrayList(); - try (DirectoryStream s = Files.newDirectoryStream(f)) { - for (Path p : s) { - remainingFiles.add(p.toString()); - } - Collections.sort(remainingFiles); - } - return remainingFiles; - } - - /** - * Validate arguments. - */ - private void validateArguments() throws BuildException { - Path tempDir = getTempDir(); - - if (tempDir == null) { - throw new BuildException("Temporary directory cannot be null."); - } - - if (Files.exists(tempDir)) { - if (!Files.isDirectory(tempDir)) { - throw new BuildException("Temporary directory is not a folder: " + tempDir.toAbsolutePath()); - } - } else { - try { - Files.createDirectories(tempDir); - } catch (IOException e) { - throw new BuildException("Failed to create temporary folder: " + tempDir, e); - } - } - } - - /** - * Validate JUnit4 presence in a concrete version. - */ - private void validateJUnit4() throws BuildException { - try { - Class clazz = Class.forName("org.junit.runner.Description"); - if (!Serializable.class.isAssignableFrom(clazz)) { - throw new BuildException("At least JUnit version 4.10 is required on junit4's taskdef classpath."); - } - } catch (ClassNotFoundException e) { - throw new BuildException("JUnit JAR must be added to junit4 taskdef's classpath."); - } - } - - /** - * Perform load balancing of the set of suites. Sets {@link ForkedJvmInfo#testSuites} - * to suites preassigned to a given slave and returns a pool of suites - * that should be load-balanced dynamically based on job stealing. - */ - private List loadBalanceSuites(List jvmInfo, - TestsCollection testsCollection, List balancers) { - - // Order test suites identically for balancers. - // and split into replicated and non-replicated suites. - Map> partitioned = sortAndSplitReplicated(testsCollection.testClasses); - - Collection replicated = partitioned.get(true); - Collection suites = partitioned.get(false); - - final List balancersWithFallback = new ArrayList<>(balancers); - balancersWithFallback.add(new RoundRobinBalancer()); - - // Go through all the balancers, the first one to assign a suite wins. - final List remaining = new ArrayList<>(suites); - Collections.sort(remaining); - - final Map> perJvmAssignments = new HashMap<>(); - for (ForkedJvmInfo si : jvmInfo) { - perJvmAssignments.put(si.id, new ArrayList()); - } - final int jvmCount = jvmInfo.size(); - for (SuiteBalancer balancer : balancersWithFallback) { - balancer.setOwner(this); - final List assignments = - balancer.assign( - Collections.unmodifiableCollection(remaining), jvmCount, masterSeed()); - - for (Assignment e : assignments) { - if (e == null) { - throw new RuntimeException("Balancer must return non-null assignments."); - } - if (!remaining.remove(e.suiteName)) { - throw new RuntimeException("Balancer must return suite name as a key: " + e.suiteName); - } - - log(String.format(Locale.ROOT, - "Assignment hint: J%-2d (cost %5d) %s (by %s)", - e.slaveId, - e.estimatedCost, - e.suiteName, - balancer.getClass().getSimpleName()), Project.MSG_VERBOSE); - - perJvmAssignments.get(e.slaveId).add(e); - } - } - - if (remaining.size() != 0) { - throw new RuntimeException("Not all suites assigned?: " + remaining); - } - - if (shuffleOnSlave) { - // Shuffle suites on slaves so that the result is always the same wrt master seed - // (sort first, then shuffle with a constant seed). - for (List assignments : perJvmAssignments.values()) { - Collections.sort(assignments); - Collections.shuffle(assignments, new Random(this.masterSeed())); - } - } - - // Take a fraction of suites scheduled as last on each slave and move them to a common - // job-stealing queue. - List stealingQueueWithHints = new ArrayList<>(); - for (ForkedJvmInfo si : jvmInfo) { - final List assignments = perJvmAssignments.get(si.id); - int moveToCommon = (int) (assignments.size() * dynamicAssignmentRatio); - - if (moveToCommon > 0) { - final List movedToCommon = - assignments.subList(assignments.size() - moveToCommon, assignments.size()); - for (Assignment a : movedToCommon) { - stealingQueueWithHints.add(new SuiteHint(a.suiteName, a.estimatedCost)); - } - movedToCommon.clear(); - } - - final ArrayList slaveSuites = (si.testSuites = new ArrayList<>()); - for (Assignment a : assignments) { - slaveSuites.add(a.suiteName); - } - } - - // Sort stealing queue according to descending cost. - Collections.sort(stealingQueueWithHints, SuiteHint.DESCENDING_BY_WEIGHT); - - // Append all replicated suites to each forked JVM, AFTER we process the stealing queue - // to enforce all replicated suites run on each bound JVM. - if (!replicated.isEmpty()) { - for (ForkedJvmInfo si : jvmInfo) { - for (String suite : replicated) { - si.testSuites.add(suite); - } - if (shuffleOnSlave) { - // Shuffle suites on slaves so that the result is always the same wrt master seed - // (sort first, then shuffle with a constant seed). - Collections.shuffle(si.testSuites, new Random(this.masterSeed())); - } - } - } - - // Dump scheduling information. - for (ForkedJvmInfo si : jvmInfo) { - log("Forked JVM J" + si.id + " assignments (after shuffle):", Project.MSG_VERBOSE); - for (String suiteName : si.testSuites) { - log(" " + suiteName, Project.MSG_VERBOSE); - } - } - - log("Stealing queue:", Project.MSG_VERBOSE); - for (SuiteHint suiteHint : stealingQueueWithHints) { - log(" " + suiteHint.suiteName + " " + suiteHint.cost, Project.MSG_VERBOSE); - } - - List stealingQueue = new ArrayList<>(stealingQueueWithHints.size()); - for (SuiteHint suiteHint : stealingQueueWithHints) { - stealingQueue.add(suiteHint.suiteName); - } - return stealingQueue; - } - - private Map> sortAndSplitReplicated(List testClasses) { - ArrayList sorted = new ArrayList<>(testClasses); - Collections.sort(sorted, new Comparator() { - @Override - public int compare(TestClass t1, TestClass t2) { - String s1 = t1.className + ";" + t1.replicate; - String s2 = t2.className + ";" + t2.replicate; - return s1.compareTo(s2); - } - }); - - List replicated = new ArrayList<>(); - List nonreplicated = new ArrayList<>(); - for (TestClass tc : sorted) { - if (tc.replicate) { - replicated.add(tc.className); - } else { - nonreplicated.add(tc.className); - } - } - - Map> result = new HashMap<>(); - result.put(Boolean.TRUE, replicated); - result.put(Boolean.FALSE, nonreplicated); - return result; - } - - /** - * Return the master seed of {@link #getSeed()}. - */ - private long masterSeed() { - long[] seeds = SeedUtils.parseSeedChain(getSeed()); - if (seeds.length < 1) { - throw new BuildException("Random seed is required."); - } - return seeds[0]; - } - - /** - * Resolve all files from a given path and simplify its definition. - */ - private org.apache.tools.ant.types.Path resolveFiles(org.apache.tools.ant.types.Path path) { - org.apache.tools.ant.types.Path cloned = new org.apache.tools.ant.types.Path(getProject()); - for (String location : path.list()) { - cloned.createPathElement().setLocation(new File(location)); - } - return cloned; - } - - /** - * Determine how many forked JVMs to use. - */ - private int determineForkedJvmCount(TestsCollection testCollection) { - int cores = Runtime.getRuntime().availableProcessors(); - int jvmCount; - if (this.parallelism.equals(PARALLELISM_AUTO)) { - if (cores >= 8) { - // Maximum parallel jvms is 4, conserve some memory and memory bandwidth. - jvmCount = 4; - } else if (cores >= 4) { - // Make some space for the aggregator. - jvmCount = 3; - } else if (cores == 3) { - // Yes, three-core chips are a thing. - jvmCount = 2; - } else { - // even for dual cores it usually makes no sense to fork more than one - // JVM. - jvmCount = 1; - } - } else if (this.parallelism.equals(PARALLELISM_MAX)) { - jvmCount = Runtime.getRuntime().availableProcessors(); - } else { - try { - jvmCount = Math.max(1, Integer.parseInt(parallelism)); - } catch (NumberFormatException e) { - throw new BuildException("parallelism must be 'auto', 'max' or a valid integer: " - + parallelism); - } - } - - if (!testCollection.hasReplicatedSuites()) { - jvmCount = Math.min(testCollection.testClasses.size(), jvmCount); - } - return jvmCount; - } - - /** - * Attach listeners and execute a slave process. - */ - private void executeSlave(final ForkedJvmInfo slave, final EventBus aggregatedBus) - throws Exception - { - final String uniqueSeed = new SimpleDateFormat("yyyyMMdd_HHmmss_SSS", Locale.ROOT).format(new Date()); - - final Path classNamesFile = tempFile(uniqueSeed, "junit4-J" + slave.id, ".suites", getTempDir()); - temporaryFiles.add(classNamesFile); - - final Path classNamesDynamic = tempFile(uniqueSeed, "junit4-J" + slave.id, ".dynamic-suites", getTempDir()); - final Path streamsBufferFile = tempFile(uniqueSeed, "junit4-J" + slave.id, ".spill", getTempDir()); - - // Dump all test class names to a temporary file. - String testClassPerLine = Joiner.on("\n").join(slave.testSuites); - log("Test class names:\n" + testClassPerLine, Project.MSG_VERBOSE); - Files.write(classNamesFile, testClassPerLine.getBytes(StandardCharsets.UTF_8)); - - // Prepare command line for java execution. - CommandlineJava commandline; - commandline = (CommandlineJava) getCommandline().clone(); - commandline.createClasspath(getProject()).add(addSlaveClasspath()); - commandline.setClassname(SlaveMainSafe.class.getName()); - if (slave.slaves == 1) { - commandline.createArgument().setValue(SlaveMain.OPTION_FREQUENT_FLUSH); - } - - // Set up full output files. - Path sysoutFile = tempFile(uniqueSeed, - "junit4-J" + slave.id, ".sysout", getTempDir()); - Path syserrFile = tempFile(uniqueSeed, - "junit4-J" + slave.id, ".syserr", getTempDir()); - - // Set up communication channel. - Path eventFile = tempFile(uniqueSeed, "junit4-J" + slave.id, ".events", getTempDir()); - temporaryFiles.add(eventFile); - commandline.createArgument().setValue(SlaveMain.OPTION_EVENTSFILE); - commandline.createArgument().setFile(eventFile.toFile()); - - if (sysouts) { - commandline.createArgument().setValue(SlaveMain.OPTION_SYSOUTS); - } - - if (debugStream) { - commandline.createArgument().setValue(SlaveMain.OPTION_DEBUGSTREAM); - } - - TailInputStream eventStream = new TailInputStream(eventFile); - - // Process user-defined RunListener classes. - if (!runListeners.isEmpty()) { - String classNames = runListeners.stream().map(x -> x.getClassName()).collect(Collectors.joining(",")); - - commandline.createArgument().setValue(SlaveMain.OPTION_RUN_LISTENERS); - commandline.createArgument().setValue(classNames); - } - - // Set up input suites file. - commandline.createArgument().setValue("@" + classNamesFile.toAbsolutePath().normalize()); - - // May or may not use dynamic load balancing, but if == 0 then we're for sure - // not using it. - if (dynamicAssignmentRatio > 0) { - commandline.createArgument().setValue(SlaveMain.OPTION_STDIN); - } - - final EventBus eventBus = new EventBus("slave-" + slave.id); - final DiagnosticsListener diagnosticsListener = new DiagnosticsListener(slave, this); - eventBus.register(diagnosticsListener); - eventBus.register(new AggregatingListener(aggregatedBus, slave)); - - final AtomicReference clientCharset = new AtomicReference(); - final AtomicBoolean clientWithLimitedCharset = new AtomicBoolean(); - final PrintWriter w = new PrintWriter(Files.newBufferedWriter(classNamesDynamic, StandardCharsets.UTF_8)); - eventBus.register(new Object() { - @Subscribe - public void onIdleSlave(final SlaveIdle idleSlave) { - aggregatedBus.post(new SlaveIdle() { - @Override - public void finished() { - idleSlave.finished(); - } - - @Override - public void newSuite(String suiteName) { - if (!clientCharset.get().newEncoder().canEncode(suiteName)) { - clientWithLimitedCharset.set(true); - log("Forked JVM J" + slave.id + " skipped suite (cannot encode suite name in charset " + - clientCharset.get() + "): " + suiteName, Project.MSG_WARN); - return; - } - - log("Forked JVM J" + slave.id + " stole suite: " + suiteName, Project.MSG_VERBOSE); - w.println(suiteName); - w.flush(); - idleSlave.newSuite(suiteName); - } - }); - } - - @Subscribe - public void onBootstrap(final BootstrapEvent e) { - Charset cs = Charset.forName(((BootstrapEvent) e).getDefaultCharsetName()); - clientCharset.set(cs); - - slave.start = System.currentTimeMillis(); - slave.setBootstrapEvent(e); - aggregatedBus.post(new ChildBootstrap(slave)); - } - - @Subscribe - public void receiveQuit(QuitEvent e) { - slave.end = System.currentTimeMillis(); - } - }); - - Closer closer = Closer.create(); - closer.register(eventStream); - closer.register(w); - try { - OutputStream sysout = closer.register(new BufferedOutputStream(Files.newOutputStream(sysoutFile))); - OutputStream syserr = closer.register(new BufferedOutputStream(Files.newOutputStream(syserrFile))); - RandomAccessFile streamsBuffer = closer.register(new RandomAccessFile(streamsBufferFile.toFile(), "rw")); - - Execute execute = forkProcess(slave, eventBus, commandline, eventStream, sysout, syserr, streamsBuffer); - log("Forked JVM J" + slave.id + " finished with exit code: " + execute.getExitValue(), Project.MSG_DEBUG); - - if (execute.isFailure()) { - final int exitStatus = execute.getExitValue(); - switch (exitStatus) { - case SlaveMain.ERR_NO_JUNIT: - throw new BuildException("Forked JVM's classpath must include a junit4 JAR."); - case SlaveMain.ERR_OLD_JUNIT: - throw new BuildException("Forked JVM's classpath must use JUnit 4.10 or newer."); - default: - Closeables.close(sysout, false); - Closeables.close(syserr, false); - - StringBuilder message = new StringBuilder(); - if (exitStatus == SlaveMain.ERR_OOM) { - message.append("Forked JVM ran out of memory."); - } else { - message.append("Forked process returned with error code: ").append(exitStatus).append("."); - } - - if (Files.size(sysoutFile) > 0 || Files.size(syserrFile) > 0) { - if (exitStatus != SlaveMain.ERR_OOM) { - message.append(" Very likely a JVM crash. "); - } - - if (jvmOutputAction.contains(JvmOutputAction.PIPE)) { - message.append(" Process output piped in logs above."); - } else if (!jvmOutputAction.contains(JvmOutputAction.IGNORE)) { - if (Files.size(sysoutFile) > 0) { - message.append(" See process stdout at: " + sysoutFile.toAbsolutePath()); - } - if (Files.size(syserrFile) > 0) { - message.append(" See process stderr at: " + syserrFile.toAbsolutePath()); - } - } - } - throw new BuildException(message.toString()); - } - } - } catch (Throwable t) { - throw closer.rethrow(t); - } finally { - try { - closer.close(); - } finally { - com.google.common.io.Files.asByteSource(classNamesDynamic.toFile()) - .copyTo(com.google.common.io.Files.asByteSink(classNamesFile.toFile(), FileWriteMode.APPEND)); - Files.delete(classNamesDynamic); - Files.delete(streamsBufferFile); - - // Check sysout/syserr lengths. - checkJvmOutput(aggregatedBus, sysoutFile, slave, "stdout"); - checkJvmOutput(aggregatedBus, syserrFile, slave, "stderr"); - } - } - - if (!diagnosticsListener.quitReceived()) { - throw new BuildException("Quit event not received from the forked process? This may indicate JVM crash or runner bugs."); - } - - if (clientWithLimitedCharset.get() && dynamicAssignmentRatio > 0) { - throw new BuildException("Forked JVM J" + slave.id + " was not be able to decode class names when using" + - " charset: " + clientCharset + ". Do not use " + - "dynamic suite balancing to work around this problem (-DdynamicAssignmentRatio=0)."); - } - } - - @SuppressForbidden("legitimate sysout.") - private void checkJvmOutput(EventBus aggregatedBus, Path file, ForkedJvmInfo forked, String fileName) throws IOException { - if (Files.size(file) > 0) { - String message = "JVM J" + forked.id + ": " + fileName + " was not empty, see: " + file; - if (jvmOutputAction.contains(JvmOutputAction.WARN)) { - log(message, Project.MSG_WARN); - } - if (jvmOutputAction.contains(JvmOutputAction.LISTENERS)) { - aggregatedBus.post(new JvmOutputEvent(forked, file.toFile())); - } - if (jvmOutputAction.contains(JvmOutputAction.PIPE)) { - log(">>> JVM J" + forked.id + ": " + fileName + " (verbatim) ----", Project.MSG_INFO); - try { - // If file > 10 mb, stream directly. Otherwise use the logger. - if (Files.size(file) < 10 * (1024 * 1024)) { - // Append to logger. - log(new String(Files.readAllBytes(file), forked.getCharset()), Project.MSG_INFO); - } else { - // Stream directly. - CharStreams.copy(Files.newBufferedReader(file, forked.getCharset()), System.out); - } - } catch (IOException e) { - log("Couldn't pipe file " + file + ": " + e.toString(), Project.MSG_INFO); - } - log("<<< JVM J" + forked.id + ": EOF ----", Project.MSG_INFO); - } - if (jvmOutputAction.contains(JvmOutputAction.IGNORE)) { - Files.delete(file); - } - if (jvmOutputAction.contains(JvmOutputAction.FAIL)) { - throw new BuildException(message); - } - return; - } - Files.delete(file); - } - - private Path tempFile(String uniqueSeed, String base, String suffix, Path tempDir) throws IOException { - return Files.createTempFile(tempDir, base + "-" + uniqueSeed, suffix); - } - - /** - * Try to provide an escaped, ready-to-use shell line to repeat a given command line. - */ - private String escapeAndJoin(String[] commandline) { - // TODO: we should try to escape special characters here, depending on the OS. - StringBuilder b = new StringBuilder(); - Pattern specials = Pattern.compile("[\\ ]"); - for (String arg : commandline) { - if (b.length() > 0) { - b.append(" "); - } - - if (specials.matcher(arg).find()) { - b.append('"').append(arg).append('"'); - } else { - b.append(arg); - } - } - return b.toString(); - } - - /** - * Execute a slave process. Pump events to the given event bus. - */ - @SuppressForbidden("legitimate sysstreams.") - private Execute forkProcess(ForkedJvmInfo slaveInfo, EventBus eventBus, - CommandlineJava commandline, - TailInputStream eventStream, OutputStream sysout, OutputStream syserr, RandomAccessFile streamsBuffer) { - try { - String tempDir = commandline.getSystemProperties().getVariablesVector().stream() - .filter(v -> v.getKey().equals("java.io.tmpdir")) - .map(v -> v.getValue()) - .findAny() - .orElse(null); - - final LocalSlaveStreamHandler streamHandler = - new LocalSlaveStreamHandler( - eventBus, testsClassLoader, System.err, eventStream, - sysout, syserr, heartbeat, streamsBuffer); - - // Add certain properties to allow identification of the forked JVM from within - // the subprocess. This can be used for policy files etc. - final Path cwd = getWorkingDirectory(slaveInfo, tempDir); - - Variable v = new Variable(); - v.setKey(CHILDVM_SYSPROP_CWD); - v.setFile(cwd.toAbsolutePath().normalize().toFile()); - commandline.addSysproperty(v); - - v = new Variable(); - v.setKey(SYSPROP_TEMPDIR); - v.setFile(getTempDir().toAbsolutePath().normalize().toFile()); - commandline.addSysproperty(v); - - v = new Variable(); - v.setKey(SysGlobals.CHILDVM_SYSPROP_JVM_ID); - v.setValue(Integer.toString(slaveInfo.id)); - commandline.addSysproperty(v); - - v = new Variable(); - v.setKey(SysGlobals.CHILDVM_SYSPROP_JVM_COUNT); - v.setValue(Integer.toString(slaveInfo.slaves)); - commandline.addSysproperty(v); - - // Emit command line before -stdin to avoid confusion. - slaveInfo.slaveCommandLine = escapeAndJoin(commandline.getCommandline()); - log("Forked child JVM at '" + cwd.toAbsolutePath().normalize() + - "', command (may need escape sequences for your shell):\n" + - slaveInfo.slaveCommandLine, Project.MSG_VERBOSE); - - final Execute execute = new Execute(); - execute.setCommandline(commandline.getCommandline()); - execute.setVMLauncher(true); - execute.setWorkingDirectory(cwd.toFile()); - execute.setStreamHandler(streamHandler); - execute.setNewenvironment(newEnvironment); - if (env.getVariables() != null) - execute.setEnvironment(env.getVariables()); - log("Starting JVM J" + slaveInfo.id, Project.MSG_DEBUG); - execute.execute(); - return execute; - } catch (IOException e) { - throw new BuildException("Could not start the child process. Run ant with -verbose to get" + - " the execution details.", e); - } - } - - private Path getWorkingDirectory(ForkedJvmInfo jvmInfo, String tempDir) throws IOException { - Path baseDir = (dir == null ? getProject().getBaseDir().toPath() : dir); - final Path forkedDir; - if (isolateWorkingDirectories) { - forkedDir = baseDir.resolve("J" + jvmInfo.id); - if (Files.isDirectory(forkedDir)) { - // If there are any files inside the forkedDir, issue a warning. - List existingFiles = listFiles(forkedDir); - if (!existingFiles.isEmpty()) { - switch (nonEmptyWorkDirAction) { - case IGNORE: - log("Cwd of a forked JVM already exists and is not empty: " - + existingFiles + " (ignoring).", Project.MSG_DEBUG); - break; - - case WIPE: - log("Cwd of a forked JVM already exists and is not empty, trying to wipe: " - + existingFiles, Project.MSG_DEBUG); - try { - Path tempPath = tempDir == null ? null : forkedDir.resolve(tempDir); - Files.walkFileTree(forkedDir, new SimpleFileVisitor() { - @Override - public FileVisitResult postVisitDirectory(Path dir, IOException iterationError) throws IOException { - if (iterationError != null) { - throw iterationError; - } - - if (Files.isSameFile(dir, forkedDir) || - (tempPath != null && Files.isSameFile(dir, tempPath))) { - // Do not delete cwd or an explicit java.io.tmpdir folder underneath. - } else { - Files.delete(dir); - } - return FileVisitResult.CONTINUE; - } - - @Override - public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { - Files.delete(file); - return FileVisitResult.CONTINUE; - } - - @Override - public FileVisitResult visitFileFailed(Path file, IOException e) throws IOException { - throw e; - } - }); - } catch (IOException e) { - throw new BuildException( - "An exception occurred while trying to wipe the working directory: " + forkedDir, e); - } - break; - case FAIL: - throw new BuildException("Cwd of a forked JVM already exists and is not empty " - + "and setOnNonEmptyWorkDirectory=" + nonEmptyWorkDirAction + ": " + existingFiles); - - default: - throw new RuntimeException("Unreachable."); - } - } - } else { - Files.createDirectories(forkedDir); - temporaryFiles.add(forkedDir); - } - } else { - forkedDir = baseDir; - } - return forkedDir; - } - - /** - * Resolve temporary folder. - */ - private Path getTempDir() { - if (this.tempDir == null) { - if (this.dir != null) { - this.tempDir = dir; - } else { - this.tempDir = getProject().getBaseDir().toPath(); - } - } - return tempDir; - } - - /** - * Process test resources. If there are any test resources that are _not_ class files, - * this will cause a build error. - */ - private TestsCollection processTestResources() { - TestsCollection collection = new TestsCollection(); - resources.setProject(getProject()); - - Iterator iter = (Iterator) resources.iterator(); - boolean javaSourceWarn = false; - while (iter.hasNext()) { - final Resource r = iter.next(); - if (!r.isExists()) - throw new BuildException("Test class resource does not exist?: " + r.getName()); - - try { - if (r.getName().endsWith(".java")) { - String pathname = r.getName(); - String className = pathname.substring(0, pathname.length() - ".java".length()); - className = className - .replace(File.separatorChar, '.') - .replace('/', '.') - .replace('\\', '.'); - collection.add(new TestClass(className)); - - if (!javaSourceWarn) { - log("Source (.java) files used for naming source suites. This is discouraged, " + - "use a resource collection pointing to .class files instead.", Project.MSG_INFO); - javaSourceWarn = true; - } - } else { - // Assume .class file. - InputStream is = r.getInputStream(); - if (!is.markSupported()) { - is = new BufferedInputStream(is); - } - - try { - is.mark(4); - if (is.read() != 0xca || - is.read() != 0xfe || - is.read() != 0xba || - is.read() != 0xbe) { - throw new BuildException("File does not start with a class magic 0xcafebabe: " - + r.getName() + ", " + r.getLocation()); - } - is.reset(); - - // Hardcoded intentionally. - final String REPLICATE_CLASS = "com.carrotsearch.randomizedtesting.annotations.ReplicateOnEachVm"; - final TestClass testClass = new TestClass(); - ClassReader reader = new ClassReader(is); - @SuppressWarnings("deprecation") - ClassVisitor annotationVisitor = new ClassVisitor(Opcodes.ASM8) { - @Override - public AnnotationVisitor visitAnnotation(String desc, boolean visible) { - String className = Type.getType(desc).getClassName(); - if (className.equals(REPLICATE_CLASS)) { - testClass.replicate = true; - } - return null; - } - }; - - reader.accept(annotationVisitor, ClassReader.SKIP_CODE | ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES); - testClass.className = reader.getClassName().replace('/', '.'); - log("Test class parsed: " + r.getName() + " as " + testClass.className, Project.MSG_DEBUG); - - collection.add(testClass); - } finally { - is.close(); - } - } - } catch (IOException e) { - throw new BuildException("Could not read or parse as Java class: " - + r.getName() + ", " + r.getLocation(), e); - } - } - - String testClassFilter = Strings.emptyToNull(getProject().getProperty(SYSPROP_TESTCLASS())); - if (testClassFilter != null) { - ClassGlobFilter filter = new ClassGlobFilter(testClassFilter); - for (Iterator i = collection.testClasses.iterator(); i.hasNext();) { - if (!filter.shouldRun(Description.createSuiteDescription(i.next().className))) { - i.remove(); - } - } - } - - return collection; - } - - /** - * Returns the slave VM command line. - */ - private CommandlineJava getCommandline() { - return slaveCommand; - } - - /** - * Adds a classpath source which contains the given resource. - * - * TODO: [GH-213] this is extremely ugly; separate the code required to run on the - * forked JVM into an isolated bundle and either create it on-demand (in temp. - * files location?) or locate it in classpath somehow (in a portable way). - */ - private org.apache.tools.ant.types.Path addSlaveClasspath() { - org.apache.tools.ant.types.Path path = new org.apache.tools.ant.types.Path(getProject()); - - String [] REQUIRED_SLAVE_CLASSES = { - SlaveMain.class.getName(), - Strings.class.getName(), - MethodGlobFilter.class.getName(), - TeeOutputStream.class.getName() - }; - - for (String clazz : Arrays.asList(REQUIRED_SLAVE_CLASSES)) { - String resource = clazz.replace(".", "/") + ".class"; - File f = LoaderUtils.getResourceSource(getClass().getClassLoader(), resource); - if (f != null) { - path.createPath().setLocation(f); - } else { - throw new BuildException("Could not locate classpath for resource: " + resource); - } - } - return path; - } -} diff --git a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/ListenersList.java b/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/ListenersList.java deleted file mode 100644 index fa3ff507..00000000 --- a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/ListenersList.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4; - -import java.util.List; - -import com.carrotsearch.ant.tasks.junit4.listeners.AggregatedEventListener; - -public class ListenersList { - - private List listeners; - - public ListenersList(List listeners) { - this.listeners = listeners; - } - - /** - * Adds a listener to the listeners list. - * @param listener - */ - public void addConfigured(AggregatedEventListener listener) { - listeners.add(listener); - } -} diff --git a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/LocalSlaveStreamHandler.java b/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/LocalSlaveStreamHandler.java deleted file mode 100644 index 4dd74da3..00000000 --- a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/LocalSlaveStreamHandler.java +++ /dev/null @@ -1,296 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.io.PrintStream; -import java.io.RandomAccessFile; -import java.lang.Thread.UncaughtExceptionHandler; -import java.nio.charset.Charset; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; - -import org.apache.tools.ant.taskdefs.ExecuteStreamHandler; -import org.apache.tools.ant.taskdefs.StreamPumper; - -import com.carrotsearch.ant.tasks.junit4.events.BootstrapEvent; -import com.carrotsearch.ant.tasks.junit4.events.Deserializer; -import com.carrotsearch.ant.tasks.junit4.events.EventType; -import com.carrotsearch.ant.tasks.junit4.events.IEvent; -import com.carrotsearch.ant.tasks.junit4.events.IStreamEvent; -import com.carrotsearch.ant.tasks.junit4.events.LowLevelHeartBeatEvent; -import com.google.common.eventbus.EventBus; - -/** - * Establish event passing with a subprocess and pump events to the bus. - */ -public class LocalSlaveStreamHandler implements ExecuteStreamHandler { - private final EventBus eventBus; - private final ClassLoader refLoader; - - private InputStream stdout; - private InputStream stderr; - - /** raw input stream to the client. */ - private OutputStream stdin; - - /** character-wrapped input stream to the client. */ - private OutputStreamWriter stdinWriter; - - private final PrintStream warnStream; - private final TailInputStream eventStream; - - private volatile boolean stopping; - - private List pumpers = new ArrayList<>(); - - private final OutputStream sysout; - private final OutputStream syserr; - private final long heartbeat; - private final RandomAccessFile streamsBuffer; - private final OutputStream streamsBufferWrapper; - - public LocalSlaveStreamHandler( - EventBus eventBus, ClassLoader classLoader, PrintStream warnStream, TailInputStream eventStream, - OutputStream sysout, OutputStream syserr, long heartbeat, final RandomAccessFile streamsBuffer) { - this.eventBus = eventBus; - this.warnStream = warnStream; - this.refLoader = classLoader; - this.eventStream = eventStream; - this.sysout = sysout; - this.syserr = syserr; - this.heartbeat = heartbeat; - this.streamsBuffer = streamsBuffer; - this.streamsBufferWrapper = new OutputStream() { - @Override - public void write(int b) throws IOException { - streamsBuffer.write(b); - } - - @Override - public void write(byte[] b) throws IOException { - streamsBuffer.write(b, 0, b.length); - } - - @Override - public void write(byte[] b, int off, int len) throws IOException { - streamsBuffer.write(b, off, len); - } - }; - } - - @Override - public void setProcessErrorStream(InputStream is) throws IOException { - this.stderr = is; - } - - @Override - public void setProcessOutputStream(InputStream is) throws IOException { - this.stdout = is; - } - - @Override - public void setProcessInputStream(OutputStream os) throws IOException { - this.stdin = os; - } - - /** - * A timestamp of last received event (GH-106). - */ - private volatile Long lastActivity; - - /** - * Watchdog thread if heartbeat is to be measured. - */ - private Thread watchdog; - - /** - * Client charset extracted from {@link BootstrapEvent}. - */ - private Charset clientCharset; - - @Override - public void start() throws IOException { - lastActivity = System.currentTimeMillis(); - - pumpers.add(new Thread(new SimpleStreamPumper(stdout, sysout), "pumper-stdout")); - pumpers.add(new Thread(new SimpleStreamPumper(stderr, syserr), "pumper-stderr")); - pumpers.add(new Thread("pumper-events") { - public void run() { - pumpEvents(eventStream); - } - }); - - if (heartbeat > 0) { - pumpers.add(watchdog = new Thread("pumper-watchdog") { - public void run() { - final long heartbeatMillis = TimeUnit.SECONDS.toMillis(heartbeat); - final long HEARTBEAT = Math.max(500, heartbeatMillis / 5); - final long HEARTBEAT_EVENT_THRESHOLD = heartbeatMillis; - try { - long lastObservedUpdate = lastActivity; - long reportDeadline = lastObservedUpdate + HEARTBEAT_EVENT_THRESHOLD; - while (true) { - Thread.sleep(HEARTBEAT); - - Long last = lastActivity; - if (last == null) { - break; // terminated. - } - - if (last != lastObservedUpdate) { - lastObservedUpdate = last; - reportDeadline = last + HEARTBEAT_EVENT_THRESHOLD; - } else { - final long current = System.currentTimeMillis(); - if (current >= reportDeadline) { - eventBus.post(new LowLevelHeartBeatEvent(last, current)); - reportDeadline = System.currentTimeMillis() + HEARTBEAT_EVENT_THRESHOLD; - } - } - } - } catch (InterruptedException e ) { - // terminate on interrupt. - } - } - }); - } - - // Start all pumper threads. - UncaughtExceptionHandler handler = new UncaughtExceptionHandler() { - public void uncaughtException(Thread t, Throwable e) { - warnStream.println("Unhandled exception in thread: " + t); - e.printStackTrace(warnStream); - } - }; - - for (Thread t : pumpers) { - t.setUncaughtExceptionHandler(handler); - t.setDaemon(true); - t.start(); - } - } - - private static class OnDiskStreamEvent implements IEvent, IStreamEvent { - private final RandomAccessFile bufferFile; - private long start; - private long end; - private EventType type; - - public OnDiskStreamEvent(EventType type, RandomAccessFile streamsBuffer, long start, long end) { - this.bufferFile = streamsBuffer; - this.start = start; - this.end = end; - this.type = type; - } - - @Override - public EventType getType() { - return type; - } - - @Override - public void copyTo(OutputStream os) throws IOException { - final long restorePosition = bufferFile.getFilePointer(); - bufferFile.seek(start); - try { - long length = end - start; - final byte [] buffer = new byte [(int) Math.min(length, 1024 * 4)]; - while (length > 0) { - int bytes = bufferFile.read(buffer, 0, (int) Math.min(length, buffer.length)); - os.write(buffer, 0, bytes); - length -= bytes; - } - } finally { - bufferFile.seek(restorePosition); - } - } - } - - /** - * Pump events from event stream. - */ - void pumpEvents(InputStream eventStream) { - try { - Deserializer deserializer = new Deserializer(eventStream, refLoader); - - IEvent event = null; - while ((event = deserializer.deserialize()) != null) { - switch (event.getType()) { - case APPEND_STDERR: - case APPEND_STDOUT: - // Ignore these two on activity heartbeats. GH-117 - break; - default: - lastActivity = System.currentTimeMillis(); - break; - } - - try { - switch (event.getType()) { - case QUIT: - eventBus.post(event); - return; - - case IDLE: - eventBus.post(new SlaveIdle(stdinWriter)); - break; - - case BOOTSTRAP: - clientCharset = Charset.forName(((BootstrapEvent) event).getDefaultCharsetName()); - stdinWriter = new OutputStreamWriter(stdin, clientCharset); - eventBus.post(event); - break; - - case APPEND_STDERR: - case APPEND_STDOUT: - assert streamsBuffer.getFilePointer() == streamsBuffer.length(); - final long bufferStart = streamsBuffer.getFilePointer(); - IStreamEvent streamEvent = (IStreamEvent) event; - streamEvent.copyTo(streamsBufferWrapper); - final long bufferEnd = streamsBuffer.getFilePointer(); - - event = new OnDiskStreamEvent(event.getType(), streamsBuffer, bufferStart, bufferEnd); - eventBus.post(event); - break; - - default: - eventBus.post(event); - } - } catch (Throwable t) { - warnStream.println("Event bus dispatch error: " + t.toString()); - t.printStackTrace(warnStream); - } - } - lastActivity = null; - } catch (Throwable e) { - if (!stopping) { - warnStream.println("Event stream error: " + e.toString()); - e.printStackTrace(warnStream); - } - } - } - - @Override - public void stop() { - lastActivity = null; - stopping = true; - try { - // Terminate watchdog early. - if (watchdog != null) { - watchdog.interrupt(); - } - - // Wait for all stream pumpers. - eventStream.completeAtEnd(); - for (Thread t : pumpers) { - t.join(); - t.interrupt(); - } - } catch (InterruptedException e) { - // Don't wait. - } - } -} diff --git a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/NonEmptyWorkDirectoryAction.java b/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/NonEmptyWorkDirectoryAction.java deleted file mode 100644 index 71e36ad4..00000000 --- a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/NonEmptyWorkDirectoryAction.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4; - -public enum NonEmptyWorkDirectoryAction { - /** Ignore any existing files in the work directory. */ - IGNORE, - - /** - * Wipe the content of the work directory clean if there are any files in it. - * Failure to delete any of the files will cause a build error. - */ - WIPE, - - /** - * Fail the build if the work directory is not empty. - */ - FAIL; -} diff --git a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/PickFromListTask.java b/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/PickFromListTask.java deleted file mode 100644 index 828477bd..00000000 --- a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/PickFromListTask.java +++ /dev/null @@ -1,133 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4; - -import static com.carrotsearch.randomizedtesting.SysGlobals.*; - -import java.util.ArrayList; -import java.util.List; -import java.util.Random; -import java.util.concurrent.atomic.AtomicInteger; - -import org.apache.tools.ant.BuildException; -import org.apache.tools.ant.Project; -import org.apache.tools.ant.ProjectComponent; -import org.apache.tools.ant.Task; - -import com.carrotsearch.randomizedtesting.SeedUtils; -import com.carrotsearch.randomizedtesting.generators.RandomPicks; -import com.google.common.base.Strings; - -/** - * An ANT task to pick and fix the random seed in advance (for selecting - * other derivative values, for example). - */ -public class PickFromListTask extends Task { - /** - * Nested value element. - */ - public final static class StringValue extends ProjectComponent { - private String value = ""; - - public void addText(String value) { - this.value += getProject().replaceProperties(value); - } - - @Override - public String toString() { - return value; - } - } - - /** - * Name of the property to set. - */ - private String propertyName; - - /** - * Allow the property to be undefined as one of - * the pick choices. - */ - private boolean allowUndefined = false; - - /** - * Random seed to use. - */ - private String random; - - /** - * Values to pick from. - */ - private List values = new ArrayList<>(); - - /** - * Execution ID used to permute the pick order for lists of identical length - * and identical seed. - */ - private static AtomicInteger executionId = new AtomicInteger(); - - public void setProperty(String propertyName) { - this.propertyName = propertyName; - } - - public void setAllowUndefined(boolean allowUndefined) { - this.allowUndefined = allowUndefined; - } - - public void setSeed(String randomSeed) { - if (!Strings.isNullOrEmpty(getProject().getUserProperty(SYSPROP_RANDOM_SEED()))) { - String userProperty = getProject().getUserProperty(SYSPROP_RANDOM_SEED()); - if (!userProperty.equals(randomSeed)) { - log("Ignoring seed attribute because it is overridden by user properties.", Project.MSG_WARN); - } - } else if (!Strings.isNullOrEmpty(randomSeed)) { - this.random = randomSeed; - } - } - - public StringValue createValue() { - StringValue v = new StringValue(); - values.add(v); - return v; - } - - /** - * Execute the task. - */ - @Override - public void execute() throws BuildException { - validate(); - - if (allowUndefined) { - values.add(null); - } - - long permutedSeed = SeedUtils.parseSeedChain(random)[0]; - permutedSeed ^= new Random(executionId.incrementAndGet()).nextLong(); - - StringValue pick = RandomPicks.randomFrom(new Random(permutedSeed), values); - if (pick != null) { - getProject().setProperty(propertyName, pick.toString()); - } - } - - /** - * Validate arguments and state. - */ - private void validate() { - if (Strings.emptyToNull(random) == null) { - random = Strings.emptyToNull(getProject().getProperty(SYSPROP_RANDOM_SEED())); - } - - if (random == null) { - throw new BuildException("Required attribute 'seed' must not be empty. Look at ."); - } - - long[] seeds = SeedUtils.parseSeedChain(random); - if (seeds.length < 1) { - throw new BuildException("Random seed is required."); - } - - if (values.isEmpty() && !allowUndefined) { - throw new BuildException("No values to pick from and allowUndefined=false."); - } - } -} diff --git a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/PickSeedTask.java b/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/PickSeedTask.java deleted file mode 100644 index 1e74ed9e..00000000 --- a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/PickSeedTask.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4; - -import java.util.Random; - -import org.apache.tools.ant.*; - -import com.carrotsearch.randomizedtesting.SeedUtils; -import com.carrotsearch.randomizedtesting.SysGlobals; -import com.google.common.base.Strings; - -/** - * An ANT task to pick and fix the random seed in advance (for selecting - * other derivative values, for example). - */ -public class PickSeedTask extends Task { - - /** - * Name of the property to set. - */ - private String propertyName; - - /** - * Picks a random seed and writes it to a given property. If the property - * is already defined nothing is done. - */ - public void setProperty(String propertyName) { - this.propertyName = propertyName; - } - - /** - * Execute the task. - */ - @Override - public void execute() throws BuildException { - validate(); - - String seedValue = Strings.emptyToNull(getProject().getProperty(propertyName)); - if (seedValue == null) { - seedValue = SeedUtils.formatSeed(new Random().nextLong()); - log("Picking master seed for property '" + propertyName + "': " - + seedValue, Project.MSG_VERBOSE); - getProject().setProperty(propertyName, seedValue); - } else { - log("Seed property '" + propertyName + "' already defined: " - + seedValue, Project.MSG_INFO); - } - } - - /** - * Validate arguments and state. - */ - private void validate() { - if (propertyName == null) { - propertyName = SysGlobals.SYSPROP_RANDOM_SEED(); - } - } -} diff --git a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/Pluralize.java b/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/Pluralize.java deleted file mode 100644 index 27b3cb5d..00000000 --- a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/Pluralize.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4; - -public final class Pluralize { - private Pluralize() {} - - public static String pluralize(int count, String word) { - if (count != 1) { - word += "s"; - } - return word; - } -} diff --git a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/RunListenerList.java b/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/RunListenerList.java deleted file mode 100644 index 2b389b21..00000000 --- a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/RunListenerList.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4; - -import com.carrotsearch.ant.tasks.junit4.runlisteners.RunListenerClass; - -import java.util.List; - -public final class RunListenerList { - private List listeners; - - public RunListenerList(List listeners) { - this.listeners = listeners; - } - - public void addConfigured(RunListenerClass runListener) { - listeners.add(runListener); - } -} \ No newline at end of file diff --git a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/SimpleStreamPumper.java b/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/SimpleStreamPumper.java deleted file mode 100644 index cb6125c9..00000000 --- a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/SimpleStreamPumper.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.UncheckedIOException; - -public class SimpleStreamPumper implements Runnable { - private final InputStream from; - private final OutputStream to; - - public SimpleStreamPumper(InputStream from, OutputStream to) { - this.from = from; - this.to = to; - } - - @Override - public void run() { - try { - byte[] buffer = new byte[1024 * 4]; - while (true) { - int len = from.read(buffer); - if (len > 0) { - to.write(buffer, 0, len); - } else if (len < 0) { - break; // EOF. - } else { - // read should be blocking? - Thread.sleep(250); - } - } - } catch (IOException e) { - throw new UncheckedIOException(e); - } catch (InterruptedException e) { - throw new RuntimeException("Pumper threads should not be interrupted?", e); - } - } -} diff --git a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/SlaveIdle.java b/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/SlaveIdle.java deleted file mode 100644 index 9fa61bca..00000000 --- a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/SlaveIdle.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4; - -import java.io.IOException; -import java.io.OutputStreamWriter; - -/** - * An event published when a slave is idle and waits for new suite classes. - */ -class SlaveIdle { - private OutputStreamWriter stdin; - - /** For delegation. */ - SlaveIdle() { - } - - public SlaveIdle(OutputStreamWriter stdin) { - this.stdin = stdin; - } - - public void finished() { - try { - stdin.close(); - } catch (IOException e) { - // Ignore, not much we can do. - } - } - - public void newSuite(String suiteName) { - try { - stdin.write(suiteName); - stdin.write("\n"); - stdin.flush(); - } catch (IOException e) { - throw new RuntimeException(e); - } - } -} diff --git a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/SuiteBalancer.java b/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/SuiteBalancer.java deleted file mode 100644 index 3ff7b227..00000000 --- a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/SuiteBalancer.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4; - -import java.util.Collection; -import java.util.List; - -/** - * A test balancer schedules test suites to be executed on a given JVM. - */ -public interface SuiteBalancer { - public final static class Assignment implements Comparable { - /** - * Test suite name. - */ - public final String suiteName; - - /** - * Slave assignment. - */ - public final int slaveId; - - /** - * Estimated cost; informational only (depends on the balancer). May be zero - * for balancers which don't use cost at all. - */ - public final int estimatedCost; - - public Assignment(String suiteName, int slaveId, int estimatedCost) { - this.suiteName = suiteName; - this.slaveId = slaveId; - this.estimatedCost = estimatedCost; - } - - @Override - public int compareTo(Assignment other) { - int v = this.suiteName.compareTo(other.suiteName); - if (v == 0) { - v = this.slaveId - other.slaveId; - } - return v; - } - } - - /** - * Sets the owner task (for logging mostly). - */ - void setOwner(JUnit4 owner); - - /** - * Provide assignments for suite names and a given number of slaves. - * - * @return Returns an ordered list with assignments. Any suite name not present - * in the keys of the returned map will be assigned by following - * balancers (or randomly). - */ - List assign(Collection suiteNames, int slaves, long seed); -} diff --git a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/TailInputStream.java b/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/TailInputStream.java deleted file mode 100644 index e9f0783a..00000000 --- a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/TailInputStream.java +++ /dev/null @@ -1,110 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4; - -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.RandomAccessFile; -import java.nio.file.Path; - -/** - * An input stream that tails from a random access file as new input appears there. - * It's a lousy solution but we don't have access to real interprocess pipes from Java. - */ -class TailInputStream extends InputStream { - /** How long to sleep (millis) before checking for updates? */ - private static final long TAIL_CHECK_DELAY = 250; - - private final RandomAccessFile raf; - private volatile boolean closed; - private volatile boolean complete; - - public TailInputStream(Path file) throws FileNotFoundException { - this.raf = new RandomAccessFile(file.toFile(), "r"); - } - - @Override - public int read() throws IOException { - if (closed) return -1; - - try { - int c; - while ((c = raf.read()) == -1) { - if (complete) { - return -1; // EOF; - } - try { - Thread.sleep(TAIL_CHECK_DELAY); - } catch (InterruptedException e) { - throw new IOException(e); - } - } - return c; - } catch (IOException e) { - if (closed) - return -1; - else - throw e; - } - } - - @Override - public int read(byte[] b, int off, int len) throws IOException { - if (closed) return -1; - - if (b == null) { - throw new NullPointerException(); - } else if (off < 0 || len < 0 || len > b.length - off) { - throw new IndexOutOfBoundsException(); - } else if (len == 0) { - return 0; - } - - try { - int rafRead = raf.read(b, off, len); - if (rafRead == -1) { - // If nothing in the buffer, wait. - do { - if (complete) { - return -1; // EOF; - } - - try { - Thread.sleep(TAIL_CHECK_DELAY); - } catch (InterruptedException e) { - throw new IOException(e); - } - } while ((rafRead = raf.read(b, off, len)) == -1); - } - return rafRead; - } catch (IOException e) { - if (closed) - return -1; - else - throw e; - } - } - - @Override - public int read(byte[] b) throws IOException { - return read(b, 0, b.length); - } - - @Override - public boolean markSupported() { - return false; - } - - @Override - public void close() throws IOException { - closed = true; - this.raf.close(); - } - - /** - * Changes the semantics of tailing so that from the moment of calling this method on, - * hitting an EOF on the tailed file will cause an EOF in read methods. - */ - public void completeAtEnd() { - complete = true; - } -} diff --git a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/TestClass.java b/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/TestClass.java deleted file mode 100644 index 14fe3a3e..00000000 --- a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/TestClass.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4; - -final class TestClass { - String className; - boolean replicate; - - public TestClass() { - this(null); - } - - public TestClass(String className) { - this.className = className; - } -} diff --git a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/TestsCollection.java b/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/TestsCollection.java deleted file mode 100644 index e502391b..00000000 --- a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/TestsCollection.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4; - -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -/** - * A collection of test suites and extracted annotation information. - */ -final class TestsCollection { - List testClasses = new ArrayList<>(); - - public void add(TestClass testClass) { - testClasses.add(testClass); - } - - public void onlyUniqueSuiteNames() { - Map unique = new LinkedHashMap<>(); - for (TestClass t : testClasses) { - unique.put(t.className, t); - } - testClasses.clear(); - testClasses.addAll(unique.values()); - } - - public boolean hasReplicatedSuites() { - for (TestClass t : testClasses) { - if (t.replicate) return true; - } - return false; - } -} diff --git a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/TestsSummary.java b/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/TestsSummary.java deleted file mode 100644 index 8a923faa..00000000 --- a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/TestsSummary.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4; - -import static com.carrotsearch.ant.tasks.junit4.Pluralize.*; - -/** - * Summary of tests execution. - */ -public class TestsSummary { - public final int suites, ignoredSuites, suiteErrors; - public final int tests, failures, errors, assumptions, ignores; - - public TestsSummary( - int suites, int ignoredSuites, int suiteErrors, - int tests, int failures, int errors, int assumptions, int ignores) { - this.suites = suites; - this.ignoredSuites = ignoredSuites; - this.suiteErrors = suiteErrors; - - this.tests = tests; - this.failures = failures; - this.errors = errors; - this.assumptions = assumptions; - this.ignores = ignores; - } - - public boolean isSuccessful() { - return (errors + failures + suiteErrors) == 0; - } - - @Override - public String toString() { - StringBuilder s = new StringBuilder(); - s.append(suites).append(pluralize(suites, " suite")); - if (ignoredSuites > 0) { - s.append(" (").append(ignoredSuites).append(" ignored)"); - } - s.append(", ").append(tests).append(pluralize(tests, " test")); - if (suiteErrors > 0) s.append(", ").append(suiteErrors).append(pluralize(suiteErrors, " suite-level error")); - if (errors > 0) s.append(", ").append(errors).append(pluralize(errors, " error")); - if (failures > 0) s.append(", ").append(failures).append(pluralize(failures, " failure")); - if (ignores + assumptions > 0) { - s.append(", ").append(ignores + assumptions).append(" ignored"); - if (assumptions > 0) { - s.append(" (").append(assumptions).append(pluralize(assumptions, " assumption")).append(")"); - } - } - return s.toString(); - } - - public int getNonIgnoredTestsCount() { - return tests - (ignores + assumptions); - } -} diff --git a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/TestsSummaryEventListener.java b/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/TestsSummaryEventListener.java deleted file mode 100644 index 426624f0..00000000 --- a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/TestsSummaryEventListener.java +++ /dev/null @@ -1,71 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4; - -import com.carrotsearch.ant.tasks.junit4.events.aggregated.AggregatedSuiteResultEvent; -import com.carrotsearch.ant.tasks.junit4.events.aggregated.AggregatedTestResultEvent; -import com.google.common.eventbus.EventBus; -import com.google.common.eventbus.Subscribe; - -/** - * Create a summary of tests execution. - * - * @see EventBus - */ -public class TestsSummaryEventListener { - private int failures; - private int tests; - private int errors; - private int assumptions; - private int ignores; - - private int suites; - private int ignoredSuites; - private int suiteErrors; - - /** - * React to suite summaries only. - */ - @Subscribe - public void suiteSummary(AggregatedSuiteResultEvent e) { - suites++; - if (!e.getFailures().isEmpty()) { - suiteErrors += e.getFailures().size(); - } - - for (AggregatedTestResultEvent testResult : e.getTests()) { - tests++; - - switch (testResult.getStatus()) { - case ERROR: - errors++; - break; - - case FAILURE: - failures++; - break; - - case IGNORED: - ignores++; - break; - - case IGNORED_ASSUMPTION: - assumptions++; - break; - - default: - break; - } - } - - if (e.isSuccessful() && - e.getTests().isEmpty()) { - ignoredSuites++; - } - } - - /** - * Return the summary of all tests. - */ - public TestsSummary getResult() { - return new TestsSummary(suites, ignoredSuites, suiteErrors, tests, failures, errors, assumptions, ignores); - } -} diff --git a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/balancers/ExecutionTimeBalancer.java b/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/balancers/ExecutionTimeBalancer.java deleted file mode 100644 index 4ece79bb..00000000 --- a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/balancers/ExecutionTimeBalancer.java +++ /dev/null @@ -1,139 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.balancers; - -import java.util.*; - -import org.apache.tools.ant.Project; -import org.apache.tools.ant.ProjectComponent; -import org.apache.tools.ant.types.FileSet; -import org.apache.tools.ant.types.ResourceCollection; - -import com.carrotsearch.ant.tasks.junit4.*; -import com.carrotsearch.ant.tasks.junit4.listeners.ExecutionTimesReport; - -/** - * A test suite balancer based on past execution times saved using - * {@link ExecutionTimesReport}. - */ -public class ExecutionTimeBalancer extends ProjectComponent implements SuiteBalancer { - private static class SlaveLoad { - public static final Comparator ASCENDING_BY_ESTIMATED_FINISH = new Comparator() { - @Override - public int compare(SlaveLoad o1, SlaveLoad o2) { - if (o1.estimatedFinish < o2.estimatedFinish) { - return -1; - } else if (o1.estimatedFinish == o2.estimatedFinish) { - return o1.id - o2.id; // Assume no overflows. - } else { - return 1; - } - } - }; - - public final int id; - public long estimatedFinish; - - public SlaveLoad(int id) { - this.id = id; - } - } - - /** - * All included execution time dumps. - */ - private List resources = new ArrayList<>(); - - /** Owning task (logging). */ - private JUnit4 owner; - - /** @see #setVerbose(boolean) */ - private boolean verbose; - - /** - * Be verbose about estimated times etc. - */ - public void setVerbose(boolean verbose) { - this.verbose = verbose; - } - - /** - * Adds a resource collection with execution hints. - */ - public void add(ResourceCollection rc) { - if (rc instanceof FileSet) { - FileSet fs = (FileSet) rc; - fs.setProject(getProject()); - } - resources.add(rc); - } - - - /** - * Assign based on execution time history. The algorithm is a greedy heuristic - * assigning the longest remaining test to the slave with the - * shortest-completion time so far. This is not optimal but fast and provides - * a decent average assignment. - */ - @Override - public List assign(Collection suiteNames, int slaves, long seed) { - // Read hints first. - final Map> hints = ExecutionTimesReport.mergeHints(resources, suiteNames); - - // Preprocess and sort costs. Take the median for each suite's measurements as the - // weight to avoid extreme measurements from screwing up the average. - final List costs = new ArrayList<>(); - for (String suiteName : suiteNames) { - final List suiteHint = hints.get(suiteName); - if (suiteHint != null) { - // Take the median for each suite's measurements as the weight - // to avoid extreme measurements from screwing up the average. - Collections.sort(suiteHint); - final Long median = suiteHint.get(suiteHint.size() / 2); - costs.add(new SuiteHint(suiteName, median)); - } - } - Collections.sort(costs, SuiteHint.DESCENDING_BY_WEIGHT); - - // Apply the assignment heuristic. - final PriorityQueue pq = new PriorityQueue( - slaves, SlaveLoad.ASCENDING_BY_ESTIMATED_FINISH); - for (int i = 0; i < slaves; i++) { - pq.add(new SlaveLoad(i)); - } - - final List assignments = new ArrayList<>(); - for (SuiteHint hint : costs) { - SlaveLoad slave = pq.remove(); - slave.estimatedFinish += hint.cost; - pq.add(slave); - - owner.log("Expected execution time for " + hint.suiteName + ": " + - Duration.toHumanDuration(hint.cost), - Project.MSG_DEBUG); - - assignments.add(new Assignment(hint.suiteName, slave.id, (int) hint.cost)); - } - - // Dump estimated execution times. - TreeMap ordered = new TreeMap(); - while (!pq.isEmpty()) { - SlaveLoad slave = pq.remove(); - ordered.put(slave.id, slave); - } - for (Integer id : ordered.keySet()) { - final SlaveLoad slave = ordered.get(id); - owner.log(String.format(Locale.ROOT, - "Expected execution time on JVM J%d: %8.2fs", - slave.id, - slave.estimatedFinish / 1000.0f), - verbose ? Project.MSG_INFO : Project.MSG_DEBUG); - } - - return assignments; - } - - - @Override - public void setOwner(JUnit4 owner) { - this.owner = owner; - } -} diff --git a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/balancers/MergeHints.java b/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/balancers/MergeHints.java deleted file mode 100644 index b9ab9ad7..00000000 --- a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/balancers/MergeHints.java +++ /dev/null @@ -1,81 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.balancers; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import org.apache.tools.ant.BuildException; -import org.apache.tools.ant.Task; -import org.apache.tools.ant.types.FileSet; -import org.apache.tools.ant.types.ResourceCollection; - -import com.carrotsearch.ant.tasks.junit4.listeners.ExecutionTimesReport; - -/** - * Merge execution hints emitted by {@link ExecutionTimeBalancer} to one file. - */ -public class MergeHints extends Task { - /** - * All included execution time dumps. - */ - private List resources = new ArrayList<>(); - - /** - * @see ExecutionTimesReport#setHistoryLength(int) - */ - private int historyLength = ExecutionTimesReport.DEFAULT_HISTORY_LENGTH; - - /** - * Output file for merged hints. - */ - private File file; - - /** - * @see ExecutionTimesReport#setHistoryLength(int) - */ - public void setHistoryLength(int historyLength) { - if (historyLength < 0) { - throw new BuildException("History length must be >= 1: " + historyLength); - } - this.historyLength = historyLength; - } - - /** - * Set the output file for merged hints. - */ - public void setFile(File file) { - this.file = file; - } - - /** - * Adds a resource collection with execution hints. - */ - public void add(ResourceCollection rc) { - if (rc instanceof FileSet) { - FileSet fs = (FileSet) rc; - fs.setProject(getProject()); - } - resources.add(rc); - } - - @Override - public void execute() throws BuildException { - // Read hints first, preserve all hints. - final Map> hints = ExecutionTimesReport.mergeHints( - resources, /* keep all */ null); - - for (List hintList : hints.values()) { - while (hintList.size() > historyLength) { - hintList.remove(0); - } - } - - try { - ExecutionTimesReport.writeHints(file, hints); - } catch (IOException e) { - throw new BuildException("Could not write updated hints file: " + file, e); - } - } -} diff --git a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/balancers/RoundRobinBalancer.java b/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/balancers/RoundRobinBalancer.java deleted file mode 100644 index c00a3ff5..00000000 --- a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/balancers/RoundRobinBalancer.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.balancers; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import com.carrotsearch.ant.tasks.junit4.JUnit4; -import com.carrotsearch.ant.tasks.junit4.SuiteBalancer; - -/** - * A round-robin suite balancer (default for non-assigned suites). - */ -public class RoundRobinBalancer implements SuiteBalancer { - - @Override - public List assign(Collection suiteNames, int slaves, long seed) { - List result = new ArrayList<>(); - int i = 0; - for (String suite : suiteNames) { - result.add(new Assignment(suite, i++, 0)); - if (i >= slaves) i = 0; - } - return result; - } - - @Override - public void setOwner(JUnit4 owner) {} -} diff --git a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/balancers/SuiteHint.java b/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/balancers/SuiteHint.java deleted file mode 100644 index 56d10ef6..00000000 --- a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/balancers/SuiteHint.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.balancers; - -import java.util.Comparator; - -/** - * A suite with the cost hint. - */ -public final class SuiteHint { - public static final Comparator DESCENDING_BY_WEIGHT = new Comparator() { - @Override - public int compare(SuiteHint o1, SuiteHint o2) { - if (o1.cost == o2.cost) - return o1.suiteName.compareTo(o2.suiteName); - - if (o1.cost < o2.cost) - return 1; - else - return -1; - } - }; - - public final String suiteName; - public final long cost; - - public SuiteHint(String suiteName, long weight) { - this.suiteName = suiteName; - this.cost = weight; - } -} \ No newline at end of file diff --git a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/balancers/TopHints.java b/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/balancers/TopHints.java deleted file mode 100644 index 12037ef2..00000000 --- a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/balancers/TopHints.java +++ /dev/null @@ -1,93 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.balancers; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; -import java.util.Locale; -import java.util.Map; - -import org.apache.tools.ant.BuildException; -import org.apache.tools.ant.Task; -import org.apache.tools.ant.types.FileSet; -import org.apache.tools.ant.types.ResourceCollection; - -import com.carrotsearch.ant.tasks.junit4.listeners.ExecutionTimesReport; - -/** - * Display the slowest test suites based on hints files. - */ -public class TopHints extends Task { - - private static class Entry { - String suiteName; - double averageHint; - - public Entry(String s, double h) { - this.suiteName = s; - this.averageHint = h; - } - } - - private static final Comparator byDescHint = new Comparator() { - @Override - public int compare(Entry o1, Entry o2) { - if (o1.averageHint < o2.averageHint) return 1; - if (o1.averageHint > o2.averageHint) return -1; - return o1.suiteName.compareTo(o2.suiteName); - } - }; - - /** - * All included execution time dumps. - */ - private List resources = new ArrayList<>(); - - /** - * Max entries to display. - */ - private int max = 10; - - /** - * The number of entries to display, maximum. - */ - public void setMax(int maxEntries) { - this.max = maxEntries; - } - - /** - * Adds a resource collection with execution hints. - */ - public void add(ResourceCollection rc) { - if (rc instanceof FileSet) { - FileSet fs = (FileSet) rc; - fs.setProject(getProject()); - } - resources.add(rc); - } - - @Override - public void execute() throws BuildException { - // Read hints first, preserve all hints. - final Map> hints = ExecutionTimesReport.mergeHints( - resources, /* keep all */ null); - - // Could be done with a pq without sorting everything... - ArrayList entries = new ArrayList(); - for (Map.Entry> e : hints.entrySet()) { - double average = 0; - for (Long v : e.getValue()) { - average += v; - } - entries.add(new Entry(e.getKey(), average / e.getValue().size())); - } - - Collections.sort(entries, byDescHint); - final int j = Math.min(max, entries.size()); - for (int i = 0; i < j; i++) { - log(String.format(Locale.ROOT, "%6.2fs | %s", - entries.get(i).averageHint / 1000.0, - entries.get(i).suiteName)); - } - } -} diff --git a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/AbstractEvent.java b/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/AbstractEvent.java deleted file mode 100644 index 4488c4de..00000000 --- a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/AbstractEvent.java +++ /dev/null @@ -1,121 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.events; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; - -import org.junit.runner.Description; - -import com.carrotsearch.ant.tasks.junit4.gson.stream.JsonReader; -import com.carrotsearch.ant.tasks.junit4.gson.stream.JsonToken; -import com.carrotsearch.ant.tasks.junit4.gson.stream.JsonWriter; - -/** - * An abstract {@link IEvent}. - */ -abstract class AbstractEvent implements RemoteEvent { - private final static char [] HEX = "0123456789ABCDEF".toCharArray(); - - /** Type is recreated in constructors anyway. */ - private transient final EventType type; - - public AbstractEvent(EventType type) { - if (this.getClass() != type.eventClass) { - throw new RuntimeException("Event type mismatch: " - + type + ", class: " + this.getClass()); - } - - this.type = type; - } - - @Override - public EventType getType() { - return type; - } - - protected static JsonWriter writeBinaryProperty(JsonWriter writer, String propertyName, byte[] value) throws IOException { - return writer.name(propertyName).value(toAscii(value)); - } - - protected static byte[] readBinaryProperty(JsonReader reader, String propertyName) throws IOException { - return fromAscii(expectProperty(reader, propertyName).nextString()); - } - - protected static String readStringProperty(JsonReader reader, String propertyName) throws IOException { - if (expectProperty(reader, propertyName).peek() != JsonToken.STRING) { - throw new IOException("Expected a non-null string for property: " + propertyName); - } - return reader.nextString(); - } - - protected static String readStringOrNullProperty(JsonReader reader, String propertyName) throws IOException { - expectProperty(reader, propertyName); - if (reader.peek() == JsonToken.STRING) { - return reader.nextString(); - } else if (reader.peek() == JsonToken.NULL) { - reader.nextNull(); - return null; - } else { - throw new IOException("Expected a non or string for property: " + propertyName); - } - } - - protected static boolean readBoolean(JsonReader reader, String propertyName) throws IOException { - expectProperty(reader, propertyName); - return reader.nextBoolean(); - } - - protected static long readLongProperty(JsonReader reader, String propertyName) throws IOException { - return expectProperty(reader, propertyName).nextLong(); - } - - protected static JsonReader expectProperty(JsonReader reader, String propertyName) throws IOException { - final String name = reader.nextName(); - if (!propertyName.equals(name)) { - throw new IOException("Expected property: " + propertyName + " but got: " + name); - } - return reader; - } - - private static byte[] fromAscii(String ascii) throws IOException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - for (int i = 0; i < ascii.length(); i++) { - char chr = ascii.charAt(i); - if (chr != '%') { - baos.write(chr); - } else { - baos.write((hexValue(ascii.charAt(++i)) << 4) | - hexValue(ascii.charAt(++i))); - } - } - return baos.toByteArray(); - } - - private static int hexValue(char hexChar) throws IOException { - if (hexChar >= '0' && hexChar <= '9') - return hexChar - '0'; - if (hexChar >= 'A' && hexChar <= 'F') - return hexChar - 'A' + 10; - if (hexChar >= 'a' && hexChar <= 'f') - return hexChar - 'a' + 10; - throw new IOException("Unexpected character in binary stream: " + hexChar); - } - - private static String toAscii(byte[] src) { - StringBuilder bb = new StringBuilder(); - for (byte b : src) { - // Pass simple ASCII range. - if (b >= 32 && b <= 126 && b != '%') { - bb.append((char) b); - } else { - bb.append('%'); - bb.append(HEX[(b >> 4) & 0x0f]); - bb.append(HEX[(b ) & 0x0f]); - } - } - return bb.toString(); - } - - public static void writeDescription(JsonWriter writer, Description e) throws IOException { - JsonHelpers.writeDescription(writer, e); - } -} diff --git a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/AbstractEventWithDescription.java b/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/AbstractEventWithDescription.java deleted file mode 100644 index 35564b09..00000000 --- a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/AbstractEventWithDescription.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.events; - -import java.io.IOException; - -import org.junit.runner.Description; - -import com.carrotsearch.ant.tasks.junit4.gson.stream.JsonReader; -import com.carrotsearch.ant.tasks.junit4.gson.stream.JsonWriter; - -abstract class AbstractEventWithDescription extends AbstractEvent implements IDescribable { - private Description description; - - public AbstractEventWithDescription(EventType type) { - super(type); - } - - public Description getDescription() { - return description; - } - - protected void setDescription(Description description) { - if (this.description != null) - throw new IllegalStateException("Initialize once."); - this.description = description; - } - - @Override - public void serialize(JsonWriter writer) throws IOException { - writeDescription(writer, description); - } - - @Override - public void deserialize(JsonReader reader) throws IOException { - this.description = JsonHelpers.readDescription(reader); - } -} diff --git a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/AppendStdErrEvent.java b/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/AppendStdErrEvent.java deleted file mode 100644 index ceb10d2e..00000000 --- a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/AppendStdErrEvent.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.events; - -import java.io.IOException; -import java.io.OutputStream; - -import com.carrotsearch.ant.tasks.junit4.gson.stream.JsonReader; -import com.carrotsearch.ant.tasks.junit4.gson.stream.JsonWriter; - -public class AppendStdErrEvent extends AbstractEvent implements IStreamEvent { - private byte[] chunk; - - protected AppendStdErrEvent() { - super(EventType.APPEND_STDERR); - } - - public AppendStdErrEvent(byte[] b, int off, int len) { - this(); - chunk = new byte [len]; - System.arraycopy(b, off, chunk, 0, len); - } - - @Override - public void copyTo(OutputStream os) throws IOException { - os.write(chunk); - } - - @Override - public void serialize(JsonWriter writer) throws IOException { - writer.beginObject(); - writeBinaryProperty(writer, "chunk", chunk); - writer.endObject(); - } - - @Override - public void deserialize(JsonReader reader) throws IOException { - reader.beginObject(); - chunk = readBinaryProperty(reader, "chunk"); - reader.endObject(); - } -} \ No newline at end of file diff --git a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/AppendStdOutEvent.java b/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/AppendStdOutEvent.java deleted file mode 100644 index d1447fc2..00000000 --- a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/AppendStdOutEvent.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.events; - -import java.io.IOException; -import java.io.OutputStream; - -import com.carrotsearch.ant.tasks.junit4.gson.stream.JsonReader; -import com.carrotsearch.ant.tasks.junit4.gson.stream.JsonWriter; - -public class AppendStdOutEvent extends AbstractEvent implements IStreamEvent { - private byte[] chunk; - - protected AppendStdOutEvent() { - super(EventType.APPEND_STDOUT); - } - - public AppendStdOutEvent(byte[] b, int off, int len) { - this(); - chunk = new byte [len]; - System.arraycopy(b, off, chunk, 0, len); - } - - @Override - public void copyTo(OutputStream os) throws IOException { - os.write(chunk); - } - - @Override - public void serialize(JsonWriter writer) throws IOException { - writer.beginObject(); - writeBinaryProperty(writer, "chunk", chunk); - writer.endObject(); - } - - @Override - public void deserialize(JsonReader reader) throws IOException { - reader.beginObject(); - chunk = readBinaryProperty(reader, "chunk"); - reader.endObject(); - } -} diff --git a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/BootstrapEvent.java b/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/BootstrapEvent.java deleted file mode 100644 index 564de8b4..00000000 --- a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/BootstrapEvent.java +++ /dev/null @@ -1,158 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.events; - -import java.io.IOException; -import java.lang.management.ManagementFactory; -import java.nio.charset.Charset; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Enumeration; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.TreeMap; - -import com.carrotsearch.ant.tasks.junit4.gson.stream.JsonReader; -import com.carrotsearch.ant.tasks.junit4.gson.stream.JsonToken; -import com.carrotsearch.ant.tasks.junit4.gson.stream.JsonWriter; - -/** - * Initial message sent from the slave to the master (if forked locally). - */ -public class BootstrapEvent extends AbstractEvent { - private static final List GUARANTEED_PROPERTIES = Arrays.asList( - "java.version", - "java.vendor", - "java.vendor.url", - "java.home", - "java.vm.specification.version", - "java.vm.specification.vendor", - "java.vm.specification.name", - "java.vm.version", - "java.vm.vendor", - "java.vm.name", - "java.specification.version", - "java.specification.vendor", - "java.specification.name", - "java.class.version", - "java.class.path", - "java.library.path", - "java.io.tmpdir", - "java.compiler", - "java.ext.dirs", - "os.name", - "os.arch", - "os.version", - "file.separator", - "path.separator", - "line.separator", - "user.name", - "user.home", - "user.dir"); - - private String defaultCharset; - private Map systemProperties; - private String pidString; - - /** Preinitialization with local machine's configuration. */ - public BootstrapEvent() { - super(EventType.BOOTSTRAP); - - this.defaultCharset = Charset.defaultCharset().name(); - - try { - pidString = ManagementFactory.getRuntimeMXBean().getName(); - } catch (Throwable t) { - pidString = ""; - } - - this.systemProperties = collectSystemProperties(); - - systemProperties.put("junit4.memory.total", - Long.toString(Runtime.getRuntime().totalMemory())); - systemProperties.put("junit4.processors", - Long.toString(Runtime.getRuntime().availableProcessors())); - systemProperties.put("junit4.pidString", pidString); - } - - private Map collectSystemProperties() { - List propertyNames = new ArrayList(); - try { - Enumeration e = System.getProperties().propertyNames(); - while (e.hasMoreElements()) { - propertyNames.add((String) e.nextElement()); - } - } catch (SecurityException e) { - // No access to the full set of properties. Try to include at least the default - // guaranteed set of properties (maybe we have read-only access). - propertyNames.addAll(GUARANTEED_PROPERTIES); - } - - TreeMap sysProps = new TreeMap(); - for (String propertyName : propertyNames) { - try { - String value = System.getProperty(propertyName); - if (value != null) { - sysProps.put(propertyName, value); - } - } catch (SecurityException e) { - // No access. Ignore. - } - } - - return sysProps; - } - - /** - * Default charset on the slave. - */ - public String getDefaultCharsetName() { - return defaultCharset; - } - - /** - * System properties on the slave. - */ - public Map getSystemProperties() { - return systemProperties; - } - - /** - * Returns a PID string or anything that approximates it and would - * help in dumping a stack trace externally, for example. - */ - public String getPidString() { - return pidString; - } - - @Override - public void serialize(JsonWriter writer) throws IOException { - writer.beginObject(); - writer.name("defaultCharset").value(defaultCharset); - writer.name("pidString").value(pidString); - - writer.name("systemProperties").beginObject(); - for (Map.Entry e : systemProperties.entrySet()) { - writer.name(e.getKey()).value(e.getValue()); - } - writer.endObject(); - - writer.endObject(); - } - - @Override - public void deserialize(JsonReader reader) throws IOException { - reader.beginObject(); - defaultCharset = readStringProperty(reader, "defaultCharset"); - pidString = readStringProperty(reader, "pidString"); - - expectProperty(reader, "systemProperties"); - reader.beginObject(); - systemProperties = new LinkedHashMap(); - while (reader.peek() != JsonToken.END_OBJECT) { - systemProperties.put(reader.nextName(), reader.nextString()); - } - reader.endObject(); - - reader.endObject(); - } -} diff --git a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/Deserializer.java b/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/Deserializer.java deleted file mode 100644 index 14e1818e..00000000 --- a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/Deserializer.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.events; - -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; - -import com.carrotsearch.ant.tasks.junit4.gson.stream.JsonReader; -import com.carrotsearch.ant.tasks.junit4.gson.stream.JsonToken; -import com.google.common.base.Charsets; - -/** - * Event deserializer. - */ -public class Deserializer { - private JsonReader input; - - public Deserializer(InputStream is, ClassLoader refLoader) throws IOException { - input = new JsonReader(new InputStreamReader(is, Charsets.UTF_8)); - input.setLenient(true); - } - - public IEvent deserialize() throws IOException { - JsonToken peek = input.peek(); - if (peek == JsonToken.END_ARRAY) - return null; - - input.beginArray(); - EventType type = EventType.valueOf(input.nextString()); - IEvent event = type.deserialize(input); - input.endArray(); - return event; - } -} diff --git a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/EventType.java b/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/EventType.java deleted file mode 100644 index d362d4fc..00000000 --- a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/EventType.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.events; - -import java.io.IOException; - -import com.carrotsearch.ant.tasks.junit4.gson.stream.JsonReader; - -/** - * Events (messages) passed between the slave and the master. - */ -public enum EventType { - BOOTSTRAP(BootstrapEvent.class), - - SUITE_STARTED(SuiteStartedEvent.class), - SUITE_FAILURE(SuiteFailureEvent.class), - SUITE_COMPLETED(SuiteCompletedEvent.class), - - APPEND_STDOUT(AppendStdOutEvent.class), - APPEND_STDERR(AppendStdErrEvent.class), - - TEST_STARTED(TestStartedEvent.class), - TEST_FAILURE(TestFailureEvent.class), - TEST_IGNORED_ASSUMPTION(TestIgnoredAssumptionEvent.class), - TEST_IGNORED(TestIgnoredEvent.class), - TEST_FINISHED(TestFinishedEvent.class), - - IDLE(IdleEvent.class), - QUIT(QuitEvent.class); - - /** - * Concrete class associated with the given event type. - */ - public final Class eventClass; - - /** - * Initialize with concrete event class. - */ - private EventType(Class eventClass) { - this.eventClass = eventClass; - } - - /** - * Deserialize a given event type from stream. - */ - public RemoteEvent deserialize(JsonReader input) throws IOException { - RemoteEvent empty; - try { - empty = eventClass.newInstance(); - empty.deserialize(input); - return empty; - } catch (InstantiationException e) { - throw new IOException(e); - } catch (IllegalAccessException e) { - throw new IOException(e); - } - } -} diff --git a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/FailureEvent.java b/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/FailureEvent.java deleted file mode 100644 index 831864fd..00000000 --- a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/FailureEvent.java +++ /dev/null @@ -1,77 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.events; - -import java.io.IOException; - -import org.junit.runner.Description; -import org.junit.runner.notification.Failure; - -import com.carrotsearch.ant.tasks.junit4.events.mirrors.FailureMirror; -import com.carrotsearch.ant.tasks.junit4.gson.stream.JsonReader; -import com.carrotsearch.ant.tasks.junit4.gson.stream.JsonWriter; - -/** - * Generic serialized failure event. - */ -public abstract class FailureEvent extends AbstractEvent implements IDescribable { - private FailureMirror failure; - - public FailureEvent(EventType type) { - super(type); - } - - protected void setFailure(Failure failure) { - if (this.failure != null) { - throw new IllegalStateException("Set only once."); - } - - this.failure = new FailureMirror(failure); - } - - public FailureMirror getFailure() { - return failure; - } - - public Description getDescription() { - return failure.getDescription(); - } - - @Override - public void serialize(JsonWriter writer) throws IOException { - writer.beginObject(); - - writer.name("description"); - writeDescription(writer, failure.getDescription()); - - writer.name("message").value(failure.getMessage()); - writer.name("trace").value(failure.getTrace()); - writer.name("throwableString").value(failure.getThrowableString()); - writer.name("throwableClass").value(failure.getThrowableClass()); - writer.name("assertionViolation").value(failure.isAssertionViolation()); - writer.name("assumptionViolation").value(failure.isAssumptionViolation()); - - writer.endObject(); - } - - @Override - public void deserialize(JsonReader reader) throws IOException { - reader.beginObject(); - - expectProperty(reader, "description"); - Description description = JsonHelpers.readDescription(reader); - String message = readStringOrNullProperty(reader, "message"); - String trace = readStringOrNullProperty(reader, "trace"); - String throwableString = readStringOrNullProperty(reader, "throwableString"); - String throwableClass = readStringOrNullProperty(reader, "throwableClass"); - boolean assertionViolation = readBoolean(reader, "assertionViolation"); - boolean assumptionViolation = readBoolean(reader, "assumptionViolation"); - - this.failure = new FailureMirror(description, - message, - trace, - throwableString, - throwableClass, - assertionViolation, - assumptionViolation); - reader.endObject(); - } -} diff --git a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/IDescribable.java b/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/IDescribable.java deleted file mode 100644 index 91c11893..00000000 --- a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/IDescribable.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.events; - -import org.junit.runner.Description; - -/** - * An event that carries a {@link Description}. - */ -public interface IDescribable { - /* - * TODO: [GH-211] we should just pass over the essential information about - * a test, without exposing Class, Description or Annotation instances (which - * are problematic to serialize, initialize, etc.) - */ - Description getDescription(); -} diff --git a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/IEvent.java b/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/IEvent.java deleted file mode 100644 index 0119d289..00000000 --- a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/IEvent.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.events; - -/** - * An event/ message passed between the forked JVM and the master. - */ -public interface IEvent { - EventType getType(); -} diff --git a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/IStreamEvent.java b/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/IStreamEvent.java deleted file mode 100644 index 3a5720d2..00000000 --- a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/IStreamEvent.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.events; - -import java.io.IOException; -import java.io.OutputStream; - -public interface IStreamEvent { - public void copyTo(OutputStream os) throws IOException; -} diff --git a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/IdleEvent.java b/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/IdleEvent.java deleted file mode 100644 index a89dd422..00000000 --- a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/IdleEvent.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.events; - -import java.io.IOException; - -import com.carrotsearch.ant.tasks.junit4.gson.stream.JsonReader; -import com.carrotsearch.ant.tasks.junit4.gson.stream.JsonWriter; - -/** - * Marker that the slave is idle and awaiting more suite names. - */ -public class IdleEvent extends AbstractEvent { - public IdleEvent() { - super(EventType.IDLE); - } - - @Override - public void serialize(JsonWriter writer) throws IOException { - writer.beginObject(); - writer.endObject(); - } - - @Override - public void deserialize(JsonReader reader) throws IOException { - reader.beginObject(); - reader.endObject(); - } -} diff --git a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/JsonHelpers.java b/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/JsonHelpers.java deleted file mode 100644 index c029b853..00000000 --- a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/JsonHelpers.java +++ /dev/null @@ -1,86 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.events; - -import java.io.IOException; -import java.lang.annotation.Annotation; -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; - -import org.junit.runner.Description; - -import com.carrotsearch.ant.tasks.junit4.gson.stream.JsonReader; -import com.carrotsearch.ant.tasks.junit4.gson.stream.JsonToken; -import com.carrotsearch.ant.tasks.junit4.gson.stream.JsonWriter; -import com.google.common.base.Objects; - -public final class JsonHelpers { - public static void writeDescription(JsonWriter writer, Description e) throws IOException { - String key = createId(e); - if (writer.inContext(key)) { - writer.value(key); - } else { - writer.registerInContext(key, e); - writer.beginObject(); - writer.name("id").value(key); - writer.name("displayName").value(e.getDisplayName()); - writer.name("methodName").value(e.getMethodName()); - writer.name("className").value(e.getClassName()); - - writer.name("children").beginArray(); - for (Description child : e.getChildren()) { - writeDescription(writer, child); - } - writer.endArray(); - writer.endObject(); - } - } - - protected static Description readDescription(JsonReader reader) throws IOException { - final Description description; - if (reader.peek() == JsonToken.STRING) { - String key = reader.nextString(); - description = (Description) reader.lookupInContext(key); - if (description == null) { - throw new IOException("Missing reference to: " + key); - } - } else { - reader.beginObject(); - String key = AbstractEvent.readStringOrNullProperty(reader, "id"); - String displayName = AbstractEvent.readStringOrNullProperty(reader, "displayName"); - String methodName = AbstractEvent.readStringOrNullProperty(reader, "methodName"); - String className = AbstractEvent.readStringOrNullProperty(reader, "className"); - - List children = new ArrayList<>(); - AbstractEvent.expectProperty(reader, "children").beginArray(); - while (reader.peek() != JsonToken.END_ARRAY) { - children.add(readDescription(reader)); - } - reader.endArray(); - - description = Description.createSuiteDescription(displayName, new Annotation [] {}); - - for (Description child : children) { - description.addChild(child); - } - - if (!Objects.equal(description.getMethodName(), methodName)) { - throw new IOException(String.format(Locale.ROOT, - "Insane, methodName does not match: %s, %s", description.getMethodName(), methodName)); - } - - if (!Objects.equal(description.getClassName(), className)) { - throw new IOException(String.format(Locale.ROOT, - "Insane, className does not match: %s, %s", description.getClassName(), className)); - } - - reader.registerInContext(key, description); - reader.endObject(); - } - - return description; - } - - private static String createId(Description description) { - return "ID#" + description.getDisplayName(); - } -} diff --git a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/LowLevelHeartBeatEvent.java b/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/LowLevelHeartBeatEvent.java deleted file mode 100644 index 232e5efb..00000000 --- a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/LowLevelHeartBeatEvent.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.events; - -/** - * Heartbeat for reporting long running tests. - */ -public class LowLevelHeartBeatEvent { - public final long lastActivity, currentTime; - - public LowLevelHeartBeatEvent(long last, long currentTime) { - this.lastActivity = last; - this.currentTime = currentTime; - } -} diff --git a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/QuitEvent.java b/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/QuitEvent.java deleted file mode 100644 index 6e9f58df..00000000 --- a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/QuitEvent.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.events; - -import java.io.IOException; - -import com.carrotsearch.ant.tasks.junit4.gson.stream.JsonReader; -import com.carrotsearch.ant.tasks.junit4.gson.stream.JsonWriter; - -/** - * Final message sent from the slave. Also signals orderly shutdown. - */ -public class QuitEvent extends AbstractEvent { - public QuitEvent() { - super(EventType.QUIT); - } - - @Override - public void serialize(JsonWriter writer) throws IOException { - writer.beginObject(); - writer.endObject(); - } - - @Override - public void deserialize(JsonReader reader) throws IOException { - reader.beginObject(); - reader.endObject(); - } -} diff --git a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/RemoteEvent.java b/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/RemoteEvent.java deleted file mode 100644 index 2bc49bd8..00000000 --- a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/RemoteEvent.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.events; - -import java.io.IOException; - -import com.carrotsearch.ant.tasks.junit4.gson.stream.JsonReader; -import com.carrotsearch.ant.tasks.junit4.gson.stream.JsonWriter; - -public interface RemoteEvent extends IEvent { - void serialize(JsonWriter writer) throws IOException; - void deserialize(JsonReader reader) throws IOException; -} diff --git a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/Serializer.java b/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/Serializer.java deleted file mode 100644 index 506fe40a..00000000 --- a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/Serializer.java +++ /dev/null @@ -1,190 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.events; - -import java.io.Closeable; -import java.io.IOException; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.io.Writer; -import java.security.AccessController; -import java.security.PrivilegedExceptionAction; -import java.util.ArrayDeque; -import java.util.concurrent.atomic.AtomicBoolean; - -import com.carrotsearch.ant.tasks.junit4.gson.stream.JsonWriter; -import com.carrotsearch.ant.tasks.junit4.slave.SlaveMain; -import com.google.common.base.Charsets; - -/** - * Event serializer. - */ -public class Serializer implements Closeable { - /** - * Should help in ensuring the right order of stream writes. - */ - private final Object lock = new Object(); - - private Writer writer; - private JsonWriter jsonWriter; - - private final ArrayDeque events = new ArrayDeque(); - - private volatile Throwable doForcedShutdown; - private Thread forceCloseDaemon; - private AtomicBoolean forceCloseDaemonQuit = new AtomicBoolean(); - - public Serializer(OutputStream os) throws IOException { - this.writer = new OutputStreamWriter(os, Charsets.UTF_8); - this.jsonWriter = new JsonWriter(writer); - this.jsonWriter.setIndent(" "); - this.jsonWriter.setLenient(true); - this.forceCloseDaemon = new Thread("JUnit4-serializer-daemon") { - { - this.setDaemon(true); - } - - @Override - public void run() { - try { - while (!forceCloseDaemonQuit.get()) { - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - // Ignore. - } - - Throwable reason = doForcedShutdown; - if (reason != null) { - try { - SlaveMain.warn("Unhandled exception in event serialization.", reason); - } finally { - Runtime.getRuntime().halt(0); - } - } - } - } catch (Throwable t) { - SlaveMain.warn("Unreachable code. Complete panic.", t); - } - } - - @Override - public UncaughtExceptionHandler getUncaughtExceptionHandler() { - return new UncaughtExceptionHandler() { - @Override - public void uncaughtException(Thread t, Throwable e) { - SlaveMain.warn("Unreachable code. Complete panic.", e); - } - }; - } - }; - - forceCloseDaemon.start(); - } - - public Serializer serialize(RemoteEvent event) throws IOException { - synchronized (lock) { - if (writer == null) { - throw new IOException("Serializer already closed."); - } - - // An alternative way of solving GH-92 and GH-110. Instead of buffering - // serialized json we emit directly. If a recursive call occurs to serialize() - // we enqueue the event and continue, serializing them in order. - events.addLast(event); - if (events.size() > 1) { - // SlaveMain.warn("Serializing " + event.getType() + " (postponed, " + events.size() + " in queue)", null); - return this; - } - - flushQueue(); - - return this; - } - } - - private final AtomicBoolean isFlushing = new AtomicBoolean(); - private void flushQueue() throws IOException { - if (!Thread.holdsLock(lock)) throw new IllegalStateException("Must be holding a lock on flushing."); - - if (isFlushing.getAndSet(true)) { - // We're already flushing, return. - // SlaveMain.warn("Flush queue already flushing", null); - return; - } - - // SlaveMain.warn("Flush queue start", null); - try { - while (!events.isEmpty()) { - if (writer == null) { - throw new IOException("Serializer already closed, with " + events.size() + " events on queue."); - } - - final RemoteEvent event = events.removeFirst(); - try { - // SlaveMain.warn("Serializing " + event.getType(), null); - AccessController.doPrivileged(new PrivilegedExceptionAction() { - @Override - public Void run() throws Exception { - jsonWriter.beginArray(); - jsonWriter.value(event.getType().name()); - event.serialize(jsonWriter); - jsonWriter.endArray(); - writer.write("\n\n"); - return null; - } - }); - } catch (Throwable t) { - doForcedShutdown = t; - break; - } - } - } finally { - isFlushing.set(false); - } - // SlaveMain.warn("Flush queue end", null); - - if (doForcedShutdown != null) { - // We can't do a stack bang here so any call is a risk of hitting SOE again. - while (true) { - try { - forceCloseDaemon.join(); - } catch (Throwable ignored) { - // Ignore. - } - } - } - } - - public Serializer flush() throws IOException { - synchronized (lock) { - if (writer != null) { - // SlaveMain.warn("flushing...", null); - flushQueue(); - writer.flush(); - } else { - // SlaveMain.warn("flushing failed (serializer closed)", null); - } - return this; - } - } - - public void close() throws IOException { - synchronized (lock) { - // SlaveMain.warn("closing...", null); - if (writer != null) { - serialize(new QuitEvent()); - flushQueue(); - - writer.close(); - writer = null; - } - forceCloseDaemonQuit.set(true); - } - - try { - forceCloseDaemon.interrupt(); - forceCloseDaemon.join(); - } catch (InterruptedException e) { - // Ignore, can't do much about it (shouldn't happen). - } - } -} \ No newline at end of file diff --git a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/SuiteCompletedEvent.java b/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/SuiteCompletedEvent.java deleted file mode 100644 index 0162e00e..00000000 --- a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/SuiteCompletedEvent.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.events; - -import java.io.IOException; - -import org.junit.runner.Description; - -import com.carrotsearch.ant.tasks.junit4.gson.stream.JsonReader; -import com.carrotsearch.ant.tasks.junit4.gson.stream.JsonWriter; - - -/** - * Serialized failure. - */ -public class SuiteCompletedEvent extends AbstractEventWithDescription { - private long startTimestamp; - private long executionTime; - - protected SuiteCompletedEvent() { - super(EventType.SUITE_COMPLETED); - } - - public SuiteCompletedEvent(Description description, long start, long duration) { - this(); - this.startTimestamp = start; - this.executionTime = duration; - setDescription(description); - } - - public long getExecutionTime() { - return executionTime; - } - - public long getStartTimestamp() { - return startTimestamp; - } - - @Override - public void serialize(JsonWriter writer) throws IOException { - writer.beginObject(); - - writer.name("description"); - super.serialize(writer); - - writer.name("startTimestamp").value(startTimestamp); - writer.name("executionTime").value(executionTime); - - writer.endObject(); - } - - @Override - public void deserialize(JsonReader reader) throws IOException { - reader.beginObject(); - - expectProperty(reader, "description"); - super.deserialize(reader); - - startTimestamp = readLongProperty(reader, "startTimestamp"); - executionTime = readLongProperty(reader, "executionTime"); - - reader.endObject(); - } -} diff --git a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/SuiteFailureEvent.java b/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/SuiteFailureEvent.java deleted file mode 100644 index ee9c1bf5..00000000 --- a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/SuiteFailureEvent.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.events; - -import org.junit.runner.notification.Failure; - -/** - * Serialized failure. - */ -public class SuiteFailureEvent extends FailureEvent { - protected SuiteFailureEvent() { - super(EventType.SUITE_FAILURE); - } - - public SuiteFailureEvent(Failure failure) { - this(); - setFailure(failure); - } -} diff --git a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/SuiteStartedEvent.java b/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/SuiteStartedEvent.java deleted file mode 100644 index 4399aa7c..00000000 --- a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/SuiteStartedEvent.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.events; - -import java.io.IOException; - -import org.junit.runner.Description; - -import com.carrotsearch.ant.tasks.junit4.gson.stream.JsonReader; -import com.carrotsearch.ant.tasks.junit4.gson.stream.JsonWriter; - - -/** - * Serialized failure. - */ -public class SuiteStartedEvent extends AbstractEventWithDescription { - private long startTimestamp; - - protected SuiteStartedEvent() { - super(EventType.SUITE_STARTED); - } - - public SuiteStartedEvent(Description description, long startTimestamp) { - this(); - setDescription(description); - this.startTimestamp = startTimestamp; - } - - public long getStartTimestamp() { - return startTimestamp; - } - - @Override - public void serialize(JsonWriter writer) throws IOException { - writer.beginObject(); - - writer.name("description"); - super.serialize(writer); - - writer.name("startTimestamp").value(startTimestamp); - - writer.endObject(); - } - - @Override - public void deserialize(JsonReader reader) throws IOException { - reader.beginObject(); - - expectProperty(reader, "description"); - super.deserialize(reader); - - startTimestamp = readLongProperty(reader, "startTimestamp"); - - reader.endObject(); - } -} \ No newline at end of file diff --git a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/TestFailureEvent.java b/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/TestFailureEvent.java deleted file mode 100644 index a5c63fbf..00000000 --- a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/TestFailureEvent.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.events; - -import org.junit.runner.notification.Failure; - -public class TestFailureEvent extends FailureEvent { - protected TestFailureEvent() { - super(EventType.TEST_FAILURE); - } - - public TestFailureEvent(Failure failure) { - this(); - setFailure(failure); - } -} diff --git a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/TestFinishedEvent.java b/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/TestFinishedEvent.java deleted file mode 100644 index b4f1c7c3..00000000 --- a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/TestFinishedEvent.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.events; - -import java.io.IOException; - -import org.junit.runner.Description; - -import com.carrotsearch.ant.tasks.junit4.gson.stream.JsonReader; -import com.carrotsearch.ant.tasks.junit4.gson.stream.JsonWriter; - - -public class TestFinishedEvent extends AbstractEventWithDescription { - private long executionTime; - private long startTimestamp; - - protected TestFinishedEvent() { - super(EventType.TEST_FINISHED); - } - - public TestFinishedEvent(Description description, long timeMillis, long startTimestamp) { - this(); - this.executionTime = timeMillis; - this.startTimestamp = startTimestamp; - setDescription(description); - } - - public long getExecutionTime() { - return executionTime; - } - - public long getStartTimestamp() { - return startTimestamp; - } - - @Override - public void serialize(JsonWriter writer) throws IOException { - writer.beginObject(); - - writer.name("description"); - super.serialize(writer); - - writer.name("startTimestamp").value(startTimestamp); - writer.name("executionTime").value(executionTime); - - writer.endObject(); - } - - @Override - public void deserialize(JsonReader reader) throws IOException { - reader.beginObject(); - - expectProperty(reader, "description"); - super.deserialize(reader); - - startTimestamp = readLongProperty(reader, "startTimestamp"); - executionTime = readLongProperty(reader, "executionTime"); - - reader.endObject(); - } -} diff --git a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/TestIgnoredAssumptionEvent.java b/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/TestIgnoredAssumptionEvent.java deleted file mode 100644 index b1b27bf7..00000000 --- a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/TestIgnoredAssumptionEvent.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.events; - -import org.junit.runner.notification.Failure; - -public class TestIgnoredAssumptionEvent extends FailureEvent { - protected TestIgnoredAssumptionEvent() { - super(EventType.TEST_IGNORED_ASSUMPTION); - } - - public TestIgnoredAssumptionEvent(Failure failure) { - this(); - setFailure(failure); - } -} diff --git a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/TestIgnoredEvent.java b/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/TestIgnoredEvent.java deleted file mode 100644 index b0fd89be..00000000 --- a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/TestIgnoredEvent.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.events; - -import java.io.IOException; - -import org.junit.runner.Description; - -import com.carrotsearch.ant.tasks.junit4.gson.stream.JsonReader; -import com.carrotsearch.ant.tasks.junit4.gson.stream.JsonWriter; - -public class TestIgnoredEvent extends AbstractEventWithDescription { - private long startTimestamp; - private String cause; - - protected TestIgnoredEvent() { - super(EventType.TEST_IGNORED); - } - - public TestIgnoredEvent(Description description, String cause) { - this(); - setDescription(description); - - // For ignored tests, take the current time as the execution timestamp. - this.startTimestamp = System.currentTimeMillis(); - this.cause = cause; - } - - public long getStartTimestamp() { - return startTimestamp; - } - - public String getCause() { - return cause; - } - - @Override - public void serialize(JsonWriter writer) throws IOException { - writer.beginObject(); - - writer.name("description"); - super.serialize(writer); - - writer.name("startTimestamp").value(startTimestamp); - writer.name("cause").value(cause); - - writer.endObject(); - } - - @Override - public void deserialize(JsonReader reader) throws IOException { - reader.beginObject(); - - expectProperty(reader, "description"); - super.deserialize(reader); - - startTimestamp = readLongProperty(reader, "startTimestamp"); - cause = readStringOrNullProperty(reader, "cause"); - - reader.endObject(); - } -} diff --git a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/TestStartedEvent.java b/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/TestStartedEvent.java deleted file mode 100644 index fd749e84..00000000 --- a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/TestStartedEvent.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.events; - -import org.junit.runner.Description; - -public class TestStartedEvent extends AbstractEventWithDescription { - protected TestStartedEvent() { - super(EventType.TEST_STARTED); - } - - public TestStartedEvent(Description description) { - this(); - setDescription(description); - } -} diff --git a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/aggregated/AggregatedQuitEvent.java b/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/aggregated/AggregatedQuitEvent.java deleted file mode 100644 index 7060becf..00000000 --- a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/aggregated/AggregatedQuitEvent.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.events.aggregated; - - -/** - * An event dispatched after all slaves have completed their jobs. - */ -public class AggregatedQuitEvent { -} diff --git a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/aggregated/AggregatedResultEvent.java b/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/aggregated/AggregatedResultEvent.java deleted file mode 100644 index b0524458..00000000 --- a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/aggregated/AggregatedResultEvent.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.events.aggregated; - -import java.util.List; - -import org.junit.runner.Description; - -import com.carrotsearch.ant.tasks.junit4.ForkedJvmInfo; -import com.carrotsearch.ant.tasks.junit4.events.IEvent; -import com.carrotsearch.ant.tasks.junit4.events.mirrors.FailureMirror; - -/** - * Aggregated result from a suite or test. - */ -public interface AggregatedResultEvent { - public Description getDescription(); - public ForkedJvmInfo getSlave(); - public boolean isSuccessful(); - public List getFailures(); - List getEventStream(); - - public long getStartTimestamp(); - public long getExecutionTime(); -} diff --git a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/aggregated/AggregatedStartEvent.java b/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/aggregated/AggregatedStartEvent.java deleted file mode 100644 index 7bcce329..00000000 --- a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/aggregated/AggregatedStartEvent.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.events.aggregated; - - -/** - * An event dispatched before any slave starts. - */ -public class AggregatedStartEvent { - private int slaves; - private int suiteCount; - - public AggregatedStartEvent(int slaves, int suiteCount) { - this.slaves = slaves; - this.suiteCount = suiteCount; - } - - /** - * Number of slave processes. - */ - public int getSlaveCount() { - return slaves; - } - - /** - * Number of test suites, total. - */ - public int getSuiteCount() { - return suiteCount; - } -} diff --git a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/aggregated/AggregatedSuiteResultEvent.java b/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/aggregated/AggregatedSuiteResultEvent.java deleted file mode 100644 index 74c1ed16..00000000 --- a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/aggregated/AggregatedSuiteResultEvent.java +++ /dev/null @@ -1,310 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.events.aggregated; - -import static com.carrotsearch.ant.tasks.junit4.events.EventType.*; - -import java.io.IOException; -import java.io.StringWriter; -import java.nio.charset.Charset; -import java.text.SimpleDateFormat; -import java.util.Collections; -import java.util.Date; -import java.util.List; -import java.util.Locale; - -import org.junit.runner.Description; - -import com.carrotsearch.ant.tasks.junit4.ForkedJvmInfo; -import com.carrotsearch.ant.tasks.junit4.events.EventType; -import com.carrotsearch.ant.tasks.junit4.events.FailureEvent; -import com.carrotsearch.ant.tasks.junit4.events.IDescribable; -import com.carrotsearch.ant.tasks.junit4.events.IEvent; -import com.carrotsearch.ant.tasks.junit4.events.IStreamEvent; -import com.carrotsearch.ant.tasks.junit4.events.JsonHelpers; -import com.carrotsearch.ant.tasks.junit4.events.mirrors.FailureMirror; -import com.carrotsearch.ant.tasks.junit4.gson.stream.JsonWriter; -import com.carrotsearch.randomizedtesting.WriterOutputStream; - -public class AggregatedSuiteResultEvent implements AggregatedResultEvent { - private transient final ForkedJvmInfo slave; - - private final long executionTime; - private final long startTimestamp; - private final Description description; - - private final List tests; - private final List suiteFailures; - private final List eventStream; - - private final AggregatedSuiteStartedEvent startEvent; - - public AggregatedSuiteResultEvent( - AggregatedSuiteStartedEvent startEvent, - ForkedJvmInfo id, - Description description, - List suiteFailures, - List tests, - List eventStream, - long startTimestamp, - long executionTime) { - this.startEvent = startEvent; - this.slave = id; - this.tests = tests; - this.suiteFailures = suiteFailures; - this.description = description; - this.eventStream = eventStream; - this.executionTime = executionTime; - this.startTimestamp = startTimestamp; - } - - public AggregatedSuiteStartedEvent getStartEvent() { - return startEvent; - } - - public List getTests() { - return tests; - } - - @Override - public List getFailures() { - return Collections.unmodifiableList(suiteFailures); - } - - @Override - public boolean isSuccessful() { - if (!suiteFailures.isEmpty()) - return false; - - for (AggregatedTestResultEvent e : tests) { - if (!e.isSuccessful()) { - return false; - } - } - - return true; - } - - @Override - public List getEventStream() { - return eventStream; - } - - @Override - public ForkedJvmInfo getSlave() { - return slave; - } - - @Override - public Description getDescription() { - return description; - } - - /** - * Execution time in milliseconds. - */ - public long getExecutionTime() { - return executionTime; - } - - /** - * Execution start timestamp (on the slave). - */ - public long getStartTimestamp() { - return startTimestamp; - } - - /** - * The number of tests that have {@link TestStatus#FAILURE} and - * include assertion violations at suite level. - */ - public int getFailureCount() { - int count = 0; - for (AggregatedTestResultEvent t : getTests()) { - if (t.getStatus() == TestStatus.FAILURE) - count++; - } - for (FailureMirror m : getFailures()) { - if (m.isAssertionViolation()) - count++; - } - return count; - } - - /** - * The number of tests that have {@link TestStatus#ERROR} and - * include the suite-level errors. - */ - public int getErrorCount() { - int count = 0; - for (AggregatedTestResultEvent t : getTests()) { - if (t.getStatus() == TestStatus.ERROR) - count++; - } - - for (FailureMirror m : getFailures()) { - if (m.isErrorViolation()) - count++; - } - return count; - } - - /** - * Return the number of ignored or assumption-ignored tests. - */ - public int getIgnoredCount() { - int count = 0; - for (AggregatedTestResultEvent t : getTests()) { - if (t.getStatus() == TestStatus.IGNORED || - t.getStatus() == TestStatus.IGNORED_ASSUMPTION) { - count++; - } - } - return count; - } - - public void serialize(JsonWriter w, boolean outputStreams) throws IOException { - w.beginObject(); - - w.name("slave").value(getSlave().id); - w.name("startTimestamp").value(getStartTimestamp()); - - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.ROOT); - w.name("startTimestampDate").value(sdf.format(new Date(getStartTimestamp()))); - - w.name("executionTime").value(getExecutionTime()); - w.name("description"); - JsonHelpers.writeDescription(w, getDescription()); - - w.name("tests"); - w.beginArray(); - for (AggregatedTestResultEvent e : getTests()) { - serialize(w, sdf, e); - } - w.endArray(); - - w.name("suiteFailures"); - w.beginArray(); - for (FailureMirror m : getFailures()) { - serialize(w, m); - } - w.endArray(); - - w.name("executionEvents"); - w.beginArray(); - serializeEvents(w, outputStreams); - w.endArray(); - - w.endObject(); - } - - private void serialize(JsonWriter w, SimpleDateFormat sdf, AggregatedTestResultEvent e) throws IOException { - w.beginObject(); - w.name("slave").value(e.getSlave().id); - w.name("startTimestamp").value(e.getStartTimestamp()); - w.name("startTimestampDate").value(sdf.format(new Date(e.getStartTimestamp()))); - w.name("executionTime").value(e.getExecutionTime()); - w.name("description"); - JsonHelpers.writeDescription(w, e.getDescription()); - w.name("status").value(e.getStatus().name()); - - w.name("testFailures"); - w.beginArray(); - for (FailureMirror m : e.getFailures()) { - serialize(w, m); - } - w.endArray(); - - w.endObject(); - } - - private void serialize(JsonWriter w, FailureMirror e) throws IOException { - w.beginObject(); - w.name("throwableClass").value(e.getThrowableClass()); - w.name("throwableString").value(e.getThrowableString()); - w.name("stackTrace").value(e.getTrace()); - - String throwableKind; - if (e.isAssertionViolation()) { - throwableKind = "assertion"; - } else if (e.isErrorViolation()) { - throwableKind = "error"; - } else if (e.isAssumptionViolation()) { - throwableKind = "assumption"; - } else { - throwableKind = "unknown"; - } - w.name("kind").value(throwableKind); - w.endObject(); - } - - private void serializeEvents(JsonWriter w, boolean outputStreams) throws IOException { - final Charset charset = getSlave().getCharset(); - int lineBuffer = 160; - final StringWriter out = new StringWriter(); - final StringWriter err = new StringWriter(); - WriterOutputStream stdout = new WriterOutputStream(out, charset, lineBuffer, false); - WriterOutputStream stderr = new WriterOutputStream(err, charset, lineBuffer, false); - for (IEvent evt : getEventStream()) { - try { - switch (evt.getType()) { - case SUITE_FAILURE: - case TEST_IGNORED_ASSUMPTION: - case TEST_IGNORED: - case TEST_STARTED: - case TEST_FINISHED: - case TEST_FAILURE: - flushBoth(w, out, err, stdout, stderr); - - w.beginObject(); - w.name("event").value(evt.getType().toString()); - w.name("description"); - JsonHelpers.writeDescription(w, ((IDescribable) evt).getDescription()); - - if (evt instanceof FailureEvent) { - w.name("failure"); - ((FailureEvent) evt).serialize(w); - } - w.endObject(); - break; - - // Flush streams only if there's interwoven output between them. - - case APPEND_STDOUT: - if (outputStreams) { - flush(APPEND_STDERR, w, stderr, err); - ((IStreamEvent) evt).copyTo(stdout); - } - break; - - case APPEND_STDERR: - if (outputStreams) { - flush(APPEND_STDOUT, w, stdout, out); - ((IStreamEvent) evt).copyTo(stderr); - } - break; - - default: - break; - } - } catch (IOException ex) { - // Ignore. - } - } - flushBoth(w, out, err, stdout, stderr); - } - - public void flushBoth(JsonWriter w, StringWriter out, StringWriter err, WriterOutputStream stdout, WriterOutputStream stderr) throws IOException { - flush(APPEND_STDOUT, w, stdout, out); - flush(APPEND_STDERR, w, stderr, err); - } - - private void flush(EventType evt, JsonWriter w, WriterOutputStream wos, StringWriter out) throws IOException { - wos.flush(); - if (out.getBuffer().length() > 0) { - w.beginObject(); - w.name("event").value(evt.toString()); - w.name("content").value(out.getBuffer().toString()); - out.getBuffer().setLength(0); - w.endObject(); - } - } -} diff --git a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/aggregated/AggregatedSuiteStartedEvent.java b/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/aggregated/AggregatedSuiteStartedEvent.java deleted file mode 100644 index e58e930d..00000000 --- a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/aggregated/AggregatedSuiteStartedEvent.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.events.aggregated; - -import com.carrotsearch.ant.tasks.junit4.ForkedJvmInfo; -import com.carrotsearch.ant.tasks.junit4.events.SuiteStartedEvent; - -public class AggregatedSuiteStartedEvent { - private transient final ForkedJvmInfo slave; - private SuiteStartedEvent suiteStartedEvent; - - public AggregatedSuiteStartedEvent(ForkedJvmInfo id, SuiteStartedEvent e) { - this.slave = id; - this.suiteStartedEvent = e; - } - - public SuiteStartedEvent getSuiteStartedEvent() { - return suiteStartedEvent; - } - - public ForkedJvmInfo getSlave() { - return slave; - } -} diff --git a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/aggregated/AggregatedTestResultEvent.java b/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/aggregated/AggregatedTestResultEvent.java deleted file mode 100644 index 5025e8a4..00000000 --- a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/aggregated/AggregatedTestResultEvent.java +++ /dev/null @@ -1,138 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.events.aggregated; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import org.junit.runner.Description; - -import com.carrotsearch.ant.tasks.junit4.ForkedJvmInfo; -import com.carrotsearch.ant.tasks.junit4.events.IEvent; -import com.carrotsearch.ant.tasks.junit4.events.TestFinishedEvent; -import com.carrotsearch.ant.tasks.junit4.events.mirrors.FailureMirror; - -/** - * A single test's execution information. - */ -public class AggregatedTestResultEvent implements AggregatedResultEvent { - private final Description suite; - private final Description description; - private final ForkedJvmInfo slave; - - private TestStatus status = TestStatus.OK; - private List failures = new ArrayList<>(); - - private List eventStream; - - private boolean hasFailures; - private boolean hasErrors; - private boolean hasIgnoredAssumptions; - - /** If {@link #status} is {@link TestStatus#IGNORED} then this contains the cause. */ - private String ignoreCause; - - /** Associated {@link TestFinishedEvent}. */ - private TestFinishedEvent testFinishedEvent; - - public AggregatedTestResultEvent(ForkedJvmInfo slave, Description suiteDescription, Description description) { - this.description = description; - this.suite = suiteDescription; - this.slave = slave; - } - - @Override - public Description getDescription() { - return description; - } - - @Override - public boolean isSuccessful() { - return status == TestStatus.OK || - status == TestStatus.IGNORED || - status == TestStatus.IGNORED_ASSUMPTION; - } - - public Description getSuiteDescription() { - return suite; - } - - @Override - public ForkedJvmInfo getSlave() { - return slave; - } - - @Override - public List getFailures() { - return Collections.unmodifiableList(failures); - } - - /** - * Execution time in millis. - */ - public long getExecutionTime() { - return testFinishedEvent.getExecutionTime(); - } - - /** - * Execution start timestamp (on the slave). - */ - public long getStartTimestamp() { - return testFinishedEvent.getStartTimestamp(); - } - - /** - * Raw {@link IEvent} stream received during the duration of this test. - */ - @Override - public List getEventStream() { - if (eventStream == null) - throw new RuntimeException("Unfinished test?" + suite + ", " + description); - return Collections.unmodifiableList(eventStream); - } - - /** - * Exit status for this test. - */ - public TestStatus getStatus() { - return status; - } - - public String getCauseForIgnored() { - return ignoreCause; - } - - void setIgnored(String cause) { - assert status == TestStatus.OK; - status = TestStatus.IGNORED; - ignoreCause = cause; - } - - void addFailure(FailureMirror failure) { - failures.add(failure); - - hasFailures |= failure.isAssertionViolation(); - hasIgnoredAssumptions |= failure.isAssumptionViolation(); - hasErrors |= failure.isErrorViolation(); - } - - void complete(TestFinishedEvent e, List eventStream) { - this.eventStream = eventStream; - this.testFinishedEvent = e; - - if (hasErrors) { - status = TestStatus.ERROR; - } else if (hasFailures) { - status = TestStatus.FAILURE; - } else if (hasIgnoredAssumptions) { - status = TestStatus.IGNORED_ASSUMPTION; - } - } - - /** - * This isn't a nice hack but it allows associating {@link TestFinishedEvent} and - * {@link AggregatedTestResultEvent} by identity. = - */ - public TestFinishedEvent getTestFinishedEvent() { - return testFinishedEvent; - } -} diff --git a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/aggregated/AggregatingListener.java b/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/aggregated/AggregatingListener.java deleted file mode 100644 index cb4e1ba8..00000000 --- a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/aggregated/AggregatingListener.java +++ /dev/null @@ -1,184 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.events.aggregated; - -import java.util.ArrayDeque; -import java.util.ArrayList; -import java.util.List; - -import org.junit.runner.Description; -import org.junit.runner.JUnitCore; - -import com.carrotsearch.ant.tasks.junit4.ForkedJvmInfo; -import com.carrotsearch.ant.tasks.junit4.events.*; -import com.carrotsearch.ant.tasks.junit4.events.mirrors.FailureMirror; -import com.google.common.collect.Lists; -import com.google.common.eventbus.EventBus; -import com.google.common.eventbus.Subscribe; - -/** - * Aggregates atomic events from {@link JUnitCore} to higher-level events that - * contain a full summary of a given test's execution. Simplifies reporting - * logic. - */ -public class AggregatingListener { - private EventBus target; - private ForkedJvmInfo slave; - - private AggregatedSuiteStartedEvent startEvent; - private Description lastSuite; - private List suiteFailures; - - private ArrayDeque tests; - private ArrayList eventStream; - private int testStartStreamMarker; - - /** - * @param target Which event bus to repost aggregated events to? - */ - public AggregatingListener(EventBus target, ForkedJvmInfo slave) { - this.target = target; - this.slave = slave; - } - - @Subscribe - public void appendToEventStream(IEvent e) { - if (eventStream != null) { - switch (e.getType()) { - case APPEND_STDOUT: - case APPEND_STDERR: - target.post(new PartialOutputEvent(slave, e)); - // fall through. - case TEST_STARTED: - case TEST_FINISHED: - case TEST_FAILURE: - case TEST_IGNORED: - case TEST_IGNORED_ASSUMPTION: - case SUITE_FAILURE: - eventStream.add(e); - break; - default: - break; - } - } - } - - /** - * Detect slow heartbeat (long time without any events) from the forked JVM. - */ - @Subscribe - public void slowHeartBeat(LowLevelHeartBeatEvent e) { - Description current = null; - if (tests != null && !tests.isEmpty()) { - current = tests.peek().getDescription(); - } else { - current = lastSuite; // may be null. - } - - target.post(new HeartBeatEvent( - slave, - current, - e.lastActivity, - e.currentTime - )); - } - - @Subscribe - public void receiveSuiteStart(SuiteStartedEvent e) { - assert lastSuite == null; - assert startEvent == null; - - tests = new ArrayDeque(); - suiteFailures = new ArrayList<>(); - eventStream = new ArrayList<>(); - lastSuite = e.getDescription(); - startEvent = new AggregatedSuiteStartedEvent(slave, e); - - target.post(startEvent); - } - - @Subscribe - public void receiveTestStart(TestStartedEvent e) { - tests.push(new AggregatedTestResultEvent(slave, lastSuite, e.getDescription())); - testStartStreamMarker = eventStream.size(); - } - - @Subscribe - public void receiveTestIgnored(TestIgnoredEvent e) { - Description description = e.getDescription(); - if (description.getMethodName() == null) { - // This is how JUnit signals ignored suites: by passing a Description that is a - // suite but has no children (so isSuite() returns false...). - return; - } - - // Test ignored is not emitted within start...end space with default JUnit runners. - // Try to correct it here. - if (!tests.isEmpty() && description.equals(tests.peek().getDescription())) { - tests.peek().setIgnored(e.getCause()); - } else { - receiveTestStart(new TestStartedEvent(description)); - tests.peek().setIgnored(e.getCause()); - receiveTestEnd(new TestFinishedEvent(description, 0, e.getStartTimestamp())); - } - } - - @Subscribe - public void receiveTestAssumptionIgnored(TestIgnoredAssumptionEvent e) { - Description description = e.getDescription(); - if (description.getMethodName() == null) { - // Don't record suite-level assumptions. They result in ignored - // tests that RandomizedRunner reports and JUnit runner ignores - // as if a suite didn't have any tests. - return; - } - - assert e.getDescription().equals(tests.peek().getDescription()); - tests.peek().addFailure(e.getFailure()); - } - - @Subscribe - public void receiveTestFailure(TestFailureEvent e) { - Description description = e.getDescription(); - if (description.getMethodName() == null) { - suiteFailures.add(e.getFailure()); - return; - } - - tests.peek().addFailure(e.getFailure()); - } - - @Subscribe - public void receiveTestEnd(TestFinishedEvent e) { - assert e.getDescription().equals(tests.peek().getDescription()); - tests.peek().complete(e, new ArrayList<>(eventStream.subList(testStartStreamMarker, eventStream.size()))); - target.post(tests.peek()); - } - - @Subscribe - public void receiveSuiteEnd(SuiteCompletedEvent e) { - target.post(new AggregatedSuiteResultEvent( - startEvent, - slave, - e.getDescription(), - suiteFailures, - Lists.newArrayList(tests.descendingIterator()), - eventStream, - e.getStartTimestamp(), - e.getExecutionTime())); - this.suiteFailures = null; - this.lastSuite = null; - this.startEvent = null; - this.tests = null; - this.eventStream = null; - } - - @Subscribe - public void receiveSuiteFailure(SuiteFailureEvent e) { - if (suiteFailures != null) { - suiteFailures.add(e.getFailure()); - } else { - receiveSuiteStart(new SuiteStartedEvent(e.getDescription(), System.currentTimeMillis())); - suiteFailures.add(e.getFailure()); - receiveSuiteEnd(new SuiteCompletedEvent(e.getDescription(), System.currentTimeMillis(), 0)); - } - } -} diff --git a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/aggregated/ChildBootstrap.java b/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/aggregated/ChildBootstrap.java deleted file mode 100644 index 1a7a20c6..00000000 --- a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/aggregated/ChildBootstrap.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.events.aggregated; - -import com.carrotsearch.ant.tasks.junit4.ForkedJvmInfo; - -public class ChildBootstrap { - public final ForkedJvmInfo childInfo; - - public ChildBootstrap(ForkedJvmInfo childInfo) { - this.childInfo = childInfo; - } - - public ForkedJvmInfo getSlave() { - return childInfo; - } -} diff --git a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/aggregated/HeartBeatEvent.java b/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/aggregated/HeartBeatEvent.java deleted file mode 100644 index d37c3c46..00000000 --- a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/aggregated/HeartBeatEvent.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.events.aggregated; - -import org.junit.runner.Description; - -import com.carrotsearch.ant.tasks.junit4.ForkedJvmInfo; - -/** - * High level heartbeat event issued to report listeners when a forked JVM - * does not repond for a longer while. The {@link #getDescription} method should - * return an approximate place where the forked JVM is at the moment, but this is - * not guaranteed (and may be null). - */ -public final class HeartBeatEvent { - private final ForkedJvmInfo slave; - private final Description description; - private final long lastActivity; - private final long currentTime; - - public HeartBeatEvent(ForkedJvmInfo slave, Description description, long lastActivity, long currentTime) { - this.slave = slave; - this.description = description; - this.lastActivity = lastActivity; - this.currentTime = currentTime; - } - - public Description getDescription() { - return description; - } - - public long getCurrentTime() { - return currentTime; - } - - public long getLastActivity() { - return lastActivity; - } - - public long getNoEventDuration() { - return getCurrentTime() - getLastActivity(); - } - - public ForkedJvmInfo getSlave() { - return slave; - } -} diff --git a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/aggregated/JvmOutputEvent.java b/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/aggregated/JvmOutputEvent.java deleted file mode 100644 index 6ca98b36..00000000 --- a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/aggregated/JvmOutputEvent.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.events.aggregated; - -import java.io.File; - -import com.carrotsearch.ant.tasks.junit4.ForkedJvmInfo; - -/** - * An event emitted when there was any unexpected JVM output - * from the forked JVM. This can happen for internal JVM logs - * or crash dumps that bypass System.* streams. - */ -public class JvmOutputEvent { - public final ForkedJvmInfo childInfo; - public final File jvmOutput; - - public JvmOutputEvent(ForkedJvmInfo childInfo, File jvmOutput) { - this.childInfo = childInfo; - this.jvmOutput = jvmOutput; - } - - public ForkedJvmInfo getSlave() { - return childInfo; - } - - public File getJvmOutputFile() { - return jvmOutput; - } -} diff --git a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/aggregated/PartialOutputEvent.java b/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/aggregated/PartialOutputEvent.java deleted file mode 100644 index 6b778ca3..00000000 --- a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/aggregated/PartialOutputEvent.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.events.aggregated; - -import com.carrotsearch.ant.tasks.junit4.ForkedJvmInfo; -import com.carrotsearch.ant.tasks.junit4.events.IEvent; -import com.carrotsearch.ant.tasks.junit4.events.IStreamEvent; - -/** - * Partial output emitted from a given slave. - */ -public class PartialOutputEvent { - private ForkedJvmInfo slave; - private IEvent event; - - public PartialOutputEvent(ForkedJvmInfo slave, IEvent e) { - assert e instanceof IStreamEvent; - this.slave = slave; - this.event = e; - } - - public ForkedJvmInfo getSlave() { - return slave; - } - - public IEvent getEvent() { - return event; - } -} diff --git a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/aggregated/TestStatus.java b/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/aggregated/TestStatus.java deleted file mode 100644 index 0cb40156..00000000 --- a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/aggregated/TestStatus.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.events.aggregated; - -public enum TestStatus { - OK, - - IGNORED, - IGNORED_ASSUMPTION, - - FAILURE, - ERROR, -} diff --git a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/mirrors/FailureMirror.java b/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/mirrors/FailureMirror.java deleted file mode 100644 index 0dbd73c3..00000000 --- a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/mirrors/FailureMirror.java +++ /dev/null @@ -1,83 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.events.mirrors; - -import org.junit.internal.AssumptionViolatedException; -import org.junit.runner.Description; -import org.junit.runner.notification.Failure; - -/** - * A type-safe mirror of {@link Failure}. - */ -public class FailureMirror { - private String message; - private String trace; - private String throwableString; - private String throwableClass; - - /** Was [@link Failure} an instance of an {@link AssertionError}? */ - private boolean assertionViolation; - private boolean assumptionViolation; - - /** The test {@link Description} that caused this failure. */ - private Description description; - - public FailureMirror(Description description, - String message, - String trace, - String throwableString, - String throwableClass, - boolean assertionViolation, - boolean assumptionViolation) { - this.message = message; - this.trace = trace; - this.throwableString = throwableString; - this.throwableClass = throwableClass; - this.assertionViolation = assertionViolation; - this.assumptionViolation = assumptionViolation; - this.description = description; - } - - public FailureMirror(Failure failure) { - this.message = failure.getMessage(); - this.description = failure.getDescription(); - this.trace = failure.getTrace(); - - final Throwable cause = failure.getException(); - this.assertionViolation = cause instanceof AssertionError; - this.assumptionViolation = cause instanceof AssumptionViolatedException; - this.throwableString = cause.toString(); - this.throwableClass = cause.getClass().getName(); - } - - public String getMessage() { - return message; - } - - public String getThrowableString() { - return throwableString; - } - - public Description getDescription() { - return description; - } - - public String getTrace() { - return trace; - } - - public boolean isAssumptionViolation() { - return assumptionViolation; - } - - public boolean isAssertionViolation() { - return assertionViolation; - } - - public boolean isErrorViolation() { - return isAssertionViolation() == false && - isAssumptionViolation() == false; - } - - public String getThrowableClass() { - return throwableClass; - } -} diff --git a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/gson/stream/IOContext.java b/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/gson/stream/IOContext.java deleted file mode 100644 index 52a6959d..00000000 --- a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/gson/stream/IOContext.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.gson.stream; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; - -public class IOContext { - private Map context = new HashMap(); - - public void registerInContext(Object key, Object value) throws IOException { - if (inContext(key)) { - throw new IOException("Key already registered: " + key); - } - if (value == null) { - throw new IOException("Value cannot be null for key: " + key); - } - context.put(key, value); - } - - public Object lookupInContext(Object key) { - return context.get(key); - } - - public boolean inContext(Object key) { - return context.containsKey(key); - } -} diff --git a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/gson/stream/JsonReader.java b/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/gson/stream/JsonReader.java deleted file mode 100644 index 5963da18..00000000 --- a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/gson/stream/JsonReader.java +++ /dev/null @@ -1,1597 +0,0 @@ -/* - * Copyright (C) 2010 Google Inc. - * - * 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. - */ - -package com.carrotsearch.ant.tasks.junit4.gson.stream; - -import java.io.Closeable; -import java.io.EOFException; -import java.io.IOException; -import java.io.Reader; - -/** - * Reads a JSON (RFC 4627) - * encoded value as a stream of tokens. This stream includes both literal - * values (strings, numbers, booleans, and nulls) as well as the begin and - * end delimiters of objects and arrays. The tokens are traversed in - * depth-first order, the same order that they appear in the JSON document. - * Within JSON objects, name/value pairs are represented by a single token. - * - *

Parsing JSON

- * To create a recursive descent parser for your own JSON streams, first create - * an entry point method that creates a {@code JsonReader}. - * - *

Next, create handler methods for each structure in your JSON text. You'll - * need a method for each object type and for each array type. - *

    - *
  • Within array handling methods, first call {@link - * #beginArray} to consume the array's opening bracket. Then create a - * while loop that accumulates values, terminating when {@link #hasNext} - * is false. Finally, read the array's closing bracket by calling {@link - * #endArray}. - *
  • Within object handling methods, first call {@link - * #beginObject} to consume the object's opening brace. Then create a - * while loop that assigns values to local variables based on their name. - * This loop should terminate when {@link #hasNext} is false. Finally, - * read the object's closing brace by calling {@link #endObject}. - *
- *

When a nested object or array is encountered, delegate to the - * corresponding handler method. - * - *

When an unknown name is encountered, strict parsers should fail with an - * exception. Lenient parsers should call {@link #skipValue()} to recursively - * skip the value's nested tokens, which may otherwise conflict. - * - *

If a value may be null, you should first check using {@link #peek()}. - * Null literals can be consumed using either {@link #nextNull()} or {@link - * #skipValue()}. - * - *

Example

- * Suppose we'd like to parse a stream of messages such as the following:
{@code
- * [
- *   {
- *     "id": 912345678901,
- *     "text": "How do I read a JSON stream in Java?",
- *     "geo": null,
- *     "user": {
- *       "name": "json_newb",
- *       "followers_count": 41
- *      }
- *   },
- *   {
- *     "id": 912345678902,
- *     "text": "@json_newb just use JsonReader!",
- *     "geo": [50.454722, -104.606667],
- *     "user": {
- *       "name": "jesse",
- *       "followers_count": 2
- *     }
- *   }
- * ]}
- * This code implements the parser for the above structure:
{@code
- *
- *   public List readJsonStream(InputStream in) throws IOException {
- *     JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
- *     try {
- *       return readMessagesArray(reader);
- *     } finally {
- *       reader.close();
- *     }
- *   }
- *
- *   public List readMessagesArray(JsonReader reader) throws IOException {
- *     List messages = new ArrayList();
- *
- *     reader.beginArray();
- *     while (reader.hasNext()) {
- *       messages.add(readMessage(reader));
- *     }
- *     reader.endArray();
- *     return messages;
- *   }
- *
- *   public Message readMessage(JsonReader reader) throws IOException {
- *     long id = -1;
- *     String text = null;
- *     User user = null;
- *     List geo = null;
- *
- *     reader.beginObject();
- *     while (reader.hasNext()) {
- *       String name = reader.nextName();
- *       if (name.equals("id")) {
- *         id = reader.nextLong();
- *       } else if (name.equals("text")) {
- *         text = reader.nextString();
- *       } else if (name.equals("geo") && reader.peek() != JsonToken.NULL) {
- *         geo = readDoublesArray(reader);
- *       } else if (name.equals("user")) {
- *         user = readUser(reader);
- *       } else {
- *         reader.skipValue();
- *       }
- *     }
- *     reader.endObject();
- *     return new Message(id, text, user, geo);
- *   }
- *
- *   public List readDoublesArray(JsonReader reader) throws IOException {
- *     List doubles = new ArrayList();
- *
- *     reader.beginArray();
- *     while (reader.hasNext()) {
- *       doubles.add(reader.nextDouble());
- *     }
- *     reader.endArray();
- *     return doubles;
- *   }
- *
- *   public User readUser(JsonReader reader) throws IOException {
- *     String username = null;
- *     int followersCount = -1;
- *
- *     reader.beginObject();
- *     while (reader.hasNext()) {
- *       String name = reader.nextName();
- *       if (name.equals("name")) {
- *         username = reader.nextString();
- *       } else if (name.equals("followers_count")) {
- *         followersCount = reader.nextInt();
- *       } else {
- *         reader.skipValue();
- *       }
- *     }
- *     reader.endObject();
- *     return new User(username, followersCount);
- *   }}
- * - *

Number Handling

- * This reader permits numeric values to be read as strings and string values to - * be read as numbers. For example, both elements of the JSON array {@code - * [1, "1"]} may be read using either {@link #nextInt} or {@link #nextString}. - * This behavior is intended to prevent lossy numeric conversions: double is - * JavaScript's only numeric type and very large values like {@code - * 9007199254740993} cannot be represented exactly on that platform. To minimize - * precision loss, extremely large values should be written and read as strings - * in JSON. - * - *

Non-Execute Prefix

- * Web servers that serve private data using JSON may be vulnerable to Cross-site - * request forgery attacks. In such an attack, a malicious site gains access - * to a private JSON file by executing it with an HTML {@code - - - - - - diff --git a/junit4-ant/src/main/resources/com/carrotsearch/ant/tasks/junit4/templates/json/js/jquery-1.7.1.min.js b/junit4-ant/src/main/resources/com/carrotsearch/ant/tasks/junit4/templates/json/js/jquery-1.7.1.min.js deleted file mode 100644 index 198b3ff0..00000000 --- a/junit4-ant/src/main/resources/com/carrotsearch/ant/tasks/junit4/templates/json/js/jquery-1.7.1.min.js +++ /dev/null @@ -1,4 +0,0 @@ -/*! jQuery v1.7.1 jquery.com | jquery.org/license */ -(function(a,b){function cy(a){return f.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:!1}function cv(a){if(!ck[a]){var b=c.body,d=f("<"+a+">").appendTo(b),e=d.css("display");d.remove();if(e==="none"||e===""){cl||(cl=c.createElement("iframe"),cl.frameBorder=cl.width=cl.height=0),b.appendChild(cl);if(!cm||!cl.createElement)cm=(cl.contentWindow||cl.contentDocument).document,cm.write((c.compatMode==="CSS1Compat"?"":"")+""),cm.close();d=cm.createElement(a),cm.body.appendChild(d),e=f.css(d,"display"),b.removeChild(cl)}ck[a]=e}return ck[a]}function cu(a,b){var c={};f.each(cq.concat.apply([],cq.slice(0,b)),function(){c[this]=a});return c}function ct(){cr=b}function cs(){setTimeout(ct,0);return cr=f.now()}function cj(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}function ci(){try{return new a.XMLHttpRequest}catch(b){}}function cc(a,c){a.dataFilter&&(c=a.dataFilter(c,a.dataType));var d=a.dataTypes,e={},g,h,i=d.length,j,k=d[0],l,m,n,o,p;for(g=1;g0){if(c!=="border")for(;g=0===c})}function S(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function K(){return!0}function J(){return!1}function n(a,b,c){var d=b+"defer",e=b+"queue",g=b+"mark",h=f._data(a,d);h&&(c==="queue"||!f._data(a,e))&&(c==="mark"||!f._data(a,g))&&setTimeout(function(){!f._data(a,e)&&!f._data(a,g)&&(f.removeData(a,d,!0),h.fire())},0)}function m(a){for(var b in a){if(b==="data"&&f.isEmptyObject(a[b]))continue;if(b!=="toJSON")return!1}return!0}function l(a,c,d){if(d===b&&a.nodeType===1){var e="data-"+c.replace(k,"-$1").toLowerCase();d=a.getAttribute(e);if(typeof d=="string"){try{d=d==="true"?!0:d==="false"?!1:d==="null"?null:f.isNumeric(d)?parseFloat(d):j.test(d)?f.parseJSON(d):d}catch(g){}f.data(a,c,d)}else d=b}return d}function h(a){var b=g[a]={},c,d;a=a.split(/\s+/);for(c=0,d=a.length;c)[^>]*$|#([\w\-]*)$)/,j=/\S/,k=/^\s+/,l=/\s+$/,m=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,n=/^[\],:{}\s]*$/,o=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,p=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,q=/(?:^|:|,)(?:\s*\[)+/g,r=/(webkit)[ \/]([\w.]+)/,s=/(opera)(?:.*version)?[ \/]([\w.]+)/,t=/(msie) ([\w.]+)/,u=/(mozilla)(?:.*? rv:([\w.]+))?/,v=/-([a-z]|[0-9])/ig,w=/^-ms-/,x=function(a,b){return(b+"").toUpperCase()},y=d.userAgent,z,A,B,C=Object.prototype.toString,D=Object.prototype.hasOwnProperty,E=Array.prototype.push,F=Array.prototype.slice,G=String.prototype.trim,H=Array.prototype.indexOf,I={};e.fn=e.prototype={constructor:e,init:function(a,d,f){var g,h,j,k;if(!a)return this;if(a.nodeType){this.context=this[0]=a,this.length=1;return this}if(a==="body"&&!d&&c.body){this.context=c,this[0]=c.body,this.selector=a,this.length=1;return this}if(typeof a=="string"){a.charAt(0)!=="<"||a.charAt(a.length-1)!==">"||a.length<3?g=i.exec(a):g=[null,a,null];if(g&&(g[1]||!d)){if(g[1]){d=d instanceof e?d[0]:d,k=d?d.ownerDocument||d:c,j=m.exec(a),j?e.isPlainObject(d)?(a=[c.createElement(j[1])],e.fn.attr.call(a,d,!0)):a=[k.createElement(j[1])]:(j=e.buildFragment([g[1]],[k]),a=(j.cacheable?e.clone(j.fragment):j.fragment).childNodes);return e.merge(this,a)}h=c.getElementById(g[2]);if(h&&h.parentNode){if(h.id!==g[2])return f.find(a);this.length=1,this[0]=h}this.context=c,this.selector=a;return this}return!d||d.jquery?(d||f).find(a):this.constructor(d).find(a)}if(e.isFunction(a))return f.ready(a);a.selector!==b&&(this.selector=a.selector,this.context=a.context);return e.makeArray(a,this)},selector:"",jquery:"1.7.1",length:0,size:function(){return this.length},toArray:function(){return F.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this[this.length+a]:this[a]},pushStack:function(a,b,c){var d=this.constructor();e.isArray(a)?E.apply(d,a):e.merge(d,a),d.prevObject=this,d.context=this.context,b==="find"?d.selector=this.selector+(this.selector?" ":"")+c:b&&(d.selector=this.selector+"."+b+"("+c+")");return d},each:function(a,b){return e.each(this,a,b)},ready:function(a){e.bindReady(),A.add(a);return this},eq:function(a){a=+a;return a===-1?this.slice(a):this.slice(a,a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(F.apply(this,arguments),"slice",F.call(arguments).join(","))},map:function(a){return this.pushStack(e.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:E,sort:[].sort,splice:[].splice},e.fn.init.prototype=e.fn,e.extend=e.fn.extend=function(){var a,c,d,f,g,h,i=arguments[0]||{},j=1,k=arguments.length,l=!1;typeof i=="boolean"&&(l=i,i=arguments[1]||{},j=2),typeof i!="object"&&!e.isFunction(i)&&(i={}),k===j&&(i=this,--j);for(;j0)return;A.fireWith(c,[e]),e.fn.trigger&&e(c).trigger("ready").off("ready")}},bindReady:function(){if(!A){A=e.Callbacks("once memory");if(c.readyState==="complete")return setTimeout(e.ready,1);if(c.addEventListener)c.addEventListener("DOMContentLoaded",B,!1),a.addEventListener("load",e.ready,!1);else if(c.attachEvent){c.attachEvent("onreadystatechange",B),a.attachEvent("onload",e.ready);var b=!1;try{b=a.frameElement==null}catch(d){}c.documentElement.doScroll&&b&&J()}}},isFunction:function(a){return e.type(a)==="function"},isArray:Array.isArray||function(a){return e.type(a)==="array"},isWindow:function(a){return a&&typeof a=="object"&&"setInterval"in a},isNumeric:function(a){return!isNaN(parseFloat(a))&&isFinite(a)},type:function(a){return a==null?String(a):I[C.call(a)]||"object"},isPlainObject:function(a){if(!a||e.type(a)!=="object"||a.nodeType||e.isWindow(a))return!1;try{if(a.constructor&&!D.call(a,"constructor")&&!D.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}var d;for(d in a);return d===b||D.call(a,d)},isEmptyObject:function(a){for(var b in a)return!1;return!0},error:function(a){throw new Error(a)},parseJSON:function(b){if(typeof b!="string"||!b)return null;b=e.trim(b);if(a.JSON&&a.JSON.parse)return a.JSON.parse(b);if(n.test(b.replace(o,"@").replace(p,"]").replace(q,"")))return(new Function("return "+b))();e.error("Invalid JSON: "+b)},parseXML:function(c){var d,f;try{a.DOMParser?(f=new DOMParser,d=f.parseFromString(c,"text/xml")):(d=new ActiveXObject("Microsoft.XMLDOM"),d.async="false",d.loadXML(c))}catch(g){d=b}(!d||!d.documentElement||d.getElementsByTagName("parsererror").length)&&e.error("Invalid XML: "+c);return d},noop:function(){},globalEval:function(b){b&&j.test(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(w,"ms-").replace(v,x)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,c,d){var f,g=0,h=a.length,i=h===b||e.isFunction(a);if(d){if(i){for(f in a)if(c.apply(a[f],d)===!1)break}else for(;g0&&a[0]&&a[j-1]||j===0||e.isArray(a));if(k)for(;i1?i.call(arguments,0):b,j.notifyWith(k,e)}}function l(a){return function(c){b[a]=arguments.length>1?i.call(arguments,0):c,--g||j.resolveWith(j,b)}}var b=i.call(arguments,0),c=0,d=b.length,e=Array(d),g=d,h=d,j=d<=1&&a&&f.isFunction(a.promise)?a:f.Deferred(),k=j.promise();if(d>1){for(;c
a",d=q.getElementsByTagName("*"),e=q.getElementsByTagName("a")[0];if(!d||!d.length||!e)return{};g=c.createElement("select"),h=g.appendChild(c.createElement("option")),i=q.getElementsByTagName("input")[0],b={leadingWhitespace:q.firstChild.nodeType===3,tbody:!q.getElementsByTagName("tbody").length,htmlSerialize:!!q.getElementsByTagName("link").length,style:/top/.test(e.getAttribute("style")),hrefNormalized:e.getAttribute("href")==="/a",opacity:/^0.55/.test(e.style.opacity),cssFloat:!!e.style.cssFloat,checkOn:i.value==="on",optSelected:h.selected,getSetAttribute:q.className!=="t",enctype:!!c.createElement("form").enctype,html5Clone:c.createElement("nav").cloneNode(!0).outerHTML!=="<:nav>",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0},i.checked=!0,b.noCloneChecked=i.cloneNode(!0).checked,g.disabled=!0,b.optDisabled=!h.disabled;try{delete q.test}catch(s){b.deleteExpando=!1}!q.addEventListener&&q.attachEvent&&q.fireEvent&&(q.attachEvent("onclick",function(){b.noCloneEvent=!1}),q.cloneNode(!0).fireEvent("onclick")),i=c.createElement("input"),i.value="t",i.setAttribute("type","radio"),b.radioValue=i.value==="t",i.setAttribute("checked","checked"),q.appendChild(i),k=c.createDocumentFragment(),k.appendChild(q.lastChild),b.checkClone=k.cloneNode(!0).cloneNode(!0).lastChild.checked,b.appendChecked=i.checked,k.removeChild(i),k.appendChild(q),q.innerHTML="",a.getComputedStyle&&(j=c.createElement("div"),j.style.width="0",j.style.marginRight="0",q.style.width="2px",q.appendChild(j),b.reliableMarginRight=(parseInt((a.getComputedStyle(j,null)||{marginRight:0}).marginRight,10)||0)===0);if(q.attachEvent)for(o in{submit:1,change:1,focusin:1})n="on"+o,p=n in q,p||(q.setAttribute(n,"return;"),p=typeof q[n]=="function"),b[o+"Bubbles"]=p;k.removeChild(q),k=g=h=j=q=i=null,f(function(){var a,d,e,g,h,i,j,k,m,n,o,r=c.getElementsByTagName("body")[0];!r||(j=1,k="position:absolute;top:0;left:0;width:1px;height:1px;margin:0;",m="visibility:hidden;border:0;",n="style='"+k+"border:5px solid #000;padding:0;'",o="
"+""+"
",a=c.createElement("div"),a.style.cssText=m+"width:0;height:0;position:static;top:0;margin-top:"+j+"px",r.insertBefore(a,r.firstChild),q=c.createElement("div"),a.appendChild(q),q.innerHTML="
t
",l=q.getElementsByTagName("td"),p=l[0].offsetHeight===0,l[0].style.display="",l[1].style.display="none",b.reliableHiddenOffsets=p&&l[0].offsetHeight===0,q.innerHTML="",q.style.width=q.style.paddingLeft="1px",f.boxModel=b.boxModel=q.offsetWidth===2,typeof q.style.zoom!="undefined"&&(q.style.display="inline",q.style.zoom=1,b.inlineBlockNeedsLayout=q.offsetWidth===2,q.style.display="",q.innerHTML="
",b.shrinkWrapBlocks=q.offsetWidth!==2),q.style.cssText=k+m,q.innerHTML=o,d=q.firstChild,e=d.firstChild,h=d.nextSibling.firstChild.firstChild,i={doesNotAddBorder:e.offsetTop!==5,doesAddBorderForTableAndCells:h.offsetTop===5},e.style.position="fixed",e.style.top="20px",i.fixedPosition=e.offsetTop===20||e.offsetTop===15,e.style.position=e.style.top="",d.style.overflow="hidden",d.style.position="relative",i.subtractsBorderForOverflowNotVisible=e.offsetTop===-5,i.doesNotIncludeMarginInBodyOffset=r.offsetTop!==j,r.removeChild(a),q=a=null,f.extend(b,i))});return b}();var j=/^(?:\{.*\}|\[.*\])$/,k=/([A-Z])/g;f.extend({cache:{},uuid:0,expando:"jQuery"+(f.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(a){a=a.nodeType?f.cache[a[f.expando]]:a[f.expando];return!!a&&!m(a)},data:function(a,c,d,e){if(!!f.acceptData(a)){var g,h,i,j=f.expando,k=typeof c=="string",l=a.nodeType,m=l?f.cache:a,n=l?a[j]:a[j]&&j,o=c==="events";if((!n||!m[n]||!o&&!e&&!m[n].data)&&k&&d===b)return;n||(l?a[j]=n=++f.uuid:n=j),m[n]||(m[n]={},l||(m[n].toJSON=f.noop));if(typeof c=="object"||typeof c=="function")e?m[n]=f.extend(m[n],c):m[n].data=f.extend(m[n].data,c);g=h=m[n],e||(h.data||(h.data={}),h=h.data),d!==b&&(h[f.camelCase(c)]=d);if(o&&!h[c])return g.events;k?(i=h[c],i==null&&(i=h[f.camelCase(c)])):i=h;return i}},removeData:function(a,b,c){if(!!f.acceptData(a)){var d,e,g,h=f.expando,i=a.nodeType,j=i?f.cache:a,k=i?a[h]:h;if(!j[k])return;if(b){d=c?j[k]:j[k].data;if(d){f.isArray(b)||(b in d?b=[b]:(b=f.camelCase(b),b in d?b=[b]:b=b.split(" ")));for(e=0,g=b.length;e-1)return!0;return!1},val:function(a){var c,d,e,g=this[0];{if(!!arguments.length){e=f.isFunction(a);return this.each(function(d){var g=f(this),h;if(this.nodeType===1){e?h=a.call(this,d,g.val()):h=a,h==null?h="":typeof h=="number"?h+="":f.isArray(h)&&(h=f.map(h,function(a){return a==null?"":a+""})),c=f.valHooks[this.nodeName.toLowerCase()]||f.valHooks[this.type];if(!c||!("set"in c)||c.set(this,h,"value")===b)this.value=h}})}if(g){c=f.valHooks[g.nodeName.toLowerCase()]||f.valHooks[g.type];if(c&&"get"in c&&(d=c.get(g,"value"))!==b)return d;d=g.value;return typeof d=="string"?d.replace(q,""):d==null?"":d}}}}),f.extend({valHooks:{option:{get:function(a){var b=a.attributes.value;return!b||b.specified?a.value:a.text}},select:{get:function(a){var b,c,d,e,g=a.selectedIndex,h=[],i=a.options,j=a.type==="select-one";if(g<0)return null;c=j?g:0,d=j?g+1:i.length;for(;c=0}),c.length||(a.selectedIndex=-1);return c}}},attrFn:{val:!0,css:!0,html:!0,text:!0,data:!0,width:!0,height:!0,offset:!0},attr:function(a,c,d,e){var g,h,i,j=a.nodeType;if(!!a&&j!==3&&j!==8&&j!==2){if(e&&c in f.attrFn)return f(a)[c](d);if(typeof a.getAttribute=="undefined")return f.prop(a,c,d);i=j!==1||!f.isXMLDoc(a),i&&(c=c.toLowerCase(),h=f.attrHooks[c]||(u.test(c)?x:w));if(d!==b){if(d===null){f.removeAttr(a,c);return}if(h&&"set"in h&&i&&(g=h.set(a,d,c))!==b)return g;a.setAttribute(c,""+d);return d}if(h&&"get"in h&&i&&(g=h.get(a,c))!==null)return g;g=a.getAttribute(c);return g===null?b:g}},removeAttr:function(a,b){var c,d,e,g,h=0;if(b&&a.nodeType===1){d=b.toLowerCase().split(p),g=d.length;for(;h=0}})});var z=/^(?:textarea|input|select)$/i,A=/^([^\.]*)?(?:\.(.+))?$/,B=/\bhover(\.\S+)?\b/,C=/^key/,D=/^(?:mouse|contextmenu)|click/,E=/^(?:focusinfocus|focusoutblur)$/,F=/^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/,G=function(a){var b=F.exec(a);b&&(b[1]=(b[1]||"").toLowerCase(),b[3]=b[3]&&new RegExp("(?:^|\\s)"+b[3]+"(?:\\s|$)"));return b},H=function(a,b){var c=a.attributes||{};return(!b[1]||a.nodeName.toLowerCase()===b[1])&&(!b[2]||(c.id||{}).value===b[2])&&(!b[3]||b[3].test((c["class"]||{}).value))},I=function(a){return f.event.special.hover?a:a.replace(B,"mouseenter$1 mouseleave$1")}; -f.event={add:function(a,c,d,e,g){var h,i,j,k,l,m,n,o,p,q,r,s;if(!(a.nodeType===3||a.nodeType===8||!c||!d||!(h=f._data(a)))){d.handler&&(p=d,d=p.handler),d.guid||(d.guid=f.guid++),j=h.events,j||(h.events=j={}),i=h.handle,i||(h.handle=i=function(a){return typeof f!="undefined"&&(!a||f.event.triggered!==a.type)?f.event.dispatch.apply(i.elem,arguments):b},i.elem=a),c=f.trim(I(c)).split(" ");for(k=0;k=0&&(h=h.slice(0,-1),k=!0),h.indexOf(".")>=0&&(i=h.split("."),h=i.shift(),i.sort());if((!e||f.event.customEvent[h])&&!f.event.global[h])return;c=typeof c=="object"?c[f.expando]?c:new f.Event(h,c):new f.Event(h),c.type=h,c.isTrigger=!0,c.exclusive=k,c.namespace=i.join("."),c.namespace_re=c.namespace?new RegExp("(^|\\.)"+i.join("\\.(?:.*\\.)?")+"(\\.|$)"):null,o=h.indexOf(":")<0?"on"+h:"";if(!e){j=f.cache;for(l in j)j[l].events&&j[l].events[h]&&f.event.trigger(c,d,j[l].handle.elem,!0);return}c.result=b,c.target||(c.target=e),d=d!=null?f.makeArray(d):[],d.unshift(c),p=f.event.special[h]||{};if(p.trigger&&p.trigger.apply(e,d)===!1)return;r=[[e,p.bindType||h]];if(!g&&!p.noBubble&&!f.isWindow(e)){s=p.delegateType||h,m=E.test(s+h)?e:e.parentNode,n=null;for(;m;m=m.parentNode)r.push([m,s]),n=m;n&&n===e.ownerDocument&&r.push([n.defaultView||n.parentWindow||a,s])}for(l=0;le&&i.push({elem:this,matches:d.slice(e)});for(j=0;j0?this.on(b,null,a,c):this.trigger(b)},f.attrFn&&(f.attrFn[b]=!0),C.test(b)&&(f.event.fixHooks[b]=f.event.keyHooks),D.test(b)&&(f.event.fixHooks[b]=f.event.mouseHooks)}),function(){function x(a,b,c,e,f,g){for(var h=0,i=e.length;h0){k=j;break}}j=j[a]}e[h]=k}}}function w(a,b,c,e,f,g){for(var h=0,i=e.length;h+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,d="sizcache"+(Math.random()+"").replace(".",""),e=0,g=Object.prototype.toString,h=!1,i=!0,j=/\\/g,k=/\r\n/g,l=/\W/;[0,0].sort(function(){i=!1;return 0});var m=function(b,d,e,f){e=e||[],d=d||c;var h=d;if(d.nodeType!==1&&d.nodeType!==9)return[];if(!b||typeof b!="string")return e;var i,j,k,l,n,q,r,t,u=!0,v=m.isXML(d),w=[],x=b;do{a.exec(""),i=a.exec(x);if(i){x=i[3],w.push(i[1]);if(i[2]){l=i[3];break}}}while(i);if(w.length>1&&p.exec(b))if(w.length===2&&o.relative[w[0]])j=y(w[0]+w[1],d,f);else{j=o.relative[w[0]]?[d]:m(w.shift(),d);while(w.length)b=w.shift(),o.relative[b]&&(b+=w.shift()),j=y(b,j,f)}else{!f&&w.length>1&&d.nodeType===9&&!v&&o.match.ID.test(w[0])&&!o.match.ID.test(w[w.length-1])&&(n=m.find(w.shift(),d,v),d=n.expr?m.filter(n.expr,n.set)[0]:n.set[0]);if(d){n=f?{expr:w.pop(),set:s(f)}:m.find(w.pop(),w.length===1&&(w[0]==="~"||w[0]==="+")&&d.parentNode?d.parentNode:d,v),j=n.expr?m.filter(n.expr,n.set):n.set,w.length>0?k=s(j):u=!1;while(w.length)q=w.pop(),r=q,o.relative[q]?r=w.pop():q="",r==null&&(r=d),o.relative[q](k,r,v)}else k=w=[]}k||(k=j),k||m.error(q||b);if(g.call(k)==="[object Array]")if(!u)e.push.apply(e,k);else if(d&&d.nodeType===1)for(t=0;k[t]!=null;t++)k[t]&&(k[t]===!0||k[t].nodeType===1&&m.contains(d,k[t]))&&e.push(j[t]);else for(t=0;k[t]!=null;t++)k[t]&&k[t].nodeType===1&&e.push(j[t]);else s(k,e);l&&(m(l,h,e,f),m.uniqueSort(e));return e};m.uniqueSort=function(a){if(u){h=i,a.sort(u);if(h)for(var b=1;b0},m.find=function(a,b,c){var d,e,f,g,h,i;if(!a)return[];for(e=0,f=o.order.length;e":function(a,b){var c,d=typeof b=="string",e=0,f=a.length;if(d&&!l.test(b)){b=b.toLowerCase();for(;e=0)?c||d.push(h):c&&(b[g]=!1));return!1},ID:function(a){return a[1].replace(j,"")},TAG:function(a,b){return a[1].replace(j,"").toLowerCase()},CHILD:function(a){if(a[1]==="nth"){a[2]||m.error(a[0]),a[2]=a[2].replace(/^\+|\s*/g,"");var b=/(-?)(\d*)(?:n([+\-]?\d*))?/.exec(a[2]==="even"&&"2n"||a[2]==="odd"&&"2n+1"||!/\D/.test(a[2])&&"0n+"+a[2]||a[2]);a[2]=b[1]+(b[2]||1)-0,a[3]=b[3]-0}else a[2]&&m.error(a[0]);a[0]=e++;return a},ATTR:function(a,b,c,d,e,f){var g=a[1]=a[1].replace(j,"");!f&&o.attrMap[g]&&(a[1]=o.attrMap[g]),a[4]=(a[4]||a[5]||"").replace(j,""),a[2]==="~="&&(a[4]=" "+a[4]+" ");return a},PSEUDO:function(b,c,d,e,f){if(b[1]==="not")if((a.exec(b[3])||"").length>1||/^\w/.test(b[3]))b[3]=m(b[3],null,null,c);else{var g=m.filter(b[3],c,d,!0^f);d||e.push.apply(e,g);return!1}else if(o.match.POS.test(b[0])||o.match.CHILD.test(b[0]))return!0;return b},POS:function(a){a.unshift(!0);return a}},filters:{enabled:function(a){return a.disabled===!1&&a.type!=="hidden"},disabled:function(a){return a.disabled===!0},checked:function(a){return a.checked===!0},selected:function(a){a.parentNode&&a.parentNode.selectedIndex;return a.selected===!0},parent:function(a){return!!a.firstChild},empty:function(a){return!a.firstChild},has:function(a,b,c){return!!m(c[3],a).length},header:function(a){return/h\d/i.test(a.nodeName)},text:function(a){var b=a.getAttribute("type"),c=a.type;return a.nodeName.toLowerCase()==="input"&&"text"===c&&(b===c||b===null)},radio:function(a){return a.nodeName.toLowerCase()==="input"&&"radio"===a.type},checkbox:function(a){return a.nodeName.toLowerCase()==="input"&&"checkbox"===a.type},file:function(a){return a.nodeName.toLowerCase()==="input"&&"file"===a.type},password:function(a){return a.nodeName.toLowerCase()==="input"&&"password"===a.type},submit:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"submit"===a.type},image:function(a){return a.nodeName.toLowerCase()==="input"&&"image"===a.type},reset:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"reset"===a.type},button:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&"button"===a.type||b==="button"},input:function(a){return/input|select|textarea|button/i.test(a.nodeName)},focus:function(a){return a===a.ownerDocument.activeElement}},setFilters:{first:function(a,b){return b===0},last:function(a,b,c,d){return b===d.length-1},even:function(a,b){return b%2===0},odd:function(a,b){return b%2===1},lt:function(a,b,c){return bc[3]-0},nth:function(a,b,c){return c[3]-0===b},eq:function(a,b,c){return c[3]-0===b}},filter:{PSEUDO:function(a,b,c,d){var e=b[1],f=o.filters[e];if(f)return f(a,c,b,d);if(e==="contains")return(a.textContent||a.innerText||n([a])||"").indexOf(b[3])>=0;if(e==="not"){var g=b[3];for(var h=0,i=g.length;h=0}},ID:function(a,b){return a.nodeType===1&&a.getAttribute("id")===b},TAG:function(a,b){return b==="*"&&a.nodeType===1||!!a.nodeName&&a.nodeName.toLowerCase()===b},CLASS:function(a,b){return(" "+(a.className||a.getAttribute("class"))+" ").indexOf(b)>-1},ATTR:function(a,b){var c=b[1],d=m.attr?m.attr(a,c):o.attrHandle[c]?o.attrHandle[c](a):a[c]!=null?a[c]:a.getAttribute(c),e=d+"",f=b[2],g=b[4];return d==null?f==="!=":!f&&m.attr?d!=null:f==="="?e===g:f==="*="?e.indexOf(g)>=0:f==="~="?(" "+e+" ").indexOf(g)>=0:g?f==="!="?e!==g:f==="^="?e.indexOf(g)===0:f==="$="?e.substr(e.length-g.length)===g:f==="|="?e===g||e.substr(0,g.length+1)===g+"-":!1:e&&d!==!1},POS:function(a,b,c,d){var e=b[2],f=o.setFilters[e];if(f)return f(a,c,b,d)}}},p=o.match.POS,q=function(a,b){return"\\"+(b-0+1)};for(var r in o.match)o.match[r]=new RegExp(o.match[r].source+/(?![^\[]*\])(?![^\(]*\))/.source),o.leftMatch[r]=new RegExp(/(^(?:.|\r|\n)*?)/.source+o.match[r].source.replace(/\\(\d+)/g,q));var s=function(a,b){a=Array.prototype.slice.call(a,0);if(b){b.push.apply(b,a);return b}return a};try{Array.prototype.slice.call(c.documentElement.childNodes,0)[0].nodeType}catch(t){s=function(a,b){var c=0,d=b||[];if(g.call(a)==="[object Array]")Array.prototype.push.apply(d,a);else if(typeof a.length=="number")for(var e=a.length;c",e.insertBefore(a,e.firstChild),c.getElementById(d)&&(o.find.ID=function(a,c,d){if(typeof c.getElementById!="undefined"&&!d){var e=c.getElementById(a[1]);return e?e.id===a[1]||typeof e.getAttributeNode!="undefined"&&e.getAttributeNode("id").nodeValue===a[1]?[e]:b:[]}},o.filter.ID=function(a,b){var c=typeof a.getAttributeNode!="undefined"&&a.getAttributeNode("id");return a.nodeType===1&&c&&c.nodeValue===b}),e.removeChild(a),e=a=null}(),function(){var a=c.createElement("div");a.appendChild(c.createComment("")),a.getElementsByTagName("*").length>0&&(o.find.TAG=function(a,b){var c=b.getElementsByTagName(a[1]);if(a[1]==="*"){var d=[];for(var e=0;c[e];e++)c[e].nodeType===1&&d.push(c[e]);c=d}return c}),a.innerHTML="",a.firstChild&&typeof a.firstChild.getAttribute!="undefined"&&a.firstChild.getAttribute("href")!=="#"&&(o.attrHandle.href=function(a){return a.getAttribute("href",2)}),a=null}(),c.querySelectorAll&&function(){var a=m,b=c.createElement("div"),d="__sizzle__";b.innerHTML="

";if(!b.querySelectorAll||b.querySelectorAll(".TEST").length!==0){m=function(b,e,f,g){e=e||c;if(!g&&!m.isXML(e)){var h=/^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec(b);if(h&&(e.nodeType===1||e.nodeType===9)){if(h[1])return s(e.getElementsByTagName(b),f);if(h[2]&&o.find.CLASS&&e.getElementsByClassName)return s(e.getElementsByClassName(h[2]),f)}if(e.nodeType===9){if(b==="body"&&e.body)return s([e.body],f);if(h&&h[3]){var i=e.getElementById(h[3]);if(!i||!i.parentNode)return s([],f);if(i.id===h[3])return s([i],f)}try{return s(e.querySelectorAll(b),f)}catch(j){}}else if(e.nodeType===1&&e.nodeName.toLowerCase()!=="object"){var k=e,l=e.getAttribute("id"),n=l||d,p=e.parentNode,q=/^\s*[+~]/.test(b);l?n=n.replace(/'/g,"\\$&"):e.setAttribute("id",n),q&&p&&(e=e.parentNode);try{if(!q||p)return s(e.querySelectorAll("[id='"+n+"'] "+b),f)}catch(r){}finally{l||k.removeAttribute("id")}}}return a(b,e,f,g)};for(var e in a)m[e]=a[e];b=null}}(),function(){var a=c.documentElement,b=a.matchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.msMatchesSelector;if(b){var d=!b.call(c.createElement("div"),"div"),e=!1;try{b.call(c.documentElement,"[test!='']:sizzle")}catch(f){e=!0}m.matchesSelector=function(a,c){c=c.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!m.isXML(a))try{if(e||!o.match.PSEUDO.test(c)&&!/!=/.test(c)){var f=b.call(a,c);if(f||!d||a.document&&a.document.nodeType!==11)return f}}catch(g){}return m(c,null,null,[a]).length>0}}}(),function(){var a=c.createElement("div");a.innerHTML="
";if(!!a.getElementsByClassName&&a.getElementsByClassName("e").length!==0){a.lastChild.className="e";if(a.getElementsByClassName("e").length===1)return;o.order.splice(1,0,"CLASS"),o.find.CLASS=function(a,b,c){if(typeof b.getElementsByClassName!="undefined"&&!c)return b.getElementsByClassName(a[1])},a=null}}(),c.documentElement.contains?m.contains=function(a,b){return a!==b&&(a.contains?a.contains(b):!0)}:c.documentElement.compareDocumentPosition?m.contains=function(a,b){return!!(a.compareDocumentPosition(b)&16)}:m.contains=function(){return!1},m.isXML=function(a){var b=(a?a.ownerDocument||a:0).documentElement;return b?b.nodeName!=="HTML":!1};var y=function(a,b,c){var d,e=[],f="",g=b.nodeType?[b]:b;while(d=o.match.PSEUDO.exec(a))f+=d[0],a=a.replace(o.match.PSEUDO,"");a=o.relative[a]?a+"*":a;for(var h=0,i=g.length;h0)for(h=g;h=0:f.filter(a,this).length>0:this.filter(a).length>0)},closest:function(a,b){var c=[],d,e,g=this[0];if(f.isArray(a)){var h=1;while(g&&g.ownerDocument&&g!==b){for(d=0;d-1:f.find.matchesSelector(g,a)){c.push(g);break}g=g.parentNode;if(!g||!g.ownerDocument||g===b||g.nodeType===11)break}}c=c.length>1?f.unique(c):c;return this.pushStack(c,"closest",a)},index:function(a){if(!a)return this[0]&&this[0].parentNode?this.prevAll().length:-1;if(typeof a=="string")return f.inArray(this[0],f(a));return f.inArray(a.jquery?a[0]:a,this)},add:function(a,b){var c=typeof a=="string"?f(a,b):f.makeArray(a&&a.nodeType?[a]:a),d=f.merge(this.get(),c);return this.pushStack(S(c[0])||S(d[0])?d:f.unique(d))},andSelf:function(){return this.add(this.prevObject)}}),f.each({parent:function(a){var b=a.parentNode;return b&&b.nodeType!==11?b:null},parents:function(a){return f.dir(a,"parentNode")},parentsUntil:function(a,b,c){return f.dir(a,"parentNode",c)},next:function(a){return f.nth(a,2,"nextSibling")},prev:function(a){return f.nth(a,2,"previousSibling")},nextAll:function(a){return f.dir(a,"nextSibling")},prevAll:function(a){return f.dir(a,"previousSibling")},nextUntil:function(a,b,c){return f.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return f.dir(a,"previousSibling",c)},siblings:function(a){return f.sibling(a.parentNode.firstChild,a)},children:function(a){return f.sibling(a.firstChild)},contents:function(a){return f.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:f.makeArray(a.childNodes)}},function(a,b){f.fn[a]=function(c,d){var e=f.map(this,b,c);L.test(a)||(d=c),d&&typeof d=="string"&&(e=f.filter(d,e)),e=this.length>1&&!R[a]?f.unique(e):e,(this.length>1||N.test(d))&&M.test(a)&&(e=e.reverse());return this.pushStack(e,a,P.call(arguments).join(","))}}),f.extend({filter:function(a,b,c){c&&(a=":not("+a+")");return b.length===1?f.find.matchesSelector(b[0],a)?[b[0]]:[]:f.find.matches(a,b)},dir:function(a,c,d){var e=[],g=a[c];while(g&&g.nodeType!==9&&(d===b||g.nodeType!==1||!f(g).is(d)))g.nodeType===1&&e.push(g),g=g[c];return e},nth:function(a,b,c,d){b=b||1;var e=0;for(;a;a=a[c])if(a.nodeType===1&&++e===b)break;return a},sibling:function(a,b){var c=[];for(;a;a=a.nextSibling)a.nodeType===1&&a!==b&&c.push(a);return c}});var V="abbr|article|aside|audio|canvas|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",W=/ jQuery\d+="(?:\d+|null)"/g,X=/^\s+/,Y=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,Z=/<([\w:]+)/,$=/",""],legend:[1,"
","
"],thead:[1,"","
"],tr:[2,"","
"],td:[3,"","
"],col:[2,"","
"],area:[1,"",""],_default:[0,"",""]},bh=U(c);bg.optgroup=bg.option,bg.tbody=bg.tfoot=bg.colgroup=bg.caption=bg.thead,bg.th=bg.td,f.support.htmlSerialize||(bg._default=[1,"div
","
"]),f.fn.extend({text:function(a){if(f.isFunction(a))return this.each(function(b){var c=f(this);c.text(a.call(this,b,c.text()))});if(typeof a!="object"&&a!==b)return this.empty().append((this[0]&&this[0].ownerDocument||c).createTextNode(a));return f.text(this)},wrapAll:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapAll(a.call(this,b))});if(this[0]){var b=f(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&a.firstChild.nodeType===1)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapInner(a.call(this,b))});return this.each(function(){var b=f(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=f.isFunction(a);return this.each(function(c){f(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){f.nodeName(this,"body")||f(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this)});if(arguments.length){var a=f.clean(arguments);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this.nextSibling)});if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,f.clean(arguments));return a}},remove:function(a,b){for(var c=0,d;(d=this[c])!=null;c++)if(!a||f.filter(a,[d]).length)!b&&d.nodeType===1&&(f.cleanData(d.getElementsByTagName("*")),f.cleanData([d])),d.parentNode&&d.parentNode.removeChild(d);return this},empty:function() -{for(var a=0,b;(b=this[a])!=null;a++){b.nodeType===1&&f.cleanData(b.getElementsByTagName("*"));while(b.firstChild)b.removeChild(b.firstChild)}return this},clone:function(a,b){a=a==null?!1:a,b=b==null?a:b;return this.map(function(){return f.clone(this,a,b)})},html:function(a){if(a===b)return this[0]&&this[0].nodeType===1?this[0].innerHTML.replace(W,""):null;if(typeof a=="string"&&!ba.test(a)&&(f.support.leadingWhitespace||!X.test(a))&&!bg[(Z.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(Y,"<$1>");try{for(var c=0,d=this.length;c1&&l0?this.clone(!0):this).get();f(e[h])[b](j),d=d.concat(j)}return this.pushStack(d,a,e.selector)}}),f.extend({clone:function(a,b,c){var d,e,g,h=f.support.html5Clone||!bc.test("<"+a.nodeName)?a.cloneNode(!0):bo(a);if((!f.support.noCloneEvent||!f.support.noCloneChecked)&&(a.nodeType===1||a.nodeType===11)&&!f.isXMLDoc(a)){bk(a,h),d=bl(a),e=bl(h);for(g=0;d[g];++g)e[g]&&bk(d[g],e[g])}if(b){bj(a,h);if(c){d=bl(a),e=bl(h);for(g=0;d[g];++g)bj(d[g],e[g])}}d=e=null;return h},clean:function(a,b,d,e){var g;b=b||c,typeof b.createElement=="undefined"&&(b=b.ownerDocument||b[0]&&b[0].ownerDocument||c);var h=[],i;for(var j=0,k;(k=a[j])!=null;j++){typeof k=="number"&&(k+="");if(!k)continue;if(typeof k=="string")if(!_.test(k))k=b.createTextNode(k);else{k=k.replace(Y,"<$1>");var l=(Z.exec(k)||["",""])[1].toLowerCase(),m=bg[l]||bg._default,n=m[0],o=b.createElement("div");b===c?bh.appendChild(o):U(b).appendChild(o),o.innerHTML=m[1]+k+m[2];while(n--)o=o.lastChild;if(!f.support.tbody){var p=$.test(k),q=l==="table"&&!p?o.firstChild&&o.firstChild.childNodes:m[1]===""&&!p?o.childNodes:[];for(i=q.length-1;i>=0;--i)f.nodeName(q[i],"tbody")&&!q[i].childNodes.length&&q[i].parentNode.removeChild(q[i])}!f.support.leadingWhitespace&&X.test(k)&&o.insertBefore(b.createTextNode(X.exec(k)[0]),o.firstChild),k=o.childNodes}var r;if(!f.support.appendChecked)if(k[0]&&typeof (r=k.length)=="number")for(i=0;i=0)return b+"px"}}}),f.support.opacity||(f.cssHooks.opacity={get:function(a,b){return br.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?parseFloat(RegExp.$1)/100+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=f.isNumeric(b)?"alpha(opacity="+b*100+")":"",g=d&&d.filter||c.filter||"";c.zoom=1;if(b>=1&&f.trim(g.replace(bq,""))===""){c.removeAttribute("filter");if(d&&!d.filter)return}c.filter=bq.test(g)?g.replace(bq,e):g+" "+e}}),f(function(){f.support.reliableMarginRight||(f.cssHooks.marginRight={get:function(a,b){var c;f.swap(a,{display:"inline-block"},function(){b?c=bz(a,"margin-right","marginRight"):c=a.style.marginRight});return c}})}),c.defaultView&&c.defaultView.getComputedStyle&&(bA=function(a,b){var c,d,e;b=b.replace(bs,"-$1").toLowerCase(),(d=a.ownerDocument.defaultView)&&(e=d.getComputedStyle(a,null))&&(c=e.getPropertyValue(b),c===""&&!f.contains(a.ownerDocument.documentElement,a)&&(c=f.style(a,b)));return c}),c.documentElement.currentStyle&&(bB=function(a,b){var c,d,e,f=a.currentStyle&&a.currentStyle[b],g=a.style;f===null&&g&&(e=g[b])&&(f=e),!bt.test(f)&&bu.test(f)&&(c=g.left,d=a.runtimeStyle&&a.runtimeStyle.left,d&&(a.runtimeStyle.left=a.currentStyle.left),g.left=b==="fontSize"?"1em":f||0,f=g.pixelLeft+"px",g.left=c,d&&(a.runtimeStyle.left=d));return f===""?"auto":f}),bz=bA||bB,f.expr&&f.expr.filters&&(f.expr.filters.hidden=function(a){var b=a.offsetWidth,c=a.offsetHeight;return b===0&&c===0||!f.support.reliableHiddenOffsets&&(a.style&&a.style.display||f.css(a,"display"))==="none"},f.expr.filters.visible=function(a){return!f.expr.filters.hidden(a)});var bD=/%20/g,bE=/\[\]$/,bF=/\r?\n/g,bG=/#.*$/,bH=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,bI=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,bJ=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,bK=/^(?:GET|HEAD)$/,bL=/^\/\//,bM=/\?/,bN=/)<[^<]*)*<\/script>/gi,bO=/^(?:select|textarea)/i,bP=/\s+/,bQ=/([?&])_=[^&]*/,bR=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,bS=f.fn.load,bT={},bU={},bV,bW,bX=["*/"]+["*"];try{bV=e.href}catch(bY){bV=c.createElement("a"),bV.href="",bV=bV.href}bW=bR.exec(bV.toLowerCase())||[],f.fn.extend({load:function(a,c,d){if(typeof a!="string"&&bS)return bS.apply(this,arguments);if(!this.length)return this;var e=a.indexOf(" ");if(e>=0){var g=a.slice(e,a.length);a=a.slice(0,e)}var h="GET";c&&(f.isFunction(c)?(d=c,c=b):typeof c=="object"&&(c=f.param(c,f.ajaxSettings.traditional),h="POST"));var i=this;f.ajax({url:a,type:h,dataType:"html",data:c,complete:function(a,b,c){c=a.responseText,a.isResolved()&&(a.done(function(a){c=a}),i.html(g?f("
").append(c.replace(bN,"")).find(g):c)),d&&i.each(d,[c,b,a])}});return this},serialize:function(){return f.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?f.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||bO.test(this.nodeName)||bI.test(this.type))}).map(function(a,b){var c=f(this).val();return c==null?null:f.isArray(c)?f.map(c,function(a,c){return{name:b.name,value:a.replace(bF,"\r\n")}}):{name:b.name,value:c.replace(bF,"\r\n")}}).get()}}),f.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){f.fn[b]=function(a){return this.on(b,a)}}),f.each(["get","post"],function(a,c){f[c]=function(a,d,e,g){f.isFunction(d)&&(g=g||e,e=d,d=b);return f.ajax({type:c,url:a,data:d,success:e,dataType:g})}}),f.extend({getScript:function(a,c){return f.get(a,b,c,"script")},getJSON:function(a,b,c){return f.get(a,b,c,"json")},ajaxSetup:function(a,b){b?b_(a,f.ajaxSettings):(b=a,a=f.ajaxSettings),b_(a,b);return a},ajaxSettings:{url:bV,isLocal:bJ.test(bW[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":bX},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":a.String,"text html":!0,"text json":f.parseJSON,"text xml":f.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:bZ(bT),ajaxTransport:bZ(bU),ajax:function(a,c){function w(a,c,l,m){if(s!==2){s=2,q&&clearTimeout(q),p=b,n=m||"",v.readyState=a>0?4:0;var o,r,u,w=c,x=l?cb(d,v,l):b,y,z;if(a>=200&&a<300||a===304){if(d.ifModified){if(y=v.getResponseHeader("Last-Modified"))f.lastModified[k]=y;if(z=v.getResponseHeader("Etag"))f.etag[k]=z}if(a===304)w="notmodified",o=!0;else try{r=cc(d,x),w="success",o=!0}catch(A){w="parsererror",u=A}}else{u=w;if(!w||a)w="error",a<0&&(a=0)}v.status=a,v.statusText=""+(c||w),o?h.resolveWith(e,[r,w,v]):h.rejectWith(e,[v,w,u]),v.statusCode(j),j=b,t&&g.trigger("ajax"+(o?"Success":"Error"),[v,d,o?r:u]),i.fireWith(e,[v,w]),t&&(g.trigger("ajaxComplete",[v,d]),--f.active||f.event.trigger("ajaxStop"))}}typeof a=="object"&&(c=a,a=b),c=c||{};var d=f.ajaxSetup({},c),e=d.context||d,g=e!==d&&(e.nodeType||e instanceof f)?f(e):f.event,h=f.Deferred(),i=f.Callbacks("once memory"),j=d.statusCode||{},k,l={},m={},n,o,p,q,r,s=0,t,u,v={readyState:0,setRequestHeader:function(a,b){if(!s){var c=a.toLowerCase();a=m[c]=m[c]||a,l[a]=b}return this},getAllResponseHeaders:function(){return s===2?n:null},getResponseHeader:function(a){var c;if(s===2){if(!o){o={};while(c=bH.exec(n))o[c[1].toLowerCase()]=c[2]}c=o[a.toLowerCase()]}return c===b?null:c},overrideMimeType:function(a){s||(d.mimeType=a);return this},abort:function(a){a=a||"abort",p&&p.abort(a),w(0,a);return this}};h.promise(v),v.success=v.done,v.error=v.fail,v.complete=i.add,v.statusCode=function(a){if(a){var b;if(s<2)for(b in a)j[b]=[j[b],a[b]];else b=a[v.status],v.then(b,b)}return this},d.url=((a||d.url)+"").replace(bG,"").replace(bL,bW[1]+"//"),d.dataTypes=f.trim(d.dataType||"*").toLowerCase().split(bP),d.crossDomain==null&&(r=bR.exec(d.url.toLowerCase()),d.crossDomain=!(!r||r[1]==bW[1]&&r[2]==bW[2]&&(r[3]||(r[1]==="http:"?80:443))==(bW[3]||(bW[1]==="http:"?80:443)))),d.data&&d.processData&&typeof d.data!="string"&&(d.data=f.param(d.data,d.traditional)),b$(bT,d,c,v);if(s===2)return!1;t=d.global,d.type=d.type.toUpperCase(),d.hasContent=!bK.test(d.type),t&&f.active++===0&&f.event.trigger("ajaxStart");if(!d.hasContent){d.data&&(d.url+=(bM.test(d.url)?"&":"?")+d.data,delete d.data),k=d.url;if(d.cache===!1){var x=f.now(),y=d.url.replace(bQ,"$1_="+x);d.url=y+(y===d.url?(bM.test(d.url)?"&":"?")+"_="+x:"")}}(d.data&&d.hasContent&&d.contentType!==!1||c.contentType)&&v.setRequestHeader("Content-Type",d.contentType),d.ifModified&&(k=k||d.url,f.lastModified[k]&&v.setRequestHeader("If-Modified-Since",f.lastModified[k]),f.etag[k]&&v.setRequestHeader("If-None-Match",f.etag[k])),v.setRequestHeader("Accept",d.dataTypes[0]&&d.accepts[d.dataTypes[0]]?d.accepts[d.dataTypes[0]]+(d.dataTypes[0]!=="*"?", "+bX+"; q=0.01":""):d.accepts["*"]);for(u in d.headers)v.setRequestHeader(u,d.headers[u]);if(d.beforeSend&&(d.beforeSend.call(e,v,d)===!1||s===2)){v.abort();return!1}for(u in{success:1,error:1,complete:1})v[u](d[u]);p=b$(bU,d,c,v);if(!p)w(-1,"No Transport");else{v.readyState=1,t&&g.trigger("ajaxSend",[v,d]),d.async&&d.timeout>0&&(q=setTimeout(function(){v.abort("timeout")},d.timeout));try{s=1,p.send(l,w)}catch(z){if(s<2)w(-1,z);else throw z}}return v},param:function(a,c){var d=[],e=function(a,b){b=f.isFunction(b)?b():b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};c===b&&(c=f.ajaxSettings.traditional);if(f.isArray(a)||a.jquery&&!f.isPlainObject(a))f.each(a,function(){e(this.name,this.value)});else for(var g in a)ca(g,a[g],c,e);return d.join("&").replace(bD,"+")}}),f.extend({active:0,lastModified:{},etag:{}});var cd=f.now(),ce=/(\=)\?(&|$)|\?\?/i;f.ajaxSetup({jsonp:"callback",jsonpCallback:function(){return f.expando+"_"+cd++}}),f.ajaxPrefilter("json jsonp",function(b,c,d){var e=b.contentType==="application/x-www-form-urlencoded"&&typeof b.data=="string";if(b.dataTypes[0]==="jsonp"||b.jsonp!==!1&&(ce.test(b.url)||e&&ce.test(b.data))){var g,h=b.jsonpCallback=f.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,i=a[h],j=b.url,k=b.data,l="$1"+h+"$2";b.jsonp!==!1&&(j=j.replace(ce,l),b.url===j&&(e&&(k=k.replace(ce,l)),b.data===k&&(j+=(/\?/.test(j)?"&":"?")+b.jsonp+"="+h))),b.url=j,b.data=k,a[h]=function(a){g=[a]},d.always(function(){a[h]=i,g&&f.isFunction(i)&&a[h](g[0])}),b.converters["script json"]=function(){g||f.error(h+" was not called");return g[0]},b.dataTypes[0]="json";return"script"}}),f.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(a){f.globalEval(a);return a}}}),f.ajaxPrefilter("script",function(a){a.cache===b&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),f.ajaxTransport("script",function(a){if(a.crossDomain){var d,e=c.head||c.getElementsByTagName("head")[0]||c.documentElement;return{send:function(f,g){d=c.createElement("script"),d.async="async",a.scriptCharset&&(d.charset=a.scriptCharset),d.src=a.url,d.onload=d.onreadystatechange=function(a,c){if(c||!d.readyState||/loaded|complete/.test(d.readyState))d.onload=d.onreadystatechange=null,e&&d.parentNode&&e.removeChild(d),d=b,c||g(200,"success")},e.insertBefore(d,e.firstChild)},abort:function(){d&&d.onload(0,1)}}}});var cf=a.ActiveXObject?function(){for(var a in ch)ch[a](0,1)}:!1,cg=0,ch;f.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&ci()||cj()}:ci,function(a){f.extend(f.support,{ajax:!!a,cors:!!a&&"withCredentials"in a})}(f.ajaxSettings.xhr()),f.support.ajax&&f.ajaxTransport(function(c){if(!c.crossDomain||f.support.cors){var d;return{send:function(e,g){var h=c.xhr(),i,j;c.username?h.open(c.type,c.url,c.async,c.username,c.password):h.open(c.type,c.url,c.async);if(c.xhrFields)for(j in c.xhrFields)h[j]=c.xhrFields[j];c.mimeType&&h.overrideMimeType&&h.overrideMimeType(c.mimeType),!c.crossDomain&&!e["X-Requested-With"]&&(e["X-Requested-With"]="XMLHttpRequest");try{for(j in e)h.setRequestHeader(j,e[j])}catch(k){}h.send(c.hasContent&&c.data||null),d=function(a,e){var j,k,l,m,n;try{if(d&&(e||h.readyState===4)){d=b,i&&(h.onreadystatechange=f.noop,cf&&delete ch[i]);if(e)h.readyState!==4&&h.abort();else{j=h.status,l=h.getAllResponseHeaders(),m={},n=h.responseXML,n&&n.documentElement&&(m.xml=n),m.text=h.responseText;try{k=h.statusText}catch(o){k=""}!j&&c.isLocal&&!c.crossDomain?j=m.text?200:404:j===1223&&(j=204)}}}catch(p){e||g(-1,p)}m&&g(j,k,m,l)},!c.async||h.readyState===4?d():(i=++cg,cf&&(ch||(ch={},f(a).unload(cf)),ch[i]=d),h.onreadystatechange=d)},abort:function(){d&&d(0,1)}}}});var ck={},cl,cm,cn=/^(?:toggle|show|hide)$/,co=/^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,cp,cq=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]],cr;f.fn.extend({show:function(a,b,c){var d,e;if(a||a===0)return this.animate(cu("show",3),a,b,c);for(var g=0,h=this.length;g=i.duration+this.startTime){this.now=this.end,this.pos=this.state=1,this.update(),i.animatedProperties[this.prop]=!0;for(b in i.animatedProperties)i.animatedProperties[b]!==!0&&(g=!1);if(g){i.overflow!=null&&!f.support.shrinkWrapBlocks&&f.each(["","X","Y"],function(a,b){h.style["overflow"+b]=i.overflow[a]}),i.hide&&f(h).hide();if(i.hide||i.show)for(b in i.animatedProperties)f.style(h,b,i.orig[b]),f.removeData(h,"fxshow"+b,!0),f.removeData(h,"toggle"+b,!0);d=i.complete,d&&(i.complete=!1,d.call(h))}return!1}i.duration==Infinity?this.now=e:(c=e-this.startTime,this.state=c/i.duration,this.pos=f.easing[i.animatedProperties[this.prop]](this.state,c,0,1,i.duration),this.now=this.start+(this.end-this.start)*this.pos),this.update();return!0}},f.extend(f.fx,{tick:function(){var a,b=f.timers,c=0;for(;c-1,k={},l={},m,n;j?(l=e.position(),m=l.top,n=l.left):(m=parseFloat(h)||0,n=parseFloat(i)||0),f.isFunction(b)&&(b=b.call(a,c,g)),b.top!=null&&(k.top=b.top-g.top+m),b.left!=null&&(k.left=b.left-g.left+n),"using"in b?b.using.call(a,k):e.css(k)}},f.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),c=this.offset(),d=cx.test(b[0].nodeName)?{top:0,left:0}:b.offset();c.top-=parseFloat(f.css(a,"marginTop"))||0,c.left-=parseFloat(f.css(a,"marginLeft"))||0,d.top+=parseFloat(f.css(b[0],"borderTopWidth"))||0,d.left+=parseFloat(f.css(b[0],"borderLeftWidth"))||0;return{top:c.top-d.top,left:c.left-d.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||c.body;while(a&&!cx.test(a.nodeName)&&f.css(a,"position")==="static")a=a.offsetParent;return a})}}),f.each(["Left","Top"],function(a,c){var d="scroll"+c;f.fn[d]=function(c){var e,g;if(c===b){e=this[0];if(!e)return null;g=cy(e);return g?"pageXOffset"in g?g[a?"pageYOffset":"pageXOffset"]:f.support.boxModel&&g.document.documentElement[d]||g.document.body[d]:e[d]}return this.each(function(){g=cy(this),g?g.scrollTo(a?f(g).scrollLeft():c,a?c:f(g).scrollTop()):this[d]=c})}}),f.each(["Height","Width"],function(a,c){var d=c.toLowerCase();f.fn["inner"+c]=function(){var a=this[0];return a?a.style?parseFloat(f.css(a,d,"padding")):this[d]():null},f.fn["outer"+c]=function(a){var b=this[0];return b?b.style?parseFloat(f.css(b,d,a?"margin":"border")):this[d]():null},f.fn[d]=function(a){var e=this[0];if(!e)return a==null?null:this;if(f.isFunction(a))return this.each(function(b){var c=f(this);c[d](a.call(this,b,c[d]()))});if(f.isWindow(e)){var g=e.document.documentElement["client"+c],h=e.document.body;return e.document.compatMode==="CSS1Compat"&&g||h&&h["client"+c]||g}if(e.nodeType===9)return Math.max(e.documentElement["client"+c],e.body["scroll"+c],e.documentElement["scroll"+c],e.body["offset"+c],e.documentElement["offset"+c]);if(a===b){var i=f.css(e,d),j=parseFloat(i);return f.isNumeric(j)?j:i}return this.css(d,typeof a=="string"?a:a+"px")}}),a.jQuery=a.$=f,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return f})})(window); \ No newline at end of file diff --git a/junit4-ant/src/main/resources/com/carrotsearch/ant/tasks/junit4/templates/json/js/jquery.pathchange.js b/junit4-ant/src/main/resources/com/carrotsearch/ant/tasks/junit4/templates/json/js/jquery.pathchange.js deleted file mode 100644 index 5e878032..00000000 --- a/junit4-ant/src/main/resources/com/carrotsearch/ant/tasks/junit4/templates/json/js/jquery.pathchange.js +++ /dev/null @@ -1,111 +0,0 @@ -// Plugin that provides a "pathchange" event on the window object, notifying an application when the URL changes -// This is accomplished by watching the hash, using the hashchange event from HTML5 or a polling interval in older browsers. -// In addition, in some modern browsers, HTML5 History Management is used to support changing the URL's path without reloading the page. -// This plugin also provides a method to navigate to a URL safely, that will use HTML5 History Management to avoid a page load. -// Everything degrades gracefully, and supports RESTful client development. - -// Browser Support: -// Chrome - Any recent version of Chrome supports everything. -// Safari - Any recent version of Safari supports everything. -// Firefox - Newer versions of Firefox support the hashchange event -// Firefox 4 betas also support HTML5 History Management -// Internet Explorer - IE8 supports hashchange -// IE6 and 7 receive inferior hashchange support through a polling interval. -// Others - Other modern browsers probably support some subset of features. - -// This plugin was authored by Ben Cherry (bcherry@gmail.com), and is released under an MIT License (do what you want with it). -// Some of the code in this plugin was adapted from Modernizr, which is also available under an MIT License. -(function($) { - // can use $(window).bind("pathchange", fn) or $(window).pathchange(fn) - $.fn.pathchange = function(handler) { - return handler ? this.bind("pathchange", handler) : this.trigger("pathchange"); - }; - - var my = $.pathchange = { - // default options - options: { - useHistory: true, // whether we use HTML5 History Management to change the current path - useHashchange: true, // whether we use HTML5 Hashchange to listen to the URL hash - pollingInterval: 250, // when using Hashchange in browsers without it, how often to poll the hash (in ms) - interceptLinks: true, // do we intercept all relative links to avoid some page reloads? - disableHashLinks: true // do we ensure all links with href=# are not followed (this would mess with our history)? - }, - - // call this once when your app is ready to use pathchange - init: function(options) { - var lastHash; - $.extend(my.options, options); - - // Listen to the HTML5 "popstate" event, if supported and desired - if (my.options.useHistory && my.detectHistorySupport()) { - $(window).bind("popstate", function(e) { - $(window).trigger("pathchange"); - }); - } - - // Listen to the HTML5 "hashchange" event, if supported and desired - if (my.options.useHashchange) { - $(window).bind("hashchange", function(e) { - $(window).trigger("pathchange"); - }); - - // Hashchange support for older browsers (IE6/7) - if (!my.detectHashchangeSupport()) { - lastHash = window.location.hash; - setInterval(function() { - if (lastHash !== window.location.hash) { - $(window).trigger("hashchange"); - lastHash = window.location.hash; - } - }, my.options.pollingInterval); - } - } - - // Intercept all relative links on the page, to avoid unneccesary page refreshes - if (my.options.interceptLinks) { - $("body").delegate("a[href^=/]", "click", function(e) { - my.changeTo($(this).attr("href")); - e.preventDefault(); - }); - } - - // Ensure all the href=# links on the page don't mess with things - if (my.options.disableHashLinks) { - $("body").delegate("a[href=#]", "click", function(e) { - e.preventDefault(); - }); - } - }, - - // Call to manually navigate the app somewhere - changeTo: function(path) { - // If we're using History Management, just push an entry - if (my.options.useHistory && my.detectHistorySupport()) { - window.history.pushState(null, null, path); - $(window).trigger("pathchange"); - } else { - // Make sure there's a hash (going from foo.com#bar to foo.com would trigger a reload in Firefox, sadly) - if (path.indexOf("#") < 0) { - path += "#"; - } - // Otherwise, navigate to the new URL. Might reload the browser. Might trigger a hashchange. - window.location.href = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ":" + window.location.port : "") + path; - } - }, - - // Simple feature detection for History Management (borrowed from Modernizr) - detectHistorySupport: function() { - return !!(window.history && history.pushState); - }, - - // Simple feature detection for hashchange (adapted from Modernizr) - detectHashchangeSupport: function() { - var isSupported = "onhashchange" in window; - if (!isSupported && window.setAttribute) { - window.setAttribute("onhashchange", "return;"); - isSupported = typeof window.onhashchange === "function"; - } - return isSupported; - } - }; -}(jQuery)); \ No newline at end of file diff --git a/junit4-ant/src/main/resources/com/carrotsearch/ant/tasks/junit4/templates/json/js/script.js b/junit4-ant/src/main/resources/com/carrotsearch/ant/tasks/junit4/templates/json/js/script.js deleted file mode 100644 index d5216e82..00000000 --- a/junit4-ant/src/main/resources/com/carrotsearch/ant/tasks/junit4/templates/json/js/script.js +++ /dev/null @@ -1,1240 +0,0 @@ -(function($) { - Array.prototype.peek = function() { - return this[this.length - 1]; - }; - - // Constants - var OK = "OK"; - var FAILURE = "FAILURE"; - var ERROR = "ERROR"; - var IGNORED = "IGNORED"; - var IGNORED_ASSUMPTION = "IGNORED_ASSUMPTION"; - - var statusOrder = [ OK, IGNORED_ASSUMPTION, IGNORED, ERROR, FAILURE ]; - var statusLabels = { - OK: "OK", - FAILURE: "FAIL", - ERROR: "ERROR", - IGNORED: "IGNORED", - IGNORED_ASSUMPTION: "IGNORED" - }; - - // Handles for UI elements - var $table, $search, $tools, $console; - - // Data model - var data, aggregates, project; - - // Application state encoded and parsed from the URL - var state = { - view: "", - order: { - columns: [], - ascendings: [] - }, - search: "", - filter: { - pass: true, - ignored: true, - error: true, - fail: true, - withoutoutput: false - }, - highlight: "", - - encode: function() { - var url = []; - process(null, this); - return url.join("/"); - - function process(property, value) { - if ($.isFunction(value)) { - return; - } - - if ($.isArray(value)) { - $.each(value, function(i, v) { - process(property + "[]", v); - }); - } else if ($.isPlainObject(value)) { - $.each(value, function(key, v) { - process((property ? property + "." : "") + key, v); - }); - } else { - url.push(property, encodeURIComponent(value)); - } - } - }, - - decode: function(string) { - var s = string || window.location.href; - var split = (s.split("#")[1] || "").split("/"); - var decoded = { }; - outer: for (var i = 0; i < split.length / 2; i++) { - var path = decodeURIComponent(split[i*2] || "").split(/\./); - var property = path.shift(); - var target = decoded; - while (path.length > 0) { - if (!$.isPlainObject(target)) { - break outer; - } - if (typeof target[property] == 'undefined') { - target[property] = { }; - } - target = target[property]; - property = path.shift(); - } - - var val = convert(decodeURIComponent(split[i*2 + 1] || "")); - if (property.indexOf("[]") > 0) { - property = property.replace(/[\[\]]/g, ""); - if (typeof target[property] == 'undefined') { - target[property] = []; - } - target[property].push(val); - } else { - target[property] = val; - } - } - delete decoded.encode; - delete decoded.decode; - delete decoded.push; - $.extend(this, decoded); - - function convert(val) { - if (val == "false") { - return false; - } else if (val == "true") { - return true; - } else { - return val; - } - } - }, - - push: function() { - var prev = window.location.hash; - window.location.hash = "#" + this.encode(); - return prev != window.location.hash; - } - }; - var wasDrilldown = false; - - // This function will be called by the JSONP data file - window.testData = function(d) { - data = d.suites; - project = d.junit4; - - var descriptionsById = { }; - - // Index descriptions by id - var htmlId = 0; - for (var i = 0; i < data.length; i++) { - mapDescriptions(data[i].description.children); - } - - // A hack to handle suite-level errors: copy them to the tests array. - eachSuite(data, function(suite) { - if (suite.suiteFailures.length > 0) { - $.each(suite.suiteFailures, function(i, failure) { - suite.tests.push({ - slave: suite.slave, - startTimestamp: suite.startTimestamp, - executionTime: 1, - description: { - methodName: "", - className: suite.description.className - }, - status: ERROR, - testFailures: [ failure ] - }); - }); - } - }); - - // Link object descriptions, split method names into semantic parts - eachTest(data, function (test) { - var description = descriptionsById[test.description]; - if (description) { - test.description = description; - } else { - description = test.description; - } - - description.packageClassName = description.className; - - var methodSplit = description.methodName.split(" "); - description.methodName = methodSplit[0]; - description.methodExtras = methodSplit[1]; - - description.packageClassMethodName = description.className + "." + description.methodName; - - var classSplit = description.className.split("\."); - description.className = classSplit.pop(); - description.packageName = classSplit.join("."); - }); - - // Link descriptions in the event list. - eachSuite(data, function(suite) { - var testsById = map(suite.tests, function(t) { return t.description.id; }); - - var hasOutput = false, hasErrors = false; - $.each(suite.executionEvents, function(j, evt) { - if ("description" in evt) { - if (testsById[evt.description]) { - evt.test = testsById[evt.description]; - } - evt.description = descriptionsById[evt.description]; - } - switch (evt.event) { - case "TEST_STARTED": - hasOutput = false; - break; - - case "APPEND_STDOUT": - hasOutput = true; - break; - - case "APPEND_STDERR": - hasErrors = true; - break; - - case "TEST_FINISHED": - evt.test.hasOutput = hasOutput; - evt.test.hasErrors = hasErrors; - hasOutput = false; - hasErrors = false; - break; - } - }); - }); - - return; - - function mapDescriptions(children) { - for (var j = 0; j < children.length; j++) { - var child = children[j]; - if (typeof child == 'object') { - descriptionsById[children[j].id] = child; - - // Assign a short HTML id to the element. We could use the one - // generated by the runner, but we'd have to map prohibited - // characters, the id would be very long to. - child.htmlId = htmlId; - htmlId++; - if (child.children) { - mapDescriptions(child.children); - } - } else { - children[j] = descriptionsById[child]; - } - } - } - } - - // Table definitions - var tables = (function() { - // Common columns of the aggregated view tables - var aggregatedViewColumns = [ - column("signature", "string", "", true), - numericColumn("count", "Tests"), - { - id: "result", - label: "Result", - sortable: true, - sorting: function(a, b) { - for (var i = 0; i < statusOrder.length; i++) { - var s = statusOrder[statusOrder.length - i]; - if ((a.statuses[s] || 0) != (b.statuses[s] || 0)) { - return (a.statuses[s] || 0) - (b.statuses[s] || 0); - } - } - return 0; - }, - renderer: function(value, html) { - html.push(statusbar(value.statuses, value.total)); - }, - type: "result" - }, - numericColumn("pass", "Pass"), - numericColumn("ignored", "Ign"), - numericColumn("error", "Err"), - numericColumn("failed", "Fail"), - numericColumn("time", "Time [ms]") - ]; - - // Filtering of irrelevant stack trace lines - var stacktracePackagesToHide = [ - 'com.carrotsearch.randomizedtesting.RandomizedRunner', - 'com.carrotsearch.ant.tasks.junit4', - 'java.lang.reflect.Method.invoke', - 'sun.reflect', - 'sun.misc', - 'java.lang', - 'java.util', - 'junit.framework', - 'org.junit.Assert', - 'org.junit.Assume', - 'org.junit.runners', - 'org.junit.runner', - 'org.junit.rules', - 'org.junit.internal' - ]; - var stacktraceFilters = [ ]; - var regexpEscape = /[-[\]{}()*+?.,\\^$|#\s]/g; - for (var i = 0; i < stacktracePackagesToHide.length; i++) { - stacktraceFilters.push(stacktracePackagesToHide[i].replace(regexpEscape, "\\$&")); - } - var stacktraceFilter = new RegExp( "(" + stacktraceFilters.join(")|(") + ")"); - - return { - methods: { - columns: [ - $.extend(column("signature", "string", "Method", true), { - renderer: function(value, html, row) { - if (row.test.hasErrors) { - html.push(""); - } - if (row.test.hasOutput && !row.test.hasErrors) { - html.push(""); - } - - searchHighlighterRenderer(value, html); - - $.each(row.test.testFailures, function(index, failure) { - var lines = failure.stackTrace.replace(/\t/g, "").split(/\n/); - - html.push("
"); - var filtered = false, filteredOut = 0; - html.push("
", escape(lines[0]), "
"); - for (var i = 1; i < lines.length; i++) { - var currentFiltered = stacktraceFilter.test(lines[i]); - if (currentFiltered != filtered) { - html.push("
", - filtered ? "" : "", - ""); - filtered = currentFiltered; - filteredOut = 0; - } else { - filteredOut++; - } - html.push(escape(lines[i]), "
"); - } - html.pop(); // the last extra
- html.push("
"); - }); - } - }), - { - id: "result", - label: "Result", - sortable: true, - sorting: function(a, b) { - if (a == b) { - return 0; - } else { - for (var i = 0; i < statusOrder.length; i++) { - var status = statusOrder[i]; - if (a == status) { - return -1; - } - if (b == status) { - return 1; - } - } - } - }, - renderer: function(value, html) { - html.push("", statusLabels[value] ,"") - }, - type: "result" - }, - numericColumn("slave", "JVM"), - { - id: "timestamp", - label: "Start", - type: "numeric", - renderer: function(value, html) { - var d = new Date(value); - html.push(zero(d.getHours()), ":", zero(d.getMinutes()), ":", zero(d.getSeconds()), ".", zerozero(d.getMilliseconds())); - - function zero(x) { - if (x < 10) { - return "0" + x; - } else { - return x; - } - } - function zerozero(x) { - if (x < 100) { - return "0" + zero(x); - } else { - return x; - } - } - }, - sortable: true - }, - numericColumn("time", "Time [ms]") - ], - rows: function(data, aggregates) { - var rows = []; - eachTest(data, function(test) { - if (!currentFilter(test)) { - return; - } - rows.push({ - id: "t" + test.description.htmlId, - signature: test.description.packageClassMethodName, - result: test.status, - time: test.executionTime, - slave: test.slave, - timestamp: test.startTimestamp, - test: test - }) - }); - return rows; - } - }, - - packages: { - columns: $.extend(true, [], aggregatedViewColumns, [ { label: "Package" } ]), - rows: function(data) { - return aggregatedRows(data, byPackage); - }, - drilldown: function($row) { - drilldown($row, "classes"); - } - }, - - classes: { - columns: $.extend(true, [], aggregatedViewColumns, [ { label: "Class" } ]), - rows: function(data) { - return aggregatedRows(data, byClass); - }, - drilldown: function($row) { - drilldown($row, "methods"); - } - } - }; - - function drilldown($row, view) { - var search = $row.find("td:eq(0)").text(); - $search.val(search); - state.search = search; - state.view = view; - refresh(); - } - - function column(id, type, label, searchable) { - return { - id: id, - sortable: true, - searchable: searchable, - type: type, - label: label, - renderer: searchHighlighterRenderer - }; - } - - function searchHighlighterRenderer(value, html) { - if (this.searchable && state.search) { - var s = state.search.toLowerCase(), sl = s.length, vlc = value.toLowerCase(), vl = value.length; - var start = 0, found = -1; - while ((found = vlc.indexOf(s, start)) >= 0) { - html.push(value.substring(start, found), "", value.substring(found, found + sl), ""); - start = found + sl; - } - html.push(value.substring(start)); - } else { - html.push(escape(value)); - } - } - - function numericColumn(id, label) { - return column(id, "numeric", label, false); - } - - function aggregatedRows(data, aggregateFunction) { - var rows = []; - - var counts = aggregate(data, testCount, { aggregate: aggregateFunction }, currentFilter); - var times = aggregate(data, totalTime, { aggregate: aggregateFunction }, currentFilter); - var statuses = aggregate(data, testCountByStatus, { aggregate: aggregateFunction }, currentFilter); - - if (!statuses.aggregate) { - return rows; - } - $.each(statuses.aggregate, function(signature, statuses) { - rows.push({ - signature: signature, - count: counts.aggregate[signature], - result: { statuses: statuses, total: counts.aggregate[signature] }, - pass: statuses[OK] || 0, - ignored: (statuses[IGNORED] || 0) + (statuses[IGNORED_ASSUMPTION] || 0), - error: statuses[ERROR] || 0, - failed: statuses[FAILURE] || 0, - time: times.aggregate[signature] - }); - }); - return rows; - } - })(); - - // Initialize the table - $(document).ready(function() { - // Create global aggregations - var counts = aggregate(data, testCount, { "global": global, "byStatus": byStatus }, noFilter); - var hasResults = keys(counts).length > 0; - - // Generate markup - var $results = $("#results"); - - // Results heading - var heading = { }; - if (hasResults) { - var numFailures = counts.byStatus[FAILURE]; - var numErrors = counts.byStatus[ERROR]; - if (numFailures > 0 || numErrors > 0) { - var h = []; - if (numErrors > 0) { - h.push(countText(counts.byStatus[ERROR], "test") + " had errors"); - heading.class = ERROR; - } - if (numFailures > 0) { - h.push(countText(counts.byStatus[FAILURE], "test") + " failed"); - heading.class = FAILURE; - } - heading.text = h.join(", "); - } else if (counts.byStatus[ERROR] > 0) { - } else { - heading.text = "tests successful"; - heading.class = OK; - } - } else { - heading.text = "no tests"; - heading.class = OK; - } - - $("header > h1").text(project["project.name"] + ":").append(" " + heading.text + "").parent().addClass(heading.class); - - // Update window title - document.title = $.trim($("header > h1").text()); - - // Results table tools - if (hasResults) { - $tools = $("
\ - \ - show: pass \ - ignored \ - error \ - fail\ - without output\ - view: packages \ - classes \ - methods \ - console\ -
").appendTo($results); - } - - // Results table - $table = $("
").appendTo($results); - if (!hasResults) { - $table.addClass("no-results"); - tableEmpty($table); - return; - } - - - // Console output, invisible by default - $console = $("
").hide().appendTo($results); - $console.delegate('.label', "mouseenter mouseleave", function () { - $(this).parent().parent().nextAll(".out, .err").add(this).toggleClass("highlight"); - $(this).closest(".suitebox").toggleClass("highlight"); - return false; - }); - $console.delegate('.out, .err', "mouseenter mouseleave", function () { - $(this).prevAll(".side").children().eq(0).children().eq(0).add(this).toggleClass("highlight"); - $(this).closest(".suitebox").toggleClass("highlight"); - return false; - }); - $console.delegate('.test.label', "click", function () { - state.highlight = $(this).parent().closest("span.test").attr("id").substring(1); - state.view = "methods"; - state.push(); - return false; - }); - - // Bind listeners - $tools.on("click", ".views", function (e) { - if (!e.target.href) { - return; - } - state.view = $(e.target).attr("href").substring(1); - - // If the search seems to be a fully qualified method/class name, - // strip the the last components to match the view type so that the - // "no test results found" message does not appear. - if (wasDrilldown) { - var split = state.search.split(/\./); - if (split.length > 1) { - if (state.view == "classes") { - strip(split, true); - $search.val(split.join(".")).trigger("drilldownUpdate"); - } else if (state.view == "packages") { - $search.val("").trigger("drilldownUpdate"); - } - } - } - - state.push(); - return false; - - function strip(split, splitIfUpper) { - var method = split[split.length - 1]; - var firstLetter = method.charAt(0); - if ((splitIfUpper && firstLetter == firstLetter.toUpperCase()) || - (!splitIfUpper && firstLetter == firstLetter.toLowerCase())) { - split.pop(); - return true; - } - return false; - } - }); - - $tools.on("click", ".filters", function (e) { - if (!e.target.href) { - return; - } - var filter = $(e.target).attr("href").substring(1); - state.filter[filter] = !state.filter[filter]; - state.push(); - return false; - }); - - $table.on("click", "th.sortable", function (e) { - var newSort = $(this).data("column"); - if (e.ctrlKey) { - // If the ordering already contains the selected column, invert - // the order. If the ordering does not contain the selected column, - // add it at the end of the ordering array. - var matched = false; - for (var i = 0; i < state.order.columns.length; i++) { - if (state.order.columns[i] == newSort) { - state.order.ascendings[i] = !state.order.ascendings[i]; - matched = true; - break; - } - } - if (!matched) { - state.order.columns.push(newSort); - state.order.ascendings.push(true); - } - } else { - // Sort by just by the requested column or change sorting order - var currentAscending = false; - for (var i = 0; i < state.order.columns.length; i++) { - if (state.order.columns[i] == newSort) { - currentAscending = state.order.ascendings[i]; - break; - } - } - state.order.columns = [ newSort ]; - state.order.ascendings = [ !currentAscending ]; - } - state.push(); - return false; - }); - - $table.on("click", "tr.drilldown", function () { - $table.data("source").spec.drilldown($(this)); - wasDrilldown = true; - state.push(); - return false; - }); - - $table.on("click", ".stacktrace", function () { - $(this).closest("td").toggleClass("fullStacktrace"); - return false; - }); - - $table.on("click", ".stdout, .stderr", function () { - state.highlight = $(this).closest("tr").attr("id").substring(1); - state.view = "console"; - state.push(); - return false; - }); - - $search = $tools.find("input[type='search']").on("keyup click drilldownUpdate", function (e) { - var $this = $(this); - typewatch(function () { - var v = $.trim($this.val()); - if (state.search != v) { - if (e.type != "drilldownUpdate") { - wasDrilldown = false; - } - state.search = v; - state.push(); - } - }, e.type == "keyup" ? 500 : 0); - }); - - // If no failures or errors, show package view ordered by package name. - // In case of errors or failures, show method view ordered by status. - if (!(counts.byStatus[FAILURE] > 0 || counts.byStatus[ERROR] > 0)) { - state.view = "packages"; - state.order = { columns: [ "signature" ], ascendings: [ true ] }; - } else { - state.view = "methods"; - state.order = { columns: [ "result" ], ascendings: [ false ] }; - } - - // React to path changes - $(window).pathchange(function () { - state.decode(); - refresh(); - }); - $.pathchange.init({ - useHistory: false - }); - - if (window.location.hash) { - $(window).pathchange(); // decode and refresh - } else { - // Push initial state to the URL, only if the URL does not contain state - if (!state.push()) { - // If the URL didn't change, we need to refresh manually - refresh(); - } - } - return this; - }); - - // Called after UI state changes to refresh the UI - function refresh() { - if (state.view == "console") { - $search.hide(); // No search in console for the time being - $table.hide(); - $console.show(); - refreshConsole(); - } else { - $console.hide(); - $search.show(); - $table.show(); - refreshTable(); - } - - refreshSummary(); - - // Show which view is active - $tools.find("a").removeClass("active").filter("[href^=#" + state.view + "]").addClass("active"); - $("#results").attr("class", state.view); - - // Show which filters are active - $tools.find(".filters a").each(function() { - $(this).toggleClass("active", state.filter[this.hash.substring(1)]); - }); - - // Update search box - $search.val(state.search); - - // Render and scroll to the highlighted element, then reset highlight - if (state.highlight) { - setTimeout(function() { - var offset = $("#" + (state.view == "console" ? "c" : "t") + state.highlight).addClass("highlight").offset().top; - $('html, body').animate({ scrollTop: offset }, 700); - state.highlight = ""; - }, 250); - } - } - - // Refreshes the results table based on the current parameters - function refreshTable() { - table($table.data("source", { - data: data, - order: state.order, - type: state.view, - spec: tables[state.view] - })); - } - - // Refreshes the summary box based on the current parameters - function refreshSummary() { - var counts = aggregate(data, testCount, { "global":global, "byStatus":byStatus }, currentFilter); - var times = aggregate(data, totalTime, { "global":global, "bySlave":bySlave }, currentFilter); - - var $summary = $("#summary").html("").attr("class", ""); - if ((counts.global || 0) == 0) { - return; - } - - $("

").html(tmpl("\ - #{tests} executed in\ - #{time} ms on\ - #{slaves}.", { - tests: countText(counts.global || 0, "test"), - time: times.global, - slaves: countText(keys(times.bySlave).length, "slave") - })).appendTo($summary); - - var html = ""; - if (!(counts.byStatus[FAILURE] > 0 || counts.byStatus[ERROR] > 0)) { - if (counts.byStatus[OK] == counts.global) { - html = "All tests passed."; - } else if ((counts.byStatus[OK] || 0) > 0) { - html = tmpl("No failures, #{passed} passed, #{ignored} ignored.", { - passed:countText(counts.byStatus[OK], "test"), - ignored:countText((counts.byStatus[IGNORED] || 0) + (counts.byStatus[IGNORED_ASSUMPTION] || 0), "test") - }); - } - } else { - var h = []; - if (counts.byStatus[FAILURE] > 0) { - h.push(counts.byStatus[FAILURE] + " failed"); - } - if (counts.byStatus[ERROR] > 0) { - h.push(countText(counts.byStatus[ERROR], "error")); - } - if (counts.byStatus[IGNORED] > 0 || counts.byStatus[IGNORED_ASSUMPTION] > 0) { - h.push((counts.byStatus[IGNORED] || 0) + (counts.byStatus[IGNORED_ASSUMPTION] || 0) + " ignored"); - } - if (counts.byStatus[OK] > 0) { - h.push(counts.byStatus[OK] + " passed"); - } - html = h.join(", "); - } - $("

").html(html).appendTo($summary); - - // Status bar - $summary.append($(statusbar(counts.byStatus, counts.global))); - } - - // Escape a string into HTML. - function htmlEscape(str) { - return String(str) - .replace(/&/g, '&') - .replace(/"/g, '"') - .replace(/'/g, ''') - .replace(//g, '>'); - } - - // Renders the console output - function refreshConsole() { - var html = []; - eachSuite(data, function (suite) { - // Check if we want to show the suite at all. Store this information in the model. - var showSuite = state.filter.withoutoutput; - var outputShown = true; - var insideTest = false; - $.each(suite.executionEvents, function(index, evtobj) { - switch (evtobj.event) { - case "TEST_STARTED": - outputShown = currentFilter(evtobj.test); - insideTest = true; - break; - - case "TEST_FINISHED": - insideTest = false; - break; - - case "APPEND_STDOUT": - case "APPEND_STDERR": - if ((insideTest && outputShown) || !insideTest) { - showSuite = true; - } - outputShown = true; - break; - } - evtobj.shown = outputShown; - }); - - if (!showSuite) { - return true; // continue the loop - } - - html.push("

", - "
", suite.description.displayName, "
", - "
");
-
-      var emptyOutBoxIndex = html.length - 1;
-      $.each(suite.executionEvents, function(index, evtobj) {
-        var shown = evtobj.shown;
-        delete evtobj.shown;
-        if (!shown) {
-          return true; // continue the loop
-        }
-
-        switch (evtobj.event) {
-          case "SUITE_FAILURE":
-            html.push("",
-                      "
suite failure
"); - break; - - case "TEST_STARTED": - // Add a content wrapper for the test... - html.push("", - "", - "
", evtobj.description.methodName, - "
"); - break; - - case "APPEND_STDOUT": - case "APPEND_STDERR": - html.push("", - htmlEscape(evtobj.content), ""); - emptyOutBoxIndex = undefined; - break; - - case "TEST_FINISHED": - html.push("
"); - break; - - default: - // do nothing. - } - }); - if (emptyOutBoxIndex !== undefined) { - html[emptyOutBoxIndex] = html[emptyOutBoxIndex].replace(/outbox/, "outbox empty"); - } - html.push("
"); - }); - if (html.length == 0) { - html.push("
No console output
"); - } - $console.html(html.join("")); - - redrawConnectors(); - } - - function redrawConnectors() { - var tagHeight = $(".outbox .tag").first().height(); - $(".outbox").each(function() { - var $box = $(this); - var $tags = $box.find(".tag"); - if ($tags.size() == 0) { - return true; - } - - // Allow repaint before drawing - setTimeout(function() { - var $canvas = $("") - .attr("width", $box.width() + 20) - .attr("height", $tags.last().offset().top - - $box.offset().top + tagHeight) - .appendTo($box); - - var ctx = $canvas.get(0).getContext('2d'); - ctx.translate(-$canvas.offset().left, -$canvas.offset().top); - - ctx.beginPath(); - ctx.strokeStyle = "#555"; - ctx.lineWidth = 0.5; - $box.find(".marker").each(function() { - var $marker = $(this); - var $label = $marker.next().children().eq(0).children().eq(0); - - var offset = $label.offset(); - var x0 = 0.5 + offset.left + $label.width() + 7.5; - var y0 = 0.5 + offset.top + $label.height() / 2; - var position = $marker.offset(); - var x1 = 1.5 + position.left; - var y1 = 1.5 + position.top + 1.5; - - ctx.moveTo(x0, y0); - ctx.bezierCurveTo((x1 + x0) / 2, y0, - (x1 + x0) / 2, y1, - x1, y1); - }); - ctx.stroke(); - }, 0); - }); - } - - // Renders contents of a table according to the provided spec - function table($table) { - var source = $table.data("source"); - var spec = source.spec, data = source.data, order = source.order; - - var html = [ ]; - - // Get the data - var rows = spec.rows(data); - if (rows.length == 0) { - tableEmpty($table); - return; - } - - var allColumnsById = map(spec.columns, function(c) { return c.id; }); - var orderColumns = [ ]; - for (var i = 0; i < order.columns.length; i++) { - orderColumns[i] = { - column: allColumnsById[order.columns[i]] || spec.columns[0], - ascending: order.ascendings[i] - }; - } - // Last implicit order by signature, makes things more predictable - orderColumns.push({ - column: allColumnsById["signature"], - ascending: true - }); - var orderColumnsById = map (orderColumns, function(o) { return o.column.id; }); - - // Render column headers - html.push("
"); - html.push(""); - $.each(spec.columns, function(i, column) { - html.push(tmpl("", { - type: column.type, - id: column.id, - sort: typeof orderColumnsById[column.id] != 'undefined' ? (orderColumnsById[column.id].ascending ? "asc" : "desc") : "", - label: column.label, - sortable: column.sortable ? "sortable" : "" - })); - }); - html.push(""); - html.push(""); - - // Sort the data - rows.sort(function(a, b) { - for (var i = 0; i < orderColumns.length; i++) { - var column = orderColumns[i].column; - var ordering = column.sorting || function(a, b) { return a > b ? 1 : b > a ? -1 : 0; } - var o = ordering(a[column.id], b[column.id]) * (orderColumns[i].ascending ? 1 : -1); - if (o != 0) { - return o; - } - } - return 0; - }); - - // Render table rows - html.push(""); - var rowStart = spec.drilldown ? ""); - $.each(spec.columns, function(i, column) { - html.push(""); - }); - html.push(""); - }); - html.push(""); - - $table.html(html.join("")); - } - - function tableEmpty($table) { - $table.html(""); - } - - function time(id, code) { - var start = Date.now(); - code(); - console.log(id, Date.now() - start); - } - - function statusbar(counts, total) { - var html = []; - html.push("
    "); - var left = 0; - for (var i = 0; i < statusOrder.length; i++) { - var status = statusOrder[i]; - var count = counts[status]; - if (count > 0) { - var width = (100 * count) / total; - html.push(tmpl("
  • ", { - status: status, - label: statusLabels[status], - pct: width, - count: count, - left: left - })); - left += width; - } - } - html.push("
"); - return html.join(""); - }; - - /** - * Aggregates the data using the provided aggregation function - * and the provided set of key transformer functions. - */ - function aggregate(data, aggregation, keys, filter) { - var a = { }; - eachTest(data, function(test) { - if (!filter(test)) { - return true; - } - - $.each(keys, function(id, key) { - var k = key.call(this, test); - - // If undefined, treat as global key and don't create an extra holder object - if (k === undefined) { - a[id] = aggregation.call(this, test, a[id]); - } else { - a[id] = a[id] || { }; - a[id][k] = aggregation.call(this, test, a[id][k]); - } - }); - }); - return a; - } - - function byStatus(test) { - return test.status; - } - - function bySlave(test) { - return test.slave; - } - - function byPackage(test) { - return test.description.packageName; - } - - function byClass(test) { - return test.description.packageClassName; - } - - function noFilter(test) { - return true; - } - - var searchTargetsByView = { packages: "packageName", classes: "packageClassName", methods: "packageClassMethodName" }; - function signatureSearchFilter(test) { - if ($.trim(state.search).length > 0) { - return test.description[searchTargetsByView[state.view]].toLowerCase().indexOf(state.search.toLowerCase()) >= 0; - } else { - return true; - } - } - - var testStatusToFilter = { OK: "pass", IGNORED: "ignored", IGNORED_ASSUMPTION: "ignored", ERROR: "error", FAILURE: "fail" }; - function statusFilter(test) { - return state.filter[testStatusToFilter[test.status]]; - } - - function currentFilter(test) { - return statusFilter(test) && - (state.view == "console" || signatureSearchFilter(test)) && - (state.view != "console" || state.filter.withoutoutput || test.hasOutput || test.hasErrors); - } - - function global() { - return undefined; - } - - function testCountByStatus(test, current) { - return addOne(current || { }, test.status); - } - - function testCount(test, current) { - return (current || 0) + 1; - } - - function totalTime(test, current) { - return (current || 0) + test.executionTime; - } - - function getOrCreate(set, key, created) { - if (typeof set[key] === "undefined") { - set[key] = created; - } - return set[key]; - } - - function addOne(set, key) { - if (typeof set[key] == "undefined") { - set[key] = 1; - } else { - set[key]++; - } - return set; - } - - function keys(o) { - var a = [ ]; - for (k in o) { - if (o.hasOwnProperty(k)) { - a.push(k); - } - } - return a; - } - - function map(collection, key) { - var result = { }; - $.each(collection, function(i, value) { - result[key(value)] = value; - }); - return result; - } - - function countText(count, noun) { - return count + " " + noun + (count == 1 ? "" : "s"); - } - - function eachTest(data, callback) { - eachSuite(data, function(suite) { - var tests = suite.tests; - for (var j = 0; j < tests.length; j++) { - callback.call(this, tests[j]); - } - }); - } - - function eachSuite(data, callback) { - for (var i = 0; i < data.length; i++) { - callback.call(this, data[i]); - } - } - - - // Inspired by jQuery Simple Templates plugin 1.1.1 - // http://andrew.hedges.name/tmpl - // Dual licensed under the MIT and GPL licenses - function tmpl(tmpl, vals) { - var rgxp, repr; - - tmpl = tmpl || ''; - vals = vals || {}; - - // regular expression for matching placeholders - rgxp = /#\{([^{}]*)}/g; - - // make replacements - repr = function (str, match) { - var m = match.split(":"); - var v = m[0]; - var t = m[1]; - return typeof vals[v] === 'string' && t != "raw" ? e(vals[v]) : vals[v]; - - function e(content) { - return content ? escape(content) : content; - } - }; - - return tmpl.replace(rgxp, repr); - } - - function escape(string) { - return typeof string === 'string' ? string.replace(/&/g, "&").replace(//g, ">") : string; - } - -})(jQuery); -var typewatch = (function(){ - var timer = 0; - return function(callback, ms){ - clearTimeout (timer); - timer = setTimeout(callback, ms); - } -})(); diff --git a/junit4-ant/src/main/resources/com/carrotsearch/ant/tasks/junit4/templates/json/tests-output.jsonp b/junit4-ant/src/main/resources/com/carrotsearch/ant/tasks/junit4/templates/json/tests-output.jsonp deleted file mode 100644 index 146e2f80..00000000 --- a/junit4-ant/src/main/resources/com/carrotsearch/ant/tasks/junit4/templates/json/tests-output.jsonp +++ /dev/null @@ -1,677 +0,0 @@ -testData({ - "junit4": { - "tests.seed": "B19FBD1BB1231191", - "project.name": "Nice project" - }, - "suites": [ - { - "slave": 0, - "startTimestamp": 1331889914622, - "startTimestampDate": "2012-03-16T10:25:14.622", - "executionTime": 109, - "description": { - "id": "id#com.carrotsearch.ant.tasks.junit4.tests.TestBeforeClassError[0]", - "displayName": "com.carrotsearch.ant.tasks.junit4.tests.TestBeforeClassError", - "className": "com.carrotsearch.ant.tasks.junit4.tests.TestBeforeClassError", - "annotations": [], - "children": [ - { - "id": "id#method(com.carrotsearch.ant.tasks.junit4.tests.TestBeforeClassError)[1]", - "displayName": "method(com.carrotsearch.ant.tasks.junit4.tests.TestBeforeClassError)", - "methodName": "method", - "className": "com.carrotsearch.ant.tasks.junit4.tests.TestBeforeClassError", - "annotations": [ - { - "org.junit.Test": { - "timeout": 0, - "expected": "org.junit.Test$None" - } - } - ], - "children": [] - } - ] - }, - "tests": [], - "suiteFailures": [ - { - "throwableClass": "java.lang.RuntimeException", - "throwableString": "java.lang.RuntimeException", - "stackTrace": "java.lang.RuntimeException\n\tat com.carrotsearch.ant.tasks.junit4.tests.TestBeforeClassError.beforeClass(TestBeforeClassError.java:9)\n\tat sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n\tat sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)\n\tat sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)\n\tat java.lang.reflect.Method.invoke(Method.java:597)\n\tat org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)\n\tat org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)\n\tat org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)\n\tat org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:27)\n\tat org.junit.runners.ParentRunner.run(ParentRunner.java:300)\n\tat org.junit.runner.JUnitCore.run(JUnitCore.java:157)\n\tat com.carrotsearch.ant.tasks.junit4.slave.SlaveMain.execute(SlaveMain.java:129)\n\tat com.carrotsearch.ant.tasks.junit4.slave.SlaveMain.main(SlaveMain.java:202)\n\tat com.carrotsearch.ant.tasks.junit4.slave.SlaveMainSafe.main(SlaveMainSafe.java:12)\n", - "kind": "error" - } - ], - "executionEvents": [ - { - "event": "SUITE_FAILURE", - "description": "id#com.carrotsearch.ant.tasks.junit4.tests.TestBeforeClassError[0]", - "failure": { - "throwableClass": "java.lang.RuntimeException", - "throwableString": "java.lang.RuntimeException", - "stackTrace": "java.lang.RuntimeException\n\tat com.carrotsearch.ant.tasks.junit4.tests.TestBeforeClassError.beforeClass(TestBeforeClassError.java:9)\n\tat sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n\tat sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)\n\tat sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)\n\tat java.lang.reflect.Method.invoke(Method.java:597)\n\tat org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)\n\tat org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)\n\tat org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)\n\tat org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:27)\n\tat org.junit.runners.ParentRunner.run(ParentRunner.java:300)\n\tat org.junit.runner.JUnitCore.run(JUnitCore.java:157)\n\tat com.carrotsearch.ant.tasks.junit4.slave.SlaveMain.execute(SlaveMain.java:129)\n\tat com.carrotsearch.ant.tasks.junit4.slave.SlaveMain.main(SlaveMain.java:202)\n\tat com.carrotsearch.ant.tasks.junit4.slave.SlaveMainSafe.main(SlaveMainSafe.java:12)\n", - "kind": "error" - } - } - ] - }, - { - "slave": 0, - "startTimestamp": 1331889914744, - "startTimestampDate": "2012-03-16T10:25:14.744", - "executionTime": 2, - "description": { - "id": "id#com.carrotsearch.ant.tasks.junit4.tests.TestIgnoredSuite[1]", - "displayName": "com.carrotsearch.ant.tasks.junit4.tests.TestIgnoredSuite", - "className": "com.carrotsearch.ant.tasks.junit4.tests.TestIgnoredSuite", - "annotations": [ - { - "org.junit.Ignore": { - "value": "" - } - } - ], - "children": [] - }, - "tests": [], - "suiteFailures": [], - "executionEvents": [] - }, - { - "slave": 0, - "startTimestamp": 1331889914756, - "startTimestampDate": "2012-03-16T10:25:14.756", - "executionTime": 18, - "description": { - "id": "id#com.carrotsearch.ant.tasks.junit4.tests.TestSysstreams[0]", - "displayName": "com.carrotsearch.ant.tasks.junit4.tests.TestSysstreams", - "className": "com.carrotsearch.ant.tasks.junit4.tests.TestSysstreams", - "annotations": [], - "children": [ - { - "id": "id#ok(com.carrotsearch.ant.tasks.junit4.tests.TestSysstreams)[1]", - "displayName": "ok(com.carrotsearch.ant.tasks.junit4.tests.TestSysstreams)", - "methodName": "ok", - "className": "com.carrotsearch.ant.tasks.junit4.tests.TestSysstreams", - "annotations": [ - { - "org.junit.Test": { - "timeout": 0, - "expected": "org.junit.Test$None" - } - } - ], - "children": [] - }, - { - "id": "id#ok_sysout_syserr(com.carrotsearch.ant.tasks.junit4.tests.TestSysstreams)[1]", - "displayName": "ok_sysout_syserr(com.carrotsearch.ant.tasks.junit4.tests.TestSysstreams)", - "methodName": "ok_sysout_syserr", - "className": "com.carrotsearch.ant.tasks.junit4.tests.TestSysstreams", - "annotations": [ - { - "org.junit.Test": { - "timeout": 0, - "expected": "org.junit.Test$None" - } - } - ], - "children": [] - } - ] - }, - "tests": [ - { - "slave": 0, - "startTimestamp": 1331889914769, - "startTimestampDate": "2012-03-16T10:25:14.769", - "executionTime": 1, - "description": "id#ok(com.carrotsearch.ant.tasks.junit4.tests.TestSysstreams)[1]", - "status": "OK", - "testFailures": [] - }, - { - "slave": 0, - "startTimestamp": 1331889914771, - "startTimestampDate": "2012-03-16T10:25:14.771", - "executionTime": 2, - "description": "id#ok_sysout_syserr(com.carrotsearch.ant.tasks.junit4.tests.TestSysstreams)[1]", - "status": "OK", - "testFailures": [] - } - ], - "suiteFailures": [], - "executionEvents": [ - { - "event": "TEST_STARTED", - "description": "id#ok(com.carrotsearch.ant.tasks.junit4.tests.TestSysstreams)[1]" - }, - { - "event": "TEST_FINISHED", - "description": "id#ok(com.carrotsearch.ant.tasks.junit4.tests.TestSysstreams)[1]" - }, - { - "event": "TEST_STARTED", - "description": "id#ok_sysout_syserr(com.carrotsearch.ant.tasks.junit4.tests.TestSysstreams)[1]" - }, - { - "event": "APPEND_STDOUT", - "content": "sysout" - }, - { - "event": "APPEND_STDERR", - "content": "syserr" - }, - { - "event": "APPEND_STDOUT", - "content": "-sysout-contd." - }, - { - "event": "APPEND_STDERR", - "content": "-syserr-contd." - }, - { - "event": "TEST_FINISHED", - "description": "id#ok_sysout_syserr(com.carrotsearch.ant.tasks.junit4.tests.TestSysstreams)[1]" - } - ] - }, - { - "slave": 0, - "startTimestamp": 1331889914800, - "startTimestampDate": "2012-03-16T10:25:14.800", - "executionTime": 93, - "description": { - "id": "id#com.carrotsearch.ant.tasks.junit4.tests.TestStatuses[0]", - "displayName": "com.carrotsearch.ant.tasks.junit4.tests.TestStatuses", - "className": "com.carrotsearch.ant.tasks.junit4.tests.TestStatuses", - "annotations": [], - "children": [ - { - "id": "id#failure(com.carrotsearch.ant.tasks.junit4.tests.TestStatuses)[1]", - "displayName": "failure(com.carrotsearch.ant.tasks.junit4.tests.TestStatuses)", - "methodName": "failure", - "className": "com.carrotsearch.ant.tasks.junit4.tests.TestStatuses", - "annotations": [ - { - "org.junit.Test": { - "timeout": 0, - "expected": "org.junit.Test$None" - } - } - ], - "children": [] - }, - { - "id": "id#error(com.carrotsearch.ant.tasks.junit4.tests.TestStatuses)[1]", - "displayName": "error(com.carrotsearch.ant.tasks.junit4.tests.TestStatuses)", - "methodName": "error", - "className": "com.carrotsearch.ant.tasks.junit4.tests.TestStatuses", - "annotations": [ - { - "org.junit.Test": { - "timeout": 0, - "expected": "org.junit.Test$None" - } - } - ], - "children": [] - }, - { - "id": "id#ignored(com.carrotsearch.ant.tasks.junit4.tests.TestStatuses)[2]", - "displayName": "ignored(com.carrotsearch.ant.tasks.junit4.tests.TestStatuses)", - "methodName": "ignored", - "className": "com.carrotsearch.ant.tasks.junit4.tests.TestStatuses", - "annotations": [ - { - "org.junit.Test": { - "timeout": 0, - "expected": "org.junit.Test$None" - } - }, - { - "org.junit.Ignore": { - "value": "" - } - } - ], - "children": [] - }, - { - "id": "id#ok(com.carrotsearch.ant.tasks.junit4.tests.TestStatuses)[1]", - "displayName": "ok(com.carrotsearch.ant.tasks.junit4.tests.TestStatuses)", - "methodName": "ok", - "className": "com.carrotsearch.ant.tasks.junit4.tests.TestStatuses", - "annotations": [ - { - "org.junit.Test": { - "timeout": 0, - "expected": "org.junit.Test$None" - } - } - ], - "children": [] - }, - { - "id": "id#ignored_a(com.carrotsearch.ant.tasks.junit4.tests.TestStatuses)[1]", - "displayName": "ignored_a(com.carrotsearch.ant.tasks.junit4.tests.TestStatuses)", - "methodName": "ignored_a", - "className": "com.carrotsearch.ant.tasks.junit4.tests.TestStatuses", - "annotations": [ - { - "org.junit.Test": { - "timeout": 0, - "expected": "org.junit.Test$None" - } - } - ], - "children": [] - } - ] - }, - "tests": [ - { - "slave": 0, - "startTimestamp": 1331889914811, - "startTimestampDate": "2012-03-16T10:25:14.811", - "executionTime": 15, - "description": "id#failure(com.carrotsearch.ant.tasks.junit4.tests.TestStatuses)[1]", - "status": "FAILURE", - "testFailures": [ - { - "throwableClass": "java.lang.AssertionError", - "throwableString": "java.lang.AssertionError", - "stackTrace": "java.lang.AssertionError\n\tat org.junit.Assert.fail(Assert.java:92)\n\tat org.junit.Assert.assertTrue(Assert.java:43)\n\tat org.junit.Assert.assertTrue(Assert.java:54)\n\tat com.carrotsearch.ant.tasks.junit4.tests.TestStatuses.failure(TestStatuses.java:24)\n\tat sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n\tat sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)\n\tat sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)\n\tat java.lang.reflect.Method.invoke(Method.java:597)\n\tat org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)\n\tat org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)\n\tat org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)\n\tat org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)\n\tat org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)\n\tat org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)\n\tat org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)\n\tat org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)\n\tat org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)\n\tat org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)\n\tat org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)\n\tat org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)\n\tat org.junit.runners.ParentRunner.run(ParentRunner.java:300)\n\tat org.junit.runner.JUnitCore.run(JUnitCore.java:157)\n\tat com.carrotsearch.ant.tasks.junit4.slave.SlaveMain.execute(SlaveMain.java:129)\n\tat com.carrotsearch.ant.tasks.junit4.slave.SlaveMain.main(SlaveMain.java:202)\n\tat com.carrotsearch.ant.tasks.junit4.slave.SlaveMainSafe.main(SlaveMainSafe.java:12)\n", - "kind": "assertion" - } - ] - }, - { - "slave": 0, - "startTimestamp": 1331889914829, - "startTimestampDate": "2012-03-16T10:25:14.829", - "executionTime": 14, - "description": "id#error(com.carrotsearch.ant.tasks.junit4.tests.TestStatuses)[1]", - "status": "ERROR", - "testFailures": [ - { - "throwableClass": "java.lang.RuntimeException", - "throwableString": "java.lang.RuntimeException", - "stackTrace": "java.lang.RuntimeException\n\tat com.carrotsearch.ant.tasks.junit4.tests.TestStatuses.error(TestStatuses.java:29)\n\tat sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n\tat sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)\n\tat sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)\n\tat java.lang.reflect.Method.invoke(Method.java:597)\n\tat org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)\n\tat org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)\n\tat org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)\n\tat org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)\n\tat org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)\n\tat org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)\n\tat org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)\n\tat org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)\n\tat org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)\n\tat org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)\n\tat org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)\n\tat org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)\n\tat org.junit.runners.ParentRunner.run(ParentRunner.java:300)\n\tat org.junit.runner.JUnitCore.run(JUnitCore.java:157)\n\tat com.carrotsearch.ant.tasks.junit4.slave.SlaveMain.execute(SlaveMain.java:129)\n\tat com.carrotsearch.ant.tasks.junit4.slave.SlaveMain.main(SlaveMain.java:202)\n\tat com.carrotsearch.ant.tasks.junit4.slave.SlaveMainSafe.main(SlaveMainSafe.java:12)\n", - "kind": "error" - } - ] - }, - { - "slave": 0, - "startTimestamp": 1331889914845, - "startTimestampDate": "2012-03-16T10:25:14.845", - "executionTime": 0, - "description": "id#ignored(com.carrotsearch.ant.tasks.junit4.tests.TestStatuses)[2]", - "status": "IGNORED", - "testFailures": [] - }, - { - "slave": 0, - "startTimestamp": 1331889914846, - "startTimestampDate": "2012-03-16T10:25:14.846", - "executionTime": 0, - "description": "id#ok(com.carrotsearch.ant.tasks.junit4.tests.TestStatuses)[1]", - "status": "OK", - "testFailures": [] - }, - { - "slave": 0, - "startTimestamp": 1331889914847, - "startTimestampDate": "2012-03-16T10:25:14.847", - "executionTime": 45, - "description": "id#ignored_a(com.carrotsearch.ant.tasks.junit4.tests.TestStatuses)[1]", - "status": "IGNORED_ASSUMPTION", - "testFailures": [ - { - "throwableClass": "org.junit.internal.AssumptionViolatedException", - "throwableString": "org.junit.internal.AssumptionViolatedException: got: \u003cfalse\u003e, expected: is \u003ctrue\u003e", - "stackTrace": "org.junit.internal.AssumptionViolatedException: got: \u003cfalse\u003e, expected: is \u003ctrue\u003e\n\tat org.junit.Assume.assumeThat(Assume.java:70)\n\tat org.junit.Assume.assumeTrue(Assume.java:39)\n\tat com.carrotsearch.ant.tasks.junit4.tests.TestStatuses.ignored_a(TestStatuses.java:19)\n\tat sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n\tat sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)\n\tat sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)\n\tat java.lang.reflect.Method.invoke(Method.java:597)\n\tat org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)\n\tat org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)\n\tat org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)\n\tat org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)\n\tat org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)\n\tat org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)\n\tat org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)\n\tat org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)\n\tat org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)\n\tat org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)\n\tat org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)\n\tat org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)\n\tat org.junit.runners.ParentRunner.run(ParentRunner.java:300)\n\tat org.junit.runner.JUnitCore.run(JUnitCore.java:157)\n\tat com.carrotsearch.ant.tasks.junit4.slave.SlaveMain.execute(SlaveMain.java:129)\n\tat com.carrotsearch.ant.tasks.junit4.slave.SlaveMain.main(SlaveMain.java:202)\n\tat com.carrotsearch.ant.tasks.junit4.slave.SlaveMainSafe.main(SlaveMainSafe.java:12)\n", - "kind": "assumption" - } - ] - } - ], - "suiteFailures": [], - "executionEvents": [ - { - "event": "TEST_STARTED", - "description": "id#failure(com.carrotsearch.ant.tasks.junit4.tests.TestStatuses)[1]" - }, - { - "event": "TEST_FAILURE", - "description": "id#failure(com.carrotsearch.ant.tasks.junit4.tests.TestStatuses)[1]", - "failure": { - "throwableClass": "java.lang.AssertionError", - "throwableString": "java.lang.AssertionError", - "stackTrace": "java.lang.AssertionError\n\tat org.junit.Assert.fail(Assert.java:92)\n\tat org.junit.Assert.assertTrue(Assert.java:43)\n\tat org.junit.Assert.assertTrue(Assert.java:54)\n\tat com.carrotsearch.ant.tasks.junit4.tests.TestStatuses.failure(TestStatuses.java:24)\n\tat sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n\tat sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)\n\tat sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)\n\tat java.lang.reflect.Method.invoke(Method.java:597)\n\tat org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)\n\tat org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)\n\tat org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)\n\tat org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)\n\tat org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)\n\tat org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)\n\tat org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)\n\tat org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)\n\tat org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)\n\tat org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)\n\tat org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)\n\tat org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)\n\tat org.junit.runners.ParentRunner.run(ParentRunner.java:300)\n\tat org.junit.runner.JUnitCore.run(JUnitCore.java:157)\n\tat com.carrotsearch.ant.tasks.junit4.slave.SlaveMain.execute(SlaveMain.java:129)\n\tat com.carrotsearch.ant.tasks.junit4.slave.SlaveMain.main(SlaveMain.java:202)\n\tat com.carrotsearch.ant.tasks.junit4.slave.SlaveMainSafe.main(SlaveMainSafe.java:12)\n", - "kind": "assertion" - } - }, - { - "event": "TEST_FINISHED", - "description": "id#failure(com.carrotsearch.ant.tasks.junit4.tests.TestStatuses)[1]" - }, - { - "event": "TEST_STARTED", - "description": "id#error(com.carrotsearch.ant.tasks.junit4.tests.TestStatuses)[1]" - }, - { - "event": "TEST_FAILURE", - "description": "id#error(com.carrotsearch.ant.tasks.junit4.tests.TestStatuses)[1]", - "failure": { - "throwableClass": "java.lang.RuntimeException", - "throwableString": "java.lang.RuntimeException", - "stackTrace": "java.lang.RuntimeException\n\tat com.carrotsearch.ant.tasks.junit4.tests.TestStatuses.error(TestStatuses.java:29)\n\tat sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n\tat sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)\n\tat sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)\n\tat java.lang.reflect.Method.invoke(Method.java:597)\n\tat org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)\n\tat org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)\n\tat org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)\n\tat org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)\n\tat org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)\n\tat org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)\n\tat org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)\n\tat org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)\n\tat org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)\n\tat org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)\n\tat org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)\n\tat org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)\n\tat org.junit.runners.ParentRunner.run(ParentRunner.java:300)\n\tat org.junit.runner.JUnitCore.run(JUnitCore.java:157)\n\tat com.carrotsearch.ant.tasks.junit4.slave.SlaveMain.execute(SlaveMain.java:129)\n\tat com.carrotsearch.ant.tasks.junit4.slave.SlaveMain.main(SlaveMain.java:202)\n\tat com.carrotsearch.ant.tasks.junit4.slave.SlaveMainSafe.main(SlaveMainSafe.java:12)\n", - "kind": "error" - } - }, - { - "event": "TEST_FINISHED", - "description": "id#error(com.carrotsearch.ant.tasks.junit4.tests.TestStatuses)[1]" - }, - { - "event": "TEST_IGNORED", - "description": "id#ignored(com.carrotsearch.ant.tasks.junit4.tests.TestStatuses)[2]" - }, - { - "event": "TEST_STARTED", - "description": "id#ok(com.carrotsearch.ant.tasks.junit4.tests.TestStatuses)[1]" - }, - { - "event": "TEST_FINISHED", - "description": "id#ok(com.carrotsearch.ant.tasks.junit4.tests.TestStatuses)[1]" - }, - { - "event": "TEST_STARTED", - "description": "id#ignored_a(com.carrotsearch.ant.tasks.junit4.tests.TestStatuses)[1]" - }, - { - "event": "TEST_IGNORED_ASSUMPTION", - "description": "id#ignored_a(com.carrotsearch.ant.tasks.junit4.tests.TestStatuses)[1]", - "failure": { - "throwableClass": "org.junit.internal.AssumptionViolatedException", - "throwableString": "org.junit.internal.AssumptionViolatedException: got: \u003cfalse\u003e, expected: is \u003ctrue\u003e", - "stackTrace": "org.junit.internal.AssumptionViolatedException: got: \u003cfalse\u003e, expected: is \u003ctrue\u003e\n\tat org.junit.Assume.assumeThat(Assume.java:70)\n\tat org.junit.Assume.assumeTrue(Assume.java:39)\n\tat com.carrotsearch.ant.tasks.junit4.tests.TestStatuses.ignored_a(TestStatuses.java:19)\n\tat sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n\tat sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)\n\tat sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)\n\tat java.lang.reflect.Method.invoke(Method.java:597)\n\tat org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)\n\tat org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)\n\tat org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)\n\tat org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)\n\tat org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)\n\tat org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)\n\tat org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)\n\tat org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)\n\tat org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)\n\tat org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)\n\tat org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)\n\tat org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)\n\tat org.junit.runners.ParentRunner.run(ParentRunner.java:300)\n\tat org.junit.runner.JUnitCore.run(JUnitCore.java:157)\n\tat com.carrotsearch.ant.tasks.junit4.slave.SlaveMain.execute(SlaveMain.java:129)\n\tat com.carrotsearch.ant.tasks.junit4.slave.SlaveMain.main(SlaveMain.java:202)\n\tat com.carrotsearch.ant.tasks.junit4.slave.SlaveMainSafe.main(SlaveMainSafe.java:12)\n", - "kind": "assumption" - } - }, - { - "event": "TEST_FINISHED", - "description": "id#ignored_a(com.carrotsearch.ant.tasks.junit4.tests.TestStatuses)[1]" - } - ] - }, - { - "slave": 0, - "startTimestamp": 1331889915015, - "startTimestampDate": "2012-03-16T10:25:15.015", - "executionTime": 90, - "description": { - "id": "id#com.carrotsearch.ant.tasks.junit4.tests.TestHierarchicalSuiteDescription[2]", - "displayName": "com.carrotsearch.ant.tasks.junit4.tests.TestHierarchicalSuiteDescription", - "className": "com.carrotsearch.ant.tasks.junit4.tests.TestHierarchicalSuiteDescription", - "annotations": [ - { - "org.junit.runner.RunWith": { - "value": "org.junit.runners.Suite" - } - }, - { - "org.junit.runners.Suite$SuiteClasses": { - "value": [ - "com.carrotsearch.ant.tasks.junit4.tests.TestHierarchicalSuiteDescription$Sub1", - "com.carrotsearch.ant.tasks.junit4.tests.TestHierarchicalSuiteDescription$Sub2", - "com.carrotsearch.ant.tasks.junit4.tests.TestHierarchicalSuiteDescription$Sub3" - ] - } - } - ], - "children": [ - { - "id": "id#com.carrotsearch.ant.tasks.junit4.tests.TestHierarchicalSuiteDescription$Sub1[0]", - "displayName": "com.carrotsearch.ant.tasks.junit4.tests.TestHierarchicalSuiteDescription$Sub1", - "className": "com.carrotsearch.ant.tasks.junit4.tests.TestHierarchicalSuiteDescription$Sub1", - "annotations": [], - "children": [ - { - "id": "id#method1(com.carrotsearch.ant.tasks.junit4.tests.TestHierarchicalSuiteDescription$Sub1)[1]", - "displayName": "method1(com.carrotsearch.ant.tasks.junit4.tests.TestHierarchicalSuiteDescription$Sub1)", - "methodName": "method1", - "className": "com.carrotsearch.ant.tasks.junit4.tests.TestHierarchicalSuiteDescription$Sub1", - "annotations": [ - { - "org.junit.Test": { - "timeout": 0, - "expected": "org.junit.Test$None" - } - } - ], - "children": [] - } - ] - }, - { - "id": "id#com.carrotsearch.ant.tasks.junit4.tests.TestHierarchicalSuiteDescription$Sub2[0]", - "displayName": "com.carrotsearch.ant.tasks.junit4.tests.TestHierarchicalSuiteDescription$Sub2", - "className": "com.carrotsearch.ant.tasks.junit4.tests.TestHierarchicalSuiteDescription$Sub2", - "annotations": [], - "children": [ - { - "id": "id#method1(com.carrotsearch.ant.tasks.junit4.tests.TestHierarchicalSuiteDescription$Sub2)[1]", - "displayName": "method1(com.carrotsearch.ant.tasks.junit4.tests.TestHierarchicalSuiteDescription$Sub2)", - "methodName": "method1", - "className": "com.carrotsearch.ant.tasks.junit4.tests.TestHierarchicalSuiteDescription$Sub2", - "annotations": [ - { - "org.junit.Test": { - "timeout": 0, - "expected": "org.junit.Test$None" - } - } - ], - "children": [] - } - ] - }, - { - "id": "id#com.carrotsearch.ant.tasks.junit4.tests.TestHierarchicalSuiteDescription$Sub3[0]", - "displayName": "com.carrotsearch.ant.tasks.junit4.tests.TestHierarchicalSuiteDescription$Sub3", - "className": "com.carrotsearch.ant.tasks.junit4.tests.TestHierarchicalSuiteDescription$Sub3", - "annotations": [], - "children": [ - { - "id": "id#method1(com.carrotsearch.ant.tasks.junit4.tests.TestHierarchicalSuiteDescription$Sub3)[1]", - "displayName": "method1(com.carrotsearch.ant.tasks.junit4.tests.TestHierarchicalSuiteDescription$Sub3)", - "methodName": "method1", - "className": "com.carrotsearch.ant.tasks.junit4.tests.TestHierarchicalSuiteDescription$Sub3", - "annotations": [ - { - "org.junit.Test": { - "timeout": 0, - "expected": "org.junit.Test$None" - } - } - ], - "children": [] - } - ] - } - ] - }, - "tests": [ - { - "slave": 0, - "startTimestamp": 1331889915049, - "startTimestampDate": "2012-03-16T10:25:15.049", - "executionTime": 0, - "description": "id#method1(com.carrotsearch.ant.tasks.junit4.tests.TestHierarchicalSuiteDescription$Sub2)[1]", - "status": "OK", - "testFailures": [] - }, - { - "slave": 0, - "startTimestamp": 1331889915086, - "startTimestampDate": "2012-03-16T10:25:15.086", - "executionTime": 4, - "description": "id#method1(com.carrotsearch.ant.tasks.junit4.tests.TestHierarchicalSuiteDescription$Sub3)[1]", - "status": "ERROR", - "testFailures": [ - { - "throwableClass": "java.lang.RuntimeException", - "throwableString": "java.lang.RuntimeException", - "stackTrace": "java.lang.RuntimeException\n\tat com.carrotsearch.ant.tasks.junit4.tests.TestHierarchicalSuiteDescription$Sub3.method1(TestHierarchicalSuiteDescription.java:40)\n\tat sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n\tat sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)\n\tat sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)\n\tat java.lang.reflect.Method.invoke(Method.java:597)\n\tat org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)\n\tat org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)\n\tat org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)\n\tat org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)\n\tat org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)\n\tat org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)\n\tat org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)\n\tat org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)\n\tat org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)\n\tat org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)\n\tat org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)\n\tat org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)\n\tat org.junit.runners.ParentRunner.run(ParentRunner.java:300)\n\tat org.junit.runners.Suite.runChild(Suite.java:128)\n\tat org.junit.runners.Suite.runChild(Suite.java:24)\n\tat org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)\n\tat org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)\n\tat org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)\n\tat org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)\n\tat org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)\n\tat org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:30)\n\tat org.junit.runners.ParentRunner.run(ParentRunner.java:300)\n\tat org.junit.runner.JUnitCore.run(JUnitCore.java:157)\n\tat com.carrotsearch.ant.tasks.junit4.slave.SlaveMain.execute(SlaveMain.java:129)\n\tat com.carrotsearch.ant.tasks.junit4.slave.SlaveMain.main(SlaveMain.java:202)\n\tat com.carrotsearch.ant.tasks.junit4.slave.SlaveMainSafe.main(SlaveMainSafe.java:12)\n", - "kind": "error" - } - ] - } - ], - "suiteFailures": [ - { - "throwableClass": "java.lang.RuntimeException", - "throwableString": "java.lang.RuntimeException", - "stackTrace": "java.lang.RuntimeException\n\tat com.carrotsearch.ant.tasks.junit4.tests.TestHierarchicalSuiteDescription$Sub1.beforeClass(TestHierarchicalSuiteDescription.java:23)\n\tat sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n\tat sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)\n\tat sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)\n\tat java.lang.reflect.Method.invoke(Method.java:597)\n\tat org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)\n\tat org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)\n\tat org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)\n\tat org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:27)\n\tat org.junit.runners.ParentRunner.run(ParentRunner.java:300)\n\tat org.junit.runners.Suite.runChild(Suite.java:128)\n\tat org.junit.runners.Suite.runChild(Suite.java:24)\n\tat org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)\n\tat org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)\n\tat org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)\n\tat org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)\n\tat org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)\n\tat org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:30)\n\tat org.junit.runners.ParentRunner.run(ParentRunner.java:300)\n\tat org.junit.runner.JUnitCore.run(JUnitCore.java:157)\n\tat com.carrotsearch.ant.tasks.junit4.slave.SlaveMain.execute(SlaveMain.java:129)\n\tat com.carrotsearch.ant.tasks.junit4.slave.SlaveMain.main(SlaveMain.java:202)\n\tat com.carrotsearch.ant.tasks.junit4.slave.SlaveMainSafe.main(SlaveMainSafe.java:12)\n", - "kind": "error" - }, - { - "throwableClass": "java.lang.RuntimeException", - "throwableString": "java.lang.RuntimeException", - "stackTrace": "java.lang.RuntimeException\n\tat com.carrotsearch.ant.tasks.junit4.tests.TestHierarchicalSuiteDescription$Sub2.afterClass(TestHierarchicalSuiteDescription.java:33)\n\tat sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n\tat sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)\n\tat sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)\n\tat java.lang.reflect.Method.invoke(Method.java:597)\n\tat org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)\n\tat org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)\n\tat org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)\n\tat org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:36)\n\tat org.junit.runners.ParentRunner.run(ParentRunner.java:300)\n\tat org.junit.runners.Suite.runChild(Suite.java:128)\n\tat org.junit.runners.Suite.runChild(Suite.java:24)\n\tat org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)\n\tat org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)\n\tat org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)\n\tat org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)\n\tat org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)\n\tat org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:30)\n\tat org.junit.runners.ParentRunner.run(ParentRunner.java:300)\n\tat org.junit.runner.JUnitCore.run(JUnitCore.java:157)\n\tat com.carrotsearch.ant.tasks.junit4.slave.SlaveMain.execute(SlaveMain.java:129)\n\tat com.carrotsearch.ant.tasks.junit4.slave.SlaveMain.main(SlaveMain.java:202)\n\tat com.carrotsearch.ant.tasks.junit4.slave.SlaveMainSafe.main(SlaveMainSafe.java:12)\n", - "kind": "error" - }, - { - "throwableClass": "java.lang.RuntimeException", - "throwableString": "java.lang.RuntimeException", - "stackTrace": "java.lang.RuntimeException\n\tat com.carrotsearch.ant.tasks.junit4.tests.TestHierarchicalSuiteDescription.afterClass(TestHierarchicalSuiteDescription.java:46)\n\tat sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n\tat sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)\n\tat sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)\n\tat java.lang.reflect.Method.invoke(Method.java:597)\n\tat org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)\n\tat org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)\n\tat org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)\n\tat org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:36)\n\tat org.junit.runners.ParentRunner.run(ParentRunner.java:300)\n\tat org.junit.runner.JUnitCore.run(JUnitCore.java:157)\n\tat com.carrotsearch.ant.tasks.junit4.slave.SlaveMain.execute(SlaveMain.java:129)\n\tat com.carrotsearch.ant.tasks.junit4.slave.SlaveMain.main(SlaveMain.java:202)\n\tat com.carrotsearch.ant.tasks.junit4.slave.SlaveMainSafe.main(SlaveMainSafe.java:12)\n", - "kind": "error" - } - ], - "executionEvents": [ - { - "event": "TEST_FAILURE", - "description": "id#com.carrotsearch.ant.tasks.junit4.tests.TestHierarchicalSuiteDescription$Sub1[0]", - "failure": { - "throwableClass": "java.lang.RuntimeException", - "throwableString": "java.lang.RuntimeException", - "stackTrace": "java.lang.RuntimeException\n\tat com.carrotsearch.ant.tasks.junit4.tests.TestHierarchicalSuiteDescription$Sub1.beforeClass(TestHierarchicalSuiteDescription.java:23)\n\tat sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n\tat sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)\n\tat sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)\n\tat java.lang.reflect.Method.invoke(Method.java:597)\n\tat org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)\n\tat org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)\n\tat org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)\n\tat org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:27)\n\tat org.junit.runners.ParentRunner.run(ParentRunner.java:300)\n\tat org.junit.runners.Suite.runChild(Suite.java:128)\n\tat org.junit.runners.Suite.runChild(Suite.java:24)\n\tat org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)\n\tat org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)\n\tat org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)\n\tat org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)\n\tat org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)\n\tat org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:30)\n\tat org.junit.runners.ParentRunner.run(ParentRunner.java:300)\n\tat org.junit.runner.JUnitCore.run(JUnitCore.java:157)\n\tat com.carrotsearch.ant.tasks.junit4.slave.SlaveMain.execute(SlaveMain.java:129)\n\tat com.carrotsearch.ant.tasks.junit4.slave.SlaveMain.main(SlaveMain.java:202)\n\tat com.carrotsearch.ant.tasks.junit4.slave.SlaveMainSafe.main(SlaveMainSafe.java:12)\n", - "kind": "error" - } - }, - { - "event": "TEST_STARTED", - "description": "id#method1(com.carrotsearch.ant.tasks.junit4.tests.TestHierarchicalSuiteDescription$Sub2)[1]" - }, - { - "event": "TEST_FINISHED", - "description": "id#method1(com.carrotsearch.ant.tasks.junit4.tests.TestHierarchicalSuiteDescription$Sub2)[1]" - }, - { - "event": "TEST_FAILURE", - "description": "id#com.carrotsearch.ant.tasks.junit4.tests.TestHierarchicalSuiteDescription$Sub2[0]", - "failure": { - "throwableClass": "java.lang.RuntimeException", - "throwableString": "java.lang.RuntimeException", - "stackTrace": "java.lang.RuntimeException\n\tat com.carrotsearch.ant.tasks.junit4.tests.TestHierarchicalSuiteDescription$Sub2.afterClass(TestHierarchicalSuiteDescription.java:33)\n\tat sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n\tat sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)\n\tat sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)\n\tat java.lang.reflect.Method.invoke(Method.java:597)\n\tat org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)\n\tat org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)\n\tat org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)\n\tat org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:36)\n\tat org.junit.runners.ParentRunner.run(ParentRunner.java:300)\n\tat org.junit.runners.Suite.runChild(Suite.java:128)\n\tat org.junit.runners.Suite.runChild(Suite.java:24)\n\tat org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)\n\tat org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)\n\tat org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)\n\tat org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)\n\tat org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)\n\tat org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:30)\n\tat org.junit.runners.ParentRunner.run(ParentRunner.java:300)\n\tat org.junit.runner.JUnitCore.run(JUnitCore.java:157)\n\tat com.carrotsearch.ant.tasks.junit4.slave.SlaveMain.execute(SlaveMain.java:129)\n\tat com.carrotsearch.ant.tasks.junit4.slave.SlaveMain.main(SlaveMain.java:202)\n\tat com.carrotsearch.ant.tasks.junit4.slave.SlaveMainSafe.main(SlaveMainSafe.java:12)\n", - "kind": "error" - } - }, - { - "event": "TEST_STARTED", - "description": "id#method1(com.carrotsearch.ant.tasks.junit4.tests.TestHierarchicalSuiteDescription$Sub3)[1]" - }, - { - "event": "TEST_FAILURE", - "description": "id#method1(com.carrotsearch.ant.tasks.junit4.tests.TestHierarchicalSuiteDescription$Sub3)[1]", - "failure": { - "throwableClass": "java.lang.RuntimeException", - "throwableString": "java.lang.RuntimeException", - "stackTrace": "java.lang.RuntimeException\n\tat com.carrotsearch.ant.tasks.junit4.tests.TestHierarchicalSuiteDescription$Sub3.method1(TestHierarchicalSuiteDescription.java:40)\n\tat sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n\tat sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)\n\tat sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)\n\tat java.lang.reflect.Method.invoke(Method.java:597)\n\tat org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)\n\tat org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)\n\tat org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)\n\tat org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)\n\tat org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)\n\tat org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)\n\tat org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)\n\tat org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)\n\tat org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)\n\tat org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)\n\tat org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)\n\tat org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)\n\tat org.junit.runners.ParentRunner.run(ParentRunner.java:300)\n\tat org.junit.runners.Suite.runChild(Suite.java:128)\n\tat org.junit.runners.Suite.runChild(Suite.java:24)\n\tat org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)\n\tat org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)\n\tat org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)\n\tat org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)\n\tat org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)\n\tat org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:30)\n\tat org.junit.runners.ParentRunner.run(ParentRunner.java:300)\n\tat org.junit.runner.JUnitCore.run(JUnitCore.java:157)\n\tat com.carrotsearch.ant.tasks.junit4.slave.SlaveMain.execute(SlaveMain.java:129)\n\tat com.carrotsearch.ant.tasks.junit4.slave.SlaveMain.main(SlaveMain.java:202)\n\tat com.carrotsearch.ant.tasks.junit4.slave.SlaveMainSafe.main(SlaveMainSafe.java:12)\n", - "kind": "error" - } - }, - { - "event": "TEST_FINISHED", - "description": "id#method1(com.carrotsearch.ant.tasks.junit4.tests.TestHierarchicalSuiteDescription$Sub3)[1]" - }, - { - "event": "SUITE_FAILURE", - "description": "id#com.carrotsearch.ant.tasks.junit4.tests.TestHierarchicalSuiteDescription[2]", - "failure": { - "throwableClass": "java.lang.RuntimeException", - "throwableString": "java.lang.RuntimeException", - "stackTrace": "java.lang.RuntimeException\n\tat com.carrotsearch.ant.tasks.junit4.tests.TestHierarchicalSuiteDescription.afterClass(TestHierarchicalSuiteDescription.java:46)\n\tat sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n\tat sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)\n\tat sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)\n\tat java.lang.reflect.Method.invoke(Method.java:597)\n\tat org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)\n\tat org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)\n\tat org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)\n\tat org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:36)\n\tat org.junit.runners.ParentRunner.run(ParentRunner.java:300)\n\tat org.junit.runner.JUnitCore.run(JUnitCore.java:157)\n\tat com.carrotsearch.ant.tasks.junit4.slave.SlaveMain.execute(SlaveMain.java:129)\n\tat com.carrotsearch.ant.tasks.junit4.slave.SlaveMain.main(SlaveMain.java:202)\n\tat com.carrotsearch.ant.tasks.junit4.slave.SlaveMainSafe.main(SlaveMainSafe.java:12)\n", - "kind": "error" - } - } - ] - } - ], - "slaves": { - "0": { - "id": 0, - "jvmName": "Java HotSpot(TM) 64-Bit Server VM, 16.3-b01", - "charset": "UTF-8", - "commandLine": "/home/dweiss/Applications/java/jdk1.6.0_20/jre/bin/java -Drt.prefix\u003drt -Drt.seed\u003dB19FBD1BB1231191 -classpath /home/dweiss/carrot2/carrotsearch.labs/randomizedtesting/integration-ant/ant-junit4/target/test-classes:/home/dweiss/carrot2/carrotsearch.labs/randomizedtesting/integration-ant/ant-junit4/target/dependency/junit-4.10.jar:/home/dweiss/carrot2/carrotsearch.labs/randomizedtesting/integration-ant/ant-junit4/target/classes:/home/dweiss/.m2/repository/com/google/guava/guava/10.0.1/guava-10.0.1.jar:/home/dweiss/carrot2/carrotsearch.labs/randomizedtesting/runner/target/classes:/home/dweiss/.m2/repository/com/google/code/gson/gson/2.0/gson-2.0.jar:/home/dweiss/.m2/repository/commons-io/commons-io/2.1/commons-io-2.1.jar com.carrotsearch.ant.tasks.junit4.slave.SlaveMainSafe -flush @/home/dweiss/carrot2/carrotsearch.labs/randomizedtesting/integration-ant/ant-junit4/target/test-classes/junit4-slave-04421343907870964512.suites", - "systemProperties": { - "file.encoding": "UTF-8", - "file.encoding.pkg": "sun.io", - "file.separator": "/", - "java.awt.graphicsenv": "sun.awt.X11GraphicsEnvironment", - "java.awt.printerjob": "sun.print.PSPrinterJob", - "java.class.path": "/home/dweiss/carrot2/carrotsearch.labs/randomizedtesting/integration-ant/ant-junit4/target/test-classes:/home/dweiss/carrot2/carrotsearch.labs/randomizedtesting/integration-ant/ant-junit4/target/dependency/junit-4.10.jar:/home/dweiss/carrot2/carrotsearch.labs/randomizedtesting/integration-ant/ant-junit4/target/classes:/home/dweiss/.m2/repository/com/google/guava/guava/10.0.1/guava-10.0.1.jar:/home/dweiss/carrot2/carrotsearch.labs/randomizedtesting/runner/target/classes:/home/dweiss/.m2/repository/com/google/code/gson/gson/2.0/gson-2.0.jar:/home/dweiss/.m2/repository/commons-io/commons-io/2.1/commons-io-2.1.jar", - "java.class.version": "50.0", - "java.endorsed.dirs": "/home/dweiss/Applications/java/jdk1.6.0_20/jre/lib/endorsed", - "java.ext.dirs": "/home/dweiss/Applications/java/jdk1.6.0_20/jre/lib/ext:/usr/java/packages/lib/ext", - "java.home": "/home/dweiss/Applications/java/jdk1.6.0_20/jre", - "java.io.tmpdir": "/tmp", - "java.library.path": "/home/dweiss/Applications/java/jdk1.6.0_20/jre/lib/amd64/server:/home/dweiss/Applications/java/jdk1.6.0_20/jre/lib/amd64:/home/dweiss/Applications/java/jdk1.6.0_20/jre/../lib/amd64:/usr/lib/jvm/java-6-openjdk/jre/lib/amd64/server:/usr/lib/jvm/java-6-openjdk/jre/lib/amd64:/usr/lib/jvm/java-6-openjdk/jre/../lib/amd64:/usr/java/packages/lib/amd64:/usr/lib64:/lib64:/lib:/usr/lib", - "java.runtime.name": "Java(TM) SE Runtime Environment", - "java.runtime.version": "1.6.0_20-b02", - "java.specification.name": "Java Platform API Specification", - "java.specification.vendor": "Sun Microsystems Inc.", - "java.specification.version": "1.6", - "java.vendor": "Sun Microsystems Inc.", - "java.vendor.url": "http://java.sun.com/", - "java.vendor.url.bug": "http://java.sun.com/cgi-bin/bugreport.cgi", - "java.version": "1.6.0_20", - "java.vm.info": "mixed mode", - "java.vm.name": "Java HotSpot(TM) 64-Bit Server VM", - "java.vm.specification.name": "Java Virtual Machine Specification", - "java.vm.specification.vendor": "Sun Microsystems Inc.", - "java.vm.specification.version": "1.0", - "java.vm.vendor": "Sun Microsystems Inc.", - "java.vm.version": "16.3-b01", - "junit4.memory.total": "62259200", - "junit4.processors": "2", - "line.separator": "\n", - "os.arch": "amd64", - "os.name": "Linux", - "os.version": "3.0.0-16-generic", - "path.separator": ":", - "rt.prefix": "rt", - "rt.seed": "B19FBD1BB1231191", - "sun.arch.data.model": "64", - "sun.boot.class.path": "/home/dweiss/Applications/java/jdk1.6.0_20/jre/lib/resources.jar:/home/dweiss/Applications/java/jdk1.6.0_20/jre/lib/rt.jar:/home/dweiss/Applications/java/jdk1.6.0_20/jre/lib/sunrsasign.jar:/home/dweiss/Applications/java/jdk1.6.0_20/jre/lib/jsse.jar:/home/dweiss/Applications/java/jdk1.6.0_20/jre/lib/jce.jar:/home/dweiss/Applications/java/jdk1.6.0_20/jre/lib/charsets.jar:/home/dweiss/Applications/java/jdk1.6.0_20/jre/classes", - "sun.boot.library.path": "/home/dweiss/Applications/java/jdk1.6.0_20/jre/lib/amd64", - "sun.cpu.endian": "little", - "sun.cpu.isalist": "", - "sun.desktop": "gnome", - "sun.io.unicode.encoding": "UnicodeLittle", - "sun.java.launcher": "SUN_STANDARD", - "sun.jnu.encoding": "UTF-8", - "sun.management.compiler": "HotSpot 64-Bit Server Compiler", - "sun.os.patch.level": "unknown", - "user.country": "US", - "user.dir": "/home/dweiss/carrot2/carrotsearch.labs/randomizedtesting/integration-ant/ant-junit4/target/test-classes/S0", - "user.home": "/home/dweiss", - "user.language": "en", - "user.name": "dweiss", - "user.timezone": "" - } - } - } -}); \ No newline at end of file diff --git a/junit4-ant/src/main/resources/com/carrotsearch/junit4/antlib.xml b/junit4-ant/src/main/resources/com/carrotsearch/junit4/antlib.xml deleted file mode 100644 index 7f279515..00000000 --- a/junit4-ant/src/main/resources/com/carrotsearch/junit4/antlib.xml +++ /dev/null @@ -1,63 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/junit4-ant/src/native/com_carrotsearch_ant_tasks_junit4_tests_Crash.h b/junit4-ant/src/native/com_carrotsearch_ant_tasks_junit4_tests_Crash.h deleted file mode 100644 index c23dde5c..00000000 --- a/junit4-ant/src/native/com_carrotsearch_ant_tasks_junit4_tests_Crash.h +++ /dev/null @@ -1,21 +0,0 @@ -/* DO NOT EDIT THIS FILE - it is machine generated */ -#include -/* Header for class com_carrotsearch_ant_tasks_junit4_tests_Crash */ - -#ifndef _Included_com_carrotsearch_ant_tasks_junit4_tests_Crash -#define _Included_com_carrotsearch_ant_tasks_junit4_tests_Crash -#ifdef __cplusplus -extern "C" { -#endif -/* - * Class: com_carrotsearch_ant_tasks_junit4_tests_Crash - * Method: crashMe - * Signature: ()V - */ -JNIEXPORT void JNICALL Java_com_carrotsearch_ant_tasks_junit4_tests_Crash_crashMe - (JNIEnv *, jclass); - -#ifdef __cplusplus -} -#endif -#endif diff --git a/junit4-ant/src/native/compile-mac.sh b/junit4-ant/src/native/compile-mac.sh deleted file mode 100755 index a2d2a070..00000000 --- a/junit4-ant/src/native/compile-mac.sh +++ /dev/null @@ -1,4 +0,0 @@ -#!/bin/bash - -CFLAGS="-I /System/Library/Frameworks/JavaVM.framework/Headers/" -gcc -m64 ${CFLAGS} -shared -static -fPIC crash.c -o lib/libcrash64.dylib diff --git a/junit4-ant/src/native/compile.sh b/junit4-ant/src/native/compile.sh deleted file mode 100755 index a5098ce9..00000000 --- a/junit4-ant/src/native/compile.sh +++ /dev/null @@ -1,21 +0,0 @@ -#!/bin/bash - -CFLAGS="-I ${JAVA_HOME}/include -I ${JAVA_HOME}/include/linux -I ${JAVA_HOME}/include/win32" - -# Linux, 64-bit. -gcc -m64 ${CFLAGS} -fPIC -c crash.c -ld -shared -static -o lib/libcrash64.so *.o - -# Linux, 32-bit. -gcc -m32 ${CFLAGS} -fPIC -c crash.c -ld -melf_i386 -shared -static -o lib/libcrash.so *.o - -# Windows, 32-bit -rm -f *.o -i686-w64-mingw32-gcc ${CFLAGS} -shared -o lib/crash.dll crash.c - -# Windows, 64-bit -rm -f *.o -x86_64-w64-mingw32-gcc ${CFLAGS} -shared -o lib/crash64.dll crash.c - -rm -f *.o diff --git a/junit4-ant/src/native/crash.c b/junit4-ant/src/native/crash.c deleted file mode 100644 index a7a72936..00000000 --- a/junit4-ant/src/native/crash.c +++ /dev/null @@ -1,9 +0,0 @@ - -#include "com_carrotsearch_ant_tasks_junit4_tests_Crash.h" -#include "stdio.h" - -JNIEXPORT void JNICALL Java_com_carrotsearch_ant_tasks_junit4_tests_Crash_crashMe - (JNIEnv * env, jclass clazz) -{ - ((char*) 0)[0] = 0; -} diff --git a/junit4-ant/src/native/lib/crash.dll b/junit4-ant/src/native/lib/crash.dll deleted file mode 100644 index 1741dec4..00000000 Binary files a/junit4-ant/src/native/lib/crash.dll and /dev/null differ diff --git a/junit4-ant/src/native/lib/crash64.dll b/junit4-ant/src/native/lib/crash64.dll deleted file mode 100644 index c80d721b..00000000 Binary files a/junit4-ant/src/native/lib/crash64.dll and /dev/null differ diff --git a/junit4-ant/src/native/lib/libcrash.so b/junit4-ant/src/native/lib/libcrash.so deleted file mode 100644 index 5b9576bd..00000000 Binary files a/junit4-ant/src/native/lib/libcrash.so and /dev/null differ diff --git a/junit4-ant/src/native/lib/libcrash64.dylib b/junit4-ant/src/native/lib/libcrash64.dylib deleted file mode 100755 index 7930f5d0..00000000 Binary files a/junit4-ant/src/native/lib/libcrash64.dylib and /dev/null differ diff --git a/junit4-ant/src/native/lib/libcrash64.so b/junit4-ant/src/native/lib/libcrash64.so deleted file mode 100644 index 30d5cfdb..00000000 Binary files a/junit4-ant/src/native/lib/libcrash64.so and /dev/null differ diff --git a/junit4-ant/src/proguard/rules.pro b/junit4-ant/src/proguard/rules.pro deleted file mode 100644 index 135259fc..00000000 --- a/junit4-ant/src/proguard/rules.pro +++ /dev/null @@ -1,23 +0,0 @@ - --dontoptimize - --dontnote --dontwarn - --renamepackage com.google=>com.carrotsearch.ant.tasks.junit4.dependencies --renamepackage org.objectweb=>com.carrotsearch.ant.tasks.junit4.dependencies --renamepackage org.apache=>com.carrotsearch.ant.tasks.junit4.dependencies --renamepackage org.simpleframework=>com.carrotsearch.ant.tasks.junit4.dependencies --renamepackage com.carrotsearch.randomizedtesting=>com.carrotsearch.ant.tasks.junit4.dependencies --repackageclasses com.carrotsearch.ant.tasks.junit4.dependencies - --keepattributes SourceFile,LineNumberTable --keepattributes *Annotation* - --keep class com.carrotsearch.ant.** { - ; ; -} - --keep class org.simpleframework.** { - ; ; -} \ No newline at end of file diff --git a/junit4-ant/src/tasks/Tasks/junit4.html b/junit4-ant/src/tasks/Tasks/junit4.html deleted file mode 100644 index 4790031f..00000000 --- a/junit4-ant/src/tasks/Tasks/junit4.html +++ /dev/null @@ -1,701 +0,0 @@ - - - - - - - - - - - JUnit4 Task - - - - -

JUnit4

-

Description

- -

This task runs tests from the JUnit testing framework in versions 4.10 and above. It to some extent -mimics the style of the default ANT's junit task, but adds the following features: -

    -
  • ability to run tests in multiple forked JVMs (isolated JVMs),
  • -
  • ability to load-balance tests based on previous execution history or job-stealing,
  • -
  • seamless integration with randomized runner - to support a global seed for randomized tests and proper seed reporting,
  • -
  • Synchronized and decluttered console output from child JVMs,
  • -
  • Built-in reporting to HTML, JSON and various forms of plain text.
  • -
- -

Note: The latest version of the JUnit framework can be found at -http://www.junit.org. -This task has been tested with JUnit 4.10 and later. -Appropriate junit*.jar must be available in the task's classpath and in the -tested code's classpath. See the examples below. -

- -

External references: More information about randomized testing. -

- -

Parameters

- -

junit4 attempts to be a drop-in replacement for ANT's default junit task, but so attributes -that make little sense have been deprecated and are ignored. Attributes specific to junit4 are highlighted in -light green.

- -
#{label}
"); - column.renderer(row[column.id], html, row); - html.push("
No tests results found
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
AttributeDescriptionRequired
printsummaryPrints the summary of all executed, ignored and failed tests after all suites have been - executed. To get per-suite summaries, configure a console report properly (see below).No; default is on.
forkNot used. ANT-junit drop-in compatibility only. Tests are always forked.--
forkmodeNot used. ANT-junit drop-in compatibility only. Tests are always forked into one more more - forked JVMs. Each suite is executed entirely on a single JVM.--
haltonerrorNot used. ANT-junit drop-in compatibility only. Use haltonfailure which handles both errors and failures.--
errorpropertyNot used. ANT-junit drop-in compatibility only. Use failureproperty which handles both errors and failures.--
haltonfailureStop the build process if a test fails (errors are considered failures as well). No; default is on (ANT's junit has the default set to 'off').
failurepropertyThe name of a property to set in the event of a failure - (errors are considered failures as well).No.
filtertraceNot used. ANT-junit drop-in compatibility only. Reports may provide their own filtering capabilities.--
timeoutNot used. ANT-junit drop-in compatibility only. Test runners provide their own timeout facilities.--
maxmemoryMaximum amount of memory to allocate to each forked VM (be careful if using lots of forks). - Note: - If you get java.lang.OutOfMemoryError: Java heap space - in some of your tests then you need to raise the size like - maxmemory="128m"No
jvmThe command used to invoke the forked java virtual machines, the default is 'java'. The command is resolved by - java.lang.Runtime.exec().No; default is java.
dir -

The directory in which to invoke the forked JVMs in. This is by default the project's basedir. - Because multiple JVMs may clash if they are generating files in the current working directory, one can use per-JVM directory - by setting isolateWorkingDirectories attribute to true; in such case each JVM gets a sub-directory - the provided dir. -

-

- See onNonEmptyWorkDirectory attribute for action taken when the forked JVM's work directory is not initially - empty. -

-
No
isolateWorkingDirectoriesIf true current working directories are isolated for each forked JVM. See dir attribute too.No; default is true.
onNonEmptyWorkDirectory -

[Since version 2.5.0]. Specifies the action taken when forked JVM's work directory is not initially empty (contains files - or directories, possibly from a previous run). The values permitted are: -

-
-
fail
-
Fails the build.
-
wipe
-
Tries to wipe the work directory clean before tests begin. Fails the build if unsuccessful.
-
ignore
-
Ignores any existing files and proceeds (not recommended).
-
-
No; default is fail.
newenvironmentDo not propagate the old environment when new - environment variables are specified.No; default is false.
includeantruntimeNot used. ANT-junit drop-in compatibility only.--
showoutputNot used. ANT-junit drop-in compatibility only. Configure console reports appropriately.--
outputtoformattersNot used. ANT-junit drop-in compatibility only. Configure console reports appropriately.--
tempdirSpecify where to store temporary files. These temporary files include a list of suites passed - to each slave JVM so it is usually wise to just leave this attribute unset - the default is to take the value of the - dir attribute or the project's basedir. - No
reloadingNot used. ANT-junit drop-in compatibility only.--
clonevmNot used. ANT-junit drop-in compatibility only.--
logfailedtestsNot used. ANT-junit drop-in compatibility only. Configure console reports appropriately to get - just the failing tests, their output etc.--
enableTestListenerEventsNot used. ANT-junit drop-in compatibility only.--
parallelism - The number of parallel slaves. Can be set to a constant max for the - maximum number of cores returned from Runtime.availableProcessors or - auto for sensible defaults depending on the number of cores. - -

Note: this setting forks physical JVM processes so it multiplies the - requirements for heap memory, IO, etc.

-
No; Can be set to any integer or: 'max', 'auto'. - The default is '1' (sequential execution in a forked JVM).
dynamicAssignmentRatio - Specifies the ratio of suites moved to dynamic assignment list (job-stealing). A dynamic - assignment list dispatches suites to the first idle slave JVM. Theoretically - this is an optimal strategy, but it is usually better to have some static assignments - to avoid communication costs. - -

A ratio of 0 means only static assignments are used. A ratio of 1 means - only dynamic assignments are used.

- -

The list of dynamic assignments is sorted by decreasing cost (always) and - is inherently prone to race conditions in distributing suites. Should there - be an error based on suite-dependency it will not be directly repeatable. In such - case use the per-slave-jvm list of suites file dumped to disk for each slave JVM. - See leaveTemporary attribute. -

No; default is '0.25' (25% of all suites are assigned dynamically).
seed - Specify random seed for anything that is randomized in junit4. The order of suites - execution and suite-JVM assignments are a result of this seed for example. - -

The master seed is also passed to slave JVMs as a system property (to bootstrap randomized runner).

-
No; default is a randomly generated seed.
prefix - Initializes custom prefix for all randomized runner properties. This must be consistent - across all junit4 invocations if done from the same classpath. Use only when REALLY needed. - No; default is randomized runner's prefix.
shuffleOnSlave - Predictably shuffle tests order after balancing. This will help in spreading - lighter and heavier tests over a single slave's execution timeline while - still keeping the same tests order depending on the seed. See nested elements - for configuring load balancers. - No; the default is 'true'.
leaveTemporary - Leave temporary junit4 files after the task quits. This can be used to trace the exact order - of suites executed on each forked JVM for example. - No; default is 'false'.
jvmOutputAction - What should be done on unexpected JVM output? JVM may write directly to the - original descriptors, bypassing redirections of System.out and System.err. Typically, - these messages will be important and should fail the build (permgen space exceeded, - compiler errors, crash dumps). However, certain legitimate logs (gc activity, class loading - logs) are also printed to these streams so sometimes the output can be ignored. - -

Allowed values (any comma-delimited combination of): ignore, listeners, pipe, fail, warn.

-
No; default is 'warn, listeners'; append text report listener - to get the actual JVM output or change to 'warn, pipe' to get the output piped to system out.
sysouts - If set to true, any sysout and syserr calls will be written to original - output and error streams (and in effect will appear as "jvm output". By default - sysout and syserrs are captured and proxied to the event stream to be synchronized - with other test events (and properly handled by reports) but occasionally - one may want to synchronize them with direct JVM output (to synchronize - with compiler output or GC output for example). - -

See examples below on examples of capturing full JVM output.

-
No; default is 'false'.
heartbeat - A duration (in seconds) before an event is dispatched about forked JVM inactivity. - This can be useful to report hung or very long tests. Heartbeat information will - include an approximate location inside the non-responding JVM (suite or test case). - No; default is '0'.
uniqueSuiteNames - Allow or disallow duplicate suite names in resource collections. By default this option - is true because certain ANT-compatible report types (like XML reports) - will have a problem with duplicate suite names (will overwrite files). - No; default is 'true'.
ifNoTests - Defines the behavior when no tests were executed successfully or failed (either - there were no tests at all or all of them were filtered out). One of the following - enum constants: 'ignore', 'warn' or 'fail'. - No; default is 'ignore'.
- - -

Nested Elements

- -

The <junit4> task supports a nested elements. Some of them are compatible with -ANT's default <junit> task while others are unique to <junit4>. - - -

Specifying classpath for tests

- -The <classpath> element represents a PATH like structure to be used for each -forked JVM. Note that classpath should include suiteable junit*.jar, otherwise your tests -wont run. - - -

Specifying test suite classes

- -Unlike standard <junit> task, <junit4> defines suite classes as -resources to .class files. These resources can originate from any resource collection and -there can be any number of resource collections with such resources. For example this definition -includes all suite classes from a ZIP file (JAR file), excluding nested classes: - -

-
- - -

jvmarg

- -

Additional parameters may be passed to the new JVM via nested <jvmarg> elements. For example:

- -

-
- -

would run the JVM with a serial garbage collector on HotSpot JVM.

- - - -

sysproperty

- -

Use nested <sysproperty> elements to specify system -properties required by the tests. These properties will be made available -to the forked JVMs during their execution. The attributes for this element are the same -as for environment variables.

- -

An extended attribute <ignoreEmpty> is supported which, if defined, -causes the property NOT to be defined in the forked JVM (as opposed to passing an empty property -value).

- -
- -

would run the test in ANT's VM and make the project's basedir property -available to the test (note the current working directory of a forked JVM will not be the - basedir typically).

- - - -

syspropertyset

- -

You can specify a set of properties to be passed to the target JVM as system properties -with syspropertysets. -This target behaves much like the default in ANT but allows a dynamic set of (remapped) -properties to be resolved at runtime. Similar to sysproperty, this -tag also supports ignoreEmpty attribute to work around -bugs -with local properties in ANT.

- -
- - -

env

- -

It is possible to specify environment variables to pass to the -forked VM via nested <env> elements. For a description -of the <env> element's attributes, see the -description in the exec task.

- - - -

bootclasspath

- -

The location of bootstrap class files can be specified using this -PATH like structure.

- - - -

assertions

- -

You can control enablement of Java 1.4 assertions with an -<assertions> -subelement.

- -

listeners and reports

- -

There is no notion of "reports" in junit4. Reports are just listeners -that attach to the even stream and can produce something (to the console, file or otherwise). You -can also attach your own listeners if you like (although you'd have to peek at the code of existing -listeners to get the feeling how this is done -- communication is via events not interfaces).

- -

report-text

- -

There are a few predefined listeners to choose from. By far the most common will be report-text -which produces console output (or plain text file). A plain text report configuration may look like this: -

- -
- -

This listener supports stack trace filtering to reduce verbosity (console output, for -example). For production or integration builds, it is recommended to keep the full stacks. -For developer runs, the default set of filters (enabled by default) can declutter the output -a bit. An example stack trace filter, with default options and two custom filters, is shown -below.

- -
- -

The level of verbosity of the output can be fine-tuned to one's needs by disabling -or enabling test statuses and suite summaries or each test's output. Experimenting -highly recommended.

- -

report-ant-xml

- -

Another listener is report-ant-xml which can produce XML files suitable -for junitreport task (although -we highly recommend using the built-in JSON report.

- -
- -

report-json

- -

Yet another built-in listener is producing a modern JSON output with test data and -an accompanying HTML5 file for visualizing it:

- -
- -

An example of a HTML5 report produced by the above can be seen here, for example. - -

runlisteners

- -

You can attach custom JUnit 4 RunListeners to your tests like this:

- -
- -

Each RunListener defined is added to each class before execution and removed after

- -

Load balancing of test suites

- -

Suites can be scattered across forked JVMs randomly or using a greedy load-balancing algorithm -(and followed by job-stealing if needed). For load balancing, previous execution -statistics will be needed. These statistics should ideally come from a single machine and multiple -executions so that they average the influence of the environment etc.

- -

A dedicated listener is used to collect and update statistics. The configuration below shows -both the listener and a balancer configuration. The balancer uses multiple sources for collecting -statistics (for example precomputed statistics and previous local runs):

- -
- - -

Capturing original JVM output

- -

JUnit4 has been designed to run reports and aggregation of test events on the master -JVM, not on the forked JVMs. This slightly complicates things when diagnostic JVM messages -are used because these messages are printed directly to original stream descriptors -by the JVM, bypassing System.out or System.err substitutions.

- -

In those rare cases when the original JVM output streams are needed (possibly -mixed with what the tests have printed), junit4 can be configured to leave the original -streams on disk or pipe them to ANT's output. An example is shown below:

- -
- -

Should one need to preserve the original output files (in case they are large, for example), -the configuration would then look as follows:

- -
- -

This would result in the following message being printed to ANT (note -the output file name contains an execution-unique element to avoid clashing with other -forked JVMs or builds).

- -
-[junit4:junit4] JVM J0: stdout was not empty, see: /home/[...]/junit4-J0-1058309761ea5fafd.sysout
-[junit4:junit4] JVM J0: stderr was not empty, see: /home/[...]/junit4-J0-1058309761ea5fafd.syserr
-
- - - diff --git a/junit4-ant/src/tasks/index.html b/junit4-ant/src/tasks/index.html deleted file mode 100644 index 35f1ea69..00000000 --- a/junit4-ant/src/tasks/index.html +++ /dev/null @@ -1,8 +0,0 @@ - - - - - -Follow to: junit4 documentation. - - diff --git a/junit4-ant/src/tasks/js/google-code-prettify/lang-apollo.js b/junit4-ant/src/tasks/js/google-code-prettify/lang-apollo.js deleted file mode 100644 index 7098baf4..00000000 --- a/junit4-ant/src/tasks/js/google-code-prettify/lang-apollo.js +++ /dev/null @@ -1,2 +0,0 @@ -PR.registerLangHandler(PR.createSimpleLexer([["com",/^#[^\n\r]*/,null,"#"],["pln",/^[\t\n\r \xa0]+/,null,"\t\n\r Â\xa0"],["str",/^"(?:[^"\\]|\\[\S\s])*(?:"|$)/,null,'"']],[["kwd",/^(?:ADS|AD|AUG|BZF|BZMF|CAE|CAF|CA|CCS|COM|CS|DAS|DCA|DCOM|DCS|DDOUBL|DIM|DOUBLE|DTCB|DTCF|DV|DXCH|EDRUPT|EXTEND|INCR|INDEX|NDX|INHINT|LXCH|MASK|MSK|MP|MSU|NOOP|OVSK|QXCH|RAND|READ|RELINT|RESUME|RETURN|ROR|RXOR|SQUARE|SU|TCR|TCAA|OVSK|TCF|TC|TS|WAND|WOR|WRITE|XCH|XLQ|XXALQ|ZL|ZQ|ADD|ADZ|SUB|SUZ|MPY|MPR|MPZ|DVP|COM|ABS|CLA|CLZ|LDQ|STO|STQ|ALS|LLS|LRS|TRA|TSQ|TMI|TOV|AXT|TIX|DLY|INP|OUT)\s/, -null],["typ",/^(?:-?GENADR|=MINUS|2BCADR|VN|BOF|MM|-?2CADR|-?[1-6]DNADR|ADRES|BBCON|[ES]?BANK=?|BLOCK|BNKSUM|E?CADR|COUNT\*?|2?DEC\*?|-?DNCHAN|-?DNPTR|EQUALS|ERASE|MEMORY|2?OCT|REMADR|SETLOC|SUBRO|ORG|BSS|BES|SYN|EQU|DEFINE|END)\s/,null],["lit",/^'(?:-*(?:\w|\\[!-~])(?:[\w-]*|\\[!-~])[!=?]?)?/],["pln",/^-*(?:[!-z]|\\[!-~])(?:[\w-]*|\\[!-~])[!=?]?/],["pun",/^[^\w\t\n\r "'-);\\\xa0]+/]]),["apollo","agc","aea"]); diff --git a/junit4-ant/src/tasks/js/google-code-prettify/lang-clj.js b/junit4-ant/src/tasks/js/google-code-prettify/lang-clj.js deleted file mode 100644 index 542a2205..00000000 --- a/junit4-ant/src/tasks/js/google-code-prettify/lang-clj.js +++ /dev/null @@ -1,18 +0,0 @@ -/* - Copyright (C) 2011 Google Inc. - - 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. -*/ -var a=null; -PR.registerLangHandler(PR.createSimpleLexer([["opn",/^[([{]+/,a,"([{"],["clo",/^[)\]}]+/,a,")]}"],["com",/^;[^\n\r]*/,a,";"],["pln",/^[\t\n\r \xa0]+/,a,"\t\n\r \xa0"],["str",/^"(?:[^"\\]|\\[\S\s])*(?:"|$)/,a,'"']],[["kwd",/^(?:def|if|do|let|quote|var|fn|loop|recur|throw|try|monitor-enter|monitor-exit|defmacro|defn|defn-|macroexpand|macroexpand-1|for|doseq|dosync|dotimes|and|or|when|not|assert|doto|proxy|defstruct|first|rest|cons|defprotocol|deftype|defrecord|reify|defmulti|defmethod|meta|with-meta|ns|in-ns|create-ns|import|intern|refer|alias|namespace|resolve|ref|deref|refset|new|set!|memfn|to-array|into-array|aset|gen-class|reduce|map|filter|find|nil?|empty?|hash-map|hash-set|vec|vector|seq|flatten|reverse|assoc|dissoc|list|list?|disj|get|union|difference|intersection|extend|extend-type|extend-protocol|prn)\b/,a], -["typ",/^:[\dA-Za-z-]+/]]),["clj"]); diff --git a/junit4-ant/src/tasks/js/google-code-prettify/lang-css.js b/junit4-ant/src/tasks/js/google-code-prettify/lang-css.js deleted file mode 100644 index 041e1f59..00000000 --- a/junit4-ant/src/tasks/js/google-code-prettify/lang-css.js +++ /dev/null @@ -1,2 +0,0 @@ -PR.registerLangHandler(PR.createSimpleLexer([["pln",/^[\t\n\f\r ]+/,null," \t\r\n "]],[["str",/^"(?:[^\n\f\r"\\]|\\(?:\r\n?|\n|\f)|\\[\S\s])*"/,null],["str",/^'(?:[^\n\f\r'\\]|\\(?:\r\n?|\n|\f)|\\[\S\s])*'/,null],["lang-css-str",/^url\(([^"')]*)\)/i],["kwd",/^(?:url|rgb|!important|@import|@page|@media|@charset|inherit)(?=[^\w-]|$)/i,null],["lang-css-kw",/^(-?(?:[_a-z]|\\[\da-f]+ ?)(?:[\w-]|\\\\[\da-f]+ ?)*)\s*:/i],["com",/^\/\*[^*]*\*+(?:[^*/][^*]*\*+)*\//],["com", -/^(?:<\!--|--\>)/],["lit",/^(?:\d+|\d*\.\d+)(?:%|[a-z]+)?/i],["lit",/^#[\da-f]{3,6}/i],["pln",/^-?(?:[_a-z]|\\[\da-f]+ ?)(?:[\w-]|\\\\[\da-f]+ ?)*/i],["pun",/^[^\s\w"']+/]]),["css"]);PR.registerLangHandler(PR.createSimpleLexer([],[["kwd",/^-?(?:[_a-z]|\\[\da-f]+ ?)(?:[\w-]|\\\\[\da-f]+ ?)*/i]]),["css-kw"]);PR.registerLangHandler(PR.createSimpleLexer([],[["str",/^[^"')]+/]]),["css-str"]); diff --git a/junit4-ant/src/tasks/js/google-code-prettify/lang-go.js b/junit4-ant/src/tasks/js/google-code-prettify/lang-go.js deleted file mode 100644 index fc18dc07..00000000 --- a/junit4-ant/src/tasks/js/google-code-prettify/lang-go.js +++ /dev/null @@ -1 +0,0 @@ -PR.registerLangHandler(PR.createSimpleLexer([["pln",/^[\t\n\r \xa0]+/,null,"\t\n\r Â\xa0"],["pln",/^(?:"(?:[^"\\]|\\[\S\s])*(?:"|$)|'(?:[^'\\]|\\[\S\s])+(?:'|$)|`[^`]*(?:`|$))/,null,"\"'"]],[["com",/^(?:\/\/[^\n\r]*|\/\*[\S\s]*?\*\/)/],["pln",/^(?:[^"'/`]|\/(?![*/]))+/]]),["go"]); diff --git a/junit4-ant/src/tasks/js/google-code-prettify/lang-hs.js b/junit4-ant/src/tasks/js/google-code-prettify/lang-hs.js deleted file mode 100644 index 9d77b083..00000000 --- a/junit4-ant/src/tasks/js/google-code-prettify/lang-hs.js +++ /dev/null @@ -1,2 +0,0 @@ -PR.registerLangHandler(PR.createSimpleLexer([["pln",/^[\t-\r ]+/,null,"\t\n \r "],["str",/^"(?:[^\n\f\r"\\]|\\[\S\s])*(?:"|$)/,null,'"'],["str",/^'(?:[^\n\f\r'\\]|\\[^&])'?/,null,"'"],["lit",/^(?:0o[0-7]+|0x[\da-f]+|\d+(?:\.\d+)?(?:e[+-]?\d+)?)/i,null,"0123456789"]],[["com",/^(?:--+[^\n\f\r]*|{-(?:[^-]|-+[^}-])*-})/],["kwd",/^(?:case|class|data|default|deriving|do|else|if|import|in|infix|infixl|infixr|instance|let|module|newtype|of|then|type|where|_)(?=[^\d'A-Za-z]|$)/, -null],["pln",/^(?:[A-Z][\w']*\.)*[A-Za-z][\w']*/],["pun",/^[^\d\t-\r "'A-Za-z]+/]]),["hs"]); diff --git a/junit4-ant/src/tasks/js/google-code-prettify/lang-lisp.js b/junit4-ant/src/tasks/js/google-code-prettify/lang-lisp.js deleted file mode 100644 index 02a30e8d..00000000 --- a/junit4-ant/src/tasks/js/google-code-prettify/lang-lisp.js +++ /dev/null @@ -1,3 +0,0 @@ -var a=null; -PR.registerLangHandler(PR.createSimpleLexer([["opn",/^\(+/,a,"("],["clo",/^\)+/,a,")"],["com",/^;[^\n\r]*/,a,";"],["pln",/^[\t\n\r \xa0]+/,a,"\t\n\r \xa0"],["str",/^"(?:[^"\\]|\\[\S\s])*(?:"|$)/,a,'"']],[["kwd",/^(?:block|c[ad]+r|catch|con[ds]|def(?:ine|un)|do|eq|eql|equal|equalp|eval-when|flet|format|go|if|labels|lambda|let|load-time-value|locally|macrolet|multiple-value-call|nil|progn|progv|quote|require|return-from|setq|symbol-macrolet|t|tagbody|the|throw|unwind)\b/,a], -["lit",/^[+-]?(?:[#0]x[\da-f]+|\d+\/\d+|(?:\.\d+|\d+(?:\.\d*)?)(?:[de][+-]?\d+)?)/i],["lit",/^'(?:-*(?:\w|\\[!-~])(?:[\w-]*|\\[!-~])[!=?]?)?/],["pln",/^-*(?:[_a-z]|\\[!-~])(?:[\w-]*|\\[!-~])[!=?]?/i],["pun",/^[^\w\t\n\r "'-);\\\xa0]+/]]),["cl","el","lisp","scm"]); diff --git a/junit4-ant/src/tasks/js/google-code-prettify/lang-lua.js b/junit4-ant/src/tasks/js/google-code-prettify/lang-lua.js deleted file mode 100644 index e83a3c46..00000000 --- a/junit4-ant/src/tasks/js/google-code-prettify/lang-lua.js +++ /dev/null @@ -1,2 +0,0 @@ -PR.registerLangHandler(PR.createSimpleLexer([["pln",/^[\t\n\r \xa0]+/,null,"\t\n\r Â\xa0"],["str",/^(?:"(?:[^"\\]|\\[\S\s])*(?:"|$)|'(?:[^'\\]|\\[\S\s])*(?:'|$))/,null,"\"'"]],[["com",/^--(?:\[(=*)\[[\S\s]*?(?:]\1]|$)|[^\n\r]*)/],["str",/^\[(=*)\[[\S\s]*?(?:]\1]|$)/],["kwd",/^(?:and|break|do|else|elseif|end|false|for|function|if|in|local|nil|not|or|repeat|return|then|true|until|while)\b/,null],["lit",/^[+-]?(?:0x[\da-f]+|(?:\.\d+|\d+(?:\.\d*)?)(?:e[+-]?\d+)?)/i], -["pln",/^[_a-z]\w*/i],["pun",/^[^\w\t\n\r \xa0][^\w\t\n\r "'+=\xa0-]*/]]),["lua"]); diff --git a/junit4-ant/src/tasks/js/google-code-prettify/lang-ml.js b/junit4-ant/src/tasks/js/google-code-prettify/lang-ml.js deleted file mode 100644 index 6df02d72..00000000 --- a/junit4-ant/src/tasks/js/google-code-prettify/lang-ml.js +++ /dev/null @@ -1,2 +0,0 @@ -PR.registerLangHandler(PR.createSimpleLexer([["pln",/^[\t\n\r \xa0]+/,null,"\t\n\r Â\xa0"],["com",/^#(?:if[\t\n\r \xa0]+(?:[$_a-z][\w']*|``[^\t\n\r`]*(?:``|$))|else|endif|light)/i,null,"#"],["str",/^(?:"(?:[^"\\]|\\[\S\s])*(?:"|$)|'(?:[^'\\]|\\[\S\s])(?:'|$))/,null,"\"'"]],[["com",/^(?:\/\/[^\n\r]*|\(\*[\S\s]*?\*\))/],["kwd",/^(?:abstract|and|as|assert|begin|class|default|delegate|do|done|downcast|downto|elif|else|end|exception|extern|false|finally|for|fun|function|if|in|inherit|inline|interface|internal|lazy|let|match|member|module|mutable|namespace|new|null|of|open|or|override|private|public|rec|return|static|struct|then|to|true|try|type|upcast|use|val|void|when|while|with|yield|asr|land|lor|lsl|lsr|lxor|mod|sig|atomic|break|checked|component|const|constraint|constructor|continue|eager|event|external|fixed|functor|global|include|method|mixin|object|parallel|process|protected|pure|sealed|trait|virtual|volatile)\b/], -["lit",/^[+-]?(?:0x[\da-f]+|(?:\.\d+|\d+(?:\.\d*)?)(?:e[+-]?\d+)?)/i],["pln",/^(?:[_a-z][\w']*[!#?]?|``[^\t\n\r`]*(?:``|$))/i],["pun",/^[^\w\t\n\r "'\xa0]+/]]),["fs","ml"]); diff --git a/junit4-ant/src/tasks/js/google-code-prettify/lang-n.js b/junit4-ant/src/tasks/js/google-code-prettify/lang-n.js deleted file mode 100644 index 6c2e85b9..00000000 --- a/junit4-ant/src/tasks/js/google-code-prettify/lang-n.js +++ /dev/null @@ -1,4 +0,0 @@ -var a=null; -PR.registerLangHandler(PR.createSimpleLexer([["str",/^(?:'(?:[^\n\r'\\]|\\.)*'|"(?:[^\n\r"\\]|\\.)*(?:"|$))/,a,'"'],["com",/^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\n\r]*)/,a,"#"],["pln",/^\s+/,a," \r\n\t\xa0"]],[["str",/^@"(?:[^"]|"")*(?:"|$)/,a],["str",/^<#[^#>]*(?:#>|$)/,a],["str",/^<(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)>/,a],["com",/^\/\/[^\n\r]*/,a],["com",/^\/\*[\S\s]*?(?:\*\/|$)/, -a],["kwd",/^(?:abstract|and|as|base|catch|class|def|delegate|enum|event|extern|false|finally|fun|implements|interface|internal|is|macro|match|matches|module|mutable|namespace|new|null|out|override|params|partial|private|protected|public|ref|sealed|static|struct|syntax|this|throw|true|try|type|typeof|using|variant|virtual|volatile|when|where|with|assert|assert2|async|break|checked|continue|do|else|ensures|for|foreach|if|late|lock|new|nolate|otherwise|regexp|repeat|requires|return|surroundwith|unchecked|unless|using|while|yield)\b/, -a],["typ",/^(?:array|bool|byte|char|decimal|double|float|int|list|long|object|sbyte|short|string|ulong|uint|ufloat|ulong|ushort|void)\b/,a],["lit",/^@[$_a-z][\w$@]*/i,a],["typ",/^@[A-Z]+[a-z][\w$@]*/,a],["pln",/^'?[$_a-z][\w$@]*/i,a],["lit",/^(?:0x[\da-f]+|(?:\d(?:_\d+)*\d*(?:\.\d*)?|\.\d\+)(?:e[+-]?\d+)?)[a-z]*/i,a,"0123456789"],["pun",/^.[^\s\w"-$'./@`]*/,a]]),["n","nemerle"]); diff --git a/junit4-ant/src/tasks/js/google-code-prettify/lang-proto.js b/junit4-ant/src/tasks/js/google-code-prettify/lang-proto.js deleted file mode 100644 index f006ad8c..00000000 --- a/junit4-ant/src/tasks/js/google-code-prettify/lang-proto.js +++ /dev/null @@ -1 +0,0 @@ -PR.registerLangHandler(PR.sourceDecorator({keywords:"bytes,default,double,enum,extend,extensions,false,group,import,max,message,option,optional,package,repeated,required,returns,rpc,service,syntax,to,true",types:/^(bool|(double|s?fixed|[su]?int)(32|64)|float|string)\b/,cStyleComments:!0}),["proto"]); diff --git a/junit4-ant/src/tasks/js/google-code-prettify/lang-scala.js b/junit4-ant/src/tasks/js/google-code-prettify/lang-scala.js deleted file mode 100644 index 60d034de..00000000 --- a/junit4-ant/src/tasks/js/google-code-prettify/lang-scala.js +++ /dev/null @@ -1,2 +0,0 @@ -PR.registerLangHandler(PR.createSimpleLexer([["pln",/^[\t\n\r \xa0]+/,null,"\t\n\r Â\xa0"],["str",/^"(?:""(?:""?(?!")|[^"\\]|\\.)*"{0,3}|(?:[^\n\r"\\]|\\.)*"?)/,null,'"'],["lit",/^`(?:[^\n\r\\`]|\\.)*`?/,null,"`"],["pun",/^[!#%&(--:-@[-^{-~]+/,null,"!#%&()*+,-:;<=>?@[\\]^{|}~"]],[["str",/^'(?:[^\n\r'\\]|\\(?:'|[^\n\r']+))'/],["lit",/^'[$A-Z_a-z][\w$]*(?![\w$'])/],["kwd",/^(?:abstract|case|catch|class|def|do|else|extends|final|finally|for|forSome|if|implicit|import|lazy|match|new|object|override|package|private|protected|requires|return|sealed|super|throw|trait|try|type|val|var|while|with|yield)\b/], -["lit",/^(?:true|false|null|this)\b/],["lit",/^(?:0(?:[0-7]+|x[\da-f]+)l?|(?:0|[1-9]\d*)(?:(?:\.\d+)?(?:e[+-]?\d+)?f?|l?)|\\.\d+(?:e[+-]?\d+)?f?)/i],["typ",/^[$_]*[A-Z][\d$A-Z_]*[a-z][\w$]*/],["pln",/^[$A-Z_a-z][\w$]*/],["com",/^\/(?:\/.*|\*(?:\/|\**[^*/])*(?:\*+\/?)?)/],["pun",/^(?:\.+|\/)/]]),["scala"]); diff --git a/junit4-ant/src/tasks/js/google-code-prettify/lang-sql.js b/junit4-ant/src/tasks/js/google-code-prettify/lang-sql.js deleted file mode 100644 index da705b0b..00000000 --- a/junit4-ant/src/tasks/js/google-code-prettify/lang-sql.js +++ /dev/null @@ -1,2 +0,0 @@ -PR.registerLangHandler(PR.createSimpleLexer([["pln",/^[\t\n\r \xa0]+/,null,"\t\n\r Â\xa0"],["str",/^(?:"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')/,null,"\"'"]],[["com",/^(?:--[^\n\r]*|\/\*[\S\s]*?(?:\*\/|$))/],["kwd",/^(?:add|all|alter|and|any|as|asc|authorization|backup|begin|between|break|browse|bulk|by|cascade|case|check|checkpoint|close|clustered|coalesce|collate|column|commit|compute|constraint|contains|containstable|continue|convert|create|cross|current|current_date|current_time|current_timestamp|current_user|cursor|database|dbcc|deallocate|declare|default|delete|deny|desc|disk|distinct|distributed|double|drop|dummy|dump|else|end|errlvl|escape|except|exec|execute|exists|exit|fetch|file|fillfactor|for|foreign|freetext|freetexttable|from|full|function|goto|grant|group|having|holdlock|identity|identitycol|identity_insert|if|in|index|inner|insert|intersect|into|is|join|key|kill|left|like|lineno|load|match|merge|national|nocheck|nonclustered|not|null|nullif|of|off|offsets|on|open|opendatasource|openquery|openrowset|openxml|option|or|order|outer|over|percent|plan|precision|primary|print|proc|procedure|public|raiserror|read|readtext|reconfigure|references|replication|restore|restrict|return|revoke|right|rollback|rowcount|rowguidcol|rule|save|schema|select|session_user|set|setuser|shutdown|some|statistics|system_user|table|textsize|then|to|top|tran|transaction|trigger|truncate|tsequal|union|unique|update|updatetext|use|user|using|values|varying|view|waitfor|when|where|while|with|writetext)(?=[^\w-]|$)/i, -null],["lit",/^[+-]?(?:0x[\da-f]+|(?:\.\d+|\d+(?:\.\d*)?)(?:e[+-]?\d+)?)/i],["pln",/^[_a-z][\w-]*/i],["pun",/^[^\w\t\n\r "'\xa0][^\w\t\n\r "'+\xa0-]*/]]),["sql"]); diff --git a/junit4-ant/src/tasks/js/google-code-prettify/lang-tex.js b/junit4-ant/src/tasks/js/google-code-prettify/lang-tex.js deleted file mode 100644 index ce96fbbd..00000000 --- a/junit4-ant/src/tasks/js/google-code-prettify/lang-tex.js +++ /dev/null @@ -1 +0,0 @@ -PR.registerLangHandler(PR.createSimpleLexer([["pln",/^[\t\n\r \xa0]+/,null,"\t\n\r Â\xa0"],["com",/^%[^\n\r]*/,null,"%"]],[["kwd",/^\\[@-Za-z]+/],["kwd",/^\\./],["typ",/^[$&]/],["lit",/[+-]?(?:\.\d+|\d+(?:\.\d*)?)(cm|em|ex|in|pc|pt|bp|mm)/i],["pun",/^[()=[\]{}]+/]]),["latex","tex"]); diff --git a/junit4-ant/src/tasks/js/google-code-prettify/lang-vb.js b/junit4-ant/src/tasks/js/google-code-prettify/lang-vb.js deleted file mode 100644 index 07506b03..00000000 --- a/junit4-ant/src/tasks/js/google-code-prettify/lang-vb.js +++ /dev/null @@ -1,2 +0,0 @@ -PR.registerLangHandler(PR.createSimpleLexer([["pln",/^[\t\n\r \xa0\u2028\u2029]+/,null,"\t\n\r Â\xa0

"],["str",/^(?:["\u201c\u201d](?:[^"\u201c\u201d]|["\u201c\u201d]{2})(?:["\u201c\u201d]c|$)|["\u201c\u201d](?:[^"\u201c\u201d]|["\u201c\u201d]{2})*(?:["\u201c\u201d]|$))/i,null,'"“â€'],["com",/^['\u2018\u2019].*/,null,"'‘’"]],[["kwd",/^(?:addhandler|addressof|alias|and|andalso|ansi|as|assembly|auto|boolean|byref|byte|byval|call|case|catch|cbool|cbyte|cchar|cdate|cdbl|cdec|char|cint|class|clng|cobj|const|cshort|csng|cstr|ctype|date|decimal|declare|default|delegate|dim|directcast|do|double|each|else|elseif|end|endif|enum|erase|error|event|exit|finally|for|friend|function|get|gettype|gosub|goto|handles|if|implements|imports|in|inherits|integer|interface|is|let|lib|like|long|loop|me|mod|module|mustinherit|mustoverride|mybase|myclass|namespace|new|next|not|notinheritable|notoverridable|object|on|option|optional|or|orelse|overloads|overridable|overrides|paramarray|preserve|private|property|protected|public|raiseevent|readonly|redim|removehandler|resume|return|select|set|shadows|shared|short|single|static|step|stop|string|structure|sub|synclock|then|throw|to|try|typeof|unicode|until|variant|wend|when|while|with|withevents|writeonly|xor|endif|gosub|let|variant|wend)\b/i, -null],["com",/^rem.*/i],["lit",/^(?:true\b|false\b|nothing\b|\d+(?:e[+-]?\d+[dfr]?|[dfilrs])?|(?:&h[\da-f]+|&o[0-7]+)[ils]?|\d*\.\d+(?:e[+-]?\d+)?[dfr]?|#\s+(?:\d+[/-]\d+[/-]\d+(?:\s+\d+:\d+(?::\d+)?(\s*(?:am|pm))?)?|\d+:\d+(?::\d+)?(\s*(?:am|pm))?)\s+#)/i],["pln",/^(?:(?:[a-z]|_\w)\w*|\[(?:[a-z]|_\w)\w*])/i],["pun",/^[^\w\t\n\r "'[\]\xa0\u2018\u2019\u201c\u201d\u2028\u2029]+/],["pun",/^(?:\[|])/]]),["vb","vbs"]); diff --git a/junit4-ant/src/tasks/js/google-code-prettify/lang-vhdl.js b/junit4-ant/src/tasks/js/google-code-prettify/lang-vhdl.js deleted file mode 100644 index 128b5b6c..00000000 --- a/junit4-ant/src/tasks/js/google-code-prettify/lang-vhdl.js +++ /dev/null @@ -1,3 +0,0 @@ -PR.registerLangHandler(PR.createSimpleLexer([["pln",/^[\t\n\r \xa0]+/,null,"\t\n\r Â\xa0"]],[["str",/^(?:[box]?"(?:[^"]|"")*"|'.')/i],["com",/^--[^\n\r]*/],["kwd",/^(?:abs|access|after|alias|all|and|architecture|array|assert|attribute|begin|block|body|buffer|bus|case|component|configuration|constant|disconnect|downto|else|elsif|end|entity|exit|file|for|function|generate|generic|group|guarded|if|impure|in|inertial|inout|is|label|library|linkage|literal|loop|map|mod|nand|new|next|nor|not|null|of|on|open|or|others|out|package|port|postponed|procedure|process|pure|range|record|register|reject|rem|report|return|rol|ror|select|severity|shared|signal|sla|sll|sra|srl|subtype|then|to|transport|type|unaffected|units|until|use|variable|wait|when|while|with|xnor|xor)(?=[^\w-]|$)/i, -null],["typ",/^(?:bit|bit_vector|character|boolean|integer|real|time|string|severity_level|positive|natural|signed|unsigned|line|text|std_u?logic(?:_vector)?)(?=[^\w-]|$)/i,null],["typ",/^'(?:active|ascending|base|delayed|driving|driving_value|event|high|image|instance_name|last_active|last_event|last_value|left|leftof|length|low|path_name|pos|pred|quiet|range|reverse_range|right|rightof|simple_name|stable|succ|transaction|val|value)(?=[^\w-]|$)/i,null],["lit",/^\d+(?:_\d+)*(?:#[\w.\\]+#(?:[+-]?\d+(?:_\d+)*)?|(?:\.\d+(?:_\d+)*)?(?:e[+-]?\d+(?:_\d+)*)?)/i], -["pln",/^(?:[a-z]\w*|\\[^\\]*\\)/i],["pun",/^[^\w\t\n\r "'\xa0][^\w\t\n\r "'\xa0-]*/]]),["vhdl","vhd"]); diff --git a/junit4-ant/src/tasks/js/google-code-prettify/lang-wiki.js b/junit4-ant/src/tasks/js/google-code-prettify/lang-wiki.js deleted file mode 100644 index 9b0b4487..00000000 --- a/junit4-ant/src/tasks/js/google-code-prettify/lang-wiki.js +++ /dev/null @@ -1,2 +0,0 @@ -PR.registerLangHandler(PR.createSimpleLexer([["pln",/^[\d\t a-gi-z\xa0]+/,null,"\t Â\xa0abcdefgijklmnopqrstuvwxyz0123456789"],["pun",/^[*=[\]^~]+/,null,"=*~^[]"]],[["lang-wiki.meta",/(?:^^|\r\n?|\n)(#[a-z]+)\b/],["lit",/^[A-Z][a-z][\da-z]+[A-Z][a-z][^\W_]+\b/],["lang-",/^{{{([\S\s]+?)}}}/],["lang-",/^`([^\n\r`]+)`/],["str",/^https?:\/\/[^\s#/?]*(?:\/[^\s#?]*)?(?:\?[^\s#]*)?(?:#\S*)?/i],["pln",/^(?:\r\n|[\S\s])[^\n\r#*=A-[^`h{~]*/]]),["wiki"]); -PR.registerLangHandler(PR.createSimpleLexer([["kwd",/^#[a-z]+/i,null,"#"]],[]),["wiki.meta"]); diff --git a/junit4-ant/src/tasks/js/google-code-prettify/lang-xq.js b/junit4-ant/src/tasks/js/google-code-prettify/lang-xq.js deleted file mode 100644 index e323ae32..00000000 --- a/junit4-ant/src/tasks/js/google-code-prettify/lang-xq.js +++ /dev/null @@ -1,3 +0,0 @@ -PR.registerLangHandler(PR.createSimpleLexer([["var pln",/^\$[\w-]+/,null,"$"]],[["pln",/^[\s=][<>][\s=]/],["lit",/^@[\w-]+/],["tag",/^<\/?[a-z](?:[\w-.:]*\w)?|\/?>$/i],["com",/^\(:[\S\s]*?:\)/],["pln",/^[(),/;[\]{}]$/],["str",/^(?:"(?:[^"\\{]|\\[\S\s])*(?:"|$)|'(?:[^'\\{]|\\[\S\s])*(?:'|$))/,null,"\"'"],["kwd",/^(?:xquery|where|version|variable|union|typeswitch|treat|to|then|text|stable|sortby|some|self|schema|satisfies|returns|return|ref|processing-instruction|preceding-sibling|preceding|precedes|parent|only|of|node|namespace|module|let|item|intersect|instance|in|import|if|function|for|follows|following-sibling|following|external|except|every|else|element|descending|descendant-or-self|descendant|define|default|declare|comment|child|cast|case|before|attribute|assert|ascending|as|ancestor-or-self|ancestor|after|eq|order|by|or|and|schema-element|document-node|node|at)\b/], -["typ",/^(?:xs:yearMonthDuration|xs:unsignedLong|xs:time|xs:string|xs:short|xs:QName|xs:Name|xs:long|xs:integer|xs:int|xs:gYearMonth|xs:gYear|xs:gMonthDay|xs:gDay|xs:float|xs:duration|xs:double|xs:decimal|xs:dayTimeDuration|xs:dateTime|xs:date|xs:byte|xs:boolean|xs:anyURI|xf:yearMonthDuration)\b/,null],["fun pln",/^(?:xp:dereference|xinc:node-expand|xinc:link-references|xinc:link-expand|xhtml:restructure|xhtml:clean|xhtml:add-lists|xdmp:zip-manifest|xdmp:zip-get|xdmp:zip-create|xdmp:xquery-version|xdmp:word-convert|xdmp:with-namespaces|xdmp:version|xdmp:value|xdmp:user-roles|xdmp:user-last-login|xdmp:user|xdmp:url-encode|xdmp:url-decode|xdmp:uri-is-file|xdmp:uri-format|xdmp:uri-content-type|xdmp:unquote|xdmp:unpath|xdmp:triggers-database|xdmp:trace|xdmp:to-json|xdmp:tidy|xdmp:subbinary|xdmp:strftime|xdmp:spawn-in|xdmp:spawn|xdmp:sleep|xdmp:shutdown|xdmp:set-session-field|xdmp:set-response-encoding|xdmp:set-response-content-type|xdmp:set-response-code|xdmp:set-request-time-limit|xdmp:set|xdmp:servers|xdmp:server-status|xdmp:server-name|xdmp:server|xdmp:security-database|xdmp:security-assert|xdmp:schema-database|xdmp:save|xdmp:role-roles|xdmp:role|xdmp:rethrow|xdmp:restart|xdmp:request-timestamp|xdmp:request-status|xdmp:request-cancel|xdmp:request|xdmp:redirect-response|xdmp:random|xdmp:quote|xdmp:query-trace|xdmp:query-meters|xdmp:product-edition|xdmp:privilege-roles|xdmp:privilege|xdmp:pretty-print|xdmp:powerpoint-convert|xdmp:platform|xdmp:permission|xdmp:pdf-convert|xdmp:path|xdmp:octal-to-integer|xdmp:node-uri|xdmp:node-replace|xdmp:node-kind|xdmp:node-insert-child|xdmp:node-insert-before|xdmp:node-insert-after|xdmp:node-delete|xdmp:node-database|xdmp:mul64|xdmp:modules-root|xdmp:modules-database|xdmp:merging|xdmp:merge-cancel|xdmp:merge|xdmp:md5|xdmp:logout|xdmp:login|xdmp:log-level|xdmp:log|xdmp:lock-release|xdmp:lock-acquire|xdmp:load|xdmp:invoke-in|xdmp:invoke|xdmp:integer-to-octal|xdmp:integer-to-hex|xdmp:http-put|xdmp:http-post|xdmp:http-options|xdmp:http-head|xdmp:http-get|xdmp:http-delete|xdmp:hosts|xdmp:host-status|xdmp:host-name|xdmp:host|xdmp:hex-to-integer|xdmp:hash64|xdmp:hash32|xdmp:has-privilege|xdmp:groups|xdmp:group-serves|xdmp:group-servers|xdmp:group-name|xdmp:group-hosts|xdmp:group|xdmp:get-session-field-names|xdmp:get-session-field|xdmp:get-response-encoding|xdmp:get-response-code|xdmp:get-request-username|xdmp:get-request-user|xdmp:get-request-url|xdmp:get-request-protocol|xdmp:get-request-path|xdmp:get-request-method|xdmp:get-request-header-names|xdmp:get-request-header|xdmp:get-request-field-names|xdmp:get-request-field-filename|xdmp:get-request-field-content-type|xdmp:get-request-field|xdmp:get-request-client-certificate|xdmp:get-request-client-address|xdmp:get-request-body|xdmp:get-current-user|xdmp:get-current-roles|xdmp:get|xdmp:function-name|xdmp:function-module|xdmp:function|xdmp:from-json|xdmp:forests|xdmp:forest-status|xdmp:forest-restore|xdmp:forest-restart|xdmp:forest-name|xdmp:forest-delete|xdmp:forest-databases|xdmp:forest-counts|xdmp:forest-clear|xdmp:forest-backup|xdmp:forest|xdmp:filesystem-file|xdmp:filesystem-directory|xdmp:exists|xdmp:excel-convert|xdmp:eval-in|xdmp:eval|xdmp:estimate|xdmp:email|xdmp:element-content-type|xdmp:elapsed-time|xdmp:document-set-quality|xdmp:document-set-property|xdmp:document-set-properties|xdmp:document-set-permissions|xdmp:document-set-collections|xdmp:document-remove-properties|xdmp:document-remove-permissions|xdmp:document-remove-collections|xdmp:document-properties|xdmp:document-locks|xdmp:document-load|xdmp:document-insert|xdmp:document-get-quality|xdmp:document-get-properties|xdmp:document-get-permissions|xdmp:document-get-collections|xdmp:document-get|xdmp:document-forest|xdmp:document-delete|xdmp:document-add-properties|xdmp:document-add-permissions|xdmp:document-add-collections|xdmp:directory-properties|xdmp:directory-locks|xdmp:directory-delete|xdmp:directory-create|xdmp:directory|xdmp:diacritic-less|xdmp:describe|xdmp:default-permissions|xdmp:default-collections|xdmp:databases|xdmp:database-restore-validate|xdmp:database-restore-status|xdmp:database-restore-cancel|xdmp:database-restore|xdmp:database-name|xdmp:database-forests|xdmp:database-backup-validate|xdmp:database-backup-status|xdmp:database-backup-purge|xdmp:database-backup-cancel|xdmp:database-backup|xdmp:database|xdmp:collection-properties|xdmp:collection-locks|xdmp:collection-delete|xdmp:collation-canonical-uri|xdmp:castable-as|xdmp:can-grant-roles|xdmp:base64-encode|xdmp:base64-decode|xdmp:architecture|xdmp:apply|xdmp:amp-roles|xdmp:amp|xdmp:add64|xdmp:add-response-header|xdmp:access|trgr:trigger-set-recursive|trgr:trigger-set-permissions|trgr:trigger-set-name|trgr:trigger-set-module|trgr:trigger-set-event|trgr:trigger-set-description|trgr:trigger-remove-permissions|trgr:trigger-module|trgr:trigger-get-permissions|trgr:trigger-enable|trgr:trigger-disable|trgr:trigger-database-online-event|trgr:trigger-data-event|trgr:trigger-add-permissions|trgr:remove-trigger|trgr:property-content|trgr:pre-commit|trgr:post-commit|trgr:get-trigger-by-id|trgr:get-trigger|trgr:document-scope|trgr:document-content|trgr:directory-scope|trgr:create-trigger|trgr:collection-scope|trgr:any-property-content|thsr:set-entry|thsr:remove-term|thsr:remove-synonym|thsr:remove-entry|thsr:query-lookup|thsr:lookup|thsr:load|thsr:insert|thsr:expand|thsr:add-synonym|spell:suggest-detailed|spell:suggest|spell:remove-word|spell:make-dictionary|spell:load|spell:levenshtein-distance|spell:is-correct|spell:insert|spell:double-metaphone|spell:add-word|sec:users-collection|sec:user-set-roles|sec:user-set-password|sec:user-set-name|sec:user-set-description|sec:user-set-default-permissions|sec:user-set-default-collections|sec:user-remove-roles|sec:user-privileges|sec:user-get-roles|sec:user-get-description|sec:user-get-default-permissions|sec:user-get-default-collections|sec:user-doc-permissions|sec:user-doc-collections|sec:user-add-roles|sec:unprotect-collection|sec:uid-for-name|sec:set-realm|sec:security-version|sec:security-namespace|sec:security-installed|sec:security-collection|sec:roles-collection|sec:role-set-roles|sec:role-set-name|sec:role-set-description|sec:role-set-default-permissions|sec:role-set-default-collections|sec:role-remove-roles|sec:role-privileges|sec:role-get-roles|sec:role-get-description|sec:role-get-default-permissions|sec:role-get-default-collections|sec:role-doc-permissions|sec:role-doc-collections|sec:role-add-roles|sec:remove-user|sec:remove-role-from-users|sec:remove-role-from-role|sec:remove-role-from-privileges|sec:remove-role-from-amps|sec:remove-role|sec:remove-privilege|sec:remove-amp|sec:protect-collection|sec:privileges-collection|sec:privilege-set-roles|sec:privilege-set-name|sec:privilege-remove-roles|sec:privilege-get-roles|sec:privilege-add-roles|sec:priv-doc-permissions|sec:priv-doc-collections|sec:get-user-names|sec:get-unique-elem-id|sec:get-role-names|sec:get-role-ids|sec:get-privilege|sec:get-distinct-permissions|sec:get-collection|sec:get-amp|sec:create-user-with-role|sec:create-user|sec:create-role|sec:create-privilege|sec:create-amp|sec:collections-collection|sec:collection-set-permissions|sec:collection-remove-permissions|sec:collection-get-permissions|sec:collection-add-permissions|sec:check-admin|sec:amps-collection|sec:amp-set-roles|sec:amp-remove-roles|sec:amp-get-roles|sec:amp-doc-permissions|sec:amp-doc-collections|sec:amp-add-roles|search:unparse|search:suggest|search:snippet|search:search|search:resolve-nodes|search:resolve|search:remove-constraint|search:parse|search:get-default-options|search:estimate|search:check-options|prof:value|prof:reset|prof:report|prof:invoke|prof:eval|prof:enable|prof:disable|prof:allowed|ppt:clean|pki:template-set-request|pki:template-set-name|pki:template-set-key-type|pki:template-set-key-options|pki:template-set-description|pki:template-in-use|pki:template-get-version|pki:template-get-request|pki:template-get-name|pki:template-get-key-type|pki:template-get-key-options|pki:template-get-id|pki:template-get-description|pki:need-certificate|pki:is-temporary|pki:insert-trusted-certificates|pki:insert-template|pki:insert-signed-certificates|pki:insert-certificate-revocation-list|pki:get-trusted-certificate-ids|pki:get-template-ids|pki:get-template-certificate-authority|pki:get-template-by-name|pki:get-template|pki:get-pending-certificate-requests-xml|pki:get-pending-certificate-requests-pem|pki:get-pending-certificate-request|pki:get-certificates-for-template-xml|pki:get-certificates-for-template|pki:get-certificates|pki:get-certificate-xml|pki:get-certificate-pem|pki:get-certificate|pki:generate-temporary-certificate-if-necessary|pki:generate-temporary-certificate|pki:generate-template-certificate-authority|pki:generate-certificate-request|pki:delete-template|pki:delete-certificate|pki:create-template|pdf:make-toc|pdf:insert-toc-headers|pdf:get-toc|pdf:clean|p:status-transition|p:state-transition|p:remove|p:pipelines|p:insert|p:get-by-id|p:get|p:execute|p:create|p:condition|p:collection|p:action|ooxml:runs-merge|ooxml:package-uris|ooxml:package-parts-insert|ooxml:package-parts|msword:clean|mcgm:polygon|mcgm:point|mcgm:geospatial-query-from-elements|mcgm:geospatial-query|mcgm:circle|math:tanh|math:tan|math:sqrt|math:sinh|math:sin|math:pow|math:modf|math:log10|math:log|math:ldexp|math:frexp|math:fmod|math:floor|math:fabs|math:exp|math:cosh|math:cos|math:ceil|math:atan2|math:atan|math:asin|math:acos|map:put|map:map|map:keys|map:get|map:delete|map:count|map:clear|lnk:to|lnk:remove|lnk:insert|lnk:get|lnk:from|lnk:create|kml:polygon|kml:point|kml:interior-polygon|kml:geospatial-query-from-elements|kml:geospatial-query|kml:circle|kml:box|gml:polygon|gml:point|gml:interior-polygon|gml:geospatial-query-from-elements|gml:geospatial-query|gml:circle|gml:box|georss:point|georss:geospatial-query|georss:circle|geo:polygon|geo:point|geo:interior-polygon|geo:geospatial-query-from-elements|geo:geospatial-query|geo:circle|geo:box|fn:zero-or-one|fn:years-from-duration|fn:year-from-dateTime|fn:year-from-date|fn:upper-case|fn:unordered|fn:true|fn:translate|fn:trace|fn:tokenize|fn:timezone-from-time|fn:timezone-from-dateTime|fn:timezone-from-date|fn:sum|fn:subtract-dateTimes-yielding-yearMonthDuration|fn:subtract-dateTimes-yielding-dayTimeDuration|fn:substring-before|fn:substring-after|fn:substring|fn:subsequence|fn:string-to-codepoints|fn:string-pad|fn:string-length|fn:string-join|fn:string|fn:static-base-uri|fn:starts-with|fn:seconds-from-time|fn:seconds-from-duration|fn:seconds-from-dateTime|fn:round-half-to-even|fn:round|fn:root|fn:reverse|fn:resolve-uri|fn:resolve-QName|fn:replace|fn:remove|fn:QName|fn:prefix-from-QName|fn:position|fn:one-or-more|fn:number|fn:not|fn:normalize-unicode|fn:normalize-space|fn:node-name|fn:node-kind|fn:nilled|fn:namespace-uri-from-QName|fn:namespace-uri-for-prefix|fn:namespace-uri|fn:name|fn:months-from-duration|fn:month-from-dateTime|fn:month-from-date|fn:minutes-from-time|fn:minutes-from-duration|fn:minutes-from-dateTime|fn:min|fn:max|fn:matches|fn:lower-case|fn:local-name-from-QName|fn:local-name|fn:last|fn:lang|fn:iri-to-uri|fn:insert-before|fn:index-of|fn:in-scope-prefixes|fn:implicit-timezone|fn:idref|fn:id|fn:hours-from-time|fn:hours-from-duration|fn:hours-from-dateTime|fn:floor|fn:false|fn:expanded-QName|fn:exists|fn:exactly-one|fn:escape-uri|fn:escape-html-uri|fn:error|fn:ends-with|fn:encode-for-uri|fn:empty|fn:document-uri|fn:doc-available|fn:doc|fn:distinct-values|fn:distinct-nodes|fn:default-collation|fn:deep-equal|fn:days-from-duration|fn:day-from-dateTime|fn:day-from-date|fn:data|fn:current-time|fn:current-dateTime|fn:current-date|fn:count|fn:contains|fn:concat|fn:compare|fn:collection|fn:codepoints-to-string|fn:codepoint-equal|fn:ceiling|fn:boolean|fn:base-uri|fn:avg|fn:adjust-time-to-timezone|fn:adjust-dateTime-to-timezone|fn:adjust-date-to-timezone|fn:abs|feed:unsubscribe|feed:subscription|feed:subscribe|feed:request|feed:item|feed:description|excel:clean|entity:enrich|dom:set-pipelines|dom:set-permissions|dom:set-name|dom:set-evaluation-context|dom:set-domain-scope|dom:set-description|dom:remove-pipeline|dom:remove-permissions|dom:remove|dom:get|dom:evaluation-context|dom:domains|dom:domain-scope|dom:create|dom:configuration-set-restart-user|dom:configuration-set-permissions|dom:configuration-set-evaluation-context|dom:configuration-set-default-domain|dom:configuration-get|dom:configuration-create|dom:collection|dom:add-pipeline|dom:add-permissions|dls:retention-rules|dls:retention-rule-remove|dls:retention-rule-insert|dls:retention-rule|dls:purge|dls:node-expand|dls:link-references|dls:link-expand|dls:documents-query|dls:document-versions-query|dls:document-version-uri|dls:document-version-query|dls:document-version-delete|dls:document-version-as-of|dls:document-version|dls:document-update|dls:document-unmanage|dls:document-set-quality|dls:document-set-property|dls:document-set-properties|dls:document-set-permissions|dls:document-set-collections|dls:document-retention-rules|dls:document-remove-properties|dls:document-remove-permissions|dls:document-remove-collections|dls:document-purge|dls:document-manage|dls:document-is-managed|dls:document-insert-and-manage|dls:document-include-query|dls:document-history|dls:document-get-permissions|dls:document-extract-part|dls:document-delete|dls:document-checkout-status|dls:document-checkout|dls:document-checkin|dls:document-add-properties|dls:document-add-permissions|dls:document-add-collections|dls:break-checkout|dls:author-query|dls:as-of-query|dbk:convert|dbg:wait|dbg:value|dbg:stopped|dbg:stop|dbg:step|dbg:status|dbg:stack|dbg:out|dbg:next|dbg:line|dbg:invoke|dbg:function|dbg:finish|dbg:expr|dbg:eval|dbg:disconnect|dbg:detach|dbg:continue|dbg:connect|dbg:clear|dbg:breakpoints|dbg:break|dbg:attached|dbg:attach|cvt:save-converted-documents|cvt:part-uri|cvt:destination-uri|cvt:basepath|cvt:basename|cts:words|cts:word-query-weight|cts:word-query-text|cts:word-query-options|cts:word-query|cts:word-match|cts:walk|cts:uris|cts:uri-match|cts:train|cts:tokenize|cts:thresholds|cts:stem|cts:similar-query-weight|cts:similar-query-nodes|cts:similar-query|cts:shortest-distance|cts:search|cts:score|cts:reverse-query-weight|cts:reverse-query-nodes|cts:reverse-query|cts:remainder|cts:registered-query-weight|cts:registered-query-options|cts:registered-query-ids|cts:registered-query|cts:register|cts:query|cts:quality|cts:properties-query-query|cts:properties-query|cts:polygon-vertices|cts:polygon|cts:point-longitude|cts:point-latitude|cts:point|cts:or-query-queries|cts:or-query|cts:not-query-weight|cts:not-query-query|cts:not-query|cts:near-query-weight|cts:near-query-queries|cts:near-query-options|cts:near-query-distance|cts:near-query|cts:highlight|cts:geospatial-co-occurrences|cts:frequency|cts:fitness|cts:field-words|cts:field-word-query-weight|cts:field-word-query-text|cts:field-word-query-options|cts:field-word-query-field-name|cts:field-word-query|cts:field-word-match|cts:entity-highlight|cts:element-words|cts:element-word-query-weight|cts:element-word-query-text|cts:element-word-query-options|cts:element-word-query-element-name|cts:element-word-query|cts:element-word-match|cts:element-values|cts:element-value-ranges|cts:element-value-query-weight|cts:element-value-query-text|cts:element-value-query-options|cts:element-value-query-element-name|cts:element-value-query|cts:element-value-match|cts:element-value-geospatial-co-occurrences|cts:element-value-co-occurrences|cts:element-range-query-weight|cts:element-range-query-value|cts:element-range-query-options|cts:element-range-query-operator|cts:element-range-query-element-name|cts:element-range-query|cts:element-query-query|cts:element-query-element-name|cts:element-query|cts:element-pair-geospatial-values|cts:element-pair-geospatial-value-match|cts:element-pair-geospatial-query-weight|cts:element-pair-geospatial-query-region|cts:element-pair-geospatial-query-options|cts:element-pair-geospatial-query-longitude-name|cts:element-pair-geospatial-query-latitude-name|cts:element-pair-geospatial-query-element-name|cts:element-pair-geospatial-query|cts:element-pair-geospatial-boxes|cts:element-geospatial-values|cts:element-geospatial-value-match|cts:element-geospatial-query-weight|cts:element-geospatial-query-region|cts:element-geospatial-query-options|cts:element-geospatial-query-element-name|cts:element-geospatial-query|cts:element-geospatial-boxes|cts:element-child-geospatial-values|cts:element-child-geospatial-value-match|cts:element-child-geospatial-query-weight|cts:element-child-geospatial-query-region|cts:element-child-geospatial-query-options|cts:element-child-geospatial-query-element-name|cts:element-child-geospatial-query-child-name|cts:element-child-geospatial-query|cts:element-child-geospatial-boxes|cts:element-attribute-words|cts:element-attribute-word-query-weight|cts:element-attribute-word-query-text|cts:element-attribute-word-query-options|cts:element-attribute-word-query-element-name|cts:element-attribute-word-query-attribute-name|cts:element-attribute-word-query|cts:element-attribute-word-match|cts:element-attribute-values|cts:element-attribute-value-ranges|cts:element-attribute-value-query-weight|cts:element-attribute-value-query-text|cts:element-attribute-value-query-options|cts:element-attribute-value-query-element-name|cts:element-attribute-value-query-attribute-name|cts:element-attribute-value-query|cts:element-attribute-value-match|cts:element-attribute-value-geospatial-co-occurrences|cts:element-attribute-value-co-occurrences|cts:element-attribute-range-query-weight|cts:element-attribute-range-query-value|cts:element-attribute-range-query-options|cts:element-attribute-range-query-operator|cts:element-attribute-range-query-element-name|cts:element-attribute-range-query-attribute-name|cts:element-attribute-range-query|cts:element-attribute-pair-geospatial-values|cts:element-attribute-pair-geospatial-value-match|cts:element-attribute-pair-geospatial-query-weight|cts:element-attribute-pair-geospatial-query-region|cts:element-attribute-pair-geospatial-query-options|cts:element-attribute-pair-geospatial-query-longitude-name|cts:element-attribute-pair-geospatial-query-latitude-name|cts:element-attribute-pair-geospatial-query-element-name|cts:element-attribute-pair-geospatial-query|cts:element-attribute-pair-geospatial-boxes|cts:document-query-uris|cts:document-query|cts:distance|cts:directory-query-uris|cts:directory-query-depth|cts:directory-query|cts:destination|cts:deregister|cts:contains|cts:confidence|cts:collections|cts:collection-query-uris|cts:collection-query|cts:collection-match|cts:classify|cts:circle-radius|cts:circle-center|cts:circle|cts:box-west|cts:box-south|cts:box-north|cts:box-east|cts:box|cts:bearing|cts:arc-intersection|cts:and-query-queries|cts:and-query-options|cts:and-query|cts:and-not-query-positive-query|cts:and-not-query-negative-query|cts:and-not-query|css:get|css:convert|cpf:success|cpf:failure|cpf:document-set-state|cpf:document-set-processing-status|cpf:document-set-last-updated|cpf:document-set-error|cpf:document-get-state|cpf:document-get-processing-status|cpf:document-get-last-updated|cpf:document-get-error|cpf:check-transition|alert:spawn-matching-actions|alert:rule-user-id-query|alert:rule-set-user-id|alert:rule-set-query|alert:rule-set-options|alert:rule-set-name|alert:rule-set-description|alert:rule-set-action|alert:rule-remove|alert:rule-name-query|alert:rule-insert|alert:rule-id-query|alert:rule-get-user-id|alert:rule-get-query|alert:rule-get-options|alert:rule-get-name|alert:rule-get-id|alert:rule-get-description|alert:rule-get-action|alert:rule-action-query|alert:remove-triggers|alert:make-rule|alert:make-log-action|alert:make-config|alert:make-action|alert:invoke-matching-actions|alert:get-my-rules|alert:get-all-rules|alert:get-actions|alert:find-matching-rules|alert:create-triggers|alert:config-set-uri|alert:config-set-trigger-ids|alert:config-set-options|alert:config-set-name|alert:config-set-description|alert:config-set-cpf-domain-names|alert:config-set-cpf-domain-ids|alert:config-insert|alert:config-get-uri|alert:config-get-trigger-ids|alert:config-get-options|alert:config-get-name|alert:config-get-id|alert:config-get-description|alert:config-get-cpf-domain-names|alert:config-get-cpf-domain-ids|alert:config-get|alert:config-delete|alert:action-set-options|alert:action-set-name|alert:action-set-module-root|alert:action-set-module-db|alert:action-set-module|alert:action-set-description|alert:action-remove|alert:action-insert|alert:action-get-options|alert:action-get-name|alert:action-get-module-root|alert:action-get-module-db|alert:action-get-module|alert:action-get-description|zero-or-one|years-from-duration|year-from-dateTime|year-from-date|upper-case|unordered|true|translate|trace|tokenize|timezone-from-time|timezone-from-dateTime|timezone-from-date|sum|subtract-dateTimes-yielding-yearMonthDuration|subtract-dateTimes-yielding-dayTimeDuration|substring-before|substring-after|substring|subsequence|string-to-codepoints|string-pad|string-length|string-join|string|static-base-uri|starts-with|seconds-from-time|seconds-from-duration|seconds-from-dateTime|round-half-to-even|round|root|reverse|resolve-uri|resolve-QName|replace|remove|QName|prefix-from-QName|position|one-or-more|number|not|normalize-unicode|normalize-space|node-name|node-kind|nilled|namespace-uri-from-QName|namespace-uri-for-prefix|namespace-uri|name|months-from-duration|month-from-dateTime|month-from-date|minutes-from-time|minutes-from-duration|minutes-from-dateTime|min|max|matches|lower-case|local-name-from-QName|local-name|last|lang|iri-to-uri|insert-before|index-of|in-scope-prefixes|implicit-timezone|idref|id|hours-from-time|hours-from-duration|hours-from-dateTime|floor|false|expanded-QName|exists|exactly-one|escape-uri|escape-html-uri|error|ends-with|encode-for-uri|empty|document-uri|doc-available|doc|distinct-values|distinct-nodes|default-collation|deep-equal|days-from-duration|day-from-dateTime|day-from-date|data|current-time|current-dateTime|current-date|count|contains|concat|compare|collection|codepoints-to-string|codepoint-equal|ceiling|boolean|base-uri|avg|adjust-time-to-timezone|adjust-dateTime-to-timezone|adjust-date-to-timezone|abs)\b/], -["pln",/^[\w:-]+/],["pln",/^[\t\n\r \xa0]+/]]),["xq","xquery"]); diff --git a/junit4-ant/src/tasks/js/google-code-prettify/lang-yaml.js b/junit4-ant/src/tasks/js/google-code-prettify/lang-yaml.js deleted file mode 100644 index c38729b6..00000000 --- a/junit4-ant/src/tasks/js/google-code-prettify/lang-yaml.js +++ /dev/null @@ -1,2 +0,0 @@ -var a=null; -PR.registerLangHandler(PR.createSimpleLexer([["pun",/^[:>?|]+/,a,":|>?"],["dec",/^%(?:YAML|TAG)[^\n\r#]+/,a,"%"],["typ",/^&\S+/,a,"&"],["typ",/^!\S*/,a,"!"],["str",/^"(?:[^"\\]|\\.)*(?:"|$)/,a,'"'],["str",/^'(?:[^']|'')*(?:'|$)/,a,"'"],["com",/^#[^\n\r]*/,a,"#"],["pln",/^\s+/,a," \t\r\n"]],[["dec",/^(?:---|\.\.\.)(?:[\n\r]|$)/],["pun",/^-/],["kwd",/^\w+:[\n\r ]/],["pln",/^\w+/]]),["yaml","yml"]); diff --git a/junit4-ant/src/tasks/js/google-code-prettify/prettify.css b/junit4-ant/src/tasks/js/google-code-prettify/prettify.css deleted file mode 100644 index d44b3a22..00000000 --- a/junit4-ant/src/tasks/js/google-code-prettify/prettify.css +++ /dev/null @@ -1 +0,0 @@ -.pln{color:#000}@media screen{.str{color:#080}.kwd{color:#008}.com{color:#800}.typ{color:#606}.lit{color:#066}.pun,.opn,.clo{color:#660}.tag{color:#008}.atn{color:#606}.atv{color:#080}.dec,.var{color:#606}.fun{color:red}}@media print,projection{.str{color:#060}.kwd{color:#006;font-weight:bold}.com{color:#600;font-style:italic}.typ{color:#404;font-weight:bold}.lit{color:#044}.pun,.opn,.clo{color:#440}.tag{color:#006;font-weight:bold}.atn{color:#404}.atv{color:#060}}pre.prettyprint{padding:2px;border:1px solid #888}ol.linenums{margin-top:0;margin-bottom:0}li.L0,li.L1,li.L2,li.L3,li.L5,li.L6,li.L7,li.L8{list-style-type:none}li.L1,li.L3,li.L5,li.L7,li.L9{background:#eee} \ No newline at end of file diff --git a/junit4-ant/src/tasks/js/google-code-prettify/prettify.js b/junit4-ant/src/tasks/js/google-code-prettify/prettify.js deleted file mode 100644 index eef5ad7e..00000000 --- a/junit4-ant/src/tasks/js/google-code-prettify/prettify.js +++ /dev/null @@ -1,28 +0,0 @@ -var q=null;window.PR_SHOULD_USE_CONTINUATION=!0; -(function(){function L(a){function m(a){var f=a.charCodeAt(0);if(f!==92)return f;var b=a.charAt(1);return(f=r[b])?f:"0"<=b&&b<="7"?parseInt(a.substring(1),8):b==="u"||b==="x"?parseInt(a.substring(2),16):a.charCodeAt(1)}function e(a){if(a<32)return(a<16?"\\x0":"\\x")+a.toString(16);a=String.fromCharCode(a);if(a==="\\"||a==="-"||a==="["||a==="]")a="\\"+a;return a}function h(a){for(var f=a.substring(1,a.length-1).match(/\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\[0-3][0-7]{0,2}|\\[0-7]{1,2}|\\[\S\s]|[^\\]/g),a= -[],b=[],o=f[0]==="^",c=o?1:0,i=f.length;c122||(d<65||j>90||b.push([Math.max(65,j)|32,Math.min(d,90)|32]),d<97||j>122||b.push([Math.max(97,j)&-33,Math.min(d,122)&-33]))}}b.sort(function(a,f){return a[0]-f[0]||f[1]-a[1]});f=[];j=[NaN,NaN];for(c=0;ci[0]&&(i[1]+1>i[0]&&b.push("-"),b.push(e(i[1])));b.push("]");return b.join("")}function y(a){for(var f=a.source.match(/\[(?:[^\\\]]|\\[\S\s])*]|\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\\d+|\\[^\dux]|\(\?[!:=]|[()^]|[^()[\\^]+/g),b=f.length,d=[],c=0,i=0;c=2&&a==="["?f[c]=h(j):a!=="\\"&&(f[c]=j.replace(/[A-Za-z]/g,function(a){a=a.charCodeAt(0);return"["+String.fromCharCode(a&-33,a|32)+"]"}));return f.join("")}for(var t=0,s=!1,l=!1,p=0,d=a.length;p=5&&"lang-"===b.substring(0,5))&&!(o&&typeof o[1]==="string"))c=!1,b="src";c||(r[f]=b)}i=d;d+=f.length;if(c){c=o[1];var j=f.indexOf(c),k=j+c.length;o[2]&&(k=f.length-o[2].length,j=k-c.length);b=b.substring(5);B(l+i,f.substring(0,j),e,p);B(l+i+j,c,C(b,c),p);B(l+i+k,f.substring(k),e,p)}else p.push(l+i,b)}a.e=p}var h={},y;(function(){for(var e=a.concat(m), -l=[],p={},d=0,g=e.length;d=0;)h[n.charAt(k)]=r;r=r[1];n=""+r;p.hasOwnProperty(n)||(l.push(r),p[n]=q)}l.push(/[\S\s]/);y=L(l)})();var t=m.length;return e}function u(a){var m=[],e=[];a.tripleQuotedStrings?m.push(["str",/^(?:'''(?:[^'\\]|\\[\S\s]|''?(?=[^']))*(?:'''|$)|"""(?:[^"\\]|\\[\S\s]|""?(?=[^"]))*(?:"""|$)|'(?:[^'\\]|\\[\S\s])*(?:'|$)|"(?:[^"\\]|\\[\S\s])*(?:"|$))/,q,"'\""]):a.multiLineStrings?m.push(["str",/^(?:'(?:[^'\\]|\\[\S\s])*(?:'|$)|"(?:[^"\\]|\\[\S\s])*(?:"|$)|`(?:[^\\`]|\\[\S\s])*(?:`|$))/, -q,"'\"`"]):m.push(["str",/^(?:'(?:[^\n\r'\\]|\\.)*(?:'|$)|"(?:[^\n\r"\\]|\\.)*(?:"|$))/,q,"\"'"]);a.verbatimStrings&&e.push(["str",/^@"(?:[^"]|"")*(?:"|$)/,q]);var h=a.hashComments;h&&(a.cStyleComments?(h>1?m.push(["com",/^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/,q,"#"]):m.push(["com",/^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\n\r]*)/,q,"#"]),e.push(["str",/^<(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)>/,q])):m.push(["com",/^#[^\n\r]*/, -q,"#"]));a.cStyleComments&&(e.push(["com",/^\/\/[^\n\r]*/,q]),e.push(["com",/^\/\*[\S\s]*?(?:\*\/|$)/,q]));a.regexLiterals&&e.push(["lang-regex",/^(?:^^\.?|[!+-]|!=|!==|#|%|%=|&|&&|&&=|&=|\(|\*|\*=|\+=|,|-=|->|\/|\/=|:|::|;|<|<<|<<=|<=|=|==|===|>|>=|>>|>>=|>>>|>>>=|[?@[^]|\^=|\^\^|\^\^=|{|\||\|=|\|\||\|\|=|~|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\s*(\/(?=[^*/])(?:[^/[\\]|\\[\S\s]|\[(?:[^\\\]]|\\[\S\s])*(?:]|$))+\/)/]);(h=a.types)&&e.push(["typ",h]);a=(""+a.keywords).replace(/^ | $/g, -"");a.length&&e.push(["kwd",RegExp("^(?:"+a.replace(/[\s,]+/g,"|")+")\\b"),q]);m.push(["pln",/^\s+/,q," \r\n\t\xa0"]);e.push(["lit",/^@[$_a-z][\w$@]*/i,q],["typ",/^(?:[@_]?[A-Z]+[a-z][\w$@]*|\w+_t\b)/,q],["pln",/^[$_a-z][\w$@]*/i,q],["lit",/^(?:0x[\da-f]+|(?:\d(?:_\d+)*\d*(?:\.\d*)?|\.\d\+)(?:e[+-]?\d+)?)[a-z]*/i,q,"0123456789"],["pln",/^\\[\S\s]?/,q],["pun",/^.[^\s\w"-$'./@\\`]*/,q]);return x(m,e)}function D(a,m){function e(a){switch(a.nodeType){case 1:if(k.test(a.className))break;if("BR"===a.nodeName)h(a), -a.parentNode&&a.parentNode.removeChild(a);else for(a=a.firstChild;a;a=a.nextSibling)e(a);break;case 3:case 4:if(p){var b=a.nodeValue,d=b.match(t);if(d){var c=b.substring(0,d.index);a.nodeValue=c;(b=b.substring(d.index+d[0].length))&&a.parentNode.insertBefore(s.createTextNode(b),a.nextSibling);h(a);c||a.parentNode.removeChild(a)}}}}function h(a){function b(a,d){var e=d?a.cloneNode(!1):a,f=a.parentNode;if(f){var f=b(f,1),g=a.nextSibling;f.appendChild(e);for(var h=g;h;h=g)g=h.nextSibling,f.appendChild(h)}return e} -for(;!a.nextSibling;)if(a=a.parentNode,!a)return;for(var a=b(a.nextSibling,0),e;(e=a.parentNode)&&e.nodeType===1;)a=e;d.push(a)}var k=/(?:^|\s)nocode(?:\s|$)/,t=/\r\n?|\n/,s=a.ownerDocument,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&&(l=s.defaultView.getComputedStyle(a,q).getPropertyValue("white-space"));var p=l&&"pre"===l.substring(0,3);for(l=s.createElement("LI");a.firstChild;)l.appendChild(a.firstChild);for(var d=[l],g=0;g=0;){var h=m[e];A.hasOwnProperty(h)?window.console&&console.warn("cannot override language handler %s",h):A[h]=a}}function C(a,m){if(!a||!A.hasOwnProperty(a))a=/^\s*=o&&(h+=2);e>=c&&(a+=2)}}catch(w){"console"in window&&console.log(w&&w.stack?w.stack:w)}}var v=["break,continue,do,else,for,if,return,while"],w=[[v,"auto,case,char,const,default,double,enum,extern,float,goto,int,long,register,short,signed,sizeof,static,struct,switch,typedef,union,unsigned,void,volatile"], -"catch,class,delete,false,import,new,operator,private,protected,public,this,throw,true,try,typeof"],F=[w,"alignof,align_union,asm,axiom,bool,concept,concept_map,const_cast,constexpr,decltype,dynamic_cast,explicit,export,friend,inline,late_check,mutable,namespace,nullptr,reinterpret_cast,static_assert,static_cast,template,typeid,typename,using,virtual,where"],G=[w,"abstract,boolean,byte,extends,final,finally,implements,import,instanceof,null,native,package,strictfp,super,synchronized,throws,transient"], -H=[G,"as,base,by,checked,decimal,delegate,descending,dynamic,event,fixed,foreach,from,group,implicit,in,interface,internal,into,is,lock,object,out,override,orderby,params,partial,readonly,ref,sbyte,sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,var"],w=[w,"debugger,eval,export,function,get,null,set,undefined,var,with,Infinity,NaN"],I=[v,"and,as,assert,class,def,del,elif,except,exec,finally,from,global,import,in,is,lambda,nonlocal,not,or,pass,print,raise,try,with,yield,False,True,None"], -J=[v,"alias,and,begin,case,class,def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,rescue,retry,self,super,then,true,undef,unless,until,when,yield,BEGIN,END"],v=[v,"case,done,elif,esac,eval,fi,function,in,local,set,then,until"],K=/^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)/,N=/\S/,O=u({keywords:[F,H,w,"caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END"+ -I,J,v],hashComments:!0,cStyleComments:!0,multiLineStrings:!0,regexLiterals:!0}),A={};k(O,["default-code"]);k(x([],[["pln",/^[^]*(?:>|$)/],["com",/^<\!--[\S\s]*?(?:--\>|$)/],["lang-",/^<\?([\S\s]+?)(?:\?>|$)/],["lang-",/^<%([\S\s]+?)(?:%>|$)/],["pun",/^(?:<[%?]|[%?]>)/],["lang-",/^]*>([\S\s]+?)<\/xmp\b[^>]*>/i],["lang-js",/^]*>([\S\s]*?)(<\/script\b[^>]*>)/i],["lang-css",/^]*>([\S\s]*?)(<\/style\b[^>]*>)/i],["lang-in.tag",/^(<\/?[a-z][^<>]*>)/i]]), -["default-markup","htm","html","mxml","xhtml","xml","xsl"]);k(x([["pln",/^\s+/,q," \t\r\n"],["atv",/^(?:"[^"]*"?|'[^']*'?)/,q,"\"'"]],[["tag",/^^<\/?[a-z](?:[\w-.:]*\w)?|\/?>$/i],["atn",/^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],["lang-uq.val",/^=\s*([^\s"'>]*(?:[^\s"'/>]|\/(?=\s)))/],["pun",/^[/<->]+/],["lang-js",/^on\w+\s*=\s*"([^"]+)"/i],["lang-js",/^on\w+\s*=\s*'([^']+)'/i],["lang-js",/^on\w+\s*=\s*([^\s"'>]+)/i],["lang-css",/^style\s*=\s*"([^"]+)"/i],["lang-css",/^style\s*=\s*'([^']+)'/i],["lang-css", -/^style\s*=\s*([^\s"'>]+)/i]]),["in.tag"]);k(x([],[["atv",/^[\S\s]+/]]),["uq.val"]);k(u({keywords:F,hashComments:!0,cStyleComments:!0,types:K}),["c","cc","cpp","cxx","cyc","m"]);k(u({keywords:"null,true,false"}),["json"]);k(u({keywords:H,hashComments:!0,cStyleComments:!0,verbatimStrings:!0,types:K}),["cs"]);k(u({keywords:G,cStyleComments:!0}),["java"]);k(u({keywords:v,hashComments:!0,multiLineStrings:!0}),["bsh","csh","sh"]);k(u({keywords:I,hashComments:!0,multiLineStrings:!0,tripleQuotedStrings:!0}), -["cv","py"]);k(u({keywords:"caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END",hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),["perl","pl","pm"]);k(u({keywords:J,hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),["rb"]);k(u({keywords:w,cStyleComments:!0,regexLiterals:!0}),["js"]);k(u({keywords:"all,and,by,catch,class,else,extends,false,finally,for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then,true,try,unless,until,when,while,yes", -hashComments:3,cStyleComments:!0,multilineStrings:!0,tripleQuotedStrings:!0,regexLiterals:!0}),["coffee"]);k(x([],[["str",/^[\S\s]+/]]),["regex"]);window.prettyPrintOne=function(a,m,e){var h=document.createElement("PRE");h.innerHTML=a;e&&D(h,e);E({g:m,i:e,h:h});return h.innerHTML};window.prettyPrint=function(a){function m(){for(var e=window.PR_SHOULD_USE_CONTINUATION?l.now()+250:Infinity;p=0){var k=k.match(g),f,b;if(b= -!k){b=n;for(var o=void 0,c=b.firstChild;c;c=c.nextSibling)var i=c.nodeType,o=i===1?o?b:c:i===3?N.test(c.nodeValue)?b:o:o;b=(f=o===b?void 0:o)&&"CODE"===f.tagName}b&&(k=f.className.match(g));k&&(k=k[1]);b=!1;for(o=n.parentNode;o;o=o.parentNode)if((o.tagName==="pre"||o.tagName==="code"||o.tagName==="xmp")&&o.className&&o.className.indexOf("prettyprint")>=0){b=!0;break}b||((b=(b=n.className.match(/\blinenums\b(?::(\d+))?/))?b[1]&&b[1].length?+b[1]:!0:!1)&&D(n,b),d={g:k,h:n,i:b},E(d))}}p foo = new ArrayList<>(); - for (int i = randomIntBetween(2, 1000); --i > 0;) { - foo.add(randomAsciiLettersOfLength(20)); - } - final EventBus aggregatedBus = new EventBus("aggregated"); - - final AtomicBoolean hadErrors = new AtomicBoolean(); - - // Code mirrors JUnit4's behavior. - final Deque stealingQueue = new ArrayDeque(foo); - aggregatedBus.register(new Object() { - volatile Thread foo; - - @Subscribe - public void onSlaveIdle(SlaveIdle slave) { - final Thread other = foo; - if (other != null) { - hadErrors.set(true); - throw new RuntimeException("Wtf? two threads in a handler: " - + other + " and " + Thread.currentThread()); - } - foo = Thread.currentThread(); - - if (stealingQueue.isEmpty()) { - slave.finished(); - } else { - String suiteName = stealingQueue.pop(); - slave.newSuite(suiteName); - } - - foo = null; - } - }); - - // stress. - ExecutorService executor = Executors.newCachedThreadPool(); - final List> slaves = new ArrayList<>(); - for (int i = 0; i < randomIntBetween(1, 10); i++) { - slaves.add(new Callable() { - @Override - public Void call() throws Exception { - aggregatedBus.post(new SlaveIdle()); - return null; - } - }); - } - for (Future f : executor.invokeAll(slaves)) { - f.get(); - } - executor.shutdown(); - - assertFalse(hadErrors.get()); - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/TestJsonByteArrayRoundtrip.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/TestJsonByteArrayRoundtrip.java deleted file mode 100644 index 27f1ced8..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/TestJsonByteArrayRoundtrip.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.util.Arrays; - -import org.junit.Assert; -import org.junit.Test; - -import com.carrotsearch.ant.tasks.junit4.events.AppendStdErrEvent; -import com.carrotsearch.ant.tasks.junit4.events.Deserializer; -import com.carrotsearch.ant.tasks.junit4.events.IEvent; -import com.carrotsearch.ant.tasks.junit4.events.Serializer; -import com.carrotsearch.randomizedtesting.RandomizedTest; -import com.carrotsearch.randomizedtesting.annotations.Repeat; - -public class TestJsonByteArrayRoundtrip extends RandomizedTest { - @Test - @Repeat(iterations = 100) - public void testRoundTrip() throws Exception { - byte[] bytes = new byte[randomIntBetween(0, 1024)]; - getRandom().nextBytes(bytes); - - check(bytes); - } - - @Test - public void testSimpleAscii() throws Exception { - check("ABCabc0123".getBytes("UTF-8")); - check("\n\t".getBytes("UTF-8")); - } - - private void check(byte[] bytes) throws Exception { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - Serializer s = new Serializer(baos); - s.serialize(new AppendStdErrEvent(bytes, 0, bytes.length)); - s.flush(); - s.close(); - - Deserializer deserializer = new Deserializer(new ByteArrayInputStream(baos.toByteArray()), - Thread.currentThread().getContextClassLoader()); - IEvent deserialize = deserializer.deserialize(); - - Assert.assertTrue(deserialize instanceof AppendStdErrEvent); - AppendStdErrEvent e = ((AppendStdErrEvent) deserialize); - baos.reset(); - e.copyTo(baos); - Assert.assertTrue( - "Exp: " + Arrays.toString(bytes) + "\n" + - "was: " + Arrays.toString(baos.toByteArray()), - Arrays.equals(bytes, baos.toByteArray())); - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/TestXmlStringsRoundtrip.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/TestXmlStringsRoundtrip.java deleted file mode 100644 index 32595af9..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/TestXmlStringsRoundtrip.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.nio.charset.StandardCharsets; -import java.util.Arrays; -import java.util.Random; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; - -import org.junit.Test; -import org.simpleframework.xml.Attribute; -import org.simpleframework.xml.Element; -import org.simpleframework.xml.Root; -import org.simpleframework.xml.core.Persister; -import org.simpleframework.xml.transform.RegistryMatcher; -import org.xml.sax.SAXParseException; - -import com.carrotsearch.ant.tasks.junit4.listeners.antxml.XmlStringTransformerAccess; -import com.carrotsearch.randomizedtesting.RandomizedTest; -import com.carrotsearch.randomizedtesting.annotations.Repeat; - -public class TestXmlStringsRoundtrip extends RandomizedTest { - @Test - @Repeat(iterations = 100) - public void testRoundTrip() throws Exception { - char[] chars = new char[randomIntBetween(0, 1024)]; - Random random = getRandom(); - for (int i = 0; i < chars.length; i++) { - chars[i] = (char) random.nextInt(); - } - - check(chars); - } - - @Test - public void testBoundary() throws Exception { - check(new char [] {'a', 0x0000, 'z'}); - check(new char [] {'a', 0x0001, 'z'}); - } - - @Root - public static class Model { - @Attribute - public String attribute; - - @Element(name = "system-out", data = true, required = true) - public String contents = ""; - - public Model() {} - - public Model(String s) { - attribute = contents = s; - } - } - - private void check(char[] chars) throws Exception { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - - RegistryMatcher rm = new RegistryMatcher(); - rm.bind(String.class, XmlStringTransformerAccess.getInstance()); - Persister persister = new Persister(rm); - persister.write(new Model(new String(chars)), baos); - - DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); - DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); - try { - docBuilder.parse(new ByteArrayInputStream(baos.toByteArray())); - } catch (SAXParseException e) { - System.out.println("Input: " + Arrays.toString(chars)); - System.out.println("XML: " + new String(baos.toByteArray(), StandardCharsets.UTF_8)); - throw e; - } - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/events/TestRemoteEventSerialization.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/events/TestRemoteEventSerialization.java deleted file mode 100644 index 062c227d..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/events/TestRemoteEventSerialization.java +++ /dev/null @@ -1,156 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.events; - -import java.io.IOException; -import java.io.StringReader; -import java.io.StringWriter; -import java.nio.charset.StandardCharsets; -import java.util.Calendar; -import java.util.Locale; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.Description; -import org.junit.runner.RunWith; -import org.junit.runner.notification.Failure; - -import com.carrotsearch.ant.tasks.junit4.gson.stream.JsonReader; -import com.carrotsearch.ant.tasks.junit4.gson.stream.JsonWriter; -import com.carrotsearch.randomizedtesting.RandomizedRunner; -import com.carrotsearch.randomizedtesting.RandomizedTest; -import com.carrotsearch.randomizedtesting.annotations.Nightly; - -import static org.junit.Assert.*; - -public class TestRemoteEventSerialization extends RandomizedTest { - @RunWith(RandomizedRunner.class) - @Nightly - public static class Clazz1 {} - public static class Clazz2 {} - - private Description description; - private long start; - private long end; - private Failure failure; - - @Before - public void setup() { - Class suiteClass = randomFrom(new Class [] { - Clazz1.class, - Clazz2.class - }); - description = Description.createSuiteDescription(suiteClass); - - Calendar c = Calendar.getInstance(Locale.ROOT); - c.set(2015, 10, 20, 0, 0, 0); - start = c.getTimeInMillis(); - end = start + randomIntBetween(0, 1000); - - String MARKER = ""; - Throwable thrownException; - try { - throw new RuntimeException(MARKER); - } catch (Throwable t) { - thrownException = t; - } - - failure = new Failure(description, thrownException); - } - - @Test - public void eventBootstrap() throws IOException { - checkRoundtrip(new BootstrapEvent()); - } - - @Test - public void eventIdle() throws IOException { - checkRoundtrip(new IdleEvent()); - } - - @Test - public void eventQuit() throws IOException { - checkRoundtrip(new QuitEvent()); - } - - @Test - public void eventStdout() throws IOException { - byte [] value = randomRealisticUnicodeOfCodepointLengthBetween(0, 10).getBytes(StandardCharsets.UTF_8); - checkRoundtrip(new AppendStdOutEvent(value, 0, value.length)); - } - - @Test - public void eventStderr() throws IOException { - byte [] value = randomRealisticUnicodeOfCodepointLengthBetween(0, 10).getBytes(StandardCharsets.UTF_8); - checkRoundtrip(new AppendStdErrEvent(value, 0, value.length)); - } - - - @Test - public void eventSuiteStarted() throws IOException { - checkRoundtrip(new SuiteStartedEvent(description, System.currentTimeMillis())); - } - - @Test - public void eventSuiteFailure() throws IOException { - checkRoundtrip(new SuiteFailureEvent(failure)); - } - - @Test - public void eventSuiteCompleted() throws IOException { - checkRoundtrip(new SuiteCompletedEvent(description, start, end)); - } - - @Test - public void eventTestStartedEvent() throws IOException { - checkRoundtrip(new TestStartedEvent(description)); - } - - @Test - public void eventTestFailureEvent() throws IOException { - checkRoundtrip(new TestFailureEvent(failure)); - } - - @Test - public void eventTestIgnoredAssumptionEvent() throws IOException { - checkRoundtrip(new TestIgnoredAssumptionEvent(failure)); - } - - @Test - public void eventTestIgnoredEvent() throws IOException { - checkRoundtrip(new TestIgnoredEvent(description, randomUnicodeOfLength(10))); - } - - @Test - public void eventTestFinishedEvent() throws IOException { - checkRoundtrip(new TestFinishedEvent(description, start, end)); - } - - private void checkRoundtrip(RemoteEvent event) throws IOException { - StringWriter sw = new StringWriter(); - - final boolean lenient = randomBoolean(); - JsonWriter jw = new JsonWriter(sw); - jw.setIndent(" "); - jw.setLenient(lenient); - event.serialize(jw); - jw.close(); - - String serialized1 = sw.toString(); - JsonReader jr = new JsonReader(new StringReader(serialized1)); - jr.setLenient(lenient); - RemoteEvent deserialized = event.getType().deserialize(jr); - - - // If we serialize again, the contents should be identical. - sw.getBuffer().setLength(0); - jw = new JsonWriter(sw); - jw.setIndent(" "); - jw.setLenient(lenient); - deserialized.serialize(jw); - jw.close(); - - String serialized2 = sw.toString(); - if (!serialized2.equals(serialized1)) { - fail("Roundtrip serialization failed:\n1: " + serialized1 + "\n2: " + serialized2); - } - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/AntBuildFileTestBase.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/AntBuildFileTestBase.java deleted file mode 100644 index ea0689dd..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/AntBuildFileTestBase.java +++ /dev/null @@ -1,150 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.it; - -import static org.hamcrest.CoreMatchers.*; - -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.IOException; -import java.io.PrintStream; - -import org.apache.tools.ant.BuildException; -import org.apache.tools.ant.DefaultLogger; -import org.apache.tools.ant.MagicNames; -import org.apache.tools.ant.Project; -import org.apache.tools.ant.ProjectHelper; -import org.apache.tools.ant.launch.Launcher; -import org.apache.tools.ant.taskdefs.Java; -import org.apache.tools.ant.types.Path; -import org.apache.tools.ant.util.LoaderUtils; -import org.junit.After; -import org.junit.Assert; - -/** - * An equivalent of BuildFileTest for JUnit4. - */ -public class AntBuildFileTestBase { - private Project project; - private ByteArrayOutputStream output; - private DefaultLogger listener; - - protected PrintStream restoreSysout; - protected PrintStream restoreSyserr; - - protected void setupProject(File projectFile) { - try { - restoreSysout = System.out; - restoreSyserr = System.err; - output = new ByteArrayOutputStream(); - PrintStream ps = new PrintStream(output, true, "UTF-8"); - System.setOut(ps); - System.setErr(ps); - - project = new Project(); - project.init(); - - project.setUserProperty(MagicNames.ANT_FILE, projectFile.getAbsolutePath()); - ProjectHelper.configureProject(project, projectFile); - - listener = new DefaultLogger(); - listener.setMessageOutputLevel(Project.MSG_DEBUG); - listener.setErrorPrintStream(ps); - listener.setOutputPrintStream(ps); - getProject().addBuildListener(listener); - - DefaultLogger console = new DefaultLogger(); - console.setMessageOutputLevel(Project.MSG_INFO); - console.setErrorPrintStream(restoreSyserr); - console.setOutputPrintStream(restoreSysout); - getProject().addBuildListener(console); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - @After - public void restoreSysouts() { - if (restoreSysout != null) System.setOut(restoreSysout); - if (restoreSyserr != null) System.setErr(restoreSyserr); - } - - protected final Project getProject() { - if (project == null) { - throw new IllegalStateException( - "Setup project file with setupProject(File) first."); - } - return project; - } - - protected final void assertLogContains(String substring) { - Assert.assertTrue("Log did not contain: '" + substring + "'", getLog() - .contains(substring)); - } - - protected final void assertLogDoesNotContain(String substring) { - Assert.assertTrue("Log contained: '" + substring + "'", - !getLog().contains(substring)); - } - - protected final String getLog() { - try { - return new String(output.toByteArray(), "UTF-8"); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - protected final void expectBuildExceptionContaining(String target, - String message, String... additionalMessages) { - try { - executeTarget(target); - Assert.fail("Expected a build failure with message: " + message); - } catch (BuildException e) { - Assert.assertThat(e.getMessage(), containsString(message)); - for (String m : additionalMessages) { - Assert.assertThat(e.getMessage(), containsString(m)); - } - } - } - - protected final void executeTarget(String target) { - getProject().executeTarget(target); - } - - protected final void executeForkedTarget(String target) { - executeForkedTarget(target, 10 * 1000L); - } - - protected final void executeForkedTarget(String target, long timeout) { - Path antPath = new Path(getProject()); - antPath.createPathElement().setLocation(sourceOf(Project.class)); - antPath.createPathElement().setLocation(sourceOf(Launcher.class)); - - Java java = new Java(); - java.setTaskName("forked"); - java.setProject(getProject()); - java.setClassname("org.apache.tools.ant.launch.Launcher"); - java.createClasspath().add(antPath); - java.setFork(true); - java.setSpawn(false); - java.setTimeout(timeout); - java.setFailonerror(false); - java.setOutputproperty("stdout"); - java.setErrorProperty("stderr"); - - java.createArg().setValue("-f"); - java.createArg().setValue(getProject().getUserProperty(MagicNames.ANT_FILE)); - java.createArg().setValue(target); - java.execute(); - - getProject().log("Forked stdout:\n" + getProject().getProperty("stdout")); - getProject().log("Forked stderr:\n" + getProject().getProperty("stderr")); - } - - /** - * Get the source location of a given class. - */ - private static File sourceOf(Class clazz) { - return LoaderUtils.getResourceSource( - clazz.getClassLoader(), clazz.getName().replace('.', '/') + ".class"); - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/JUnit4XmlTestBase.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/JUnit4XmlTestBase.java deleted file mode 100644 index 8ced8805..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/JUnit4XmlTestBase.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.it; - -import java.io.File; -import java.io.IOException; -import java.net.URI; -import java.net.URL; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; - -import org.junit.Before; -import org.junit.Rule; -import org.junit.rules.TestRule; -import org.junit.runner.Description; -import org.junit.runners.model.Statement; - -/** - * A base class for tests contained in junit4.xml - * file. - */ -public class JUnit4XmlTestBase extends AntBuildFileTestBase { - @Rule - public TestRule dumpLogOnError = new TestRule() { - @Override - public Statement apply(final Statement base, Description description) { - return new Statement() { - @Override - public void evaluate() throws Throwable { - try { - base.evaluate(); - } catch (Throwable e) { - System.out.println("Ant log: " + getLog()); - throw e; - } - } - }; - } - }; - - @Before - public void setUp() throws Exception { - URI resource = getClass().getClassLoader().getResource("junit4.xml").toURI(); - if (!resource.getScheme().equals("file")) { - throw new IOException("junit4.xml not under a file URI: " + resource); - } - - Path absolute = Paths.get(resource).toAbsolutePath(); - // System.out.println("junit4.xml at: " + absolute + (Files.exists(absolute) ? " (exists)" : " (does not exist)")); - - super.setupProject(absolute.toFile()); - } - - protected static int countPattern(String output, String substr) { - int count = 0; - for (int i = 0; i < output.length();) { - int index = output.indexOf(substr, i); - if (index < 0) { - break; - } - count++; - i = index + 1; - } - return count; - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestAltJavaVendors.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestAltJavaVendors.java deleted file mode 100644 index 02ad613c..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestAltJavaVendors.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.it; - - -import java.io.File; - -import org.apache.tools.ant.types.Path; -import org.junit.Assert; -import org.junit.Assume; -import org.junit.Test; - - -public class TestAltJavaVendors extends JUnit4XmlTestBase { - @Test - public void altVendors() { - String altVendors = System.getProperty("alt.jvms"); - Assume.assumeTrue(altVendors != null && !altVendors.trim().isEmpty()); - - for (String jvm : new Path(getProject(), altVendors).list()) { - getProject().log("Trying JVM: " + jvm); - Assert.assertTrue("JVM is not a file: " + jvm, new File(jvm).isFile()); - Assert.assertTrue("JVM is not executable: " + jvm, new File(jvm).canExecute()); - - getProject().setProperty("jvm.exec", jvm); - expectBuildExceptionContaining("alt-vendor", - "1 suite, 5 tests, 1 error, 1 failure, 2 ignored (1 assumption)"); - } - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestAntXmlReport.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestAntXmlReport.java deleted file mode 100644 index 455bec52..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestAntXmlReport.java +++ /dev/null @@ -1,97 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.it; - -import static org.junit.Assert.*; - -import java.io.File; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; - -import org.junit.Assert; -import org.junit.Test; -import org.simpleframework.xml.Attribute; -import org.simpleframework.xml.Element; -import org.simpleframework.xml.Order; -import org.simpleframework.xml.Root; -import org.simpleframework.xml.core.Persister; - -public class TestAntXmlReport extends JUnit4XmlTestBase { - @Root(name = "failsafe-summary") - @Order(elements = {"completed", "errors", "failures", "skipped", "failureMessage"}) - public static class MavenFailsafeSummaryModel_Local { - @Attribute(required = false) - public Integer result; - - @Attribute - public boolean timeout = false; - - @Element - public int completed; - - @Element - public int errors; - - @Element - public int failures; - - @Element - public int skipped; - - @Element(required = false) - public String failureMessage = ""; - } - - @Test - public void antxml() throws Exception { - super.executeTarget("antxml"); - - // Simple check for existence. - Assert.assertTrue( - new File(getProject().getBaseDir(), "ant-xmls/TEST-com.carrotsearch.ant.tasks.junit4.tests.TestBeforeClassError.xml").length() > 0); - - Assert.assertTrue( - new File(getProject().getBaseDir(), "ant-xmls/TEST-com.carrotsearch.ant.tasks.junit4.tests.replication.TestSuiteReplicated-2.xml").length() > 0); - - // Check for warning messages about duplicate suites. - assertLogContains("Duplicate suite name used with XML reports"); - - // Attempt to read and parse. - File basedir = new File(getProject().getBaseDir(), "ant-xmls"); - for (File f : basedir.listFiles()) { - if (f.isFile() && f.getName().endsWith(".xml")) { - DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); - DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); - docBuilder.parse(f); - } - } - } - - @Test - public void summary() throws Exception { - super.executeTarget("antxml-summary"); - - Persister p = new Persister(); - File parent = getProject().getBaseDir(); - - MavenFailsafeSummaryModel_Local m1 = p.read(MavenFailsafeSummaryModel_Local.class, new File(parent, "ant-xmls2/summary1.xml")); - assertEquals(255, (int) m1.result); - assertEquals(5, m1.completed); - assertEquals(2, m1.skipped); - assertEquals(1, m1.errors); - assertEquals(1, m1.failures); - - m1 = p.read(MavenFailsafeSummaryModel_Local.class, new File(parent, "ant-xmls2/summary2.xml")); - assertEquals(null, m1.result); - assertEquals(1, m1.completed); - assertEquals(0, m1.skipped); - assertEquals(0, m1.errors); - assertEquals(0, m1.failures); - - m1 = p.read(MavenFailsafeSummaryModel_Local.class, new File(parent, "ant-xmls2/summary3.xml")); - assertEquals(254, (int) m1.result); - assertEquals(0, m1.completed); - assertEquals(0, m1.skipped); - assertEquals(0, m1.errors); - assertEquals(0, m1.failures); - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestChildVmSysprops.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestChildVmSysprops.java deleted file mode 100644 index 5a8cc41d..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestChildVmSysprops.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.it; - - -import org.junit.Test; - - -public class TestChildVmSysprops extends JUnit4XmlTestBase { - @Test - public void sysprops() { - executeTarget("childvm_sysprops"); - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestCrashesAndExceptions.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestCrashesAndExceptions.java deleted file mode 100644 index 3fa34d43..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestCrashesAndExceptions.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.it; - - -import java.io.File; - -import org.junit.Test; - - -public class TestCrashesAndExceptions extends JUnit4XmlTestBase { - @Test - public void slavehanging() { - executeTarget("slavehanging"); - assertLogContains("Caused by: java.lang.ArithmeticException"); - } - - - @Test - public void jvmcrash() { - expectBuildExceptionContaining("jvmcrash", "was not empty, see:"); - File cwd = getProject().getBaseDir(); - for (File crashDump : cwd.listFiles()) { - if (crashDump.isFile() && - (crashDump.getName().matches("^hs_err_pid.+\\.log") || - crashDump.getName().endsWith(".mdmp") || - crashDump.getName().endsWith(".dmp") || - crashDump.getName().endsWith(".dump") || - crashDump.getName().endsWith(".trc"))) { - crashDump.delete(); - } - } - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestCwdConflict.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestCwdConflict.java deleted file mode 100644 index c4792d84..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestCwdConflict.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.it; - - -import org.junit.Test; - - -public class TestCwdConflict extends JUnit4XmlTestBase { - @Test - public void cwdconflict() { - super.executeTarget("cwdconflict"); - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestDuplicateResourceCollections.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestDuplicateResourceCollections.java deleted file mode 100644 index 2ff9b408..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestDuplicateResourceCollections.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.it; - - -import org.junit.Test; - - -public class TestDuplicateResourceCollections extends JUnit4XmlTestBase { - @Test - public void duplicateResourceCollectionEntries() { - super.executeTarget("duplicateresources"); - - assertLogContains("10 suites, 10 tests"); - assertLogContains("JVM J0"); - assertLogContains("JVM J1"); - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestFileEncodings.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestFileEncodings.java deleted file mode 100644 index f28ee35d..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestFileEncodings.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.it; - -import java.io.DataInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; - -import org.junit.Assert; -import org.junit.Test; - -public class TestFileEncodings extends JUnit4XmlTestBase { - @Test - public void checkTypicalEncodings() throws IOException { - super.executeTarget("fileencodings"); - - File logFile = new File(getProject().getProperty("log.file")); - - byte [] contents = new byte [(int) logFile.length()]; - DataInputStream dis = new DataInputStream(new FileInputStream(logFile)); - dis.readFully(contents); - dis.close(); - - String log = new String(contents, "UTF-8"); - Assert.assertEquals(1, countPattern(log, "US-ASCII=cze??, ??????, ???")); - Assert.assertEquals(1, countPattern(log, "iso8859-1=cze??, ??????, ???")); - Assert.assertEquals(1, countPattern(log, "UTF-8=cześć, Привет, 今日ã¯")); - Assert.assertEquals(1, countPattern(log, "UTF-16=cześć, Привет, 今日ã¯")); - Assert.assertEquals(1, countPattern(log, "UTF-16LE=cześć, Привет, 今日ã¯")); - Assert.assertEquals(1, countPattern(log, "UTF-32=cześć, Привет, 今日ã¯")); - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestFiltering.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestFiltering.java deleted file mode 100644 index 885569d7..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestFiltering.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.it; - - -import org.junit.Test; - - -public class TestFiltering extends JUnit4XmlTestBase { - @Test - public void classfilter() { - executeTarget("classfilter"); - assertLogContains("Tests summary: 1 suite"); - } - - @Test - public void methodfilter() { - executeTarget("methodfilter"); - assertLogContains("Tests summary: 1 suite, 2 tests"); - } - - @Test - public void filterexpression() { - executeTarget("filterexpression"); - - assertLogContains("Parsed test filtering expression: (@foo AND (NOT @bar))"); - assertLogContains(">foo<"); - assertLogDoesNotContain(">foobar<"); - assertLogDoesNotContain(">bar<"); - assertLogDoesNotContain(">foobar2<"); - assertLogDoesNotContain(">bar2<"); - assertLogContains("Tests summary: 2 suites (1 ignored), 1 test"); - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestHeartbeat.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestHeartbeat.java deleted file mode 100644 index 2624c1c7..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestHeartbeat.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.it; - - -import org.junit.Test; - -/** - * Test heartbeat on slow, non-updating tests. - */ -public class TestHeartbeat extends JUnit4XmlTestBase { - @Test - public void testHeartbeat() { - executeTarget("testHeartbeat"); - assertLogContains("HEARTBEAT J0"); - assertLogContains("at: HeartbeatSlow.method1"); - assertLogDoesNotContain("Exception thrown by subscriber method"); - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestIfNoTestsOption.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestIfNoTestsOption.java deleted file mode 100644 index 0a4379f4..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestIfNoTestsOption.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.it; - - -import org.junit.Test; - - -public class TestIfNoTestsOption extends JUnit4XmlTestBase { - @Test - public void allFilteredOut() { - expectBuildExceptionContaining("allFilteredOut", "There were no executed tests: 0 suites, 0 tests"); - } - - @Test - public void oneIgnored() { - expectBuildExceptionContaining("oneIgnored", "There were no executed tests: 1 suite, 1 test, 1 ignored"); - } - - @Test - public void oneAssumptionIgnored() { - expectBuildExceptionContaining("oneAssumptionIgnored", "There were no executed tests: 1 suite, 1 test, 1 ignored"); - } - - @Test - public void oneSuccessfull() { - executeTarget("oneSuccessful"); - } - - @Test - public void oneFailure() { - expectBuildExceptionContaining("oneFailure", "There were test failures: 1 suite, 1 test, 1 failure"); - } - - @Test - public void oneError() { - expectBuildExceptionContaining("oneError", "There were test failures: 1 suite, 1 test, 1 error"); - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestJUnitCompat.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestJUnitCompat.java deleted file mode 100644 index a5e76758..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestJUnitCompat.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.it; - - -import org.junit.Test; - - -public class TestJUnitCompat extends JUnit4XmlTestBase { - @Test - public void junitcompat1() { - super.expectBuildExceptionContaining( - "junitcompat1", " elements are not supported"); - } - - @Test - public void junitcompat2() { - super.expectBuildExceptionContaining( - "junitcompat2", " elements are not supported"); - } - - @Test - public void junitcompat3() { - super.expectBuildExceptionContaining( - "junitcompat3", " elements are not supported"); - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestJsonReport.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestJsonReport.java deleted file mode 100644 index 9361e3ee..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestJsonReport.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.it; - - -import java.io.File; - -import org.junit.Assert; -import org.junit.Test; - - -public class TestJsonReport extends JUnit4XmlTestBase { - @Test - public void antxml() { - super.executeTarget("json"); - - Assert.assertTrue( - new File(getProject().getBaseDir(), - "json/report.json").length() > 0); - Assert.assertTrue( - new File(getProject().getBaseDir(), - "json/report.jsonp").length() > 0); - Assert.assertTrue( - new File(getProject().getBaseDir(), - "json/output.html").length() > 0); - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestJvmLogging.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestJvmLogging.java deleted file mode 100644 index 22e0dbc4..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestJvmLogging.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.it; - -import org.junit.Test; - -/** - * Check JVM logging settings. Thet seem to use process descriptors not - * {@link System} streams. - */ -public class TestJvmLogging extends JUnit4XmlTestBase { - @Test - public void jvmverbose() { - executeTarget("jvmverbose"); - assertLogContains("was not empty, see"); - } - - @Test - public void sysouts() { - executeTarget("sysouts"); - assertLogContains("syserr-syserr-contd."); - assertLogContains("sysout-sysout-contd."); - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestMiscJUnit4Attributes.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestMiscJUnit4Attributes.java deleted file mode 100644 index bffa780f..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestMiscJUnit4Attributes.java +++ /dev/null @@ -1,103 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.it; - - -import org.junit.Test; - -import com.carrotsearch.ant.tasks.junit4.tests.TestAfterClassError; -import com.carrotsearch.ant.tasks.junit4.tests.TestBeforeClassError; - - -public class TestMiscJUnit4Attributes extends JUnit4XmlTestBase { - @Test - public void customprefix() { - executeForkedTarget("customprefix"); - } - - @Test - public void statuses() throws Throwable { - expectBuildExceptionContaining("statuses", - "1 suite, 5 tests, 1 error, 1 failure, 2 ignored (1 assumption)"); - } - - @Test - public void ignoredSuite() throws Throwable { - executeTarget("ignoredSuite"); - assertLogContains("Tests summary: 1 suite (1 ignored), 0 tests"); - } - - @Test - public void beforeClassError() throws Throwable { - expectBuildExceptionContaining("beforeClassError", - "1 suite, 0 tests, 1 suite-level error"); - assertLogContains("| " + TestBeforeClassError.class.getSimpleName() + " (suite)"); - } - - @Test - public void afterClassError() throws Throwable { - expectBuildExceptionContaining("afterClassError", - "1 suite, 1 test, 1 suite-level error"); - assertLogContains("| " + TestAfterClassError.class.getSimpleName() + " (suite)"); - } - - @Test - public void hierarchicalSuiteDescription() throws Throwable { - expectBuildExceptionContaining("hierarchicalSuiteDescription", - "1 suite, 2 tests, 3 suite-level errors, 1 error"); - } - - @Test - public void dir() { - executeTarget("dir"); - } - - @Test - public void maxmem() { - executeTarget("maxmem"); - } - - @Test - public void jvmarg() { - executeTarget("jvmarg"); - } - - @Test - public void seedpassing() { - executeTarget("seedpassing"); - } - - @Test - public void seedpassingInvalid() { - expectBuildExceptionContaining("seedpassing.invalid", "Not a valid seed chain"); - } - - @Test - public void reproducestring() { - executeTarget("reproducestring"); - assertLogContains("2> Reproduce: "); - } - - @Test - public void assertions() { - expectBuildExceptionContaining("assertions", "There were test failures"); - assertLogContains("> Throwable #1: java.lang.AssertionError: foobar"); - } - - @Test - public void balancing() { - executeTarget("balancing"); - assertLogContains("Assignment hint: J0 (cost 2019) com.carrotsearch.ant.tasks.junit4.tests.sub2.TestTwoSeconds (by ExecutionTimeBalancer)"); - assertLogContains("Assignment hint: J1 (cost 1002) com.carrotsearch.ant.tasks.junit4.tests.sub2.TestOneSecond (by ExecutionTimeBalancer)"); - assertLogContains("Assignment hint: J1 (cost 501) com.carrotsearch.ant.tasks.junit4.tests.sub2.TestHalfSecond (by ExecutionTimeBalancer)"); - assertLogContains("Assignment hint: J1 (cost 2) com.carrotsearch.ant.tasks.junit4.tests.sub2.TestZeroSeconds (by ExecutionTimeBalancer)"); - } - - @Test - public void balancing_nohints() { - executeTarget("balancing_nohints"); - } - - @Test - public void mergehints() { - executeTarget("mergehints"); - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestOnNonEmptyWorkDirectory.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestOnNonEmptyWorkDirectory.java deleted file mode 100644 index d48ec335..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestOnNonEmptyWorkDirectory.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.it; - - -import org.junit.Ignore; -import org.junit.Test; - - -public class TestOnNonEmptyWorkDirectory extends JUnit4XmlTestBase { - @Test - public void actionFail() { - expectBuildExceptionContaining("onNonEmptyWorkDirectory-fail", - "existing-dir", - "Cwd of a forked JVM already exists and is not empty"); - } - - @Test - public void actionWipe() { - executeTarget("onNonEmptyWorkDirectory-wipe"); - assertLogContains("Cwd of a forked JVM already exists and is not empty, trying to wipe"); - } - - @Test - public void actionIgnore() { - executeTarget("onNonEmptyWorkDirectory-ignore"); - assertLogContains("Cwd of a forked JVM already exists and is not empty"); - } - - // https://github.com/randomizedtesting/randomizedtesting/issues/247 - @Test - public void tmpDirUnderCwd() { - executeTarget("onNonEmptyWorkDirectory-tmpDirUnderCwd"); - assertLogContains("Created tmpfile"); - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestOomCode.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestOomCode.java deleted file mode 100644 index 10601dc9..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestOomCode.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.it; - -import org.junit.Ignore; -import org.junit.Test; - -public class TestOomCode extends JUnit4XmlTestBase { - @Test - @Ignore("Not portable across JVMs") - public void oom() { - super.executeForkedTarget("oomcode", 5 * 60 * 1000L); - assertLogContains("Forked JVM ran out of memory"); - assertLogContains("WARN: JVM out of memory"); - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestOomPermGen.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestOomPermGen.java deleted file mode 100644 index 009cbcea..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestOomPermGen.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.it; - -import org.junit.Ignore; -import org.junit.Test; - -public class TestOomPermGen extends JUnit4XmlTestBase { - @Test - @Ignore("Not portable across JVMs") - public void oom() { - super.executeForkedTarget("oompermgen", 5 * 60 * 1000L); - if (!getLog().contains("1 ignored (1 assumption)")) { - assertLogContains("java.lang.OutOfMemoryError"); - } - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestOutputCapture.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestOutputCapture.java deleted file mode 100644 index 4ed32e7a..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestOutputCapture.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.it; - - -import org.junit.Test; - -/** - * Test things related to output capturing. - */ -public class TestOutputCapture extends JUnit4XmlTestBase { - @Test - public void sysstreams() { - executeTarget("sysstreams"); - assertLogContains("Tests summary: 1 suite, 2 tests"); - assertLogContains("1> sysout-sysout-contd."); - assertLogContains("2> syserr-syserr-contd."); - } - - @Test - public void outofordersysouts() { - executeTarget("outofordersysouts"); - } - - @Test - public void staticScopeOutput() { - executeTarget("staticScopeOutput"); - assertLogContains("1> static-scope"); - assertLogContains("1> before-class"); - assertLogContains("1> after-class"); - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestPickSeed.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestPickSeed.java deleted file mode 100644 index ba64deb9..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestPickSeed.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.it; - - -import java.util.HashMap; -import java.util.TreeSet; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.junit.Assert; -import org.junit.Test; - - -public class TestPickSeed extends JUnit4XmlTestBase { - - @Test - public void pickSeed() { - for (int i = 0; i < 7; i++) { - super.executeTarget("randomsysproperty"); - } - - HashMap> props = new HashMap>(); - - for (String key : new String [] { - "prefix.dummy1", - "prefix.dummy2", - "replaced.dummy1", - "replaced.dummy2", - }) { - TreeSet values = new TreeSet(); - Pattern p = Pattern.compile("(?:> )(" + key + ")(?:=)([^\\s]+)"); - Matcher m = p.matcher(getLog()); - while (m.find()) { - values.add(m.group(2)); - } - - props.put(key, values); - } - - Assert.assertEquals(props.get("prefix.dummy1"), props.get("replaced.dummy1")); - Assert.assertEquals(props.get("prefix.dummy2"), props.get("replaced.dummy2")); - - // At least two unique values. - Assert.assertTrue(props.get("prefix.dummy1").size() >= 2); - // null (missing value) should be there. - Assert.assertTrue(props.get("prefix.dummy2").contains("null")); - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestPreconditions.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestPreconditions.java deleted file mode 100644 index ae37b588..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestPreconditions.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.it; - - -import org.junit.Test; - - -public class TestPreconditions extends JUnit4XmlTestBase { - @Test - public void nojunit() { - expectBuildExceptionContaining("nojunit", "Forked JVM's classpath must include a junit4 JAR"); - } - - @Test - public void oldjunit() { - executeForkedTarget("oldjunit"); - assertLogContains("Forked JVM's classpath must use JUnit 4.10 or newer"); - } - - @Test - public void nojunit_task() { - executeForkedTarget("nojunit-task"); - assertLogContains("JUnit JAR must be added to junit4 taskdef's classpath"); - } - - @Test - public void oldjunit_task() { - executeForkedTarget("oldjunit-task"); - assertLogContains("At least JUnit version 4.10 is required on junit4's taskdef classpath"); - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestReplication.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestReplication.java deleted file mode 100644 index a70fcda6..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestReplication.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.it; - - -import java.util.Arrays; -import java.util.HashSet; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.junit.Assert; -import org.junit.Test; - -public class TestReplication extends JUnit4XmlTestBase { - @Test - public void singleSuiteReplication() { - super.executeTarget("replicateSingleTest"); - - assertLogContains("Replicated test, VM: 0"); - assertLogContains("Replicated test, VM: 1"); - assertLogContains("Replicated test, VM: 2"); - } - - @Test - public void replicationAndBalancing() { - super.executeTarget("replicationAndBalancing"); - - assertLogContains("Non-replicated test, VM: 0"); - assertLogContains("Non-replicated test, VM: 1"); - assertLogContains("Replicated test, VM: 0"); - assertLogContains("Replicated test, VM: 1"); - assertLogContains("Replicated test, VM: 2"); - } - - @Test - public void pseudoBalancing() { - super.executeTarget("pseudoBalancing"); - - assertLogContains("3 suites, 300 tests, 200 ignored (200 assumptions)"); - - String log = getLog(); - for (int i = 0; i < 100; i++) { - Pattern p = Pattern.compile("(Test " + i + " executed on VM )([0-9]+)"); - Matcher m = p.matcher(log); - Assert.assertTrue(m.find()); - int jvm = Integer.parseInt(m.group(2)); - - HashSet s = new HashSet(Arrays.asList(0, 1, 2)); - s.remove(jvm); - for (int ignoredOnJvm : s) { - assertLogContains("Test " + i + " ignored on VM " + ignoredOnJvm); - } - } - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestRunListeners.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestRunListeners.java deleted file mode 100644 index e9c65403..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestRunListeners.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.it; - -import org.junit.Test; - -public class TestRunListeners extends JUnit4XmlTestBase { - - @Test - public void singleUserDefinedRunListener() { - super.executeTarget("singleUserDefinedRunListener"); - - assertLogContains("UserDefinedRunListener1.testStarted()"); - assertLogContains("UserDefinedRunListener1.testFinished()"); - } - - @Test - public void multipleUserDefinedRunListeners() { - super.executeTarget("multipleUserDefinedRunListeners"); - - assertLogContains("UserDefinedRunListener2.testStarted()"); - assertLogContains("UserDefinedRunListener2.testFinished()"); - - assertLogContains("UserDefinedRunListener3.testStarted()"); - assertLogContains("UserDefinedRunListener3.testFinished()"); - } - -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestSecuritySandbox.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestSecuritySandbox.java deleted file mode 100644 index d660a5e9..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestSecuritySandbox.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.it; - - -import com.carrotsearch.ant.tasks.junit4.tests.FailInAfterClass; -import com.carrotsearch.ant.tasks.junit4.tests.ReasonForAssumptionIgnored; -import org.junit.Assert; -import org.junit.Test; - -import java.util.regex.Pattern; - -/** - * Test report-text listener. - */ -public class TestSecuritySandbox extends JUnit4XmlTestBase { - @Test - public void gh255() { - super.executeTarget("gh255"); - assertLogContains("access denied (\"java.util.PropertyPermission\" \"foo\" \"write\")"); - assertLogContains("Tests summary: 1 suite, 1 test, 1 error"); - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestShutdownHookDeadlock.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestShutdownHookDeadlock.java deleted file mode 100644 index d1cecd1e..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestShutdownHookDeadlock.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.it; - -import org.junit.Assert; -import org.junit.Test; - - -public class TestShutdownHookDeadlock extends JUnit4XmlTestBase { - @Test - public void slavehanging() { - long start = System.currentTimeMillis(); - executeForkedTarget("shutdownhook", 120 * 1000L); - long end = System.currentTimeMillis(); - - // This isn't a strong assertion but it'll do here. If the execution time > 60 seconds - // something is stinky. - Assert.assertTrue(end - start < 60 * 1000); - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestSourceSuitesAsInput.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestSourceSuitesAsInput.java deleted file mode 100644 index c252473f..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestSourceSuitesAsInput.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.it; - - -import org.junit.Test; - -public class TestSourceSuitesAsInput extends JUnit4XmlTestBase { - @Test - public void sourcesuites() { - super.executeTarget("sourcesuites"); - assertLogContains("Tests summary: 1 suite, 1 test"); - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestStackOverflowInEventEmitter.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestStackOverflowInEventEmitter.java deleted file mode 100644 index e2781350..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestStackOverflowInEventEmitter.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.it; - - -import org.junit.Test; - - -public class TestStackOverflowInEventEmitter extends JUnit4XmlTestBase { - @Test - public void stackoverflow() { - super.expectBuildExceptionContaining("stackoverflow", "Quit event not received from the forked process?"); - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestStatsProperties.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestStatsProperties.java deleted file mode 100644 index 90ad9c50..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestStatsProperties.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.it; - - -import org.junit.Test; - - -public class TestStatsProperties extends JUnit4XmlTestBase { - @Test - public void allFilteredOut() { - super.executeTarget("statsProperties"); - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestSuiteClassesBad.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestSuiteClassesBad.java deleted file mode 100644 index 73a550be..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestSuiteClassesBad.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.it; - - -import org.junit.Test; - - -public class TestSuiteClassesBad extends JUnit4XmlTestBase { - @Test - public void notaclass() { - expectBuildExceptionContaining("notaclass", - "File does not start with a class magic"); - } - - @Test - public void notinstantiable() { - expectBuildExceptionContaining("notinstantiable", - "There were test failures: 1 suite, 1 test, 1 error"); - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestSuiteDuplicates.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestSuiteDuplicates.java deleted file mode 100644 index 292ec60a..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestSuiteDuplicates.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.it; - - -import org.junit.Test; - - -public class TestSuiteDuplicates extends JUnit4XmlTestBase { - @Test - public void suiteduplicate() { - super.executeTarget("suiteduplicate"); - - assertLogContains("2 suites, 2 tests"); - assertLogContains("JVM J0"); - assertLogContains("JVM J1"); - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestSysProperties.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestSysProperties.java deleted file mode 100644 index 779d653a..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestSysProperties.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.it; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.junit.Assert; -import org.junit.Test; - -public class TestSysProperties extends JUnit4XmlTestBase { - @Test - public void failureProperty() { - executeTarget("failureProperty"); - } - - @Test - public void failureTypePassing() { - executeTarget("failureTypePassing"); - assertLogContains("Throwable #1: com.carrotsearch.ant.tasks.junit4.tests.SyntheticException"); - assertLogContains("Tests summary: 1 suite, 1 test, 1 error"); - - super.restoreSyserr.println(getLog()); - } - - @Test - public void escaping() { - executeTarget("escaping"); - assertLogContains("\"-Dsysprop.key2=abc def\""); - } - - @Test - public void sysproperty() { - executeTarget("sysproperty"); - } - - @Test - public void env() { - executeTarget("env"); - } - - @Test - public void iters() { - executeTarget("iters"); - Pattern p = Pattern.compile("TestSuccess\\.alwaysPasses"); - Matcher matcher = p.matcher(getLog()); - int count = 0; - while (matcher.find()) { - count++; - } - Assert.assertEquals(5, count); - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestSysPropertySet.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestSysPropertySet.java deleted file mode 100644 index 1eb2050b..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestSysPropertySet.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.it; - -import org.junit.Test; - -public class TestSysPropertySet extends JUnit4XmlTestBase { - @Test - public void altVendors() { - getProject().setProperty("prefix.dummy1", "value1"); - getProject().setProperty("prefix.dummy2", "value2"); - - executeTarget("syspropertyset"); - - assertLogContains("value1"); - assertLogContains("value2"); - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestSysoutOOM.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestSysoutOOM.java deleted file mode 100644 index 07a6bb84..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestSysoutOOM.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.it; - - -import org.junit.Test; - - -public class TestSysoutOOM extends JUnit4XmlTestBase { - @Test - public void sysoutoom() { - super.executeTarget("sysoutoom"); - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestTextReport.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestTextReport.java deleted file mode 100644 index 435c5ff4..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestTextReport.java +++ /dev/null @@ -1,118 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.it; - - -import java.util.regex.Pattern; - -import org.junit.Assert; -import org.junit.Test; - -import com.carrotsearch.ant.tasks.junit4.tests.FailInAfterClass; -import com.carrotsearch.ant.tasks.junit4.tests.ReasonForAssumptionIgnored; - -/** - * Test report-text listener. - */ -public class TestTextReport extends JUnit4XmlTestBase { - @Test - public void suiteerror() { - super.executeTarget("suiteerror"); - - int count = countPattern(getLog(), FailInAfterClass.MESSAGE); - Assert.assertEquals(1, count); - } - - @Test - public void reasonForIgnored() { - super.executeTarget("reasonForIgnored"); - assertLogContains("@DisabledGroup"); - assertLogContains("> Cause: Annotated @Ignore"); - assertLogContains("(Ignored method.)"); - } - - @Test - public void reasonForIgnoredByDisabledGroup() { - super.executeTarget("reasonForIgnoredByDisabledGroup"); - String log = getLog(); - Assert.assertTrue(log.contains("(@DisabledGroup(value=foo bar))") || - log.contains("(@DisabledGroup(value=\"foo bar\"))")); - } - - @Test - public void reasonForSuiteAssumptionIgnored() { - super.executeTarget("reasonForSuiteAssumptionIgnored"); - - int count = countPattern(getLog(), ReasonForAssumptionIgnored.MESSAGE); - Assert.assertEquals(2, count); - } - - @Test - public void listeners() { - super.executeTarget("listeners"); - assertLogContains("testStarted: passing(com.carrotsearch.ant.tasks.junit4.tests.SuiteListeners)"); - assertLogContains("testFinished: passing(com.carrotsearch.ant.tasks.junit4.tests.SuiteListeners)"); - } - - @Test - public void timestamps() { - super.executeTarget("timestamps"); - Assert.assertTrue(getLog(), - Pattern.compile("\\[([0-9]{2}):([0-9]{2}):([0-9]{2})\\.([0-9]{3})\\]").matcher(getLog()).find()); - } - - @Test - public void sysoutsOnSuiteFailure() { - super.executeTarget("sysoutsOnSuiteFailure"); - assertLogContains("ignored-sysout"); - assertLogContains("success-sysout"); - assertLogContains("afterclass-sysout"); - assertLogContains("beforeclass-sysout"); - super.restoreSyserr.println(getLog()); - } - - @Test - public void sysoutsOnSuiteTimeout() { - super.executeTarget("sysoutsOnSuiteTimeout"); - assertLogContains("beforeclass-sysout"); - assertLogContains("test-sysout"); - String log = getLog(); - Assert.assertTrue( - log.indexOf("1> test-sysout") < - log.indexOf("Suite execution timed out:")); - } - - @Test - public void sysoutsPassthrough() { - super.executeTarget("sysouts_passthrough"); - } - - @Test - public void failureslist() { - super.executeTarget("failureslist"); - assertLogContains("Tests with failures"); - } - - @Test - public void filtertrace_default() { - super.executeTarget("filtertrace_default"); - - assertLogDoesNotContain("at sun.reflect."); - assertLogDoesNotContain("at java.lang.reflect.Method"); - assertLogDoesNotContain("at org.junit.runners."); - assertLogDoesNotContain("at com.carrotsearch.ant.tasks.junit4.slave.SlaveMain"); - } - - @Test - public void filtertrace_custom() { - super.executeTarget("filtertrace_custom"); - - assertLogContains("java.lang.reflect.Method"); - assertLogDoesNotContain("at org.junit."); - assertLogDoesNotContain(".SlaveMain."); - } - - @Test - public void errorsSoFarIndicator() { - super.executeTarget("errorsSoFar"); - assertLogContains("Completed [1/1 (1!)]"); - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestUnhandledSlaveFailure.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestUnhandledSlaveFailure.java deleted file mode 100644 index 5f73cac8..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestUnhandledSlaveFailure.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.it; - -import java.io.IOException; - -import org.junit.Test; - -import com.carrotsearch.ant.tasks.junit4.tests.FireUnhandledRunnerException; - -public class TestUnhandledSlaveFailure extends JUnit4XmlTestBase { - @Test - public void checkSlaveMainFailure() throws IOException { - super.expectBuildExceptionContaining("slavemainfailure", "process threw an exception"); - assertLogContains(FireUnhandledRunnerException.EXCEPTION_MESSAGE); - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestWeirdClasses.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestWeirdClasses.java deleted file mode 100644 index 7f013118..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/it/TestWeirdClasses.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.it; - - -import org.junit.Test; - -public class TestWeirdClasses extends JUnit4XmlTestBase { - /* - * Just run an example that shows JUnit's behavior on package-private/ abstract classes. - * https://github.com/carrotsearch/randomizedtesting/issues/91 - */ - @Test - public void antxml() { - super.executeTarget("weirdclasses"); - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/listeners/antxml/XmlStringTransformerAccess.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/listeners/antxml/XmlStringTransformerAccess.java deleted file mode 100644 index 84d16d66..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/listeners/antxml/XmlStringTransformerAccess.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.listeners.antxml; - -public class XmlStringTransformerAccess { - public static XmlStringTransformer getInstance() { - return new XmlStringTransformer(); - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/runlisteners/UserDefinedRunListener1.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/runlisteners/UserDefinedRunListener1.java deleted file mode 100644 index 4a942504..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/runlisteners/UserDefinedRunListener1.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.runlisteners; - -import org.junit.runner.Description; -import org.junit.runner.Result; -import org.junit.runner.notification.Failure; -import org.junit.runner.notification.RunListener; - -public class UserDefinedRunListener1 extends RunListener { - - @Override - public void testRunStarted(Description description) throws Exception { - System.out.print("UserDefinedRunListener1.testRunStarted()"); - } - - @Override - public void testRunFinished(Result result) throws Exception { - System.out.print("UserDefinedRunListener1.testRunFinished()"); - } - - @Override - public void testStarted(Description description) throws Exception { - System.out.print("UserDefinedRunListener1.testStarted()"); - } - - @Override - public void testFinished(Description description) throws Exception { - System.out.print("UserDefinedRunListener1.testFinished()"); - } - - @Override - public void testFailure(Failure failure) throws Exception { - System.out.print("UserDefinedRunListener1.testFailure()"); - } - - @Override - public void testAssumptionFailure(Failure failure) { - System.out.print("UserDefinedRunListener1.testAssumptionFailure()"); - } - - @Override - public void testIgnored(Description description) throws Exception { - System.out.print("UserDefinedRunListener1.testIgnored()"); - } - -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/runlisteners/UserDefinedRunListener2.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/runlisteners/UserDefinedRunListener2.java deleted file mode 100644 index a0b585bc..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/runlisteners/UserDefinedRunListener2.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.runlisteners; - -import org.junit.runner.Description; -import org.junit.runner.Result; -import org.junit.runner.notification.Failure; -import org.junit.runner.notification.RunListener; - -public class UserDefinedRunListener2 extends RunListener { - - @Override - public void testRunStarted(Description description) throws Exception { - System.out.print("UserDefinedRunListener2.testRunStarted()"); - } - - @Override - public void testRunFinished(Result result) throws Exception { - System.out.print("UserDefinedRunListener2.testRunFinished()"); - } - - @Override - public void testStarted(Description description) throws Exception { - System.out.print("UserDefinedRunListener2.testStarted()"); - } - - @Override - public void testFinished(Description description) throws Exception { - System.out.print("UserDefinedRunListener2.testFinished()"); - } - - @Override - public void testFailure(Failure failure) throws Exception { - System.out.print("UserDefinedRunListener2.testFailure()"); - } - - @Override - public void testAssumptionFailure(Failure failure) { - System.out.print("UserDefinedRunListener2.testAssumptionFailure()"); - } - - @Override - public void testIgnored(Description description) throws Exception { - System.out.print("UserDefinedRunListener2.testIgnored()"); - } - -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/runlisteners/UserDefinedRunListener3.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/runlisteners/UserDefinedRunListener3.java deleted file mode 100644 index 1e22056b..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/runlisteners/UserDefinedRunListener3.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.runlisteners; - -import org.junit.runner.Description; -import org.junit.runner.Result; -import org.junit.runner.notification.Failure; -import org.junit.runner.notification.RunListener; - -public class UserDefinedRunListener3 extends RunListener { - - @Override - public void testRunStarted(Description description) throws Exception { - System.out.print("UserDefinedRunListener3.testRunStarted()"); - } - - @Override - public void testRunFinished(Result result) throws Exception { - System.out.print("UserDefinedRunListener3.testRunFinished()"); - } - - @Override - public void testStarted(Description description) throws Exception { - System.out.print("UserDefinedRunListener3.testStarted()"); - } - - @Override - public void testFinished(Description description) throws Exception { - System.out.print("UserDefinedRunListener3.testFinished()"); - } - - @Override - public void testFailure(Failure failure) throws Exception { - System.out.print("UserDefinedRunListener3.testFailure()"); - } - - @Override - public void testAssumptionFailure(Failure failure) { - System.out.print("UserDefinedRunListener3.testAssumptionFailure()"); - } - - @Override - public void testIgnored(Description description) throws Exception { - System.out.print("UserDefinedRunListener3.testIgnored()"); - } - -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/spikes/FloatSampling.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/spikes/FloatSampling.java deleted file mode 100644 index def46432..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/spikes/FloatSampling.java +++ /dev/null @@ -1,119 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.spikes; - -import java.util.ArrayDeque; -import java.util.Arrays; -import java.util.Locale; -import java.util.Random; - -import org.junit.Test; - -import com.carrotsearch.randomizedtesting.RandomizedTest; -import com.carrotsearch.randomizedtesting.annotations.Seed; - -public class FloatSampling extends RandomizedTest { - @SuppressWarnings("serial") - @Test - @Seed("deadbeef") - public void recurse() { - Random rnd = new Random(1) { - ArrayDeque r = new ArrayDeque<>(Arrays.asList( - Math.nextAfter(1f, Double.NEGATIVE_INFINITY), - Math.nextAfter(1f, Double.NEGATIVE_INFINITY), - Math.nextAfter(1f, Double.NEGATIVE_INFINITY), - Math.nextAfter(1f, Double.NEGATIVE_INFINITY) - )); - - @Override - public float nextFloat() { - if (r.isEmpty()) { - return super.nextFloat(); - } else { - return r.removeFirst(); - } - }; - }; - - float from = -Float.MAX_VALUE, - to = Float.MAX_VALUE; - System.out.println("R=" + info(randomBetween(rnd, from, to))); - - System.out.println(info(-0.0f)); - System.out.println(info(Math.nextAfter(0f, Double.NEGATIVE_INFINITY))); - System.out.println(info(Math.nextAfter(-0.0f, Double.NEGATIVE_INFINITY))); - } - - public static float randomBetween(Random rnd, float from, float to) { - assert !Float.isNaN(from) && - !Float.isNaN(to) && - !Float.isInfinite(from) && - !Float.isInfinite(to); - - float span = Float.MAX_VALUE; - // TODO: when there's a difference of 4 ulps low and high may never converge, we should - // select manually then. - while (from != to) { - // proportional selection factor between from and to. - float s = rnd.nextFloat(); - - // Determine lower ends of an interval where s and nextUp(s) would divide - // the representation space between from and to. Then proceed recursively - // until there's a single element left. - float low = low(s, from, to); - float high = low(Math.nextUp(s), from, to); - - // Sanity check. - assert (span = alwaysDecreases(span, high - low)) >= 0; - System.out.println(info(low)); - System.out.println(info(high)); - System.out.println("(" + from + ", " + to + ") -> s=" + s + " => (" + low + "," + high + "), range=" + (high - low)); - - from = low; to = high; - } - - return from; - } - - private static float alwaysDecreases(float prevSpan, float newSpan) { - if (prevSpan <= newSpan) { - throw new AssertionError("Interval should always decrease: " + prevSpan + " " + newSpan); - } - return newSpan; - } - - private static float low(float s, float min, float max) { - // Avoid range overflow by calculating proportion differently: - // s * (max - min) + min = - // s * max + (1 - s) * min - - if (s == 0f) return min; - if (s == 1f) return max; - - // All intermediate results are always pessimistically rounded down. - - float c1 = s * max; - if (c1 > 0) { - c1 = Math.nextAfter(c1, Double.NEGATIVE_INFINITY); - } - - float c4 = 1f - s; - if (c4 > 0) { - c4 = Math.nextAfter(c4, Double.NEGATIVE_INFINITY); - } - - float c2 = c4 * min; - if (c2 > 0) { - c2 = Math.nextAfter(c2, Double.NEGATIVE_INFINITY); - } - - float c3 = c1 + c2; - if (c3 > 0) { - c3 = Math.nextAfter(c3, Double.NEGATIVE_INFINITY); - } - - return c3; - } - - private static String info(float f) { - return String.format(Locale.ROOT, "<%.50f, 0x%08x>", f, Float.floatToIntBits(f)); - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/spikes/LocalRun.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/spikes/LocalRun.java deleted file mode 100644 index 3034308e..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/spikes/LocalRun.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.spikes; - -import java.io.RandomAccessFile; -import java.util.Date; - - -@SuppressWarnings("resource") -public class LocalRun { - public static void main(String[] args) throws Exception { - System.out.println("Live and prosper."); - - // make sure to delete raf first. - final RandomAccessFile raf = new RandomAccessFile("shared.log", "rw"); - final RandomAccessFile raf2 = new RandomAccessFile("shared.log", "r"); - - Thread t1 = new Thread() { - @Override - public void run() { - while (true) { - try { - int c = raf2.read(); - if (c == -1) { - Thread.sleep(500); - continue; - } - - System.out.write(c); - System.out.flush(); - } catch (Exception e) { - e.printStackTrace(); - } - } - } - }; - - Thread t2 = new Thread() { - @Override - public void run() { - try { - while (true) { - raf.write((new Date().toString() + "\n").getBytes("UTF-8")); - Thread.sleep(2000); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - }; - - t1.start(); - t2.start(); - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/spikes/TestStatusesIDE.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/spikes/TestStatusesIDE.java deleted file mode 100644 index b51ebe86..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/spikes/TestStatusesIDE.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.spikes; - -import org.junit.Assert; -import org.junit.Assume; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; - -import com.carrotsearch.randomizedtesting.RandomizedRunner; -import com.carrotsearch.randomizedtesting.annotations.Nightly; -import com.carrotsearch.randomizedtesting.annotations.TestCaseOrdering; - -@Ignore -@RunWith(RandomizedRunner.class) -@TestCaseOrdering(TestCaseOrdering.AlphabeticOrder.class) -public class TestStatusesIDE { - @Test - public void _001_ok() { - } - - @Test @Ignore - public void _002_ignored() { - } - - @Test - public void _003_ignoredByExplicitAssumption() { - Assume.assumeTrue(false); - } - - @Test @Nightly - public void _004_ignoredByNightlyGroup() { - } - - @Test - public void _005_failedWithAssertion() { - Assert.assertTrue(false); - } - - @Test - public void _006_failedWithException() { - throw new RuntimeException(); - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/ChildVmSysprops.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/ChildVmSysprops.java deleted file mode 100644 index 88d40314..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/ChildVmSysprops.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.tests; - -import java.io.File; - -import org.junit.Assert; -import org.junit.Test; - -public class ChildVmSysprops { - @Test - public void cwd() { - Assert.assertNotNull(System.getProperty("junit4.childvm.cwd")); - Assert.assertTrue(new File(System.getProperty("junit4.childvm.cwd")).isDirectory()); - } - - @Test - public void id() { - Assert.assertNotNull(Integer.parseInt(System.getProperty("junit4.childvm.id"))); - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/Crash.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/Crash.java deleted file mode 100644 index 9d00ac89..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/Crash.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.tests; - -public class Crash { - public static native void crashMe(); - - public static void loadLibrary() { - StringBuilder b = new StringBuilder("Could not link with crashlib."); - try { - System.loadLibrary("crash"); - return; - } catch (UnsatisfiedLinkError e) { - b.append("\n").append(e.toString()); - } - - try { - System.loadLibrary("crash64"); - return; - } catch (UnsatisfiedLinkError e) { - b.append("\n").append(e.toString()); - } - - throw new UnsatisfiedLinkError(b.toString()); - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/CwdConflict1.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/CwdConflict1.java deleted file mode 100644 index 3382577e..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/CwdConflict1.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.tests; - -import java.io.File; - -import org.junit.Test; - -public class CwdConflict1 { - @Test - public void testCreateConflictingFile() throws Exception { - File file = new File("cwdconflict.tmp"); - if (!file.createNewFile()) { - throw new RuntimeException("File already exists."); - } - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/CwdConflict2.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/CwdConflict2.java deleted file mode 100644 index f33de691..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/CwdConflict2.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.tests; - - -public class CwdConflict2 extends CwdConflict1 { -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/DisabledGroup.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/DisabledGroup.java deleted file mode 100644 index 95dc8fa8..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/DisabledGroup.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.tests; - -import java.lang.annotation.*; - -import com.carrotsearch.randomizedtesting.annotations.TestGroup; - -@Documented -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.METHOD, ElementType.TYPE}) -@Inherited -@TestGroup(enabled = false) -public @interface DisabledGroup { - /** Additional description, if needed. */ - String value() default ""; -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/EscapeSequences.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/EscapeSequences.java deleted file mode 100644 index aa5124bd..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/EscapeSequences.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.tests; - -import org.junit.Test; - -public class EscapeSequences { - @Test - public void emitEscape() { - System.out.print("stdout: foo & bar"); - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/FailInAfterClass.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/FailInAfterClass.java deleted file mode 100644 index 3df9f1b0..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/FailInAfterClass.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.tests; - -import org.junit.AfterClass; -import org.junit.Test; - -public class FailInAfterClass { - public final static String MESSAGE = "This is @AfterClass output."; - - @Test - public void dummy() {} - - @AfterClass - public static void afterClass() { - System.out.println(MESSAGE); - throw new RuntimeException(); - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/FileEncoding.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/FileEncoding.java deleted file mode 100644 index 580969cb..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/FileEncoding.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.tests; - -import java.io.*; -import java.nio.charset.Charset; -import org.junit.Test; - -public class FileEncoding { - @Test - public void checkFileEncoding() throws IOException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - PrintStream ps = new PrintStream(baos); - ps.println("unicode string=cześć, Привет, 今日ã¯"); - ps.close(); - - String encoding = System.getProperty("file.encoding"); - System.out.println("file.encoding=" + encoding); - System.out.println("charset=" + Charset.defaultCharset()); - System.out.println("unicode string in " + encoding + "=cześć, Привет, 今日ã¯"); - System.out.println("unicode string PrintStream'ed: " + baos.size() + " bytes, hex dump:"); - - HexDump.dump(baos.toByteArray(), 0, System.out, 0); - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/FireUnhandledRunnerException.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/FireUnhandledRunnerException.java deleted file mode 100644 index 11856df3..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/FireUnhandledRunnerException.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.tests; - -import org.junit.Test; - -import com.carrotsearch.ant.tasks.junit4.slave.SlaveMain; - -public class FireUnhandledRunnerException { - public static final String EXCEPTION_MESSAGE = "BAMBOOOOOCHA!"; - - @Test - public void polluteRunner() { - System.setProperty(SlaveMain.SYSPROP_FIRERUNNERFAILURE, EXCEPTION_MESSAGE); - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/HeartbeatSlow.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/HeartbeatSlow.java deleted file mode 100644 index f944002c..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/HeartbeatSlow.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.tests; - -import java.util.concurrent.TimeUnit; - -import org.junit.Test; - -public class HeartbeatSlow { - @Test - public void method1() throws Exception { - Thread.sleep(TimeUnit.SECONDS.toMillis(3)); - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/HexDump.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/HexDump.java deleted file mode 100644 index 3231fd75..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/HexDump.java +++ /dev/null @@ -1,147 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.tests; - -import java.io.IOException; -import java.io.OutputStream; - -/** - * Dumps data in hexadecimal format. - *

- * Provides a single function to take an array of bytes and display it - * in hexadecimal form. - *

- * Origin of code: POI. - * - * @author Scott Sanders - * @author Marc Johnson - * @version $Id: HexDump.java 736507 2009-01-22 00:52:15Z jukka $ - */ -public class HexDump { - - /** - * Instances should NOT be constructed in standard programming. - */ - public HexDump() { - super(); - } - - /** - * Dump an array of bytes to an OutputStream. The output is formatted - * for human inspection, with a hexadecimal offset followed by the - * hexadecimal values of the next 16 bytes of data and the printable ASCII - * characters (if any) that those bytes represent printed per each line - * of output. - *

- * The offset argument specifies the start offset of the data array - * within a larger entity like a file or an incoming stream. For example, - * if the data array contains the third kibibyte of a file, then the - * offset argument should be set to 2048. The offset value printed - * at the beginning of each line indicates where in that larger entity - * the first byte on that line is located. - *

- * All bytes between the given index (inclusive) and the end of the - * data array are dumped. - * - * @param data the byte array to be dumped - * @param offset offset of the byte array within a larger entity - * @param stream the OutputStream to which the data is to be - * written - * @param index initial index into the byte array - * - * @throws IOException is thrown if anything goes wrong writing - * the data to stream - * @throws ArrayIndexOutOfBoundsException if the index is - * outside the data array's bounds - * @throws IllegalArgumentException if the output stream is null - */ - - public static void dump(byte[] data, long offset, - OutputStream stream, int index) - throws IOException, ArrayIndexOutOfBoundsException, - IllegalArgumentException { - - if ((index < 0) || (index >= data.length)) { - throw new ArrayIndexOutOfBoundsException( - "illegal index: " + index + " into array of length " - + data.length); - } - if (stream == null) { - throw new IllegalArgumentException("cannot write to nullstream"); - } - long display_offset = offset + index; - StringBuilder buffer = new StringBuilder(74); - - for (int j = index; j < data.length; j += 16) { - int chars_read = data.length - j; - - if (chars_read > 16) { - chars_read = 16; - } - dump(buffer, display_offset).append(' '); - for (int k = 0; k < 16; k++) { - if (k < chars_read) { - dump(buffer, data[k + j]); - } else { - buffer.append(" "); - } - buffer.append(' '); - } - for (int k = 0; k < chars_read; k++) { - if ((data[k + j] >= ' ') && (data[k + j] < 127)) { - buffer.append((char) data[k + j]); - } else { - buffer.append('.'); - } - } - buffer.append(EOL); - stream.write(buffer.toString().getBytes()); - stream.flush(); - buffer.setLength(0); - display_offset += chars_read; - } - } - - /** - * The line-separator (initializes to "line.separator" system property. - */ - public static final String EOL = - System.getProperty("line.separator"); - private static final char[] _hexcodes = - { - '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', - 'A', 'B', 'C', 'D', 'E', 'F' - }; - private static final int[] _shifts = - { - 28, 24, 20, 16, 12, 8, 4, 0 - }; - - /** - * Dump a long value into a StringBuilder. - * - * @param _lbuffer the StringBuilder to dump the value in - * @param value the long value to be dumped - * @return StringBuilder containing the dumped value. - */ - private static StringBuilder dump(StringBuilder _lbuffer, long value) { - for (int j = 0; j < 8; j++) { - _lbuffer - .append(_hexcodes[((int) (value >> _shifts[j])) & 15]); - } - return _lbuffer; - } - - /** - * Dump a byte value into a StringBuilder. - * - * @param _cbuffer the StringBuilder to dump the value in - * @param value the byte value to be dumped - * @return StringBuilder containing the dumped value. - */ - private static StringBuilder dump(StringBuilder _cbuffer, byte value) { - for (int j = 0; j < 2; j++) { - _cbuffer.append(_hexcodes[(value >> _shifts[j + 6]) & 15]); - } - return _cbuffer; - } - -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/NotInstantiable.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/NotInstantiable.java deleted file mode 100644 index 3c30d23d..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/NotInstantiable.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.tests; - -import org.junit.Test; - -@SuppressWarnings("all") -public class NotInstantiable { - static { - System.out.println("Can't instantiate me." + 1 / ((Long) null)); - } - - public NotInstantiable() {} - - @Test - public void method() {} -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/OomCode.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/OomCode.java deleted file mode 100644 index b777f766..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/OomCode.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.tests; - -import java.util.LinkedList; - -import org.junit.Test; - -public class OomCode { - static LinkedList ohMy = new LinkedList(); - - @Test - public void oomInCode() { - int stringLength = 1024 * 1024 * 5; - while (true) { - try { - ohMy.add(new byte [stringLength]); - } catch (OutOfMemoryError e) { - if (stringLength < 100) { - throw e; - } else { - stringLength /= 2; - } - } - } - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/OomPermGen.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/OomPermGen.java deleted file mode 100644 index 5207d806..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/OomPermGen.java +++ /dev/null @@ -1,81 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.tests; - -import static org.objectweb.asm.Opcodes.ACC_PUBLIC; -import static org.objectweb.asm.Opcodes.ACC_SUPER; -import static org.objectweb.asm.Opcodes.ALOAD; -import static org.objectweb.asm.Opcodes.INVOKESPECIAL; -import static org.objectweb.asm.Opcodes.RETURN; -import static org.objectweb.asm.Opcodes.V1_6; - -import java.lang.management.ManagementFactory; -import java.lang.management.MemoryPoolMXBean; -import java.util.ArrayList; -import java.util.List; -import java.util.Random; - -import org.junit.Assume; -import org.junit.Test; -import org.objectweb.asm.ClassWriter; -import org.objectweb.asm.MethodVisitor; - -public class OomPermGen { - abstract class WhoaClassLoader extends ClassLoader { - public abstract Class defineNewClass(byte [] clazz) throws ClassNotFoundException; - } - - WhoaClassLoader cl = new WhoaClassLoader() { - public Class defineNewClass(byte [] clazz) throws ClassNotFoundException { - return super.defineClass(null, clazz, 0, clazz.length); - } - }; - - @Test - public void explodePermGen() throws Exception { - MemoryPoolMXBean permGenPool = null; - for (MemoryPoolMXBean mp : ManagementFactory.getMemoryPoolMXBeans()) { - if (mp.getName().contains("Perm Gen")) { - permGenPool = mp; - break; - } - } - - if (permGenPool == null) { - // No permgen pool? - Assume.assumeTrue(false); - } - - // Just keep on loading classes until we explode. - Random rnd = new Random(0xdeadbeef); - int classes = 0; - List> keep = new ArrayList>(); - while (true) { - if ((classes++ % 1000) == 0) { - System.out.println(permGenPool.getName() + " => " + permGenPool.getUsage()); - } - - // Prepare a new unique exception class with asm. Throw it. - Class clz = generateExceptionClass(rnd.nextLong()); - clz.newInstance(); - keep.add(clz); - } - } - - public Class generateExceptionClass(long x) throws Exception { - ClassWriter cw = new ClassWriter(0); - MethodVisitor mv; - cw.visit(V1_6, ACC_PUBLIC + ACC_SUPER, - "com/carrotsearch/ant/tasks/junit4/tests/SyntheticException_" + x, null, - "java/lang/Exception", null); - - mv = cw.visitMethod(ACC_PUBLIC, "", "()V", null, null); - mv.visitCode(); - mv.visitVarInsn(ALOAD, 0); - mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Exception", "", "()V", false); - mv.visitInsn(RETURN); - mv.visitMaxs(1, 1); - mv.visitEnd(); - cw.visitEnd(); - - return cl.defineNewClass(cw.toByteArray()); - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/OutOfOrderSysouts.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/OutOfOrderSysouts.java deleted file mode 100644 index 921ceb9a..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/OutOfOrderSysouts.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.tests; - -import org.junit.*; - -import com.carrotsearch.randomizedtesting.RandomizedTest; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope.Scope; - -@ThreadLeakScope(Scope.SUITE) -public class OutOfOrderSysouts extends RandomizedTest { - private static Thread t; - - static { - t = new Thread("background-non-daemon") { - public void run() { - sysout("Starting..."); - try { - while (true) { - syserr("garbage..."); - Thread.sleep(1); - } - } catch (Exception e) { - // empty. - } - } - }; - t.start(); - } - - @Before - public void before() { - sleep(1 + randomIntBetween(0, 20)); - } - - @AfterClass - public static void afterClass() throws Exception { - t.interrupt(); - t.join(); - } - - @Test public void method1() { sysout("method1"); } - @Test public void method2() { sysout("method2"); } - @Test public void method3() { sysout("method3"); } - @Test public void method4() { sysout("method4"); } - @Test public void method5() { sysout("method5"); } - @Test public void method6() { sysout("method6"); } - @Test public void method7() { sysout("method7"); } - @Test public void method8() { sysout("method8"); } - @Test public void method9() { sysout("method9"); } - @Test public void method10() { sysout("method10"); } - @Test public void method11() { sysout("method11"); } - - static void sysout(String msg) { - System.out.println(msg); - System.out.flush(); - } - - static void syserr(String msg) { - System.out.println(msg); - System.out.flush(); - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/RandomSysProperty.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/RandomSysProperty.java deleted file mode 100644 index a17381ae..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/RandomSysProperty.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.tests; - -import org.junit.Test; - -public class RandomSysProperty { - @Test - public void test1() { - for (String s : new String [] { - "prefix.dummy1", - "prefix.dummy2", - "replaced.dummy1", - "replaced.dummy2", - }) { - System.out.println(s + "=" + System.getProperty(s)); - } - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/ReasonForAssumptionIgnored.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/ReasonForAssumptionIgnored.java deleted file mode 100644 index 684c0f5b..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/ReasonForAssumptionIgnored.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.tests; - -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; - -import com.carrotsearch.ant.tasks.junit4.it.TestTextReport; -import com.carrotsearch.randomizedtesting.RandomizedRunner; -import com.carrotsearch.randomizedtesting.RandomizedTest; - -/** - * Holder class for tests used in - * {@link TestTextReport#reasonForSuiteAssumptionIgnored()}. - */ -public class ReasonForAssumptionIgnored { - public final static String MESSAGE = "FooBar"; - - @RunWith(RandomizedRunner.class) - public static class IgnoredClassRR extends IgnoredClass { - } - - public static class IgnoredClass { - @BeforeClass - public static void beforeClass() { - RandomizedTest.assumeTrue(MESSAGE, false); - } - - @Test - public void ignored1() {} - - @Test - public void ignored2() {} - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/ReasonForIgnored.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/ReasonForIgnored.java deleted file mode 100644 index 5f242333..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/ReasonForIgnored.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.tests; - -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; - -import com.carrotsearch.ant.tasks.junit4.it.TestTextReport; -import com.carrotsearch.randomizedtesting.RandomizedRunner; - -/** - * Holder class for tests used in {@link TestTextReport#reasonForIgnored()}. - */ -public class ReasonForIgnored -{ - public static class IgnoredMethods { - @Test - @Ignore - public void simplyIgnored() { - } - - @Test - @Ignore("Ignored method.") - public void ignoredWithRationale() { - } - } - - @Ignore("Ignored class.") - public static class IgnoredClass { - @Test - public void ignoredByClass() { - System.out.println("Hello!"); - } - } - - @RunWith(RandomizedRunner.class) - public static class IgnoredMethodsRR extends IgnoredMethods { - @Test - @Ignore("Ignored method (2).") - public void ignoredAgain() { - } - } - - @Ignore("Ignored class.") - @RunWith(RandomizedRunner.class) - public static class IgnoredClassRR extends IgnoredClass { - } - - @RunWith(RandomizedRunner.class) - public static class IgnoredGroup { - @DisabledGroup @Test - public void ignoredByGroup() {} - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/ReasonForIgnoredByDisabledGroup.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/ReasonForIgnoredByDisabledGroup.java deleted file mode 100644 index 35276ce0..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/ReasonForIgnoredByDisabledGroup.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.tests; - -import org.junit.Test; - -import com.carrotsearch.randomizedtesting.RandomizedTest; - -public class ReasonForIgnoredByDisabledGroup extends RandomizedTest -{ - @Test - @DisabledGroup("foo bar") - public void disabledGroup() {} -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/ShutdownHook.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/ShutdownHook.java deleted file mode 100644 index 8e1dd9de..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/ShutdownHook.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.tests; - -import org.junit.Test; - -public class ShutdownHook { - @Test - public void testShutdownHook() { - Runtime.getRuntime().addShutdownHook(new Thread() { - public void run() { - // Delay by about a minute. - long deadline = System.currentTimeMillis() + 60 * 1000; - while (System.currentTimeMillis() < deadline) { - try { - Thread.sleep(1000); - } catch (Exception e) {} - } - } - }); - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/SlaveHangingBackgroundThreads.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/SlaveHangingBackgroundThreads.java deleted file mode 100644 index 053476e1..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/SlaveHangingBackgroundThreads.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.tests; - -import java.util.concurrent.CountDownLatch; - -import org.junit.Test; - - -public class SlaveHangingBackgroundThreads { - static { - final CountDownLatch latch = new CountDownLatch(1); - new Thread("background-non-daemon") { - public void run() { - System.out.println("Starting."); - try { - latch.countDown(); - // Wait looong. - Thread.sleep(1000 * 60 * 60); - } catch (Exception e) { - // empty. - } - } - }.start(); - - try { - latch.await(); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } - - // Cause an unchecked exception. - @SuppressWarnings("unused") - int a = 2 / 0; - } - - @Test - public void method() { - // Ok, passes. - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/StackOverflow.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/StackOverflow.java deleted file mode 100644 index c63808f7..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/StackOverflow.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.tests; - -import org.junit.Test; - -public class StackOverflow { - @Test - public void stackoverflow() { - for (int i = 0; i < 100; i++) { - try { - doStackOverflowAndPrint(0); - } catch (StackOverflowError e) { - // Should have failed inside the runner's infrastructure? - } - } - System.exit(0); - } - - private void doStackOverflowAndPrint(int i) { - System.out.println("Stack overflow attempt: " + i); - doStackOverflowAndPrint(i + 1); - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/SuiteListeners.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/SuiteListeners.java deleted file mode 100644 index 9f15f6d7..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/SuiteListeners.java +++ /dev/null @@ -1,69 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.tests; - -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.Description; -import org.junit.runner.Result; -import org.junit.runner.notification.Failure; -import org.junit.runner.notification.RunListener; - -import com.carrotsearch.randomizedtesting.RandomizedTest; -import com.carrotsearch.randomizedtesting.annotations.Listeners; - -import static org.junit.Assert.*; - -@Listeners({ - SuiteListeners.PrintEventListener.class -}) -public class SuiteListeners extends RandomizedTest { - - public static class PrintEventListener extends RunListener { - - @Override - public void testRunStarted(Description description) throws Exception { - System.out.println("testRunStarted: " + description); - } - - @Override - public void testRunFinished(Result result) throws Exception { - System.out.println("testRunFinished."); - } - - @Override - public void testStarted(Description description) throws Exception { - System.out.println("testStarted: " + description); - } - - @Override - public void testFinished(Description description) throws Exception { - System.out.println("testFinished: " + description); - } - - @Override - public void testFailure(Failure failure) throws Exception { - System.out.println("testFailure: " + failure); - } - - @Override - public void testAssumptionFailure(Failure failure) { - System.out.println("testAssumptionFailure: " + failure); - } - - @Override - public void testIgnored(Description description) throws Exception { - System.out.println("testIgnored: " + description); - } - } - - @Test - public void passing() {} - - @Test @Ignore - public void ignored() {} - - @Test - public void aignored() { assumeTrue(false); } - - @Test - public void failure() { fail(); } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/SysPropertySets.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/SysPropertySets.java deleted file mode 100644 index b0226f0b..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/SysPropertySets.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.tests; - -import org.junit.Test; - -public class SysPropertySets { - @Test - public void test1() { - System.out.println(System.getProperty("prefix.dummy1")); - System.out.println(System.getProperty("prefix.dummy2")); - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/SysoutOom1.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/SysoutOom1.java deleted file mode 100644 index 3b6f79a1..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/SysoutOom1.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.tests; - -import org.junit.Test; - -public class SysoutOom1 { - @Test - public void writealot() { - write("012345678901234567890123456789".toCharArray()); - } - - protected final void write(char[] charArray) { - char [] chars = new char [200]; - for (int i = 0; i < chars.length; i++) { - chars[i] = charArray[i % charArray.length]; - } - - int emitChars = 1024 * 1024 * 25; - while (emitChars > 0) { - System.out.print(chars); - emitChars -= chars.length; - } - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/SysoutOom2.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/SysoutOom2.java deleted file mode 100644 index cdcc6473..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/SysoutOom2.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.tests; - -import org.junit.Test; - -public class SysoutOom2 extends SysoutOom1 { - @Override - @Test - public void writealot() { - write("abcdefghjqiuqiugqwpicvaisuvcipsvcuipqyfpuixv".toCharArray()); - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/SysoutPassthrough.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/SysoutPassthrough.java deleted file mode 100644 index 3eeec63e..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/SysoutPassthrough.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.tests; - -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; - -public class SysoutPassthrough { - @BeforeClass - public static void beforeclass() { - println("-beforeclass-"); - } - - @Before - public void before() { - println("-before-"); - } - - @Test - public void test1() { - println("-test1-"); - } - - @Test - public void test2() { - println("-test2-"); - } - - @After - public void after() { - print("-after-"); - } - - @AfterClass - public static void afterclass() { - println("-afterclass-"); - } - - private static void print(String m) { - System.out.print(m); - System.out.flush(); - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - throw new RuntimeException(); - } - } - - private static void println(String m) { - print(m + "\n"); - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/SysoutsOnSuiteFailure.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/SysoutsOnSuiteFailure.java deleted file mode 100644 index 63d5476b..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/SysoutsOnSuiteFailure.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.tests; - -import org.junit.AfterClass; -import org.junit.Assume; -import org.junit.BeforeClass; -import org.junit.Test; - -public class SysoutsOnSuiteFailure { - - @BeforeClass - public static void beforeClass() { - System.out.println("beforeclass-sysout."); - } - - @Test - public void assumptionIgnored() { - System.out.println("ignored-sysout."); - Assume.assumeTrue(false); - } - - @Test - public void success() { - System.out.println("success-sysout."); - } - - @AfterClass - public static void afterClass() { - System.out.println("afterclass-sysout."); - throw new RuntimeException(); - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/SysoutsOnSuiteTimeout.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/SysoutsOnSuiteTimeout.java deleted file mode 100644 index 394b8954..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/SysoutsOnSuiteTimeout.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.tests; - -import org.junit.BeforeClass; -import org.junit.Test; - -import com.carrotsearch.randomizedtesting.RandomizedTest; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakAction; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakAction.Action; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakGroup; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakGroup.Group; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakLingering; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope.Scope; -import com.carrotsearch.randomizedtesting.annotations.TimeoutSuite; - -@ThreadLeakScope(Scope.SUITE) -@ThreadLeakGroup(Group.MAIN) -@ThreadLeakAction({Action.WARN, Action.INTERRUPT}) -@ThreadLeakLingering(linger = 1000) -@TimeoutSuite(millis = 1000) -public class SysoutsOnSuiteTimeout extends RandomizedTest { - @BeforeClass - public static void beforeClass() { - System.out.println("beforeclass-sysout."); - } - - @Test - public void success() throws Exception { - System.out.println("test-sysout."); - Thread.sleep(100000); - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/TestAfterClassError.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/TestAfterClassError.java deleted file mode 100644 index 65ffa1f2..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/TestAfterClassError.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.tests; - -import org.junit.AfterClass; -import org.junit.Test; - -public class TestAfterClassError { - @AfterClass - public static void afterClass() { - throw new RuntimeException(); - } - - @Test - public void method() {} -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/TestBeforeClassError.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/TestBeforeClassError.java deleted file mode 100644 index 04318a30..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/TestBeforeClassError.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.tests; - -import org.junit.BeforeClass; -import org.junit.Test; - -public class TestBeforeClassError { - @BeforeClass - public static void beforeClass() { - throw new RuntimeException(); - } - - @Test - public void method() {} -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/TestCreateTmpFile.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/TestCreateTmpFile.java deleted file mode 100644 index 956e6b33..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/TestCreateTmpFile.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.tests; - -import static org.junit.Assert.*; - -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; - -import org.junit.Test; - -public class TestCreateTmpFile { - @Test - public void createTmpFile() throws IOException { - Path path = Paths.get(System.getProperty("java.io.tmpdir")).toAbsolutePath(); - System.out.println("Temporary folder at: " + path + ", exists: " + Files.exists(path)); - Path tmpFile = Files.createTempFile("tmp", ".txt"); - assertTrue(Files.exists(tmpFile)); - System.out.println("Created tmpfile: " + tmpFile.toAbsolutePath()); - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/TestDir.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/TestDir.java deleted file mode 100644 index 23986fe0..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/TestDir.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.tests; - -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Paths; - -import org.junit.Test; - -public class TestDir { - @Test - public void createDir() throws IOException { - Files.createFile(Paths.get("touch.me")); - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/TestEnvVar.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/TestEnvVar.java deleted file mode 100644 index 22448b88..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/TestEnvVar.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.tests; - -import java.io.IOException; - -import org.junit.Assert; -import org.junit.Test; - -public class TestEnvVar { - /** - * Check environment property passing. - */ - @Test - public void testEnvVar() throws IOException { - String value = System.getenv("env.variable"); - Assert.assertEquals("foobar", value); - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/TestEscaping.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/TestEscaping.java deleted file mode 100644 index 2b7d500c..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/TestEscaping.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.tests; - -import org.junit.Assert; -import org.junit.Test; - -public class TestEscaping { - @Test - public void checkEscapes() { - // success it is. - System.out.println(System.getProperty("sysprop.key")); - System.out.println(System.getProperty("sysprop.key2")); - System.out.println(System.getProperty("sysprop.key3")); - System.out.println(System.getenv("env.variable")); - - Assert.assertEquals("${nonexistent-1}", System.getProperty("sysprop.key")); - Assert.assertEquals("abc def", System.getProperty("sysprop.key2")); - Assert.assertEquals("%PATH%", System.getProperty("sysprop.key3")); - Assert.assertEquals("${nonexistent-3}", System.getenv("env.variable")); - } - - public static void main(String[] args) { - new TestEscaping().checkEscapes(); - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/TestFailureTypePassing.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/TestFailureTypePassing.java deleted file mode 100644 index 856d72ce..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/TestFailureTypePassing.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.tests; - -import static org.objectweb.asm.Opcodes.ACC_PUBLIC; -import static org.objectweb.asm.Opcodes.ACC_SUPER; -import static org.objectweb.asm.Opcodes.ALOAD; -import static org.objectweb.asm.Opcodes.INVOKESPECIAL; -import static org.objectweb.asm.Opcodes.RETURN; -import static org.objectweb.asm.Opcodes.V1_6; - -import org.junit.Test; -import org.objectweb.asm.ClassWriter; -import org.objectweb.asm.MethodVisitor; - -public class TestFailureTypePassing { - @Test - public void nonStandardError() throws Exception { - // Prepare a new unique exception class with asm. Throw it. - Class clz = generateExceptionClass(); - throw Exception.class.cast(clz.newInstance()); - } - - public static Class generateExceptionClass() throws Exception { - ClassWriter cw = new ClassWriter(0); - MethodVisitor mv; - cw.visit(V1_6, ACC_PUBLIC + ACC_SUPER, - "com/carrotsearch/ant/tasks/junit4/tests/SyntheticException", null, - "java/lang/Exception", null); - - mv = cw.visitMethod(ACC_PUBLIC, "", "()V", null, null); - mv.visitCode(); - mv.visitVarInsn(ALOAD, 0); - mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Exception", "", "()V", false); - mv.visitInsn(RETURN); - mv.visitMaxs(1, 1); - mv.visitEnd(); - cw.visitEnd(); - - return new ClassLoader() { - public Class defineNewClass(byte [] clazz) throws ClassNotFoundException { - return super.defineClass(null, clazz, 0, clazz.length); - } - }.defineNewClass(cw.toByteArray()); - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/TestFilteringExpressions.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/TestFilteringExpressions.java deleted file mode 100644 index 95e1bc33..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/TestFilteringExpressions.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.tests; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Inherited; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -import org.junit.Test; - -import com.carrotsearch.randomizedtesting.RandomizedTest; -import com.carrotsearch.randomizedtesting.annotations.TestGroup; - -public class TestFilteringExpressions { - @Retention(RetentionPolicy.RUNTIME) - @Target({ElementType.METHOD, ElementType.TYPE}) - @Inherited - @TestGroup(enabled = false) - public static @interface Foo {} - - @Retention(RetentionPolicy.RUNTIME) - @Target({ElementType.METHOD, ElementType.TYPE}) - @Inherited - @TestGroup(enabled = false) - public static @interface Bar {} - - public static class Example1 extends RandomizedTest { - @Test @Foo - public void testFoo() { - System.out.println(">foo<"); - } - - @Test @Foo @Bar - public void testFooBar() { - System.out.println(">foobar<"); - } - - @Test @Bar - public void testBar() { - System.out.println(">bar<"); - } - } - - public static class Example2 extends RandomizedTest { - @Test @Foo @Bar - public void testFooBar() { - System.out.println(">foobar2<"); - } - - @Test @Bar - public void testBar() { - System.out.println(">bar2<"); - } - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/TestHierarchicalSuiteDescription.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/TestHierarchicalSuiteDescription.java deleted file mode 100644 index 26bd3b38..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/TestHierarchicalSuiteDescription.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.tests; - -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Suite; -import org.junit.runners.Suite.SuiteClasses; - -@RunWith(Suite.class) -@SuiteClasses({ - TestHierarchicalSuiteDescription.Sub1.class, - TestHierarchicalSuiteDescription.Sub2.class, - TestHierarchicalSuiteDescription.Sub3.class -}) -public class TestHierarchicalSuiteDescription { - public static class Sub1 { - @Test - public void method1() {} - - @BeforeClass - public static void beforeClass() { - throw new RuntimeException(); - } - } - - public static class Sub2 { - @Test - public void method1() {} - - @AfterClass - public static void afterClass() { - throw new RuntimeException(); - } - } - - public static class Sub3 { - @Test - public void method1() { - throw new RuntimeException(); - } - } - - @AfterClass - public static void afterClass() { - throw new RuntimeException(); - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/TestIgnoredSuite.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/TestIgnoredSuite.java deleted file mode 100644 index 2824c633..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/TestIgnoredSuite.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.tests; - -import org.junit.Ignore; -import org.junit.Test; - -@Ignore -public class TestIgnoredSuite { - @Test - public void method1() {} - - @Test - public void method2() {} - - @Test - public void method3() {} - - @Test - public void method4() {} - - @Test - public void method5() {} -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/TestInvalidUtfCharacter.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/TestInvalidUtfCharacter.java deleted file mode 100644 index 4f21d1b4..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/TestInvalidUtfCharacter.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.tests; - -import org.junit.Test; - -public class TestInvalidUtfCharacter { - @Test - public void emitInvalidCharacter() throws Exception { - String msg = "Invalid char: >\u0002< >\u0000<"; - System.out.println(msg); - System.out.flush(); - throw new Exception(msg); - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/TestJvmArg.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/TestJvmArg.java deleted file mode 100644 index 2ecdef74..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/TestJvmArg.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.tests; - -import org.junit.Assert; -import org.junit.Test; - -public class TestJvmArg { - /** - * Check system property passing. - */ - @Test - public void testJvmArg() { - Assert.assertEquals("foobar", System.getProperty("test.param")); - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/TestJvmCrash.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/TestJvmCrash.java deleted file mode 100644 index 6f0053a7..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/TestJvmCrash.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.tests; - -import java.io.IOException; - -import org.junit.Assert; -import org.junit.Test; - -public class TestJvmCrash { - /** - * Check jvm crash. - */ - @Test - public void testJvmCrash() throws IOException { - // Try going into native mode first and cause a sigsegv. - // This will work for any jvm (?). - Crash.loadLibrary(); - Crash.crashMe(); - Assert.fail(); - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/TestMaxMem.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/TestMaxMem.java deleted file mode 100644 index 00f51343..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/TestMaxMem.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.tests; - -import org.junit.Assert; -import org.junit.Test; - -public class TestMaxMem { - /** - * Check max memory setting to be less than 100mb. - */ - @Test - public void testMaxMemory() { - long maxMemory = Runtime.getRuntime().maxMemory(); - Assert.assertTrue(maxMemory / (1024 * 1024) < 110); - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/TestReproduceString.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/TestReproduceString.java deleted file mode 100644 index 6164b8b4..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/TestReproduceString.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.tests; - -import org.junit.Assert; -import org.junit.Test; - -import com.carrotsearch.randomizedtesting.RandomizedTest; -import com.carrotsearch.randomizedtesting.annotations.Listeners; -import com.carrotsearch.randomizedtesting.listeners.ReproduceInfoPrinter; - -@Listeners({ - ReproduceInfoPrinter.class -}) -public class TestReproduceString extends RandomizedTest { - @Test - public void alwaysFail() { - Assert.fail(); - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/TestSecuritySandbox.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/TestSecuritySandbox.java deleted file mode 100644 index d27061b2..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/TestSecuritySandbox.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.tests; - -import org.junit.Test; - -public class TestSecuritySandbox { - @Test - public void accessDenied() { - System.getProperty("foo"); - System.setProperty("foo", "bar"); - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/TestSeedPassing.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/TestSeedPassing.java deleted file mode 100644 index 63790dd6..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/TestSeedPassing.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.tests; - -import java.io.IOException; - -import org.junit.Assert; -import org.junit.Test; - -import com.carrotsearch.randomizedtesting.*; -import static com.carrotsearch.randomizedtesting.SysGlobals.*; - -public class TestSeedPassing extends RandomizedTest { - @Test - public void checkSeedSet() throws IOException { - String expected = SeedUtils.formatSeedChain( - new Randomness(0xdeadbeefL, RandomSupplier.DEFAULT), - new Randomness(0xcafebabeL, RandomSupplier.DEFAULT)); - - Assert.assertEquals( - expected, - System.getProperty(SYSPROP_RANDOM_SEED())); - - Assert.assertEquals( - "[CAFEBABE]", - SeedUtils.formatSeedChain(getContext().getRandomness())); - - Assert.assertEquals( - "[DEADBEEF]", - SeedUtils.formatSeedChain( - new Randomness( - SeedUtils.parseSeed(getContext().getRunnerSeedAsString()), - RandomSupplier.DEFAULT))); - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/TestStaticScopeOutput.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/TestStaticScopeOutput.java deleted file mode 100644 index 9ac5fa24..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/TestStaticScopeOutput.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.tests; - -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; - -/** - * Static scope output. - */ -public class TestStaticScopeOutput { - static { - System.out.println("static-scope"); - System.out.flush(); - } - - @BeforeClass - public static void beforeClass() { - System.out.println("before-class"); - System.out.flush(); - } - - @Test - public void testMethod() { - System.out.println("test-method"); - System.out.flush(); - } - - @AfterClass - public static void afterClass() { - System.out.println("after-class"); - System.out.flush(); - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/TestStatuses.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/TestStatuses.java deleted file mode 100644 index 7e30b221..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/TestStatuses.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.tests; - -import org.junit.Assert; -import org.junit.Assume; -import org.junit.Ignore; -import org.junit.Test; - -public class TestStatuses { - @Test - public void ok() { - } - - @Test @Ignore - public void ignored() { - } - - @Test - public void ignored_a() { - Assume.assumeTrue(false); - } - - @Test - public void failure() { - Assert.assertTrue(false); - } - - @Test - public void error() { - throw new RuntimeException(); - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/TestSuccess.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/TestSuccess.java deleted file mode 100644 index 0c1853f9..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/TestSuccess.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.tests; - -import org.junit.Test; - -import com.carrotsearch.randomizedtesting.RandomizedTest; -import com.carrotsearch.randomizedtesting.SeedUtils; - -public class TestSuccess extends RandomizedTest { - @Test - public void alwaysPasses() { - System.out.println("Seed: " + - SeedUtils.formatSeedChain(getContext().getRandomness())); - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/TestSysstreams.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/TestSysstreams.java deleted file mode 100644 index 5d44c3d9..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/TestSysstreams.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.tests; - -import org.junit.Test; - -public class TestSysstreams { - @Test - public void ok() {} - - @Test - public void ok_sysout_syserr() { - System.out.print("sysout"); - System.out.flush(); - System.err.print("syserr"); - System.err.flush(); - System.out.print("-sysout-contd."); - System.out.flush(); - System.err.print("-syserr-contd."); - System.err.flush(); - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/bad/TestAbstract.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/bad/TestAbstract.java deleted file mode 100644 index a560c76d..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/bad/TestAbstract.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.tests.bad; - -import org.junit.Test; - -public abstract class TestAbstract { - @Test - public void shouldBeIgnored() {} -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/bad/TestPackagePrivate.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/bad/TestPackagePrivate.java deleted file mode 100644 index 04022ed9..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/bad/TestPackagePrivate.java +++ /dev/null @@ -1,4 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.tests.bad; - -class TestPackagePrivate { -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/replication/TestNonReplicated1.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/replication/TestNonReplicated1.java deleted file mode 100644 index 926a2d70..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/replication/TestNonReplicated1.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.tests.replication; - -import org.junit.Test; - -import com.carrotsearch.randomizedtesting.RandomizedTest; - -public class TestNonReplicated1 extends RandomizedTest { - @Test - public void nonReplicatedTest() { - System.out.println("Non-replicated test, VM: " + System.getProperty("junit4.childvm.id")); - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/replication/TestNonReplicated2.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/replication/TestNonReplicated2.java deleted file mode 100644 index c71dd106..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/replication/TestNonReplicated2.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.tests.replication; - -import org.junit.Test; - -import com.carrotsearch.randomizedtesting.RandomizedTest; - -public class TestNonReplicated2 extends RandomizedTest { - @Test - public void nonReplicatedTest() { - System.out.println("Non-replicated test, VM: " + System.getProperty("junit4.childvm.id")); - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/replication/TestPseudoLoadBalancing.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/replication/TestPseudoLoadBalancing.java deleted file mode 100644 index a556812a..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/replication/TestPseudoLoadBalancing.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.tests.replication; - -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; - -import org.junit.Before; -import org.junit.Test; - -import com.carrotsearch.randomizedtesting.RandomizedTest; -import com.carrotsearch.randomizedtesting.annotations.Name; -import com.carrotsearch.randomizedtesting.annotations.ParametersFactory; -import com.carrotsearch.randomizedtesting.annotations.ReplicateOnEachVm; - -@ReplicateOnEachVm -public class TestPseudoLoadBalancing extends RandomizedTest { - private int id; - private int jvmId; - private int jvms; - - public TestPseudoLoadBalancing(@Name("id") int id) { - this.id = id; - } - - @Before - public void pseudoLoadBalancing() { - jvmId = Integer.parseInt(System.getProperty("junit4.childvm.id")); - jvms = Integer.parseInt(System.getProperty("junit4.childvm.count")); - - assumeTrue( - String.format(Locale.ROOT, "Test %d ignored on VM %d.", id, jvmId), - (id % jvms) == jvmId); - } - - @Test - public void replicatedTest() { - System.out.println(String.format(Locale.ROOT, "Test %d executed on VM %d.", id, jvmId)); - } - - @ParametersFactory - public static Iterable parameters() { - List args = new ArrayList(); - for (int i = 0; i < 100; i++) { - args.add($(i)); - } - return args; - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/replication/TestSuiteReplicated.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/replication/TestSuiteReplicated.java deleted file mode 100644 index b1159240..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/replication/TestSuiteReplicated.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.tests.replication; - -import org.junit.Test; - -import com.carrotsearch.randomizedtesting.RandomizedTest; -import com.carrotsearch.randomizedtesting.annotations.ReplicateOnEachVm; - -@ReplicateOnEachVm -public class TestSuiteReplicated extends RandomizedTest { - @Test - public void replicatedTest() { - System.out.println("Replicated test, VM: " + System.getProperty("junit4.childvm.id")); - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/sub1/TestAssertions.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/sub1/TestAssertions.java deleted file mode 100644 index e6a658ed..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/sub1/TestAssertions.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.tests.sub1; - -import org.junit.Test; - -public class TestAssertions { - @Test - public void failOnAssertion() { - assert false : "foobar"; - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/sub2/TestHalfSecond.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/sub2/TestHalfSecond.java deleted file mode 100644 index 071f23dd..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/sub2/TestHalfSecond.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.tests.sub2; - -import org.junit.Test; - -public class TestHalfSecond { - @Test - public void halfSecond() throws Exception { - Thread.sleep(500); - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/sub2/TestOneSecond.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/sub2/TestOneSecond.java deleted file mode 100644 index 705eeb0a..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/sub2/TestOneSecond.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.tests.sub2; - -import org.junit.Test; - -public class TestOneSecond { - @Test - public void quarterSecond1() throws Exception { - Thread.sleep(250); - } - - @Test - public void quarterSecond2() throws Exception { - Thread.sleep(250); - } - - @Test - public void quarterSecond3() throws Exception { - Thread.sleep(250); - } - - @Test - public void quarterSecond4() throws Exception { - Thread.sleep(250); - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/sub2/TestTwoSeconds.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/sub2/TestTwoSeconds.java deleted file mode 100644 index 9722ffdd..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/sub2/TestTwoSeconds.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.tests.sub2; - -import org.junit.Test; - -public class TestTwoSeconds { - @Test - public void oneSecond1() throws Exception { - Thread.sleep(1000); - } - - @Test - public void oneSecond2() throws Exception { - Thread.sleep(1000); - } -} diff --git a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/sub2/TestZeroSeconds.java b/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/sub2/TestZeroSeconds.java deleted file mode 100644 index 334bacff..00000000 --- a/junit4-ant/src/test/java/com/carrotsearch/ant/tasks/junit4/tests/sub2/TestZeroSeconds.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.carrotsearch.ant.tasks.junit4.tests.sub2; - -import org.junit.Test; - -public class TestZeroSeconds { - @Test - public void zero() throws Exception { - } -} diff --git a/junit4-ant/src/test/resources/hints-fixed.log b/junit4-ant/src/test/resources/hints-fixed.log deleted file mode 100644 index de317cf9..00000000 --- a/junit4-ant/src/test/resources/hints-fixed.log +++ /dev/null @@ -1,4 +0,0 @@ -com.carrotsearch.ant.tasks.junit4.tests.sub2.TestHalfSecond=500,501,501,501,521 -com.carrotsearch.ant.tasks.junit4.tests.sub2.TestOneSecond=1002,1018,1022,1002,1002 -com.carrotsearch.ant.tasks.junit4.tests.sub2.TestTwoSeconds=2016,2019,2028,2024,2019 -com.carrotsearch.ant.tasks.junit4.tests.sub2.TestZeroSeconds=15,2,1,22,2 diff --git a/junit4-ant/src/test/resources/junit4.xml b/junit4-ant/src/test/resources/junit4.xml deleted file mode 100644 index a8472ab7..00000000 --- a/junit4-ant/src/test/resources/junit4.xml +++ /dev/null @@ -1,1572 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ${native.libs} - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ${basedir} - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - jvm.exec property must be set. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - UTF-8 - UTF-16 - US-ASCII - iso8859-1 - - - - UTF-8 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ${junit4.stats.tests} - ${junit4.stats.errors} - ${junit4.stats.failures} - ${junit4.stats.ignores} - ${junit4.stats.suites} - ${junit4.stats.assumptions} - ${junit4.stats.suiteErrors} - ${junit4.stats.nonIgnored} - ${junit4.stats.successful} - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ${junit4.stats.tests} - ${junit4.stats.errors} - ${junit4.stats.failures} - ${junit4.stats.ignores} - ${junit4.stats.suites} - ${junit4.stats.assumptions} - ${junit4.stats.suiteErrors} - ${junit4.stats.nonIgnored} - ${junit4.stats.successful} - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/junit4-ant/src/test/resources/security.policy b/junit4-ant/src/test/resources/security.policy deleted file mode 100644 index 24b2187f..00000000 --- a/junit4-ant/src/test/resources/security.policy +++ /dev/null @@ -1,37 +0,0 @@ - -//// permission for the junit4 jar -grant codeBase "${junit4.jar.url}" { - // needed because JUnit requests/ runners don't use access controller contexts - // and the access control domain propagates up the stack. - permission java.lang.RuntimePermission "accessDeclaredMembers"; - // needed for io stream handling - permission java.lang.RuntimePermission "setIO"; - // needed for accessing log files, etc. - permission java.io.FilePermission "${junit4.tempDir}${/}*", "read,write,delete,execute"; -}; - -//// permissions for the randomized runner jar -grant codeBase "${randomizedtesting.jar.url}" { - // optionally needed for access to private test methods (e.g. beforeClass) - permission java.lang.reflect.ReflectPermission "suppressAccessChecks"; - // needed to handle uncaught exceptions from other threads - permission java.lang.RuntimePermission "setDefaultUncaughtExceptionHandler"; - // needed for getTopThreads - permission java.lang.RuntimePermission "modifyThreadGroup"; - // needed for TestClass creation - permission java.lang.RuntimePermission "accessDeclaredMembers"; - // needed for ThreadLeakControl - permission java.lang.RuntimePermission "getStackTrace"; -}; - -//// permissions for the junit jar -grant codeBase "${junit.jar.url}" { - // needed for TestClass creation - permission java.lang.RuntimePermission "accessDeclaredMembers"; -}; - -//// Test class permission: we want this to be minimal! -grant { - permission java.util.PropertyPermission "*", "read"; - permission java.io.FilePermission "${junit4.childvm.cwd}${/}*", "read,write,delete"; -}; diff --git a/junit4-maven-plugin-tests/pom.xml b/junit4-maven-plugin-tests/pom.xml deleted file mode 100644 index f61530d2..00000000 --- a/junit4-maven-plugin-tests/pom.xml +++ /dev/null @@ -1,70 +0,0 @@ - - 4.0.0 - - - com.carrotsearch.randomizedtesting - randomizedtesting-parent - 2.7.9-SNAPSHOT - ../pom.xml - - - junit4-maven-plugin-tests - - jar - - - true - - - - - junit - junit - - - - com.carrotsearch.randomizedtesting - randomizedtesting-runner - ${project.version} - - - - com.carrotsearch.randomizedtesting - junit4-maven-plugin - ${project.version} - - - - - - - maven-invoker-plugin - - true - src/it - ${project.build.directory}/it - true - - **/pom.xml - - - pom.xml - - verify - ${project.build.directory}/local-repo - src/it/settings.xml - - - - integration-test - - install - run - - - - - - - diff --git a/junit4-maven-plugin-tests/src/it/01-basic-test/invoker.properties b/junit4-maven-plugin-tests/src/it/01-basic-test/invoker.properties deleted file mode 100644 index ad075dbf..00000000 --- a/junit4-maven-plugin-tests/src/it/01-basic-test/invoker.properties +++ /dev/null @@ -1 +0,0 @@ -invoker.goals=test \ No newline at end of file diff --git a/junit4-maven-plugin-tests/src/it/01-basic-test/pom.xml b/junit4-maven-plugin-tests/src/it/01-basic-test/pom.xml deleted file mode 100644 index 63b0090a..00000000 --- a/junit4-maven-plugin-tests/src/it/01-basic-test/pom.xml +++ /dev/null @@ -1,123 +0,0 @@ - - 4.0.0 - - com.carrotsearch.randomizedtesting - junit4-maven-plugin-tests - 0.0.1-SNAPSHOT - - jar - - - 3.0.2 - - - - UTF-8 - UTF-8 - - 1.8 - 1.8 - - - - - com.carrotsearch.randomizedtesting - randomizedtesting-runner - @project.version@ - test - - - - com.carrotsearch.thirdparty - simple-xml-safe - 2.7.1 - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.1 - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - true - - - - - com.carrotsearch.randomizedtesting - junit4-maven-plugin - @project.version@ - - - junit4-tests - - junit4 - - - 10 - pipe,ignore - true - warn - - com.carrotsearch.thirdparty:simple-xml-safe - - - - -DargLine.property=foobar - -DargLine.property2=foobar - - - - - - - - - - - - - - - - - - **/Test0*.class - - - **/Buhu* - - - - - - - - - - - - diff --git a/junit4-maven-plugin-tests/src/it/01-basic-test/src/test/java/com/carrotsearch/examples/randomizedrunner/Test001InsideMaven.java b/junit4-maven-plugin-tests/src/it/01-basic-test/src/test/java/com/carrotsearch/examples/randomizedrunner/Test001InsideMaven.java deleted file mode 100644 index 927e1e37..00000000 --- a/junit4-maven-plugin-tests/src/it/01-basic-test/src/test/java/com/carrotsearch/examples/randomizedrunner/Test001InsideMaven.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.carrotsearch.examples.randomizedrunner; - -import org.junit.Assert; -import org.junit.Test; - -public class Test001InsideMaven { - @Test - public void success() { - // Empty. - } - - @Test - public void checkArgLinePassed() { - Assert.assertEquals("foobar", System.getProperty("argLine.property")); - Assert.assertEquals("foobar", System.getProperty("argLine.property2")); - Assert.assertEquals("foobar", System.getProperty("verbatim.section")); - } -} diff --git a/junit4-maven-plugin-tests/src/it/01-basic-test/verify.bsh b/junit4-maven-plugin-tests/src/it/01-basic-test/verify.bsh deleted file mode 100644 index f69c4e7f..00000000 --- a/junit4-maven-plugin-tests/src/it/01-basic-test/verify.bsh +++ /dev/null @@ -1,19 +0,0 @@ - -import java.io.*; -import java.util.*; -import java.util.regex.*; - -import com.carrotsearch.maven.plugins.junit4.*; - -la = new LogAssert(new File(basedir, "build.log")); - -// Tests successful. -la.assertLogContains("Tests summary: 1 suite, 2 tests"); - -// Listener enabled. -la.assertLogContains("| Test001InsideMaven.success"); - -// Assertions. -la.assertLogContains("-ea:com.carrotsearch.ant.tasks.junit4.tests.sub1..."); - -return true; diff --git a/junit4-maven-plugin-tests/src/it/02-config-inheritance/invoker.properties b/junit4-maven-plugin-tests/src/it/02-config-inheritance/invoker.properties deleted file mode 100644 index cd7f006e..00000000 --- a/junit4-maven-plugin-tests/src/it/02-config-inheritance/invoker.properties +++ /dev/null @@ -1 +0,0 @@ -invoker.goals=verify \ No newline at end of file diff --git a/junit4-maven-plugin-tests/src/it/02-config-inheritance/pom.xml b/junit4-maven-plugin-tests/src/it/02-config-inheritance/pom.xml deleted file mode 100644 index 941044ea..00000000 --- a/junit4-maven-plugin-tests/src/it/02-config-inheritance/pom.xml +++ /dev/null @@ -1,142 +0,0 @@ - - 4.0.0 - - com.carrotsearch.randomizedtesting - junit4-maven-plugin-tests - 0.0.1-SNAPSHOT - - jar - - - UTF-8 - - 1.6 - 1.6 - - - @project.version@ - - - - - com.carrotsearch.randomizedtesting - randomizedtesting-runner - ${rr.version} - test - - - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - true - - - - default-test - none - - - - - - - com.carrotsearch.randomizedtesting - junit4-maven-plugin - ${rr.version} - - - - 10 - pipe,ignore - true - warn - - - - - - - arg.common - - - - - - - unit-tests - test - - junit4 - - true - - - **/Test*.class - **/*Test.class - - - **/*$* - - - - - - - integration-tests - integration-test - - junit4 - - true - - - **/IT*.class - **/*IT.class - - - **/*$* - - - - - - - - - - - com.carrotsearch.randomizedtesting - junit4-maven-plugin - - - - unit-tests - - - arg.unit - - - - - - - integration-tests - - - arg.it - - - - - - - - diff --git a/junit4-maven-plugin-tests/src/it/02-config-inheritance/src/test/java/com/carrotsearch/examples/randomizedrunner/IntegrationIT.java b/junit4-maven-plugin-tests/src/it/02-config-inheritance/src/test/java/com/carrotsearch/examples/randomizedrunner/IntegrationIT.java deleted file mode 100644 index d9642882..00000000 --- a/junit4-maven-plugin-tests/src/it/02-config-inheritance/src/test/java/com/carrotsearch/examples/randomizedrunner/IntegrationIT.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.carrotsearch.examples.randomizedrunner; - -import org.junit.Assert; -import org.junit.Test; - -public class IntegrationIT { - @Test - public void commonArg() { - Assert.assertEquals("arg.common", System.getProperty("arg.common")); - } - - @Test - public void itConfigArg() { - Assert.assertEquals("arg.it", System.getProperty("arg.it")); - } -} diff --git a/junit4-maven-plugin-tests/src/it/02-config-inheritance/src/test/java/com/carrotsearch/examples/randomizedrunner/UnitTest.java b/junit4-maven-plugin-tests/src/it/02-config-inheritance/src/test/java/com/carrotsearch/examples/randomizedrunner/UnitTest.java deleted file mode 100644 index 9ce5d6a4..00000000 --- a/junit4-maven-plugin-tests/src/it/02-config-inheritance/src/test/java/com/carrotsearch/examples/randomizedrunner/UnitTest.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.carrotsearch.examples.randomizedrunner; - -import org.junit.Assert; -import org.junit.Test; - -public class UnitTest { - @Test - public void commonArg() { - Assert.assertEquals("arg.common", System.getProperty("arg.common")); - } - - @Test - public void unitConfigArg() { - Assert.assertEquals("arg.unit", System.getProperty("arg.unit")); - } -} diff --git a/junit4-maven-plugin-tests/src/it/02-config-inheritance/verify.bsh b/junit4-maven-plugin-tests/src/it/02-config-inheritance/verify.bsh deleted file mode 100644 index ed51a189..00000000 --- a/junit4-maven-plugin-tests/src/it/02-config-inheritance/verify.bsh +++ /dev/null @@ -1,16 +0,0 @@ - -import java.io.*; -import java.util.*; -import java.util.regex.*; - -import com.carrotsearch.maven.plugins.junit4.*; - -la = new LogAssert(new File(basedir, "build.log")); - -// Tests successful. -la.assertLogContains("Tests summary: 1 suite, 2 tests"); - -// Build successful. -la.assertLogContains("BUILD SUCCESS"); - -return true; diff --git a/junit4-maven-plugin-tests/src/it/settings.xml b/junit4-maven-plugin-tests/src/it/settings.xml deleted file mode 100644 index c8f77f0b..00000000 --- a/junit4-maven-plugin-tests/src/it/settings.xml +++ /dev/null @@ -1,55 +0,0 @@ - - - - - - - - it-repo - - true - - - - local.central - @localRepositoryUrl@ - - true - - - true - - - - - - local.central - @localRepositoryUrl@ - - true - - - true - - - - - - diff --git a/junit4-maven-plugin-tests/src/test/java/com/carrotsearch/maven/plugins/junit4/LogAssert.java b/junit4-maven-plugin-tests/src/test/java/com/carrotsearch/maven/plugins/junit4/LogAssert.java deleted file mode 100644 index 157443a4..00000000 --- a/junit4-maven-plugin-tests/src/test/java/com/carrotsearch/maven/plugins/junit4/LogAssert.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.carrotsearch.maven.plugins.junit4; - -import java.io.File; -import java.io.IOException; -import java.nio.charset.Charset; -import java.nio.file.Files; - -import org.junit.Assert; - -/** - * Asserts on the content of integration tests' log file. - */ -public class LogAssert { - private String logFile; - - public LogAssert(File buildLog) throws IOException { - this.logFile = new String(Files.readAllBytes(buildLog.toPath()), Charset.defaultCharset()); - } - - public void assertLogContains(String text) { - Assert.assertTrue("Log file was expected to contain: '" - + text + "'", logFile.indexOf(text) >= 0); - } -} diff --git a/junit4-maven-plugin/pom.xml b/junit4-maven-plugin/pom.xml deleted file mode 100644 index 648d76cc..00000000 --- a/junit4-maven-plugin/pom.xml +++ /dev/null @@ -1,144 +0,0 @@ - - 4.0.0 - - - com.carrotsearch.randomizedtesting - randomizedtesting-parent - 2.7.9-SNAPSHOT - ../pom.xml - - - junit4-maven-plugin - - maven-plugin - - - - com.carrotsearch.randomizedtesting - junit4-ant - ${project.version} - - - - com.carrotsearch.randomizedtesting - randomizedtesting-runner - ${project.version} - true - - - - org.apache.maven - maven-plugin-api - ${minimum.maven.version} - - - - org.apache.maven - maven-core - jar - ${minimum.maven.version} - - - - org.apache.maven - maven-artifact - jar - ${minimum.maven.version} - - - - org.apache.maven - maven-compat - ${minimum.maven.version} - - - - org.apache.maven.plugin-tools - maven-plugin-annotations - 3.5 - provided - - - - org.apache.ant - ant - compile - - - - org.apache.ant - ant-junit - compile - - - - org.dom4j - dom4j - - - - org.apache.maven.shared - maven-common-artifact-filters - 3.0.0 - - - google-collections - com.google.collections - - - maven-project - org.apache.maven - - - - - - org.apache.maven.plugins - maven-antrun-plugin - ${version.maven-antrun-plugin} - jar - - - maven-project - org.apache.maven - - - - - - - - - de.thetaphi - forbiddenapis - - - - org.apache.maven.plugins - maven-plugin-plugin - - - java-annotations - - - - - mojo-descriptor - process-classes - - descriptor - - - - - generated-helpmojo - - helpmojo - - - - - - - diff --git a/junit4-maven-plugin/src/main/java/com/carrotsearch/maven/plugins/junit4/JUnit4Mojo.java b/junit4-maven-plugin/src/main/java/com/carrotsearch/maven/plugins/junit4/JUnit4Mojo.java deleted file mode 100644 index 05c8c803..00000000 --- a/junit4-maven-plugin/src/main/java/com/carrotsearch/maven/plugins/junit4/JUnit4Mojo.java +++ /dev/null @@ -1,891 +0,0 @@ -package com.carrotsearch.maven.plugins.junit4; - -import static com.google.common.base.MoreObjects.*; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.io.StringReader; -import java.io.StringWriter; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.apache.maven.artifact.Artifact; -import org.apache.maven.artifact.resolver.ArtifactResolutionResult; -import org.apache.maven.artifact.resolver.ArtifactResolver; -import org.apache.maven.artifact.resolver.filter.ArtifactFilter; -import org.apache.maven.artifact.resolver.filter.ExcludesArtifactFilter; -import org.apache.maven.artifact.resolver.filter.ScopeArtifactFilter; -import org.apache.maven.artifact.versioning.DefaultArtifactVersion; -import org.apache.maven.artifact.versioning.InvalidVersionSpecificationException; -import org.apache.maven.artifact.versioning.VersionRange; -import org.apache.maven.execution.MavenSession; -import org.apache.maven.plugin.AbstractMojo; -import org.apache.maven.plugin.MojoExecutionException; -import org.apache.maven.plugin.MojoFailureException; -import org.apache.maven.plugin.antrun.AntrunXmlPlexusConfigurationWriter; -import org.apache.maven.plugins.annotations.Component; -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.plugins.annotations.ResolutionScope; -import org.apache.maven.project.MavenProject; -import org.apache.maven.repository.RepositorySystem; -import org.apache.maven.shared.artifact.filter.PatternIncludesArtifactFilter; -import org.apache.tools.ant.BuildException; -import org.apache.tools.ant.Project; -import org.apache.tools.ant.ProjectHelper; -import org.codehaus.plexus.configuration.PlexusConfiguration; -import org.dom4j.Document; -import org.dom4j.DocumentFactory; -import org.dom4j.Element; -import org.dom4j.io.OutputFormat; -import org.dom4j.io.SAXReader; -import org.dom4j.io.XMLWriter; - -import com.carrotsearch.ant.tasks.junit4.JUnit4; -import com.carrotsearch.ant.tasks.junit4.listeners.TextReport; -import com.carrotsearch.randomizedtesting.RandomizedRunner; -import com.google.common.base.Strings; -import com.google.common.io.Closer; - -/** - * Run tests using a delegation to Randomized - * Testing's JUnit4 ANT task. - */ -@Mojo( - name = "junit4", - defaultPhase = LifecyclePhase.TEST, - threadSafe = true, - requiresProject = true, - requiresDependencyResolution = ResolutionScope.TEST) -public class JUnit4Mojo extends AbstractMojo { - /** An empty String[]. */ - private static final String[] EMPTY_STRING_ARRAY = new String [] {}; - - /** An empty Map. */ - private static final Map EMPTY_STRING_STRING_MAP = Collections.emptyMap(); - - /** Default target in the generated ANT file. */ - private static final String DEFAULT_TARGET = "__default__"; - - /** - * The Maven project object - */ - @Parameter( - property = "project", - readonly = true, - required = true) - private MavenProject project; - - /** - * Base directory to invoke slave VMs in. Also note isolateWorkingDirectories - * parameter. - */ - @Parameter( - property = "project.build.directory", - readonly = true, - required = true) - private File dir; - - /** - * The directory to store temporary files in. - */ - @Parameter( - property = "project.build.directory") - private File tempDir; - - /** - * The number of parallel f. Can be set to a constant "max" for the - * number of cores returned from {@link Runtime#availableProcessors()} or - * "auto" for sensible defaults depending on the number of cores. - * The default is a single subprocess. - * - *

Note that this setting forks physical JVM processes so it multiplies the - * requirements for heap memory, IO, etc. - */ - @Parameter(defaultValue = "1") - private String parallelism = JUnit4.DEFAULT_PARALLELISM; - - /** - * Property to set to "true" if there is a failure in a test. The use of this - * property is discouraged in Maven (builds should be declarative). - */ - @Parameter - private String failureProperty; - - /** - * Initial random seed used for shuffling test suites and other sources - * of pseudo-randomness. If not set, any random value is set. - * - *

The seed's format is compatible with {@link RandomizedRunner} so that - * seed can be fixed for suites and methods alike. Unless the global prefix of - * randomized testing properties is changed, the seed can be overridden using "tests.seed" - * property. - */ - @Parameter(property = "tests.seed", defaultValue = "") - private String seed; - - /** - * Predictably shuffle tests order after balancing. This will help in spreading - * lighter and heavier tests over a single slave's execution timeline while - * still keeping the same tests order depending on the seed. - */ - @Parameter(defaultValue = "true") - private boolean shuffleOnSlave = JUnit4.DEFAULT_SHUFFLE_ON_SLAVE; - - /** - * Prints the summary of all executed, ignored etc. tests at the end. - */ - @Parameter(defaultValue = "true") - private boolean printSummary = JUnit4.DEFAULT_PRINT_SUMMARY; - - /** - * Stop the build process if there were failures or errors during test execution. - */ - @Parameter(defaultValue = "true") - private boolean haltOnFailure = JUnit4.DEFAULT_HALT_ON_FAILURE; - - /** - * If set to true each forked JVM gets a separate working directory - * under whatever is set in dir. The directory naming for each JVM - * follows: "Jnum", where num is the forked JVM's number. - * Directories are created automatically and removed unless leaveTemporary - * is set to true. - */ - @Parameter(defaultValue = "true") - private boolean isolateWorkingDirectories = JUnit4.DEFAULT_ISOLATE_WORKING_DIRECTORIES; - - /** - * Sets the action performed when current work directory for a forked JVM is not empty - * and isolateWorkingDirectories is set to true. - */ - @Parameter(defaultValue = "fail") - private String onNonEmptyWorkDirectory = JUnit4.DEFAULT_NON_EMPTY_WORKDIR_ACTION.name(); - - /** - * If set to true, any sysout and syserr calls will be written to original - * output and error streams (and in effect will appear as "jvm output". By default - * sysout and syserrs are captured and proxied to the event stream to be synchronized - * with other test events but occasionally one may want to synchronize them with direct - * JVM output (to synchronize with compiler output or GC output for example). - */ - @Parameter(defaultValue = "false") - private boolean sysouts = JUnit4.DEFAULT_SYSOUTS; - - /** - * Specifies the ratio of suites moved to dynamic assignment list. A dynamic - * assignment list dispatches suites to the first idle slave JVM. Theoretically - * this is an optimal strategy, but it is usually better to have some static assignments - * to avoid communication costs. - * - *

A ratio of 0 means only static assignments are used. A ratio of 1 means - * only dynamic assignments are used. - * - *

The list of dynamic assignments is sorted by decreasing cost (always) and - * is inherently prone to race conditions in distributing suites. Should there - * be an error based on suite-dependency it will not be directly repeatable. In such - * case use the per-slave-jvm list of suites file dumped to disk for each slave JVM. - * (see leaveTemporary parameter). - */ - @Parameter(defaultValue = "0.25") - private float dynamicAssignmentRatio = JUnit4.DEFAULT_DYNAMIC_ASSIGNMENT_RATIO; - - /** - * Set the maximum memory to be used by all forked JVMs. The value as - * defined by -mx or -Xmx in the java - * command line options. - */ - @Parameter - private String maxMemory; - - /** - * Set to true to leave temporary files for diagnostics. - */ - @Parameter - private boolean leaveTemporary; - - /** - * Add an additional argument to any forked JVM. - */ - @Parameter - private String [] jvmArgs; - - /** - * Arbitrary JVM options to set on the command line. - */ - @Parameter(property = "argLine") - private String argLine; - - /** - * Adds a system property to any forked JVM. - */ - @Parameter - private Map systemProperties; - - /** - * Adds an environment variable to any forked JVM. - */ - @Parameter - private Map environmentVariables; - - /** - * The command used to invoke the Java Virtual Machine, default is 'java'. The - * command is resolved by java.lang.Runtime.exec(). - */ - @Parameter(defaultValue = "java") - private String jvm; - - /** - * The directory containing generated test classes of the project being - * tested. This will be included at the beginning of the test classpath. - */ - @Parameter(defaultValue = "${project.build.testOutputDirectory}") - private File testClassesDirectory; - - /** - * The directory containing generated classes of the project being - * tested. This will be included after testClassesDirectory. - */ - @Parameter(defaultValue = "${project.build.outputDirectory}") - private File classesDirectory; - - /** - * A list of <include> elements specifying the tests (by pattern) that should be included in testing. When not - * specified defaults to: - *

-   * <include>**/*Test.class</include>
-   * <include>**/Test*.class</include>
-   * 
- * Note that this may result in nested classes being included for tests. Use proper exclusion patterns. - */ - @Parameter - private List includes; - - /** - * A list of <exclude> elements specifying the tests (by pattern) that should be excluded in testing. When not - * specified defaults to: - *
-   * <exclude>**/*$*.class</exclude>
-   * 
- * This patterns excludes any nested classes that might otherwise be included. - */ - @Parameter - private List excludes; - - /** - * This parameter adds a listener emitting surefire-compatible XMLs if no other listeners - * are added. If there are any configured listeners, this parameter is omitted (you can - * add a maven-compatible listener manually). - */ - @Parameter(defaultValue = "${project.build.directory}/surefire-reports") - private File surefireReportsDirectory; - - /** - * Specifies the name of the JUnit artifact used for running tests. JUnit dependency - * must be in at least version 4.10. - */ - @Parameter( - property = "junitArtifactName", - defaultValue = "junit:junit") - private String junitArtifactName; - - /** - * What should be done on unexpected JVM output? JVM may write directly to the - * original descriptors, bypassing redirections of System.out and System.err. Typically, - * these messages will be important and should fail the build (permgen space exceeded, - * compiler errors, crash dumps). However, certain legitimate logs (gc activity, class loading - * logs) are also printed to these streams so sometimes the output can be ignored. - * - *

Allowed values (any comma-delimited combination of): ignore, pipe, warn, fail. - */ - @Parameter( - property = "jvmOutputAction", - defaultValue = "pipe,warn") - private String jvmOutputAction; - - /** - * Allows or disallow duplicate suite names in resource collections. By default this option - * is true because certain ANT-compatible report types (like XML reports) - * will have a problem with duplicate suite names (will overwrite files). - */ - @Parameter(defaultValue = "" + JUnit4.DEFAULT_UNIQUE_SUITE_NAME) - private boolean uniqueSuiteNames = JUnit4.DEFAULT_UNIQUE_SUITE_NAME; - - /** - * Raw listeners configuration. Same XML as for ANT. - */ - @Parameter - private PlexusConfiguration listeners; - - /** - * Raw runListeners configuration. Same XML as for ANT. - */ - @Parameter - private PlexusConfiguration runListeners; - - - /** - * Raw assertions configuration. Same XML as for ANT. - */ - @Parameter - private PlexusConfiguration assertions; - - /** - * Raw balancers configuration. Same XML as for ANT. - */ - @Parameter - private PlexusConfiguration balancers; - - /** - * Raw section to copy/paste into ANT-driver. - */ - @Parameter - private PlexusConfiguration verbatim; - - /** - * Sets the heartbeat used to detect inactive/ hung forked tests (JVMs) to the given - * number of seconds. The heartbeat detects - * no-event intervals and will report them to listeners. Notably, {@link TextReport} report will - * emit heartbeat information (to a file or console). - * - *

Setting the heartbeat to zero means no detection. - */ - @Parameter(defaultValue = "0") - private long heartbeat; - - /** - * Set this to "true" to skip running tests, but still compile them. Its use - * is NOT RECOMMENDED, but quite convenient on occasion. - */ - @Parameter( - property = "skipTests", - defaultValue = "false") - private boolean skipTests; - - /** - * Project packaging mode to skip POM-projects - */ - @Parameter( - defaultValue = "${project.packaging}", - readonly = true) - private String packaging; - - /** - * List of dependencies to exclude from the test classpath. Each dependency - * string must follow the format - * groupId:artifactId. For example: org.acme:project-a - * - *

This is modeled after surefire. An excluded dependency does not mean its - * transitive dependencies will also be excluded. - */ - @Parameter - private List classpathDependencyExcludes; - - /** - * A dependency scope to exclude from the test classpath. The scope can be one of the following scopes: - *

- *

    - *
  • compile - system, provided, compile - *
  • runtime - compile, runtime - *
  • test - system, provided, compile, runtime, test - *
- */ - @Parameter(defaultValue = "") - private String classpathDependencyScopeExclude; - - /** - * Additional elements to be appended to the classpath. - */ - @Parameter - private List additionalClasspathElements; - - /** - * Initializes custom prefix for all junit4 properties. This must be consistent - * across all junit4 invocations if done from the same classpath. Use only when REALLY needed. - */ - @Parameter() - private String prefix; - - /** - * Enables a debug stream from each forked JVM. This will create an additional file - * next to each events file. For debugging the framework only, not a general-purpose setting. - */ - @Parameter() - private Boolean debugStream; - - /** - * Set new environment for the forked process? - */ - @Parameter() - private Boolean newEnvironment; - - /** - * What to do when no tests were executed (all tests were ignored)? Possible values: - * ignore, fail, warn. - */ - @Parameter(defaultValue = "ignore") - private String ifNoTests; - - /** - * Sets the property prefix to which test statistics are saved. - */ - @Parameter() - private String statsPropertyPrefix; - - /** - * Map of plugin artifacts. - */ - @Parameter( - defaultValue = "${plugin.artifactMap}", - required = true, - readonly = true) - private Map pluginArtifactMap; - - /** - * Map of project artifacts. - */ - @Parameter( - defaultValue = "${project.artifactMap}", - required = true, - readonly = true) - private Map projectArtifactMap; - - /** - * The current build session instance. - */ - @Parameter( - property = "session", - required = true, - readonly = true) - private MavenSession session; - - /** - * Repository. - * - * @component - * @readonly - * @required - */ - @Component - private RepositorySystem repositorySystem; - - /** - * For retrieval of artifact's metadata. - */ - @SuppressWarnings("deprecation") - @Component - private org.apache.maven.artifact.metadata.ArtifactMetadataSource metadataSource; - - /** - * - */ - @Component - private ArtifactResolver resolver; - - - /** - * Run the mojo. - */ - @Override - public void execute() throws MojoExecutionException, MojoFailureException { - if ("pom".equals(packaging)) { - getLog().debug("Skipping execution for packaging \"" + packaging + "\""); - return; - } - - // Check directory existence first. - if (!dir.isDirectory() || - !tempDir.isDirectory()) { - getLog().warn("Location does not exist or is not a directory: " + dir.getAbsolutePath()); - skipTests = true; - } - - if (skipTests) { - return; - } - - validateParameters(); - - // Ant project setup. - final Project antProject = new Project(); - antProject.init(); - antProject.setBaseDir(dir); - antProject.addBuildListener(new MavenListenerAdapter(getLog())); - - // Generate JUnit4 ANT task model and generate a synthetic ANT file. - Document doc = DocumentFactory.getInstance().createDocument(); - try { - populateJUnitElement(createDocumentSkeleton(doc)); - File tempAntFile = createTemporaryAntFile(doc); - - ProjectHelper.configureProject(antProject, tempAntFile); - try { - antProject.executeTarget(DEFAULT_TARGET); - } finally { - if (!leaveTemporary) { - tempAntFile.delete(); - } - } - } catch (IOException e) { - throw new MojoExecutionException("An I/O error occurred: " + e.getMessage(), e); - } catch (BuildException e) { - throw new MojoExecutionException(e.getMessage(), e.getCause()); - } catch (Throwable t) { - throw new RuntimeException(t); - } - } - - /** - * Initial validation of input parameters and configuration. - */ - private void validateParameters() throws MojoExecutionException { - // Check for junit dependency on project level. - Artifact junitArtifact = projectArtifactMap.get(junitArtifactName); - - if (junitArtifact == null) { - throw new MojoExecutionException("Missing JUnit artifact in project dependencies: " - + junitArtifactName); - } - checkVersion("JUnit", "[4.10,)", junitArtifact); - - // Fill in complex defaults if not given. - if (includes == null || includes.isEmpty()) { - includes = Arrays.asList( - "**/Test*.class", "**/*Test.class"); - } - if (excludes == null || excludes.isEmpty()) { - excludes = Arrays.asList( - "**/*$*.class"); - } - } - - /** - * Ensure artifactName matches version versionSpec. - */ - private void checkVersion(String artifactName, String versionSpec, Artifact artifact) - throws MojoExecutionException { - VersionRange range; - try { - range = VersionRange.createFromVersionSpec(versionSpec); - if (!range.containsVersion(new DefaultArtifactVersion(artifact.getVersion()))) - { - throw new MojoExecutionException( - "JUnit4 plugin requires " + artifactName + " in version " + - versionSpec + " among project dependencies, you declared: " - + artifact.getVersion()); - } - } catch (InvalidVersionSpecificationException e) { - throw new RuntimeException(e); - } - } - - /** - * Populate junit4 task with attributes and values. - */ - private void populateJUnitElement(Element junit4) { - // Attributes. - if (dir != null) junit4.addAttribute("dir", dir.getAbsolutePath()); - if (tempDir != null) junit4.addAttribute("tempDir", tempDir.getAbsolutePath()); - if (parallelism != null) junit4.addAttribute("parallelism", parallelism); - if (failureProperty != null) junit4.addAttribute("failureProperty", failureProperty); - if (seed != null) junit4.addAttribute("seed", seed); - if (jvm != null) junit4.addAttribute("jvm", jvm); - if (maxMemory != null) junit4.addAttribute("maxMemory", maxMemory); - if (jvmOutputAction != null) junit4.addAttribute("jvmOutputAction", jvmOutputAction); - if (heartbeat != 0) junit4.addAttribute("heartbeat", Long.toString(heartbeat)); - if (prefix != null) junit4.addAttribute("prefix", prefix); - if (debugStream != null) junit4.addAttribute("debugStream", debugStream.toString()); - if (newEnvironment != null) junit4.addAttribute("newEnvironment", newEnvironment.toString()); - if (ifNoTests != null) junit4.addAttribute("ifNoTests", ifNoTests); - if (statsPropertyPrefix != null) junit4.addAttribute("statsPropertyPrefix", statsPropertyPrefix); - if (onNonEmptyWorkDirectory != null) junit4.addAttribute("onNonEmptyWorkDirectory", onNonEmptyWorkDirectory); - - junit4.addAttribute("shuffleOnSlave", Boolean.toString(shuffleOnSlave)); - junit4.addAttribute("printSummary", Boolean.toString(printSummary)); - junit4.addAttribute("isolateWorkingDirectories", Boolean.toString(isolateWorkingDirectories)); - junit4.addAttribute("haltOnFailure", Boolean.toString(haltOnFailure)); - junit4.addAttribute("leaveTemporary", Boolean.toString(leaveTemporary)); - junit4.addAttribute("dynamicAssignmentRatio", Float.toString(dynamicAssignmentRatio)); - junit4.addAttribute("sysouts", Boolean.toString(sysouts)); - junit4.addAttribute("uniqueSuiteNames", Boolean.toString(uniqueSuiteNames)); - - - // JVM args. - for (String jvmArg : firstNonNull(jvmArgs, EMPTY_STRING_ARRAY)) { - junit4.addElement("jvmarg").addAttribute("value", jvmArg); - } - - if (argLine != null) { - junit4.addElement("jvmarg").addAttribute("line", argLine); - } - - // System properties - for (Map.Entry e : - firstNonNull(systemProperties, EMPTY_STRING_STRING_MAP).entrySet()) { - Element sysproperty = junit4.addElement("sysproperty"); - sysproperty.addAttribute("key", Strings.nullToEmpty(e.getKey())); - sysproperty.addAttribute("value", Strings.nullToEmpty(e.getValue())); - } - - // Environment variables. - for (Map.Entry e : - firstNonNull(environmentVariables, EMPTY_STRING_STRING_MAP).entrySet()) { - Element sysproperty = junit4.addElement("env"); - sysproperty.addAttribute("key", Strings.nullToEmpty(e.getKey())); - sysproperty.addAttribute("value", Strings.nullToEmpty(e.getValue())); - } - - // Tests input. - setupTestInput(junit4); - - // Tests classpath - setupTestClasspath(junit4); - - // Copy over listeners configuration. - if (listeners != null) { - appendRawXml(listeners, junit4); - } else { - // Add a console listener and a surefire-like XML listener. - Element listenersElement = junit4.addElement("listeners"); - - Element surefireReport = listenersElement.addElement("report-ant-xml"); - surefireReport.addAttribute("dir", surefireReportsDirectory.getAbsolutePath()); - surefireReport.addAttribute("mavenExtensions", "true"); - - Element consoleReport = listenersElement.addElement("report-text"); - consoleReport.addAttribute("showThrowable", "true"); - consoleReport.addAttribute("showStackTraces", "true"); - consoleReport.addAttribute("showOutput", "never"); - - consoleReport.addAttribute("showStatusOk", "false"); - consoleReport.addAttribute("showStatusError", "true"); - consoleReport.addAttribute("showStatusFailure", "true"); - consoleReport.addAttribute("showStatusIgnored", "false"); - - consoleReport.addAttribute("showSuiteSummary", "true"); - } - - // Copy over runlisteners - appendRawXml(runListeners, junit4); - - // Copy over assertions - appendRawXml(assertions, junit4); - - // Copy over balancers - appendRawXml(balancers, junit4); - - // Copy over verbatim section. - if (verbatim != null) { - for (PlexusConfiguration c : verbatim.getChildren()) { - appendRawXml(c, junit4); - } - } - } - - /** - * Append raw XML configuration. - */ - private void appendRawXml(PlexusConfiguration config, Element elem) { - try { - if (config == null) { - return; - } - - StringWriter writer = new StringWriter(); - AntrunXmlPlexusConfigurationWriter xmlWriter = new AntrunXmlPlexusConfigurationWriter(); - xmlWriter.write(config, writer); - Element root = new SAXReader().read( - new StringReader(writer.toString())).getRootElement(); - root.detach(); - elem.add(root); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - /** - * Create a temporary ANT file for executing JUnit4 ANT task. - */ - private File createTemporaryAntFile(Document doc) throws IOException { - Closer closer = Closer.create(); - try { - File antFile = File.createTempFile("junit4-ant-", ".xml", dir); - OutputStream os = closer.register(new FileOutputStream(antFile)); - XMLWriter xmlWriter = new XMLWriter(os, OutputFormat.createPrettyPrint()); - xmlWriter.write(doc); - return antFile; - } catch (Throwable t) { - throw closer.rethrow(t); - } finally { - closer.close(); - } - } - - /** - * Creates a skeleton of a single-target ANT build file with JUnit4 task inside. - */ - private Element createDocumentSkeleton(Document doc) { - Element project = doc.addElement("project"); - project.addAttribute("name", "junit4-maven-synthetic"); - project.addAttribute("default", DEFAULT_TARGET); - - project.addComment("Define JUnit4 task and data types."); - Element taskdef = project.addElement("taskdef"); - taskdef.addAttribute("resource", JUnit4.ANTLIB_RESOURCE_NAME); - addArtifactClassPath( - taskdef.addElement("classpath"), - pluginArtifactMap.get("com.carrotsearch.randomizedtesting:junit4-ant")); - addArtifactClassPath( - taskdef.addElement("classpath"), - projectArtifactMap.get("junit:junit")); - - project.addComment("Invoke JUnit4 task."); - Element target = project.addElement("target"); - target.addAttribute("name", DEFAULT_TARGET); - - Element junit4 = target.addElement("junit4"); - return junit4; - } - - /** - * Append classpath elements of the given artefact to classpath. - */ - private void addArtifactClassPath(Element cp, Artifact artifact) { - ArtifactResolutionResult result = resolveArtifact(artifact); - if (!result.isSuccess()) { - throw new RuntimeException("Could not resolve: " + artifact.toString()); - } - - for (Artifact a : result.getArtifacts()) { - cp.addElement("pathelement").addAttribute( - "location", a.getFile().getAbsolutePath()); - } - } - - /** - * Resolve a given artifact given exclusion list. (copied from surefire). - */ - @SuppressWarnings({"deprecation"}) - private ArtifactResolutionResult resolveArtifact(Artifact artifact, Artifact... filtered) { - final ArtifactFilter filter; - if (filtered.length > 0) { - List exclusions = new ArrayList<>(filtered.length); - for (Artifact filteredArtifact : filtered) { - exclusions.add(filteredArtifact.getGroupId() + ":" - + filteredArtifact.getArtifactId()); - } - filter = new ExcludesArtifactFilter(exclusions); - } else { - filter = null; - } - - Artifact originatingArtifact = repositorySystem.createArtifact("dummy", "dummy", "1.0", "jar"); - try { - return resolver.resolveTransitively( - Collections.singleton( artifact ), - originatingArtifact, - session.getLocalRepository(), - project.getPluginArtifactRepositories(), - metadataSource, filter); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - /** - * Setup the classpath used for tests. - */ - private void setupTestClasspath(Element junit4) { - junit4.addComment("Runtime classpath."); - Element cp = junit4.addElement("classpath"); - - // Test classes. - cp.addComment("Test classes directory."); - cp.addElement("pathelement").addAttribute("location", testClassesDirectory.getAbsolutePath()); - - // Classes directory. - cp.addComment("Test classes directory."); - cp.addElement("pathelement").addAttribute("location", classesDirectory.getAbsolutePath()); - - // Project dependencies. - cp.addComment("Project dependencies."); - - Set classpathArtifacts = (Set) project.getArtifacts(); - - if (!Strings.isNullOrEmpty(classpathDependencyScopeExclude)) { - classpathArtifacts = filterArtifacts(cp, classpathArtifacts, - new ScopeArtifactFilter(classpathDependencyScopeExclude)); - } - - if (classpathDependencyExcludes != null && !classpathDependencyExcludes.isEmpty()) { - classpathArtifacts = filterArtifacts(cp, classpathArtifacts, - new PatternIncludesArtifactFilter(classpathDependencyExcludes)); - } - - for (Artifact artifact : classpathArtifacts) { - if (artifact.getArtifactHandler().isAddedToClasspath()) { - File file = artifact.getFile(); - if (file != null) { - cp.addComment("Dependency artifact: " + artifact.getId()); - cp.addElement("pathelement").addAttribute("location", - file.getAbsolutePath()); - } - } - } - - // Additional dependencies. - cp.addComment("Additional classpath elements."); - if (additionalClasspathElements != null && !additionalClasspathElements.isEmpty()) { - for (String classpathElement : additionalClasspathElements) { - if (!Strings.isNullOrEmpty(classpathElement)) { - cp.addElement("pathelement").addAttribute("location", classpathElement); - } - } - } - } - - /** - * Return a new set containing only the artifacts accepted by the given filter. - */ - private Set filterArtifacts(Element cp, Set artifacts, ArtifactFilter filter) { - Set filteredArtifacts = new LinkedHashSet<>(); - for (Artifact artifact : artifacts) { - if (!filter.include(artifact)) { - filteredArtifacts.add(artifact); - } else { - cp.addComment("Filtered out artifact: " + artifact.getId() + ", location: " - + artifact.getFile()); - } - } - return filteredArtifacts; - } - - /** - * Setup the input test suites (classes locations and patterns). - */ - private void setupTestInput(Element junit4) { - Element patternSet = DocumentFactory.getInstance().createElement("patternset"); - for (String includePattern : includes) { - patternSet.addElement("include").addAttribute("name", includePattern); - } - for (String excludePattern : excludes) { - patternSet.addElement("exclude").addAttribute("name", excludePattern); - } - - if (testClassesDirectory != null) { - junit4.addComment("Test classes search paths and patterns."); - Element fs = junit4.addElement("fileset"); - fs.addAttribute("dir", testClassesDirectory.getAbsolutePath()); - fs.addAttribute("erroronmissingdir", "false"); - fs.add(patternSet.createCopy()); - } - } -} diff --git a/junit4-maven-plugin/src/main/java/com/carrotsearch/maven/plugins/junit4/MavenListenerAdapter.java b/junit4-maven-plugin/src/main/java/com/carrotsearch/maven/plugins/junit4/MavenListenerAdapter.java deleted file mode 100644 index 776f44fb..00000000 --- a/junit4-maven-plugin/src/main/java/com/carrotsearch/maven/plugins/junit4/MavenListenerAdapter.java +++ /dev/null @@ -1,73 +0,0 @@ -package com.carrotsearch.maven.plugins.junit4; - -import org.apache.maven.plugin.logging.Log; -import org.apache.tools.ant.*; - -/** - * An adapter to maven logging system from ANT {@link BuildListener}. - */ -final class MavenListenerAdapter implements BuildListener { - private final Log log; - - public MavenListenerAdapter(Log log) { - this.log = log; - } - - @Override - public void messageLogged(BuildEvent event) { - final Throwable exception = event.getException(); - final String message = event.getMessage(); - switch (event.getPriority()) { - case Project.MSG_DEBUG: - case Project.MSG_VERBOSE: - if (exception != null) { - log.debug(message, exception); - } else { - log.debug(message); - } - break; - - case Project.MSG_INFO: - if (exception != null) { - log.info(message, exception); - } else { - log.info(message); - } - break; - - case Project.MSG_WARN: - if (exception != null) { - log.warn(message, exception); - } else { - log.warn(message); - } - break; - - case Project.MSG_ERR: - if (exception != null) { - log.error(message, exception); - } else { - log.error(message); - } - break; - } - } - - @Override - public void buildFinished(BuildEvent event) {} - - @Override - public void buildStarted(BuildEvent event) {} - - @Override - public void targetFinished(BuildEvent event) {} - - @Override - public void targetStarted(BuildEvent event) {} - - @Override - public void taskFinished(BuildEvent event) {} - - @Override - public void taskStarted(BuildEvent event) {} -} diff --git a/junit4-maven-plugin/src/site/site.xml b/junit4-maven-plugin/src/site/site.xml deleted file mode 100644 index 6c9a4225..00000000 --- a/junit4-maven-plugin/src/site/site.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - diff --git a/pom.xml b/pom.xml deleted file mode 100644 index cd128d90..00000000 --- a/pom.xml +++ /dev/null @@ -1,692 +0,0 @@ - - - - - 4.0.0 - - - ${minimum.maven.version} - - - com.carrotsearch.randomizedtesting - randomizedtesting-parent - 2.7.9-SNAPSHOT - pom - - RandomizedTesting Parent POM - https://github.com/randomizedtesting/randomizedtesting - JUnit test runner and plugins for running JUnit tests with pseudo-randomness. - 2011 - - - Carrot Search s.c. - http://carrotsearch.com - - - - - Carrot Search s.c. - info@carrotsearch.com - Carrot Search s.c. - http://www.carrotsearch.com - - - - - - The Apache Software License, Version 2.0 - http://www.apache.org/licenses/LICENSE-2.0.txt - repo - - - - - - site - scm:git:git@github.com:randomizedtesting/randomizedtesting.git - - - - - scm:git:git@github.com:randomizedtesting/randomizedtesting.git - scm:git:git@github.com:randomizedtesting/randomizedtesting.git - git@github.com:randomizedtesting/randomizedtesting.git - - - - 3.2.5 - - UTF-8 - UTF-8 - - 1.8 - 1.8 - - - - 4.13.1 - 1.9.15 - 2.2.0 - - 1.8 - 3.0.0-M1 - 3.0.0 - 3.0.0 - 3.0.0-M1 - 2.5 - - - - randomized-runner - junit4-ant - junit4-maven-plugin - junit4-maven-plugin-tests - examples/maven - examples/ant - examples/security-manager - - - - - - org.apache.ant - ant - ${version.ant} - - - - org.apache.ant - ant-junit - ${version.ant} - - - - org.dom4j - dom4j - 2.1.3 - - - - com.google.guava - guava - 25.0-jre - - - jsr305 - com.google.code.findbugs - - - com.google.errorprone - error_prone_annotations - - - com.google.j2objc - j2objc-annotations - - - org.codehaus.mojo - animal-sniffer-annotations - - - - - - org.ow2.asm - asm - 8.0.1 - - - - com.carrotsearch.thirdparty - simple-xml-safe - 2.7.1 - - - - junit - junit - ${version.junit} - - - - org.assertj - assertj-core - ${version.assertj} - test - - - - - - - - org.apache.maven.plugins - maven-site-plugin - - - attach-descriptor - - attach-descriptor - - - - - - - - - - org.apache.maven.plugins - maven-site-plugin - 3.5.1 - - - - org.apache.maven.plugins - maven-clean-plugin - ${version.maven-clean-plugin} - - false - true - - - ${project.build.directory} - - eclipse/** - idea/** - - - - - - - - org.apache.maven.plugins - maven-deploy-plugin - 2.8.2 - - - - org.apache.maven.plugins - maven-plugin-plugin - 3.5 - - - - org.apache.maven.plugins - maven-source-plugin - 3.0.1 - - - - org.apache.maven.plugins - maven-assembly-plugin - 2.6 - - - - org.apache.maven.plugins - maven-jar-plugin - 3.0.2 - - - - org.apache.maven.plugins - maven-install-plugin - 2.5.2 - - - - org.apache.maven.plugins - maven-resources-plugin - 3.0.1 - - - - org.apache.maven.plugins - maven-enforcer-plugin - ${version.maven-enforcer-plugin} - - - - org.apache.maven.plugins - maven-dependency-plugin - 2.10 - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.5.1 - - - - org.apache.maven.plugins - maven-gpg-plugin - 1.6 - - - - org.apache.maven.plugins - maven-surefire-plugin - ${version.maven-surefire-plugin} - - - - org.apache.maven.plugins - maven-antrun-plugin - ${version.maven-antrun-plugin} - - - - org.apache.ant - ant - ${version.ant} - - - org.apache.ant - ant-junit - ${version.ant} - - - - - - org.apache.felix - maven-bundle-plugin - 3.2.0 - - - - org.apache.maven.plugins - maven-project-info-reports-plugin - 2.9 - - - - org.apache.maven.plugins - maven-javadoc-plugin - ${version.maven-javadoc-plugin} - - - - org.apache.maven.plugins - maven-invoker-plugin - 2.0.0 - - - - de.thetaphi - forbiddenapis - ${version.forbiddenapis} - - - - check-forbidden-apis - verify - - check - - - 1.8 - false - false - true - - - **.SuppressForbidden - - - jdk-unsafe - jdk-deprecated - jdk-system-out - jdk-non-portable - - - - - - - - - - - - - - - quick - - true - true - - - - - profile.ide.eclipse-m2e - - - - m2e.version - - - - - - - - - - org.eclipse.m2e - lifecycle-mapping - 1.0.0 - - - - - - org.apache.felix - maven-bundle-plugin - [1.0.0,) - - manifest - - - - - - - - - - de.thetaphi - forbiddenapis - [1.0.0,) - - testCheck - check - - - - - - - - - - org.apache.maven.plugins - maven-plugin-plugin - [3.4,) - - descriptor - helpmojo - - - - - - - - - - - - - org.apache.maven.plugins - maven-site-plugin - - true - UTF-8 - UTF-8 - - - - - org.apache.maven.plugins - maven-scm-publish-plugin - 1.1 - - gh-pages - - - - - - - - - eclipse - - compile antrun:run - - - - maven-antrun-plugin - ${version.maven-antrun-plugin} - - - default-cli - none - false - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - run - - - - - - org.apache.ant - ant - ${version.ant} - - - - - - - - - - sonatype-oss-release - - - - sonatype-nexus-snapshots - Sonatype Nexus Snapshots - https://oss.sonatype.org/content/repositories/snapshots - - - sonatype-nexus-staging - Sonatype Nexus Releases - https://oss.sonatype.org/service/local/staging/deploy/maven2/ - - - - - - sonatype-nexus-snapshots - Sonatype Nexus Snapshots - https://oss.sonatype.org/content/repositories/snapshots - - false - - - true - - - - - - - - org.apache.maven.plugins - maven-gpg-plugin - - - **/*.gz - **/*.zip - - - - - - sign - - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - - ${project.build.sourceEncoding} - ${project.name} v${project.version} API Documentation - ${project.name} v${project.version} API Documentation - UTF-8 - false - - - - attach-javadocs - - jar - - - - - - - org.apache.maven.plugins - maven-source-plugin - - true - - - - attach-sources - - jar-no-fork - - - - - - - - - - doclint-java8-disable - - [1.8,) - - - - - org.apache.maven.plugins - maven-javadoc-plugin - - none - - - - - - - - - - - org.apache.maven.plugins - maven-project-info-reports-plugin - - false - - - - - summary - index - dependencies - issue-tracking - scm - plugins - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - - UTF-8 - true - true - - - - non-aggregate - - javadoc - - - - - - maven-plugin-plugin - - - - diff --git a/randomized-runner/pom.xml b/randomized-runner/pom.xml deleted file mode 100644 index 5309d2cc..00000000 --- a/randomized-runner/pom.xml +++ /dev/null @@ -1,76 +0,0 @@ - - 4.0.0 - - - com.carrotsearch.randomizedtesting - randomizedtesting-parent - 2.7.9-SNAPSHOT - ../pom.xml - - - randomizedtesting-runner - RandomizedTesting Randomized Runner - - - - junit - junit - jar - compile - - - - org.assertj - assertj-core - test - - - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - ${version.maven-javadoc-plugin} - - - - RandomizedRunner and RandomizedTest - com.carrotsearch.randomizedtesting* - - - Annotations - com.carrotsearch.randomizedtesting.annotations - - - Listeners, Generators and Validators - com.carrotsearch.randomizedtesting.generators:com.carrotsearch.randomizedtesting.listeners:com.carrotsearch.randomizedtesting.validators - - - - - - - - - - de.thetaphi - forbiddenapis - - - - org.apache.felix - maven-bundle-plugin - - - JavaSE-1.8 - ${project.groupId}.${project.artifactId} - ${project.groupId}.*;version="${project.version}" - - - - - - diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/AnnotatedMethodProvider.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/AnnotatedMethodProvider.java deleted file mode 100644 index 43689522..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/AnnotatedMethodProvider.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import org.junit.Test; - -import java.lang.annotation.Annotation; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Map; - -/** - * Base class for {@link TestMethodProvider}s based on annotations. - */ -public abstract class AnnotatedMethodProvider implements TestMethodProvider { - private final Class annotation; - - public AnnotatedMethodProvider(Class ann) { - this.annotation = ann; - } - - @Override - public Collection getTestMethods(Class suiteClass, ClassModel suiteClassModel) { - // Return all methods annotated with the given annotation. Rely on further validation - // to weed out static or otherwise invalid methods. - Map methods = suiteClassModel.getAnnotatedLeafMethods(annotation); - if (annotation.equals(Test.class)) { - // @Test doesn't have inherited attribute, yet behaves like one. Fix it here by returning most - // specific method with a parent marked @Test - List fixed = new ArrayList(); - for (ClassModel.MethodModel mm : methods.values()) { - // find the most specific method. - ClassModel.MethodModel override; - while ((override = mm.getDown()) != null) { - mm = override; - } - - fixed.add(mm.element); - } - return fixed; - } - return methods.keySet(); - } -} diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/AssertingRandom.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/AssertingRandom.java deleted file mode 100644 index 513e80e5..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/AssertingRandom.java +++ /dev/null @@ -1,180 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import java.lang.ref.WeakReference; -import java.util.Random; - -/** - * A random with a delegate, preventing {@link Random#setSeed(long)} and locked - * to be used by a single thread. - */ -@SuppressWarnings("serial") -public final class AssertingRandom extends Random { - private final Random delegate; - private final WeakReference ownerRef; - private final String ownerName; - private final StackTraceElement[] allocationStack; - - /** - * Track out-of-context use of this {@link Random} instance. This introduces memory - * barriers and scheduling side-effects but there's no other way to do it in any other - * way and sharing randoms across threads or test cases is very bad and worth tracking. - */ - private volatile boolean valid = true; - - /** - * Enable paranoid mode when assertions are enabled. - */ - private final static boolean assertionsEnabled = AssertingRandom.class.desiredAssertionStatus(); - - /** - * Creates an instance to be used by owner thread and delegating - * to delegate until {@link #destroy()}ed. - */ - public AssertingRandom(Thread owner, Random delegate) { - // Must be here, the only Random constructor. Has side-effects on setSeed, see below. - super(0); - - this.delegate = delegate; - this.ownerRef = new WeakReference(owner); - this.ownerName = owner.toString(); - this.allocationStack = Thread.currentThread().getStackTrace(); - } - - @Override - protected int next(int bits) { - throw new RuntimeException("Shouldn't be reachable."); - } - - @Override - public boolean nextBoolean() { - checkValid(); - return delegate.nextBoolean(); - } - - @Override - public void nextBytes(byte[] bytes) { - checkValid(); - delegate.nextBytes(bytes); - } - - @Override - public double nextDouble() { - checkValid(); - return delegate.nextDouble(); - } - - @Override - public float nextFloat() { - checkValid(); - return delegate.nextFloat(); - } - - @Override - public double nextGaussian() { - checkValid(); - return delegate.nextGaussian(); - } - - @Override - public int nextInt() { - checkValid(); - return delegate.nextInt(); - } - - @Override - public int nextInt(int n) { - checkValid(); - return delegate.nextInt(n); - } - - @Override - public long nextLong() { - checkValid(); - return delegate.nextLong(); - } - - @Override - public void setSeed(long seed) { - // This is an interesting case of observing uninitialized object from an instance method - // (this method is called from the superclass constructor). - if (seed == 0 && delegate == null) { - return; - } - - throw noSetSeed(); - } - - @Override - public String toString() { - checkValid(); - return delegate.toString(); - } - - @Override - public boolean equals(Object obj) { - checkValid(); - return delegate.equals(obj); - } - - @Override - public int hashCode() { - checkValid(); - return delegate.hashCode(); - } - - /** - * This object will no longer be usable after this method is called. - */ - public void destroy() { - this.valid = false; - } - - /* */ - private final void checkValid() { - // Fastpath if assertions are disabled. - if (!isVerifying()) { - return; - } - - if (!valid) { - throw new IllegalStateException("This Random instance has been invalidated and " + - "is probably used out of its allowed context (test or suite)."); - } - - final Thread owner = ownerRef.get(); - if (owner == null || Thread.currentThread() != owner) { - Throwable allocationEx = new StackTraceHolder("Original allocation stack for this Random (" + - "allocated by " + ownerName + ")"); - allocationEx.setStackTrace(allocationStack); - throw new IllegalStateException( - "This Random was created for/by another thread (" + ownerName + ")." + - " Random instances must not be shared (acquire per-thread). Current thread: " + - Thread.currentThread().toString(), allocationEx); - } - } - - @Override - protected Object clone() throws CloneNotSupportedException { - checkValid(); - throw new CloneNotSupportedException("Don't clone test Randoms."); - } - - /** - * @return Return true if this class is verifying sharing and lifecycle assertions. - * @see "https://github.com/randomizedtesting/randomizedtesting/issues/234" - */ - public static boolean isVerifying() { - return assertionsEnabled; - } - - static RuntimeException noSetSeed() { - return new RuntimeException( - RandomizedRunner.class.getSimpleName() + - " prevents changing the seed of its random generators to assure repeatability" + - " of tests. If you need a mutable instance of Random, create a new (local) instance," + - " preferably with the initial seed aquired from this Random instance."); - } - - // Overriding this has side effects on the GC; let's not be paranoid. - /* protected void finalize() throws Throwable { super.finalize(); } */ -} diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/ClassGlobFilter.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/ClassGlobFilter.java deleted file mode 100644 index 62b003b4..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/ClassGlobFilter.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import org.junit.runner.Description; - -/** - * A filter for {@link Description#getClassName()}. - */ -public class ClassGlobFilter extends GlobFilter { - public ClassGlobFilter(String globPattern) { - super(globPattern); - } - - @Override - public boolean shouldRun(Description description) { - String className = description.getClassName(); - return className == null || globMatches(className); - } - - @Override - public String describe() { - return "Class matches: " + globPattern; - } -} diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/ClassModel.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/ClassModel.java deleted file mode 100644 index 45944685..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/ClassModel.java +++ /dev/null @@ -1,294 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import java.lang.annotation.Annotation; -import java.lang.reflect.Field; -import java.lang.reflect.Member; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -/** - * Class model for a test suite. Builds relationship (overrides/ shadows) links - * for methods and fields. - */ -public final class ClassModel { - static final Comparator methodSorter = new Comparator() { - @Override - public int compare(Method o1, Method o2) { - return o1.toGenericString().compareTo( - o2.toGenericString()); - } - }; - - static final Comparator fieldSorter = new Comparator() { - @Override - public int compare(Field o1, Field o2) { - return o1.toGenericString().compareTo( - o2.toGenericString()); - } - }; - - private final LinkedHashMap methods; - private final LinkedHashMap fields; - - public static enum Scope { - PUBLIC, - PROTECTED, - PACKAGE, - PRIVATE - } - - abstract static class ClassElement> { - private final int modifiers; - private final Scope scope; - - public final T element; - private E up; - private E down; - - public ClassElement(T element) { - this.element = element; - this.modifiers = element.getModifiers(); - this.scope = getAccessScope(modifiers); - } - - private static Scope getAccessScope(int modifiers) { - if (Modifier.isPublic(modifiers)) return Scope.PUBLIC; - if (Modifier.isProtected(modifiers)) return Scope.PROTECTED; - if (Modifier.isPrivate(modifiers)) return Scope.PRIVATE; - return Scope.PACKAGE; - } - - void setDown(E down) { assert this.down == null; this.down = down; } - void setUp(E up) { assert this.up == null; this.up = up; } - - public E getDown() { return down; } - public E getUp() { return up; } - public Scope getAccessScope() { return scope; } - - abstract boolean overridesOrShadows(ClassElement sub); - } - - private static abstract class ModelBuilder> { - final LinkedHashMap build(Class clazz) { - final LinkedHashMap elements = new LinkedHashMap(); - final Map> tops = new HashMap>(); - for (Class c = clazz; c != Object.class; c = c.getSuperclass()) { - for (T_MEMBER m : members(c)) { - final T_MODEL model = model(m); - if (elements.put(m, model) != null) { - throw new RuntimeException("Class element should not have duplicates in superclasses: " + m); - } - - // Link up overridden/ shadowed methods to any current tops. - if (model.getAccessScope() != Scope.PRIVATE) { - List list = tops.get(model); - if (list == null) { - tops.put(model, list = new ArrayList()); - } - for (Iterator i = list.iterator(); i.hasNext();) { - T_MODEL sub = i.next(); - if (model.overridesOrShadows(sub)) { - i.remove(); - sub.setUp(model); - model.setDown(sub); - } - } - list.add(model); - } - } - } - return elements; - } - - protected abstract T_MEMBER[] members(Class c); - protected abstract T_MODEL model(T_MEMBER t); - } - - public static final class MethodModel extends ClassElement { - public MethodModel(Method m) { - super(m); - } - - @Override - public String toString() { - return element.getDeclaringClass().getSimpleName() + "." + element.getName(); - } - - @Override - boolean overridesOrShadows(ClassElement sub) { - final Method m1 = element; - final Method m2 = sub.element; - - if (!m1.getName().equals(m2.getName())) { - return false; - } - - if (!Arrays.equals(m1.getParameterTypes(), m2.getParameterTypes())) { - return false; - } - - final Package package1 = m1.getDeclaringClass().getPackage(); - final Package package2 = m2.getDeclaringClass().getPackage(); - if (getAccessScope() == Scope.PACKAGE) { - return package1.equals(package2); - } else { - return true; - } - } - - @Override - public int hashCode() { - int hashCode = element.getName().hashCode(); - for (Class c : element.getParameterTypes()) { - hashCode += 31 * c.hashCode(); - } - return hashCode; - } - - @Override - public boolean equals(Object obj) { - MethodModel other = (MethodModel) obj; - return element.getName().equals(other.element.getName()) && - Arrays.equals(element.getParameterTypes(), - other.element.getParameterTypes()); - } - } - - public static final class FieldModel extends ClassElement { - public FieldModel(Field f) { - super(f); - } - - @Override - public String toString() { - return element.getDeclaringClass().getSimpleName() + "." + element.getName(); - } - - @Override - boolean overridesOrShadows(ClassElement sub) { - final Field f1 = element; - final Field f2 = sub.element; - - if (!f1.getName().equals(f2.getName())) { - return false; - } - - final Package package1 = f1.getDeclaringClass().getPackage(); - final Package package2 = f1.getDeclaringClass().getPackage(); - if (getAccessScope() == Scope.PACKAGE) { - return package1.equals(package2); - } else { - return true; - } - } - - @Override - public int hashCode() { - return element.getName().hashCode(); - } - - @Override - public boolean equals(Object obj) { - FieldModel other = (FieldModel) obj; - return element.getName().equals(other.element.getName()); - } - } - - public ClassModel(Class clazz) { - methods = methodsModel(clazz); - fields = fieldsModel(clazz); - } - - private static LinkedHashMap methodsModel(Class clazz) { - return new ModelBuilder() { - @Override - protected Method [] members(Class c) { - Method[] declaredMethods = c.getDeclaredMethods(); - Arrays.sort(declaredMethods, methodSorter); - return declaredMethods; - } - - @Override - protected MethodModel model(Method t) { - return new MethodModel(t); - } - }.build(clazz); - } - - private static LinkedHashMap fieldsModel(Class clazz) { - return new ModelBuilder() { - @Override - protected Field [] members(Class c) { - Field[] declaredFields = c.getDeclaredFields(); - Arrays.sort(declaredFields, fieldSorter); - return declaredFields; - } - - @Override - protected FieldModel model(Field t) { - return new FieldModel(t); - } - }.build(clazz); - } - - public Map getMethods() { - return Collections.unmodifiableMap(methods); - } - - public Map getFields() { - return Collections.unmodifiableMap(fields); - } - - public Map getAnnotatedLeafMethods(final Class annotation) { - LinkedHashMap result = new LinkedHashMap(); -outer: - for (Map.Entry e : getMethods().entrySet()) { - MethodModel mm = e.getValue(); - - if (mm.element.isAnnotationPresent(annotation)) { - for (MethodModel next = mm.getDown(); next != null; next = next.getDown()) { - if (next.element.isAnnotationPresent(annotation)) { - // At least one override has the annotation on it, so skip any super methods - // because it'd double the test. - continue outer; - } - } - - result.put(e.getKey(), mm); - } - } - return Collections.unmodifiableMap(result); - } - - public T getAnnotation(Method method, Class annClass, boolean inherited) { - MethodModel methodModel = methods.get(method); - if (methodModel == null) { - throw new IllegalArgumentException("No model for method: " + methodModel); - } - - if (inherited) { - for (; methodModel != null; methodModel = methodModel.getUp()) { - T annValue = methodModel.element.getAnnotation(annClass); - if (annValue != null) { - return annValue; - } - } - return null; - } else { - return method.getAnnotation(annClass); - } - } - - public boolean isAnnotationPresent(Method method, Class annClass, boolean inherited) { - return getAnnotation(method, annClass, inherited) != null; - } -} diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/Classes.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/Classes.java deleted file mode 100644 index dbc95df5..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/Classes.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -final class Classes { - private Classes() {} - - public static String simpleName(Class c) { - String fullName = c.getName(); - int lastDot = fullName.lastIndexOf("."); - if (lastDot < 0) { - return fullName; - } else { - return fullName.substring(lastDot + 1); - } - } -} diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/CloseableResourceInfo.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/CloseableResourceInfo.java deleted file mode 100644 index 6236f782..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/CloseableResourceInfo.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import java.io.Closeable; - -/** - * Allocation information (Thread, allocation stack) for tracking disposable - * resources. - */ -final class CloseableResourceInfo { - private final Closeable resource; - private final LifecycleScope scope; - private final StackTraceElement[] allocationStack; - private final String threadName; - - public CloseableResourceInfo(Closeable resource, LifecycleScope scope, Thread t, StackTraceElement[] allocationStack) { - this.resource = resource; - this.threadName = Threads.threadName(t); - this.allocationStack = allocationStack; - this.scope = scope; - } - - public Closeable getResource() { - return resource; - } - - public StackTraceElement[] getAllocationStack() { - return allocationStack; - } - - public LifecycleScope getScope() { - return scope; - } - - /** - * Return the allocating thread's name at the time of creating this resource info. - */ - public String getThreadName() { - return threadName; - } -} diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/FilterExpressionParser.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/FilterExpressionParser.java deleted file mode 100644 index 7fe83af5..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/FilterExpressionParser.java +++ /dev/null @@ -1,315 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Locale; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * Test group conditions filter parser. - */ -public final class FilterExpressionParser { - static final Node [] EMPTY = new Node [0]; - - @SuppressWarnings("serial") - final class SyntaxException extends RuntimeException { - final Node node; - - SyntaxException(Node node, String msg) { - super(msg); - this.node = node; - } - - @Override - public String getMessage() { - if (node != null && node.range != null) { - return super.getMessage() + " At: \"" + node.range + "\""; - } else { - return super.getMessage(); - } - } - } - - interface IContext { - boolean defaultValue(); - boolean hasGroup(String value); - } - - static class InputRange { - final String s; - final int start; - final int len; - - InputRange(String value, int start, int length) { - this.s = value; - this.start = start; - this.len = length; - } - - public String value() { - return s.substring(start, start + len); - } - - public String toString() { - return s.substring(0, start) + - ">" + value() + - "<" + s.substring(start + len); - } - } - - public abstract class Node { - int lbp; - Node [] args = EMPTY; - public InputRange range; - - Node nud() { - throw new SyntaxException(this, "Syntax error."); - } - - Node led(Node left) { - throw new SyntaxException(this, "Not an operator."); - } - - @Override - public String toString() { - return getClass().getSimpleName().replace("Node", ""); - } - - public final String toExpression() { - return toExpression(new StringBuilder()).toString(); - } - - protected StringBuilder toExpression(StringBuilder b) { - throw new UnsupportedOperationException("Not an expression node: " + toString()); - } - - public boolean evaluate(IContext context) { - throw new UnsupportedOperationException("Not an evaluation node: " + toString()); - } - } - - class EosNode extends Node { - public EosNode() { - this.lbp = -1; - } - } - - class DefaultNode extends Node { - @Override - Node nud() { - return this; - } - - @Override - protected StringBuilder toExpression(StringBuilder b) { - b.append("default"); - return b; - } - - @Override - public boolean evaluate(IContext context) { - return context.defaultValue(); - } - } - - abstract class InfixNode extends Node { - @Override - Node led(Node left) { - if (!nodes.hasNext()) { - throw new SyntaxException(this, "Missing argument for " - + toString().toUpperCase(Locale.ROOT) + "."); - } - - args = new Node [] {left, expression(lbp)}; - return this; - } - } - - class AndNode extends InfixNode { - public AndNode() { - this.lbp = 30; - } - - @Override - protected StringBuilder toExpression(StringBuilder b) { - assert args.length == 2; - b.append("("); - b.append(super.args[0].toExpression()); - b.append(" AND "); - b.append(super.args[1].toExpression()); - b.append(")"); - return b; - } - - @Override - public boolean evaluate(IContext context) { - assert args.length == 2; - return super.args[0].evaluate(context) && - super.args[1].evaluate(context); - } - } - - class OrNode extends InfixNode { - public OrNode() { - this.lbp = 20; - } - - @Override - protected StringBuilder toExpression(StringBuilder b) { - assert args.length == 2; - b.append("("); - b.append(super.args[0].toExpression()); - b.append(" OR "); - b.append(super.args[1].toExpression()); - b.append(")"); - return b; - } - - @Override - public boolean evaluate(IContext context) { - assert args.length == 2; - return super.args[0].evaluate(context) || - super.args[1].evaluate(context); - } - } - - class NotNode extends Node { - public NotNode() { - this.lbp = 40; - } - - @Override - Node nud() { - args = new Node[] { expression(lbp) }; - return this; - } - - @Override - protected StringBuilder toExpression(StringBuilder b) { - assert args.length == 1; - b.append("(NOT "); - b.append(super.args[0].toExpression()); - b.append(")"); - return b; - } - - @Override - public boolean evaluate(IContext context) { - assert args.length == 1; - return !super.args[0].evaluate(context); - } - } - - class OpeningBracketNode extends Node { - @Override - Node nud() { - Node expr = expression(0); - - if (current.getClass() != ClosingBracketNode.class) { - throw new SyntaxException(current, "Expected closing bracket."); - } - current = nodes.next(); - - return expr; - } - } - - class ClosingBracketNode extends Node { - @Override - Node led(Node left) { - throw new SyntaxException(this, "Unbalanced parenthesis."); - } - } - - class TestGroupNode extends Node { - @Override - Node nud() { - return this; - } - - @Override - protected StringBuilder toExpression(StringBuilder b) { - b.append(range.value()); - return b; - } - - @Override - public boolean evaluate(IContext context) { - return context.hasGroup(range.value()); - } - } - - private Iterator nodes; - private Node current; - - Node expression(int rbp) { - Node n = current; - current = nodes.next(); - Node left = n.nud(); - while (rbp < current.lbp) { - n = current; - current = nodes.next(); - left = n.led(left); - } - return left; - } - - /** - * Pratt's parser. - */ - public Node parse(String rule) { - nodes = tokenize(rule); - current = nodes.next(); - if (current instanceof EosNode) { - return new DefaultNode(); - } else { - return expression(-1); - } - } - - /** - * Very simple regexp based tokenizer. We don't need to be fancy or super-fast. - */ - private Iterator tokenize(String rule) { - Matcher m = Pattern.compile( - "(?:\\s*)(([^\\s\\(\\)]+)|([\\(\\)]))").matcher(rule); - List tokens = new ArrayList(); - while (m.find()) { - final int s = m.start(1); - final int len = m.end(1) - s; - final String value = m.group(1); - - final Node t; - if (value.equalsIgnoreCase("DEFAULT")) { - t = new DefaultNode(); - } else if (value.equals("(")) { - t = new OpeningBracketNode(); - } else if (value.equals(")")) { - t = new ClosingBracketNode(); - } else if (value.equalsIgnoreCase("and")) { - t = new AndNode(); - } else if (value.equalsIgnoreCase("or")) { - t = new OrNode(); - } else if (value.equalsIgnoreCase("not")) { - t = new NotNode(); - } else if (value.startsWith("@")) { - t = new TestGroupNode(); - } else { - throw new SyntaxException(null, String.format(Locale.ROOT, - "Unrecognized token '%s'. At: \"%s\"", - value == null ? "" : value, - new InputRange(rule, s, len))); - } - - t.range = new InputRange(rule, s, len); - tokens.add(t); - } - - Node eos = new EosNode(); - eos.range = new InputRange(rule, rule.length(), 0); - tokens.add(eos); - return tokens.iterator(); - } -} diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/GlobFilter.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/GlobFilter.java deleted file mode 100644 index 28d63ba7..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/GlobFilter.java +++ /dev/null @@ -1,69 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import java.util.regex.Pattern; - -import org.junit.runner.Description; -import org.junit.runner.manipulation.Filter; - -/** - * A filter that matches something using globbing (*) pattern. - */ -public abstract class GlobFilter extends Filter { - protected final String globPattern; - private final Pattern pattern; - - public GlobFilter(String glob) { - this.globPattern = glob; - this.pattern = globToPattern(glob); - } - - /** - * Check if a given string matches the glob. - */ - public final boolean globMatches(String string) { - boolean result = pattern.matcher(string).matches(); - return result; - } - - /** - * Simplified conversion to a regexp. - */ - private Pattern globToPattern(String glob) { - StringBuilder pattern = new StringBuilder("^"); - for (char c : glob.toCharArray()) { - switch (c) { - case '*': - pattern.append(".*"); - break; - case '?': - pattern.append('.'); - break; - case '.': - case '$': - case '-': - case '{': - case '}': - case '[': - case ']': - case '(': - case ')': - pattern.append("\\"); - pattern.append(c); - break; - case '\\': - pattern.append("\\\\"); - break; - default: - pattern.append(c); - } - } - pattern.append('$'); - return Pattern.compile(pattern.toString()); - } - - @Override - public abstract boolean shouldRun(Description description); - - @Override - public abstract String describe(); -} diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/GroupEvaluator.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/GroupEvaluator.java deleted file mode 100644 index c7c0dc64..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/GroupEvaluator.java +++ /dev/null @@ -1,178 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import java.lang.annotation.Annotation; -import java.lang.reflect.AnnotatedElement; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; - -import com.carrotsearch.randomizedtesting.FilterExpressionParser.IContext; -import com.carrotsearch.randomizedtesting.FilterExpressionParser.Node; -import com.carrotsearch.randomizedtesting.RandomizedRunner.TestCandidate; -import com.carrotsearch.randomizedtesting.annotations.TestGroup; - -/** - * Evaluates enabled/ disabled state for a given test group. - */ -public final class GroupEvaluator { - private static class TestGroupInfo { - final TestGroup group; - final String name; - final String sysProperty; - final boolean enabled; - - TestGroupInfo(Class annType) { - group = annType.getAnnotation(TestGroup.class); - name = TestGroup.Utilities.getGroupName(annType); - sysProperty = TestGroup.Utilities.getSysProperty(annType); - - boolean enabled; - try { - enabled = RandomizedTest.systemPropertyAsBoolean(sysProperty, group.enabled()); - } catch (IllegalArgumentException e) { - // Ignore malformed system property, disable the group if malformed though. - enabled = false; - } - this.enabled = enabled; - } - } - - private final HashMap, TestGroupInfo> testGroups; - private final Node filter; - private String filterExpression; - - GroupEvaluator(List testCandidates) { - testGroups = collectGroups(testCandidates); - - filterExpression = System.getProperty(SysGlobals.SYSPROP_TESTFILTER()); - if (filterExpression != null && filterExpression.trim().isEmpty()) { - filterExpression = null; - } - - filter = filterExpression != null ? new FilterExpressionParser().parse(filterExpression) : null; - } - - private HashMap, TestGroupInfo> collectGroups(List testCandidates) { - final HashMap, TestGroupInfo> groups = new HashMap, TestGroupInfo>(); - - // Collect all groups declared on methods and instance classes. - HashSet> clazzes = new HashSet>(); - HashSet annotations = new HashSet(); - for (TestCandidate c : testCandidates) { - final Class testClass = c.getTestClass(); - if (!clazzes.contains(testClass)) { - clazzes.add(testClass); - annotations.addAll(Arrays.asList(testClass.getAnnotations())); - } - annotations.addAll(Arrays.asList(c.method.getAnnotations())); - } - - // Get TestGroup annotated annotations. - for (Annotation ann : annotations) { - Class annType = ann.annotationType(); - if (!groups.containsKey(ann) && annType.isAnnotationPresent(TestGroup.class)) { - groups.put(annType, new TestGroupInfo(annType)); - } - } - - return groups; - } - - void appendGroupFilteringOptions(ReproduceErrorMessageBuilder builder) { - for (TestGroupInfo info : testGroups.values()) { - if (System.getProperty(info.sysProperty) != null) { - builder.appendOpt(info.sysProperty, System.getProperty(info.sysProperty)); - } - } - - if (hasFilteringExpression()) { - builder.appendOpt(SysGlobals.SYSPROP_TESTFILTER(), filterExpression); - } - } - - boolean hasFilteringExpression() { - return filterExpression != null; - } - - /** - * @return Returns a non-null string with the reason why the annotated element (class, test or test-class pair) - * should be ignored in the execution. This is an expert-level method, typically tests - * shouldn't be concerned with this. - */ - public String getIgnoreReason(AnnotatedElement... elements) { - final Map annotations = new HashMap(); - - for (AnnotatedElement element : elements) { - for (Annotation ann : element.getAnnotations()) { - Class annType = ann.annotationType(); - if (annType.isAnnotationPresent(TestGroup.class)) { - if (!testGroups.containsKey(annType)) { - testGroups.put(annType, new TestGroupInfo(annType)); - } - annotations.put(testGroups.get(annType).name, ann); - } - } - } - - String defaultState = null; - for (Annotation ann : annotations.values()) { - TestGroupInfo g = testGroups.get(ann.annotationType()); - if (!g.enabled) { - defaultState = "'" + g.name + "' test group is disabled (" + toString(ann) + ")"; - break; - } - } - - if (hasFilteringExpression()) { - final String defaultStateCopy = defaultState; - boolean enabled = filter.evaluate(new IContext() { - @Override - public boolean defaultValue() { - return defaultStateCopy == null; - } - - @Override - public boolean hasGroup(String value) { - if (value.startsWith("@")) value = value.substring(1); - for (Annotation ann : annotations.values()) { - if (value.equalsIgnoreCase(testGroups.get(ann.annotationType()).name)) { - return true; - } - } - return false; - } - }); - return enabled ? null : "Test filter condition: " + filterExpression; - } else { - return defaultState; - } - } - - private String toString(Annotation ann) { - if (ann == null) return "@null?"; - return ann.toString().replace( - ann.annotationType().getName(), - ann.annotationType().getSimpleName()); - } - - /** - * @return Returns the current state of the an annotation marked with - * {@link TestGroup}. Note that tests may be enabled or disabled using filtering - * expressions so an enabled group does not necessarily mean a test marked with - * this group will be executed. - */ - public boolean isGroupEnabled(Class testGroupAnnotation) { - if (!testGroups.containsKey(testGroupAnnotation)) { - if (!testGroupAnnotation.isAnnotationPresent(TestGroup.class)) { - throw new IllegalArgumentException("This annotation is not marked with @" - + TestGroup.class.getName() + ": " + testGroupAnnotation.getName()); - } - - testGroups.put(testGroupAnnotation, new TestGroupInfo(testGroupAnnotation)); - } - - return testGroups.get(testGroupAnnotation).enabled; - } -} diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/InstanceProvider.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/InstanceProvider.java deleted file mode 100644 index 28d8db6e..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/InstanceProvider.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -/** - * Provide a test instance. - */ -interface InstanceProvider { - Object newInstance() throws Throwable; -} diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/JUnit3MethodProvider.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/JUnit3MethodProvider.java deleted file mode 100644 index 8a627b56..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/JUnit3MethodProvider.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Map; - -import com.carrotsearch.randomizedtesting.ClassModel.MethodModel; - -/** - * Method provider selecting tests that follow a name pattern of test(.*). - */ -public class JUnit3MethodProvider implements TestMethodProvider { - @Override - public Collection getTestMethods(Class suiteClass, ClassModel suiteClassModel) { - Map methods = suiteClassModel.getMethods(); - ArrayList result = new ArrayList(); - for (MethodModel mm : methods.values()) { - if (mm.getDown() == null && mm.element.getName().startsWith("test")) { - result.add(mm.element); - } - } - return result; - } -} diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/JUnit4MethodProvider.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/JUnit4MethodProvider.java deleted file mode 100644 index 7d868a1b..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/JUnit4MethodProvider.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import org.junit.Test; - -/** - * Method provider selecting {@link Test} annotated public instance parameterless methods. - */ -public class JUnit4MethodProvider extends AnnotatedMethodProvider { - public JUnit4MethodProvider() { - super(Test.class); - } -} diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/LifecycleScope.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/LifecycleScope.java deleted file mode 100644 index 65bd480a..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/LifecycleScope.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import org.junit.After; -import org.junit.AfterClass; - -/** - * Lifecycle stages for tracking resources. - */ -public enum LifecycleScope { - /** - * A single test case, including all {@link After} hooks. - */ - TEST, - - /** - * A single suite (class), including all {@link AfterClass} hooks. - */ - SUITE; -} diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/MethodGlobFilter.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/MethodGlobFilter.java deleted file mode 100644 index e928951c..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/MethodGlobFilter.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import org.junit.runner.Description; - -/** - * A filter for {@link Description#getMethodName()}. - */ -public class MethodGlobFilter extends GlobFilter { - public MethodGlobFilter(String globPattern) { - super(globPattern); - } - - @Override - public boolean shouldRun(Description description) { - String methodName = description.getMethodName(); - return methodName == null || globMatches(methodName); - } - - @Override - public String describe() { - return "Method matches: " + globPattern; - } -} diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/MixWithSuiteName.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/MixWithSuiteName.java deleted file mode 100644 index 8ee997c1..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/MixWithSuiteName.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import com.carrotsearch.randomizedtesting.annotations.SeedDecorators; - -/** - * A {@link SeedDecorator} to be used with {@link SeedDecorators} annotation - * to modify the master {@link Randomness} with a hash off the suite's class name. - */ -public class MixWithSuiteName implements SeedDecorator { - private long xorHash; - - @Override - public void initialize(Class suiteClass) { - this.xorHash = fmix64(suiteClass.getName().hashCode()); - } - - @Override - public long decorate(long seed) { - return seed ^ xorHash; - } - - /** final mix from murmur hash 3. */ - private long fmix64(long k) { - k ^= k >>> 33; - k *= 0xff51afd7ed558ccdL; - k ^= k >>> 33; - k *= 0xc4ceb9fe1a85ec53L; - k ^= k >>> 33; - return k; - } -} \ No newline at end of file diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/MurmurHash3.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/MurmurHash3.java deleted file mode 100644 index 1f738236..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/MurmurHash3.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -/** - * Hash routines for primitive types. The implementation is based on the finalization step - * from Austin Appleby's MurmurHash3. - * - * @see "http://sites.google.com/site/murmurhash/" - */ -final class MurmurHash3 -{ - private MurmurHash3() - { - // no instances. - } - - /** - * Hashes a 4-byte sequence (Java int). - */ - public static int hash(int k) - { - k ^= k >>> 16; - k *= 0x85ebca6b; - k ^= k >>> 13; - k *= 0xc2b2ae35; - k ^= k >>> 16; - return k; - } - - /** - * Hashes an 8-byte sequence (Java long). - */ - public static long hash(long k) - { - k ^= k >>> 33; - k *= 0xff51afd7ed558ccdL; - k ^= k >>> 33; - k *= 0xc4ceb9fe1a85ec53L; - k ^= k >>> 33; - - return k; - } -} diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/ObjectProcedure.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/ObjectProcedure.java deleted file mode 100644 index e97efa79..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/ObjectProcedure.java +++ /dev/null @@ -1,6 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -interface ObjectProcedure -{ - public void apply(KType value); -} diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/RandomSupplier.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/RandomSupplier.java deleted file mode 100644 index 07e8709d..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/RandomSupplier.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import java.util.Random; - -public interface RandomSupplier { - static RandomSupplier DEFAULT = new RandomSupplier() { - @Override - public Random get(long seed) { - return new Xoroshiro128PlusRandom(seed); - } - }; - - Random get(long seed); -} diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/RandomizedContext.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/RandomizedContext.java deleted file mode 100644 index c29a16d0..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/RandomizedContext.java +++ /dev/null @@ -1,390 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import java.io.Closeable; -import java.lang.Thread.State; -import java.lang.reflect.Method; -import java.util.*; -import java.util.concurrent.Callable; - -import com.carrotsearch.randomizedtesting.annotations.Nightly; - -/** - * Context variables for an execution of a test suite (hooks and tests) running - * under a {@link RandomizedRunner}. - */ -public final class RandomizedContext { - /** Coordination at global level. */ - private static final Object _globalLock = new Object(); - /** Coordination at context level. */ - private final Object _contextLock = new Object(); - - /** - * Per thread assigned resources. - */ - private final static class PerThreadResources { - /** - * Generators of pseudo-randomness. This is a queue because we stack - * them during lifecycle phases (suite/ method level). - */ - final ArrayDeque randomnesses = new ArrayDeque(); - } - - /** - * All thread groups we're currently tracking contexts for. - */ - final static IdentityHashMap contexts - = new IdentityHashMap(); - - /** - * Per thread resources for each context. Allow GCing of threads. - */ - final WeakHashMap perThreadResources - = new WeakHashMap(); - - /** A thread group that shares this context. */ - private final ThreadGroup threadGroup; - - /** @see #getTargetClass() */ - private final Class suiteClass; - - /** The runner to which we're bound. */ - private final RandomizedRunner runner; - - /** The context and all of its resources are no longer usable. */ - private volatile boolean disposed; - - /** - * Disposable resources. - */ - private EnumMap> disposableResources - = new EnumMap>(LifecycleScope.class); - - private Method currentMethod; - - /** */ - private RandomizedContext(ThreadGroup tg, Class suiteClass, RandomizedRunner runner) { - this.threadGroup = tg; - this.suiteClass = suiteClass; - this.runner = runner; - } - - /** The class (suite) being tested. */ - public Class getTargetClass() { - checkDisposed(); - return suiteClass; - } - - /** Runner's seed. */ - long getRunnerSeed() { - return runner.runnerRandomness.getSeed(); - } - - /** - * Returns the runner's master seed, formatted. - */ - public String getRunnerSeedAsString() { - checkDisposed(); - return SeedUtils.formatSeed(getRunnerSeed()); - } - - /** Source of randomness for the context's thread. */ - public Randomness getRandomness() { - return getPerThread().randomnesses.peekFirst(); - } - - /** - * Return all {@link Randomness} on the stack for the current thread. The most - * recent (currently used) randomness comes last in this array. - */ - Randomness [] getRandomnesses() { - ArrayDeque randomnesses = getPerThread().randomnesses; - Randomness[] array = randomnesses.toArray(new Randomness [randomnesses.size()]); - for (int i = 0, j = array.length - 1; i < j; i++, j--) { - Randomness r = array[i]; - array[i] = array[j]; - array[j] = r; - } - return array; - } - - /** - * A shorthand for calling {@link #getRandomness()} and then {@link Randomness#getRandom()}. - */ - public Random getRandom() { - return getRandomness().getRandom(); - } - - /** - * Return true if {@link Nightly} test group is explicitly enabled. - * - * @see RandomizedContext#getGroupEvaluator() - * @see GroupEvaluator#isGroupEnabled(Class) - */ - public boolean isNightly() { - checkDisposed(); - return getGroupEvaluator().isGroupEnabled(Nightly.class); - } - - /** - * @return Returns the context for the calling thread or throws an - * {@link IllegalStateException} if the thread is out of scope. - * @throws IllegalStateException If context is not available. - */ - public static RandomizedContext current() { - return context(Thread.currentThread()); - } - - /** - * Access to the runner governing this context. - */ - public RandomizedRunner getRunner() { - return runner; - } - - /** - * Dispose the given resource at the end of a given lifecycle scope. If the {@link Closeable} - * throws an exception, the test case or suite will end in a failure. - * - * @return resource (for call chaining). - */ - public T closeAtEnd(T resource, LifecycleScope scope) { - synchronized (_contextLock) { - List resources = disposableResources.get(scope); - if (resources == null) { - disposableResources.put(scope, resources = new ArrayList()); - } - resources.add(new CloseableResourceInfo( - resource, scope, Thread.currentThread(), Thread.currentThread().getStackTrace())); - return resource; - } - } - - /** - * Provide access to {@link GroupEvaluator}. - */ - public GroupEvaluator getGroupEvaluator() { - return runner.groupEvaluator; - } - - /** - * Pushes the given randomness to the top of the stack, runs the {@link Callable} and disposes - * the randomness before the this method returns. - *

- * This utility method can be used to initialize resources in a reproducible way since all calls to utility methods - * like {@link com.carrotsearch.randomizedtesting.RandomizedTest#randomInt()} et.al. are forwarded to the current - * RandomContext which uses the provided randomness from the top of the stack. - *

- * - * @param randomness the randomness to push to the top of the stack - * @param callable the callable to execute - * @param the return type of the callable - * @return the result of the call to {@link java.util.concurrent.Callable#call()} - * @throws Exception if {@link java.util.concurrent.Callable#call()} throws an exception - */ - public T runWithPrivateRandomness(Randomness randomness, Callable callable) throws Exception { - push(randomness); - try { - return callable.call(); - } finally { - popAndDestroy(); - } - } - - /** - * Pushes the given randomness to the top of the stack, runs the {@link Callable} and disposes - * the randomness before the this method returns. - *

- * This utility method can be used to initialize resources in a reproducible way since all calls to utility methods - * like {@link com.carrotsearch.randomizedtesting.RandomizedTest#randomInt()} et.al. are forwarded to the current - * RandomContext which uses the provided randomness from the top of the stack. - *

- * - * @param seed The initial seed for the new, private randomness - * @param callable the callable to execute - * @param the return type of the callable - * @return the result of the call to {@link java.util.concurrent.Callable#call()} - * @throws Exception if {@link java.util.concurrent.Callable#call()} throws an exception - */ - public T runWithPrivateRandomness(long seed, Callable callable) throws Exception { - Randomness randomness = getRandomness(); - Randomness prv = new Randomness(seed, randomness.getRandomSupplier(), randomness.getDecorators()); - return runWithPrivateRandomness(prv, callable); - } - - /** - * Dispose of any resources registered in the given scope. - */ - void closeResources(ObjectProcedure consumer, LifecycleScope scope) { - List resources; - synchronized (_contextLock) { - resources = disposableResources.remove(scope); - } - - if (resources != null) { - for (CloseableResourceInfo info : resources) { - consumer.apply(info); - } - } - } - - static RandomizedContext context(Thread thread) { - ThreadGroup currentGroup = thread.getThreadGroup(); - if (currentGroup == null) { - throw new IllegalStateException("No context for a terminated thread: " + Threads.threadName(thread)); - } - - synchronized (_globalLock) { - RandomizedContext context; - while (true) { - context = contexts.get(currentGroup); - if (context == null && currentGroup.getParent() != null) { - currentGroup = currentGroup.getParent(); - } else { - break; - } - } - - if (context == null) { - throw new IllegalStateException("No context information for thread: " + - Threads.threadName(thread) + ". " + - "Is this thread running under a " + - RandomizedRunner.class + " runner context? Add @RunWith(" + RandomizedRunner.class + ".class)" + - " to your test class. Make sure your code accesses random contexts within " - + "@BeforeClass and @AfterClass boundary (for example, static test class initializers are " - + "not permitted to access random contexts)."); - } - - synchronized (context._contextLock) { - if (!context.perThreadResources.containsKey(thread)) { - PerThreadResources perThreadResources = new PerThreadResources(); - perThreadResources.randomnesses.push( - context.runner.runnerRandomness.clone(thread)); - context.perThreadResources.put(thread, perThreadResources); - } - } - - return context; - } - } - - /** - * Create a new context bound to a thread group. - */ - static RandomizedContext create(ThreadGroup tg, Class suiteClass, RandomizedRunner runner) { - assert Thread.currentThread().getThreadGroup() == tg; - synchronized (_globalLock) { - RandomizedContext ctx = new RandomizedContext(tg, suiteClass, runner); - contexts.put(tg, ctx); - ctx.perThreadResources.put(Thread.currentThread(), new PerThreadResources()); - return ctx; - } - } - - /** - * Dispose of the context. - */ - void dispose() { - synchronized (_globalLock) { - checkDisposed(); - disposed = true; - contexts.remove(threadGroup); - - // Clean up and invalidate any per-thread published randoms. - synchronized (_contextLock) { - for (PerThreadResources ref : perThreadResources.values()) { - if (ref != null) { - for (Randomness randomness : ref.randomnesses) { - randomness.destroy(); - } - } - } - } - } - } - - /** Push a new randomness on top of the stack. */ - void push(Randomness rnd) { - getPerThread().randomnesses.push(rnd); - } - - /** Pop a randomness off the stack and dispose it. */ - void popAndDestroy() { - getPerThread().randomnesses.pop().destroy(); - } - - /** Return per-thread resources associated with the current thread. */ - private PerThreadResources getPerThread() { - checkDisposed(); - synchronized (_contextLock) { - return perThreadResources.get(Thread.currentThread()); - } - } - - /** - * Throw an exception if disposed. - */ - private void checkDisposed() { - if (disposed) { - throw new IllegalStateException("Context disposed: " + - toString() + " for thread: " + Thread.currentThread()); - } - } - - /** - * Clone context information between the current thread and another thread. - * This is for internal use only to propagate context information when forking. - */ - static void cloneFor(Thread t) { - if (t.getState() != State.NEW) { - throw new IllegalStateException("The thread to share context with is not in NEW state: " + t); - } - - final ThreadGroup tGroup = t.getThreadGroup(); - if (tGroup == null) { - throw new IllegalStateException("No thread group for thread: " + t); - } - - Thread me = Thread.currentThread(); - if (me.getThreadGroup() != tGroup) { - throw new IllegalArgumentException("Both threads must share the thread group."); - } - - synchronized (_globalLock) { - RandomizedContext context = contexts.get(tGroup); - if (context == null) { - throw new IllegalStateException("No context information for thread: " + t); - } - - synchronized (context._contextLock) { - if (context.perThreadResources.containsKey(t)) { - throw new IllegalStateException("Context already initialized for thread: " + t); - } - - if (!context.perThreadResources.containsKey(me)) { - throw new IllegalStateException("Context not initialized for thread: " + me); - } - - PerThreadResources perThreadResources = new PerThreadResources(); - for (Randomness r : context.perThreadResources.get(me).randomnesses) { - perThreadResources.randomnesses.addLast(r.clone(t)); - } - context.perThreadResources.put(t, perThreadResources); - } - } - } - - void setTargetMethod(Method method) { - this.currentMethod = method; - } - - /** - * @return Return the currently executing test case method (the thread may still - * be within test rules and may never actually hit the method). This method may return - * null if called from the static context (no test case is being executed at - * the moment). - */ - public Method getTargetMethod() { - checkDisposed(); - return currentMethod; - } -} diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/RandomizedRunner.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/RandomizedRunner.java deleted file mode 100644 index a11d5891..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/RandomizedRunner.java +++ /dev/null @@ -1,1997 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import static com.carrotsearch.randomizedtesting.SysGlobals.*; - -import java.lang.Thread.UncaughtExceptionHandler; -import java.lang.annotation.Annotation; -import java.lang.annotation.Inherited; -import java.lang.reflect.AnnotatedElement; -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.security.AccessController; -import java.security.PrivilegedAction; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.HashSet; -import java.util.IdentityHashMap; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Random; -import java.util.Set; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicLong; -import java.util.logging.Level; -import java.util.logging.Logger; - -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.ClassRule; -import org.junit.Ignore; -import org.junit.Rule; -import org.junit.Test; -import org.junit.Assert; -import org.junit.AssumptionViolatedException; -import org.junit.rules.TestRule; -import org.junit.runner.Description; -import org.junit.runner.Result; -import org.junit.runner.Runner; -import org.junit.runner.manipulation.Filter; -import org.junit.runner.manipulation.Filterable; -import org.junit.runner.manipulation.NoTestsRemainException; -import org.junit.runner.notification.Failure; -import org.junit.runner.notification.RunListener; -import org.junit.runner.notification.RunNotifier; -import org.junit.runners.model.FrameworkField; -import org.junit.runners.model.FrameworkMethod; -import org.junit.runners.model.InitializationError; -import org.junit.runners.model.MultipleFailureException; -import org.junit.runners.model.Statement; -import org.junit.runners.model.TestClass; - -import com.carrotsearch.randomizedtesting.ClassModel.MethodModel; -import com.carrotsearch.randomizedtesting.annotations.Listeners; -import com.carrotsearch.randomizedtesting.annotations.Name; -import com.carrotsearch.randomizedtesting.annotations.ParametersFactory; -import com.carrotsearch.randomizedtesting.annotations.Repeat; -import com.carrotsearch.randomizedtesting.annotations.Seed; -import com.carrotsearch.randomizedtesting.annotations.SeedDecorators; -import com.carrotsearch.randomizedtesting.annotations.Seeds; -import com.carrotsearch.randomizedtesting.annotations.TestCaseInstanceProvider; -import com.carrotsearch.randomizedtesting.annotations.TestCaseOrdering; -import com.carrotsearch.randomizedtesting.annotations.TestContextRandomSupplier; -import com.carrotsearch.randomizedtesting.annotations.TestMethodProviders; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakAction; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakFilters; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakGroup; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakLingering; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakZombies; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakZombies.Consequence; -import com.carrotsearch.randomizedtesting.annotations.Timeout; -import com.carrotsearch.randomizedtesting.annotations.TimeoutSuite; -import com.carrotsearch.randomizedtesting.rules.StatementAdapter; - -/** - * A {@link Runner} implementation for running randomized test cases with - * predictable and repeatable randomness. - * - *

Supports the following JUnit4 features: - *

    - *
  • {@link BeforeClass}-annotated methods (before all tests of a class/superclass),
  • - *
  • {@link Before}-annotated methods (before each test),
  • - *
  • {@link Test}-annotated methods,
  • - *
  • {@link After}-annotated methods (after each test),
  • - *
  • {@link AfterClass}-annotated methods (after all tests of a class/superclass),
  • - *
  • {@link Rule}-annotated fields implementing {@link org.junit.rules.MethodRule} - * and {@link TestRule}.
  • - *
- * - *

Contracts: - *

    - *
  • {@link BeforeClass}, {@link Before} - * methods declared in superclasses are called before methods declared in subclasses,
  • - *
  • {@link AfterClass}, {@link After} - * methods declared in superclasses are called after methods declared in subclasses,
  • - *
  • {@link BeforeClass}, {@link Before}, {@link AfterClass}, {@link After} - * methods declared within the same class are called in randomized order - * derived from the master seed (repeatable with the same seed),
  • - *
- * - *

Deviations from "standard" JUnit: - *

    - *
  • test methods are allowed to return values (the return value is ignored),
  • - *
  • hook methods need not be public; in fact, it is encouraged to make them private to - * avoid accidental shadowing which silently drops parent hooks from executing - * (applies to class hooks mostly, but also to instance hooks).
  • - *
  • all exceptions raised during hooks or test case execution are reported to the notifier, - * there is no suppression or chaining of exceptions,
  • - *
  • a test method must not leave behind any active threads; this is detected - * using {@link ThreadGroup} active counts and is sometimes problematic (many classes - * in the standard library leave active threads behind without waiting for them to terminate). - * One can use the {@link ThreadLeakScope}, {@link ThreadLeakAction} - * and other annotations to control how aggressive the detection - * strategy is and if it fails the test or not.
  • - *
  • uncaught exceptions from any of children threads will cause the test to fail.
  • - *
- * - * @see RandomizedTest - * @see ThreadLeakAction - * @see ThreadLeakScope - * @see ThreadLeakZombies - * @see ThreadLeakGroup - * @see ThreadLeakLingering - * @see ThreadLeakFilters - * @see Listeners - * @see RandomizedContext - * @see TestMethodProviders - */ -public final class RandomizedRunner extends Runner implements Filterable { - /** - * Fake package of a stack trace entry inserted into exceptions thrown by - * test methods. These stack entries contain additional information about - * seeds used during execution. - */ - public static final String AUGMENTED_SEED_PACKAGE = "__randomizedtesting"; - - /** - * Default timeout for a single test case. By default - * the timeout is disabled. Use global system property - * {@link SysGlobals#SYSPROP_TIMEOUT} or an annotation {@link Timeout} if you need to set - * timeouts or expect some test cases may hang. This will slightly slow down - * the tests because each test case is executed in a forked thread. - * - * @see SysGlobals#SYSPROP_TIMEOUT() - */ - public static final int DEFAULT_TIMEOUT = 0; - - /** - * Default timeout for an entire suite. By default - * the timeout is disabled. Use the global system property - * {@link SysGlobals#SYSPROP_TIMEOUT_SUITE} or an annotation {@link TimeoutSuite} - * if you need to set - * timeouts or expect some tests (hooks) may hang. - * - * @see SysGlobals#SYSPROP_TIMEOUT_SUITE() - */ - public static final int DEFAULT_TIMEOUT_SUITE = 0; - - /** - * The default number of first interrupts, then Thread.stop attempts. - */ - public static final int DEFAULT_KILLATTEMPTS = 5; - - /** - * Time in between interrupt retries or stop retries. - */ - public static final int DEFAULT_KILLWAIT = 500; - - /** - * The default number of test repeat iterations. - */ - public static final int DEFAULT_ITERATIONS = 1; - - /** - * Test candidate (model). - */ - class TestCandidate { - public final long seed; - public final Description description; - public final Method method; - public final InstanceProvider instanceProvider; - - public TestCandidate(Method method, long seed, Description description, InstanceProvider instanceProvider) { - this.seed = seed; - this.description = description; - this.method = method; - this.instanceProvider = instanceProvider; - } - - public Class getTestClass() { - return suiteClass; - } - } - - /** - * Package scope logger. - */ - final static Logger logger = Logger.getLogger(RandomizedRunner.class.getSimpleName()); - - /** - * A sequencer for affecting the initial seed in case of rapid succession of this class - * instance creations. Not likely, but can happen two could get the same seed. - */ - private final static AtomicLong sequencer = new AtomicLong(); - - private static final List DEFAULT_STACK_FILTERS = Arrays.asList(new String [] { - "org.junit.", - "junit.framework.", - "sun.", - "java.lang.reflect.", - "com.carrotsearch.randomizedtesting.", - }); - - /** The class with test methods (suite). */ - private final Class suiteClass; - - /** The runner's seed (master). */ - final Randomness runnerRandomness; - - /** - * If {@link SysGlobals#SYSPROP_RANDOM_SEED} property is used with two arguments (master:method) - * then this field contains method-level override. - */ - private Randomness testCaseRandomnessOverride; - - /** - * The number of each test's randomized iterations. - * - * @see SysGlobals#SYSPROP_ITERATIONS - */ - private final Integer iterationsOverride; - - /** All test candidates, processed (seeds assigned) and flattened. */ - private List testCandidates; - - /** Class suite description. */ - private Description suiteDescription; - - /** - * All tests are executed under a specified thread group so that we can have some control - * over how many threads have been started/ stopped. System daemons shouldn't be under - * this group. - */ - RunnerThreadGroup runnerThreadGroup; - - /** - * @see #subscribeListeners(RunNotifier) - */ - private final List autoListeners = new ArrayList(); - - /** - * @see SysGlobals#SYSPROP_APPEND_SEED - */ - private boolean appendSeedParameter; - - /** - * Stack trace filtering/ dumping. - */ - private final TraceFormatting traces; - - /** - * The container we're running in. - */ - private RunnerContainer containerRunner; - - /** - * {@link UncaughtExceptionHandler} for capturing uncaught exceptions - * from the test group and globally. - */ - QueueUncaughtExceptionsHandler handler; - - /** - * Class model. - */ - private ClassModel classModel; - - /** - * Random class implementation supplier. - */ - private final RandomSupplier randomSupplier; - - /** - * Methods cache. - */ - private Map,List> shuffledMethodsCache = new HashMap,List>(); - - /** - * A marker for flagging zombie threads (leaked threads that couldn't be killed). - */ - static AtomicBoolean zombieMarker = new AtomicBoolean(false); - - /** - * The "main" thread group we will be tracking (including subgroups). - */ - final static ThreadGroup mainThreadGroup = Thread.currentThread().getThreadGroup(); - - private final Map restoreProperties = new HashMap(); - - public GroupEvaluator groupEvaluator; - - /** Creates a new runner for the given class. */ - public RandomizedRunner(Class testClass) throws InitializationError { - appendSeedParameter = RandomizedTest.systemPropertyAsBoolean(SYSPROP_APPEND_SEED(), false); - - if (RandomizedTest.systemPropertyAsBoolean(SYSPROP_STACKFILTERING(), true)) { - this.traces = new TraceFormatting(DEFAULT_STACK_FILTERS); - } else { - this.traces = new TraceFormatting(); - } - - this.suiteClass = testClass; - this.classModel = new ClassModel(testClass); - - // Try to detect the JUnit runner's container. This changes reporting - // behavior slightly. - this.containerRunner = detectContainer(); - - // Initialize the runner's master seed/ randomness source. - { - List decorators = new ArrayList(); - for (SeedDecorators decAnn : getAnnotationsFromClassHierarchy(testClass, SeedDecorators.class)) { - for (Class clazz : decAnn.value()) { - try { - SeedDecorator dec = clazz.newInstance(); - dec.initialize(testClass); - decorators.add(dec); - } catch (Throwable t) { - throw new RuntimeException("Could not initialize suite class: " - + testClass.getName() + " because its @SeedDecorators contains non-instantiable: " - + clazz.getName(), t); - } - } - } - SeedDecorator[] decArray = decorators.toArray(new SeedDecorator [decorators.size()]); - - randomSupplier = determineRandomSupplier(testClass); - - final long randomSeed = MurmurHash3.hash(sequencer.getAndIncrement() + System.nanoTime()); - final String globalSeed = emptyToNull(System.getProperty(SYSPROP_RANDOM_SEED())); - final long initialSeed; - if (globalSeed != null) { - final long[] seedChain = SeedUtils.parseSeedChain(globalSeed); - if (seedChain.length == 0 || seedChain.length > 2) { - throw new IllegalArgumentException("Invalid system property " - + SYSPROP_RANDOM_SEED() + " specification: " + globalSeed); - } - - if (seedChain.length > 1) { - testCaseRandomnessOverride = new Randomness(seedChain[1], randomSupplier); - } - - initialSeed = seedChain[0]; - } else if (suiteClass.isAnnotationPresent(Seed.class)) { - initialSeed = seedFromAnnot(suiteClass, randomSeed)[0]; - } else { - initialSeed = randomSeed; - } - runnerRandomness = new Randomness(initialSeed, randomSupplier, decArray); - } - - // Iterations property is primary wrt to annotations, so we leave an "undefined" value as null. - if (emptyToNull(System.getProperty(SYSPROP_ITERATIONS())) != null) { - this.iterationsOverride = RandomizedTest.systemPropertyAsInt(SYSPROP_ITERATIONS(), 0); - if (iterationsOverride < 1) - throw new IllegalArgumentException( - "System property " + SYSPROP_ITERATIONS() + " must be >= 1: " + iterationsOverride); - } else { - this.iterationsOverride = null; - } - - try { - // Fail fast if suiteClass is inconsistent or selected "standard" JUnit rules are somehow broken. - validateTarget(); - - // Collect all test candidates, regardless if they will be executed or not. - suiteDescription = Description.createSuiteDescription(suiteClass); - testCandidates = collectTestCandidates(suiteDescription); - this.groupEvaluator = new GroupEvaluator(testCandidates); - - // GH-251: Apply suite and test filters early so that the returned Description gets updated. - if (emptyToNull(System.getProperty(SYSPROP_TESTMETHOD())) != null) { - try { - filter(new MethodGlobFilter(System.getProperty(SYSPROP_TESTMETHOD()))); - } catch (NoTestsRemainException e) { - // Ignore the exception in the constructor. - } - } - - if (emptyToNull(System.getProperty(SYSPROP_TESTCLASS())) != null) { - Filter suiteFilter = new ClassGlobFilter(System.getProperty(SYSPROP_TESTCLASS())); - if (!suiteFilter.shouldRun(suiteDescription)) { - suiteDescription.getChildren().clear(); - testCandidates.clear(); - } - } - } catch (Throwable t) { - throw new InitializationError(t); - } - } - - private RandomSupplier determineRandomSupplier(Class testClass) { - List randomImpl = getAnnotationsFromClassHierarchy(testClass, TestContextRandomSupplier.class); - if (randomImpl.size() == 0) { - return RandomSupplier.DEFAULT; - } else { - Class clazz = randomImpl.get(randomImpl.size() - 1).value(); - try { - return clazz.newInstance(); - } catch (InstantiationException | IllegalAccessException e) { - throw new IllegalArgumentException("Could not instantiate random supplier of class: " + clazz, e); - } - } - } - - /** - * Attempt to detect the container we're running under. - */ - private static RunnerContainer detectContainer() { - StackTraceElement [] stack = Thread.currentThread().getStackTrace(); - if (stack.length > 0) { - String topClass = stack[stack.length - 1].getClassName(); - - if (topClass.equals("org.eclipse.jdt.internal.junit.runner.RemoteTestRunner")) { - return RunnerContainer.ECLIPSE; - } - - if (topClass.startsWith("com.intellij.")) { - return RunnerContainer.IDEA; - } - } - return RunnerContainer.UNKNOWN; - } - - /** - * Return the current tree of test descriptions (filtered). - */ - @Override - public Description getDescription() { - return suiteDescription; - } - - /** - * Implement {@link Filterable} because GUIs depend on it to run tests selectively. - */ - @Override - public void filter(Filter filter) throws NoTestsRemainException { - // Apply the filter to test candidates. - testCandidates = applyFilters(suiteClass, testCandidates, Collections.singleton(filter)); - - // Prune any removed tests from the already created Descriptions - // and prune any empty resulting suites. - Set descriptions = Collections.newSetFromMap(new IdentityHashMap()); - for (TestCandidate tc : testCandidates) { - descriptions.add(tc.description); - } - - suiteDescription = prune(suiteDescription, descriptions); - - if (testCandidates.isEmpty()) { - throw new NoTestsRemainException(); - } - } - - private static Description prune(Description suite, Set permitted) { - if (suite.isSuite()) { - ArrayList children = suite.getChildren(); - ArrayList retained = new ArrayList<>(children.size()); - for (Description child : children) { - if (child.isSuite()) { - final Description description = prune(child, permitted); - if (!child.getChildren().isEmpty()) { - retained.add(description); - } - } else if (permitted.contains(child)) { - retained.add(child); - } - } - - final Description suiteDescription = suite.childlessCopy(); - for (Description description : retained) { - suiteDescription.addChild(description); - } - return suiteDescription; - } - return suite; - } - - /** - * Runs all tests and hooks. - */ - @Override - public void run(RunNotifier notifier) { - processSystemProperties(); - try { - runSuite(notifier); - } finally { - restoreSystemProperties(); - } - } - - private void restoreSystemProperties() { - for (Map.Entry e : restoreProperties.entrySet()) { - try { - if (e.getValue() == null) { - System.clearProperty(e.getKey()); - } else { - System.setProperty(e.getKey(), e.getValue()); - } - } catch (SecurityException x) { - logger.warning("Could not restore system property: " + e.getKey() + " => " + e.getValue()); - } - } - } - - private void processSystemProperties() { - try { - String jvmCount = System.getProperty(SysGlobals.CHILDVM_SYSPROP_JVM_COUNT); - String jvmId = System.getProperty(SysGlobals.CHILDVM_SYSPROP_JVM_ID); - if (emptyToNull(jvmCount) == null && - emptyToNull(jvmId) == null) { - // We don't run under JUnit4 so we have to fill in these manually. - System.setProperty(SysGlobals.CHILDVM_SYSPROP_JVM_COUNT, "1"); - System.setProperty(SysGlobals.CHILDVM_SYSPROP_JVM_ID, "0"); - restoreProperties.put(SysGlobals.CHILDVM_SYSPROP_JVM_COUNT, jvmCount); - restoreProperties.put(SysGlobals.CHILDVM_SYSPROP_JVM_ID, jvmId); - } - } catch (SecurityException e) { - // Ignore if we can't set those properties. - logger.warning("Could not set child VM count and ID properties."); - } - } - - static class UncaughtException { - final Thread thread; - final String threadName; - final Throwable error; - - UncaughtException(Thread t, Throwable error) { - this.threadName = Threads.threadName(t); - this.thread = t; - this.error = error; - } - } - - /** - * Queue uncaught exceptions. - */ - static class QueueUncaughtExceptionsHandler implements UncaughtExceptionHandler { - private final ArrayList uncaughtExceptions = new ArrayList(); - private boolean reporting = true; - - @Override - public void uncaughtException(Thread t, Throwable e) { - synchronized (this) { - if (!reporting) { - return; - } - uncaughtExceptions.add(new UncaughtException(t, e)); - } - - Logger.getLogger(RunnerThreadGroup.class.getSimpleName()).log( - Level.WARNING, - "Uncaught exception in thread: " + t, e); - } - - /** - * Stop reporting uncaught exceptions. - */ - void stopReporting() { - synchronized (this) { - reporting = false; - } - } - - /** - * Resume uncaught exception reporting. - */ - void resumeReporting() { - synchronized (this) { - reporting = true; - } - } - - /** - * Return the current list of uncaught exceptions and clear it. - */ - public List getUncaughtAndClear() { - synchronized (this) { - final ArrayList copy = new ArrayList(uncaughtExceptions); - uncaughtExceptions.clear(); - return copy; - } - } - } - - /** - * Test execution logic for the entire suite. - */ - private void runSuite(final RunNotifier notifier) { - // NOTE: this effectively means we can't run concurrent randomized runners. - final UncaughtExceptionHandler previous = Thread.getDefaultUncaughtExceptionHandler(); - handler = new QueueUncaughtExceptionsHandler(); - AccessController.doPrivileged(new PrivilegedAction() { - @Override - public Void run() { - Thread.setDefaultUncaughtExceptionHandler(handler); - return null; - } - }); - - this.runnerThreadGroup = new RunnerThreadGroup( - "TGRP-" + Classes.simpleName(suiteClass)); - - final Thread runner = new Thread(runnerThreadGroup, - "SUITE-" + Classes.simpleName(suiteClass) + "-seed#" + SeedUtils.formatSeedChain(runnerRandomness)) { - public void run() { - try { - // Make sure static initializers are invoked and that they are invoked outside of - // the randomized context scope. This is for consistency so that we're not relying - // on the class NOT being initialized before. - try { - Class.forName(suiteClass.getName(), true, suiteClass.getClassLoader()); - } catch (ExceptionInInitializerError e) { - throw e.getCause(); - } - - RandomizedContext context = createContext(runnerThreadGroup); - runSuite(context, notifier); - context.dispose(); - } catch (Throwable t) { - notifier.fireTestFailure(new Failure(suiteDescription, t)); - } - } - }; - - runner.start(); - try { - runner.join(); - } catch (InterruptedException e) { - notifier.fireTestFailure(new Failure(suiteDescription, - new RuntimeException("Interrupted while waiting for the suite runner? Weird.", e))); - } - - UncaughtExceptionHandler current = Thread.getDefaultUncaughtExceptionHandler(); - if (current != handler) { - notifier.fireTestFailure(new Failure(suiteDescription, - new RuntimeException("Suite replaced Thread.defaultUncaughtExceptionHandler. " + - "It's better not to touch it. Or at least revert it to what it was before. Current: " + - (current == null ? "(null)" : current.getClass())))); - } - - AccessController.doPrivileged(new PrivilegedAction() { - @Override - public Void run() { - Thread.setDefaultUncaughtExceptionHandler(previous); - return null; - } - }); - runnerThreadGroup = null; - handler = null; - } - - /** - * Test execution logic for the entire suite, executing under designated - * {@link RunnerThreadGroup}. - */ - private void runSuite(final RandomizedContext context, final RunNotifier notifier) { - final Result result = new Result(); - final RunListener accounting = result.createListener(); - notifier.addListener(accounting); - - final Randomness classRandomness = runnerRandomness.clone(Thread.currentThread()); - context.push(classRandomness); - try { - // Check for automatically hookable listeners. - subscribeListeners(notifier); - - // Fire a synthetic "suite started" event. - for (RunListener r : autoListeners) { - try { - r.testRunStarted(suiteDescription); - } catch (Throwable e) { - logger.log(Level.SEVERE, "Panic: RunListener hook shouldn't throw exceptions.", e); - } - } - - final List tests = testCandidates; - if (!tests.isEmpty()) { - Map ignored = determineIgnoredTests(tests); - - if (ignored.size() == tests.size()) { - // All tests ignored, ignore class hooks but report all the ignored tests. - for (TestCandidate c : tests) { - if (ignored.get(c)) { - reportAsIgnored(notifier, groupEvaluator, c); - } - } - } else { - ThreadLeakControl threadLeakControl = new ThreadLeakControl(notifier, this); - Statement s = runTestsStatement(threadLeakControl.notifier(), tests, ignored, threadLeakControl); - s = withClassBefores(s); - s = withClassAfters(s); - s = withClassRules(s); - s = withCloseContextResources(s, LifecycleScope.SUITE); - s = threadLeakControl.forSuite(s, suiteDescription); - try { - s.evaluate(); - } catch (Throwable t) { - t = augmentStackTrace(t, runnerRandomness); - if (isAssumptionViolated(t)) { - // Fire assumption failure before method ignores. (GH-103). - notifier.fireTestAssumptionFailed(new Failure(suiteDescription, t)); - - // Class level assumptions cause all tests to be ignored. - // see Rants#RANT_3 - for (final TestCandidate c : tests) { - notifier.fireTestIgnored(c.description); - } - } else { - fireTestFailure(notifier, suiteDescription, t); - } - } - } - } - } catch (Throwable t) { - notifier.fireTestFailure(new Failure(suiteDescription, t)); - } - - // Fire a synthetic "suite ended" event and unsubscribe listeners. - for (RunListener r : autoListeners) { - try { - r.testRunFinished(result); - } catch (Throwable e) { - logger.log(Level.SEVERE, "Panic: RunListener hook shouldn't throw exceptions.", e); - } - } - - // Final cleanup. - notifier.removeListener(accounting); - unsubscribeListeners(notifier); - context.popAndDestroy(); - } - - /** - * Determine the set of ignored tests. - */ - private Map determineIgnoredTests(List tests) { - Map ignoredTests = new IdentityHashMap<>(); - for (TestCandidate c : tests) { - // If it's an @Ignore-marked test, always report it as ignored, remove it from execution. - if (hasIgnoreAnnotation(c) ) { - ignoredTests.put(c, true); - } - - // Otherwise, check if the test should be ignored due to test group annotations or filtering - // expression - if (isTestFiltered(groupEvaluator, c)) { - // If we're running under an IDE, report the test back as ignored. Otherwise - // check if filtering expression is being used. If not, report the test as ignored - // (test group exclusion at work). - if (containerRunner == RunnerContainer.ECLIPSE || - containerRunner == RunnerContainer.IDEA || - !groupEvaluator.hasFilteringExpression()) { - ignoredTests.put(c, true); - } else { - ignoredTests.put(c, false); - } - } - } - return ignoredTests; - } - - /** - * Wrap with a rule to close context resources. - */ - private static Statement withCloseContextResources(final Statement s, final LifecycleScope scope) { - return new StatementAdapter(s) { - @Override - protected void afterAlways(final List errors) throws Throwable { - final ObjectProcedure disposer = new ObjectProcedure() { - public void apply(CloseableResourceInfo info) { - try { - info.getResource().close(); - } catch (Throwable t) { - ResourceDisposalError e = new ResourceDisposalError( - "Resource in scope " + - info.getScope().name() + " failed to close. Resource was" - + " registered from thread " + info.getThreadName() - + ", registration stack trace below.", t); - e.setStackTrace(info.getAllocationStack()); - errors.add(e); - } - } - }; - - RandomizedContext.current().closeResources(disposer, scope); - } - }; - } - - private Statement runTestsStatement( - final RunNotifier notifier, - final List tests, - final Map ignored, - final ThreadLeakControl threadLeakControl) { - return new Statement() { - public void evaluate() throws Throwable { - for (final TestCandidate c : tests) { - if (threadLeakControl.isTimedOut()) { - break; - } - - // Setup test thread's name so that stack dumps produce seed, test method, etc. - final String testThreadName = "TEST-" + Classes.simpleName(suiteClass) + - "." + c.method.getName() + "-seed#" + SeedUtils.formatSeedChain(runnerRandomness); - final String restoreName = Thread.currentThread().getName(); - - // This has a side effect of setting up a nested context for the test thread. - final RandomizedContext current = RandomizedContext.current(); - try { - Thread.currentThread().setName(testThreadName); - current.push(new Randomness(c.seed, randomSupplier)); - current.setTargetMethod(c.method); - - if (ignored.containsKey(c)) { - // Ignore the test, but report only if requested. - if (ignored.get(c)) { - reportAsIgnored(notifier, groupEvaluator, c); - } - } else { - runSingleTest(notifier, c, threadLeakControl); - } - } finally { - Thread.currentThread().setName(restoreName); - current.setTargetMethod(null); - current.popAndDestroy(); - } - } - } - }; - } - - void reportAsIgnored(RunNotifier notifier, GroupEvaluator ge, TestCandidate c) { - if (c.method.getAnnotation(Ignore.class) != null) { - notifier.fireTestIgnored(c.description); - return; - } - - String ignoreReason = ge.getIgnoreReason(c.method, suiteClass); - if (ignoreReason != null) { - notifier.fireTestStarted(c.description); - notifier.fireTestAssumptionFailed(new Failure(c.description, - new AssumptionViolatedException(ignoreReason))); - notifier.fireTestFinished(c.description); - } - } - - private void fireTestFailure(RunNotifier notifier, Description description, Throwable t) { - if (t instanceof MultipleFailureException) { - for (Throwable nested : ((MultipleFailureException) t).getFailures()) { - fireTestFailure(notifier, description, nested); - } - } else { - notifier.fireTestFailure(new Failure(description, t)); - } - } - - /** - * Decorate a {@link Statement} with {@link BeforeClass} hooks. - */ - private Statement withClassBefores(final Statement s) { - return new Statement() { - @Override - public void evaluate() throws Throwable { - try { - for (Method method : getShuffledMethods(BeforeClass.class)) { - invoke(method, null); - } - } catch (Throwable t) { - throw augmentStackTrace(t, runnerRandomness); - } - s.evaluate(); - } - }; - } - - private Statement withClassAfters(final Statement s) { - return new Statement() { - @Override - public void evaluate() throws Throwable { - List errors = new ArrayList(); - try { - s.evaluate(); - } catch (Throwable t) { - errors.add(augmentStackTrace(t, runnerRandomness)); - } - - for (Method method : getShuffledMethods(AfterClass.class)) { - try { - invoke(method, null); - } catch (Throwable t) { - errors.add(augmentStackTrace(t, runnerRandomness)); - } - } - - MultipleFailureException.assertEmpty(errors); - } - }; - } - - /** - * Wrap with {@link ClassRule}s. - */ - private Statement withClassRules(Statement s) { - List classRules = getAnnotatedFieldValues(null, ClassRule.class, TestRule.class); - for (TestRule rule : classRules) { - s = rule.apply(s, suiteDescription); - } - return s; - } - - /** - * Runs a single test in the "master" test thread. - */ - void runSingleTest(final RunNotifier notifier, - final TestCandidate c, - final ThreadLeakControl threadLeakControl) { - notifier.fireTestStarted(c.description); - - try { - // Get the test instance. - final Object instance = c.instanceProvider.newInstance(); - - // Collect rules and execute wrapped method. - Statement s = new Statement() { - public void evaluate() throws Throwable { - invoke(c.method, instance); - } - }; - - s = wrapExpectedExceptions(s, c); - s = wrapBeforeAndAfters(s, c, instance); - s = wrapMethodRules(s, c, instance); - s = withCloseContextResources(s, LifecycleScope.TEST); - s = threadLeakControl.forTest(s, c); - s.evaluate(); - } catch (Throwable e) { - e = augmentStackTrace(e); - if (isAssumptionViolated(e)) { - notifier.fireTestAssumptionFailed(new Failure(c.description, e)); - } else { - fireTestFailure(notifier, c.description, e); - } - } finally { - notifier.fireTestFinished(c.description); - } - } - - /** - * Wrap before and after hooks. - */ - private Statement wrapBeforeAndAfters(Statement s, final TestCandidate c, final Object instance) { - // Process @Before hooks. The first @Before to fail will immediately stop processing any other @Befores. - final List befores = getShuffledMethods(Before.class); - if (!befores.isEmpty()) { - final Statement afterBefores = s; - s = new Statement() { - @Override - public void evaluate() throws Throwable { - for (Method m : befores) { - invoke(m, instance); - } - afterBefores.evaluate(); - } - }; - } - - // Process @After hooks. All @After hooks are processed, regardless of their own exceptions. - final List afters = getShuffledMethods(After.class); - if (!afters.isEmpty()) { - final Statement beforeAfters = s; - s = new Statement() { - @Override - public void evaluate() throws Throwable { - List cumulative = new ArrayList(); - try { - beforeAfters.evaluate(); - } catch (Throwable t) { - cumulative.add(t); - } - - // All @Afters must be called. - for (Method m : afters) { - try { - invoke(m, instance); - } catch (Throwable t) { - cumulative.add(t); - } - } - - // At end, throw the exception or propagete. - if (cumulative.size() == 1) { - throw cumulative.get(0); - } else if (cumulative.size() > 1) { - throw new MultipleFailureException(cumulative); - } - } - }; - } - - return s; - } - - /** - * Wrap the given statement into another catching the expected exception, if declared. - */ - private Statement wrapExpectedExceptions(final Statement s, TestCandidate c) { - Test ann = c.method.getAnnotation(Test.class); - - if (ann == null) { - return s; - } - - // If there's no expected class, don't wrap. Eh, None is package-private... - final Class expectedClass = ann.expected(); - if (expectedClass.getName().equals("org.junit.Test$None")) { - return s; - } - - return new Statement() { - @Override - public void evaluate() throws Throwable { - try { - s.evaluate(); - } catch (Throwable t) { - if (!expectedClass.isInstance(t)) { - throw t; - } - // We caught something that was expected. No worries then. - return; - } - - // If we're here this means we passed the test that expected a failure. - Assert.fail("Expected an exception but the test passed: " - + expectedClass.getName()); - } - }; - } - - /** - * Wrap the given statement in any declared MethodRules (old style rules). - */ - @SuppressWarnings("deprecation") - private Statement wrapMethodRules(Statement s, TestCandidate c, Object instance) { - FrameworkMethod fm = new FrameworkMethod(c.method); - - // Old-style MethodRules first. - List methodRules = - getAnnotatedFieldValues(instance, Rule.class, org.junit.rules.MethodRule.class); - for (org.junit.rules.MethodRule rule : methodRules) { - s = rule.apply(s, fm, instance); - } - - // New-style TestRule next. - List testRules = - getAnnotatedFieldValues(instance, Rule.class, TestRule.class); - for (TestRule rule : testRules) { - s = rule.apply(s, c.description); - } - - return s; - } - - /* - * We're using JUnit infrastructure here, but provide constant - * ordering of the result. The returned list has class...super order. - */ - private List getAnnotatedFieldValues(Object test, - Class annotationClass, Class valueClass) { - TestClass info = AccessController.doPrivileged(new PrivilegedAction() { - @Override - public TestClass run() { - return new TestClass(suiteClass); - } - }); - List results = new ArrayList(); - - List annotatedFields = - new ArrayList(info.getAnnotatedFields(annotationClass)); - - // Split fields by class - final HashMap, List> byClass = - new HashMap, List>(); - for (FrameworkField field : annotatedFields) { - Class clz = field.getField().getDeclaringClass(); - if (!byClass.containsKey(clz)) { - byClass.put(clz, new ArrayList()); - } - byClass.get(clz).add(field); - } - - // Consistent order at class level. - for (List fields : byClass.values()) { - Collections.sort(fields, new Comparator() { - @Override - public int compare(FrameworkField o1, FrameworkField o2) { - return o1.getField().getName().compareTo( - o2.getField().getName()); - } - }); - Collections.shuffle(fields, new Random(runnerRandomness.getSeed())); - } - - annotatedFields.clear(); - for (Class clz = suiteClass; clz != null; clz = clz.getSuperclass()) { - List clzFields = byClass.get(clz); - if (clzFields != null) { - annotatedFields.addAll(clzFields); - } - } - - for (FrameworkField each : annotatedFields) { - try { - Object fieldValue = each.get(test); - if (valueClass.isInstance(fieldValue)) - results.add(valueClass.cast(fieldValue)); - } catch (IllegalAccessException e) { - throw new RuntimeException(e); - } - } - - return results; - } - - /** - * Create randomized context for the run. The context is shared by all - * threads in a given thread group (but the source of {@link Randomness} - * is assigned per-thread). - */ - private RandomizedContext createContext(ThreadGroup tg) { - return RandomizedContext.create(tg, suiteClass, this); - } - - /** Subscribe annotation listeners to the notifier. */ - private void subscribeListeners(RunNotifier notifier) { - for (Listeners ann : getAnnotationsFromClassHierarchy(suiteClass, Listeners.class)) { - for (Class clazz : ann.value()) { - try { - RunListener listener = clazz.newInstance(); - autoListeners.add(listener); - notifier.addListener(listener); - } catch (Throwable t) { - throw new RuntimeException("Could not initialize suite class: " - + suiteClass.getName() + " because its @Listener is not instantiable: " - + clazz.getName(), t); - } - } - } - } - - /** Unsubscribe listeners. */ - private void unsubscribeListeners(RunNotifier notifier) { - for (RunListener r : autoListeners) - notifier.removeListener(r); - } - - private static List applyFilters(Class suiteClass, - List testCandidates, - Collection testFilters) { - final List filtered; - if (testFilters.isEmpty()) { - filtered = new ArrayList(testCandidates); - } else { - filtered = new ArrayList<>(testCandidates.size()); - for (TestCandidate candidate : testCandidates) { - boolean shouldRun = true; - for (Filter f : testFilters) { - // Inquire for both full description (possibly with parameters and seed) - // and simplified description (just method name). - if (f.shouldRun(candidate.description) || - f.shouldRun(Description.createTestDescription( - suiteClass, candidate.method.getName()))) { - continue; - } - - shouldRun = false; - break; - } - - if (shouldRun) { - filtered.add(candidate); - } - } - } - return filtered; - } - - /** - * Normalize empty strings to nulls. - */ - static String emptyToNull(String value) { - if (value == null || value.trim().isEmpty()) - return null; - return value.trim(); - } - - /** - * Returns true if we should ignore this test candidate. - */ - private boolean hasIgnoreAnnotation(TestCandidate c) { - return c.method.getAnnotation(Ignore.class) != null; - } - - private boolean isTestFiltered(GroupEvaluator ev, TestCandidate c) { - return ev.getIgnoreReason(c.method, suiteClass) != null; - } - - /** - * Construct a list of ordered framework methods. Minor tweaks are done depending - * on the annotation (reversing order, etc.). - */ - private List getShuffledMethods(Class ann) { - List methods = shuffledMethodsCache.get(ann); - if (methods != null) { - return methods; - } - - methods = new ArrayList(classModel.getAnnotatedLeafMethods(ann).keySet()); - - // Shuffle sub-ranges using class level randomness. - Random rnd = new Random(runnerRandomness.getSeed()); - for (int i = 0, j = 0; i < methods.size(); i = j) { - final Method m = methods.get(i); - j = i + 1; - while (j < methods.size() && m.getDeclaringClass() == methods.get(j).getDeclaringClass()) { - j++; - } - - if (j - i > 1) { - Collections.shuffle(methods.subList(i, j), rnd); - } - } - - // Reverse processing order to super...clazz for befores - if (ann == Before.class || ann == BeforeClass.class) { - Collections.reverse(methods); - } - - methods = Collections.unmodifiableList(methods); - shuffledMethodsCache.put(ann, methods); - return methods; - } - - /** - * Collect all test candidates, regardless if they will be executed or not. At this point - * individual test methods are also expanded into multiple executions corresponding - * to the number of iterations ({@link SysGlobals#SYSPROP_ITERATIONS}) and the initial method seed - * is preassigned. - * - *

The order of test candidates is shuffled based on the runner's random.

- * - * @see Rants#RANT_1 - */ - private List collectTestCandidates(Description classDescription) { - // Get the test instance provider if explicitly stated. - TestMethodProviders providersAnnotation = - suiteClass.getAnnotation(TestMethodProviders.class); - - // If nothing, fallback to the default. - final TestMethodProvider [] providers; - if (providersAnnotation != null) { - providers = new TestMethodProvider [providersAnnotation.value().length]; - int i = 0; - for (Class clazz : providersAnnotation.value()) { - try { - providers[i++] = clazz.newInstance(); - } catch (Exception e) { - throw new RuntimeException(TestMethodProviders.class.getSimpleName() + - " classes could not be instantiated.", e); - } - } - } else { - providers = new TestMethodProvider [] { - new JUnit4MethodProvider(), - // new JUnit3MethodProvider(), - }; - } - - // Get test methods from providers. - final Set allTestMethods = new HashSet(); - for (TestMethodProvider provider : providers) { - Collection testMethods = provider.getTestMethods(suiteClass, classModel); - allTestMethods.addAll(testMethods); - } - - List testMethods = new ArrayList(allTestMethods); - Collections.sort(testMethods, new Comparator() { - @Override - public int compare(Method m1, Method m2) { - return m1.toGenericString().compareTo(m2.toGenericString()); - } - }); - - // Perform candidate method validation. - validateTestMethods(testMethods); - - // Random (but consistent) shuffle. - Collections.shuffle(testMethods, new Random(runnerRandomness.getSeed())); - - Constructor[] constructors = suiteClass.getConstructors(); - if (constructors.length != 1) { - throw new RuntimeException("There must be exactly one constructor: " + constructors.length); - } - final Constructor constructor = constructors[0]; - - // Collect test method-parameters pairs. - List testCases = collectMethodExecutions(constructor, testMethods); - - // Test case ordering. Shuffle only real test cases, don't allow shuffling - // or changing the order of reiterations or explicit @Seed annotations that - // multiply a given test. - TestCaseOrdering methodOrder = suiteClass.getAnnotation(TestCaseOrdering.class); - if (methodOrder != null) { - try { - Collections.sort(testCases, methodOrder.value().newInstance()); - } catch (InstantiationException | IllegalAccessException e) { - throw new RuntimeException("Could not sort test methods.", e); - } - } - - // Collect all variants of execution for a single method/ parameters pair. - Map descriptionRepetitions = new HashMap<>(); - List allTests = new ArrayList(); - Map> sameMethodVariants = new LinkedHashMap>(); - for (TestMethodExecution testCase : testCases) { - List variants = collectCandidatesForMethod(descriptionRepetitions, constructor, testCase); - allTests.addAll(variants); - - List existing = sameMethodVariants.get(testCase.method); - if (existing == null) { - existing = new ArrayList<>(variants); - sameMethodVariants.put(testCase.method, existing); - } else { - existing.addAll(variants); - } - } - - // Rearrange JUnit Description into a hierarchy if a given method - // has more than one variant (due to multiple repetitions, parameters or seeds). - for (Map.Entry> e : sameMethodVariants.entrySet()) { - List candidates = e.getValue(); - if (candidates.size() > 1) { - Description methodParent = Description.createSuiteDescription(e.getKey().getName()); - suiteDescription.addChild(methodParent); - for (TestCandidate candidate : candidates) { - methodParent.addChild(candidate.description); - } - } else { - suiteDescription.addChild(candidates.iterator().next().description); - } - } - - return allTests; - } - - /** - * Helper tuple (Method, instance params). - */ - static private class TestMethodExecution implements TestMethodAndParams { - final Object [] params; - final List paramsWrapper; - final Method method; - final String argFormattingTemplate; - final InstanceProvider instanceProvider; - - public TestMethodExecution(Method m, String argFormattingTemplate, Object[] params, InstanceProvider instanceProvider) { - this.method = m; - this.params = params; - this.paramsWrapper = Collections.unmodifiableList(Arrays.asList(params)); - this.argFormattingTemplate = argFormattingTemplate; - this.instanceProvider = instanceProvider; - } - - @Override - public Method getTestMethod() { - return method; - } - - @Override - public List getInstanceArguments() { - return paramsWrapper; - } - } - - /** - * Collect test candidates for a single method and the given seed. - */ - private List collectCandidatesForMethod( - Map descriptionRepetitions, - final Constructor constructor, - TestMethodExecution testCase) { - final Method method = testCase.method; - final Object[] params = testCase.params; - final boolean fixedSeed = isConstantSeedForAllIterations(method); - final int methodIterations = determineMethodIterationCount(method); - final long[] seeds = determineMethodSeeds(method); - - final List candidates = new ArrayList(); - - String argFormattingTemplate = testCase.argFormattingTemplate; - if (methodIterations > 1 || seeds.length > 1 || appendSeedParameter) { - final int seedParamIndex = params.length + 1; - argFormattingTemplate += " seed=%" + seedParamIndex + "$s"; - } - - for (final long testSeed : seeds) { - for (int i = 0; i < methodIterations; i++) { - final long thisSeed = (fixedSeed ? testSeed : testSeed ^ MurmurHash3.hash((long) i)); - - // Format constructor arguments. - Object [] args = Arrays.copyOf(testCase.params, testCase.params.length + 1, Object[].class); - args[args.length - 1] = SeedUtils.formatSeedChain(runnerRandomness, new Randomness(thisSeed, randomSupplier)); - String formattedArguments = String.format(Locale.ROOT, argFormattingTemplate, args); - - String key = method.getName() + "::" + formattedArguments; - int cnt = 1 + zeroForNull(descriptionRepetitions.get(key)); - descriptionRepetitions.put(key, cnt); - if (cnt > 1) { - formattedArguments += " #" + cnt; - } - - if (!formattedArguments.trim().isEmpty()) { - // GH-253: IntelliJ only recognizes test names for re-runs when " [...]" is used... - // Leave for now (backward compat?) - if (containerRunner == RunnerContainer.IDEA) { - formattedArguments = " [" + formattedArguments.trim() + "]"; - } else { - formattedArguments = " {" + formattedArguments.trim() + "}"; - } - } - - Description description = Description.createSuiteDescription( - String.format(Locale.ROOT, "%s%s(%s)", method.getName(), formattedArguments, suiteClass.getName()), - method.getAnnotations()); - - // Create an instance and delay instantiation exception if possible. - candidates.add(new TestCandidate(method, thisSeed, description, testCase.instanceProvider)); - } - } - - return candidates; - } - - /** Replace null with zero. */ - private static int zeroForNull(Integer v) { - return v == null ? 0 : v; - } - - /** - * Collect test method executions from list of test methods and - * potentially parameters from parameter factory methods. - */ - public List collectMethodExecutions(Constructor constructor, List testMethods) { - final List testCases = new ArrayList<>(); - String argFormattingTemplate = createDefaultArgumentFormatting(constructor); - final Map factoryMethods = classModel.getAnnotatedLeafMethods(ParametersFactory.class); - - if (factoryMethods.isEmpty()) { - Object[] noArgs = new Object [0]; - InstanceProvider instanceProvider = getInstanceProvider(constructor, noArgs); - for (Method testMethod : testMethods) { - testCases.add(new TestMethodExecution(testMethod, argFormattingTemplate, noArgs, instanceProvider)); - } - } else { - for (Method factoryMethod : factoryMethods.keySet()) { - Validation.checkThat(factoryMethod) - .isStatic() - .isPublic(); - - if (!Iterable.class.isAssignableFrom(factoryMethod.getReturnType())) { - throw new RuntimeException("@" + ParametersFactory.class.getSimpleName() + " annotated " + - "methods must be public, static and returning Iterable:" + factoryMethod); - } - - ParametersFactory pfAnnotation = factoryMethod.getAnnotation(ParametersFactory.class); - if (!pfAnnotation.argumentFormatting().equals(ParametersFactory.DEFAULT_FORMATTING)) { - argFormattingTemplate = pfAnnotation.argumentFormatting(); - } - - List args = new ArrayList<>(); - try { - Iterable factoryArguments = Iterable.class.cast(factoryMethod.invoke(null)); - for (Object o : factoryArguments) { - if (!(o instanceof Object[])) { - throw new RuntimeException("Expected Object[] for each set of constructor arguments: " + o); - } - args.add((Object[]) o); - } - } catch (InvocationTargetException e) { - if (isAssumptionViolated(e.getCause())) { - return Collections.emptyList(); - } - Rethrow.rethrow(e.getCause()); - } catch (Throwable t) { - throw new RuntimeException("Error collecting parameters from: " + factoryMethod, t); - } - - if (pfAnnotation.shuffle()) { - Collections.shuffle(args, new Random(runnerRandomness.getSeed())); - } - - for (Object[] constructorArgs : args) { - InstanceProvider instanceProvider = getInstanceProvider(constructor, constructorArgs); - for (Method testMethod : testMethods) { - testCases.add(new TestMethodExecution(testMethod, argFormattingTemplate, constructorArgs, instanceProvider)); - } - } - } - } - return testCases; - } - - private boolean isAssumptionViolated(Throwable cause) { - return cause instanceof org.junit.AssumptionViolatedException || - cause instanceof org.junit.internal.AssumptionViolatedException; - } - - /** - * Determine instance provider. - */ - private InstanceProvider getInstanceProvider(Constructor constructor, Object[] args) { - TestCaseInstanceProvider.Type type = TestCaseInstanceProvider.Type.INSTANCE_PER_TEST_METHOD; - TestCaseInstanceProvider providerAnn = suiteClass.getAnnotation(TestCaseInstanceProvider.class); - if (providerAnn != null) { - type = providerAnn.value(); - } - - switch (type) { - case INSTANCE_PER_CONSTRUCTOR_ARGS: - return new SameInstanceProvider(new NewInstanceProvider(constructor, args)); - case INSTANCE_PER_TEST_METHOD: - return new NewInstanceProvider(constructor, args); - default: - throw new RuntimeException(); - } - } - - private static class SameInstanceProvider implements InstanceProvider { - private final InstanceProvider delegate; - private volatile Object instance; - - public SameInstanceProvider(InstanceProvider delegate) { - this.delegate = delegate; - } - - @Override - public Object newInstance() throws Throwable { - // There should be no concurrent-threaded access to this method, ever, - // but we can be called from multiple threads sequentially. - if (instance == null) { - instance = delegate.newInstance(); - } - return instance; - } - } - - private static class NewInstanceProvider implements InstanceProvider { - private final Constructor constructor; - private final Object[] args; - - public NewInstanceProvider(Constructor constructor, Object[] args) { - this.constructor = constructor; - this.args = args; - } - - @Override - public Object newInstance() throws Throwable { - try { - return constructor.newInstance(args); - } catch (InvocationTargetException e) { - throw ((InvocationTargetException) e).getTargetException(); - } catch (IllegalArgumentException e) { - throw new IllegalArgumentException( - "Constructor arguments do not match provider parameters?", e); - } - } - } - - /** - * Default formatting string for constructor arguments. - */ - private static String createDefaultArgumentFormatting(Constructor constructor) { - StringBuilder b = new StringBuilder(); - final int argCount = constructor.getParameterTypes().length; - Annotation [][] anns = constructor.getParameterAnnotations(); - for (int i = 0; i < argCount; i++) { - String argName = null; - - for (Annotation ann : anns[i]) { - if (ann != null && ann.annotationType().equals(Name.class)) { - argName = ((Name) ann).value(); - break; - } - } - - if (argName == null) { - argName = "p" + i; - } - - b.append(i > 0 ? " " : "") - .append(argName) - .append("=%s"); - } - - return b.toString(); - } - - /** - * Determine if a given method's iterations should run with a fixed seed or not. - */ - private boolean isConstantSeedForAllIterations(Method method) { - if (testCaseRandomnessOverride != null) - return true; - - Repeat repeat; - if ((repeat = method.getAnnotation(Repeat.class)) != null) { - return repeat.useConstantSeed(); - } - if ((repeat = suiteClass.getAnnotation(Repeat.class)) != null) { - return repeat.useConstantSeed(); - } - - return false; - } - - /** - * Determine method iteration count based on (first declaration order wins): - *
    - *
  • global property {@link SysGlobals#SYSPROP_ITERATIONS}.
  • - *
  • method annotation {@link Repeat}.
  • - *
  • class annotation {@link Repeat}.
  • - *
  • The default (1).
  • - *
      - */ - private int determineMethodIterationCount(Method method) { - // Global override. - if (iterationsOverride != null) - return iterationsOverride; - - Repeat repeat; - if ((repeat = method.getAnnotation(Repeat.class)) != null) { - return repeat.iterations(); - } - if ((repeat = suiteClass.getAnnotation(Repeat.class)) != null) { - return repeat.iterations(); - } - - return DEFAULT_ITERATIONS; - } - - /** - * Determine a given method's initial random seed. - * - * @see Seed - * @see Seeds - */ - private long [] determineMethodSeeds(Method method) { - if (testCaseRandomnessOverride != null) { - return new long [] { testCaseRandomnessOverride.getSeed() }; - } - - // We assign each method a different starting hash based on the global seed - // and a hash of their name (so that the order of methods does not matter, only - // their names). Take into account global override and method and class level - // {@link Seed} annotations. - final long randomSeed = - runnerRandomness.getSeed() ^ MurmurHash3.hash((long) method.getName().hashCode()); - final HashSet seeds = new HashSet(); - - // Check method-level @Seed and @Seeds annotation first. - // They take precedence over anything else. - Seed seed; - if ((seed = method.getAnnotation(Seed.class)) != null) { - for (long s : seedFromAnnot(method, randomSeed)) { - seeds.add(s); - } - } - - // Check a number of seeds on a single method. - Seeds seedsValue = classModel.getAnnotation(method, Seeds.class, true); - if (seedsValue != null) { - for (Seed s : seedsValue.value()) { - if (s.value().equals("random")) - seeds.add(randomSeed); - else { - for (long s2 : SeedUtils.parseSeedChain(s.value())) { - seeds.add(s2); - } - } - } - } - - // Check suite-level override. - if (seeds.isEmpty()) { - if ((seed = suiteClass.getAnnotation(Seed.class)) != null) { - if (!seed.value().equals("random")) { - long [] seedChain = SeedUtils.parseSeedChain(suiteClass.getAnnotation(Seed.class).value()); - if (seedChain.length > 1) - seeds.add(seedChain[1]); - } - } - } - - // If still empty, add the derived random seed. - if (seeds.isEmpty()) { - seeds.add(randomSeed); - } - - long [] result = new long [seeds.size()]; - int i = 0; - for (Long s : seeds) { - result[i++] = s; - } - return result; - } - - /** - * Invoke a given method on a suiteClass instance (can be null for static methods). - */ - void invoke(final Method m, Object instance, Object... args) throws Throwable { - if (!Modifier.isPublic(m.getModifiers())) { - try { - if (!m.isAccessible()) { - AccessController.doPrivileged(new PrivilegedAction() { - @Override - public Void run() { - m.setAccessible(true); - return null; - }}); - } - } catch (SecurityException e) { - throw new RuntimeException("There is a non-public method that needs to be called. This requires " + - "ReflectPermission('suppressAccessChecks'). Don't run with the security manager or " + - " add this permission to the runner. Offending method: " + m.toGenericString()); - } - } - - try { - m.invoke(instance, args); - } catch (InvocationTargetException e) { - throw e.getCause(); - } - } - - /** - * Perform additional checks on methods returned from the providers. - */ - private void validateTestMethods(List testMethods) { - HashSet> parents = new HashSet>(); - for (Class c = suiteClass; c != null; c = c.getSuperclass()) { - parents.add(c); - } - - for (Method method : testMethods) { - if (!parents.contains(method.getDeclaringClass())) { - throw new IllegalArgumentException("Test method does not belong to " + - "test suite class hierarchy: " + method.getDeclaringClass() + "#" + - method.getName()); - } - - // * method() - Validation.checkThat(method) - .describedAs("Test method " + suiteClass.getName() + "#" + method.getName()) - .isPublic() - .isNotStatic() - .hasArgsCount(0); - - // No @Test(timeout=...) and @Timeout at the same time. - Test testAnn = classModel.getAnnotation(method, Test.class, true); - if (testAnn != null && testAnn.timeout() > 0 && classModel.isAnnotationPresent(method, Timeout.class, true)) { - throw new IllegalArgumentException("Conflicting @Test(timeout=...) and @Timeout " + - "annotations in: " + suiteClass.getName() + "#" + method.getName()); - } - - // @Seed annotation on test methods must have at most 1 seed value. - Seed seed = classModel.getAnnotation(method, Seed.class, true); - if (seed != null) { - try { - String seedChain = seed.value(); - if (!seedChain.equals("random")) { - long[] chain = SeedUtils.parseSeedChain(seedChain); - if (chain.length > 1) { - throw new IllegalArgumentException("@Seed on methods must contain one seed only (no runner seed)."); - } - } - } catch (IllegalArgumentException e) { - throw new RuntimeException("@Seed annotation invalid on method " - + method.getName() + ", in class " + suiteClass.getName() + ": " - + e.getMessage()); - } - } - } - } - - /** - * Validate methods and hooks in the suiteClass. Follows "standard" JUnit rules, - * with some exceptions on return values and more rigorous checking of shadowed - * methods and fields. - */ - private void validateTarget() { - // Target is accessible (public, concrete, has a parameterless constructor etc). - Validation.checkThat(suiteClass) - .describedAs("Suite class " + suiteClass.getName()) - .isPublic() - .isConcreteClass(); - - // Check constructors. - Constructor [] constructors = suiteClass.getConstructors(); - if (constructors.length != 1 || !Modifier.isPublic(constructors[0].getModifiers())) { - throw new RuntimeException("A test class is expected to have one public constructor " - + " (parameterless or with types matching static @" + ParametersFactory.class - + "-annotated method's output): " + suiteClass.getName()); - } - - // If there is a parameterized constructor, look for a static method that privides parameters. - if (constructors[0].getParameterTypes().length > 0) { - Collection factories = classModel.getAnnotatedLeafMethods(ParametersFactory.class).keySet(); - if (factories.isEmpty()) { - throw new RuntimeException("A test class with a parameterized constructor is expected " - + " to have a static @" + ParametersFactory.class - + "-annotated method: " + suiteClass.getName()); - } - - for (Method m : factories) { - Validation.checkThat(m) - .describedAs("@ParametersFactory method " + suiteClass.getName() + "#" + m.getName()) - .isStatic() - .isPublic() - .hasArgsCount(0) - .hasReturnType(Iterable.class); - } - } - - // @BeforeClass - for (Method method : classModel.getAnnotatedLeafMethods(BeforeClass.class).keySet()) { - Validation.checkThat(method) - .describedAs("@BeforeClass method " + suiteClass.getName() + "#" + method.getName()) - .isStatic() - .hasArgsCount(0); - } - - // @AfterClass - for (Method method : classModel.getAnnotatedLeafMethods(AfterClass.class).keySet()) { - Validation.checkThat(method) - .describedAs("@AfterClass method " + suiteClass.getName() + "#" + method.getName()) - .isStatic() - .hasArgsCount(0); - } - - // @Before - for (Method method : classModel.getAnnotatedLeafMethods(Before.class).keySet()) { - Validation.checkThat(method) - .describedAs("@Before method " + suiteClass.getName() + "#" + method.getName()) - .isNotStatic() - .hasArgsCount(0); - } - - // @After - for (Method method : classModel.getAnnotatedLeafMethods(After.class).keySet()) { - Validation.checkThat(method) - .describedAs("@After method " + suiteClass.getName() + "#" + method.getName()) - .isNotStatic() - .hasArgsCount(0); - } - - // TODO: [GH-214] Validate @Rule fields (what are the "rules" for these anyway?) - } - - /** - * Augment stack trace of the given exception with seed infos. - */ - static T augmentStackTrace(T e, Randomness... seeds) { - if (seeds.length == 0) { - seeds = RandomizedContext.current().getRandomnesses(); - } - - final String seedChain = SeedUtils.formatSeedChain(seeds); - final String existingSeed = seedFromThrowable(e); - if (existingSeed != null && existingSeed.equals(seedChain)) { - return e; - } - - List stack = new ArrayList( - Arrays.asList(e.getStackTrace())); - - stack.add(0, new StackTraceElement(AUGMENTED_SEED_PACKAGE + ".SeedInfo", - "seed", seedChain, 0)); - - e.setStackTrace(stack.toArray(new StackTraceElement [stack.size()])); - return e; - } - - /** - * Collect all annotations from a clazz hierarchy. Superclass's annotations come first. - * {@link Inherited} annotations are removed (hopefully, the spec. isn't clear on this whether - * the same object is returned or not for inherited annotations). - */ - private static List getAnnotationsFromClassHierarchy(Class clazz, Class annotation) { - List anns = new ArrayList(); - IdentityHashMap inherited = new IdentityHashMap(); - for (Class c = clazz; c != Object.class; c = c.getSuperclass()) { - if (c.isAnnotationPresent(annotation)) { - T ann = c.getAnnotation(annotation); - if (ann.annotationType().isAnnotationPresent(Inherited.class) && - inherited.containsKey(ann)) { - continue; - } - anns.add(ann); - inherited.put(ann, ann); - } - } - - Collections.reverse(anns); - return anns; - } - - /** - * Get an annotated element's {@link Seed} annotation and determine if it's fixed - * or not. If it is fixed, return the seeds. Otherwise return randomSeed. - */ - private long [] seedFromAnnot(AnnotatedElement element, long randomSeed) { - Seed seed = element.getAnnotation(Seed.class); - String seedChain = seed.value(); - if (seedChain.equals("random")) { - return new long [] { randomSeed }; - } - - return SeedUtils.parseSeedChain(seedChain); - } - - /** - * Stack trace formatting utilities. These may be initialized to filter out certain packages. - */ - public TraceFormatting getTraceFormatting() { - return traces; - } - - /** - * {@link RandomizedRunner} augments stack traces of test methods that ended in an exception - * and inserts a fake entry starting with {@link #AUGMENTED_SEED_PACKAGE}. - * - * @return A string is returned with seeds combined, if any. Null is returned if no augmentation - * can be found. - */ - public static String seedFromThrowable(Throwable t) { - StringBuilder b = new StringBuilder(); - while (t != null) { - for (StackTraceElement s : t.getStackTrace()) { - if (s.getClassName().startsWith(AUGMENTED_SEED_PACKAGE)) { - if (b.length() > 0) b.append(", "); - b.append(s.getFileName()); - } - } - t = t.getCause(); - } - - if (b.length() == 0) - return null; - else - return b.toString(); - } - - /** - * Attempts to extract just the method name from parameterized notation. - */ - public static String methodName(Description description) { - return description.getMethodName().replaceAll("\\s?\\{.+\\}", ""); - } - - /** - * Returns true if any previous (or current) suite marked with - * {@link Consequence#IGNORE_REMAINING_TESTS} has - * left zombie threads. - */ - public static boolean hasZombieThreads() { - return zombieMarker.get(); - } -} diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/RandomizedTest.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/RandomizedTest.java deleted file mode 100644 index fd9d02ab..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/RandomizedTest.java +++ /dev/null @@ -1,891 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import java.io.Closeable; -import java.io.IOException; -import java.net.ServerSocket; -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; -import java.nio.file.*; -import java.nio.file.attribute.BasicFileAttributes; -import java.text.SimpleDateFormat; -import java.util.Arrays; -import java.util.Comparator; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Random; -import java.util.TimeZone; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.function.Supplier; - -import org.junit.Assume; -import org.junit.AssumptionViolatedException; -import org.junit.runner.RunWith; - -import com.carrotsearch.randomizedtesting.annotations.Listeners; -import com.carrotsearch.randomizedtesting.annotations.Nightly; -import com.carrotsearch.randomizedtesting.annotations.SuppressForbidden; -import com.carrotsearch.randomizedtesting.generators.BiasedNumbers; -import com.carrotsearch.randomizedtesting.generators.RandomBytes; -import com.carrotsearch.randomizedtesting.generators.RandomNumbers; -import com.carrotsearch.randomizedtesting.generators.RandomPicks; -import com.carrotsearch.randomizedtesting.generators.RandomStrings; - -/** - * Common scaffolding for subclassing randomized tests. - * - * @see Listeners - * @see RandomizedContext - */ -@RunWith(RandomizedRunner.class) -public class RandomizedTest { - /** - * The global multiplier property (Double). - * - * @see #multiplier() - */ - public static final String SYSPROP_MULTIPLIER = "randomized.multiplier"; - - /* Commonly used charsets (these must be supported by every JVM). */ - - protected static final Charset UTF8 = StandardCharsets.UTF_8; - protected static final Charset UTF16 = StandardCharsets.UTF_16; - protected static final Charset ISO8859_1 = StandardCharsets.ISO_8859_1; - protected static final Charset US_ASCII = StandardCharsets.US_ASCII; - - /* This charset does not need to be supported, but I don't know any JVM under which it wouldn't be. */ - - protected static final Charset UTF32 = Charset.forName("UTF-32"); - - /** - * Default multiplier. - * - * @see #SYSPROP_MULTIPLIER - */ - private static final double DEFAULT_MULTIPLIER = 1.0d; - - /** - * Shortcut for {@link RandomizedContext#current()}. - */ - public static RandomizedContext getContext() { - return RandomizedContext.current(); - } - - /** - * Returns true if {@link Nightly} test group is enabled. - * - * @see Nightly - */ - public static boolean isNightly() { - return getContext().isNightly(); - } - - /** - * Shortcut for {@link RandomizedContext#getRandom()}. Even though this method - * is static, it returns per-thread {@link Random} instance, so no race conditions - * can occur. - * - *

      It is recommended that specific methods are used to pick random values. - */ - public static Random getRandom() { - return getContext().getRandom(); - } - - // - // Random value pickers. Shortcuts to methods in {@link #getRandom()} mostly. - // - - public static boolean randomBoolean() { return getRandom().nextBoolean(); } - public static byte randomByte() { return (byte) getRandom().nextInt(); } - public static short randomShort() { return (short) getRandom().nextInt(); } - public static int randomInt() { return getRandom().nextInt(); } - public static float randomFloat() { return getRandom().nextFloat(); } - public static double randomDouble() { return getRandom().nextDouble(); } - public static long randomLong() { return getRandom().nextLong(); } - - /** @see Random#nextGaussian() */ - public static double randomGaussian() { return getRandom().nextGaussian(); } - - // - // Biased value pickers. - // - - /** - * A biased "evil" random float between min and max (inclusive). - * - * @see BiasedNumbers#randomFloatBetween(Random, float, float) - */ - public static float biasedFloatBetween(float min, float max) { return BiasedNumbers.randomFloatBetween(getRandom(), min, max); } - - /** - * A biased "evil" random double between min and max (inclusive). - * - * @see BiasedNumbers#randomDoubleBetween(Random, double, double) - */ - public static double biasedDoubleBetween(double min, double max) { return BiasedNumbers.randomDoubleBetween(getRandom(), min, max); } - - // - // Delegates to RandomBytes. - // - - /** - * Returns a byte array with random content. - * - * @param length The length of the byte array. Can be zero. - * @return Returns a byte array with random content. - */ - public static byte[] randomBytesOfLength(int length) { - return RandomBytes.randomBytesOfLength(new Random(getRandom().nextLong()), length); - } - - /** - * Returns a byte array with random content. - * - * @param minLength The minimum length of the byte array. Can be zero. - * @param maxLength The maximum length of the byte array. Can be zero. - * @return Returns a byte array with random content. - */ - public static byte[] randomBytesOfLength(int minLength, int maxLength) { - return RandomBytes.randomBytesOfLengthBetween(new Random(getRandom().nextLong()), minLength, maxLength); - } - - // - // Delegates to RandomNumbers. - // - - /** - * A random integer from 0..max (inclusive). - */ - @Deprecated - public static int randomInt(int max) { - return RandomNumbers.randomIntBetween(getRandom(), 0, max); - } - - /** - * A random long from 0..max (inclusive). - */ - @Deprecated - public static long randomLong(long max) { - return RandomNumbers.randomLongBetween(getRandom(), 0, max); - } - - /** - * A random integer from min to max (inclusive). - * - * @see #scaledRandomIntBetween(int, int) - */ - public static int randomIntBetween(int min, int max) { - return RandomNumbers.randomIntBetween(getRandom(), min, max); - } - - /** - * An alias for {@link #randomIntBetween(int, int)}. - * - * @see #scaledRandomIntBetween(int, int) - */ - public static int between(int min, int max) { - return randomIntBetween(min, max); - } - - /** - * A random long from min to max (inclusive). - */ - public static long randomLongBetween(long min, long max) { - return RandomNumbers.randomLongBetween(getRandom(), min, max); - } - - /** - * An alias for {@link #randomLongBetween}. - */ - public static long between(long min, long max) { - return randomLongBetween(min, max); - } - - /** - * Returns a random value greater or equal to min. The value - * picked is affected by {@link #isNightly()} and {@link #multiplier()}. - * - * @see #scaledRandomIntBetween(int, int) - */ - public static int atLeast(int min) { - if (min < 0) throw new IllegalArgumentException("atLeast requires non-negative argument: " + min); - return scaledRandomIntBetween(min, Integer.MAX_VALUE); - } - - /** - * Returns a non-negative random value smaller or equal max. The value - * picked is affected by {@link #isNightly()} and {@link #multiplier()}. - * - *

      This method is effectively an alias to: - *

      -   * scaledRandomIntBetween(0, max)
      -   * 
      - * - * @see #scaledRandomIntBetween(int, int) - */ - public static int atMost(int max) { - if (max < 0) throw new IllegalArgumentException("atMost requires non-negative argument: " + max); - return scaledRandomIntBetween(0, max); - } - - /** - * Rarely returns true in about 10% of all calls (regardless of the - * {@link #isNightly()} mode). - */ - public static boolean rarely() { - return randomInt(100) >= 90; - } - - /** - * The exact opposite of {@link #rarely()}. - */ - public static boolean frequently() { - return !rarely(); - } - - // - // Delegates to RandomPicks - // - - /** - * Pick a random object from the given array. The array must not be empty. - */ - public static T randomFrom(T [] array) { - return RandomPicks.randomFrom(getRandom(), array); - } - - /** - * Pick a random object from the given list. - */ - public static T randomFrom(List list) { - return RandomPicks.randomFrom(getRandom(), list); - } - - public static byte randomFrom(byte [] array) { return RandomPicks.randomFrom(getRandom(), array); } - public static short randomFrom(short [] array) { return RandomPicks.randomFrom(getRandom(), array); } - public static int randomFrom(int [] array) { return RandomPicks.randomFrom(getRandom(), array); } - public static char randomFrom(char [] array) { return RandomPicks.randomFrom(getRandom(), array); } - public static float randomFrom(float [] array) { return RandomPicks.randomFrom(getRandom(), array); } - public static long randomFrom(long [] array) { return RandomPicks.randomFrom(getRandom(), array); } - public static double randomFrom(double [] array) { return RandomPicks.randomFrom(getRandom(), array); } - - // - // "multiplied" or scaled value pickers. These will be affected by global multiplier. - // - - /** - * A multiplier can be used to linearly scale certain values. It can be used to make data - * or iterations of certain tests "heavier" for nightly runs, for example. - * - *

      The default multiplier value is 1.

      - * - * @see #SYSPROP_MULTIPLIER - */ - public static double multiplier() { - checkContext(); - return systemPropertyAsDouble(SYSPROP_MULTIPLIER, DEFAULT_MULTIPLIER); - } - - /** - * Returns a "scaled" number of iterations for loops which can have a variable - * iteration count. This method is effectively - * an alias to {@link #scaledRandomIntBetween(int, int)}. - */ - public static int iterations(int min, int max) { - return scaledRandomIntBetween(min, max); - } - - /** - * Returns a "scaled" random number between min and max (inclusive). The number of - * iterations will fall between [min, max], but the selection will also try to - * achieve the points below: - *
        - *
      • the multiplier can be used to move the number of iterations closer to min - * (if it is smaller than 1) or closer to max (if it is larger than 1). Setting - * the multiplier to 0 will always result in picking min.
      • - *
      • on normal runs, the number will be closer to min than to max.
      • - *
      • on nightly runs, the number will be closer to max than to min.
      • - *
      - * - * @see #multiplier() - * - * @param min Minimum (inclusive). - * @param max Maximum (inclusive). - * @return Returns a random number between min and max. - */ - public static int scaledRandomIntBetween(int min, int max) { - if (min < 0) throw new IllegalArgumentException("min must be >= 0: " + min); - if (min > max) throw new IllegalArgumentException("max must be >= min: " + min + ", " + max); - - double point = Math.min(1, Math.abs(randomGaussian()) * 0.3) * multiplier(); - double range = max - min; - int scaled = (int) Math.round(Math.min(point * range, range)); - if (isNightly()) { - return max - scaled; - } else { - return min + scaled; - } - } - - // Methods to help with I/O and environment. - - /** - * @see #globalTempDir() - */ - private static Path globalTempDir; - - /** */ - private static AtomicInteger tempSubFileNameCount = new AtomicInteger(0); - - /** - * Global temporary directory created for the duration of this class's lifespan. If - * multiple class loaders are used, there may be more global temp dirs, but it - * shouldn't really be the case in practice. - */ - public static Path globalTempDir() throws IOException { - checkContext(); - synchronized (RandomizedTest.class) { - if (globalTempDir == null) { - String tempDirPath = System.getProperty("java.io.tmpdir"); - if (tempDirPath == null) - throw new IOException("No property java.io.tmpdir?"); - - Path tempDir = Paths.get(tempDirPath); - if (!Files.isDirectory(tempDir) || !Files.isWritable(tempDir)) { - throw new IOException("Temporary folder not accessible: " + tempDir.toAbsolutePath()); - } - - globalTempDir = createTemp(tempDir, true, () -> { - SimpleDateFormat tsFormat = new SimpleDateFormat("'tests-'yyyyMMddHHmmss'-'SSS", Locale.ROOT); - return tsFormat.format(new Date()); - }); - - Runtime.getRuntime().addShutdownHook(new Thread() { - @SuppressForbidden("Legitimate use of syserr.") - public void run() { - try { - rmDir(globalTempDir); - } catch (IOException e) { - // Not much else to do but to log and quit. - System.err.println("Could not delete global temporary folder: " - + globalTempDir.toAbsolutePath() + ". Cause: "); - e.printStackTrace(System.err); - } - } - }); - } - return globalTempDir; - } - } - - private static Path createTemp(Path parent, boolean dir, Supplier nameSupplier) throws IOException { - int retries = 10; - Path target; - do { - try { - Path candidate = parent.resolve(nameSupplier.get()); - if (dir) { - target = Files.createDirectory(candidate); - } else { - target = Files.createFile(candidate); - } - break; - } catch (FileAlreadyExistsException e) { - if (--retries < 0) { - throw new IOException("Could not create a unique temporary folder under: " + parent); - } - try { - Thread.sleep(new Random().nextInt(250)); - } catch (InterruptedException ex) { - throw new IOException(ex); - } - } - } while (true); - return target; - } - - /** - * Creates a new temporary directory for the {@link LifecycleScope#TEST} duration. - * - * @see #globalTempDir() - */ - public Path newTempDir() throws IOException { - return newTempDir(LifecycleScope.TEST); - } - - /** - * Creates a temporary directory, deleted after the given lifecycle phase. - * Temporary directory is created relative to a globally picked temporary directory. - */ - public static Path newTempDir(LifecycleScope scope) throws IOException { - checkContext(); - synchronized (RandomizedTest.class) { - Path tempDir = createTemp(globalTempDir(), true, RandomizedTest::nextTempName); - getContext().closeAtEnd(new TempPathResource(tempDir), scope); - return tempDir; - } - } - - /** - * Registers a {@link Closeable} resource that should be closed after the test - * completes. - * - * @return resource (for call chaining). - */ - public T closeAfterTest(T resource) { - return getContext().closeAtEnd(resource, LifecycleScope.TEST); - } - - /** - * Registers a {@link Closeable} resource that should be closed after the suite - * completes. - * - * @return resource (for call chaining). - */ - public static T closeAfterSuite(T resource) { - return getContext().closeAtEnd(resource, LifecycleScope.SUITE); - } - - /** - * Creates a new temporary file for the {@link LifecycleScope#TEST} duration. - */ - public Path newTempFile() throws IOException { - return newTempFile(LifecycleScope.TEST); - } - - /** - * Creates a new temporary file deleted after the given lifecycle phase completes. - * The file is physically created on disk, but is not locked or opened. - */ - public static Path newTempFile(LifecycleScope scope) throws IOException { - checkContext(); - synchronized (RandomizedTest.class) { - Path tempFile = createTemp(globalTempDir(), false, RandomizedTest::nextTempName); - getContext().closeAtEnd(new TempPathResource(tempFile), scope); - return tempFile; - } - } - - /** Next temporary filename. */ - protected static String nextTempName() { - return String.format(Locale.ROOT, "%04d has-space", tempSubFileNameCount.getAndIncrement()); - } - - /** - * Recursively delete a folder. Throws an exception if any failure occurs. - * - * @param path Path to the folder to be (recursively) deleted. The folder must - * exist. - */ - public static void rmDir(Path path) throws IOException { - if (!Files.isDirectory(path)) { - throw new IOException("Not a folder: " + path); - } - - try { - Files.walkFileTree(path, new SimpleFileVisitor() { - @Override - public FileVisitResult postVisitDirectory(Path dir, IOException iterationError) throws IOException { - if (iterationError != null) { - throw iterationError; - } - Files.delete(dir); - return FileVisitResult.CONTINUE; - } - - @Override - public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { - Files.delete(file); - return FileVisitResult.CONTINUE; - } - - @Override - public FileVisitResult visitFileFailed(Path file, IOException e) throws IOException { - throw e; - } - }); - } catch (IOException e) { - throw new IOException("Could not remove directory: " + path, e); - } - } - - /** - * Assign a temporary server socket. If you need a temporary port one can - * assign a server socket and close it immediately, just to acquire its port - * number. - * - * @param scope - * The lifecycle scope to close the socket after. If the socket is - * closed earlier, nothing happens (silently dropped). - */ - public static ServerSocket newServerSocket(LifecycleScope scope) throws IOException { - final ServerSocket socket = new ServerSocket(0); - getContext().closeAtEnd(new Closeable() { - public void close() throws IOException { - if (!socket.isClosed()) - socket.close(); - } - }, scope); - - return socket; - } - - /** - * Return a random Locale from the available locales on the system. - * - *

      Warning: This test assumes the returned array of locales is repeatable from jvm execution - * to jvm execution. It _may_ be different from jvm to jvm and as such, it can render - * tests execute in a different way.

      - */ - public static Locale randomLocale() { - Locale[] availableLocales = Locale.getAvailableLocales(); - Arrays.sort(availableLocales, new Comparator() { - public int compare(Locale o1, Locale o2) { - return o1.toString().compareTo(o2.toString()); - } - }); - return randomFrom(availableLocales); - } - - /** - * Return a random TimeZone from the available timezones on the system. - * - *

      Warning: This test assumes the returned array of time zones is repeatable from jvm execution - * to jvm execution. It _may_ be different from jvm to jvm and as such, it can render - * tests execute in a different way.

      - */ - public static TimeZone randomTimeZone() { - final String[] availableIDs = TimeZone.getAvailableIDs(); - Arrays.sort(availableIDs); - return TimeZone.getTimeZone(randomFrom(availableIDs)); - } - - // - // Characters and strings. Delegates to RandomStrings and that in turn to StringGenerators. - // - - /** - * @deprecated Use {@link #randomAsciiLettersOfLengthBetween} instead. - */ - @Deprecated - public static String randomAsciiOfLengthBetween(int minCodeUnits, int maxCodeUnits) { - return randomAsciiLettersOfLengthBetween(minCodeUnits, maxCodeUnits); - } - - /** - * @deprecated Use {@link #randomAsciiLettersOfLength} instead. - */ - @Deprecated - public static String randomAsciiOfLength(int codeUnits) { - return randomAsciiLettersOfLength(codeUnits); - } - - /** - * @see RandomStrings#randomAsciiLettersOfLengthBetween - */ - public static String randomAsciiLettersOfLengthBetween(int minLetters, int maxLetters) { - return RandomStrings.randomAsciiLettersOfLengthBetween(getRandom(), minLetters, maxLetters); - } - - /** - * @see RandomStrings#randomAsciiLettersOfLength - */ - public static String randomAsciiLettersOfLength(int codeUnits) { - return RandomStrings.randomAsciiLettersOfLength(getRandom(), codeUnits); - } - - /** - * @see RandomStrings#randomAsciiAlphanumOfLengthBetween - */ - public static String randomAsciiAlphanumOfLengthBetween(int minCodeUnits, int maxCodeUnits) { - return RandomStrings.randomAsciiAlphanumOfLengthBetween(getRandom(), minCodeUnits, maxCodeUnits); - } - - /** - * @see RandomStrings#randomAsciiAlphanumOfLength - */ - public static String randomAsciiAlphanumOfLength(int codeUnits) { - return RandomStrings.randomAsciiAlphanumOfLength(getRandom(), codeUnits); - } - - /** - * @see RandomStrings#randomUnicodeOfLengthBetween - */ - public static String randomUnicodeOfLengthBetween(int minCodeUnits, int maxCodeUnits) { - return RandomStrings.randomUnicodeOfLengthBetween(getRandom(), - minCodeUnits, maxCodeUnits); - } - - /** - * @see RandomStrings#randomUnicodeOfLength - */ - public static String randomUnicodeOfLength(int codeUnits) { - return RandomStrings.randomUnicodeOfLength(getRandom(), codeUnits); - } - - /** - * @see RandomStrings#randomUnicodeOfCodepointLengthBetween - */ - public static String randomUnicodeOfCodepointLengthBetween(int minCodePoints, int maxCodePoints) { - return RandomStrings.randomUnicodeOfCodepointLengthBetween(getRandom(), - minCodePoints, maxCodePoints); - } - - /** - * @see RandomStrings#randomUnicodeOfCodepointLength - */ - public static String randomUnicodeOfCodepointLength(int codePoints) { - return RandomStrings.randomUnicodeOfCodepointLength(getRandom(), codePoints); - } - - /** - * @see RandomStrings#randomRealisticUnicodeOfLengthBetween - */ - public static String randomRealisticUnicodeOfLengthBetween(int minCodeUnits, int maxCodeUnits) { - return RandomStrings.randomRealisticUnicodeOfLengthBetween(getRandom(), - minCodeUnits, maxCodeUnits); - } - - /** - * @see RandomStrings#randomRealisticUnicodeOfLength - */ - public static String randomRealisticUnicodeOfLength(int codeUnits) { - return RandomStrings.randomRealisticUnicodeOfLength(getRandom(), codeUnits); - } - - /** - * @see RandomStrings#randomRealisticUnicodeOfCodepointLengthBetween - */ - public static String randomRealisticUnicodeOfCodepointLengthBetween( - int minCodePoints, int maxCodePoints) { - return RandomStrings.randomRealisticUnicodeOfCodepointLengthBetween( - getRandom(), minCodePoints, maxCodePoints); - } - - /** - * @see RandomStrings#randomRealisticUnicodeOfCodepointLength - */ - public static String randomRealisticUnicodeOfCodepointLength(int codePoints) { - return RandomStrings.randomRealisticUnicodeOfCodepointLength(getRandom(), - codePoints); - } - - /** - * This is an absolutely hacky utility to take a vararg as input and return the array - * of arguments as output. The name is a dollar for brevity, idea borrowed from - * http://code.google.com/p/junitparams/. - */ - public static Object [] $(Object... objects) { - return objects; - } - - /** - * @see #$ - */ - public static Object [][] $$(Object[]... objects) { - return objects; - } - - // - // wrappers for utility methods elsewhere that don't require try..catch blocks - // and rethrow the original checked exception if needed. dirty a bit, but saves - // keystrokes... - // - - /** - * Same as {@link Thread#sleep(long)}. - */ - public static void sleep(long millis) { - try { - Thread.sleep(millis); - } catch (InterruptedException e) { - Rethrow.rethrow(e); - } - } - - // - // Extensions of Assume (with a message). - // - - /** - * Making {@link Assume#assumeTrue(boolean)} directly available. - */ - public static void assumeTrue(boolean condition) { - Assume.assumeTrue(condition); - } - - /** - * Reverse of {@link #assumeTrue(boolean)}. - */ - public static void assumeFalse(boolean condition) { - assumeTrue(!condition); - } - - /** - * Making {@link Assume#assumeNotNull(Object...)} directly available. - */ - public static void assumeNotNull(Object... objects) { - Assume.assumeNotNull(objects); - } - - /** - * @param condition - * If false an {@link AssumptionViolatedException} is - * thrown by this method and the test case (should be) ignored (or - * rather technically, flagged as a failure not passing a certain - * assumption). Tests that are assumption-failures do not break - * builds (again: typically). - * @param message - * Message to be included in the exception's string. - */ - public static void assumeTrue(String message, boolean condition) { - if (!condition) { - // @see {@link Rants#RANT_2}. - throw new AssumptionViolatedException(message); - } - } - - /** - * Reverse of {@link #assumeTrue(String, boolean)}. - */ - public static void assumeFalse(String message, boolean condition) { - assumeTrue(message, !condition); - } - - /** - * Assume t is null. - */ - public static void assumeNoException(String msg, Throwable t) { - if (t != null) { - // This does chain the exception as the cause. - throw new AssumptionViolatedException(msg, t); - } - } - - /** - * Making {@link Assume#assumeNoException(Throwable)} directly available. - */ - public static void assumeNoException(Throwable t) { - Assume.assumeNoException(t); - } - - // - // System properties and their conversion to common types, with defaults. - // - - /** - * Get a system property and convert it to a double, if defined. Otherwise, return the default value. - */ - public static double systemPropertyAsDouble(String propertyName, double defaultValue) { - String v = System.getProperty(propertyName); - if (v != null && !v.trim().isEmpty()) { - try { - return Double.parseDouble(v.trim()); - } catch (NumberFormatException e) { - throw new IllegalArgumentException("Double value expected for property " + - propertyName + ": " + v, e); - } - } else { - return defaultValue; - } - } - - /** - * Get a system property and convert it to a float, if defined. Otherwise, return the default value. - */ - public static float systemPropertyAsFloat(String propertyName, float defaultValue) { - String v = System.getProperty(propertyName); - if (v != null && !v.trim().isEmpty()) { - try { - return Float.parseFloat(v.trim()); - } catch (NumberFormatException e) { - throw new IllegalArgumentException("Float value expected for property " + - propertyName + ": " + v, e); - } - } else { - return defaultValue; - } - } - - /** - * Get a system property and convert it to an int, if defined. Otherwise, return the default value. - */ - public static int systemPropertyAsInt(String propertyName, int defaultValue) { - String v = System.getProperty(propertyName); - if (v != null && !v.trim().isEmpty()) { - try { - return Integer.parseInt(v.trim()); - } catch (NumberFormatException e) { - throw new IllegalArgumentException("Integer value expected for property " + - propertyName + ": " + v, e); - } - } else { - return defaultValue; - } - } - - /** - * Get a system property and convert it to a long, if defined. Otherwise, return the default value. - */ - public static float systemPropertyAsLong(String propertyName, int defaultValue) { - String v = System.getProperty(propertyName); - if (v != null && !v.trim().isEmpty()) { - try { - return Long.parseLong(v.trim()); - } catch (NumberFormatException e) { - throw new IllegalArgumentException("Long value expected for property " + - propertyName + ": " + v, e); - } - } else { - return defaultValue; - } - } - - /** Boolean constants mapping. */ - @SuppressWarnings("serial") - private final static HashMap BOOLEANS = new HashMap() {{ - put( "true", true); put( "false", false); - put( "on", true); put( "off", false); - put( "yes", true); put( "no", false); - put("enabled", true); put("disabled", false); - }}; - - /** - * Get a system property and convert it to a boolean, if defined. This method returns - * true if the property exists an is set to any of the following strings - * (case-insensitive): true, on, yes, enabled. - * - *

      false is returned if the property exists and is set to any of the - * following strings (case-insensitive): - * false, off, no, disabled. - */ - public static boolean systemPropertyAsBoolean(String propertyName, boolean defaultValue) { - String v = System.getProperty(propertyName); - - if (v != null && !v.trim().isEmpty()) { - v = v.trim(); - Boolean result = BOOLEANS.get(v); - if (result != null) - return result.booleanValue(); - else - throw new IllegalArgumentException("Boolean value expected for property " + - propertyName + " " + - "(true/false, on/off, enabled/disabled, yes/no): " + v); - } else { - return defaultValue; - } - } - - // - // Miscellaneous infrastructure. - // - - /** - * Ensures we're running with an initialized {@link RandomizedContext}. - */ - private static void checkContext() { - // Will throw an exception if not available. - RandomizedContext.current(); - } -} diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/Randomness.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/Randomness.java deleted file mode 100644 index 44aa65d6..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/Randomness.java +++ /dev/null @@ -1,83 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import java.util.Random; - -/** - * Per-thread, per-lifecycle state randomness defined as an initial seed and - * the current Random instance. - * - *

      An instance of this class will be typically available from {@link RandomizedContext}. - * No need to instantiate manually. - * - * @see RandomizedContext - */ -public final class Randomness { - private final long seed; - private final Random random; - - private final RandomSupplier supplier; - private final SeedDecorator[] decorators; - - public Randomness(Thread owner, RandomSupplier supplier, long seed, SeedDecorator... decorators) { - this.seed = seed; - this.decorators = decorators; - this.supplier = supplier; - - Random delegate = supplier.get(decorate(seed, decorators)); - if (AssertingRandom.isVerifying()) { - this.random = new AssertingRandom(owner, delegate); - } else { - this.random = delegate; - } - } - - public Randomness(long seed, RandomSupplier supplier, SeedDecorator...decorators) { - this(Thread.currentThread(), supplier, seed, decorators); - } - - /** Random instance for this randomness. */ - public Random getRandom() { - return random; - } - - RandomSupplier getRandomSupplier() { - return supplier; - } - - SeedDecorator[] getDecorators() { - return decorators; - } - - Randomness clone(Thread newOwner) { - return new Randomness(newOwner, supplier, seed, decorators); - } - - @Override - public String toString() { - return "[Randomness, seed=" + SeedUtils.formatSeedChain(this) + "]"; - } - - /** - * Invalidate the underling randomness. - */ - void destroy() { - if (random instanceof AssertingRandom) { - ((AssertingRandom) random).destroy(); - } - } - - /** Starting seed, read-only for tests. */ - long getSeed() { - return seed; - } - - /** - * Decorate a given seed. - */ - private static long decorate(long seed, SeedDecorator[] decorators) { - for (SeedDecorator decorator : decorators) { - seed = decorator.decorate(seed); - } - return seed; - } -} \ No newline at end of file diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/Rants.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/Rants.java deleted file mode 100644 index d3faf56c..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/Rants.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import java.lang.reflect.Method; - -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; - -/** - * Rants about blocker limitations of JUnit... - */ -final class Rants { - enum RantType { - // General - ANNOYANCE, - DAMN_TERRIBLE, - WTF, - - // Personal - ISHOULDHAVEBECOMEALAWYER - } - - /** - * This if freaking dumb... there's absolutely no way to carry test class/ test name - * separately from the display name, so we can't easily include seed info on the test - * case. If we do, Eclipse complains it cannot find the target class/ test name. If we don't, - * Eclipse's JUnit runner gets confused and doesn't show test case execution properly. - * - * We can't even use a proxy or a subclass because Description has a private constructor. Eh. - * - * Having a Description properly indicate the test case/ class is useful because we could re-run - * a concrete repetition of a given test from the UI. Currently this is impossible - we can - * re-run the entire iteration sequence only (or fix the seed on the method, but this requires - * changes to the code). - */ - public static RantType RANT_1 = RantType.DAMN_TERRIBLE; - - /** - * Default assumption methods (and constructors in AssumptionViolatedException) - * do not allow specifying a custom message? - */ - public static RantType RANT_2 = RantType.ANNOYANCE; - - /** - * Why is failed assumption propagated as a Failure? This is weird an unnatural. - */ - public static RantType RANT_3 = RantType.DAMN_TERRIBLE; - - /** - * JUnit is inconsistent in how it treats annotations on methods. Some of them are "inherited" and - * some require presence on the exact same {@link Method} as the one used for testing. This has awkward - * side effects, for example {@link Ignore} and {@link Test} must co-exist on the same method, not - * on virtual method hierarchy. You cannot make {@link Test} methods protected and publish them in - * subclasses. Shadowing of {@link BeforeClass} methods is inconsistent (non-annotated shadowed method - * will not be called, shadowed method annotated with {@link BeforeClass} prevents the shadowed method - * from being called), etc. - */ - public static RantType RANT_4 = RantType.DAMN_TERRIBLE; -} diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/ReproduceErrorMessageBuilder.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/ReproduceErrorMessageBuilder.java deleted file mode 100644 index a2c39bad..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/ReproduceErrorMessageBuilder.java +++ /dev/null @@ -1,105 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import java.util.Arrays; - -import org.junit.runner.Description; - -import static com.carrotsearch.randomizedtesting.SysGlobals.*; -import static com.carrotsearch.randomizedtesting.RandomizedRunner.*; - -// TODO: [GH-212]: how to provide better reproduce messages (especially with -// external runner tasks that provide system properties, jvm options, etc?) - -/** - * A builder for constructing "reproduce with" message. - * - * @see #appendAllOpts(Description) - */ -public class ReproduceErrorMessageBuilder { - private final StringBuilder b; - - public ReproduceErrorMessageBuilder() { - this(new StringBuilder()); - } - - public ReproduceErrorMessageBuilder(StringBuilder builder) { - this.b = builder; - } - - /** - * Append all JVM options that may help in reproducing the error. Options are - * appended to the provided StringBuilder in the "command-line" syntax of: - *

      -   * -Doption="value"
      -   * 
      - * - * @param description Suite or test description. - */ - public ReproduceErrorMessageBuilder appendAllOpts(Description description) { - RandomizedContext ctx = null; - try { - ctx = RandomizedContext.current(); - appendOpt(SYSPROP_RANDOM_SEED(), ctx.getRunnerSeedAsString()); - } catch (IllegalStateException e) { - logger.warning("No context available when dumping reproduce options?"); - } - - if (description.getClassName() != null) { - appendOpt(SYSPROP_TESTCLASS(), description.getClassName()); - } - - if (description.getMethodName() != null) { - appendOpt(SYSPROP_TESTMETHOD(), methodName(description)); - } - - appendRunnerProperties(); - appendTestGroupOptions(ctx); - appendEnvironmentSettings(); - - return this; - } - - public ReproduceErrorMessageBuilder appendEnvironmentSettings() { - for (String sysPropName : Arrays.asList( - "file.encoding", "user.timezone")) { - if (emptyToNull(System.getProperty(sysPropName)) != null) { - appendOpt(sysPropName, System.getProperty(sysPropName)); - } - } - return this; - } - - public ReproduceErrorMessageBuilder appendTestGroupOptions(RandomizedContext ctx) { - if (ctx != null) { - ctx.getGroupEvaluator().appendGroupFilteringOptions(this); - } - return this; - } - - public ReproduceErrorMessageBuilder appendRunnerProperties() { - appendOpt(SYSPROP_PREFIX(), CURRENT_PREFIX()); - for (String sysPropName : Arrays.asList( - SYSPROP_STACKFILTERING(), - SYSPROP_ITERATIONS(), - SYSPROP_KILLATTEMPTS(), - SYSPROP_KILLWAIT(), - SYSPROP_TIMEOUT())) { - if (System.getProperty(sysPropName) != null) { - appendOpt(sysPropName, System.getProperty(sysPropName)); - } - } - return this; - } - - /** - * Append a single VM option. - */ - public ReproduceErrorMessageBuilder appendOpt(String sysPropName, String value) { - if (b.length() > 0) { - b.append(" "); - } - - b.append("-D").append(sysPropName).append("=").append(value); - return this; - } -} diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/ResourceDisposalError.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/ResourceDisposalError.java deleted file mode 100644 index b593aaa0..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/ResourceDisposalError.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -/** - * Thrown when a resource could not be released. - * - * @see RandomizedContext#closeAtEnd(java.io.Closeable, LifecycleScope) - */ -@SuppressWarnings("serial") -class ResourceDisposalError extends Error { - public ResourceDisposalError(String msg, Throwable cause) { - super(msg, cause); - } -} diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/Rethrow.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/Rethrow.java deleted file mode 100644 index afe9b427..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/Rethrow.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -/** - * Rethrowing checked exceptions as unchecked ones. Eh, it is sometimes useful... - */ -public final class Rethrow { - /** - * Classy puzzler to rethrow any checked exception as an unchecked one. - */ - @SuppressWarnings("all") - private static class Rethrower { - private void rethrow(Throwable t) throws T { - throw (T) t; - } - } - - /** - * Rethrows t (identical object). - */ - public static RuntimeException rethrow(Throwable t) { - new Rethrower().rethrow(t); - // Inaccessible. - return null; - } -} - diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/RunnerContainer.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/RunnerContainer.java deleted file mode 100644 index 0f884a28..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/RunnerContainer.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -/** - * What kind of container are we in? Unfortunately we need to adjust - * to some "assumptions" containers make about runners. - */ -enum RunnerContainer { - ECLIPSE, - IDEA, - UNKNOWN -} \ No newline at end of file diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/RunnerThreadGroup.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/RunnerThreadGroup.java deleted file mode 100644 index 9e51e7b7..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/RunnerThreadGroup.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -/** - * A {@link ThreadGroup} under which all tests (and hooks) are executed. Theoretically, there - * should be no thread outside of this group's control. - */ -final class RunnerThreadGroup extends ThreadGroup { - /* */ - RunnerThreadGroup(String name) { - super(name); - } - - /** - * Capture all uncaught exceptions from this group's threads. - */ - @Override - public void uncaughtException(Thread t, Throwable e) { - // Try to get the context for this thread and augment the exception with the seed. - try { - e = RandomizedRunner.augmentStackTrace(e); - } catch (IllegalArgumentException ignore) { - // Very likely the randomized context has been destroyed. Don't try to augment the exception. - e.addSuppressed(ignore); - } catch (Throwable ignore) { - e.addSuppressed(ignore); - } - - super.uncaughtException(t, e); - } -} diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/SeedDecorator.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/SeedDecorator.java deleted file mode 100644 index ffb466a7..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/SeedDecorator.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import com.carrotsearch.randomizedtesting.annotations.SeedDecorators; - -/** - * This is an advanced feature. See {@link SeedDecorators} annotation. - */ -public interface SeedDecorator { - /** - * Called once after instantiation to set up the decorator. - */ - void initialize(Class suiteClass); - - /** - * Called to decorate the initial seed for a {@link Randomness}. - */ - long decorate(long seed); -} diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/SeedUtils.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/SeedUtils.java deleted file mode 100644 index 6b47c7c9..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/SeedUtils.java +++ /dev/null @@ -1,70 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -/** - * Utilities for parsing random seeds. - */ -public final class SeedUtils { - private final static char [] HEX = "0123456789ABCDEF".toCharArray(); - - private SeedUtils() {} - - /** - * Parse a single seed. The seed needs to be cleaned up from any surrounding characters. - */ - public static long parseSeed(String seed) { - long result = 0; - for (char chr : seed.toCharArray()) { - chr = Character.toLowerCase(chr); - result = result << 4; - if (chr >= '0' && chr <= '9') - result |= (chr - '0'); - else if (chr >= 'a' && chr <= 'f') - result |= (chr - 'a' + 10); - else - throw new IllegalArgumentException("Expected hexadecimal seed: " + seed); - } - return result; - } - - /** - * Format a single seed. - */ - public static String formatSeed(long seed) { - StringBuilder b = new StringBuilder(); - do { - b.append(HEX[(int) (seed & 0xF)]); - seed = seed >>> 4; - } while (seed != 0); - return b.reverse().toString(); - } - - /** - * Parse a seed chain formatted with {@link SeedUtils#formatSeedChain(Randomness...)}. - */ - public static long [] parseSeedChain(String chain) { - chain = chain.replaceAll("[\\[\\]]", ""); - if (!chain.matches("[0-9A-Fa-f\\:]+")) { - throw new IllegalArgumentException("Not a valid seed chain: " + chain); - } - String [] splits = chain.split("[\\:]"); - long [] longs = new long [splits.length]; - for (int i = 0; i < splits.length; i++) - longs[i] = parseSeed(splits[i]); - return longs; - } - - /** - * Formats randomness seed or seeds into something the user can type in to get predictably repeatable - * execution. - */ - public static String formatSeedChain(Randomness... randomnesses) { - StringBuilder b = new StringBuilder(); - b.append("["); - for (int i = 0; i < randomnesses.length; i++) { - if (i > 0) b.append(":"); - b.append(formatSeed(randomnesses[i].getSeed())); - } - b.append("]"); - return b.toString(); - } -} diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/StackTraceHolder.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/StackTraceHolder.java deleted file mode 100644 index 8d4b606a..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/StackTraceHolder.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -/** - * This is never thrown. The only purpose it serves it to carry chained stack traces - * for informational purposes. - */ -@SuppressWarnings("serial") -final class StackTraceHolder extends Throwable { - public StackTraceHolder(String message) { - super(message); - } -} diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/SysGlobals.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/SysGlobals.java deleted file mode 100644 index 471361cd..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/SysGlobals.java +++ /dev/null @@ -1,235 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import org.junit.runners.JUnit4; - -import com.carrotsearch.randomizedtesting.annotations.Repeat; -import com.carrotsearch.randomizedtesting.annotations.Seeds; -import com.carrotsearch.randomizedtesting.rules.RequireAssertionsRule; - -/** - * Global names for system properties controlling the behavior of {@link JUnit4} ANT task - * and {@link RandomizedRunner}. - */ -public final class SysGlobals { - /** System property passed to forked VMs: VM ID (sequential integer between 0 and the (number of concurrent jvms - 1)). */ - public static final String CHILDVM_SYSPROP_JVM_ID = "junit4.childvm.id"; - - /** System property passed to forked VMs: the number of concurrent JVMs. */ - public static final String CHILDVM_SYSPROP_JVM_COUNT = "junit4.childvm.count"; - - private final static Object lock = new Object(); - - /** - * Default prefix for all properties. - */ - private static final String DEFAULT_PREFIX = "tests"; - - /** - * A common prefix for all system properties used by randomizedtesting - * packages. It is discouraged to change this property but it may be used to resolve - * conflicts with packages that have overlapping property names. - */ - private static final String SYSPROP_PREFIX = DEFAULT_PREFIX + ".prefix"; - - /** - * Global singleton. Initialized once. - */ - private static SysGlobals singleton; - - /** - * Singleton initialization stack for easier debugging. - */ - private static StackTraceElement[] singletonInitStack; - - /** Initialized singleton's prefix. */ - private final String prefix; - - /* Property names, rendered. */ - private final String SYSPROP_STACKFILTERING; - private final String SYSPROP_RANDOM_SEED; - private final String SYSPROP_ITERATIONS; - private final String SYSPROP_TESTCLASS; - private final String SYSPROP_TESTMETHOD; - private final String SYSPROP_TESTFILTER; - private final String SYSPROP_KILLATTEMPTS; - private final String SYSPROP_KILLWAIT; - private final String SYSPROP_TIMEOUT; - private final String SYSPROP_TIMEOUT_SUITE; - private final String SYSPROP_APPEND_SEED; - private final String SYSPROP_ASSERTS; - - // Singleton constructor. - private SysGlobals(String prefix) { - this.prefix = prefix; - - this.SYSPROP_STACKFILTERING = prefixWith(prefix, "stackfiltering"); - this.SYSPROP_RANDOM_SEED = prefixWith(prefix, "seed"); - this.SYSPROP_ITERATIONS = prefixWith(prefix, "iters"); - this.SYSPROP_TESTCLASS = prefixWith(prefix, "class"); - this.SYSPROP_TESTMETHOD = prefixWith(prefix, "method"); - this.SYSPROP_TESTFILTER = prefixWith(prefix, "filter"); - this.SYSPROP_KILLATTEMPTS = prefixWith(prefix, "killattempts"); - this.SYSPROP_KILLWAIT = prefixWith(prefix, "killwait"); - this.SYSPROP_TIMEOUT = prefixWith(prefix, "timeout"); - this.SYSPROP_TIMEOUT_SUITE = prefixWith(prefix, "timeoutSuite"); - this.SYSPROP_APPEND_SEED = prefixWith(prefix, "appendseed"); - this.SYSPROP_ASSERTS = prefixWith(prefix, "asserts"); - } - - /** */ - private String prefixWith(String prefix, String propertyName) { - if (prefix.isEmpty()) { - return propertyName; - } else { - return prefix + (prefix.endsWith(".") ? "" : ".") + propertyName; - } - } - - /** */ - private static SysGlobals singleton() { - synchronized (lock) { - if (singleton == null) { - String prefix = System.getProperty(SYSPROP_PREFIX); - if (prefix == null) { - prefix = DEFAULT_PREFIX; - } - initializeWith(prefix); - } - return singleton; - } - } - - /** */ - public static SysGlobals initializeWith(String prefix) { - if (prefix == null) { - throw new IllegalArgumentException("Prefix must not be null."); - } - - synchronized (lock) { - if (singleton == null) { - singleton = new SysGlobals(prefix); - singletonInitStack = Thread.currentThread().getStackTrace(); - } - - if (!singleton.prefix.equals(prefix)) { - Exception e = new Exception("Original singleton initialization stack."); - e.setStackTrace(singletonInitStack); - throw new RuntimeException("A singleton has been initialized already with a " + - "different prefix: existing=" + singleton.prefix + ", attempted=" + prefix, e); - } - - return singleton; - } - } - - /** - * Global system property that holds the prefix used by other properties. - */ - public static String SYSPROP_PREFIX() { return SYSPROP_PREFIX; } - - /** - * Static singleton's property prefix. Initializes it if not already initialized. - */ - public static String CURRENT_PREFIX() { return singleton().prefix; } - - /** - * Enable or disable stack filtering. - */ - public static String SYSPROP_STACKFILTERING() { return singleton().SYSPROP_STACKFILTERING; } - - /** - * System property with an integer defining global initialization seeds for all - * random generators. Should guarantee test reproducibility. - */ - public static String SYSPROP_RANDOM_SEED() { return singleton().SYSPROP_RANDOM_SEED; } - - /** - * The global override for the number of each test's repetitions. - */ - public static String SYSPROP_ITERATIONS() { return singleton().SYSPROP_ITERATIONS; } - - /** - * Global override for picking out a single test class to execute. All other - * classes are ignored. The property can contain "globbing patterns" similar - * to shell expansion patterns. For example: - *
      -   * *MyTest
      -   * 
      - * will pick all classes ending in MyTest (in any package, including nested static - * classes if they appear on input). - */ - public static String SYSPROP_TESTCLASS() { return singleton().SYSPROP_TESTCLASS; } - - /** - * Global override for picking out a single test method to execute. If a - * matching method exists in more than one class, it will be executed. - */ - public static String SYSPROP_TESTMETHOD() { return singleton().SYSPROP_TESTMETHOD; } - - /** - * Global test filter. - */ - public static String SYSPROP_TESTFILTER() { return singleton().SYSPROP_TESTFILTER; } - - /** - * If there's a runaway thread, how many times do we try to interrupt and - * then kill it before we give up? Runaway threads may affect other tests (bad idea). - */ - public static String SYSPROP_KILLATTEMPTS() { return singleton().SYSPROP_KILLATTEMPTS; } - - /** - * If there's a runaway thread, how long should we wait between iterations of - * putting a silver bullet through its heart? - */ - public static String SYSPROP_KILLWAIT() { return singleton().SYSPROP_KILLWAIT; } - - /** - * Global override for a single test case's maximum execution time after which - * it is considered out of control and an attempt to interrupt it is executed. - * - *

      The timeout value should be in milliseconds. If the value is trailed by a - * "!" then the timeout value takes precedence over annotations, otherwise annotations - * take precedence over the default timeout. This is useful for running debugging - * sessions, for example, when default timeouts may be too short. - * - * @see RandomizedRunner#DEFAULT_TIMEOUT - */ - public static String SYSPROP_TIMEOUT() { return singleton().SYSPROP_TIMEOUT; } - - /** - * Global override for entire suite's maximum execution time after which - * it is considered out of control. - * - *

      The timeout value should be in milliseconds. If the value is trailed by a - * "!" then the timeout value takes precedence over annotations, otherwise annotations - * take precedence over the default timeout. This is useful for running debugging - * sessions, for example, when default timeouts may be too short. - * - * @see RandomizedRunner#DEFAULT_TIMEOUT_SUITE - */ - public static String SYSPROP_TIMEOUT_SUITE() { return singleton().SYSPROP_TIMEOUT_SUITE; } - - /** - * If true, append seed parameter to all methods. Methods that are for some - * reason repeated (due to {@link Repeat} annotation or multiple {@link Seeds}, for example) - * are always postfixed with the seed to discriminate tests from each other. Otherwise many - * GUI clients have a problem in telling which test result was which. - */ - public static String SYSPROP_APPEND_SEED() { return singleton().SYSPROP_APPEND_SEED; } - - /** - * Returns the property name to express the desired status of assertions during tests. - * - * @see RequireAssertionsRule - */ - public static String SYSPROP_ASSERTS() { return singleton().SYSPROP_ASSERTS; } - - /** - * Prefix a given property name with a common prefix. The prefix itself can be overridden - * using SYSPROP_PREFIX. This method initializes static singleton property - * names so it shouldn't be called on class initialization anywhere. - */ - public static String prefixProperty(String propertyName) { - return singleton().prefixWith(singleton.prefix, propertyName); - } -} diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/TeeOutputStream.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/TeeOutputStream.java deleted file mode 100644 index aae91edc..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/TeeOutputStream.java +++ /dev/null @@ -1,163 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import java.io.IOException; -import java.io.OutputStream; - -/** - * Custom teeing stream that ensures both streams receive the output and - * no exceptions are quietly suppressed. - */ -public class TeeOutputStream extends OutputStream { - private final OutputStream first; - private final OutputStream second; - - public TeeOutputStream(OutputStream first, OutputStream second) { - this.first = first; - this.second = second; - } - - @Override - public void write(int b) throws IOException { - IOException ex = null; - - try { - first.write(b); - } catch (IOException e) { - ex = e; - } - - try { - second.write(b); - } catch (IOException e) { - if (ex != null) { - ex.addSuppressed(e); - } else { - ex = e; - } - } - - if (ex != null) { - throw ex; - } - } - - @Override - public void write(byte[] b, int off, int len) throws IOException { - IOException ex = null; - - try { - first.write(b, off, len); - } catch (IOException e) { - ex = e; - } - - try { - second.write(b, off, len); - } catch (IOException e) { - if (ex != null) { - ex.addSuppressed(e); - } else { - ex = e; - } - } - - if (ex != null) { - throw ex; - } - } - - @Override - public void close() throws IOException { - IOException ex = null; - - try { - first.close(); - } catch (IOException e) { - ex = e; - } - - try { - second.close(); - } catch (IOException e) { - if (ex != null) { - ex.addSuppressed(e); - } else { - ex = e; - } - } - - if (ex != null) { - throw ex; - } - } - - @Override - public void flush() throws IOException { - IOException ex = null; - - try { - first.flush(); - } catch (IOException e) { - ex = e; - } - - try { - second.flush(); - } catch (IOException e) { - if (ex != null) { - ex.addSuppressed(e); - } else { - ex = e; - } - } - - if (ex != null) { - throw ex; - } - } - - @Override - public void write(byte[] b) throws IOException { - IOException ex = null; - - try { - first.write(b); - } catch (IOException e) { - ex = e; - } - - try { - second.write(b); - } catch (IOException e) { - if (ex != null) { - ex.addSuppressed(e); - } else { - ex = e; - } - } - - if (ex != null) { - throw ex; - } - } - - @Override - public String toString() { - return "[tee: 1:" + first + ", 2:" + second + "]"; - } - - @Override - public boolean equals(Object obj) { - throw new UnsupportedOperationException(); - } - - @Override - public int hashCode() { - throw new UnsupportedOperationException(); - } - - @Override - protected Object clone() throws CloneNotSupportedException { - throw new CloneNotSupportedException(); - } -} diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/TempPathResource.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/TempPathResource.java deleted file mode 100644 index 5506c4f4..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/TempPathResource.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import java.io.*; -import java.nio.file.Files; -import java.nio.file.Path; - -/** - * A temporary path resource will be deleted at the end of a given lifecycle phase. - * - * @see RandomizedContext#closeAtEnd(Closeable, LifecycleScope) - * @see RandomizedTest#newTempDir() - */ -public class TempPathResource implements Closeable { - private final Path location; - - public TempPathResource(Path location) { - this.location = location; - } - - public void close() throws IOException { - if (Files.isDirectory(location)) { - RandomizedTest.rmDir(location); - } else { - Files.deleteIfExists(location); - } - } -} diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/TestMethodAndParams.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/TestMethodAndParams.java deleted file mode 100644 index 6db86384..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/TestMethodAndParams.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import java.lang.reflect.Method; -import java.util.List; - -import com.carrotsearch.randomizedtesting.annotations.TestCaseOrdering; - -/** - * A single test case entry composed of the test method - * and the arguments eventually passed to the test class's constructor. - * - * @see TestCaseOrdering - */ -public interface TestMethodAndParams { - Method getTestMethod(); - List getInstanceArguments(); -} diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/TestMethodProvider.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/TestMethodProvider.java deleted file mode 100644 index 6fc35cbb..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/TestMethodProvider.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import java.lang.reflect.Method; -import java.util.Collection; - -/** - * Responsible for providing individual test instances and their descriptions. Also - * performs class validation to ensure test methods are valid. - */ -public interface TestMethodProvider { - /** - * Determine which methods are test methods. The contract is that methods must - * be public, instance bound (not static) and parameterless. No other - * restrictions apply (as if these weren't enough...). - * - * @param suiteClass - * The suite class. - * @param suiteClassModel - * A precomputed model of the suite class including method annotations and - * class hierarchy walking utilities. This is made available for performance - * reasons only. - * @return Return a set of methods which should be invoked by the runner as - * tests. - */ - Collection getTestMethods(Class suiteClass, ClassModel suiteClassModel); -} diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/ThreadFilter.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/ThreadFilter.java deleted file mode 100644 index 8ac48565..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/ThreadFilter.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakFilters; - -/** - * @see ThreadLeakFilters - */ -public interface ThreadFilter { - /** - * @return Return true if thread t should be - * filtered out. - */ - public boolean reject(Thread t); -} \ No newline at end of file diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/ThreadLeakControl.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/ThreadLeakControl.java deleted file mode 100644 index 9a724c15..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/ThreadLeakControl.java +++ /dev/null @@ -1,940 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import static com.carrotsearch.randomizedtesting.RandomizedRunner.DEFAULT_KILLATTEMPTS; -import static com.carrotsearch.randomizedtesting.RandomizedRunner.DEFAULT_KILLWAIT; -import static com.carrotsearch.randomizedtesting.RandomizedRunner.DEFAULT_TIMEOUT; -import static com.carrotsearch.randomizedtesting.RandomizedRunner.DEFAULT_TIMEOUT_SUITE; -import static com.carrotsearch.randomizedtesting.RandomizedTest.systemPropertyAsInt; -import static com.carrotsearch.randomizedtesting.SysGlobals.SYSPROP_KILLATTEMPTS; -import static com.carrotsearch.randomizedtesting.SysGlobals.SYSPROP_KILLWAIT; -import static com.carrotsearch.randomizedtesting.SysGlobals.SYSPROP_TIMEOUT; -import static com.carrotsearch.randomizedtesting.SysGlobals.SYSPROP_TIMEOUT_SUITE; - -import java.lang.annotation.Annotation; -import java.lang.management.ManagementFactory; -import java.lang.management.ThreadInfo; -import java.lang.reflect.AnnotatedElement; -import java.security.AccessController; -import java.security.PrivilegedAction; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.EnumSet; -import java.util.Formatter; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.locks.LockSupport; -import java.util.logging.Logger; - -import org.junit.Test; -import org.junit.AssumptionViolatedException; -import org.junit.runner.Description; -import org.junit.runner.Result; -import org.junit.runner.notification.Failure; -import org.junit.runner.notification.RunListener; -import org.junit.runner.notification.RunNotifier; -import org.junit.runner.notification.StoppedByUserException; -import org.junit.runners.model.MultipleFailureException; -import org.junit.runners.model.Statement; - -import com.carrotsearch.randomizedtesting.RandomizedRunner.TestCandidate; -import com.carrotsearch.randomizedtesting.RandomizedRunner.UncaughtException; -import com.carrotsearch.randomizedtesting.annotations.SuppressForbidden; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakAction; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakAction.Action; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakFilters; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakGroup; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakLingering; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope.Scope; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakZombies; -import com.carrotsearch.randomizedtesting.annotations.Timeout; -import com.carrotsearch.randomizedtesting.annotations.TimeoutSuite; - -/** - * Everything corresponding to thread leak control. This is very, very fragile to changes - * because of how threads interact and where they can be spun off. - */ -@SuppressWarnings("resource") -class ThreadLeakControl { - /** A dummy class serving as the source of defaults for annotations. */ - @ThreadLeakScope - @ThreadLeakAction - @ThreadLeakLingering - @ThreadLeakZombies - @ThreadLeakFilters - @ThreadLeakGroup - private static class DefaultAnnotationValues {} - - /** - * Shared LOGGER. - */ - private final static Logger LOGGER = RandomizedRunner.logger; - - /** - * How many attempts to interrupt and then kill a runaway thread before giving up? - */ - private final int killAttempts; - - /** - * How long to wait between attempts to kill a runaway thread (millis). - */ - private final int killWait; - - /** - * Target notifier. - */ - private final RunNotifier targetNotifier; - - /** - * This is the assumed set of threads without leaks. - */ - private final Set expectedSuiteState; - - /** - * Atomic section for passing notifier events. - */ - private final Object notifierLock = new Object(); - - /** - * @see SubNotifier - */ - private final SubNotifier subNotifier; - - /** - * Test timeout. - */ - private TimeoutValue testTimeout; - - /** - * Suite timeout. - */ - private TimeoutValue suiteTimeout; - - /** - * Built-in filters. - */ - private final List builtinFilters; - - /** - * User filter (compound). - */ - private ThreadFilter suiteFilters; - - /** - * The governing runner. - */ - private final RandomizedRunner runner; - - /** - * Suite timeout. - */ - private AtomicBoolean suiteTimedOut = new AtomicBoolean(); - - /** - * Thread leak detection group. - */ - ThreadLeakGroup threadLeakGroup; - - /** - * Sub-notifier that controls passing events back in case of timeouts. - */ - private class SubNotifier extends RunNotifier { - private boolean stopRequested = false; - Description testInProgress; - - @Override - public void addListener(RunListener listener) { throw new UnsupportedOperationException(); } - @Override - public void addFirstListener(RunListener listener) { throw new UnsupportedOperationException(); } - @Override - public void removeListener(RunListener listener) { throw new UnsupportedOperationException(); } - @Override - public void fireTestRunFinished(Result result) { throw new UnsupportedOperationException(); } - @Override - public void fireTestRunStarted(Description description) { throw new UnsupportedOperationException(); } - - @Override - public void fireTestStarted(Description description) throws StoppedByUserException { - synchronized (notifierLock) { - if (stopRequested) return; - targetNotifier.fireTestStarted(description); - testInProgress = description; - } - } - - @Override - public void fireTestAssumptionFailed(Failure failure) { - synchronized (notifierLock) { - if (stopRequested) return; - targetNotifier.fireTestAssumptionFailed(failure); - } - } - - @Override - public void fireTestFailure(Failure failure) { - synchronized (notifierLock) { - if (stopRequested) return; - targetNotifier.fireTestFailure(failure); - } - } - - @Override - public void fireTestIgnored(Description description) { - synchronized (notifierLock) { - if (stopRequested) return; - testInProgress = null; - targetNotifier.fireTestIgnored(description); - } - } - - @Override - public void fireTestFinished(Description description) { - synchronized (notifierLock) { - if (stopRequested) return; - testInProgress = null; - targetNotifier.fireTestFinished(description); - } - } - - /** - * Detach from target notifier. - */ - @Override - public void pleaseStop() { - stopRequested = true; - } - } - - /** - * Timeout parsing code and logic. - */ - private static class TimeoutValue { - private final int timeoutOverride; - private final boolean globalTimeoutFirst; - - TimeoutValue(String sysprop, int defaultValue) { - String timeoutValue = System.getProperty(sysprop); - boolean globalTimeoutFirst = false; - if (timeoutValue == null || timeoutValue.trim().length() == 0) { - timeoutValue = null; - } - if (timeoutValue != null) { - // Check for timeout precedence. - globalTimeoutFirst = timeoutValue.matches("[0-9]+\\!"); - timeoutValue = timeoutValue.replaceAll("\\!", ""); - } else { - timeoutValue = Integer.toString(defaultValue); - } - - this.timeoutOverride = Integer.parseInt(timeoutValue); - this.globalTimeoutFirst = globalTimeoutFirst; - } - - int getTimeout(Integer value) { - if (globalTimeoutFirst) { - return timeoutOverride; - } else { - return value != null ? value : timeoutOverride; - } - } - } - - /** */ - private static class ThisThreadFilter implements ThreadFilter { - private final Thread t; - - public ThisThreadFilter(Thread t) { - this.t = t; - } - - @Override - public boolean reject(Thread t) { - return this.t == t; - } - } - - private static ThreadFilter or(final ThreadFilter... filters) { - return new ThreadFilter() { - @Override - public boolean reject(Thread t) { - boolean reject = false; - for (ThreadFilter f : filters) { - if (reject |= f.reject(t)) { - break; - } - } - return reject; - } - }; - } - - /** */ - private static class KnownSystemThread implements ThreadFilter { - @Override - public boolean reject(Thread t) { - // Explicit check for system group. - ThreadGroup tgroup = t.getThreadGroup(); - if (tgroup != null && "system".equals(tgroup.getName()) && tgroup.getParent() == null) { - return true; - } - - // Explicit check for Serializer shutdown daemon. - if (t.getName().equals("JUnit4-serializer-daemon")) { - return true; - } - - // Explicit check for java flight recorder (jfr) threads. - if (t.getName().equals("JFR request timer")) { - return true; - } - - // Explicit check for YourKit Java Profiler (YJP) agent thread. - if (t.getName().equals("YJPAgent-Telemetry")) { - return true; - } - - // J9 memory pool thread. - if (t.getName().equals("MemoryPoolMXBean notification dispatcher")) { - return true; - } - - // Explicit check for MacOSX AWT-AppKit - if (t.getName().equals("AWT-AppKit")) { - return true; - } - - // Explicit check for TokenPoller (MessageDigest spawns it). - if (t.getName().contains("Poller SunPKCS11")) { - return true; - } - - // forked process reaper on Unixish systems - if (t.getName().equals("process reaper")) { - return true; - } - - final List stack = new ArrayList(Arrays.asList(getStackTrace(t))); - Collections.reverse(stack); - - // Explicit check for GC$Daemon - if (stack.size() >= 1 && - stack.get(0).getClassName().startsWith("sun.misc.GC$Daemon")) { - return true; - } - - return false; - } - } - - /** */ - ThreadLeakControl(RunNotifier notifier, RandomizedRunner runner) { - this.targetNotifier = notifier; - this.subNotifier = new SubNotifier(); - this.runner = runner; - - this.killAttempts = systemPropertyAsInt(SYSPROP_KILLATTEMPTS(), DEFAULT_KILLATTEMPTS); - this.killWait = systemPropertyAsInt(SYSPROP_KILLWAIT(), DEFAULT_KILLWAIT); - - // Determine default timeouts. - testTimeout = new TimeoutValue(SYSPROP_TIMEOUT(), DEFAULT_TIMEOUT); - suiteTimeout = new TimeoutValue(SYSPROP_TIMEOUT_SUITE(), DEFAULT_TIMEOUT_SUITE); - - builtinFilters = Arrays.asList( - new ThisThreadFilter(Thread.currentThread()), - new KnownSystemThread()); - - // Determine a set of expected threads up front (unfiltered). - expectedSuiteState = Collections.unmodifiableSet(Threads.getAllThreads()); - } - - /** - * Runs a {@link Statement} and keeps any exception and - * completion flag. - */ - private static class StatementRunner implements Runnable { - private final Statement s; - - volatile Throwable error; - volatile boolean completed; - - StatementRunner(Statement s) { - this.s = s; - } - - public void run() { - try { - s.evaluate(); - } catch (Throwable t) { - error = t; - } finally { - completed = true; - } - } - } - - /** - * Check on zombie threads status. - */ - private static void checkZombies() throws AssumptionViolatedException { - if (RandomizedRunner.hasZombieThreads()) { - throw new AssumptionViolatedException("Leaked background threads present (zombies)."); - } - } - - /** - * A {@link Statement} for wrapping suite-level execution. - */ - Statement forSuite(final Statement s, final Description suiteDescription) { - final Class suiteClass = RandomizedContext.current().getTargetClass(); - final int timeout = determineTimeout(suiteClass); - - return new Statement() { - @Override - public void evaluate() throws Throwable { - checkZombies(); - - threadLeakGroup = firstAnnotated(ThreadLeakGroup.class, suiteClass, DefaultAnnotationValues.class); - final List errors = new ArrayList(); - suiteFilters = instantiateFilters(errors, suiteClass); - MultipleFailureException.assertEmpty(errors); - - final StatementRunner sr = new StatementRunner(s); - final boolean timedOut = forkTimeoutingTask(sr, timeout, errors); - - synchronized (notifierLock) { - if (timedOut) { - // Mark as timed out so that we don't do any checks in any currently running test - suiteTimedOut.set(true); - - // Flush streams so that we don't get warning outputs before sysout buffers. - flushStreams(); - - // Emit a warning. - LOGGER.warning("Suite execution timed out: " + suiteDescription + formatThreadStacksFull()); - - // mark subNotifier as dead (no longer passing events). - subNotifier.pleaseStop(); - } - } - - if (timedOut) { - // complete subNotifier state in case in the middle of a test. - if (subNotifier.testInProgress != null) { - targetNotifier.fireTestFailure( - new Failure(subNotifier.testInProgress, - RandomizedRunner.augmentStackTrace( - emptyStack(new Exception("Test abandoned because suite timeout was reached."))))); - targetNotifier.fireTestFinished(subNotifier.testInProgress); - } - - // throw suite failure (timeout). - errors.add(RandomizedRunner.augmentStackTrace( - emptyStack(new Exception("Suite timeout exceeded (>= " + timeout + " msec).")))); - } - - final AnnotatedElement [] chain = { suiteClass, DefaultAnnotationValues.class }; - List threadLeakErrors = timedOut ? new ArrayList() : errors; - checkThreadLeaks( - refilter(expectedSuiteState, suiteFilters), threadLeakErrors, LifecycleScope.SUITE, suiteDescription, chain); - processUncaught(errors, runner.handler.getUncaughtAndClear()); - - MultipleFailureException.assertEmpty(errors); - } - - @SuppressForbidden("Legitimate use of syserr.") - private void flushStreams() { - System.out.flush(); - System.err.flush(); - } - }; - } - - /** - * A {@link Statement} for wrapping test-level execution. - */ - Statement forTest(final Statement s, final TestCandidate c) { - final int timeout = determineTimeout(c); - - return new Statement() { - @Override - public void evaluate() throws Throwable { - checkZombies(); - - final StatementRunner sr = new StatementRunner(s); - final List errors = new ArrayList(); - final Set beforeTestState = getThreads(suiteFilters); - final boolean timedOut = forkTimeoutingTask(sr, timeout, errors); - - if (suiteTimedOut.get()) { - return; - } - - if (timedOut) { - LOGGER.warning("Test execution timed out: " + c.description + formatThreadStacksFull()); - } - - if (timedOut) { - errors.add(RandomizedRunner.augmentStackTrace( - emptyStack(new Exception("Test timeout exceeded (>= " + timeout + " msec).")))); - } - - final AnnotatedElement [] chain = - { c.method, c.getTestClass(), DefaultAnnotationValues.class }; - List threadLeakErrors = timedOut ? new ArrayList() : errors; - checkThreadLeaks(beforeTestState, threadLeakErrors, LifecycleScope.TEST, c.description, chain); - processUncaught(errors, runner.handler.getUncaughtAndClear()); - - MultipleFailureException.assertEmpty(errors); - } - }; - } - - /** - * Refilter a set of threads - */ - protected Set refilter(Set in, ThreadFilter f) { - HashSet t = new HashSet(in); - for (Iterator i = t.iterator(); i.hasNext();) { - if (f.reject(i.next())) { - i.remove(); - } - } - return t; - } - - /** - * Instantiate a full set of {@link ThreadFilter}s for a suite. - */ - private ThreadFilter instantiateFilters(List errors, Class suiteClass) { - ThreadLeakFilters ann = - firstAnnotated(ThreadLeakFilters.class, suiteClass, DefaultAnnotationValues.class); - - final ArrayList filters = new ArrayList(); - for (Class c : ann.filters()) { - try { - filters.add(c.newInstance()); - } catch (Throwable t) { - errors.add(t); - } - } - - if (ann.defaultFilters()) { - filters.addAll(builtinFilters); - } - - return or(filters.toArray(new ThreadFilter[filters.size()])); - } - - /** - * Clears a {@link Throwable}'s stack. - */ - private static T emptyStack(T t) { - t.setStackTrace(new StackTraceElement [0]); - return t; - } - - /** - * Process uncaught exceptions. - */ - protected void processUncaught(List errors, List uncaughtList) { - for (UncaughtException e : uncaughtList) { - errors.add(emptyStack(new UncaughtExceptionError( - "Captured an uncaught exception in thread: " + e.threadName, e.error))); - } - } - - /** - * Perform a thread leak check at the given scope. - */ - @SuppressWarnings("deprecation") - protected void checkThreadLeaks( - Set expectedState, - List errors, - LifecycleScope scope, Description description, - AnnotatedElement... annotationChain) - { - final ThreadLeakScope annScope = firstAnnotated(ThreadLeakScope.class, annotationChain); - - // Return immediately if no checking. - if (annScope.value() == Scope.NONE) - return; - - // If suite scope check is requested skip testing at test level. - if (annScope.value() == Scope.SUITE && scope == LifecycleScope.TEST) { - return; - } - - // Check for the set of live threads, with optional lingering. - int lingerTime = firstAnnotated(ThreadLeakLingering.class, annotationChain).linger(); - HashSet threads = getThreads(suiteFilters); - threads.removeAll(expectedState); - - if (lingerTime > 0 && !threads.isEmpty()) { - final long deadline = System.currentTimeMillis() + lingerTime; - try { - LOGGER.warning("Will linger awaiting termination of " + threads.size() + " leaked thread(s)."); - do { - // Check every few hundred milliseconds until deadline occurs. We want to break out - // sooner than the maximum lingerTime but there is no explicit even that - // would wake us up, so poll periodically. - Thread.sleep(100); - - threads = getThreads(suiteFilters); - threads.removeAll(expectedState); - if (threads.isEmpty() || System.currentTimeMillis() > deadline) - break; - } while (true); - } catch (InterruptedException e) { - LOGGER.warning("Lingering interrupted."); - } - } - - if (threads.isEmpty()) { - return; - } - - // Take one more snapshot, this time including stack traces (costly). - HashMap withTraces = getThreadsWithTraces(suiteFilters); - withTraces.keySet().removeAll(expectedState); - if (withTraces.isEmpty()) { - return; - } - - // Build up failure message (include stack traces of leaked threads). - StringBuilder message = new StringBuilder(threads.size() + " thread" + - (threads.size() == 1 ? "" : "s") + - " leaked from " + - scope + " scope at " + description + ": "); - message.append(formatThreadStacks(withTraces)); - - // The first exception is leaked threads error. - errors.add(RandomizedRunner.augmentStackTrace( - emptyStack(new ThreadLeakError(message.toString())))); - - // Perform actions on leaked threads. - final EnumSet actions = EnumSet.noneOf(Action.class); - actions.addAll(Arrays.asList(firstAnnotated(ThreadLeakAction.class, annotationChain).value())); - - if (actions.contains(Action.WARN)) { - LOGGER.severe(message.toString()); - } - - Set zombies = Collections.emptySet(); - if (actions.contains(Action.INTERRUPT)) { - zombies = tryToInterruptAll(errors, withTraces.keySet()); - } - - // Process zombie thread check consequences here. - if (!zombies.isEmpty()) { - switch (firstAnnotated(ThreadLeakZombies.class, annotationChain).value()) { - case CONTINUE: - // Do nothing about it. - break; - case IGNORE_REMAINING_TESTS: - // Mark zombie thread presence. - RandomizedRunner.zombieMarker.set(true); - break; - default: - throw new RuntimeException("Missing case."); - } - } - } - - /** - * Dump threads and their current stack trace. - */ - private String formatThreadStacks(Map threads) { - StringBuilder message = new StringBuilder(); - int cnt = 1; - final Formatter f = new Formatter(message, Locale.ROOT); - for (Map.Entry e : threads.entrySet()) { - f.format(Locale.ROOT, "\n %2d) %s", cnt++, Threads.threadName(e.getKey())).flush(); - if (e.getValue().length == 0) { - message.append("\n at (empty stack)"); - } else { - for (StackTraceElement ste : e.getValue()) { - message.append("\n at ").append(ste); - } - } - } - return message.toString(); - } - - /** Collect thread names. */ - private String threadNames(Collection threads) { - StringBuilder b = new StringBuilder(); - final Formatter f = new Formatter(b, Locale.ROOT); - int cnt = 1; - for (Thread t : threads) { - f.format(Locale.ROOT, "\n %2d) %s", cnt++, Threads.threadName(t)); - } - return b.toString(); - } - - /** Dump thread state. */ - private String formatThreadStacksFull() { - try { - StringBuilder b = new StringBuilder(); - b.append("\n==== jstack at approximately timeout time ====\n"); - for (ThreadInfo ti : ManagementFactory.getThreadMXBean().dumpAllThreads(true, true)) { - Threads.append(b, ti); - } - b.append("^^==============================================\n"); - return b.toString(); - } catch (Throwable e) { - // Ignore, perhaps not available. - } - return formatThreadStacks(getThreadsWithTraces()); - } - - private static StackTraceElement[] getStackTrace(final Thread t) { - return AccessController.doPrivileged(new PrivilegedAction() { - @Override - public StackTraceElement[] run() { - return t.getStackTrace(); - } - }); - } - - /** - * Returns all {@link ThreadLeakGroup} applicable threads, with stack - * traces, for analysis. - */ - private HashMap getThreadsWithTraces(ThreadFilter... filters) { - final Set threads = getThreads(filters); - final HashMap r = new HashMap(); - for (Thread t : threads) { - r.put(t, getStackTrace(t)); - } - return r; - } - - /** - * Returns all {@link ThreadLeakGroup} threads for analysis. - */ - private HashSet getThreads(ThreadFilter... filters) { - HashSet threads; - switch (threadLeakGroup.value()) { - case ALL: - threads = Threads.getAllThreads(); - break; - case MAIN: - threads = Threads.getThreads(RandomizedRunner.mainThreadGroup); - break; - case TESTGROUP: - threads = Threads.getThreads(runner.runnerThreadGroup); - break; - default: - throw new RuntimeException(); - } - - final ThreadFilter filter = or(filters); - for (Iterator i = threads.iterator(); i.hasNext();) { - Thread t = i.next(); - if (!t.isAlive() || filter.reject(t)) { - i.remove(); - } - } - - return threads; - } - - /** - * Attempt to interrupt all threads in the given set. - */ - private Set tryToInterruptAll(List errors, Set threads) { - LOGGER.info("Starting to interrupt leaked threads:" + threadNames(threads)); - - // stop reporting uncaught exceptions. - runner.handler.stopReporting(); - try { - // This means we have an unknown ordering of interrupt calls but - // there is very little we can do about it, really. - final HashSet ordered = new HashSet(threads); - - int interruptAttempts = this.killAttempts; - int interruptWait = this.killWait; - boolean allDead; - final int restorePriority = Thread.currentThread().getPriority(); - do { - allDead = true; - try { - Thread.currentThread().setPriority(Thread.MAX_PRIORITY); - for (Thread t : ordered) { - t.interrupt(); - } - - // Maximum wait time. Progress through the threads, trying to join but - // decrease the join time each time. - long waitDeadline = System.currentTimeMillis() + interruptWait; - for (Iterator i = ordered.iterator(); i.hasNext();) { - final Thread t = i.next(); - if (t.isAlive()) { - allDead = false; - join(t, Math.max(1, waitDeadline - System.currentTimeMillis()), Thread::sleep); - } else { - i.remove(); - } - } - } catch (InterruptedException e) { - interruptAttempts = 0; - } - } while (!allDead && --interruptAttempts > 0); - Thread.currentThread().setPriority(restorePriority); - - // Check after the last join. - HashMap zombies = new HashMap(); - for (Thread t : ordered) { - if (t.isAlive()) { - zombies.put(t, getStackTrace(t)); - } - } - - if (zombies.isEmpty()) { - LOGGER.info("All leaked threads terminated."); - } else { - String message = "There are still zombie threads that couldn't be terminated:" + formatThreadStacks(zombies); - LOGGER.severe(message); - errors.add(RandomizedRunner.augmentStackTrace( - emptyStack(new ThreadLeakError(message.toString())))); - } - - return zombies.keySet(); - } finally { - runner.handler.resumeReporting(); - } - } - - /** - * Fork or not depending on the timeout value. - */ - boolean forkTimeoutingTask(StatementRunner r, int timeout, List errors) - throws InterruptedException - { - if (timeout == 0) { - r.run(); - } else { - final Thread owner = Thread.currentThread(); - final AtomicBoolean done = new AtomicBoolean(); - - Thread t = new Thread(() -> { - try { - r.run(); - } finally { - done.set(true); - LockSupport.unpark(owner); - } - }, Thread.currentThread().getName() + "-worker"); - RandomizedContext.cloneFor(t); - - t.start(); - join(t, timeout, (millis) -> { - LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(millis)); - if (done.get()) { - t.join(); - } - }); - } - - final boolean timedOut = !r.completed; - if (r.error != null) errors.add(r.error); - return timedOut; - } - - static interface AwaitCond { - void await(long millis) throws InterruptedException; - } - - static void join(Thread t, long millis, AwaitCond cond) throws InterruptedException { - if (millis <= 0) { - throw new IllegalArgumentException("Timeout must be positive: " + millis); - } - - long deadline = System.currentTimeMillis() + millis; - while (t.isAlive()) { - long delay = deadline - System.currentTimeMillis(); - if (delay > 0) { - // Don't wait longer than a few millis, then recheck condition. - // We use sleep because Thread.join() is synchronized and this thread may - // get stuck on getting the monitor for an indefinite amount of time. - cond.await(Math.min(250, delay)); - } else { - break; - } - } - } - - boolean isTimedOut() { - return suiteTimedOut.get(); - } - - /** - * Return the {@link RunNotifier} that should be used by any sub-statements - * running actual instance-scope tests. We need this because we need to - * prevent spurious notifications after suite timeouts. - */ - RunNotifier notifier() { - return subNotifier; - } - - /** - * Determine timeout for a suite. - * - * @return Returns timeout in milliseconds or 0 if the test should run until - * finished (possibly blocking forever). - */ - private int determineTimeout(Class suiteClass) { - TimeoutSuite timeoutAnn = suiteClass.getAnnotation(TimeoutSuite.class); - return suiteTimeout.getTimeout(timeoutAnn == null ? null : timeoutAnn.millis()); - } - - /** - * Determine timeout for a single test method (candidate). - * - * @return Returns timeout in milliseconds or 0 if the test should run until - * finished (possibly blocking forever). - */ - private int determineTimeout(TestCandidate c) { - Integer timeout = null; - - Timeout timeoutAnn = c.getTestClass().getAnnotation(Timeout.class); - if (timeoutAnn != null) { - timeout = (int) Math.min(Integer.MAX_VALUE, timeoutAnn.millis()); - } - - // @Test annotation timeout value. - Test testAnn = c.method.getAnnotation(Test.class); - if (testAnn != null && testAnn.timeout() > 0) { - timeout = (int) Math.min(Integer.MAX_VALUE, testAnn.timeout()); - } - - // Method-override. - timeoutAnn = c.method.getAnnotation(Timeout.class); - if (timeoutAnn != null) { - timeout = timeoutAnn.millis(); - } - - return testTimeout.getTimeout(timeout); - } - - /** - * Returns an annotation's instance declared on any annotated element (first one wins) - * or the default value if not present on any of them. - */ - private static T firstAnnotated(Class clazz, AnnotatedElement... elements) { - for (AnnotatedElement element : elements) { - T ann = element.getAnnotation(clazz); - if (ann != null) return ann; - } - throw new RuntimeException("default annotation value must be within elements."); - } -} diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/ThreadLeakError.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/ThreadLeakError.java deleted file mode 100644 index 4ac5cb91..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/ThreadLeakError.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -/** - * A thread went wild. - */ -@SuppressWarnings("serial") -final class ThreadLeakError extends Error { - public ThreadLeakError(String message) { - super(message); - } -} diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/Threads.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/Threads.java deleted file mode 100644 index 6aac849d..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/Threads.java +++ /dev/null @@ -1,139 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import java.lang.Thread.State; -import java.lang.management.LockInfo; -import java.lang.management.MonitorInfo; -import java.lang.management.ThreadInfo; -import java.security.AccessController; -import java.security.PrivilegedAction; -import java.util.Arrays; -import java.util.EnumMap; -import java.util.HashSet; - -final class Threads { - private Threads() {} - - /** - * Collect thread information, JVM vendor insensitive. - */ - public static String threadName(Thread t) { - return "Thread[" + - "id=" + t.getId() + - ", name=" + t.getName() + - ", state=" + t.getState() + - ", group=" + groupName(t.getThreadGroup()) + - "]"; - } - - private static String groupName(ThreadGroup threadGroup) { - if (threadGroup == null) { - return "{null group}"; - } else { - return threadGroup.getName(); - } - } - - private final static EnumMap lockInfoStrings; - static { - lockInfoStrings = new EnumMap(State.class); - lockInfoStrings.put(State.BLOCKED, "blocked on "); - lockInfoStrings.put(State.WAITING, "waiting on "); - lockInfoStrings.put(State.TIMED_WAITING, "timed waiting on "); - lockInfoStrings.put(State.TERMINATED, "terminated? on "); - lockInfoStrings.put(State.RUNNABLE, "runnable? on "); - lockInfoStrings.put(State.NEW, "new? on "); - } - - /** - * Dump {@link ThreadInfo} information. - */ - public static void append(StringBuilder b, ThreadInfo ti) { - b.append('"').append(ti.getThreadName()).append('"'); - b.append(" ID=").append(ti.getThreadId()); - - final State threadState = ti.getThreadState(); - b.append(" ").append(threadState); - if (ti.getLockName() != null) { - b.append(" on ").append(ti.getLockName()); - } - - if (ti.getLockOwnerName() != null) { - b.append(" owned by \"").append(ti.getLockOwnerName()) - .append("\" ID=").append(ti.getLockOwnerId()); - } - - b.append(ti.isSuspended() ? " (suspended)" : ""); - b.append(ti.isInNative() ? " (in native code)" : ""); - b.append("\n"); - - final StackTraceElement[] stack = ti.getStackTrace(); - final LockInfo lockInfo = ti.getLockInfo(); - final MonitorInfo [] monitorInfos = ti.getLockedMonitors(); - for (int i = 0; i < stack.length; i++) { - b.append("\tat ").append(stack[i]).append("\n"); - if (i == 0 && lockInfo != null) { - b.append("\t- ") - .append(lockInfoStrings.get(threadState)) - .append(lockInfo) - .append("\n"); - } - - for (MonitorInfo mi : monitorInfos) { - if (mi.getLockedStackDepth() == i) { - b.append("\t- locked ").append(mi).append("\n"); - } - } - } - - LockInfo [] lockInfos = ti.getLockedSynchronizers(); - if (lockInfos.length > 0) { - b.append("\tLocked synchronizers:\n"); - for (LockInfo li : ti.getLockedSynchronizers()) { - b.append("\t- ").append(li).append("\n"); - } - } - b.append("\n"); - } - - public static HashSet getAllThreads() { - ThreadGroup tg = getTopThreadGroup(); - return getThreads(tg); - } - - public static HashSet getThreads(ThreadGroup tg) { - Thread [] threads = new Thread [2]; - int maxIndex; - while ((maxIndex = doEnumerate(tg, threads, true)) == threads.length) { - threads = new Thread [threads.length * 2]; - } - return new HashSet(Arrays.asList(threads).subList(0, maxIndex)); - } - - private static int doEnumerate(final ThreadGroup tg, final Thread[] threads, final boolean recurse) { - return AccessController.doPrivileged(new PrivilegedAction() { - @Override - public Integer run() { - return tg.enumerate(threads, recurse); - } - }); - } - - public static ThreadGroup getTopThreadGroup() { - // a lame workaround so that J9 works. - ThreadGroup tg = AccessController.doPrivileged(new PrivilegedAction() { - @Override - public ThreadGroup run() { - ThreadGroup tg = Thread.currentThread().getThreadGroup(); - while (tg != null && tg.getParent() != null) { - tg = tg.getParent(); - } - return tg; - } - }); - - if (tg == null) { - throw new RuntimeException("No root ThreadGroup for thread: " + Thread.currentThread()); - } - return tg; - } -} diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/TraceFormatting.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/TraceFormatting.java deleted file mode 100644 index 905f0109..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/TraceFormatting.java +++ /dev/null @@ -1,94 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import java.util.*; - -/** - * Utilities for dealing with throwables, stacks, etc. - */ -public final class TraceFormatting { - /** Stack filtering prefixes. */ - private final List filteredPrefixes; - - /** - * Default stack traces, no filtering. - */ - public TraceFormatting() { - this(Collections. emptyList()); - } - - public TraceFormatting(List filteredPrefixes) { - this.filteredPrefixes = filteredPrefixes; - } - - /** Format an exception and all of its nested stacks into a string. */ - public String formatThrowable(Throwable t) { - return formatThrowable(new StringBuilder(), t).toString(); - } - - /** Format an exception and all of its nested stacks into a string. */ - public StringBuilder formatThrowable(StringBuilder b, Throwable t) { - b.append(t.toString()).append("\n"); - formatStackTrace(b, t.getStackTrace()); - if (t.getCause() != null) { - b.append("Caused by: "); - formatThrowable(b, t.getCause()); - } - return b; - } - - /** Format a list of stack entries into a string. */ - public StringBuilder formatStackTrace(StringBuilder b, StackTraceElement[] stackTrace) { - return formatStackTrace(b, Arrays.asList(stackTrace)); - } - - public String formatStackTrace(StackTraceElement[] stackTrace) { - return formatStackTrace(Arrays.asList(stackTrace)); - } - - public String formatStackTrace(Iterable stackTrace) { - return formatStackTrace(new StringBuilder(), stackTrace).toString(); - } - - /** Format a list of stack entries into a string. */ - public StringBuilder formatStackTrace(StringBuilder b, Iterable stackTrace) { - Set filteredSet = new HashSet(); - for (StackTraceElement e : stackTrace) { - String stackLine = e.toString(); - - String filtered = null; - for (String prefix : filteredPrefixes) { - if (stackLine.startsWith(prefix)) { - filtered = prefix; - break; - } - } - - if (filtered != null) { - if (filteredSet.isEmpty()) { - b.append(" [..."); - } - filteredSet.add(filtered); - } else { - appendFiltered(b, filteredSet); - b.append(" ").append(stackLine).append("\n"); - } - } - appendFiltered(b, filteredSet); - return b; - } - - private static void appendFiltered(StringBuilder b, Set filteredSet) { - if (!filteredSet.isEmpty()) { - boolean first = true; - for (String prefix : filteredSet) { - if (!first) { - b.append(", "); - } - first = false; - b.append(prefix).append("*"); - } - b.append("]\n"); - filteredSet.clear(); - } - } -} diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/UncaughtExceptionError.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/UncaughtExceptionError.java deleted file mode 100644 index ea3b4daf..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/UncaughtExceptionError.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -/** - * This is thrown on uncaught exceptions during suite or test execution. - */ -@SuppressWarnings("serial") -final class UncaughtExceptionError extends Error { - public UncaughtExceptionError(String message, Throwable cause) { - super(message, cause); - } -} diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/Validation.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/Validation.java deleted file mode 100644 index fb82ddd5..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/Validation.java +++ /dev/null @@ -1,111 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.util.Arrays; - -/** - * Validation utilities. Chained-call style. - */ -final class Validation { - - public static final class MethodValidation { - private final Method m; - private String description; - - public MethodValidation(Method m) { - this.m = m; - this.description = "Method " + m.getName(); - } - - public MethodValidation describedAs(String message) { - this.description = message; - return this; - } - - public MethodValidation isPublic() { - if (!Modifier.isPublic(m.getModifiers())) { - throw new RuntimeException(description + " should be public."); - } - return this; - } - - public MethodValidation hasArgsCount(int argsCount) { - if (m.getParameterTypes().length != argsCount) { - throw new RuntimeException(description + " should have " + argsCount + " parameters and" + - " has these: " + Arrays.toString(m.getParameterTypes())); - } - return this; - } - - public MethodValidation isStatic() { - if (!Modifier.isStatic(m.getModifiers())) { - throw new RuntimeException(description + " should be static."); - } - return this; - } - - public MethodValidation isNotStatic() { - if (Modifier.isStatic(m.getModifiers())) { - throw new RuntimeException(description + " should be instance method (not static)."); - } - return this; - } - - public MethodValidation hasReturnType(Class clazz) { - if (!clazz.isAssignableFrom(m.getReturnType())) { - throw new RuntimeException(description + " should have a return " + - "type assignable to: " + clazz.getName()); - } - return this; - } - } - - public static final class ClassValidation { - private final Class clazz; - private String description; - - public ClassValidation(Class clazz) { - this.clazz = clazz; - this.description = "Class " + clazz.getName(); - } - - public ClassValidation describedAs(String message) { - this.description = message; - return this; - } - - public ClassValidation isPublic() { - if (!Modifier.isPublic(clazz.getModifiers())) { - throw new RuntimeException(description + " should be public."); - } - return this; - } - - public ClassValidation isConcreteClass() { - if (Modifier.isInterface(clazz.getModifiers())) { - throw new RuntimeException(description + " should be a conrete class (not an interface)."); - } - if (Modifier.isAbstract(clazz.getModifiers())) { - throw new RuntimeException(description + " should be a concrete class (not abstract)."); - } - return this; - } - - public void hasPublicNoArgsConstructor() { - try { - clazz.getConstructor(new Class [0]); - } catch (Throwable e) { - throw new RuntimeException(description + " should have a public parameterless constructor."); - } - } - } - - public static MethodValidation checkThat(Method method) { - return new MethodValidation(method); - } - - public static ClassValidation checkThat(Class clazz) { - return new ClassValidation(clazz); - } -} diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/WriterOutputStream.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/WriterOutputStream.java deleted file mode 100644 index 86963e6b..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/WriterOutputStream.java +++ /dev/null @@ -1,288 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import java.io.IOException; -import java.io.OutputStream; -import java.io.Writer; -import java.nio.ByteBuffer; -import java.nio.CharBuffer; -import java.nio.charset.Charset; -import java.nio.charset.CharsetDecoder; -import java.nio.charset.CoderResult; -import java.nio.charset.CodingErrorAction; - -/** - * {@link OutputStream} implementation that transforms a byte stream to a - * character stream using a specified charset encoding and writes the resulting - * stream to a {@link Writer}. The stream is transformed using a - * {@link CharsetDecoder} object, guaranteeing that all charset - * encodings supported by the JRE are handled correctly. - *

      - * The output of the {@link CharsetDecoder} is buffered using a fixed size buffer. - * This implies that the data is written to the underlying {@link Writer} in chunks - * that are no larger than the size of this buffer. By default, the buffer is - * flushed only when it overflows or when {@link #flush()} or {@link #close()} - * is called. In general there is therefore no need to wrap the underlying {@link Writer} - * in a {@link java.io.BufferedWriter}. {@link WriterOutputStream} can also - * be instructed to flush the buffer after each write operation. In this case, all - * available data is written immediately to the underlying {@link Writer}, implying that - * the current position of the {@link Writer} is correlated to the current position - * of the {@link WriterOutputStream}. - *

      - * {@link WriterOutputStream} implements the inverse transformation of {@link java.io.OutputStreamWriter}; - * in the following example, writing to out2 would have the same result as writing to - * out directly (provided that the byte sequence is legal with respect to the - * charset encoding): - *

      - * OutputStream out = ...
      - * Charset cs = ...
      - * OutputStreamWriter writer = new OutputStreamWriter(out, cs);
      - * WriterOutputStream out2 = new WriterOutputStream(writer, cs);
      - * {@link WriterOutputStream} implements the same transformation as {@link java.io.InputStreamReader}, - * except that the control flow is reversed: both classes transform a byte stream - * into a character stream, but {@link java.io.InputStreamReader} pulls data from the underlying stream, - * while {@link WriterOutputStream} pushes it to the underlying stream. - *

      - * Note that while there are use cases where there is no alternative to using - * this class, very often the need to use this class is an indication of a flaw - * in the design of the code. This class is typically used in situations where an existing - * API only accepts an {@link OutputStream} object, but where the stream is known to represent - * character data that must be decoded for further use. - *

      - * Instances of {@link WriterOutputStream} are not thread safe. - * - * @since 2.0 - */ -public class WriterOutputStream extends OutputStream { - private static final int DEFAULT_BUFFER_SIZE = 1024; - - private final Writer writer; - private final CharsetDecoder decoder; - private final boolean writeImmediately; - - /** - * ByteBuffer used as input for the decoder. This buffer can be small - * as it is used only to transfer the received data to the - * decoder. - */ - private final ByteBuffer decoderIn = ByteBuffer.allocate(128); - - /** - * CharBuffer used as output for the decoder. It should be - * somewhat larger as we write from this buffer to the - * underlying Writer. - */ - private final CharBuffer decoderOut; - - /** - * Constructs a new {@link WriterOutputStream} with a default output buffer size of - * 1024 characters. The output buffer will only be flushed when it overflows or when - * {@link #flush()} or {@link #close()} is called. - * - * @param writer the target {@link Writer} - * @param decoder the charset decoder - * @since 2.1 - */ - public WriterOutputStream(Writer writer, CharsetDecoder decoder) { - this(writer, decoder, DEFAULT_BUFFER_SIZE, false); - } - - /** - * Constructs a new {@link WriterOutputStream}. - * - * @param writer the target {@link Writer} - * @param decoder the charset decoder - * @param bufferSize the size of the output buffer in number of characters - * @param writeImmediately If true the output buffer will be flushed after each - * write operation, i.e. all available data will be written to the - * underlying {@link Writer} immediately. If false, the - * output buffer will only be flushed when it overflows or when - * {@link #flush()} or {@link #close()} is called. - * @since 2.1 - */ - public WriterOutputStream(Writer writer, CharsetDecoder decoder, int bufferSize, boolean writeImmediately) { - this.writer = writer; - this.decoder = decoder; - this.writeImmediately = writeImmediately; - decoderOut = CharBuffer.allocate(bufferSize); - } - - /** - * Constructs a new {@link WriterOutputStream}. - * - * @param writer the target {@link Writer} - * @param charset the charset encoding - * @param bufferSize the size of the output buffer in number of characters - * @param writeImmediately If true the output buffer will be flushed after each - * write operation, i.e. all available data will be written to the - * underlying {@link Writer} immediately. If false, the - * output buffer will only be flushed when it overflows or when - * {@link #flush()} or {@link #close()} is called. - */ - public WriterOutputStream(Writer writer, Charset charset, int bufferSize, boolean writeImmediately) { - this(writer, - charset.newDecoder() - .onMalformedInput(CodingErrorAction.REPLACE) - .onUnmappableCharacter(CodingErrorAction.REPLACE) - .replaceWith("?"), - bufferSize, - writeImmediately); - } - - /** - * Constructs a new {@link WriterOutputStream} with a default output buffer size of - * 1024 characters. The output buffer will only be flushed when it overflows or when - * {@link #flush()} or {@link #close()} is called. - * - * @param writer the target {@link Writer} - * @param charset the charset encoding - */ - public WriterOutputStream(Writer writer, Charset charset) { - this(writer, charset, DEFAULT_BUFFER_SIZE, false); - } - - /** - * Constructs a new {@link WriterOutputStream}. - * - * @param writer the target {@link Writer} - * @param charsetName the name of the charset encoding - * @param bufferSize the size of the output buffer in number of characters - * @param writeImmediately If true the output buffer will be flushed after each - * write operation, i.e. all available data will be written to the - * underlying {@link Writer} immediately. If false, the - * output buffer will only be flushed when it overflows or when - * {@link #flush()} or {@link #close()} is called. - */ - public WriterOutputStream(Writer writer, String charsetName, int bufferSize, boolean writeImmediately) { - this(writer, Charset.forName(charsetName), bufferSize, writeImmediately); - } - - /** - * Constructs a new {@link WriterOutputStream} with a default output buffer size of - * 1024 characters. The output buffer will only be flushed when it overflows or when - * {@link #flush()} or {@link #close()} is called. - * - * @param writer the target {@link Writer} - * @param charsetName the name of the charset encoding - */ - public WriterOutputStream(Writer writer, String charsetName) { - this(writer, charsetName, DEFAULT_BUFFER_SIZE, false); - } - - /** - * Constructs a new {@link WriterOutputStream} that uses the default character encoding - * and with a default output buffer size of 1024 characters. The output buffer will only - * be flushed when it overflows or when {@link #flush()} or {@link #close()} is called. - * - * @param writer the target {@link Writer} - */ - public WriterOutputStream(Writer writer) { - this(writer, Charset.defaultCharset(), DEFAULT_BUFFER_SIZE, false); - } - - /** - * Write bytes from the specified byte array to the stream. - * - * @param b the byte array containing the bytes to write - * @param off the start offset in the byte array - * @param len the number of bytes to write - * @throws IOException if an I/O error occurs - */ - @Override - public void write(byte[] b, int off, int len) throws IOException { - while (len > 0) { - int c = Math.min(len, decoderIn.remaining()); - decoderIn.put(b, off, c); - processInput(false); - len -= c; - off += c; - } - if (writeImmediately) { - flushOutput(); - } - } - - /** - * Write bytes from the specified byte array to the stream. - * - * @param b the byte array containing the bytes to write - * @throws IOException if an I/O error occurs - */ - @Override - public void write(byte[] b) throws IOException { - write(b, 0, b.length); - } - - /** - * Write a single byte to the stream. - * - * @param b the byte to write - * @throws IOException if an I/O error occurs - */ - @Override - public void write(int b) throws IOException { - write(new byte[] { (byte)b }, 0, 1); - } - - /** - * Flush the stream. Any remaining content accumulated in the output buffer - * will be written to the underlying {@link Writer}. After that - * {@link Writer#flush()} will be called. - * @throws IOException if an I/O error occurs - */ - @Override - public void flush() throws IOException { - flushOutput(); - writer.flush(); - } - - /** - * Close the stream. Any remaining content accumulated in the output buffer - * will be written to the underlying {@link Writer}. After that - * {@link Writer#close()} will be called. - * @throws IOException if an I/O error occurs - */ - @Override - public void close() throws IOException { - processInput(true); - flushOutput(); - writer.close(); - } - - /** - * Decode the contents of the input ByteBuffer into a CharBuffer. - * - * @param endOfInput indicates end of input - * @throws IOException if an I/O error occurs - */ - private void processInput(boolean endOfInput) throws IOException { - // Prepare decoderIn for reading - decoderIn.flip(); - CoderResult coderResult; - while (true) { - coderResult = decoder.decode(decoderIn, decoderOut, endOfInput); - if (coderResult.isOverflow()) { - flushOutput(); - } else if (coderResult.isUnderflow()) { - break; - } else { - // The decoder is configured to replace malformed input and unmappable characters, - // so we should not get here. - throw new IOException("Unexpected coder result"); - } - } - // Discard the bytes that have been read - decoderIn.compact(); - } - - /** - * Flush the output. - * - * @throws IOException if an I/O error occurs - */ - private void flushOutput() throws IOException { - if (decoderOut.position() > 0) { - writer.write(decoderOut.array(), 0, decoderOut.position()); - decoderOut.rewind(); - } - } -} diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/Xoroshiro128PlusRandom.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/Xoroshiro128PlusRandom.java deleted file mode 100644 index 35f9f5c0..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/Xoroshiro128PlusRandom.java +++ /dev/null @@ -1,97 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import java.util.Random; - -/** - * Implements Xoroshiro128PlusRandom. Not synchronized (anywhere). - * - * @see "http://xoroshiro.di.unimi.it/" - */ -@SuppressWarnings("serial") -public class Xoroshiro128PlusRandom extends Random { - private static final double DOUBLE_UNIT = 0x1.0p-53; // 1.0 / (1L << 53); - private static final float FLOAT_UNIT = 0x1.0p-24f; // 1.0 / (1L << 24); - - private long s0, s1; - - public Xoroshiro128PlusRandom(long seed) { - // Must be here, the only Random constructor. Has side-effects on setSeed, see below. - super(0); - - s0 = MurmurHash3.hash(seed); - s1 = MurmurHash3.hash(s0); - - if (s0 == 0 && s1 == 0) { - s0 = MurmurHash3.hash(0xdeadbeefL); - s1 = MurmurHash3.hash(s0); - } - } - - @Override - public void setSeed(long seed) { - // Called from super constructor and observing uninitialized state? - if (s0 == 0 && s1 == 0) { - return; - } - - throw AssertingRandom.noSetSeed(); - } - - @Override - public boolean nextBoolean() { - return nextLong() >= 0; - } - - @Override - public void nextBytes(byte[] bytes) { - for (int i = 0, len = bytes.length; i < len; ) { - long rnd = nextInt(); - for (int n = Math.min(len - i, 8); n-- > 0; rnd >>>= 8) { - bytes[i++] = (byte) rnd; - } - } - } - - @Override - public double nextDouble() { - return (nextLong() >>> 11) * DOUBLE_UNIT; - } - - @Override - public float nextFloat() { - return (nextInt() >>> 8) * FLOAT_UNIT; - } - - @Override - public int nextInt() { - return (int) nextLong(); - } - - @Override - public int nextInt(int n) { - // Leave superclass's implementation. - return super.nextInt(n); - } - - @Override - public double nextGaussian() { - // Leave superclass's implementation. - return super.nextGaussian(); - } - - @Override - public long nextLong() { - final long s0 = this.s0; - long s1 = this.s1; - final long result = s0 + s1; - s1 ^= s0; - this.s0 = Long.rotateLeft(s0, 55) ^ s1 ^ s1 << 14; - this.s1 = Long.rotateLeft(s1, 36); - return result; - } - - @Override - protected int next(int bits) { - return ((int) nextLong()) >>> (32 - bits); - } -} diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/annotations/Listeners.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/annotations/Listeners.java deleted file mode 100644 index 6bb87099..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/annotations/Listeners.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.carrotsearch.randomizedtesting.annotations; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -import org.junit.runner.notification.RunListener; -import org.junit.runner.notification.RunNotifier; - -import com.carrotsearch.randomizedtesting.RandomizedRunner; - -/** - * Annotate your suite class with this annotation to automatically add hooks to - * the {@link RunNotifier} used for executing tests inside - * {@link RandomizedRunner}. - * - * @see #value() - */ -@Documented -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.TYPE}) -public @interface Listeners { - /** - * An array of listener classes. These classes must be instantiable (public, static, no-args - * constructor, etc.). - */ - Class[] value(); -} diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/annotations/Name.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/annotations/Name.java deleted file mode 100644 index f674b71a..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/annotations/Name.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.carrotsearch.randomizedtesting.annotations; - -import java.lang.annotation.*; - -/** - * Used to annotate constructor parameters for parameterized tests. - * - * @see ParametersFactory - */ -@Documented -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.PARAMETER}) -public @interface Name { - public String value(); -} diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/annotations/Nightly.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/annotations/Nightly.java deleted file mode 100644 index 0dd5c7f7..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/annotations/Nightly.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.carrotsearch.randomizedtesting.annotations; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Inherited; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -import com.carrotsearch.randomizedtesting.RandomizedTest; - -/** - * An annotation indicating a given test case (or suite) should run only during - * nightly tests. - * - *

      The notion of "nightly" tests is based on an assumption that these tests can - * take longer than usual or require more resources than usual. Nightly tests will - * be most commonly used with higher scaling multipliers as in - * ({@link RandomizedTest#SYSPROP_MULTIPLIER}.

      - */ -@Documented -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.METHOD, ElementType.TYPE}) -@Inherited -@TestGroup(enabled = false) -public @interface Nightly { - /** Additional description, if needed. */ - String value() default ""; -} diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/annotations/ParametersFactory.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/annotations/ParametersFactory.java deleted file mode 100644 index 834626f2..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/annotations/ParametersFactory.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.carrotsearch.randomizedtesting.annotations; - -import java.lang.annotation.*; -import java.util.Formatter; - -/** - * Used to annotate methods providing parameters for parameterized tests. The method - * annotated as the factory must be static, public, parameterless and must have a return - * type assignable to {@link Iterable}<Object[]>. - * - *

      The iterable must return arrays conforming to the suite class's constructor - * with respect to the number and types of parameters. - * - *

      The constructor's parameters can be annotated with {@link Name} to provide - * more descriptive parameter names for test descriptions. - * - * @see Name - */ -@Documented -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.METHOD}) -public @interface ParametersFactory { - /** - * Use default argument formatting for test cases. - */ - public static final String DEFAULT_FORMATTING = "default"; - - /** - * Specify custom formatting for test names (constructor arguments). - * The string must be a valid argument to Java's built-in {@link Formatter}. - * Constructor arguments are available in the order they were returned - * from {@link ParametersFactory}. Not all arguments have to be used, - * for example: {@code foo=%1$s} would select only the second argument (indexes - * are zero-based). - */ - String argumentFormatting() default DEFAULT_FORMATTING; - - /** - * Shuffles the order of tests generated for the parameter set. - */ - boolean shuffle() default true; -} diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/annotations/Repeat.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/annotations/Repeat.java deleted file mode 100644 index 46e2e3a4..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/annotations/Repeat.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.carrotsearch.randomizedtesting.annotations; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Inherited; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Repeats randomized test case a given number of times. Repetitions can - * start with a different seed (predictably derived from the first one) or - * start from the same seed every time (useful to check if a given test is truly - * predictable for a given seed or not). - */ -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.METHOD, ElementType.TYPE}) -@Inherited -public @interface Repeat { - /** - * Repeat this many iterations. Must be greater or equal 1. - */ - int iterations() default 1; - - /** - * Re-run all iterations with a constant seed. This may be helpful in checking - * if a given test is really predictably random. - */ - boolean useConstantSeed() default false; -} \ No newline at end of file diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/annotations/ReplicateOnEachVm.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/annotations/ReplicateOnEachVm.java deleted file mode 100644 index 8c6e4b3c..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/annotations/ReplicateOnEachVm.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.carrotsearch.randomizedtesting.annotations; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Inherited; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - *

      Replicates the test class on each concurrent forked JVM. If only a single JVM - * is used for running tests, this annotation has no effect.

      - * - *

      The purpose of this annotation is to, for example, replicate a single test suite - * across multiple forked JVMs and then selectively ignore or execute tests on each - * JVM, depending on its number, providing poor-man's load balancing for individual - * test cases (test suites are balanced by the framework itself).

      - */ -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.TYPE}) -@Inherited -public @interface ReplicateOnEachVm {} \ No newline at end of file diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/annotations/Seed.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/annotations/Seed.java deleted file mode 100644 index 8ef6fc3d..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/annotations/Seed.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.carrotsearch.randomizedtesting.annotations; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Inherited; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -import com.carrotsearch.randomizedtesting.SysGlobals; - -/** - * Defines the starting seed for a given test or the entire suite. - * - *

      If applied to the - * suite, it semantically overrides {@link SysGlobals#SYSPROP_RANDOM_SEED}, but - * does not affect individual test cases (these should be repeatable anyway).

      - * - *

      If applied to the method, it overrides the default randomized value that is derived - * from the global suite's seed.

      - * - *

      Typically, you'll want to override the class's seed to make the test repeat a "fixed" - * scenario. Occasionally if there's a single failing test case for repeated tests, one - * may want to override both to fix both the class's randomness and a given test case randomness. - */ -@Documented -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.METHOD, ElementType.TYPE}) -@Inherited -public @interface Seed { - /** - * The seed expressed as a hexadecimal long number or a string random to - * indicate randomized seed should be used (default value). - * - *

      The default value random can be used to construct a list of known - * seeds for which a test previously failed and a random seed in addition to that (coverage - * of previous failures + randomized run). See {@link Seeds} for more info. - */ - String value() default "random"; -} \ No newline at end of file diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/annotations/SeedDecorators.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/annotations/SeedDecorators.java deleted file mode 100644 index 45926fec..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/annotations/SeedDecorators.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.carrotsearch.randomizedtesting.annotations; - -import java.lang.annotation.*; - -import com.carrotsearch.randomizedtesting.SeedDecorator; - -/** - * Allows modifying the master seed (before the suite is started). - * - *

      Use this annotation when you want to perturb or modify the master seed. This may be - * useful if there are decisions taken in static contexts of multiple suites. In such a case - * these decisions would always be identical (because at static context level the seed is - * always derived from the same master). With a {@link SeedDecorator} one can perturb - * the seed for every suite. - * - *

        - *
      • Extra care should be used to make permutations consistent across different runs.
      • - *
      • Seed decorators must be thread-safe, re-entrable, preferably unsynchronized and - * must never fail!
      • - *
      - * - * @see #value() - */ -@Documented -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.TYPE}) -public @interface SeedDecorators { - /** - * - */ - Class[] value(); -} diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/annotations/Seeds.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/annotations/Seeds.java deleted file mode 100644 index ae238173..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/annotations/Seeds.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.carrotsearch.randomizedtesting.annotations; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Inherited; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Defines a list of starting seeds for a given test. - * - *

      Typically, you'll want to override the class's seed to make the test repeat a "fixed" - * scenario in which the test was known to fail in the past. In addition, you may still permit - * a randomized seed by adding a non-restricted {@link Seed} as in:

      - *
      - * {@literal @}{@link Seeds}({
      - *   {@literal @}{@link Seed}("deadbeef"),
      - *   {@literal @}{@link Seed}("cafebabe"), 
      - *   {@literal @}{@link Seed}()})
      - * 
      - */ -@Documented -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.METHOD}) -@Inherited -public @interface Seeds { - /** - * A non-empty array of {@link Seed}s. - */ - Seed [] value(); -} \ No newline at end of file diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/annotations/SuppressForbidden.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/annotations/SuppressForbidden.java deleted file mode 100644 index 1ad2647e..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/annotations/SuppressForbidden.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.carrotsearch.randomizedtesting.annotations; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Suppresses forbidden-API checks. - */ -@Retention(RetentionPolicy.CLASS) -@Target({ - ElementType.CONSTRUCTOR, - ElementType.FIELD, - ElementType.METHOD, - ElementType.TYPE }) -public @interface SuppressForbidden { - String value(); -} diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/annotations/TestCaseInstanceProvider.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/annotations/TestCaseInstanceProvider.java deleted file mode 100644 index 6b2400a5..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/annotations/TestCaseInstanceProvider.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.carrotsearch.randomizedtesting.annotations; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Inherited; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Determines how instances of the test suite class are created for each test - * case. - * - * By default JUnit creates a new class instance for every test to prevent test - * case ordering dependencies. This is sometimes inconvenient as there is no - * "suite" context other than static fields (which are a nuisance to clean up - * properly, for example). This annotation changes the default behavior and - * permits the test cases to be executed on the same instance, for example. - * - * Note that special care should be given to scenarios in which same-instance is - * reused with arguments provided via {@link ParametersFactory} (each set of - * parameters will create a separate instance, which will then be used to run - * all of test suite's test cases). - * - * Note that the same instance will be used if the test cases are multiplied - * with {@link Seeds} or {@link Repeat} annotations. - * - * @see TestCaseInstanceProvider.Type#INSTANCE_PER_TEST_METHOD - * @see TestCaseInstanceProvider.Type#INSTANCE_PER_CONSTRUCTOR_ARGS - */ -@Documented -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.TYPE}) -@Inherited -public @interface TestCaseInstanceProvider { - public static enum Type { - /** - * Each method (test case) will receive a new instance of the class. This is - * JUnit's default. - */ - INSTANCE_PER_TEST_METHOD, - - /** - * Each set of constructor arguments (provided from - * {@link ParametersFactory} or the default empty constructor) creates an - * instance that is then reused for all of the suite's tests. - */ - INSTANCE_PER_CONSTRUCTOR_ARGS; - } - - Type value() default Type.INSTANCE_PER_TEST_METHOD; -} diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/annotations/TestCaseOrdering.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/annotations/TestCaseOrdering.java deleted file mode 100644 index e58fa1e5..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/annotations/TestCaseOrdering.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.carrotsearch.randomizedtesting.annotations; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Inherited; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; -import java.util.Comparator; - -import com.carrotsearch.randomizedtesting.TestMethodAndParams; - -/** - * Test case ordering. The returned comparator will be used for sorting - * all {@link TestMethodAndParams} entries, where method is the test method - * and params are potential parameters to the constructor for a given - * test (if {@link ParametersFactory} is used). - * - * The sort is stable with respect to the original (shuffled) order of - * test cases. - */ -@Documented -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.TYPE}) -@Inherited -public @interface TestCaseOrdering { - /** - * The comparator used to sort all test cases. - * - * @see TestCaseOrdering - */ - Class> value(); - - /** - * Alphabetic, increasing order by method name. - */ - public static class AlphabeticOrder implements Comparator { - @Override - public int compare(TestMethodAndParams o1, TestMethodAndParams o2) { - return o1.getTestMethod().getName().compareTo( - o2.getTestMethod().getName()); - } - } -} diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/annotations/TestContextRandomSupplier.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/annotations/TestContextRandomSupplier.java deleted file mode 100644 index 36cfaf7e..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/annotations/TestContextRandomSupplier.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.carrotsearch.randomizedtesting.annotations; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Inherited; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; -import java.util.Random; - -import com.carrotsearch.randomizedtesting.RandomSupplier; -import com.carrotsearch.randomizedtesting.RandomizedContext; - -/** - * A supplier of {@link Random} instances for the {@link RandomizedContext}. The supplier class must declare - * a public no-arg constructor. - */ -@Documented -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.TYPE}) -@Inherited -public @interface TestContextRandomSupplier { - Class value(); -} diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/annotations/TestGroup.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/annotations/TestGroup.java deleted file mode 100644 index f3232283..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/annotations/TestGroup.java +++ /dev/null @@ -1,81 +0,0 @@ -package com.carrotsearch.randomizedtesting.annotations; - -import java.lang.annotation.Annotation; -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Inherited; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; -import java.util.Locale; - -import com.carrotsearch.randomizedtesting.RandomizedRunner; -import com.carrotsearch.randomizedtesting.SysGlobals; - -/** - * A test group applied to an annotation indicates that a given annotation - * can be used on individual tests as "labels". The meaning of these labels is - * mostly application-specific (example: {@link Nightly} which indicates slower, - * more intensive tests that are skipped during regular runs). - * - *

      {@link RandomizedRunner} collects groups from all tests in a suite. A group - * can be enabled or disabled using boolean system properties (or test - * hooks in the code). A test case is executed if it has no groups or if all of its groups - * are enabled. - */ -@Documented -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.ANNOTATION_TYPE}) -@Inherited -public @interface TestGroup { - /** - * The name of a test group. If not defined, the default (lowercased annotation - * name) is used. - */ - String name() default ""; - - /** - * System property used to enable/ disable a group. If empty, a default is used: - *

      -   * tests.name
      -   * 
      - */ - String sysProperty() default ""; - - /** - * Is the group enabled or disabled by default (unless overridden by test group filtering - * rules). - */ - boolean enabled() default true; - - /** - * Utilities to deal with annotations annotated with {@link TestGroup}. - */ - public static class Utilities { - public static String getGroupName(Class annotationClass) { - TestGroup testGroup = annotationClass.getAnnotation(TestGroup.class); - if (testGroup == null) - throw new IllegalArgumentException("Annotation must have a @TestGroup annotation: " - + annotationClass); - - String tmp = emptyToNull(testGroup.name()); - return tmp == null ? annotationClass.getSimpleName().toLowerCase(Locale.ROOT) : tmp; - } - - public static String getSysProperty(Class annotationClass) { - TestGroup testGroup = annotationClass.getAnnotation(TestGroup.class); - if (testGroup == null) - throw new IllegalArgumentException("Annotation must have a @TestGroup annotation: " - + annotationClass); - - String tmp = emptyToNull(testGroup.sysProperty()); - return (tmp != null ? tmp : SysGlobals.prefixProperty(getGroupName(annotationClass))); - } - - private static String emptyToNull(String value) { - if (value == null || value.trim().isEmpty()) - return null; - return value.trim(); - } - } -} diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/annotations/TestMethodProviders.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/annotations/TestMethodProviders.java deleted file mode 100644 index c485afcc..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/annotations/TestMethodProviders.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.carrotsearch.randomizedtesting.annotations; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Inherited; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -import com.carrotsearch.randomizedtesting.TestMethodProvider; - -/** - * Test case method provider. - * - * TODO: it would be nice to have an _instance_ provider as opposed to method provider, - * but it's hellishly difficult to integrate with the rest of the infrastructure (seeds, - * repetitions, etc.). - */ -@Documented -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.TYPE}) -@Inherited -public @interface TestMethodProviders { - Class[] value(); -} diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/annotations/ThreadLeakAction.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/annotations/ThreadLeakAction.java deleted file mode 100644 index 42410443..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/annotations/ThreadLeakAction.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.carrotsearch.randomizedtesting.annotations; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Inherited; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.METHOD, ElementType.TYPE}) -@Inherited -public @interface ThreadLeakAction { - public static enum Action { - /** Emit a warning using Java's logging system. */ - WARN, - - /** Try to {@link Thread#interrupt()} any leaked threads. */ - INTERRUPT; - }; - - Action [] value() default { Action.WARN, Action.INTERRUPT }; -} \ No newline at end of file diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/annotations/ThreadLeakFilters.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/annotations/ThreadLeakFilters.java deleted file mode 100644 index 018b6503..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/annotations/ThreadLeakFilters.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.carrotsearch.randomizedtesting.annotations; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Inherited; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -import com.carrotsearch.randomizedtesting.ThreadFilter; - -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.TYPE}) -@Inherited -public @interface ThreadLeakFilters { - boolean defaultFilters() default true; - Class [] filters() default {}; -} \ No newline at end of file diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/annotations/ThreadLeakGroup.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/annotations/ThreadLeakGroup.java deleted file mode 100644 index a05002d2..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/annotations/ThreadLeakGroup.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.carrotsearch.randomizedtesting.annotations; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Inherited; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.TYPE}) -@Inherited -public @interface ThreadLeakGroup { - public static enum Group { - /** - * All JVM threads will be tracked. - * - *

      WARNING: This option will not work - * on IBM J9 because of livelock bugs in {@link Thread#getAllStackTraces()}. - */ - ALL, - - /** - * The "main" thread group and descendants will be tracked. - */ - MAIN, - - /** - * Only per-suite test group and descendants will be tracked. - */ - TESTGROUP - } - - Group value() default Group.MAIN; -} \ No newline at end of file diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/annotations/ThreadLeakLingering.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/annotations/ThreadLeakLingering.java deleted file mode 100644 index 0d7f3a0d..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/annotations/ThreadLeakLingering.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.carrotsearch.randomizedtesting.annotations; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Inherited; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; -import java.util.Timer; -import java.util.concurrent.Executors; - -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.METHOD, ElementType.TYPE}) -@Inherited -public @interface ThreadLeakLingering { - /** - * Time in millis to "linger" for any left-behind threads. If equals 0, there - * is no waiting. - * - *

      - * This is particularly useful if there's no way to {@link Thread#join()} and - * wait for the potential forked threads to terminate. This is the case with - * {@link Timer} or {@link Executors} for example. - */ - int linger() default 0; -} \ No newline at end of file diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/annotations/ThreadLeakScope.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/annotations/ThreadLeakScope.java deleted file mode 100644 index 5daf6eec..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/annotations/ThreadLeakScope.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.carrotsearch.randomizedtesting.annotations; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Inherited; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -import org.junit.ClassRule; -import org.junit.Rule; - -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.TYPE}) -@Inherited -public @interface ThreadLeakScope { - public static enum Scope { - /** - * No thread leaks from any individual test (including {@link Rule}s) or the - * entire suite (including {@link ClassRule}s). - */ - TEST, - - /** - * No thread leaks from entire suite scope (individual tests may leak threads, - * they become part of the suite scope). - */ - SUITE, - - /** - * No thread leak checks at all. Highly discouraged. - */ - NONE - } - - Scope value() default Scope.TEST; -} \ No newline at end of file diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/annotations/ThreadLeakZombies.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/annotations/ThreadLeakZombies.java deleted file mode 100644 index bfff252d..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/annotations/ThreadLeakZombies.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.carrotsearch.randomizedtesting.annotations; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Inherited; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.TYPE}) -@Inherited -public @interface ThreadLeakZombies { - public static enum Consequence { - /** - * Continue execution with zombie threads running in the background as if - * nothing happened. This is NOT a good idea because zombie threads may be - * fiddling with the test instance or static fields. It is strongly - * recommended to use a combination of - * {@link ThreadLeakAction.Action#INTERRUPT} together with - * {@link #IGNORE_REMAINING_TESTS} to enforce interruption of leaked threads - * and if this does not succeed just ignore any tests further on. - *

      - * For the reasons outlined above, this enum flag is marked as - * {@link Deprecated}. It will be supported and will not be removed, - * however. - */ - @Deprecated - CONTINUE, - - /** - * Ignore any remaining tests once zombie threads have been detected. See - * {@link #CONTINUE} for joint use with {@link ThreadLeakAction}. - */ - IGNORE_REMAINING_TESTS; - }; - - Consequence value() default Consequence.IGNORE_REMAINING_TESTS; -} \ No newline at end of file diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/annotations/Timeout.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/annotations/Timeout.java deleted file mode 100644 index 94715002..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/annotations/Timeout.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.carrotsearch.randomizedtesting.annotations; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Inherited; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.rules.TestRule; - -import com.carrotsearch.randomizedtesting.RandomizedRunner; -import com.carrotsearch.randomizedtesting.SysGlobals; - -/** - * Maximum execution time for a single test method. Test methods are defined as - * any instance-scope {@link TestRule}s, {@link Before} and {@link After} hooks - * and {@link Test} methods. Suite class's constructor is not part of the - * measured code (see {@link TimeoutSuite}). - * - *

      - * Overrides a global default {@link RandomizedRunner#DEFAULT_TIMEOUT} or a - * system property override {@link SysGlobals#SYSPROP_TIMEOUT}. - * - * @see TimeoutSuite - */ -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.METHOD, ElementType.TYPE}) -@Inherited -public @interface Timeout { - /** - * Timeout time in millis. The timeout time is approximate, it may take longer - * to actually abort the test case. - */ - public int millis(); -} diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/annotations/TimeoutSuite.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/annotations/TimeoutSuite.java deleted file mode 100644 index ea55d58c..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/annotations/TimeoutSuite.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.carrotsearch.randomizedtesting.annotations; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Inherited; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.rules.TestRule; - -import com.carrotsearch.randomizedtesting.RandomizedRunner; -import com.carrotsearch.randomizedtesting.SysGlobals; - -/** - * Maximum execution time for an entire suite (including all hooks and tests). - * Suite is defined as any class-scope {@link TestRule}s, {@link BeforeClass} - * and {@link AfterClass} hooks, suite class's constructor, instance-scope - * {@link TestRule}s, {@link Before} and {@link After} hooks and {@link Test} - * methods. - * - *

      - * The suite class's static initializer is not part of the measured code - * (if you have static initializers in your tests, get rid of them). - * - *

      - * Overrides the global default {@link RandomizedRunner#DEFAULT_TIMEOUT} or a - * system property override {@link SysGlobals#SYSPROP_TIMEOUT}. - * - * @see Timeout - */ -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.TYPE}) -@Inherited -public @interface TimeoutSuite { - /** - * Timeout time in millis. The timeout time is approximate, it may take longer - * to actually abort the suite. - */ - public int millis(); -} diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/generators/ASCIIGenerator.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/generators/ASCIIGenerator.java deleted file mode 100644 index a2071088..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/generators/ASCIIGenerator.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.carrotsearch.randomizedtesting.generators; - -/** - * A generator emitting simple ASCII characters from the set - * (newlines not counted): - *

      - * abcdefghijklmnopqrstuvwxyz
      - * ABCDEFGHIJKLMNOPQRSTUVWXYZ
      - * 
      - * - * @deprecated Use {@link AsciiLettersGenerator} instead. - */ -@Deprecated -public class ASCIIGenerator extends AsciiLettersGenerator { - -} \ No newline at end of file diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/generators/AsciiAlphanumGenerator.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/generators/AsciiAlphanumGenerator.java deleted file mode 100644 index 8fce59c8..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/generators/AsciiAlphanumGenerator.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.carrotsearch.randomizedtesting.generators; - -/** - * A generator emitting simple ASCII alphanumeric letters and numbers - * from the set (newlines not counted): - *
      - * abcdefghijklmnopqrstuvwxyz
      - * ABCDEFGHIJKLMNOPQRSTUVWXYZ
      - * 0123456789
      - * 
      - */ -public class AsciiAlphanumGenerator extends CodepointSetGenerator { - private final static char [] CHARS = - ("abcdefghijklmnopqrstuvwxyz" + - "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + - "0123456789").toCharArray(); - - public AsciiAlphanumGenerator() { - super(CHARS); - } -} diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/generators/AsciiLettersGenerator.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/generators/AsciiLettersGenerator.java deleted file mode 100644 index 81cc2f08..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/generators/AsciiLettersGenerator.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.carrotsearch.randomizedtesting.generators; - -/** - * A generator emitting simple ASCII characters from the set - * (newlines not counted): - *
      - * abcdefghijklmnopqrstuvwxyz
      - * ABCDEFGHIJKLMNOPQRSTUVWXYZ
      - * 
      - */ -public class AsciiLettersGenerator extends CodepointSetGenerator { - private final static char [] CHARS = - ("abcdefghijklmnopqrstuvwxyz" + - "ABCDEFGHIJKLMNOPQRSTUVWXYZ").toCharArray(); - - public AsciiLettersGenerator() { - super(CHARS); - } -} diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/generators/BiasedNumbers.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/generators/BiasedNumbers.java deleted file mode 100644 index c11d4c50..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/generators/BiasedNumbers.java +++ /dev/null @@ -1,270 +0,0 @@ -package com.carrotsearch.randomizedtesting.generators; - -import java.util.Random; - -/** - * Utility classes for selecting numbers at random, but not necessarily - * in an uniform way. The implementation will try to pick "evil" numbers - * more often than uniform selection would. This includes exact range - * boundaries, numbers very close to range boundaries, numbers very close - * (or equal) to zero, etc. - * - * The exact method of selection is implementation-dependent and - * may change (if we find even more evil ways). - */ -public final class BiasedNumbers { - private static final int EVIL_RANGE_LEFT = 1; - private static final int EVIL_RANGE_RIGHT = 1; - private static final int EVIL_VERY_CLOSE_RANGE_ENDS = 20; - private static final int EVIL_ZERO_OR_NEAR = 5; - private static final int EVIL_SIMPLE_PROPORTION = 10; - private static final int EVIL_RANDOM_REPRESENTATION_BITS = 10; - - /** - * A random double between min (inclusive) and max - * (inclusive). If you wish to have an exclusive range, - * use {@link Math#nextAfter(double, double)} to adjust the range. - * - * The code was inspired by GeoTestUtil from Apache Lucene. - * - * @param min Left range boundary, inclusive. May be {@link Double#NEGATIVE_INFINITY}, but not NaN. - * @param max Right range boundary, inclusive. May be {@link Double#POSITIVE_INFINITY}, but not NaN. - */ - public static double randomDoubleBetween(Random r, double min, double max) { - assert max >= min : "max must be >= min: " + min + ", " + max; - assert !Double.isNaN(min) && !Double.isNaN(max); - - boolean hasZero = min <= 0 && max >= 0; - - int pick = r.nextInt( - EVIL_RANGE_LEFT + - EVIL_RANGE_RIGHT + - EVIL_VERY_CLOSE_RANGE_ENDS + - (hasZero ? EVIL_ZERO_OR_NEAR : 0) + - EVIL_SIMPLE_PROPORTION + - EVIL_RANDOM_REPRESENTATION_BITS); - - // Exact range ends - pick -= EVIL_RANGE_LEFT; - if (pick < 0 || min == max) { - return min; - } - - pick -= EVIL_RANGE_RIGHT; - if (pick < 0) { - return max; - } - - // If we're dealing with infinities, adjust them to discrete values. - assert min != max; - if (Double.isInfinite(min)) { - min = Math.nextUp(min); - } - if (Double.isInfinite(max)) { - max = Math.nextAfter(max, Double.NEGATIVE_INFINITY); - } - - // Numbers "very" close to range ends. "very" means a few floating point - // representation steps (ulps) away. - pick -= EVIL_VERY_CLOSE_RANGE_ENDS; - if (pick < 0) { - if (r.nextBoolean()) { - return fuzzUp(r, min, max); - } else { - return fuzzDown(r, max, min); - } - } - - // Zero or near-zero values, if within the range. - if (hasZero) { - pick -= EVIL_ZERO_OR_NEAR; - if (pick < 0) { - int v = r.nextInt(4); - if (v == 0) { - return 0d; - } else if (v == 1) { - return -0.0d; - } else if (v == 2) { - return fuzzDown(r, 0d, min); - } else if (v == 3) { - return fuzzUp(r, 0d, max); - } - } - } - - // Simple proportional selection. - pick -= EVIL_SIMPLE_PROPORTION; - if (pick < 0) { - return min + (max - min) * r.nextDouble(); - } - - // Random representation space selection. This will be heavily biased - // and overselect from the set of tiny values, if they're allowed. - pick -= EVIL_RANDOM_REPRESENTATION_BITS; - if (pick < 0) { - long from = toSortable(min); - long to = toSortable(max); - return fromSortable(RandomNumbers.randomLongBetween(r, from, to)); - } - - throw new RuntimeException("Unreachable."); - } - - /** - * Fuzzify the input value by decreasing it by a few ulps, but never past min. - */ - public static double fuzzDown(Random r, double v, double min) { - assert v >= min; - for (int steps = RandomNumbers.randomIntBetween(r, 1, 10); steps > 0 && v > min; steps--) { - v = Math.nextAfter(v, Double.NEGATIVE_INFINITY); - } - return v; - } - - /** - * Fuzzify the input value by increasing it by a few ulps, but never past max. - */ - public static double fuzzUp(Random r, double v, double max) { - assert v <= max; - for (int steps = RandomNumbers.randomIntBetween(r, 1, 10); steps > 0 && v < max; steps--) { - v = Math.nextUp(v); - } - return v; - } - - private static double fromSortable(long sortable) { - return Double.longBitsToDouble(flip(sortable)); - } - - private static long toSortable(double value) { - return flip(Double.doubleToLongBits(value)); - } - - private static long flip(long bits) { - return bits ^ (bits >> 63) & 0x7fffffffffffffffL; - } - - /** - * A random float between min (inclusive) and max - * (inclusive). If you wish to have an exclusive range, - * use {@link Math#nextAfter(float, double)} to adjust the range. - * - * The code was inspired by GeoTestUtil from Apache Lucene. - * - * @param min Left range boundary, inclusive. May be {@link Float#NEGATIVE_INFINITY}, but not NaN. - * @param max Right range boundary, inclusive. May be {@link Float#POSITIVE_INFINITY}, but not NaN. - */ - public static float randomFloatBetween(Random r, float min, float max) { - assert max >= min : "max must be >= min: " + min + ", " + max; - assert !Float.isNaN(min) && !Float.isNaN(max); - - boolean hasZero = min <= 0 && max >= 0; - - int pick = r.nextInt( - EVIL_RANGE_LEFT + - EVIL_RANGE_RIGHT + - EVIL_VERY_CLOSE_RANGE_ENDS + - (hasZero ? EVIL_ZERO_OR_NEAR : 0) + - EVIL_SIMPLE_PROPORTION + - EVIL_RANDOM_REPRESENTATION_BITS); - - // Exact range ends - pick -= EVIL_RANGE_LEFT; - if (pick < 0 || min == max) { - return min; - } - - pick -= EVIL_RANGE_RIGHT; - if (pick < 0) { - return max; - } - - // If we're dealing with infinities, adjust them to discrete values. - assert min != max; - if (Float.isInfinite(min)) { - min = Math.nextUp(min); - } - if (Float.isInfinite(max)) { - max = Math.nextAfter(max, Double.NEGATIVE_INFINITY); - } - - // Numbers "very" close to range ends. "very" means a few floating point - // representation steps (ulps) away. - pick -= EVIL_VERY_CLOSE_RANGE_ENDS; - if (pick < 0) { - if (r.nextBoolean()) { - return fuzzUp(r, min, max); - } else { - return fuzzDown(r, max, min); - } - } - - // Zero or near-zero values, if within the range. - if (hasZero) { - pick -= EVIL_ZERO_OR_NEAR; - if (pick < 0) { - int v = r.nextInt(4); - if (v == 0) { - return 0f; - } else if (v == 1) { - return -0.0f; - } else if (v == 2) { - return fuzzDown(r, 0f, min); - } else if (v == 3) { - return fuzzUp(r, 0f, max); - } - } - } - - // Simple proportional selection. - pick -= EVIL_SIMPLE_PROPORTION; - if (pick < 0) { - return (float) (min + (((double) max - min) * r.nextDouble())); - } - - // Random representation space selection. This will be heavily biased - // and overselect from the set of tiny values, if they're allowed. - pick -= EVIL_RANDOM_REPRESENTATION_BITS; - if (pick < 0) { - int from = toSortable(min); - int to = toSortable(max); - return fromSortable(RandomNumbers.randomIntBetween(r, from, to)); - } - - throw new RuntimeException("Unreachable."); - } - - /** - * Fuzzify the input value by decreasing it by a few ulps, but never past min. - */ - public static float fuzzDown(Random r, float v, float min) { - assert v >= min; - for (int steps = RandomNumbers.randomIntBetween(r, 1, 10); steps > 0 && v > min; steps--) { - v = Math.nextAfter(v, Double.NEGATIVE_INFINITY); - } - return v; - } - - /** - * Fuzzify the input value by increasing it by a few ulps, but never past max. - */ - public static float fuzzUp(Random r, float v, float max) { - assert v <= max; - for (int steps = RandomNumbers.randomIntBetween(r, 1, 10); steps > 0 && v < max; steps--) { - v = Math.nextUp(v); - } - return v; - } - - private static float fromSortable(int sortable) { - return Float.intBitsToFloat(flip(sortable)); - } - - private static int toSortable(float value) { - return flip(Float.floatToIntBits(value)); - } - - private static int flip(int floatBits) { - return floatBits ^ (floatBits >> 31) & 0x7fffffff; - } -} diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/generators/CodepointSetGenerator.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/generators/CodepointSetGenerator.java deleted file mode 100644 index 7de5909d..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/generators/CodepointSetGenerator.java +++ /dev/null @@ -1,139 +0,0 @@ -package com.carrotsearch.randomizedtesting.generators; - -import java.util.Random; - -/** - * A string generator from a predefined set of codepoints or characters. - */ -public class CodepointSetGenerator extends StringGenerator { - final int [] bmp; - final int [] supplementary; - final int [] all; - - /** - * All characters must be from BMP (no parts of surrogate pairs allowed). - */ - public CodepointSetGenerator(char[] chars) { - this.bmp = new int [chars.length]; - this.supplementary = new int [0]; - - for (int i = 0; i < chars.length; i++) { - bmp[i] = ((int) chars[i]) & 0xffff; - - if (isSurrogate(chars[i])) { - throw new IllegalArgumentException("Value is part of a surrogate pair: 0x" - + Integer.toHexString(bmp[i])); - } - } - - this.all = concat(bmp, supplementary); - if (all.length == 0) { - throw new IllegalArgumentException("Empty set of characters?"); - } - } - - /** - * Parse the given {@link String} and split into BMP and supplementary codepoints. - */ - public CodepointSetGenerator(String s) { - int bmps = 0; - int supplementaries = 0; - for (int i = 0; i < s.length();) { - int codepoint = s.codePointAt(i); - if (Character.isSupplementaryCodePoint(codepoint)) { - supplementaries++; - } else { - bmps++; - } - - i += Character.charCount(codepoint); - } - - this.bmp = new int [bmps]; - this.supplementary = new int [supplementaries]; - for (int i = 0; i < s.length();) { - int codepoint = s.codePointAt(i); - if (Character.isSupplementaryCodePoint(codepoint)) { - supplementary[--supplementaries] = codepoint; - } else { - bmp[--bmps] = codepoint; - } - - i += Character.charCount(codepoint); - } - - this.all = concat(bmp, supplementary); - if (all.length == 0) { - throw new IllegalArgumentException("Empty set of characters?"); - } - } - - @Override - public String ofCodeUnitsLength(Random r, int minCodeUnits, int maxCodeUnits) { - int length = RandomNumbers.randomIntBetween(r, minCodeUnits, maxCodeUnits); - - // Check and cater for odd number of code units if no bmp characters are given. - if (bmp.length == 0 && isOdd(length)) { - if (minCodeUnits == maxCodeUnits) { - throw new IllegalArgumentException("Cannot return an odd number of code units " - + " when surrogate pairs are the only available codepoints."); - } else { - // length is odd so we move forward or backward to the closest even number. - if (length == minCodeUnits) { - length++; - } else { - length--; - } - } - } - - int [] codepoints = new int [length]; - int actual = 0; - while (length > 0) { - if (length == 1) { - codepoints[actual] = bmp[r.nextInt(bmp.length)]; - } else { - codepoints[actual] = all[r.nextInt(all.length)]; - } - - if (Character.isSupplementaryCodePoint(codepoints[actual])) { - length -= 2; - } else { - length -= 1; - } - actual++; - } - return new String(codepoints, 0, actual); - } - - @Override - public String ofCodePointsLength(Random r, int minCodePoints, int maxCodePoints) { - int length = RandomNumbers.randomIntBetween(r, minCodePoints, maxCodePoints); - int [] codepoints = new int [length]; - while (length > 0) { - codepoints[--length] = all[r.nextInt(all.length)]; - } - return new String(codepoints, 0, codepoints.length); - } - - /** Is a given number odd? */ - private boolean isOdd(int v) { - return (v & 1) != 0; - } - - private int[] concat(int[]... arrays) { - int totalLength = 0; - for (int[] a : arrays) totalLength += a.length; - int [] concat = new int [totalLength]; - for (int i = 0, j = 0; j < arrays.length;) { - System.arraycopy(arrays[j], 0, concat, i, arrays[j].length); - i += arrays[j].length; - j++; - } - return concat; - } - - private boolean isSurrogate(char chr) { - return (chr >= 0xd800 && chr <= 0xdfff); - } -} diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/generators/RandomBytes.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/generators/RandomBytes.java deleted file mode 100644 index 3e8a70f9..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/generators/RandomBytes.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.carrotsearch.randomizedtesting.generators; - -import java.util.Random; - -/** - * Random byte sequence generators. - */ -public final class RandomBytes { - /** - * @param r Random generator. - * @param length The length of the byte array. Can be zero. - * @return Returns a byte array with random content. - */ - public static byte[] randomBytesOfLength(Random r, int length) { - return randomBytesOfLengthBetween(r, length, length); - } - - /** - * @param r Random generator. - * @param minLength The minimum length of the byte array. Can be zero. - * @param maxLength The maximum length of the byte array. Can be zero. - * @return Returns a byte array with random content. - */ - public static byte[] randomBytesOfLengthBetween(Random r, int minLength, int maxLength) { - byte[] bytes = new byte[RandomNumbers.randomIntBetween(r, minLength, maxLength)]; - for (int i = 0; i < bytes.length; i++) { - bytes[i] = (byte) r.nextInt(); - } - return bytes; - } -} diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/generators/RandomNumbers.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/generators/RandomNumbers.java deleted file mode 100644 index d66f291c..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/generators/RandomNumbers.java +++ /dev/null @@ -1,80 +0,0 @@ -package com.carrotsearch.randomizedtesting.generators; - -import java.util.Random; - -/** - * Utility classes for selecting random numbers from within a range or the - * numeric domain for a given type. - * - * @see BiasedNumbers - */ -public final class RandomNumbers { - /** - * A random integer between min (inclusive) and max (inclusive). - */ - public static int randomIntBetween(Random r, int min, int max) { - assert max >= min : "max must be >= min: " + min + ", " + max; - long range = (long) max - (long) min; - if (range < Integer.MAX_VALUE) { - return min + r.nextInt(1 + (int) range); - } else { - return toIntExact(min + nextLong(r, 1 + range)); - } - } - - /** - * A random long between min (inclusive) and max (inclusive). - */ - public static long randomLongBetween(Random r, long min, long max) { - assert max >= min : "max must be >= min: " + min + ", " + max; - long range = max - min; - if (range < 0) { - range -= Long.MAX_VALUE; - if (range == Long.MIN_VALUE) { - // Full spectrum. - return r.nextLong(); - } else { - long first = r.nextLong() & Long.MAX_VALUE; - long second = range == Long.MAX_VALUE ? (r.nextLong() & Long.MAX_VALUE) : nextLong(r, range + 1); - return min + first + second; - } - } else { - long second = range == Long.MAX_VALUE ? (r.nextLong() & Long.MAX_VALUE) : nextLong(r, range + 1); - return min + second; - } - } - - /** - * Similar to {@link Random#nextInt(int)}, but returns a long between - * 0 (inclusive) and n (exclusive). - * - * @param rnd Random generator. - * @param n the bound on the random number to be returned. Must be - * positive. - * @return Returns a random number between 0 and n-1. - */ - public static long nextLong(Random rnd, long n) { - if (n <= 0) { - throw new IllegalArgumentException("n <= 0: " + n); - } - - long value = rnd.nextLong(); - long range = n - 1; - if ((n & range) == 0L) { - value &= range; - } else { - for (long u = value >>> 1; u + range - (value = u % n) < 0L;) { - u = rnd.nextLong() >>> 1; - } - } - return value; - } - - private static int toIntExact(long value) { - if (value > Integer.MAX_VALUE) { - throw new ArithmeticException("Overflow: " + value); - } else { - return (int) value; - } - } -} diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/generators/RandomPicks.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/generators/RandomPicks.java deleted file mode 100644 index 2f153b1c..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/generators/RandomPicks.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.carrotsearch.randomizedtesting.generators; - -import java.util.Collection; -import java.util.Iterator; -import java.util.List; -import java.util.Random; - -/** - * Random selections of objects. - */ -public final class RandomPicks { - public static byte randomFrom(Random r, byte [] array) { checkZeroLength(array.length); return array[r.nextInt(array.length)]; } - public static short randomFrom(Random r, short [] array) { checkZeroLength(array.length); return array[r.nextInt(array.length)]; } - public static int randomFrom(Random r, int [] array) { checkZeroLength(array.length); return array[r.nextInt(array.length)]; } - public static char randomFrom(Random r, char [] array) { checkZeroLength(array.length); return array[r.nextInt(array.length)]; } - public static float randomFrom(Random r, float [] array) { checkZeroLength(array.length); return array[r.nextInt(array.length)]; } - public static long randomFrom(Random r, long [] array) { checkZeroLength(array.length); return array[r.nextInt(array.length)]; } - public static double randomFrom(Random r, double [] array) { checkZeroLength(array.length); return array[r.nextInt(array.length)]; } - - private static void checkZeroLength(int length) { - if (length == 0) { - throw new IllegalArgumentException("Can't pick a random object from an empty array."); - } - } - - /** - * Pick a random object from the given array. - */ - public static T randomFrom(Random r, T [] array) { - checkZeroLength(array.length); - return array[r.nextInt(array.length)]; - } - - /** - * Pick a random object from the given list. - */ - public static T randomFrom(Random r, List list) { - if (list.size() == 0) { - throw new IllegalArgumentException("Can't pick a random object from an empty list."); - } - return list.get(r.nextInt(list.size())); - } - - /** - * Pick a random object from the collection. Requires linear scanning. - */ - public static T randomFrom(Random r, Collection collection) { - final int size = collection.size(); - if (size == 0) { - throw new IllegalArgumentException("Can't pick a random object from an empty collection."); - } - int pick = r.nextInt(size); - T value = null; - for (Iterator i = collection.iterator();; pick--) { - value = i.next(); - if (pick == 0) { - break; - } - } - return value; - } -} diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/generators/RandomStrings.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/generators/RandomStrings.java deleted file mode 100644 index 6c580fe4..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/generators/RandomStrings.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.carrotsearch.randomizedtesting.generators; - -import java.util.Random; - -/** - * A facade to various implementations of {@link StringGenerator} interface. - */ -public final class RandomStrings { - public final static RealisticUnicodeGenerator realisticUnicodeGenerator = new RealisticUnicodeGenerator(); - public final static UnicodeGenerator unicodeGenerator = new UnicodeGenerator(); - public final static AsciiLettersGenerator asciiLettersGenerator = new AsciiLettersGenerator(); - public final static AsciiAlphanumGenerator asciiAlphanumGenerator = new AsciiAlphanumGenerator(); - - /** - * @deprecated Use {@link RandomStrings#asciiLettersGenerator} instead. - */ - @Deprecated - public final static ASCIIGenerator asciiGenerator = new ASCIIGenerator(); - - // Ultra wide monitor required to read the source code :) - - /** @deprecated Use {@link #randomAsciiLettersOfLengthBetween} instead. */ - @Deprecated - public static String randomAsciiOfLengthBetween (Random r, int minCodeUnits, int maxCodeUnits) {return asciiGenerator.ofCodeUnitsLength(r, minCodeUnits, maxCodeUnits); } - - /** @deprecated Use {@link #randomAsciiLettersOfLength} instead. */ - @Deprecated - public static String randomAsciiOfLength (Random r, int codeUnits) {return asciiGenerator.ofCodeUnitsLength(r, codeUnits, codeUnits); } - - public static String randomAsciiLettersOfLengthBetween (Random r, int minCodeUnits, int maxCodeUnits) {return asciiLettersGenerator.ofCodeUnitsLength(r, minCodeUnits, maxCodeUnits); } - public static String randomAsciiLettersOfLength (Random r, int codeUnits) {return asciiLettersGenerator.ofCodeUnitsLength(r, codeUnits, codeUnits); } - - public static String randomAsciiAlphanumOfLengthBetween (Random r, int minCodeUnits, int maxCodeUnits) {return asciiAlphanumGenerator.ofCodeUnitsLength(r, minCodeUnits, maxCodeUnits); } - public static String randomAsciiAlphanumOfLength (Random r, int codeUnits) {return asciiAlphanumGenerator.ofCodeUnitsLength(r, codeUnits, codeUnits); } - - public static String randomUnicodeOfLengthBetween (Random r, int minCodeUnits, int maxCodeUnits) {return unicodeGenerator.ofCodeUnitsLength(r, minCodeUnits, maxCodeUnits); } - public static String randomUnicodeOfLength (Random r, int codeUnits) {return unicodeGenerator.ofCodeUnitsLength(r, codeUnits, codeUnits); } - public static String randomUnicodeOfCodepointLengthBetween (Random r, int minCodePoints, int maxCodePoints) {return unicodeGenerator.ofCodePointsLength(r, minCodePoints, maxCodePoints); } - public static String randomUnicodeOfCodepointLength (Random r, int codePoints) {return unicodeGenerator.ofCodePointsLength(r, codePoints, codePoints); } - - public static String randomRealisticUnicodeOfLengthBetween (Random r, int minCodeUnits, int maxCodeUnits) {return realisticUnicodeGenerator.ofCodeUnitsLength(r, minCodeUnits, maxCodeUnits); } - public static String randomRealisticUnicodeOfLength (Random r, int codeUnits) {return realisticUnicodeGenerator.ofCodeUnitsLength(r, codeUnits, codeUnits); } - public static String randomRealisticUnicodeOfCodepointLengthBetween (Random r, int minCodePoints, int maxCodePoints) {return realisticUnicodeGenerator.ofCodePointsLength(r, minCodePoints, maxCodePoints); } - public static String randomRealisticUnicodeOfCodepointLength (Random r, int codePoints) {return realisticUnicodeGenerator.ofCodePointsLength(r, codePoints, codePoints); } -} diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/generators/RealisticUnicodeGenerator.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/generators/RealisticUnicodeGenerator.java deleted file mode 100644 index 786e060d..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/generators/RealisticUnicodeGenerator.java +++ /dev/null @@ -1,92 +0,0 @@ -package com.carrotsearch.randomizedtesting.generators; - -import java.util.Random; - -/** - * A string generator that emits valid unicodeGenerator codepoints. - */ -public class RealisticUnicodeGenerator extends StringGenerator { - /** Index-aligned with {@link #blockEnds}. */ - private static final int[] blockStarts = { - 0x0000, 0x0080, 0x0100, 0x0180, 0x0250, 0x02B0, 0x0300, 0x0370, 0x0400, - 0x0500, 0x0530, 0x0590, 0x0600, 0x0700, 0x0750, 0x0780, 0x07C0, 0x0800, - 0x0900, 0x0980, 0x0A00, 0x0A80, 0x0B00, 0x0B80, 0x0C00, 0x0C80, 0x0D00, - 0x0D80, 0x0E00, 0x0E80, 0x0F00, 0x1000, 0x10A0, 0x1100, 0x1200, 0x1380, - 0x13A0, 0x1400, 0x1680, 0x16A0, 0x1700, 0x1720, 0x1740, 0x1760, 0x1780, - 0x1800, 0x18B0, 0x1900, 0x1950, 0x1980, 0x19E0, 0x1A00, 0x1A20, 0x1B00, - 0x1B80, 0x1C00, 0x1C50, 0x1CD0, 0x1D00, 0x1D80, 0x1DC0, 0x1E00, 0x1F00, - 0x2000, 0x2070, 0x20A0, 0x20D0, 0x2100, 0x2150, 0x2190, 0x2200, 0x2300, - 0x2400, 0x2440, 0x2460, 0x2500, 0x2580, 0x25A0, 0x2600, 0x2700, 0x27C0, - 0x27F0, 0x2800, 0x2900, 0x2980, 0x2A00, 0x2B00, 0x2C00, 0x2C60, 0x2C80, - 0x2D00, 0x2D30, 0x2D80, 0x2DE0, 0x2E00, 0x2E80, 0x2F00, 0x2FF0, 0x3000, - 0x3040, 0x30A0, 0x3100, 0x3130, 0x3190, 0x31A0, 0x31C0, 0x31F0, 0x3200, - 0x3300, 0x3400, 0x4DC0, 0x4E00, 0xA000, 0xA490, 0xA4D0, 0xA500, 0xA640, - 0xA6A0, 0xA700, 0xA720, 0xA800, 0xA830, 0xA840, 0xA880, 0xA8E0, 0xA900, - 0xA930, 0xA960, 0xA980, 0xAA00, 0xAA60, 0xAA80, 0xABC0, 0xAC00, 0xD7B0, - 0xE000, 0xF900, 0xFB00, 0xFB50, 0xFE00, 0xFE10, - 0xFE20, 0xFE30, 0xFE50, 0xFE70, 0xFF00, 0xFFF0, - 0x10000, 0x10080, 0x10100, 0x10140, 0x10190, 0x101D0, 0x10280, 0x102A0, - 0x10300, 0x10330, 0x10380, 0x103A0, 0x10400, 0x10450, 0x10480, 0x10800, - 0x10840, 0x10900, 0x10920, 0x10A00, 0x10A60, 0x10B00, 0x10B40, 0x10B60, - 0x10C00, 0x10E60, 0x11080, 0x12000, 0x12400, 0x13000, 0x1D000, 0x1D100, - 0x1D200, 0x1D300, 0x1D360, 0x1D400, 0x1F000, 0x1F030, 0x1F100, 0x1F200, - 0x20000, 0x2A700, 0x2F800, 0xE0000, 0xE0100, 0xF0000, 0x100000 - }; - - /** Index-aligned with {@link #blockStarts}. */ - private static final int[] blockEnds = { - 0x007F, 0x00FF, 0x017F, 0x024F, 0x02AF, 0x02FF, 0x036F, 0x03FF, 0x04FF, - 0x052F, 0x058F, 0x05FF, 0x06FF, 0x074F, 0x077F, 0x07BF, 0x07FF, 0x083F, - 0x097F, 0x09FF, 0x0A7F, 0x0AFF, 0x0B7F, 0x0BFF, 0x0C7F, 0x0CFF, 0x0D7F, - 0x0DFF, 0x0E7F, 0x0EFF, 0x0FFF, 0x109F, 0x10FF, 0x11FF, 0x137F, 0x139F, - 0x13FF, 0x167F, 0x169F, 0x16FF, 0x171F, 0x173F, 0x175F, 0x177F, 0x17FF, - 0x18AF, 0x18FF, 0x194F, 0x197F, 0x19DF, 0x19FF, 0x1A1F, 0x1AAF, 0x1B7F, - 0x1BBF, 0x1C4F, 0x1C7F, 0x1CFF, 0x1D7F, 0x1DBF, 0x1DFF, 0x1EFF, 0x1FFF, - 0x206F, 0x209F, 0x20CF, 0x20FF, 0x214F, 0x218F, 0x21FF, 0x22FF, 0x23FF, - 0x243F, 0x245F, 0x24FF, 0x257F, 0x259F, 0x25FF, 0x26FF, 0x27BF, 0x27EF, - 0x27FF, 0x28FF, 0x297F, 0x29FF, 0x2AFF, 0x2BFF, 0x2C5F, 0x2C7F, 0x2CFF, - 0x2D2F, 0x2D7F, 0x2DDF, 0x2DFF, 0x2E7F, 0x2EFF, 0x2FDF, 0x2FFF, 0x303F, - 0x309F, 0x30FF, 0x312F, 0x318F, 0x319F, 0x31BF, 0x31EF, 0x31FF, 0x32FF, - 0x33FF, 0x4DBF, 0x4DFF, 0x9FFF, 0xA48F, 0xA4CF, 0xA4FF, 0xA63F, 0xA69F, - 0xA6FF, 0xA71F, 0xA7FF, 0xA82F, 0xA83F, 0xA87F, 0xA8DF, 0xA8FF, 0xA92F, - 0xA95F, 0xA97F, 0xA9DF, 0xAA5F, 0xAA7F, 0xAADF, 0xABFF, 0xD7AF, 0xD7FF, - 0xF8FF, 0xFAFF, 0xFB4F, 0xFDFF, 0xFE0F, 0xFE1F, - 0xFE2F, 0xFE4F, 0xFE6F, 0xFEFF, 0xFFEF, 0xFFFF, - 0x1007F, 0x100FF, 0x1013F, 0x1018F, 0x101CF, 0x101FF, 0x1029F, 0x102DF, - 0x1032F, 0x1034F, 0x1039F, 0x103DF, 0x1044F, 0x1047F, 0x104AF, 0x1083F, - 0x1085F, 0x1091F, 0x1093F, 0x10A5F, 0x10A7F, 0x10B3F, 0x10B5F, 0x10B7F, - 0x10C4F, 0x10E7F, 0x110CF, 0x123FF, 0x1247F, 0x1342F, 0x1D0FF, 0x1D1FF, - 0x1D24F, 0x1D35F, 0x1D37F, 0x1D7FF, 0x1F02F, 0x1F09F, 0x1F1FF, 0x1F2FF, - 0x2A6DF, 0x2B73F, 0x2FA1F, 0xE007F, 0xE01EF, 0xFFFFF, 0x10FFFF - }; - - @Override - public String ofCodeUnitsLength(Random r, int minCodeUnits, int maxCodeUnits) { - int length = RandomNumbers.randomIntBetween(r, minCodeUnits, maxCodeUnits); - final int block = r.nextInt(blockStarts.length); - - final StringBuilder sb = new StringBuilder(); - while (length > 0) { - int cp = RandomNumbers.randomIntBetween(r, blockStarts[block], blockEnds[block]); - if (length > Character.charCount(cp)) { - sb.appendCodePoint(cp); - length -= Character.charCount(cp); - } else { - // Padding for blocks that don't fit. - sb.appendCodePoint('a'); - length--; - } - } - return sb.toString(); - } - - @Override - public String ofCodePointsLength(Random r, int minCodePoints, int maxCodePoints) { - final int length = RandomNumbers.randomIntBetween(r, minCodePoints, maxCodePoints); - final int block = r.nextInt(blockStarts.length); - final StringBuilder sb = new StringBuilder(); - for (int i = 0; i < length; i++) - sb.appendCodePoint(RandomNumbers.randomIntBetween(r, blockStarts[block], blockEnds[block])); - return sb.toString(); - } -} diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/generators/StringGenerator.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/generators/StringGenerator.java deleted file mode 100644 index 2c8d5d9c..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/generators/StringGenerator.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.carrotsearch.randomizedtesting.generators; - -import java.util.Random; - -/** - * A {@link StringGenerator} generates random strings composed of characters. What these characters - * are and their distribution depends on a subclass. - * - * @see String - */ -public abstract class StringGenerator { - /** - * An alias for {@link #ofCodeUnitsLength(Random, int, int)}. - */ - public String ofStringLength(Random r, int minCodeUnits, int maxCodeUnits) { - return ofCodeUnitsLength(r, minCodeUnits, maxCodeUnits); - } - - /** - * @return Returns a string of variable length between minCodeUnits (inclusive) - * and maxCodeUnits (inclusive) length. Code units are essentially - * an equivalent of char type, see {@link String} class for - * explanation. - * - * @param minCodeUnits Minimum number of code units (inclusive). - * @param maxCodeUnits Maximum number of code units (inclusive). - * @throws IllegalArgumentException Thrown if the generator cannot emit random string - * of the given unit length. For example a generator emitting only extended unicodeGenerator - * plane characters (encoded as surrogate pairs) will not be able to emit an odd number - * of code units. - */ - public abstract String ofCodeUnitsLength(Random r, int minCodeUnits, int maxCodeUnits); - - /** - * @return Returns a string of variable length between minCodePoints (inclusive) - * and maxCodePoints (inclusive) length. Code points are full unicodeGenerator - * codepoints or an equivalent of int type, see {@link String} class for - * explanation. The returned {@link String#length()} may exceed maxCodeUnits - * because certain code points may be encoded as surrogate pairs. - * - * @param minCodePoints Minimum number of code points (inclusive). - * @param maxCodePoints Maximum number of code points (inclusive). - */ - public abstract String ofCodePointsLength(Random r, int minCodePoints, int maxCodePoints); -} diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/generators/UnicodeGenerator.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/generators/UnicodeGenerator.java deleted file mode 100644 index 66243746..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/generators/UnicodeGenerator.java +++ /dev/null @@ -1,92 +0,0 @@ -package com.carrotsearch.randomizedtesting.generators; - -import java.util.Random; - -/** - * A string generator that emits valid unicodeGenerator codepoints. - */ -public class UnicodeGenerator extends StringGenerator { - private final static int SURROGATE_RANGE = Character.MAX_SURROGATE - Character.MIN_SURROGATE + 1; - private final static int CODEPOINT_RANGE = Character.MAX_CODE_POINT - SURROGATE_RANGE; - - @Override - public String ofCodeUnitsLength(Random r, int minCodeUnits, int maxCodeUnits) { - int length = RandomNumbers.randomIntBetween(r, minCodeUnits, maxCodeUnits); - char [] chars = new char [length]; - for (int i = 0; i < chars.length;) { - final int t = RandomNumbers.randomIntBetween(r, 0, 4); - if (t == 0 && i < length - 1) { - // Make a surrogate pair - chars[i++] = (char) RandomNumbers.randomIntBetween(r, 0xd800, 0xdbff); // high - chars[i++] = (char) RandomNumbers.randomIntBetween(r, 0xdc00, 0xdfff); // low - } else if (t <= 1) { - chars[i++] = (char) RandomNumbers.randomIntBetween(r, 0, 0x007f); - } else if (t == 2) { - chars[i++] = (char) RandomNumbers.randomIntBetween(r, 0x80, 0x07ff); - } else if (t == 3) { - chars[i++] = (char) RandomNumbers.randomIntBetween(r, 0x800, 0xd7ff); - } else if (t == 4) { - chars[i++] = (char) RandomNumbers.randomIntBetween(r, 0xe000, 0xffff); - } - } - return new String(chars); - } - - @Override - public String ofCodePointsLength(Random r, int minCodePoints, int maxCodePoints) { - int length = RandomNumbers.randomIntBetween(r, minCodePoints, maxCodePoints); - int [] chars = new int [length]; - for (int i = 0; i < chars.length; i++) { - int v = RandomNumbers.randomIntBetween(r, 0, CODEPOINT_RANGE); - if (v >= Character.MIN_SURROGATE) - v += SURROGATE_RANGE; - chars[i] = v; - } - return new String(chars, 0, chars.length); - } - - /** - * Returns a random string that will have a random UTF-8 representation length between - * minUtf8Length and maxUtf8Length. - * - * @param minUtf8Length Minimum UTF-8 representation length (inclusive). - * @param maxUtf8Length Maximum UTF-8 representation length (inclusive). - */ - public String ofUtf8Length(Random r, int minUtf8Length, int maxUtf8Length) { - final int length = RandomNumbers.randomIntBetween(r, minUtf8Length, maxUtf8Length); - final char[] buffer = new char [length * 3]; - int bytes = length; - int i = 0; - for (; i < buffer.length && bytes != 0; i++) { - int t; - if (bytes >= 4) { - t = r.nextInt(5); - } else if (bytes >= 3) { - t = r.nextInt(4); - } else if (bytes >= 2) { - t = r.nextInt(2); - } else { - t = 0; - } - if (t == 0) { - buffer[i] = (char) RandomNumbers.randomIntBetween(r, 0, 0x7f); - bytes--; - } else if (1 == t) { - buffer[i] = (char) RandomNumbers.randomIntBetween(r, 0x80, 0x7ff); - bytes -= 2; - } else if (2 == t) { - buffer[i] = (char) RandomNumbers.randomIntBetween(r, 0x800, 0xd7ff); - bytes -= 3; - } else if (3 == t) { - buffer[i] = (char) RandomNumbers.randomIntBetween(r, 0xe000, 0xffff); - bytes -= 3; - } else if (4 == t) { - // Make a surrogate pair - buffer[i++] = (char) RandomNumbers.randomIntBetween(r, 0xd800, 0xdbff); // high - buffer[i] = (char) RandomNumbers.randomIntBetween(r, 0xdc00, 0xdfff); // low - bytes -= 4; - } - } - return new String(buffer, 0, i); - } -} diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/listeners/ReproduceInfoPrinter.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/listeners/ReproduceInfoPrinter.java deleted file mode 100644 index 4d384fe5..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/listeners/ReproduceInfoPrinter.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.carrotsearch.randomizedtesting.listeners; - -import org.junit.internal.AssumptionViolatedException; -import org.junit.runner.Description; -import org.junit.runner.notification.Failure; -import org.junit.runner.notification.RunListener; - -import com.carrotsearch.randomizedtesting.*; -import com.carrotsearch.randomizedtesting.annotations.SuppressForbidden; - -/** - * A {@link RunListener} that emits to {@link System#err} a string with command - * line parameters allowing quick test re-run under ANT command line. - */ -public class ReproduceInfoPrinter extends RunListener { - @Override - @SuppressForbidden("Legitimate use of syserr.") - public void testFailure(Failure failure) throws Exception { - // Ignore assumptions. - if (failure.getException() instanceof AssumptionViolatedException) { - return; - } - - final Description d = failure.getDescription(); - final StringBuilder b = new StringBuilder(); - b.append("FAILURE : ").append(d.getDisplayName()).append("\n"); - b.append("Message : " + failure.getMessage() + "\n"); - b.append("Reproduce: "); - new ReproduceErrorMessageBuilder(b).appendAllOpts(failure.getDescription()); - - b.append("\n"); - b.append("Throwable:\n"); - if (failure.getException() != null) { - TraceFormatting traces = new TraceFormatting(); - try { - traces = RandomizedContext.current().getRunner().getTraceFormatting(); - } catch (IllegalStateException e) { - // Ignore if no context. - } - traces.formatThrowable(b, failure.getException()); - } - - System.err.println(b.toString()); - } -} diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/rules/NoClassHooksShadowingRule.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/rules/NoClassHooksShadowingRule.java deleted file mode 100644 index 5e3c9f59..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/rules/NoClassHooksShadowingRule.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.carrotsearch.randomizedtesting.rules; - -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import org.junit.AfterClass; -import org.junit.BeforeClass; - -/** - * Don't allow {@link BeforeClass} and {@link AfterClass} hook shadowing as it is most - * likely a user error. JUnit rules for shadowed hook methods are weird. - */ -public class NoClassHooksShadowingRule extends NoShadowingOrOverridesOnMethodsRule { - public NoClassHooksShadowingRule() { - super(BeforeClass.class, AfterClass.class); - } -} - diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/rules/NoInstanceHooksOverridesRule.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/rules/NoInstanceHooksOverridesRule.java deleted file mode 100644 index 7f9addab..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/rules/NoInstanceHooksOverridesRule.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.carrotsearch.randomizedtesting.rules; - -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR 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.Before; - -/** - * Don't allow {@link Before} and {@link After} hook overrides as it is most - * likely a user error and will result in superclass methods not being called - * (requires manual chaining). - */ -public class NoInstanceHooksOverridesRule extends NoShadowingOrOverridesOnMethodsRule { - public NoInstanceHooksOverridesRule() { - super(Before.class, After.class); - } -} - diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/rules/NoShadowingOrOverridesOnMethodsRule.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/rules/NoShadowingOrOverridesOnMethodsRule.java deleted file mode 100644 index 26f7a4b1..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/rules/NoShadowingOrOverridesOnMethodsRule.java +++ /dev/null @@ -1,89 +0,0 @@ -package com.carrotsearch.randomizedtesting.rules; - -import java.lang.annotation.Annotation; -import java.lang.reflect.Method; -import java.util.Map; - -import org.junit.rules.TestRule; -import org.junit.runner.Description; -import org.junit.runners.model.Statement; - -import com.carrotsearch.randomizedtesting.ClassModel; -import com.carrotsearch.randomizedtesting.RandomizedContext; -import com.carrotsearch.randomizedtesting.ClassModel.MethodModel; - -/** - * Discovers shadowing or override relationships among methods annotated with any of the - * provided annotations. - */ -public abstract class NoShadowingOrOverridesOnMethodsRule implements TestRule { - private Class[] annotations; - - @SafeVarargs - public NoShadowingOrOverridesOnMethodsRule(Class... annotations) { - this.annotations = annotations; - } - - @Override - public final Statement apply(final Statement base, final Description description) { - return new Statement() { - @Override - public void evaluate() throws Throwable { - Class testClass; - try { - testClass = RandomizedContext.current().getTargetClass(); - } catch (Throwable t) { - testClass = description.getTestClass(); - } - - validate(testClass); - base.evaluate(); - } - }; - } - - public final void validate(Class clazz) throws Throwable { - ClassModel classModel = new ClassModel(clazz); - - for (Class annClass : annotations) { - checkNoShadowsOrOverrides(clazz, classModel, annClass); - } - } - - private void checkNoShadowsOrOverrides(Class clazz, ClassModel classModel, Class ann) { - Map annotatedLeafMethods = classModel.getAnnotatedLeafMethods(ann); - - StringBuilder b = new StringBuilder(); - for (Map.Entry e : annotatedLeafMethods.entrySet()) { - if (verify(e.getKey())) { - MethodModel mm = e.getValue(); - if (mm.getDown() != null || mm.getUp() != null) { - b.append("Methods annotated with @" + ann.getName() + " shadow or override each other:\n"); - while (mm.getUp() != null) { - mm = mm.getUp(); - } - while (mm != null) { - b.append(" - "); - if (mm.element.isAnnotationPresent(ann)) b.append("@").append(ann.getSimpleName()).append(" "); - b.append(signature(mm.element)).append("\n"); - mm = mm.getDown(); - } - } - } - } - - if (b.length() > 0) { - throw new RuntimeException("There are overridden methods annotated with " - + ann.getName() + ". These methods would not be executed by JUnit and need to manually chain themselves which can lead to" + - " maintenance problems. Consider using different method names or make hook methods private.\n" + b.toString().trim()); - } - } - - protected boolean verify(Method key) { - return true; - } - - private String signature(Method m) { - return m.toString(); - } -} diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/rules/RamUsageEstimator.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/rules/RamUsageEstimator.java deleted file mode 100644 index 74ca8186..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/rules/RamUsageEstimator.java +++ /dev/null @@ -1,987 +0,0 @@ - -/* - * Imported from java-sizeof project. - */ - -package com.carrotsearch.randomizedtesting.rules; - -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES 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.management.ManagementFactory; -import java.lang.reflect.Array; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.security.AccessController; -import java.security.PrivilegedAction; -import java.text.DecimalFormat; -import java.text.DecimalFormatSymbols; -import java.util.*; - -/** - * Estimates the size (memory representation) of Java objects. - * - * @see #sizeOf(Object) - * @see #shallowSizeOf(Object) - * @see #shallowSizeOfInstance(Class) - */ -final class RamUsageEstimator { - /** - * JVM diagnostic features. - */ - public static enum JvmFeature { - OBJECT_REFERENCE_SIZE("Object reference size estimated using array index scale."), - ARRAY_HEADER_SIZE("Array header size estimated using array based offset."), - FIELD_OFFSETS("Shallow instance size based on field offsets."), - OBJECT_ALIGNMENT("Object alignment retrieved from HotSpotDiagnostic MX bean."); - - public final String description; - - private JvmFeature(String description) { - this.description = description; - } - - @Override - public String toString() { - return super.name() + " (" + description + ")"; - } - } - - /** JVM info string for debugging and reports. */ - public final static String JVM_INFO_STRING; - - /** One kilobyte bytes. */ - public static final long ONE_KB = 1024; - - /** One megabyte bytes. */ - public static final long ONE_MB = ONE_KB * ONE_KB; - - /** One gigabyte bytes.*/ - public static final long ONE_GB = ONE_KB * ONE_MB; - - /** No instantiation. */ - private RamUsageEstimator() {} - - public final static int NUM_BYTES_BOOLEAN = 1; - public final static int NUM_BYTES_BYTE = 1; - public final static int NUM_BYTES_CHAR = 2; - public final static int NUM_BYTES_SHORT = 2; - public final static int NUM_BYTES_INT = 4; - public final static int NUM_BYTES_FLOAT = 4; - public final static int NUM_BYTES_LONG = 8; - public final static int NUM_BYTES_DOUBLE = 8; - - /** - * Number of bytes this jvm uses to represent an object reference. - */ - public final static int NUM_BYTES_OBJECT_REF; - - /** - * Number of bytes to represent an object header (no fields, no alignments). - */ - public final static int NUM_BYTES_OBJECT_HEADER; - - /** - * Number of bytes to represent an array header (no content, but with alignments). - */ - public final static int NUM_BYTES_ARRAY_HEADER; - - /** - * A constant specifying the object alignment boundary inside the JVM. Objects will - * always take a full multiple of this constant, possibly wasting some space. - */ - public final static int NUM_BYTES_OBJECT_ALIGNMENT; - - /** - * Sizes of primitive classes. - */ - private static final Map,Integer> primitiveSizes; - static { - primitiveSizes = new IdentityHashMap,Integer>(); - primitiveSizes.put(boolean.class, NUM_BYTES_BOOLEAN); - primitiveSizes.put(byte.class, NUM_BYTES_BYTE); - primitiveSizes.put(char.class, NUM_BYTES_CHAR); - primitiveSizes.put(short.class, NUM_BYTES_SHORT); - primitiveSizes.put(int.class, NUM_BYTES_INT); - primitiveSizes.put(float.class, NUM_BYTES_FLOAT); - primitiveSizes.put(double.class, NUM_BYTES_DOUBLE); - primitiveSizes.put(long.class, NUM_BYTES_LONG); - } - - /** - * A handle to sun.misc.Unsafe. - */ - private final static Object theUnsafe; - - /** - * A handle to sun.misc.Unsafe#fieldOffset(Field). - */ - private final static Method objectFieldOffsetMethod; - - /** - * All the supported "internal" JVM features detected at clinit. - */ - private final static EnumSet supportedFeatures; - - /** - * Initialize constants and try to collect information about the JVM internals. - */ - static { - // Initialize empirically measured defaults. We'll modify them to the current - // JVM settings later on if possible. - int referenceSize = Constants.JRE_IS_64BIT ? 8 : 4; - int objectHeader = Constants.JRE_IS_64BIT ? 16 : 8; - // The following is objectHeader + NUM_BYTES_INT, but aligned (object alignment) - // so on 64 bit JVMs it'll be align(16 + 4, @8) = 24. - int arrayHeader = Constants.JRE_IS_64BIT ? 24 : 12; - - supportedFeatures = EnumSet.noneOf(JvmFeature.class); - - Class unsafeClass = null; - Object tempTheUnsafe = null; - try { - unsafeClass = Class.forName("sun.misc.Unsafe"); - final Field unsafeField = unsafeClass.getDeclaredField("theUnsafe"); - unsafeField.setAccessible(true); - tempTheUnsafe = unsafeField.get(null); - } catch (Exception e) { - // Ignore. - } - theUnsafe = tempTheUnsafe; - - // get object reference size by getting scale factor of Object[] arrays: - try { - final Method arrayIndexScaleM = unsafeClass.getMethod("arrayIndexScale", Class.class); - referenceSize = ((Number) arrayIndexScaleM.invoke(theUnsafe, Object[].class)).intValue(); - supportedFeatures.add(JvmFeature.OBJECT_REFERENCE_SIZE); - } catch (Exception e) { - // ignore. - } - - // "best guess" based on reference size. We will attempt to modify - // these to exact values if there is supported infrastructure. - objectHeader = Constants.JRE_IS_64BIT ? (8 + referenceSize) : 8; - arrayHeader = Constants.JRE_IS_64BIT ? (8 + 2 * referenceSize) : 12; - - // get the object header size: - // - first try out if the field offsets are not scaled (see warning in Unsafe docs) - // - get the object header size by getting the field offset of the first field of a dummy object - // If the scaling is byte-wise and unsafe is available, enable dynamic size measurement for - // estimateRamUsage(). - Method tempObjectFieldOffsetMethod = null; - try { - final Method objectFieldOffsetM = unsafeClass.getMethod("objectFieldOffset", Field.class); - final Field dummy1Field = DummyTwoLongObject.class.getDeclaredField("dummy1"); - final int ofs1 = ((Number) objectFieldOffsetM.invoke(theUnsafe, dummy1Field)).intValue(); - final Field dummy2Field = DummyTwoLongObject.class.getDeclaredField("dummy2"); - final int ofs2 = ((Number) objectFieldOffsetM.invoke(theUnsafe, dummy2Field)).intValue(); - if (Math.abs(ofs2 - ofs1) == NUM_BYTES_LONG) { - final Field baseField = DummyOneFieldObject.class.getDeclaredField("base"); - objectHeader = ((Number) objectFieldOffsetM.invoke(theUnsafe, baseField)).intValue(); - supportedFeatures.add(JvmFeature.FIELD_OFFSETS); - tempObjectFieldOffsetMethod = objectFieldOffsetM; - } - } catch (Exception e) { - // Ignore. - } - objectFieldOffsetMethod = tempObjectFieldOffsetMethod; - - // Get the array header size by retrieving the array base offset - // (offset of the first element of an array). - try { - final Method arrayBaseOffsetM = unsafeClass.getMethod("arrayBaseOffset", Class.class); - // we calculate that only for byte[] arrays, it's actually the same for all types: - arrayHeader = ((Number) arrayBaseOffsetM.invoke(theUnsafe, byte[].class)).intValue(); - supportedFeatures.add(JvmFeature.ARRAY_HEADER_SIZE); - } catch (Exception e) { - // Ignore. - } - - NUM_BYTES_OBJECT_REF = referenceSize; - NUM_BYTES_OBJECT_HEADER = objectHeader; - NUM_BYTES_ARRAY_HEADER = arrayHeader; - - // Try to get the object alignment (the default seems to be 8 on Hotspot, - // regardless of the architecture). - int objectAlignment = 8; - try { - final Class beanClazz = Class.forName("com.sun.management.HotSpotDiagnosticMXBean"); - // Try to get the diagnostic mxbean without calling {@link ManagementFactory#getPlatformMBeanServer()} - // which starts AWT thread (and shows junk in the dock) on a Mac: - Object hotSpotBean; - // Java 7+, HotSpot - try { - hotSpotBean = ManagementFactory.class - .getMethod("getPlatformMXBean", Class.class) - .invoke(null, beanClazz); - } catch (Exception e1) { - // Java 6, HotSpot - try { - Class sunMF = Class.forName("sun.management.ManagementFactory"); - hotSpotBean = sunMF.getMethod("getDiagnosticMXBean").invoke(null); - } catch (Exception e2) { - // Last resort option is an attempt to get it from ManagementFactory's server anyway (may start AWT). - hotSpotBean = ManagementFactory.newPlatformMXBeanProxy( - ManagementFactory.getPlatformMBeanServer(), - "com.sun.management:type=HotSpotDiagnostic", beanClazz); - } - } - if (hotSpotBean != null) { - final Method getVMOptionMethod = beanClazz.getMethod("getVMOption", String.class); - final Object vmOption = getVMOptionMethod.invoke(hotSpotBean, "ObjectAlignmentInBytes"); - objectAlignment = Integer.parseInt( - vmOption.getClass().getMethod("getValue").invoke(vmOption).toString()); - supportedFeatures.add(JvmFeature.OBJECT_ALIGNMENT); - } - } catch (Exception e) { - // Ignore. - } - - NUM_BYTES_OBJECT_ALIGNMENT = objectAlignment; - - JVM_INFO_STRING = "[JVM: " + - Constants.JVM_NAME + ", " + Constants.JVM_VERSION + ", " + Constants.JVM_VENDOR + ", " + - Constants.JAVA_VENDOR + ", " + Constants.JAVA_VERSION + "]"; - } - - /** - * Cached information about a given class. - */ - private static final class ClassCache { - public final long alignedShallowInstanceSize; - public final Field[] referenceFields; - - public ClassCache(long alignedShallowInstanceSize, Field[] referenceFields) { - this.alignedShallowInstanceSize = alignedShallowInstanceSize; - this.referenceFields = referenceFields; - } - } - - // Object with just one field to determine the object header size by getting the offset of the dummy field: - @SuppressWarnings("unused") - private static final class DummyOneFieldObject { - public byte base; - } - - // Another test object for checking, if the difference in offsets of dummy1 and dummy2 is 8 bytes. - // Only then we can be sure that those are real, unscaled offsets: - @SuppressWarnings("unused") - private static final class DummyTwoLongObject { - public long dummy1, dummy2; - } - - /** - * Returns true, if the current JVM is fully supported by {@code RamUsageEstimator}. - * If this method returns {@code false} you are maybe using a 3rd party Java VM - * that is not supporting Oracle/Sun private APIs. The memory estimates can be - * imprecise then (no way of detecting compressed references, alignments, etc.). - * Lucene still tries to use sensible defaults. - */ - public static boolean isSupportedJVM() { - return supportedFeatures.size() == JvmFeature.values().length; - } - - /** - * Aligns an object size to be the next multiple of {@link #NUM_BYTES_OBJECT_ALIGNMENT}. - */ - public static long alignObjectSize(long size) { - size += (long) NUM_BYTES_OBJECT_ALIGNMENT - 1L; - return size - (size % NUM_BYTES_OBJECT_ALIGNMENT); - } - - /** Returns the size in bytes of the byte[] object. */ - public static long sizeOf(byte[] arr) { - return alignObjectSize((long) NUM_BYTES_ARRAY_HEADER + arr.length); - } - - /** Returns the size in bytes of the boolean[] object. */ - public static long sizeOf(boolean[] arr) { - return alignObjectSize((long) NUM_BYTES_ARRAY_HEADER + arr.length); - } - - /** Returns the size in bytes of the char[] object. */ - public static long sizeOf(char[] arr) { - return alignObjectSize((long) NUM_BYTES_ARRAY_HEADER + (long) NUM_BYTES_CHAR * arr.length); - } - - /** Returns the size in bytes of the short[] object. */ - public static long sizeOf(short[] arr) { - return alignObjectSize((long) NUM_BYTES_ARRAY_HEADER + (long) NUM_BYTES_SHORT * arr.length); - } - - /** Returns the size in bytes of the int[] object. */ - public static long sizeOf(int[] arr) { - return alignObjectSize((long) NUM_BYTES_ARRAY_HEADER + (long) NUM_BYTES_INT * arr.length); - } - - /** Returns the size in bytes of the float[] object. */ - public static long sizeOf(float[] arr) { - return alignObjectSize((long) NUM_BYTES_ARRAY_HEADER + (long) NUM_BYTES_FLOAT * arr.length); - } - - /** Returns the size in bytes of the long[] object. */ - public static long sizeOf(long[] arr) { - return alignObjectSize((long) NUM_BYTES_ARRAY_HEADER + (long) NUM_BYTES_LONG * arr.length); - } - - /** Returns the size in bytes of the double[] object. */ - public static long sizeOf(double[] arr) { - return alignObjectSize((long) NUM_BYTES_ARRAY_HEADER + (long) NUM_BYTES_DOUBLE * arr.length); - } - - /** - * Estimates the RAM usage by the given object. It will - * walk the object tree and sum up all referenced objects. - * - *

      Resource Usage: This method internally uses a set of - * every object seen during traversals so it does allocate memory - * (it isn't side-effect free). After the method exits, this memory - * should be GCed.

      - */ - public static long sizeOf(Object obj) { - ArrayList stack = new ArrayList(); - stack.add(obj); - return measureSizeOf(stack); - } - - /** - * Same as {@link #sizeOf(Object)} but sums up all the arguments. Not an - * overload to prevent accidental parameter conflicts with {@link #sizeOf(Object)}. - */ - public static long sizeOfAll(Object... objects) { - return sizeOfAll(Arrays.asList(objects)); - } - - /** - * Same as {@link #sizeOf(Object)} but sums up all the arguments. Not an - * overload to prevent accidental parameter conflicts with {@link #sizeOf(Object)}. - */ - public static long sizeOfAll(Iterable objects) { - final ArrayList stack; - if (objects instanceof Collection) { - stack = new ArrayList(((Collection) objects).size()); - } else { - stack = new ArrayList(); - } - - for (Object o : objects) { - stack.add(o); - } - - return measureSizeOf(stack); - } - - /** - * Estimates a "shallow" memory usage of the given object. For arrays, this will be the - * memory taken by array storage (no subreferences will be followed). For objects, this - * will be the memory taken by the fields. - * - * JVM object alignments are also applied. - */ - public static long shallowSizeOf(Object obj) { - if (obj == null) return 0; - final Class clz = obj.getClass(); - if (clz.isArray()) { - return shallowSizeOfArray(obj); - } else { - return shallowSizeOfInstance(clz); - } - } - - /** - * Same as {@link #shallowSizeOf(Object)} but sums up all the arguments. Not an - * overload to prevent accidental parameter conflicts with {@link #shallowSizeOf(Object)}. - */ - public static long shallowSizeOfAll(Object... objects) { - return shallowSizeOfAll(Arrays.asList(objects)); - } - - /** - * Same as {@link #shallowSizeOf(Object)} but sums up all the arguments. Duplicate - * objects are not resolved and will be counted twice. - * Not an overload to prevent accidental parameter conflicts with - * {@link #shallowSizeOf(Object)}. - */ - public static long shallowSizeOfAll(Iterable objects) { - long sum = 0; - for (Object o : objects) { - sum += shallowSizeOf(o); - } - return sum; - } - - /** - * Returns the shallow instance size in bytes an instance of the given class would occupy. - * This works with all conventional classes and primitive types, but not with arrays - * (the size then depends on the number of elements and varies from object to object). - * - * @see #shallowSizeOf(Object) - * @throws IllegalArgumentException if {@code clazz} is an array class. - */ - public static long shallowSizeOfInstance(Class clazz) { - if (clazz.isArray()) - throw new IllegalArgumentException("This method does not work with array classes."); - if (clazz.isPrimitive()) - return primitiveSizes.get(clazz); - - long size = NUM_BYTES_OBJECT_HEADER; - - // Walk type hierarchy - for (;clazz != null; clazz = clazz.getSuperclass()) { - final Class target = clazz; - final Field[] fields = AccessController.doPrivileged(new PrivilegedAction() { - @Override - public Field[] run() { - return target.getDeclaredFields(); - } - }); - for (Field f : fields) { - if (!Modifier.isStatic(f.getModifiers())) { - size = adjustForField(size, f); - } - } - } - return alignObjectSize(size); - } - - /** Return the set of unsupported JVM features that improve the estimation. */ - public static EnumSet getUnsupportedFeatures() { - EnumSet unsupported = EnumSet.allOf(JvmFeature.class); - unsupported.removeAll(supportedFeatures); - return unsupported; - } - - /** Return the set of supported JVM features that improve the estimation. */ - public static EnumSet getSupportedFeatures() { - return EnumSet.copyOf(supportedFeatures); - } - - /** - * Return shallow size of any array. - */ - private static long shallowSizeOfArray(Object array) { - long size = NUM_BYTES_ARRAY_HEADER; - final int len = Array.getLength(array); - if (len > 0) { - Class arrayElementClazz = array.getClass().getComponentType(); - if (arrayElementClazz.isPrimitive()) { - size += (long) len * primitiveSizes.get(arrayElementClazz); - } else { - size += (long) NUM_BYTES_OBJECT_REF * len; - } - } - return alignObjectSize(size); - } - - /** - * Non-recursive version of object descend. This consumes more memory than recursive in-depth - * traversal but prevents stack overflows on long chains of objects - * or complex graphs (a max. recursion depth on my machine was ~5000 objects linked in a chain - * so not too much). - * - * @param stack Root objects. - */ - private static long measureSizeOf(ArrayList stack) { - final IdentityHashSet seen = new IdentityHashSet(); - final IdentityHashMap, ClassCache> classCache = new IdentityHashMap, ClassCache>(); - - long totalSize = 0; - while (!stack.isEmpty()) { - final Object ob = stack.remove(stack.size() - 1); - - if (ob == null || seen.contains(ob)) { - continue; - } - seen.add(ob); - - final Class obClazz = ob.getClass(); - if (obClazz.isArray()) { - /* - * Consider an array, possibly of primitive types. Push any of its references to - * the processing stack and accumulate this array's shallow size. - */ - long size = NUM_BYTES_ARRAY_HEADER; - final int len = Array.getLength(ob); - if (len > 0) { - Class componentClazz = obClazz.getComponentType(); - if (componentClazz.isPrimitive()) { - size += (long) len * primitiveSizes.get(componentClazz); - } else { - size += (long) NUM_BYTES_OBJECT_REF * len; - - for (int i = len; --i >= 0 ;) { - final Object o = Array.get(ob, i); - if (o != null && !seen.contains(o)) { - stack.add(o); - } - } - } - } - totalSize += alignObjectSize(size); - } else { - /* - * Consider an object. Push any references it has to the processing stack - * and accumulate this object's shallow size. - */ - try { - ClassCache cachedInfo = classCache.get(obClazz); - if (cachedInfo == null) { - classCache.put(obClazz, cachedInfo = createCacheEntry(obClazz)); - } - - for (Field f : cachedInfo.referenceFields) { - // Fast path to eliminate redundancies. - final Object o = f.get(ob); - if (o != null && !seen.contains(o)) { - stack.add(o); - } - } - - totalSize += cachedInfo.alignedShallowInstanceSize; - } catch (IllegalAccessException e) { - // this should never happen as we enabled setAccessible(). - throw new RuntimeException("Reflective field access failed?", e); - } - } - } - - // Help the GC. - seen.clear(); - stack.clear(); - classCache.clear(); - - return totalSize; - } - - /** - * Create a cached information about shallow size and reference fields for - * a given class. - */ - private static ClassCache createCacheEntry(final Class clazz) { - ClassCache cachedInfo; - long shallowInstanceSize = NUM_BYTES_OBJECT_HEADER; - final ArrayList referenceFields = new ArrayList(32); - for (Class c = clazz; c != null; c = c.getSuperclass()) { - final Class target = clazz; - final Field[] fields = AccessController.doPrivileged(new PrivilegedAction() { - @Override - public Field[] run() { - return target.getDeclaredFields(); - } - }); - for (final Field f : fields) { - if (!Modifier.isStatic(f.getModifiers())) { - shallowInstanceSize = adjustForField(shallowInstanceSize, f); - - if (!f.getType().isPrimitive()) { - try { - AccessController.doPrivileged(new PrivilegedAction() { - @Override - public Void run() { - f.setAccessible(true); - return null; - } - }); - } catch (Exception e) { - throw new IllegalStateException("Unable to access '" + f + "' to estimate memory usage", e); - } - referenceFields.add(f); - } - } - } - } - - cachedInfo = new ClassCache( - alignObjectSize(shallowInstanceSize), - referenceFields.toArray(new Field[referenceFields.size()])); - return cachedInfo; - } - - /** - * This method returns the maximum representation size of an object. sizeSoFar - * is the object's size measured so far. f is the field being probed. - * - *

      The returned offset will be the maximum of whatever was measured so far and - * f field's offset and representation size (unaligned). - */ - private static long adjustForField(long sizeSoFar, final Field f) { - final Class type = f.getType(); - final int fsize = type.isPrimitive() ? primitiveSizes.get(type) : NUM_BYTES_OBJECT_REF; - if (objectFieldOffsetMethod != null) { - try { - final long offsetPlusSize = - ((Number) objectFieldOffsetMethod.invoke(theUnsafe, f)).longValue() + fsize; - return Math.max(sizeSoFar, offsetPlusSize); - } catch (IllegalAccessException ex) { - throw new RuntimeException("Access problem with sun.misc.Unsafe", ex); - } catch (InvocationTargetException ite) { - final Throwable cause = ite.getCause(); - if (cause instanceof RuntimeException) - throw (RuntimeException) cause; - if (cause instanceof Error) - throw (Error) cause; - // this should never happen (Unsafe does not declare - // checked Exceptions for this method), but who knows? - throw new RuntimeException("Call to Unsafe's objectFieldOffset() throwed "+ - "checked Exception when accessing field " + - f.getDeclaringClass().getName() + "#" + f.getName(), cause); - } - } else { - // No alignments based on field type/ subclass fields alignments? - return sizeSoFar + fsize; - } - } - - /** - * Returns size in human-readable units (GB, MB, KB or bytes). - */ - public static String humanReadableUnits(long bytes) { - return humanReadableUnits(bytes, - new DecimalFormat("0.#", DecimalFormatSymbols.getInstance(Locale.ROOT))); - } - - /** - * Returns size in human-readable units (GB, MB, KB or bytes). - */ - public static String humanReadableUnits(long bytes, DecimalFormat df) { - if (bytes / ONE_GB > 0) { - return df.format((float) bytes / ONE_GB) + " GB"; - } else if (bytes / ONE_MB > 0) { - return df.format((float) bytes / ONE_MB) + " MB"; - } else if (bytes / ONE_KB > 0) { - return df.format((float) bytes / ONE_KB) + " KB"; - } else { - return bytes + " bytes"; - } - } - - /** - * Return a human-readable size of a given object. - * @see #sizeOf(Object) - * @see #humanReadableUnits(long) - */ - public static String humanSizeOf(Object object) { - return humanReadableUnits(sizeOf(object)); - } -} - -/** - * An identity hash set implemented using open addressing. No null keys are allowed. - */ -final class IdentityHashSet implements Iterable { - /** - * Default load factor. - */ - public final static float DEFAULT_LOAD_FACTOR = 0.75f; - - /** - * Minimum capacity for the set. - */ - public final static int MIN_CAPACITY = 4; - - /** - * All of set entries. Always of power of two length. - */ - public Object[] keys; - - /** - * Cached number of assigned slots. - */ - public int assigned; - - /** - * The load factor for this set (fraction of allocated or deleted slots before - * the buffers must be rehashed or reallocated). - */ - public final float loadFactor; - - /** - * Cached capacity threshold at which we must resize the buffers. - */ - private int resizeThreshold; - - /** - * Creates a hash set with the default capacity of 16. - * load factor of {@value #DEFAULT_LOAD_FACTOR}. ` - */ - public IdentityHashSet() { - this(16, DEFAULT_LOAD_FACTOR); - } - - /** - * Creates a hash set with the given capacity, load factor of - * {@value #DEFAULT_LOAD_FACTOR}. - */ - public IdentityHashSet(int initialCapacity) { - this(initialCapacity, DEFAULT_LOAD_FACTOR); - } - - /** - * Creates a hash set with the given capacity and load factor. - */ - public IdentityHashSet(int initialCapacity, float loadFactor) { - initialCapacity = Math.max(MIN_CAPACITY, initialCapacity); - - assert initialCapacity > 0 : "Initial capacity must be between (0, " - + Integer.MAX_VALUE + "]."; - assert loadFactor > 0 && loadFactor < 1 : "Load factor must be between (0, 1)."; - this.loadFactor = loadFactor; - allocateBuffers(roundCapacity(initialCapacity)); - } - - /** - * Adds a reference to the set. Null keys are not allowed. - */ - public boolean add(KType e) { - assert e != null : "Null keys not allowed."; - - if (assigned >= resizeThreshold) expandAndRehash(); - - final int mask = keys.length - 1; - int slot = rehash(e) & mask; - Object existing; - while ((existing = keys[slot]) != null) { - if (e == existing) { - return false; // already found. - } - slot = (slot + 1) & mask; - } - assigned++; - keys[slot] = e; - return true; - } - - /** - * Checks if the set contains a given ref. - */ - public boolean contains(KType e) { - final int mask = keys.length - 1; - int slot = rehash(e) & mask; - Object existing; - while ((existing = keys[slot]) != null) { - if (e == existing) { - return true; - } - slot = (slot + 1) & mask; - } - return false; - } - - /** Rehash via MurmurHash. */ - private static int rehash(Object o) { - return MurmurHash3.hash(System.identityHashCode(o)); - } - - /** - * Expand the internal storage buffers (capacity) or rehash current keys and - * values if there are a lot of deleted slots. - */ - private void expandAndRehash() { - final Object[] oldKeys = this.keys; - - assert assigned >= resizeThreshold; - allocateBuffers(nextCapacity(keys.length)); - - /* - * Rehash all assigned slots from the old hash table. - */ - final int mask = keys.length - 1; - for (int i = 0; i < oldKeys.length; i++) { - final Object key = oldKeys[i]; - if (key != null) { - int slot = rehash(key) & mask; - while (keys[slot] != null) { - slot = (slot + 1) & mask; - } - keys[slot] = key; - } - } - Arrays.fill(oldKeys, null); - } - - /** - * Allocate internal buffers for a given capacity. - * - * @param capacity - * New capacity (must be a power of two). - */ - private void allocateBuffers(int capacity) { - this.keys = new Object[capacity]; - this.resizeThreshold = (int) (capacity * DEFAULT_LOAD_FACTOR); - } - - /** - * Return the next possible capacity, counting from the current buffers' size. - */ - protected int nextCapacity(int current) { - assert current > 0 && Long.bitCount(current) == 1 : "Capacity must be a power of two."; - assert ((current << 1) > 0) : "Maximum capacity exceeded (" - + (0x80000000 >>> 1) + ")."; - - if (current < MIN_CAPACITY / 2) current = MIN_CAPACITY / 2; - return current << 1; - } - - /** - * Round the capacity to the next allowed value. - */ - protected int roundCapacity(int requestedCapacity) { - // Maximum positive integer that is a power of two. - if (requestedCapacity > (0x80000000 >>> 1)) return (0x80000000 >>> 1); - - int capacity = MIN_CAPACITY; - while (capacity < requestedCapacity) { - capacity <<= 1; - } - - return capacity; - } - - public void clear() { - assigned = 0; - Arrays.fill(keys, null); - } - - public int size() { - return assigned; - } - - public boolean isEmpty() { - return size() == 0; - } - - @Override - public Iterator iterator() { - return new Iterator() { - int pos = -1; - Object nextElement = fetchNext(); - - @Override - public boolean hasNext() { - return nextElement != null; - } - - @SuppressWarnings("unchecked") - @Override - public KType next() { - Object r = this.nextElement; - if (r == null) { - throw new NoSuchElementException(); - } - this.nextElement = fetchNext(); - return (KType) r; - } - - private Object fetchNext() { - pos++; - while (pos < keys.length && keys[pos] == null) { - pos++; - } - - return (pos >= keys.length ? null : keys[pos]); - } - - @Override - public void remove() { - throw new UnsupportedOperationException(); - } - }; - } -} - -/** - * Hash routines for primitive types. The implementation is based on the - * finalization step from Austin Appleby's MurmurHash3. - * - * @see "http://sites.google.com/site/murmurhash/" - */ -final class MurmurHash3 { - private MurmurHash3() { - // no instances. - } - - /** - * Hashes a 4-byte sequence (Java int). - */ - public static int hash(int k) { - k ^= k >>> 16; - k *= 0x85ebca6b; - k ^= k >>> 13; - k *= 0xc2b2ae35; - k ^= k >>> 16; - return k; - } - - /** - * Hashes an 8-byte sequence (Java long). - */ - public static long hash(long k) { - k ^= k >>> 33; - k *= 0xff51afd7ed558ccdL; - k ^= k >>> 33; - k *= 0xc4ceb9fe1a85ec53L; - k ^= k >>> 33; - - return k; - } -} - -/** - * Some useful constants. - **/ -final class Constants { - private Constants() {} // can't construct - - /** True iff running on a 64bit JVM */ - public static final boolean JRE_IS_64BIT; - - /** The value of System.getProperty("java.version"). **/ - public static final String JAVA_VERSION = System.getProperty("java.version"); - public static final String JAVA_VENDOR = System.getProperty("java.vendor"); - public static final String JVM_VENDOR = System.getProperty("java.vm.vendor"); - public static final String JVM_VERSION = System.getProperty("java.vm.version"); - public static final String JVM_NAME = System.getProperty("java.vm.name"); - public static final String OS_ARCH = System.getProperty("os.arch"); - public static final String OS_VERSION = System.getProperty("os.version"); - - static { - final String OS_ARCH = System.getProperty("os.arch"); - boolean is64Bit = false; - try { - final Class unsafeClass = Class.forName("sun.misc.Unsafe"); - final Field unsafeField = unsafeClass.getDeclaredField("theUnsafe"); - unsafeField.setAccessible(true); - final Object unsafe = unsafeField.get(null); - final int addressSize = ((Number) unsafeClass.getMethod("addressSize").invoke(unsafe)).intValue(); - is64Bit = addressSize >= 8; - } catch (Exception e) { - final String x = System.getProperty("sun.arch.data.model"); - if (x != null) { - is64Bit = x.indexOf("64") != -1; - } else { - if (OS_ARCH != null && OS_ARCH.indexOf("64") != -1) { - is64Bit = true; - } else { - is64Bit = false; - } - } - } - JRE_IS_64BIT = is64Bit; - } -} diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/rules/RequireAssertionsRule.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/rules/RequireAssertionsRule.java deleted file mode 100644 index 706bc103..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/rules/RequireAssertionsRule.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.carrotsearch.randomizedtesting.rules; - -import java.util.Objects; - -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR 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.ClassRule; -import org.junit.rules.TestRule; - -import com.carrotsearch.randomizedtesting.RandomizedTest; -import com.carrotsearch.randomizedtesting.SysGlobals; -import com.carrotsearch.randomizedtesting.annotations.SuppressForbidden; - -/** - * Require assertions {@link TestRule}. - * - * @see ClassRule - */ -public class RequireAssertionsRule extends TestRuleAdapter { - public static final boolean TEST_ASSERTS_ENABLED = - RandomizedTest.systemPropertyAsBoolean(SysGlobals.SYSPROP_ASSERTS(), /* default to assertions required */ true); - - private final Class targetClass; - - public RequireAssertionsRule(Class targetClass) { - this.targetClass = Objects.requireNonNull(targetClass); - } - - @SuppressForbidden("Permitted sysout.") - @Override - protected void before() throws Throwable { - // Make sure -ea matches -Dtests.asserts. - boolean assertsEnabled = targetClass.desiredAssertionStatus(); - if (assertsEnabled != TEST_ASSERTS_ENABLED) { - String msg = "Assertion state mismatch on " + targetClass.getSimpleName() + ": "; - if (assertsEnabled) { - msg += "-ea was specified"; - } else { - msg += "-ea was not specified"; - } - msg += " but -Dtests.asserts=" + TEST_ASSERTS_ENABLED; - - System.err.println(msg); - throw new Exception(msg); - } - } -} \ No newline at end of file diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/rules/StatementAdapter.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/rules/StatementAdapter.java deleted file mode 100644 index 47c57b72..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/rules/StatementAdapter.java +++ /dev/null @@ -1,72 +0,0 @@ -package com.carrotsearch.randomizedtesting.rules; - -import java.util.ArrayList; -import java.util.List; - -import org.junit.After; -import org.junit.AfterClass; -import org.junit.rules.RuleChain; -import org.junit.runners.model.MultipleFailureException; -import org.junit.runners.model.Statement; - -/** - * An abstract {@link Statement} that guarantees the execution of - * {@link #afterAlways} even if an exception has been thrown from delegate - * {@link Statement}. This is much like {@link AfterClass} or {@link After} - * annotations but can be used with {@link RuleChain} to guarantee the order of - * execution. - */ -public abstract class StatementAdapter extends Statement { - - private final Statement delegate; - - protected StatementAdapter(Statement delegate) { - this.delegate = delegate; - } - - /** - * - */ - @Override - final public void evaluate() throws Throwable { - final ArrayList errors = new ArrayList(); - - try { - before(); - delegate.evaluate(); - afterIfSuccessful(); - } catch (Throwable t) { - errors.add(t); - } - - try { - afterAlways(errors); - } catch (Throwable t) { - errors.add(t); - } - - MultipleFailureException.assertEmpty(errors); - } - - /** - * Always called before the delegate {@link Statement}. - */ - protected void before() throws Throwable {} - - /** - * Always called after the delegate {@link Statement}, even if an exception - * (or assumption failure) occurs. Any exceptions thrown from the body of this - * method will be chained using {@link MultipleFailureException}. - * - * @param errors - * A list of errors received so far. The list is modifiable although - * should only be extended with new potential exceptions. - */ - protected void afterAlways(List errors) throws Throwable {} - - /** - * Called only if the delegate {@link Statement} returned successfully. - */ - protected void afterIfSuccessful() throws Throwable {} - -} diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/rules/StaticFieldsInvariantRule.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/rules/StaticFieldsInvariantRule.java deleted file mode 100644 index f6b01211..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/rules/StaticFieldsInvariantRule.java +++ /dev/null @@ -1,183 +0,0 @@ -package com.carrotsearch.randomizedtesting.rules; - -import java.lang.reflect.Field; -import java.lang.reflect.Modifier; -import java.security.AccessController; -import java.security.PrivilegedAction; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Locale; - -import junit.framework.AssertionFailedError; - -import org.junit.ClassRule; -import org.junit.rules.TestRule; -import org.junit.runner.Description; -import org.junit.runners.model.Statement; - -import com.carrotsearch.randomizedtesting.RandomizedContext; - -/** - * A {@link TestRule} that ensures static, reference fields of the suite class - * (and optionally its superclasses) are cleaned up after a suite is completed. - * This is helpful in finding out static memory leaks (a class references - * something huge but is no longer used). - * - * @see ClassRule - * @see #accept(Field) - */ -public class StaticFieldsInvariantRule implements TestRule { - public static final long DEFAULT_LEAK_THRESHOLD = 10 * 1024 * 1024; - - private final long leakThreshold; - private final boolean countSuperclasses; - - /** - * By default use {@link #DEFAULT_LEAK_THRESHOLD} as the threshold and count - * in superclasses. - */ - public StaticFieldsInvariantRule() { - this(DEFAULT_LEAK_THRESHOLD, true); - } - - public StaticFieldsInvariantRule(long leakThresholdBytes, boolean countSuperclasses) { - this.leakThreshold = leakThresholdBytes; - this.countSuperclasses = countSuperclasses; - } - - static class Entry implements Comparable { - final Field field; - final Object value; - long ramUsed; - - public Entry(Field field, Object value) { - this.field = field; - this.value = value; - } - - @Override - public int compareTo(Entry o) { - if (this.ramUsed > o.ramUsed) return -1; - if (this.ramUsed < o.ramUsed) return 1; - return this.field.toString().compareTo(o.field.toString()); - } - } - - @Override - public Statement apply(final Statement s, final Description d) { - return new StatementAdapter(s) { - @Override - protected void afterAlways(List errors) throws Throwable { - // Try to get the target class from the context, if available. - Class testClass = null; - try { - testClass = RandomizedContext.current().getTargetClass(); - } catch (Throwable t) { - // Ignore. - } - - if (testClass == null) { - // This is JUnit's ugly way that attempts Class.forName and may use a different - // classloader... let's use it as a last resort option. - testClass = d.getTestClass(); - } - - // No test class? Weird. - if (testClass == null) { - throw new RuntimeException("Test class could not be acquired from the randomized " + - "context or the Description object."); - } - - // Collect all fields first to count references to the same object once. - ArrayList fieldsAndValues = new ArrayList(); - ArrayList values = new ArrayList(); - for (Class c = testClass; countSuperclasses && c.getSuperclass() != null; c = c.getSuperclass()) { - final Class target = c; - Field[] allFields = AccessController.doPrivileged(new PrivilegedAction() { - @Override - public Field[] run() { - return target.getDeclaredFields(); - } - }); - for (final Field field : allFields) { - if (Modifier.isStatic(field.getModifiers()) && - !field.getType().isPrimitive() && - accept(field)) { - try { - AccessController.doPrivileged(new PrivilegedAction() { - @Override - public Void run() { - field.setAccessible(true); - return null; - } - }); - Object v = field.get(null); - if (v != null) { - fieldsAndValues.add(new Entry(field, v)); - values.add(v); - } - } catch (SecurityException e) { - errors.add(new RuntimeException("Could not access field '" + field.getName() + "'.", e)); - } - } - } - } - - final long ramUsage; - try { - ramUsage = RamUsageEstimator.sizeOfAll(values); - } catch (Exception ex) { - // some problem occurred while trying to measure (e.g. Java 9, SecurityManager). - // we iterate over all fields to get the "bad one": - final StringBuilder b = new StringBuilder(); - b.append("Clean up static fields (in @AfterClass?) and null them, ") - .append("your test still has references to classes of which the ") - .append("sizes cannot be measured due to security restrictions or Java 9 ") - .append("module encapsulation:"); - for (final Entry e : fieldsAndValues) { - try { - RamUsageEstimator.sizeOf(e.value); - } catch (Exception ex1) { - b.append("\n - ").append(e.field); - } - } - - AssertionFailedError err = new AssertionFailedError(b.toString()); - err.initCause(ex); - errors.add(err); - return; - } - - if (ramUsage > leakThreshold) { - // Count per-field information to get the heaviest fields. - for (Entry e : fieldsAndValues) { - e.ramUsed = RamUsageEstimator.sizeOf(e.value); - } - Collections.sort(fieldsAndValues); - - StringBuilder b = new StringBuilder(); - b.append(String.format(Locale.ROOT, "Clean up static fields (in @AfterClass?), " - + "your test seems to hang on to approximately %,d bytes (threshold is %,d). " + - "Field reference sizes (counted individually):", - ramUsage, leakThreshold)); - - for (Entry e : fieldsAndValues) { - b.append(String.format(Locale.ROOT, "\n - %,d bytes, %s", e.ramUsed, - e.field.toString())); - } - - errors.add(new AssertionFailedError(b.toString())); - } - } - }; - } - - /** - * @return Return false to exclude a given field from being - * counted. By default final fields are rejected. - */ - protected boolean accept(Field field) { - return !Modifier.isFinal(field.getModifiers()); - } -} diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/rules/SystemPropertiesInvariantRule.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/rules/SystemPropertiesInvariantRule.java deleted file mode 100644 index 24eba6fa..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/rules/SystemPropertiesInvariantRule.java +++ /dev/null @@ -1,136 +0,0 @@ -package com.carrotsearch.randomizedtesting.rules; - -import java.util.*; - -import org.junit.ClassRule; -import org.junit.Rule; -import org.junit.rules.TestRule; -import org.junit.runner.Description; -import org.junit.runners.model.MultipleFailureException; -import org.junit.runners.model.Statement; - -/** - * A {@link TestRule} that ensures system properties remain unmodified by the nested - * {@link Statement}. This can be applied both at suite level and at test level. - * - * This rule requires appropriate security permission to read and write - * system properties ({@link System#getProperties()}) if running under a security - * manager. - * - * @see SystemPropertiesRestoreRule - * @see ClassRule - * @see Rule - */ -public class SystemPropertiesInvariantRule implements TestRule { - /** - * Ignored property keys. - */ - private final HashSet ignoredProperties; - - /** - * Cares about all properties. - */ - public SystemPropertiesInvariantRule() { - this(Collections.emptySet()); - } - - /** - * Don't care about the given set of properties. - */ - public SystemPropertiesInvariantRule(String... ignoredProperties) { - this.ignoredProperties = new HashSet(Arrays.asList(ignoredProperties)); - } - - /** - * Don't care about the given set of properties. - */ - public SystemPropertiesInvariantRule(Set ignoredProperties) { - this.ignoredProperties = new HashSet(ignoredProperties); - } - - @Override - public Statement apply(final Statement s, Description d) { - return new Statement() { - @Override - public void evaluate() throws Throwable { - TreeMap before = SystemPropertiesRestoreRule.systemPropertiesAsMap(); - ArrayList errors = new ArrayList(); - try { - s.evaluate(); - } catch (Throwable t) { - errors.add(t); - } finally { - final TreeMap after = SystemPropertiesRestoreRule.systemPropertiesAsMap(); - - // Remove ignored if they exist. - before.keySet().removeAll(ignoredProperties); - after.keySet().removeAll(ignoredProperties); - - if (!after.equals(before)) { - errors.add( - new AssertionError("System properties invariant violated.\n" + - collectErrorMessage(before, after))); - } - - // Restore original properties. - SystemPropertiesRestoreRule.restore(before, after, ignoredProperties); - } - - MultipleFailureException.assertEmpty(errors); - } - - private StringBuilder collectErrorMessage( - TreeMap before, TreeMap after) { - TreeSet newKeys = new TreeSet(after.keySet()); - newKeys.removeAll(before.keySet()); - - TreeSet missingKeys = new TreeSet(before.keySet()); - missingKeys.removeAll(after.keySet()); - - TreeSet differentKeyValues = new TreeSet(before.keySet()); - differentKeyValues.retainAll(after.keySet()); - for (Iterator i = differentKeyValues.iterator(); i.hasNext();) { - String key = i.next(); - String valueBefore = before.get(key); - String valueAfter = after.get(key); - if ((valueBefore == null && valueAfter == null) || - (valueBefore.equals(valueAfter))) { - i.remove(); - } - } - - final StringBuilder b = new StringBuilder(); - if (!missingKeys.isEmpty()) { - b.append("Missing keys:\n"); - for (String key : missingKeys) { - b.append(" ").append(key) - .append("=") - .append(before.get(key)) - .append("\n"); - } - } - if (!newKeys.isEmpty()) { - b.append("New keys:\n"); - for (String key : newKeys) { - b.append(" ").append(key) - .append("=") - .append(after.get(key)) - .append("\n"); - } - } - if (!differentKeyValues.isEmpty()) { - b.append("Different values:\n"); - for (String key : differentKeyValues) { - b.append(" [old]").append(key) - .append("=") - .append(before.get(key)).append("\n"); - b.append(" [new]").append(key) - .append("=") - .append(after.get(key)).append("\n"); - } - } - return b; - } - }; - } -} \ No newline at end of file diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/rules/SystemPropertiesRestoreRule.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/rules/SystemPropertiesRestoreRule.java deleted file mode 100644 index 8a1cbb4a..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/rules/SystemPropertiesRestoreRule.java +++ /dev/null @@ -1,128 +0,0 @@ -package com.carrotsearch.randomizedtesting.rules; - -import java.util.*; - -import org.junit.ClassRule; -import org.junit.Rule; -import org.junit.rules.TestRule; -import org.junit.runner.Description; -import org.junit.runners.model.Statement; - -/** - * A {@link TestRule} which restores system properties from before the nested - * {@link Statement}. - * - * This rule requires appropriate security permission to read and write - * system properties ({@link System#getProperties()}) if running under a security - * manager. - * - * @see SystemPropertiesInvariantRule - * @see ClassRule - * @see Rule - */ -public class SystemPropertiesRestoreRule implements TestRule { - /** - * Ignored property keys. - */ - private final HashSet ignoredProperties; - - /** - * Restores all properties. - */ - public SystemPropertiesRestoreRule() { - this(Collections.emptySet()); - } - - /** - * @param ignoredProperties Properties that will be ignored (and will not be restored). - */ - public SystemPropertiesRestoreRule(Set ignoredProperties) { - this.ignoredProperties = new HashSet(ignoredProperties); - } - - /** - * @param ignoredProperties Properties that will be ignored (and will not be restored). - */ - public SystemPropertiesRestoreRule(String... ignoredProperties) { - this.ignoredProperties = new HashSet(Arrays.asList(ignoredProperties)); - } - - @Override - public Statement apply(final Statement s, Description d) { - return new Statement() { - @Override - public void evaluate() throws Throwable { - TreeMap before = systemPropertiesAsMap(); - try { - s.evaluate(); - } finally { - TreeMap after = systemPropertiesAsMap(); - if (!after.equals(before)) { - // Restore original properties. - restore(before, after, ignoredProperties); - } - } - } - }; - } - - private static TreeMap cloneAsMap(Properties properties) { - TreeMap result = new TreeMap(); - for (Enumeration e = properties.propertyNames(); e.hasMoreElements();) { - final Object key = e.nextElement(); - // Skip non-string properties or values, they're abuse of Properties object. - if (key instanceof String) { - String value = properties.getProperty((String) key); - if (value == null) { - Object ovalue = properties.get(key); - if (ovalue != null) { - // ovalue has to be a non-string object. Skip the property because - // System.clearProperty won't be able to cast back the existing value. - continue; - } - } - result.put((String) key, value); - } - } - return result; - } - - static void restore( - TreeMap before, - TreeMap after, - Set ignoredKeys) { - - // Clear anything that is present after but wasn't before. - after.keySet().removeAll(before.keySet()); - for (String key : after.keySet()) { - if (!ignoredKeys.contains(key)) - System.clearProperty(key); - } - - // Restore original property values unless they are ignored (then leave). - for (Map.Entry e : before.entrySet()) { - String key = e.getValue(); - if (!ignoredKeys.contains(key)) { - if (key == null) { - System.clearProperty(e.getKey()); // Can this happen? - } else { - System.setProperty(e.getKey(), key); - } - } - } - } - - static TreeMap systemPropertiesAsMap() { - try { - return cloneAsMap(System.getProperties()); - } catch (SecurityException e) { - AssertionError ae = new AssertionError("Access to System.getProperties() denied."); - try { - ae.initCause(e); - } catch (Exception ignored) { - // If we can't initCause, ignore it. - } - throw ae; - } - } -} \ No newline at end of file diff --git a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/rules/TestRuleAdapter.java b/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/rules/TestRuleAdapter.java deleted file mode 100644 index d695ae62..00000000 --- a/randomized-runner/src/main/java/com/carrotsearch/randomizedtesting/rules/TestRuleAdapter.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.carrotsearch.randomizedtesting.rules; - -import java.util.List; - -import org.junit.After; -import org.junit.AfterClass; -import org.junit.rules.RuleChain; -import org.junit.rules.TestRule; -import org.junit.runner.Description; -import org.junit.runners.model.MultipleFailureException; -import org.junit.runners.model.Statement; - -/** - * An abstract {@link TestRule} that guarantees the execution of - * {@link #afterAlways} even if an exception has been thrown from delegate - * {@link Statement}. This is much like {@link AfterClass} or {@link After} - * annotations but can be used with {@link RuleChain} to guarantee the order of - * execution. - */ -public abstract class TestRuleAdapter implements TestRule { - @Override - public Statement apply(final Statement s, final Description d) { - return new StatementAdapter(s) { - @Override - protected void before() throws Throwable { - TestRuleAdapter.this.before(); - } - - @Override - protected void afterAlways(List errors) throws Throwable { - TestRuleAdapter.this.afterAlways(errors); - } - - @Override - protected void afterIfSuccessful() throws Throwable { - TestRuleAdapter.this.afterIfSuccessful(); - } - }; - } - - /** - * Always called before the delegate {@link Statement}. - */ - protected void before() throws Throwable {} - - /** - * Always called after the delegate {@link Statement}, even if an exception - * (or assumption failure) occurs. Any exceptions thrown from the body of this - * method will be chained using {@link MultipleFailureException}. - * - * @param errors - * A list of errors received so far. The list is modifiable although - * should only be extended with new potential exceptions. - */ - protected void afterAlways(List errors) throws Throwable {} - - /** - * Called only if the delegate {@link Statement} returned successfully. - */ - protected void afterIfSuccessful() throws Throwable {} -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/PrintEventListener.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/PrintEventListener.java deleted file mode 100644 index cd34856a..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/PrintEventListener.java +++ /dev/null @@ -1,66 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import java.io.PrintStream; -import java.util.Locale; -import java.util.concurrent.atomic.AtomicInteger; - -import org.junit.runner.Description; -import org.junit.runner.Result; -import org.junit.runner.notification.Failure; -import org.junit.runner.notification.RunListener; - -public class PrintEventListener extends RunListener { - private final PrintStream out; - private AtomicInteger assumptions = new AtomicInteger(); - - public PrintEventListener(PrintStream out) { - this.out = out; - } - - @Override - public void testRunStarted(Description description) throws Exception { - out.println("Run started."); - } - - @Override - public void testRunFinished(Result result) throws Exception { - out.println(String.format(Locale.ROOT, - "Run finished: run=%s, ignored=%s, failures=%s, assumptions=%s\n", - result.getRunCount(), - result.getIgnoreCount(), - result.getFailureCount(), - assumptions.get())); - } - - @Override - public void testStarted(Description description) throws Exception { - out.println("Started : " + description.getMethodName()); - } - - @Override - public void testFinished(Description description) throws Exception { - out.println("Finished: " + description.getMethodName()); - } - - @Override - public void testFailure(Failure failure) throws Exception { - out.println("Failure : " + failure); - } - - @Override - public void testAssumptionFailure(Failure failure) { - out.println("Assumpt.: " + failure); - assumptions.incrementAndGet(); - } - - @Override - public void testIgnored(Description description) throws Exception { - String methodName = description.getMethodName(); - if (methodName == null) { - // Ignored due to class-level @Ignore or some other reason. - out.println("Ignored : " + description.getDisplayName()); - } else { - out.println("Ignored : " + description.getMethodName()); - } - } -} \ No newline at end of file diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestBiasedNumbers.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestBiasedNumbers.java deleted file mode 100644 index c0ad7228..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestBiasedNumbers.java +++ /dev/null @@ -1,80 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import java.util.Locale; -import java.util.Random; - -import org.assertj.core.api.Assertions; -import org.junit.Test; - -import com.carrotsearch.randomizedtesting.annotations.Repeat; -import com.carrotsearch.randomizedtesting.generators.BiasedNumbers; - -public class TestBiasedNumbers extends RandomizedTest { - @Test - @Repeat(iterations = 100) - public void biasedFloats() { - Random r = getRandom(); - - // Some sanity checks. - sanityCheck(r, Float.NEGATIVE_INFINITY, Float.NEGATIVE_INFINITY); - sanityCheck(r, Float.NEGATIVE_INFINITY, 0); - sanityCheck(r, Float.NEGATIVE_INFINITY, Float.POSITIVE_INFINITY); - sanityCheck(r, 0, Float.POSITIVE_INFINITY); - sanityCheck(r, 0f, 0); - sanityCheck(r, 0f, 1); - sanityCheck(r, -1f, 1); - sanityCheck(r, 1f, 2); - } - - private void sanityCheck(Random r, float from, float to) { - for (int i = 0; i < 100; i++) { - float v = BiasedNumbers.randomFloatBetween(r, from, to); - Assertions.assertThat(v).isNotNaN(); - Assertions.assertThat(v >= from && v <= to).isTrue(); - } - } - - @Test - @Repeat(iterations = 100) - public void biasedDoubles() { - Random r = getRandom(); - - // Some sanity checks. - sanityCheck(r, Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY); - sanityCheck(r, Double.NEGATIVE_INFINITY, 0); - sanityCheck(r, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY); - sanityCheck(r, 0, Double.POSITIVE_INFINITY); - sanityCheck(r, 0d, 0); - sanityCheck(r, 0d, 1); - sanityCheck(r, -1d, 1); - sanityCheck(r, 1d, 2); - } - - private void sanityCheck(Random r, double from, double to) { - for (int i = 0; i < 100; i++) { - double v = BiasedNumbers.randomDoubleBetween(r, from, to); - Assertions.assertThat(v).isNotNaN(); - Assertions.assertThat(v >= from && v <= to).isTrue(); - } - } - - @Test - public void histo() { - Random rnd = getRandom(); - int r = 10; - int [][] counts = new int [r + 1][r + 1]; - for (int i = 0; i < 100000; i++) { - float x = r / 2 + BiasedNumbers.randomFloatBetween(rnd, -r/2, r/2); - float y = r / 2 + BiasedNumbers.randomFloatBetween(rnd, -r/2, r/2); - - counts[Math.round(x)][Math.round(y)]++; - } - - for (int x = 0; x < counts.length; x++) { - for (int y = 0; y < counts.length; y++) { - System.out.printf(Locale.ROOT, "%10d ", counts[x][y]); - } - System.out.println(); - } - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestChildTestGroupThreads.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestChildTestGroupThreads.java deleted file mode 100644 index 9f12755e..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestChildTestGroupThreads.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import java.util.Random; - -import org.junit.Test; - -/** - * Make sure we can access contexts from a sub-thread group. - */ -public class TestChildTestGroupThreads extends RandomizedTest { - volatile int guard; - - @Test - public void testSubgroup() throws Exception { - ThreadGroup tgroup = new ThreadGroup("child group"); - final Thread t = new Thread(tgroup, "child thread") { - public void run() { - Random rnd = RandomizedContext.current().getRandom(); - guard += rnd.nextInt(); - } - }; - - t.start(); - t.join(); - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestClassMethodFiltering.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestClassMethodFiltering.java deleted file mode 100644 index ebd57eca..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestClassMethodFiltering.java +++ /dev/null @@ -1,122 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import static org.junit.Assert.*; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.junit.After; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import static com.carrotsearch.randomizedtesting.SysGlobals.*; - -/** - * Check if global filtering works. - */ -public class TestClassMethodFiltering extends WithNestedTestClass { - static List methods = new ArrayList(); - - @RunWith(RandomizedRunner.class) - public static class Nested1 { - @BeforeClass - public static void beforeClass() { - methods.add("beforeClass1"); - } - - @Test - public void method1() { - assumeRunningNested(); - methods.add("method1"); - } - - @Test - public void method2() { - assumeRunningNested(); - methods.add("method2"); - } - } - - @RunWith(RandomizedRunner.class) - public static class Nested2 { - @BeforeClass - public static void beforeClass() { - methods.add("beforeClass2"); - } - - @Test - public void method1() { - assumeRunningNested(); - methods.add("method1"); - } - } - - /** - * Class filter (all methods). - */ - @Test - public void testClassFilter() { - System.setProperty(SYSPROP_TESTCLASS(), Nested1.class.getName()); - runTests(Nested1.class, Nested2.class); - assertTrue( - Arrays.asList("beforeClass1", "method1", "method2").equals(methods) || - Arrays.asList("beforeClass1", "method2", "method1").equals(methods)); - } - - /** - * Class and method filter (single method). - */ - @Test - public void testClassMethodFilter() { - System.setProperty(SYSPROP_TESTCLASS(), Nested1.class.getName()); - System.setProperty(SYSPROP_TESTMETHOD(), "method2"); - runTests(Nested1.class, Nested2.class); - assertEquals(Arrays.asList("beforeClass1", "method2"), methods); - } - - /** - * Awkward case: only method filter. - */ - @Test - public void testMethodFilter() { - System.setProperty(SYSPROP_TESTMETHOD(), "method1"); - runTests(Nested1.class, Nested2.class); - assertEquals(Arrays.asList("beforeClass1", "method1", "beforeClass2", "method1"), methods); - } - - /** - * Glob class name filter· - */ - @Test - public void testGlobClassName() { - System.setProperty(SYSPROP_TESTCLASS(), "*Nested1"); - runTests(Nested1.class, Nested2.class); - assertTrue( - Arrays.asList("beforeClass1", "method1", "method2").equals(methods) || - Arrays.asList("beforeClass1", "method2", "method1").equals(methods)); - } - - /** - * Glob method name filter· - */ - @Test - public void testGlobMethodName() { - System.setProperty(SYSPROP_TESTMETHOD(), "*hod1"); - runTests(Nested1.class, Nested2.class); - assertEquals(Arrays.asList("beforeClass1", "method1", "beforeClass2", "method1"), methods); - } - - @Before - public void cleanupBefore() { - cleanupAfter(); - } - - @After - public void cleanupAfter() { - System.clearProperty(SYSPROP_TESTCLASS()); - System.clearProperty(SYSPROP_TESTMETHOD()); - methods.clear(); - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestContextRandom.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestContextRandom.java deleted file mode 100644 index a96bcb40..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestContextRandom.java +++ /dev/null @@ -1,87 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import java.util.ArrayList; -import java.util.List; - -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; -import com.carrotsearch.randomizedtesting.annotations.Seed; - -/** - * Check if the context's random is indeed repeatable. - */ -public class TestContextRandom extends WithNestedTestClass { - static ArrayList numbers = new ArrayList(); - - public static class Nested1 extends RandomizedTest { - @Seed("deadbeef") // Fix the seed to get a repeatable result - @Test - public void testMethod() { - numbers.clear(); - for (int i = 0; i < 10; i++) { - numbers.add(randomInt()); - } - } - } - - public static class Nested2 extends RandomizedTest { - @Test - public void testMethod() { - numbers.clear(); - for (int i = 0; i < 10; i++) { - numbers.add(randomInt()); - } - } - } - - public static class Nested3 extends RandomizedTest { - @Seed("deadbeef") // Fix the seed to get a repeatable result even if subthreads use randomness. - @Test - public void testMethod() throws Exception { - Thread t = new Thread() { - @Override - public void run() { - numbers.clear(); - for (int i = 0; i < 10; i++) { - numbers.add(randomInt()); - } - } - }; - t.start(); - t.join(); - } - } - - /** - * Check that subthreads get the same randomness for {@link Seed} - * annotation on a method. - */ - @Test - @Ignore("Forked threads get the master seed (by-design).") - public void testFixedSeedSubthreads() { - runTests(Nested3.class); - List run1 = new ArrayList(numbers); - runTests(Nested3.class); - List run2 = new ArrayList(numbers); - Assert.assertEquals(run1, run2); - } - - @Test - public void testFixedSeed() { - runTests(Nested1.class); - List run1 = new ArrayList(numbers); - runTests(Nested1.class); - List run2 = new ArrayList(numbers); - Assert.assertEquals(run1, run2); - } - - @Test - public void testRandomSeed() { - runTests(Nested2.class); - List run1 = new ArrayList(numbers); - runTests(Nested2.class); - List run2 = new ArrayList(numbers); - Assert.assertFalse(run1.equals(run2)); - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestCustomMethodProvider.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestCustomMethodProvider.java deleted file mode 100644 index d79fe125..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestCustomMethodProvider.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Inherited; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.JUnitCore; -import org.junit.runner.Result; -import org.junit.runners.model.InitializationError; - -import com.carrotsearch.randomizedtesting.annotations.TestMethodProviders; - -public class TestCustomMethodProvider extends WithNestedTestClass { - @Retention(RetentionPolicy.RUNTIME) - @Target({ElementType.METHOD}) - @Inherited - public static @interface MyTest { - } - - public static class MyTestMethodProvider extends AnnotatedMethodProvider { - public MyTestMethodProvider() { - super(MyTest.class); - } - } - - @TestMethodProviders({MyTestMethodProvider.class}) - public static class Base {} - - public static class T4 extends Base { @MyTest private void test1() {} } - public static class T2 extends Base { @MyTest void test1() {} } - public static class T3 extends Base { @MyTest protected void test1() {} } - public static class T1 extends Base { @MyTest public void test1() {} } - - public static class ST4 extends Base { @MyTest static private void test1() {} } - public static class ST2 extends Base { @MyTest static void test1() {} } - public static class ST3 extends Base { @MyTest static protected void test1() {} } - public static class ST1 extends Base { @MyTest static public void test1() {} } - - public static class AT1 extends Base { @MyTest public void test1(int arg) {} } - public static class RT1 extends Base { @MyTest public int test1() { return 0; } } - - @Test - public void testJUnit4Valid() throws InitializationError { - Class [] valid = { - T1.class, RT1.class - }; - - for (Class cl : valid) { - Result r = new JUnitCore().run(new RandomizedRunner(cl)); - Assert.assertEquals(0, r.getFailureCount()); - Assert.assertEquals(1, r.getRunCount()); - } - } - - @Test - public void testJUnit4Invalid() { - Class [] invalid = { - T2.class, T3.class, T4.class, - ST1.class, ST2.class, ST3.class, ST4.class, - AT1.class - }; - - for (Class cl : invalid) { - try { - new JUnitCore().run(new RandomizedRunner(cl)); - Assert.fail("Expected to fail for: " + cl); - } catch (InitializationError e) { - // expected. - } - } - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestCustomTestContextSupplier.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestCustomTestContextSupplier.java deleted file mode 100644 index c7fb0c28..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestCustomTestContextSupplier.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import static org.junit.Assert.*; - -import java.util.Random; - -import org.junit.Test; - -import com.carrotsearch.randomizedtesting.annotations.TestContextRandomSupplier; - -/** - * - */ -@TestContextRandomSupplier(TestCustomTestContextSupplier.CustomSupplier.class) -public class TestCustomTestContextSupplier extends RandomizedTest { - public static class CustomSupplier implements RandomSupplier { - @SuppressWarnings("serial") - @Override - public Random get(long seed) { - return new Random() { - int value; - - @Override - public int nextInt() { - return value++; - } - }; - } - } - - @Test - public void testCustomSupplier() throws Exception { - // Can't just check for instanceof because random can be wrapped - // with AssertingRandom. - Random rnd = RandomizedContext.current().getRandom(); - for (int i = 0; i < 10; i++) { - assertEquals(rnd.nextInt(), i); - } - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestExpected.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestExpected.java deleted file mode 100644 index bbdedcf6..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestExpected.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import org.assertj.core.api.Assertions; -import org.junit.Test; - -/** - * Test {@link Test#expected()}. - */ -public class TestExpected extends WithNestedTestClass { - public static class Nested1 extends RandomizedTest { - @Test(expected = RuntimeException.class) - public void testMethod1() { - throw new RuntimeException(); - } - - // We expect a RuntimeException but get an error: should fail. - @Test(expected = RuntimeException.class) - public void testMethod2() { - assumeRunningNested(); - throw new Error(); - } - } - - public static class Nested2 extends RandomizedTest { - @Test(expected = RuntimeException.class) - public void testMethod1() { - assumeRunningNested(); - // Don't do anything. - } - } - - @Test - public void testExpectedFailureDifferentException() { - FullResult f = checkTestsOutput(2, 0, 1, 0, Nested1.class); - Assertions.assertThat(f.getFailures().get(0).getException()) - .isInstanceOf(Error.class); - } - - @Test - public void testExpectedFailurePassed() { - checkTestsOutput(1, 0, 1, 0, Nested2.class); - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestFailurePropagationCompatibility.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestFailurePropagationCompatibility.java deleted file mode 100644 index 00995f10..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestFailurePropagationCompatibility.java +++ /dev/null @@ -1,148 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import java.util.ArrayList; -import java.util.Random; - -import org.junit.*; -import org.junit.rules.RuleChain; -import org.junit.rules.TestRule; -import org.junit.runner.*; -import org.junit.runner.notification.Failure; -import org.junit.runners.model.MultipleFailureException; -import org.junit.runners.model.Statement; - - -/** - * Check failure propagation compatibility against JUnit. - */ -public class TestFailurePropagationCompatibility extends WithNestedTestClass { - static Random random; - static int frequency; - - public static class MaybeFailRule implements TestRule { - @Override - public Statement apply(final Statement base, Description description) { - return new Statement() { - @Override - public void evaluate() throws Throwable { - try { - maybeFail(); - base.evaluate(); - maybeFail(); - } catch (Throwable t) { - maybeFail(); - } finally { - maybeFail(); - } - } - }; - } - } - - public static class FailRandomly1 { - public FailRandomly1() { - maybeFail(); - } - - @ClassRule - public static TestRule classRule1 = RuleChain - .outerRule(new MaybeFailRule()) - .around(new MaybeFailRule()); - - @Rule - public TestRule testRule1 = RuleChain - .outerRule(new MaybeFailRule()) - .around(new MaybeFailRule()); - - @BeforeClass public static void beforeClass1() { maybeFail(); } - @Before public void before() { maybeFail(); } - @Test public void test() { maybeFail(); } - @After public void after() { maybeFail(); } - @AfterClass public static void afterClass() { maybeFail(); } - } - - public static class FailRandomly2 extends FailRandomly1 { - public FailRandomly2() { - maybeFail(); - } - - @ClassRule - public static TestRule classRule2 = RuleChain - .outerRule(new MaybeFailRule()) - .around(new MaybeFailRule()); - - @Rule - public TestRule testRule2 = RuleChain - .outerRule(new MaybeFailRule()) - .around(new MaybeFailRule()); - - @BeforeClass public static void beforeClass2() { maybeFail(); } - @Before public void before2() { maybeFail(); } - @After public void after2() { maybeFail(); } - @AfterClass public static void afterClass2() { maybeFail(); } - } - - @RunWith(RandomizedRunner.class) - public static class FailRandomly3 extends FailRandomly2 { - } - - static void maybeFail() { - if (random != null) { - if (random.nextInt(frequency) == 0) { - if (random.nextBoolean()) { - throw new RuntimeException("State: " + random.nextLong()); - } else { - ArrayList errors = new ArrayList(); - errors.add(new RuntimeException("State: " + random.nextLong())); - errors.add(new RuntimeException("State: " + random.nextLong())); - // Throw MultipleFailureException as if unchecked. - Rethrow.rethrow(new MultipleFailureException(errors)); - } - } - } - } - - @Test - public void testRunEquals() throws Exception { - Random rnd = new Random(); // initial. - for (int f = 1; f < 10; f += 2) { - frequency = f; - for (int i = 0; i < 25; i++) { - final long seed = rnd.nextLong() + i; - random = new Random(seed); - Result junit4 = new JUnitCore().run(FailRandomly2.class); - random = new Random(seed); - Result rr = new JUnitCore().run(FailRandomly3.class); - - String traceJunit4 = executionTrace(junit4); - String traceRR = executionTrace(rr); - if (!traceJunit4.equals(traceRR)) { - System.out.println("=== Random(" + seed + "), freq: " + frequency); - System.out.println("--- JUnit4:"); - System.out.println(traceJunit4); - System.out.println("--- RandomizedRunner:"); - System.out.println(traceRR); - Assert.fail(); - } - } - } - } - - @AfterClass - public static void cleanup() { - random = null; - } - - private String executionTrace(Result r) { - StringBuilder sb = new StringBuilder(); - sb.append("Run count: " + r.getRunCount() + "\n"); - sb.append("Ignore count: " + r.getIgnoreCount() + "\n"); - sb.append("Failure count: " + r.getFailureCount() + "\n"); - for (Failure f : r.getFailures()) { - Throwable t = f.getException(); - sb.append(t.getClass().getName() + ": " + t.getMessage()); - sb.append("\n\n"); - } - return sb.toString(); - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestFilterExpressionParser.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestFilterExpressionParser.java deleted file mode 100644 index eaf642a2..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestFilterExpressionParser.java +++ /dev/null @@ -1,157 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import java.util.ArrayDeque; -import java.util.Arrays; -import java.util.Deque; -import java.util.List; - -import org.assertj.core.api.Assertions; -import org.junit.Test; - -import com.carrotsearch.randomizedtesting.FilterExpressionParser.IContext; -import com.carrotsearch.randomizedtesting.FilterExpressionParser.Node; -import com.carrotsearch.randomizedtesting.FilterExpressionParser.SyntaxException; - -public class TestFilterExpressionParser { - @Test - public void testParsingSanity() { - // input -> expected bracketing. - Deque examples = new ArrayDeque(Arrays.asList( - "", "default", - "default", "default", - "@nightly", "@nightly", - "@nightly or @slow", "(@nightly OR @slow)", - "@nightly and @slow", "(@nightly AND @slow)", - "@nightly and not @slow", "(@nightly AND (NOT @slow))", - "@nightly and (not @slow)", "(@nightly AND (NOT @slow))", - "not @slow", "(NOT @slow)", - "not not @slow", "(NOT (NOT @slow))", - "not @nightly or @slow", "((NOT @nightly) OR @slow)", - "not(@nightly or @slow)", "(NOT (@nightly OR @slow))", - "(@nightly and (not @slow))", "(@nightly AND (NOT @slow))")); - - while (!examples.isEmpty()) { - String input = examples.remove(); - String expected = examples.remove(); - - System.out.println("-- " + input); - Node root = new FilterExpressionParser().parse(input); - String expression = root.toExpression(); - System.out.println(" " + expression); - - Assertions.assertThat(expression) - .as(input) - .isEqualTo(expected); - - Assertions.assertThat(new FilterExpressionParser().parse(expression).toExpression()) - .as(input) - .isEqualTo(expression); - } - } - - @Test - public void testTrueExpressions() { - // {groups}, {rules} - Deque examples = new ArrayDeque(Arrays.asList(new String [][] { - {}, - {"not @foo", "not default"}, - - {"@nightly"}, - {"@nightly", "@nightly or @foo", "@foo or @nightly", "not not @nightly"}, - - {"@nightly", "@slow"}, - {"@nightly and @slow", "@nightly and not @foo", "not @nightly or @slow"}, - - {"default"}, - {"", "default"}, - })); - - while (!examples.isEmpty()) { - final List groups = Arrays.asList((String[]) examples.pop()); - IContext context = new IContext() { - @Override - public boolean defaultValue() { - return hasGroup("default"); - } - - @Override - public boolean hasGroup(String value) { - return groups.contains(value); - } - }; - - for (String rule : examples.pop()) { - Assertions.assertThat(new FilterExpressionParser().parse(rule).evaluate(context)) - .as("ctx=" + groups + ", rule=" + rule) - .isEqualTo(true); - } - } - } - - @Test - public void testFalseExpressions() { - // {groups}, {rules} - Deque examples = new ArrayDeque(Arrays.asList(new String [][] { - {}, - {"@foo", "default"}, - - {"@nightly"}, - {"not @nightly", "@nightly and @foo"}, - - {"@nightly", "@slow"}, - {"not(@nightly or @slow)"}, - })); - - while (!examples.isEmpty()) { - final List groups = Arrays.asList((String[]) examples.pop()); - IContext context = new IContext() { - @Override - public boolean defaultValue() { - return hasGroup("default"); - } - - @Override - public boolean hasGroup(String value) { - return groups.contains(value); - } - }; - - for (String rule : examples.pop()) { - Assertions.assertThat(new FilterExpressionParser().parse(rule).evaluate(context)) - .as("ctx=" + groups + ", rule=" + rule) - .isEqualTo(false); - } - } - } - - @Test - public void testErrors() { - for (String rule : Arrays.asList( - "nightly", - "@nightly and ", - "@nightly or ", - "@nightly and or @slow", - "and not @slow", - "(@nightly))", - "((@nightly or @slow)" - )) { - - System.out.println("-- " + rule); - try { - new FilterExpressionParser().parse(rule); - Assertions.fail("Should cause an exception: " + rule); - } catch (SyntaxException e) { - System.out.println(" " + e.getMessage()); - } - } - } - - @Test - public void testInvalidToken() { - try { - new FilterExpressionParser().parse("@nightly and foo or @bar"); - } catch (SyntaxException e) { - Assertions.assertThat(e.toString()).contains(">foo<"); - } - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestFormattingRandomSeeds.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestFormattingRandomSeeds.java deleted file mode 100644 index c3c49926..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestFormattingRandomSeeds.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; - -import com.carrotsearch.randomizedtesting.annotations.Repeat; - -@RunWith(RandomizedRunner.class) -public class TestFormattingRandomSeeds { - @Test - public void minusOne() { - check(-1L); - } - - @Test - public void zero() { - check(0); - } - - @Test - public void maxLong() { - check(Long.MAX_VALUE); - } - - /** Heck, why not use ourselves here? ;) */ - @Test - @Repeat(iterations = 1000) - public void noise() { - check(RandomizedContext.current().getRandom().nextLong()); - } - - private void check(long seed) { - String asString = SeedUtils.formatSeedChain(new Randomness(seed, RandomSupplier.DEFAULT)); - Assert.assertEquals(seed, SeedUtils.parseSeedChain(asString)[0]); - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestGlobFilter.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestGlobFilter.java deleted file mode 100644 index 08d2bb0b..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestGlobFilter.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import org.assertj.core.api.Assertions; -import org.junit.Assert; -import org.junit.Test; - -public class TestGlobFilter { - @Test - public void testBrackets() { - GlobFilter gf = new MethodGlobFilter("ab(*)"); - Assert.assertTrue(gf.globMatches("ab()")); - Assert.assertTrue(gf.globMatches("ab(foo)")); - Assert.assertTrue(gf.globMatches("ab(bar=xxx)")); - - gf = new MethodGlobFilter("test {yaml=resthandler/10_Foo/Bar (Hello)}"); - Assert.assertTrue(gf.globMatches("test {yaml=resthandler/10_Foo/Bar (Hello)}")); - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestHookMethodOrderWithExceptions.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestHookMethodOrderWithExceptions.java deleted file mode 100644 index b78ffdbe..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestHookMethodOrderWithExceptions.java +++ /dev/null @@ -1,131 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import java.util.ArrayList; -import java.util.List; -import java.util.Random; - -import org.assertj.core.api.Assertions; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; - -import com.carrotsearch.randomizedtesting.WithNestedTestClass.FullResult; -import com.carrotsearch.randomizedtesting.annotations.Repeat; - -/** - * Try to be compatible with JUnit's runners wrt method hooks throwing - * exceptions. - */ -public class TestHookMethodOrderWithExceptions extends RandomizedTest { - static final List callOrder = new ArrayList(); - - /** - * Test superclass. - */ - public abstract static class Super { - static Random rnd; - - @BeforeClass - public static void beforeClassSuper() { - callOrder.add("beforeClassSuper"); - maybeThrowException(); - } - - @Before - public final void beforeTest() { - callOrder.add("beforeTestSuper"); - maybeThrowException(); - } - - @After - public final void afterTest() { - callOrder.add("afterTestSuper"); - maybeThrowException(); - - } - - @AfterClass - public static void afterClassSuper() { - callOrder.add("afterClassSuper"); - maybeThrowException(); - } - - public static void maybeThrowException() { - if (rnd != null && rnd.nextInt(10) == 0) { - throw new RuntimeException(); - } - } - } - - /** - * Test subclass. - */ - public static class SubSub extends Super { - @BeforeClass - public static void beforeClass() { - callOrder.add("beforeClassSub"); - maybeThrowException(); - } - - @Before - public void beforeTestSub() { - callOrder.add("beforeTestSub"); - maybeThrowException(); - } - - @Test - public void testMethod() { - callOrder.add("testMethodSub"); - maybeThrowException(); - } - - @After - public void afterTestSub() { - callOrder.add("afterTestSub"); - maybeThrowException(); - } - - @AfterClass - public static void afterClass() { - callOrder.add("afterClassSub"); - maybeThrowException(); - } - } - - @Before - public void setup() { - callOrder.clear(); - } - - @After - public void cleanup() { - callOrder.clear(); - } - - @RunWith(RandomizedRunner.class) - public static class WithRandomizedRunner extends SubSub {} - public static class WithRegularRunner extends SubSub {} - - @Test @Repeat(iterations = 20) - public void checkOrderSameAsJUnit() throws Exception { - long seed = RandomizedContext.current().getRandomness().getSeed(); - - callOrder.clear(); - Super.rnd = new Random(seed); - - FullResult r1 = WithNestedTestClass.runTests(WithRegularRunner.class); - List junitOrder = new ArrayList(callOrder); - - callOrder.clear(); - Super.rnd = new Random(seed); - FullResult r2 = WithNestedTestClass.runTests(WithRandomizedRunner.class); - List rrunnerOrder = new ArrayList(callOrder); - - Assert.assertEquals(junitOrder, rrunnerOrder); - Assertions.assertThat(r1.getRunCount()).isEqualTo(r2.getRunCount()); - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestHooksWithEmptyTestSet.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestHooksWithEmptyTestSet.java deleted file mode 100644 index 76806646..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestHooksWithEmptyTestSet.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import static org.junit.Assert.assertFalse; - -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; - -/** - * Hooks should _not_ execute if there are no test cases to run. Note that - * ignored test cases behave as if there was something to execute (!). - */ -public class TestHooksWithEmptyTestSet extends WithNestedTestClass { - @RunWith(RandomizedRunner.class) - public static class Nested { - static boolean beforeClassExecuted; - static boolean afterClassExecuted; - - @BeforeClass - public static void beforeClass() { - assumeRunningNested(); - beforeClassExecuted = true; - } - - @AfterClass - public static void afterClass() { - afterClassExecuted = true; - } - } - - /** - * Check if methods get the same seed on every run with a fixed runner's seed. - */ - @Test - public void testSameMethodRandomnessWithFixedRunner() { - Nested.beforeClassExecuted = false; - Nested.afterClassExecuted = false; - checkTestsOutput(0, 0, 0, 0, Nested.class); - assertFalse(Nested.beforeClassExecuted); - assertFalse(Nested.afterClassExecuted); - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestIgnoredRunCount.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestIgnoredRunCount.java deleted file mode 100644 index 2e7b817b..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestIgnoredRunCount.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import org.junit.*; -import org.junit.runner.*; - -/** - * Test {@link Result}'s run count for ignored tests. - */ -public class TestIgnoredRunCount extends WithNestedTestClass { - public static class Nested1 { - @Test @Ignore - public void ignored() {} - } - - @RunWith(RandomizedRunner.class) - public static class Nested2 { - @Test @Ignore - public void ignored() {} - } - - @Test - public void checkIgnoredCount() throws Exception { - checkTestsOutput(0, 1, 0, 0, Nested1.class); - checkTestsOutput(0, 1, 0, 0, Nested2.class); - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestInstantiationTime.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestInstantiationTime.java deleted file mode 100644 index a479594e..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestInstantiationTime.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import org.junit.BeforeClass; -import org.junit.Test; - -/** - * Check that {@link BeforeClass} hooks are called before instance initializers. - */ -public class TestInstantiationTime extends RandomizedTest { - - private static String constant; - - /** - * Instance initializer. Will result in an NPE if - * {@link #prepare()} is not invoked before. - */ - public String copyOfStatic = constant.toUpperCase(); - - @BeforeClass - public static void prepare() { - constant = "constant"; - } - - @Test - public void testDummy() { - // empty. - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestIterationsAnnotation.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestIterationsAnnotation.java deleted file mode 100644 index 994e269d..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestIterationsAnnotation.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; - -import com.carrotsearch.randomizedtesting.annotations.Repeat; - -/** - * Nightly mode checks. - */ -public class TestIterationsAnnotation extends RandomizedTest { - static int iterations = 0; - - @Test @Repeat(iterations = 10) - public void nightly() { - iterations++; - } - - @BeforeClass - public static void clean() { - iterations = 0; - } - - @AfterClass - public static void cleanupAfter() { - Assert.assertEquals(10, iterations); - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestJ9SysThreads.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestJ9SysThreads.java deleted file mode 100644 index 0a6caa8d..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestJ9SysThreads.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import java.lang.management.ManagementFactory; -import java.lang.management.MemoryPoolMXBean; - -import org.junit.Test; - -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakAction; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakAction.Action; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope.Scope; - -/** - * Test {@link Test#expected()}. - */ -public class TestJ9SysThreads extends WithNestedTestClass { - @ThreadLeakScope(Scope.SUITE) - @ThreadLeakAction({Action.INTERRUPT}) - public static class Nested extends RandomizedTest { - @Test - public void testMethod1() { - assumeRunningNested(); - - for (MemoryPoolMXBean mbean : ManagementFactory.getMemoryPoolMXBeans()) { - mbean.getUsage(); - sysout.println(mbean.getClass().getName()); - } - } - } - - @Test - public void testSuccessfulExceptedFailure() { - checkTestsOutput(1, 0, 0, 0, Nested.class); - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestJUnit3MethodProvider.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestJUnit3MethodProvider.java deleted file mode 100644 index 742b1434..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestJUnit3MethodProvider.java +++ /dev/null @@ -1,71 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.JUnitCore; -import org.junit.runner.Result; -import org.junit.runners.model.InitializationError; - -import com.carrotsearch.randomizedtesting.annotations.TestMethodProviders; - -public class TestJUnit3MethodProvider { - @TestMethodProviders({JUnit3MethodProvider.class}) - public static class Base {} - - @SuppressWarnings("unused") - public static class T4 extends Base { private void test1() {} } - public static class T2 extends Base { void test1() {} } - public static class T3 extends Base { protected void test1() {} } - public static class T1 extends Base { public void test1() {} } - - @SuppressWarnings("unused") - public static class ST4 extends Base { static private void test1() {} } - public static class ST2 extends Base { static void test1() {} } - public static class ST3 extends Base { static protected void test1() {} } - public static class ST1 extends Base { static public void test1() {} } - - public static class AT1 extends Base { public void test1(int arg) {} } - public static class RT1 extends Base { public int test1() { return 0; } } - - @Test - public void testJUnit3Valid() throws Exception { - Class [] valid = { - T1.class, RT1.class - }; - - for (Class cl : valid) { - Result r = new JUnitCore().run(new RandomizedRunner(cl)); - Assert.assertEquals(0, r.getFailureCount()); - Assert.assertEquals(1, r.getRunCount()); - } - } - - @Test - public void testJUnit3Invalid() { - Class [] invalid = { - T2.class, T3.class, T4.class, - ST1.class, ST2.class, ST3.class, ST4.class, - AT1.class - }; - - for (Class cl : invalid) { - try { - new JUnitCore().run(new RandomizedRunner(cl)); - Assert.fail("Expected to fail for: " + cl); - } catch (InitializationError e) { - // expected. - } - } - } - - public static class S1 extends Base { public void test1() {} } - public static class S2 extends S1 { public void test1() {} } - public static class S3 extends S2 { public void test1() {} } - - @Test - public void testJUnit3Overrides() throws Exception { - Result r = new JUnitCore().run(new RandomizedRunner(S3.class)); - Assert.assertEquals(0, r.getFailureCount()); - Assert.assertEquals(1, r.getRunCount()); - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestListenersAnnotation.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestListenersAnnotation.java deleted file mode 100644 index 25c5e808..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestListenersAnnotation.java +++ /dev/null @@ -1,95 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import java.util.ArrayList; -import java.util.List; - -import org.junit.Assert; -import org.junit.Assume; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.Description; -import org.junit.runner.Result; -import org.junit.runner.notification.Failure; -import org.junit.runner.notification.RunListener; - -import com.carrotsearch.randomizedtesting.annotations.Listeners; - -/** - * Test listeners on suite. - */ -public class TestListenersAnnotation extends WithNestedTestClass { - - public static List buffer = new ArrayList(); - - public static class NoopListener extends RunListener { - } - - public static class BufferAppendListener extends RunListener { - public void testRunStarted(Description description) throws Exception { - buffer.add("run started: " + description.getMethodName()); - } - - public void testStarted(Description description) throws Exception { - buffer.add("test started: " + description.getMethodName()); - } - - @Override - public void testFinished(Description description) throws Exception { - buffer.add("test finished: " + description.getMethodName()); - } - - @Override - public void testAssumptionFailure(Failure failure) { - buffer.add("assumption failed: " + failure.getDescription().getMethodName()); - } - - @Override - public void testIgnored(Description description) throws Exception { - buffer.add("test ignored: " + description.getMethodName()); - } - - @Override - public void testFailure(Failure failure) throws Exception { - buffer.add("failure: " + failure.getDescription().getMethodName()); - } - - @Override - public void testRunFinished(Result result) throws Exception { - buffer.add("run finished: " + result.getRunCount()); - } - } - - @Listeners({BufferAppendListener.class}) - public static class Nested1 extends RandomizedTest { - } - - @Listeners({NoopListener.class}) - public static class Nested2 extends Nested1 { - @Test @Ignore - public void ignored() { - } - - @Test - public void passing() throws Exception { - } - - @Test - public void failing() throws Exception { - assumeRunningNested(); - Assert.fail(); - } - - @Test - public void assumptionFailing() throws Exception { - assumeRunningNested(); - Assume.assumeTrue(false); - } - } - - @Test - public void checkListeners() { - runTests(Nested2.class); - // Perhaps this is overly simple, but we just want to know that it executed. - Assert.assertTrue(buffer.size() > 0); - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestMacSysThreads.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestMacSysThreads.java deleted file mode 100644 index a4614300..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestMacSysThreads.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import java.lang.management.ManagementFactory; - -import javax.management.MBeanServer; - -import org.junit.Test; - -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakAction; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakAction.Action; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope.Scope; - -/** - * Test Mac system threads. - */ -public class TestMacSysThreads extends WithNestedTestClass { - @ThreadLeakScope(Scope.SUITE) - @ThreadLeakAction({Action.WARN}) - public static class Nested extends RandomizedTest { - @Test - public void testMethod1() { - MBeanServer mb = ManagementFactory.getPlatformMBeanServer(); - mb.getMBeanCount(); - RandomizedTest.sleep(2500); - } - } - - @Test - public void testSuccessful() { - checkTestsOutput(1, 0, 0, 0, Nested.class); - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestManyThreadsOOM.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestManyThreadsOOM.java deleted file mode 100644 index 2915752c..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestManyThreadsOOM.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import java.util.Random; - -import org.junit.Test; - -import com.carrotsearch.randomizedtesting.annotations.Repeat; - -/** - * Make sure we don't OOM even if we recreate many, many threads during a test/ suite. - */ -public class TestManyThreadsOOM extends RandomizedTest { - volatile int guard; - - @Test - @Repeat(iterations = 10) - public void testSpawnManyThreads() throws Exception { - // create threads sequentially, attaching a big blob of data to each, then - // touch the context from within a thread and die. - for (int i = 0; i < 500; i++) { - final Thread t = new Thread() { - final byte [] hold = new byte [1024 * 1024 * 10]; - - public void run() { - Random rnd = RandomizedContext.current().getRandom(); - guard += rnd.nextInt() + hold.length; - } - }; - - t.start(); - t.join(); - } - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestNightlyMode.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestNightlyMode.java deleted file mode 100644 index f5752a02..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestNightlyMode.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import static org.junit.Assert.assertTrue; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import com.carrotsearch.randomizedtesting.annotations.Nightly; -import com.carrotsearch.randomizedtesting.annotations.TestGroup; - -/** - * Nightly mode checks. - */ -public class TestNightlyMode extends WithNestedTestClass { - public static class Nested extends RandomizedTest { - @Test - public void passOnNightlyOnly() { - assumeRunningNested(); - assertTrue(isNightly()); - } - - @Test @Nightly("Nightly only test case.") - public void nightlyOnly() throws Exception { - } - } - - @Test - public void invalidValueNightly() { - System.setProperty(TestGroup.Utilities.getSysProperty(Nightly.class), "invalid-value"); - dailyDefault(); - } - - @Test - public void nightly() { - System.setProperty(TestGroup.Utilities.getSysProperty(Nightly.class), "yes"); - checkTestsOutput(2, 0, 0, 0, Nested.class); - } - - @Test - public void dailyDefault() { - checkTestsOutput(2, 0, 1, 1, Nested.class); - } - - @Before - public void cleanupBefore() { - cleanupAfter(); - } - - @After - public void cleanupAfter() { - System.clearProperty(TestGroup.Utilities.getSysProperty(Nightly.class)); - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestOutOfScopeRandomUse.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestOutOfScopeRandomUse.java deleted file mode 100644 index ffc3300e..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestOutOfScopeRandomUse.java +++ /dev/null @@ -1,135 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import static org.junit.Assert.fail; - -import java.util.List; -import java.util.Random; - -import org.assertj.core.api.Assertions; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.notification.Failure; - -import com.carrotsearch.randomizedtesting.annotations.Timeout; - -import org.junit.Assert; - -/** - * Check out of scope {@link Random} use. - */ -public class TestOutOfScopeRandomUse extends WithNestedTestClass { - public static class Nested extends RandomizedTest { - static Random instanceRandom; - static Random beforeHookRandom; - static Random staticContextRandom; - volatile static Random otherThreadRandom; - - @BeforeClass - public static void beforeClass() throws Exception { - assumeRunningNested(); - instanceRandom = null; - staticContextRandom = getRandom(); - - // Should be able to use the random we've acquired for the static context. - staticContextRandom.nextBoolean(); - - Thread t = new Thread() { - public void run() { - otherThreadRandom = getRandom(); - } - }; - t.start(); - t.join(); - } - - @AfterClass - public static void afterClass() { - if (!isRunningNested()) { - return; - } - - // Again should be able to use the random we've acquired for the static context. - staticContextRandom.nextBoolean(); - } - - @Before - public void before() { - beforeHookRandom = getRandom(); - } - - private void touchRandom() { - assumeRunningNested(); - - // We shouldn't be able to reach to some other thread's random for which - // the context is still valid. - try { - otherThreadRandom.nextBoolean(); - fail("Shouldn't be able to use another thread's Random."); - } catch (IllegalStateException e) { - // Expected. - } - - // We should always be able to reach to @Before hook initialized Random. - beforeHookRandom.nextBoolean(); - - // Check if we're the first method or the latter methods. - if (instanceRandom == null) { - instanceRandom = getRandom(); - } else { - // for anything not-first, we shouldn't be able to reuse first random anymore. - try { - instanceRandom.nextBoolean(); - fail("Shouldn't be able to use another test's Random."); - } catch (IllegalStateException e) { - // Expected. - } - } - } - - @Test - public void method1() throws Exception { - touchRandom(); - } - - @Test @Timeout(millis = 2000) - public void method2() throws Exception { - touchRandom(); - - // We shouldn't be able to use the static random because timeouting tests - // are executed in their own thread and before and after class hooks are - // dispatched in their own thread to allow termination/ interruptions. - try { - staticContextRandom.nextBoolean(); - fail("Shouldn't be able to use static context thread's Random."); - } catch (IllegalStateException e) { - // Expected. - } - } - } - - @Before - public void checkRunningWithAssertions() { - // Sharing Random is only checked with -ea - // https://github.com/randomizedtesting/randomizedtesting/issues/234 - RandomizedTest.assumeTrue("AssertionRandom not verifying sharing.", AssertingRandom.isVerifying()); - } - - @Test - public void testCrossTestCaseIsolation() throws Throwable { - List failures = runTests(Nested.class).getFailures(); - Assertions.assertThat(failures).isEmpty(); - } - - @Test - public void testCrossTestSuiteIsolation() { - runTests(Nested.class); - try { - Nested.staticContextRandom.nextBoolean(); - Assert.fail("Shouldn't be able to use another suite's Random."); - } catch (IllegalStateException e) { - // Expected. - } - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestOverlappingMethodProviders.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestOverlappingMethodProviders.java deleted file mode 100644 index 2850fa39..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestOverlappingMethodProviders.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.JUnitCore; -import org.junit.runner.Result; - -import com.carrotsearch.randomizedtesting.annotations.TestMethodProviders; - -public class TestOverlappingMethodProviders { - @TestMethodProviders({ - JUnit4MethodProvider.class, - JUnit3MethodProvider.class - }) - public static class Base { - @Test - public void testMe() {} - } - - @Test - public void testSingleMethod() throws Exception { - Result r = new JUnitCore().run(Base.class); - Assert.assertEquals(0, r.getFailureCount()); - Assert.assertEquals(1, r.getRunCount()); - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestOverridingDefaultExceptionHandler.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestOverridingDefaultExceptionHandler.java deleted file mode 100644 index 4cc50d00..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestOverridingDefaultExceptionHandler.java +++ /dev/null @@ -1,77 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import java.lang.Thread.UncaughtExceptionHandler; -import java.util.List; -import java.util.concurrent.CopyOnWriteArrayList; - -import org.assertj.core.api.Assertions; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; - -public class TestOverridingDefaultExceptionHandler extends WithNestedTestClass { - static List throwableMessages = new CopyOnWriteArrayList<>(); - - @SuppressWarnings("serial") - public static class TestException extends RuntimeException { - public TestException(String msg) { - super(msg); - } - } - - public static class Nested extends RandomizedTest { - private static UncaughtExceptionHandler defaultHandler; - - @BeforeClass - public static void beforeClass() { - defaultHandler = Thread.getDefaultUncaughtExceptionHandler(); - Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() { - public void uncaughtException(Thread t, Throwable e) { - if (e instanceof TestException) { - throwableMessages.add(e.getMessage()); - } else { - defaultHandler.uncaughtException(t, e); - } - } - }); - } - - @AfterClass - public static void afterClass() { - Thread.setDefaultUncaughtExceptionHandler(defaultHandler); - } - - @Test - public void exceptionFromChildThread() throws Exception { - Thread t = new Thread() { - @Override - public void run() { - throw new TestException("exceptionFromChildThread"); - } - }; - t.start(); - t.join(); - } - - @Test - public void exceptionFromSubGroup() throws Exception { - ThreadGroup subgroup = new ThreadGroup("subgroup"); - Thread t = new Thread(subgroup, new Runnable() { - @Override - public void run() { - throw new TestException("exceptionFromSubGroup"); - } - }); - t.start(); - t.join(); - } - } - - @Test - public void testHandlerPropagation() { - runTests(Nested.class); - - Assertions.assertThat(throwableMessages).contains("exceptionFromChildThread"); - Assertions.assertThat(throwableMessages).contains("exceptionFromSubGroup"); - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestParameterized.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestParameterized.java deleted file mode 100644 index 060d3b62..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestParameterized.java +++ /dev/null @@ -1,124 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import static org.junit.Assert.*; - -import java.util.Arrays; -import java.util.Collections; - -import org.assertj.core.api.Assertions; -import org.junit.Assert; -import org.junit.Test; - -import com.carrotsearch.randomizedtesting.annotations.Name; -import com.carrotsearch.randomizedtesting.annotations.ParametersFactory; -import com.carrotsearch.randomizedtesting.annotations.Repeat; -import com.carrotsearch.randomizedtesting.annotations.Seed; -import com.carrotsearch.randomizedtesting.annotations.Seeds; - -public class TestParameterized extends WithNestedTestClass { - public static class Nested extends RandomizedTest { - public Nested(@Name("value") int value, @Name("string") String v) { - } - - @Test - @Repeat(iterations = 3) - public void testOne() { - } - - @Test - public void testTwo() { - } - - @Seeds({@Seed("deadbeef"), @Seed("cafebabe")}) - @Test - @Repeat(iterations = 2, useConstantSeed = true) - public void testThree() { - } - - @ParametersFactory - public static Iterable parameters() { - return Arrays.asList($$( - $(1, "abc"), - $(2, "def"))); - } - } - - @Test - public void testWithRepeatsAndSeeds() { - checkTestsOutput(16, 0, 0, 0, Nested.class); - } - - public static class Nested2 extends RandomizedTest { - public Nested2(@Name("paramName") int value) { - } - - @Test - public void failing() { - assumeRunningNested(); - fail(); - } - - @ParametersFactory - public static Iterable parameters() { - assumeRunningNested(); - return Arrays.asList($$($("xyz"))); - } - } - - @Test - public void testNameAnnotation() { - FullResult r = checkTestsOutput(1, 0, 1, 0, Nested2.class); - Assertions.assertThat(r.getFailures()).hasSize(1); - Assertions.assertThat(r.getFailures().get(0).getDescription().getMethodName()) - .contains("paramName=xyz"); - Assert.assertEquals("failing", RandomizedRunner.methodName(r.getFailures().get(0).getDescription())); - } - - public static class Nested3 extends Nested2 { - public Nested3(@Name("paramName") int value) { - super(value); - } - - @ParametersFactory - public static Iterable parameters() { - return Collections.emptyList(); - } - } - - public static class Nested4 extends Nested3 { - public Nested4(@Name("paramName") int value) { - super(value); - } - - @ParametersFactory - public static Iterable parameters() { - assumeTrue(false); - throw new RuntimeException(); - } - } - - - public static class Nested5 extends RandomizedTest { - public Nested5() {} - - @Test - public void testMe() {} - - @ParametersFactory - public static Iterable parameters() { - return Arrays.asList(new Object[] {}, - new Integer[] {}); - } - } - - @Test - public void testEmptyParamsList() { - checkTestsOutput(0, 0, 0, 0, Nested3.class); - checkTestsOutput(0, 0, 0, 0, Nested4.class); - } - - @Test - public void testNonObjectArray() { - checkTestsOutput(2, 0, 0, 0, Nested5.class); - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestParameterizedShufflesOrder.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestParameterizedShufflesOrder.java deleted file mode 100644 index 536d198f..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestParameterizedShufflesOrder.java +++ /dev/null @@ -1,87 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import org.assertj.core.api.Assertions; -import org.junit.BeforeClass; -import org.junit.Test; - -import com.carrotsearch.randomizedtesting.annotations.ParametersFactory; - -public class TestParameterizedShufflesOrder extends WithNestedTestClass { - static StringBuilder buf; - - public static abstract class Base extends RandomizedTest { - private final int value; - - public Base(int value) { - this.value = value; - } - - @BeforeClass - public static void checkNested() { - assumeRunningNested(); - } - - @Test - public void testFoo() { - buf.append(value).append(","); - } - } - - public static class NoShuffle extends Base { - public NoShuffle(int value) { - super(value); - } - - @ParametersFactory(shuffle = false) - public static Iterable parameters() { - List params = new ArrayList(); - for (int i = 0; i < 10; i++) { - params.add($(i)); - } - return params; - } - } - - public static class WithShuffle extends Base { - public WithShuffle(int value) { - super(value); - } - - @ParametersFactory() - public static Iterable parameters() { - List params = new ArrayList(); - for (int i = 0; i < 10; i++) { - params.add($(i)); - } - return params; - } - } - - @Test - public void testWithoutShuffle() { - Set runs = new HashSet(); - for (int i = 0; i < 10; i++) { - buf = new StringBuilder(); - Assertions.assertThat(runTests(NoShuffle.class).wasSuccessful()).isTrue(); - runs.add(buf.toString()); - } - Assertions.assertThat(runs).hasSize(1); - } - - @Test - public void testWithShuffle() { - Set runs = new HashSet(); - int iters = 10; - for (int i = 0; i < iters; i++) { - buf = new StringBuilder(); - Assertions.assertThat(runTests(WithShuffle.class).wasSuccessful()).isTrue(); - runs.add(buf.toString()); - } - Assertions.assertThat(runs).hasSize(iters); - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestRandom.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestRandom.java deleted file mode 100644 index fa031594..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestRandom.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import static org.junit.Assert.*; - -import java.util.Arrays; -import java.util.Random; - -import org.junit.Test; - -import com.carrotsearch.randomizedtesting.annotations.Repeat; - -@Repeat(iterations = 100) -public class TestRandom extends RandomizedTest { - @Test - public void testDoubleDistribution() { - Random rnd = getRandom(); - - int [] buckets = new int [100]; - int reps = 1000000; - for (int i = 0; i < reps; i++) { - double d = rnd.nextDouble(); - if (d < 0d || d >= 1d) { - fail("Oops: " + d); - } - - buckets[(int) (d * buckets.length)]++; - } - - // The distribution should be +- 10% within average. - int expectedAverage = reps / buckets.length; - int min = expectedAverage - expectedAverage / 10; - int max = expectedAverage + expectedAverage / 10; - for (int i = 0; i < buckets.length; i++) { - if (buckets[i] < min || buckets[i] > max) { - fail("oops: " + buckets[i] + " biased? " + Arrays.toString(buckets)); - } - } - } - - @Test - public void testFloatDistribution() { - Random rnd = getRandom(); - - int [] buckets = new int [100]; - int reps = 1000000; - for (int i = 0; i < reps; i++) { - float d = rnd.nextFloat(); - if (d < 0f || d >= 1f) { - fail("Oops: " + d); - } - - buckets[(int) (d * buckets.length)]++; - } - - // The distribution should be +- 10% within average. - int expectedAverage = reps / buckets.length; - int min = expectedAverage - expectedAverage / 10; - int max = expectedAverage + expectedAverage / 10; - for (int i = 0; i < buckets.length; i++) { - if (buckets[i] < min || buckets[i] > max) { - fail("oops: " + buckets[i] + " biased? " + Arrays.toString(buckets)); - } - } - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestRandomInStaticInitializer.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestRandomInStaticInitializer.java deleted file mode 100644 index c17bf964..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestRandomInStaticInitializer.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import java.util.Random; - -import org.junit.Test; - -import static org.junit.Assert.*; - -/** - * Check out of scope {@link Random} use. - */ -public class TestRandomInStaticInitializer extends RandomizedTest { - static boolean wasOutOfScope; - - static { - try { - RandomizedContext.current(); - } catch (IllegalStateException e) { - wasOutOfScope = true; - } - } - - @Test - public void testStaticInitializerOutOfScope() { - assertTrue(wasOutOfScope); - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestRandomNumbers.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestRandomNumbers.java deleted file mode 100644 index 2c930862..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestRandomNumbers.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import static org.junit.Assert.*; - -import java.util.Random; - -import org.junit.Test; - -import com.carrotsearch.randomizedtesting.annotations.Repeat; -import com.carrotsearch.randomizedtesting.generators.RandomNumbers; - -@Repeat(iterations = 100) -public class TestRandomNumbers extends RandomizedTest { - @Test - public void testRandomIntBetween() { - int max = Integer.MAX_VALUE; - int min = Integer.MIN_VALUE; - - Random rnd = getRandom(); - checkRandomInt(rnd, 1, 1); - checkRandomInt(rnd, 0, 100); - checkRandomInt(rnd, 0, max); - checkRandomInt(rnd, min, 0); - checkRandomInt(rnd, -1, max); - checkRandomInt(rnd, min, 1); - checkRandomInt(rnd, min, max); - } - - @Test - public void testRandomLongBetween() { - long max = Long.MAX_VALUE; - long min = Long.MIN_VALUE; - - Random rnd = getRandom(); - checkRandomLong(rnd, 1, 1); - checkRandomLong(rnd, 0, 100); - checkRandomLong(rnd, 0, max); - checkRandomLong(rnd, min, 0); - checkRandomLong(rnd, -1, max); - checkRandomLong(rnd, min, 1); - checkRandomLong(rnd, min, max); - } - - private void checkRandomInt(Random rnd, int min, int max) { - for (int i = 0; i < 100000; i++) { - int v = RandomNumbers.randomIntBetween(rnd, min, max); - if (v < min || v > max) { - fail(min + " " + max + ": " + v); - } - } - } - - private void checkRandomLong(Random rnd, long min, long max) { - for (int i = 0; i < 100000; i++) { - long v = RandomNumbers.randomLongBetween(rnd, min, max); - if (v < min || v > max) { - fail(min + " " + max + ": " + v); - } - } - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestRandomizedContext.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestRandomizedContext.java deleted file mode 100644 index 48966f60..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestRandomizedContext.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import org.junit.Test; - -import java.util.concurrent.Callable; - -import static org.junit.Assert.*; - -/** - */ -public class TestRandomizedContext extends RandomizedTest { - - @Test - public void testRunWithPrivateRandomness() throws Exception { - final int iters = randomIntBetween(1, 10); - for (int j = 0; j < iters; j++) { - final long seed = randomLong(); - final int[] first = RandomizedContext.current().runWithPrivateRandomness(seed, new Callable() { - @Override - public int[] call() throws Exception { - final int size = randomIntBetween(10, 1000); - final int[] result = new int[size]; - for (int i = 0; i < size; i++) { - result[i] = randomInt(); - } - return result; - } - }); - assertNotNull(first); - final int[] second = RandomizedContext.current().runWithPrivateRandomness(seed, new Callable() { - @Override - public int[] call() throws Exception { - final int size = randomIntBetween(10, 1000); - final int[] result = new int[size]; - for (int i = 0; i < size; i++) { - result[i] = randomInt(); - } - return result; - } - }); - assertNotNull(second); - assertNotSame(first, second); - assertArrayEquals("first and second sequence must be identical", first, second); - } - } - -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestRandomizedTest.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestRandomizedTest.java deleted file mode 100644 index 40a53487..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestRandomizedTest.java +++ /dev/null @@ -1,264 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import java.io.IOException; -import java.net.ServerSocket; -import java.nio.file.DirectoryStream; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.TimeZone; -import java.util.Arrays; - -import org.junit.Test; -import org.junit.internal.AssumptionViolatedException; - -import static org.junit.Assert.*; - -public class TestRandomizedTest extends RandomizedTest { - @Test - public void testRandomIntBetween() { - boolean [] array = new boolean [10]; - for (int i = 0; i < 10000; i++) - array[randomIntBetween(0, array.length - 1)] = true; - - for (boolean b: array) - assertTrue(b); - } - - @Test - public void testAtLeast() { - assertEquals(atLeast(Integer.MAX_VALUE), Integer.MAX_VALUE); - int v = randomIntBetween(0, Integer.MAX_VALUE); - for (int i = 0; i < 10000; i++) - assertTrue(atLeast(v) >= v); - } - - @Test - public void testAtMost() { - assertEquals(atMost(0), 0); - int v = randomIntBetween(0, Integer.MAX_VALUE); - for (int i = 0; i < 10000; i++) - assertTrue(atMost(v) <= v); - } - - @Test - public void testRandomIntBetweenBoundaryCases() { - for (int i = 0; i < 10000; i++) { - int j = randomIntBetween(0, Integer.MAX_VALUE); - assertTrue(j >= 0 && j <= Integer.MAX_VALUE); - - // This must fall in range, but nonetheless - randomIntBetween(Integer.MIN_VALUE, Integer.MAX_VALUE); - } - } - - @Test - public void testRandomFromArray() { - try { - randomFrom(new Object [] {}); - fail(); - } catch (IllegalArgumentException e) { - // expected. - } - - Integer [] ints = new Integer [10]; - for (int i = 0; i < ints.length; i++) - ints[i] = i; - - for (int i = 0; i < 10000; i++) { - Integer j = randomFrom(ints); - if (j != null) { - ints[j] = null; - } - } - - for (int i = 0; i < ints.length; i++) - assertTrue(ints[i] == null); - } - - @Test - public void testRandomFromList() { - try { - randomFrom(Collections.emptyList()); - fail(); - } catch (IllegalArgumentException e) { - // expected. - } - - List ints = new ArrayList(); - for (int i = 0; i < 10; i++) - ints.add(i); - - for (int i = 0; i < 10000; i++) { - Integer j = randomFrom(ints); - if (j != null) { - ints.set(j, null); - } - } - - for (int i = 0; i < ints.size(); i++) - assertTrue(ints.get(i) == null); - } - - @Test - public void testNewTempDir() throws IOException { - for (int i = 0; i < 10; i++) { - Path dir = newTempDir(); - assertNotNull(dir); - assertTrue(Files.isDirectory(dir)); - assertTrue(Files.isWritable(dir)); - assertTrue(Files.isReadable(dir)); - assertTrue(Files.isExecutable(dir)); - try (DirectoryStream path = Files.newDirectoryStream(dir)) { - assertFalse(path.iterator().hasNext()); - } - } - } - - @Test - public void testNewTempFile() throws IOException { - for (int i = 0; i < 10; i++) { - Path file = newTempFile(); - assertNotNull(file); - assertTrue(Files.isRegularFile(file)); - assertTrue(Files.isWritable(file)); - assertTrue(Files.isReadable(file)); - assertTrue(file.getFileName().toString().indexOf(' ') >= 0); - Files.newOutputStream(file).close(); - } - } - - @Test - public void testRandomLocale() { - assertNotNull(randomLocale()); - } - - @Test - public void testRandomTimeZone() throws Exception { - try { - final String[] availableIDs = TimeZone.getAvailableIDs(); - Arrays.sort(availableIDs); - for (String id : availableIDs) { - assertNotNull(id); - if (TimeZone.getTimeZone(id) == null) { - fail("getTimeZone null: " + id); - } - } - } catch (Exception e) { - System.out.println("Wtf."); - e.printStackTrace(); - throw e; - } - - assertNotNull(randomTimeZone()); - } - - @Test - public void testRandomAsciiOfLength() { - assertTrue(randomAsciiLettersOfLength(0).isEmpty()); - - for (int i = 0; i < 1000; i++) { - int maxLength = randomIntBetween(0, 20); - String str = randomAsciiLettersOfLength(maxLength); - assertTrue(str.matches("[a-zA-Z]*")); - assertTrue(str.length() <= maxLength); - } - } - - @Test - public void testRandomAlphanumOfLength() { - assertTrue(randomAsciiAlphanumOfLength(0).isEmpty()); - - for (int i = 0; i < 1000; i++) { - int maxLength = randomIntBetween(0, 20); - String str = randomAsciiAlphanumOfLength(maxLength); - assertTrue(str.matches("[a-zA-Z0-9]*")); - assertTrue(str.length() <= maxLength); - } - } - - @Test - public void testRandomUnicodeOfLength() { - for (int i = 0; i < 1000; i++) { - int maxLength = randomIntBetween(0, 20); - String str = randomUnicodeOfLength(maxLength); - assertTrue(str.length() + " " + maxLength, str.length() <= maxLength); - } - } - - @Test - public void testRandomRealisticUnicodeOfLength() { - assertTrue(randomRealisticUnicodeOfLength(0).isEmpty()); - assertTrue(randomRealisticUnicodeOfCodepointLength(0).isEmpty()); - - for (int i = 0; i < 1000; i++) { - int minLength = randomIntBetween(0, 20); - int maxLength = minLength + randomIntBetween(0, 20); - String str = randomRealisticUnicodeOfCodepointLength(maxLength); - int codepoints = countCodepoints(str); - assertTrue(codepoints <= maxLength); - - str = randomRealisticUnicodeOfCodepointLengthBetween(minLength, maxLength); - codepoints = countCodepoints(str); - assertTrue(codepoints >= minLength); - assertTrue(codepoints <= maxLength); - } - } - - private static int countCodepoints(String str) { - return str.codePointCount(0, str.length()); - } - - @Test - public void testAssumeTrue() { - String message = randomUnicodeOfLength(10); - try { - assumeTrue(message, false); - } catch (AssumptionViolatedException e) { - assertTrue(e.getMessage().contains(message)); - } - } - - @Test - public void testAssumeNoException() { - String message = randomUnicodeOfLength(10); - Throwable t = new Throwable(); - try { - assumeNoException(message, t); - } catch (AssumptionViolatedException e) { - assertTrue(e.getMessage().contains(message)); - assertSame(t, e.getCause()); - } - } - - @Test - public void testIterations() { - assertEquals(0, iterations(0, 0)); - assertEquals(Integer.MAX_VALUE, iterations(Integer.MAX_VALUE, Integer.MAX_VALUE)); - - for (int i = 0; i < iterations(1, 1000); i++) { - int j = iterations(0, 100); - assertTrue(j >= 0 && j <= 100); - } - } - - @Test - public void testNewServerSocket() throws IOException { - ServerSocket socket = newServerSocket(LifecycleScope.TEST); - socket.close(); - } - - @Test - public void testRarely() throws IOException { - int rarely = 0; - int calls = 100000; - for (int i = 0; i < calls; i++) { - if (rarely()) rarely++; - } - - double rf = rarely / (double) calls * 100; - assertTrue("rarely should be > 5% & < 15%: " + rf, rf > 5 && rf < 15); - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestRepeatTestWithComplexDescription.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestRepeatTestWithComplexDescription.java deleted file mode 100644 index 1cdeacf2..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestRepeatTestWithComplexDescription.java +++ /dev/null @@ -1,75 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import java.util.ArrayList; -import java.util.List; - -import org.assertj.core.api.Assertions; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.Description; -import org.junit.runner.notification.RunListener; - -import com.carrotsearch.randomizedtesting.annotations.Listeners; -import com.carrotsearch.randomizedtesting.annotations.Name; -import com.carrotsearch.randomizedtesting.annotations.ParametersFactory; -import com.carrotsearch.randomizedtesting.annotations.Repeat; -import com.carrotsearch.randomizedtesting.annotations.Seed; -import com.carrotsearch.randomizedtesting.annotations.Seeds; -import com.carrotsearch.randomizedtesting.rules.SystemPropertiesRestoreRule; - -/** */ -public class TestRepeatTestWithComplexDescription extends WithNestedTestClass { - @Rule - public SystemPropertiesRestoreRule restoreProperties = new SystemPropertiesRestoreRule(); - - static ArrayList buf; - - public static class CaptureFailuresListener extends RunListener { - @Override - public void testStarted(Description description) throws Exception { - buf.add(description.getMethodName()); - } - } - - @Seed("deadbeef") - @Listeners({CaptureFailuresListener.class}) - public static class Nested extends RandomizedTest { - public Nested(@Name("value") String value) { - } - - @Test - @Seeds({@Seed(), @Seed("deadbeef")}) - @Repeat(iterations = 5, useConstantSeed = false) - public void testFoo() {} - - @Test - public void testBar() {} - - @ParametersFactory() - public static Iterable parameters() { - assumeRunningNested(); - - List params = new ArrayList(); - params.add($("")); - params.add($("a/b/c")); - params.add($("\\")); - params.add($("$[]{}\\")); - return params; - } - } - - @Test - public void checkFilteringByName() { - // Collect all test names first. - buf = new ArrayList(); - runTests(Nested.class); - - for (String testName : buf) { - buf = new ArrayList(); - System.setProperty(SysGlobals.SYSPROP_TESTMETHOD(), testName); - - Assertions.assertThat(runTests(Nested.class).wasSuccessful()).isTrue(); - Assertions.assertThat(buf).containsOnly(testName); - } - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestResourceDisposal.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestResourceDisposal.java deleted file mode 100644 index 4fb5b4dd..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestResourceDisposal.java +++ /dev/null @@ -1,108 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import java.io.Closeable; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; - -import org.junit.Assert; - - -/** - * Check resource disposal facilities. - */ -public class TestResourceDisposal extends WithNestedTestClass { - static class DummyCloseable implements Closeable { - public boolean closed; - public void close() throws IOException { - if (closed) throw new IOException(); - closed = true; - } - } - - public static class Nested extends RandomizedTest { - static List testScope = new ArrayList(); - static List suiteScope = new ArrayList(); - static boolean allTestScopeClosed; - static boolean allSuiteScopeOpen; - - @BeforeClass - public static void clean() { - testScope.clear(); - suiteScope.clear(); - - suiteScope.add(closeAfterSuite(new DummyCloseable())); - } - - @AfterClass - public static void afterClass() { - allTestScopeClosed = true; - for (DummyCloseable c : Nested.testScope) { - if (!c.closed) allTestScopeClosed = false; - } - - allSuiteScopeOpen = true; - for (DummyCloseable c : Nested.suiteScope) { - if (c.closed) allSuiteScopeOpen = false; - } - } - - @Test - public void testScopeResource() { - assumeRunningNested(); - testScope.add(closeAfterTest(new DummyCloseable())); - testScope.add(closeAfterTest(new DummyCloseable())); - } - - @Test - public void testScopeResourceWithFailures() { - assumeRunningNested(); - testScope.add(closeAfterTest(new DummyCloseable())); - testScope.add(closeAfterTest(new DummyCloseable())); - throw new RuntimeException(); - } - - @Test - public void suiteScopeFromTest() { - assumeRunningNested(); - suiteScope.add(closeAfterSuite(new DummyCloseable())); - suiteScope.add(closeAfterSuite(new DummyCloseable())); - } - } - - @Test - public void testResourceDisposalTestScope() { - checkTestsOutput(3, 0, 1, 0, Nested.class); - for (DummyCloseable c : Nested.testScope) { - Assert.assertTrue(c.closed); - } - Assert.assertTrue(Nested.allTestScopeClosed); - } - - @Test - public void testResourceDisposalSuiteScope() { - runTests(Nested.class); - for (DummyCloseable c : Nested.suiteScope) { - Assert.assertTrue(c.closed); - } - Assert.assertTrue(Nested.allSuiteScopeOpen); - } - - public static class Nested2 extends RandomizedTest { - @Test - public void testScope() { - assumeRunningNested(); - closeAfterTest(closeAfterTest(new DummyCloseable())); - } - } - - @Test - public void testFailedDisposalBreaksTestCase() { - FullResult r = checkTestsOutput(1, 0, 1, 0, Nested2.class); - Assert.assertTrue(r.getFailures().get(0).getException() instanceof ResourceDisposalError); - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestRules.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestRules.java deleted file mode 100644 index fe52bbb9..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestRules.java +++ /dev/null @@ -1,133 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import java.util.ArrayList; -import java.util.List; - -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.MethodRule; -import org.junit.rules.RuleChain; -import org.junit.rules.TestRule; -import org.junit.runner.Description; -import org.junit.runner.JUnitCore; -import org.junit.runner.Request; -import org.junit.runners.model.FrameworkMethod; -import org.junit.runners.model.Statement; - -/** - * {@link Rule} and {@link MethodRule} support. - */ -@SuppressWarnings({"deprecation"}) -public class TestRules extends WithNestedTestClass { - static List order; - - public static class MethodRuleSupport { - @Rule - public MethodRule rule1 = new MethodRule() { - public Statement apply(final Statement base, FrameworkMethod method, Object target) { - return new Statement() { - @Override - public void evaluate() throws Throwable { - assumeRunningNested(); - order.add("rule1-before"); - base.evaluate(); - order.add("rule1-after"); - } - }; - } - }; - - @Test - public void passing() { - order.add("passing"); - } - } - - public static class SimpleRule implements TestRule { - private String msg; - - public SimpleRule(String msg) { - this.msg = msg; - } - - @Override - public Statement apply(final Statement base, Description description) { - return new Statement() { - public void evaluate() throws Throwable { - assumeRunningNested(); - order.add(msg + "-before"); - try { - base.evaluate(); - } finally { - order.add(msg + "-after"); - } - } - }; - } - } - - public static class NewRuleSupportPassing { - @Rule - public TestRule rule1 = RuleChain - .outerRule(new SimpleRule("outer")) - .around(new SimpleRule("inner")); - - @Test - public void passing() { - order.add("passing"); - } - } - - public static class NewRuleSupportFailing { - @Rule - public TestRule rule1 = RuleChain - .outerRule(new SimpleRule("outer")) - .around(new SimpleRule("inner")); - - @Test - public void failing() { - order.add("failing"); - throw new RuntimeException(); - } - } - - public static class NewRuleSupportIgnored { - @Rule - public TestRule rule1 = RuleChain - .outerRule(new SimpleRule("outer")) - .around(new SimpleRule("inner")); - - @Test @Ignore - public void ignored() { - order.add("ignored"); - throw new RuntimeException(); - } - } - - @Test - public void checkOldMethodRules() throws Exception { - assertSameExecution(MethodRuleSupport.class); - } - - @Test - public void checkNewTestRules() throws Exception { - assertSameExecution(NewRuleSupportPassing.class); - assertSameExecution(NewRuleSupportFailing.class); - assertSameExecution(NewRuleSupportIgnored.class); - } - - private void assertSameExecution(Class clazz) throws Exception { - order = new ArrayList<>(); - runTests(clazz); - List order1 = order; - order = new ArrayList<>(); - - new JUnitCore().run(Request.runner(new RandomizedRunner(clazz))); - List order2 = order; - order = null; - - Assert.assertEquals(order1, order2); - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestSeedDecorator.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestSeedDecorator.java deleted file mode 100644 index 89872ae4..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestSeedDecorator.java +++ /dev/null @@ -1,73 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import java.util.*; - -import org.assertj.core.api.Assertions; -import org.junit.*; -import org.junit.runner.RunWith; - -import com.carrotsearch.randomizedtesting.annotations.SeedDecorators; -import com.carrotsearch.randomizedtesting.generators.RandomStrings; - -/** - * Test seed decorators. - */ -public class TestSeedDecorator extends WithNestedTestClass { - private static List runnerSeeds = new ArrayList(); - private static List strings = new ArrayList(); - - @RunWith(RandomizedRunner.class) - public static class Nested1 { - @BeforeClass - public static void generateSequence() { - strings.add(RandomStrings.randomAsciiLettersOfLength(RandomizedContext.current().getRandom(), 200)); - } - - @Test - public void method1() { - assumeRunningNested(); - runnerSeeds.add(RandomizedContext.current().getRunnerSeedAsString()); - } - } - - public static class Nested2 extends Nested1 { - } - - @SeedDecorators({ - MixWithSuiteName.class - }) - public static class Nested3 extends Nested1 { - } - - public static class Nested4 extends Nested3 { - } - - @Before @After - public void cleanup() { - runnerSeeds.clear(); - strings.clear(); - System.clearProperty(SysGlobals.SYSPROP_RANDOM_SEED()); - } - - @Test - public void testDecoratedMaster() { - String masterSeed = SeedUtils.formatSeed(new Random().nextLong()); - System.setProperty(SysGlobals.SYSPROP_RANDOM_SEED(), masterSeed); - - // These classes should get a different master seed (perturbed by decorator). - runTests(Nested1.class, Nested2.class, Nested3.class, Nested4.class); - - // All four classes get the same initial "runner" seed. - Assert.assertEquals(4, runnerSeeds.size()); - Assert.assertEquals(1, new HashSet(runnerSeeds).toArray().length); - - // @BeforeClass scope strings for Nested1 and Nested2 should be the same - // because these classes share identical master seed. - Assertions.assertThat(strings.get(1)).isEqualTo(strings.get(0)); - // but Nested3 and Nested4 have a seed decorator so strings there - // should be different. - Assertions.assertThat(strings.get(2)).isNotEqualTo(strings.get(0)); - Assertions.assertThat(strings.get(3)).isNotEqualTo(strings.get(0)); - Assertions.assertThat(strings.get(2)).isNotEqualTo(strings.get(3)); - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestSeedFixing.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestSeedFixing.java deleted file mode 100644 index f61402a7..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestSeedFixing.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import static org.junit.Assert.assertEquals; - -import org.assertj.core.api.Assertions; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; - -import com.carrotsearch.randomizedtesting.annotations.Seed; - -/** - * Seed fixing for static fixtures and/or methods using annotations. - */ -@RunWith(RandomizedRunner.class) -@Seed("deadbeef") -public class TestSeedFixing { - @BeforeClass - public static void beforeClass() { - assertEquals(0xdeadbeefL, RandomizedContext.current().getRandomness().getSeed()); - } - - @Seed("cafebabe") - @Test - public void dummy() { - Assertions - .assertThat(Long.toHexString(RandomizedContext.current().getRandomness().getSeed())) - .isEqualTo("cafebabe"); - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestSeedFixingWithProperties.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestSeedFixingWithProperties.java deleted file mode 100644 index 4d922b9e..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestSeedFixingWithProperties.java +++ /dev/null @@ -1,82 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import static com.carrotsearch.randomizedtesting.SysGlobals.SYSPROP_ITERATIONS; -import static com.carrotsearch.randomizedtesting.SysGlobals.SYSPROP_RANDOM_SEED; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.junit.After; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; - -/** - * Seed fixing for static fixtures and/or methods using system properties. - */ -public class TestSeedFixingWithProperties extends WithNestedTestClass { - static List seeds = new ArrayList(); - - @RunWith(RandomizedRunner.class) - public static class Nested { - @BeforeClass - public static void staticFixture() { - seeds.add(RandomizedContext.current().getRandomness().getSeed()); - } - - @Test - public void testMethod() { - seeds.add(RandomizedContext.current().getRandomness().getSeed()); - } - } - - /** - * Combined seed: fixing everything: the runner, method and any repetitions. - */ - @Test - public void testRunnerAndMethodProperty() { - System.setProperty(SYSPROP_RANDOM_SEED(), "deadbeef:cafebabe"); - System.setProperty(SYSPROP_ITERATIONS(), "3"); - runTests(Nested.class); - assertEquals(Arrays.asList(0xdeadbeefL, 0xcafebabeL, 0xcafebabeL, 0xcafebabeL), seeds); - } - - /** - * Runner seed fixing only (methods have predictable pseudo-random seeds derived from - * the runner). - */ - @Test - public void testFixedRunnerPropertyOnly() { - System.setProperty(SYSPROP_RANDOM_SEED(), "deadbeef"); - System.setProperty(SYSPROP_ITERATIONS(), "3"); - checkTestsOutput(3, 0, 0, 0, Nested.class); - assertEquals(0xdeadbeefL, seeds.get(0).longValue()); - // _very_ slim chances of this actually being true... - assertFalse( - seeds.get(0).longValue() == seeds.get(1).longValue() && - seeds.get(1).longValue() == seeds.get(2).longValue()); - - // We should have the same randomized seeds on methods for the same runner seed, - // so check if this is indeed true. - List copy = new ArrayList(seeds); - seeds.clear(); - runTests(Nested.class); - assertEquals(copy, seeds); - } - - @Before - public void cleanupBefore() { - cleanupAfter(); - } - - @After - public void cleanupAfter() { - System.clearProperty(SYSPROP_ITERATIONS()); - System.clearProperty(SYSPROP_RANDOM_SEED()); - seeds.clear(); - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestSeedParameterOptional.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestSeedParameterOptional.java deleted file mode 100644 index 0076c271..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestSeedParameterOptional.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import java.util.HashSet; - -import org.junit.Assert; - -import org.junit.Test; -import org.junit.runner.*; -import org.junit.runner.notification.RunListener; - -import com.carrotsearch.randomizedtesting.annotations.*; - - -/** - * Check if seed parameter is optional if no repetitions - * of the test are requested. - */ -public class TestSeedParameterOptional extends WithNestedTestClass { - public static class Nested extends RandomizedTest { - @Seeds({ - @Seed("deadbeef"), - @Seed("cafebabe"), - @Seed // Adds a randomized execution too. - }) - @Test - @Repeat(iterations = 2, useConstantSeed = true) - public void method1() { } - - @Seed("cafebabe") - @Test - public void method2() { } - - @Test - public void method3() { } - } - - @Test - public void checkNames() { - final HashSet tests = new HashSet(); - - JUnitCore junit = new JUnitCore(); - junit.addListener(new RunListener() { - @Override - public void testStarted(Description description) throws Exception { - tests.add(description.getMethodName()); - } - }); - - junit.run(Nested.class); - - // Single repetitions, no seed parameter in test name. - Assert.assertTrue(tests.contains("method2")); - Assert.assertTrue(tests.contains("method3")); - - // Method 1 has 2x3 repetitions. - int count = 0; - for (String s : tests) { - if (s.startsWith("method1")) { - count++; - } - } - Assert.assertEquals(6, count); - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestSeedRepeatable.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestSeedRepeatable.java deleted file mode 100644 index b2450856..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestSeedRepeatable.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import static org.junit.Assert.assertEquals; - -import java.util.HashMap; -import java.util.Map; - -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; - -import com.carrotsearch.randomizedtesting.annotations.Seed; - -public class TestSeedRepeatable extends WithNestedTestClass { - @Seed("deadbeef") - @RunWith(RandomizedRunner.class) - public static class Nested { - static Map seeds = new HashMap(); - - @BeforeClass - public static void nested() { - assumeRunningNested(); - } - - @Test - public void testMethod1() { - checkSeed("method1"); - } - - @Test - public void testMethod2() { - checkSeed("method2"); - } - - private void checkSeed(String key) { - final Object seed = RandomizedContext.current().getRandomness().getSeed(); - if (seeds.containsKey(key)) { - assertEquals(seeds.get(key), seed); - } else { - seeds.put(key, seed); - } - } - } - - /** - * Check if methods get the same seed on every run with a fixed runner's seed. - */ - @Test - public void testSameMethodRandomnessWithFixedRunner() { - Nested.seeds.clear(); - checkTestsOutput(2, 0, 0, 0, Nested.class); - checkTestsOutput(2, 0, 0, 0, Nested.class); - checkTestsOutput(2, 0, 0, 0, Nested.class); - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestSetSeedLocked.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestSetSeedLocked.java deleted file mode 100644 index 097c9f12..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestSetSeedLocked.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import org.junit.Test; - -import static org.junit.Assert.*; - -public class TestSetSeedLocked extends RandomizedTest { - @Test - public void testMethod() { - try { - getRandom().setSeed(0); - fail(); - } catch (RuntimeException e) { - // Ok, expected. - } - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestStackAugmentation.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestStackAugmentation.java deleted file mode 100644 index 09a2dfa8..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestStackAugmentation.java +++ /dev/null @@ -1,94 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runner.notification.Failure; - -import com.carrotsearch.randomizedtesting.annotations.Seed; - -/** - * {@link RandomizedRunner} can augment stack traces to include seed info. Check - * if it works. - */ -public class TestStackAugmentation extends WithNestedTestClass { - @RunWith(RandomizedRunner.class) - @Seed("deadbeef") - public static class Nested { - @Test @Seed("cafebabe") - public void testMethod1() { - assumeRunningNested(); - - // Throws a chained exception. - try { - throw new RuntimeException("Inner."); - } catch (Exception e) { - throw new Error("Outer.", e); - } - } - } - - @Test - public void testMethodLevel() { - FullResult result = checkTestsOutput(1, 0, 1, 0, Nested.class); - - Failure f = result.getFailures().get(0); - String seedFromThrowable = RandomizedRunner.seedFromThrowable(f.getException()); - assertNotNull(seedFromThrowable); - assertTrue("[DEADBEEF:CAFEBABE]".compareToIgnoreCase(seedFromThrowable) == 0); - } - - @RunWith(RandomizedRunner.class) - @Seed("deadbeef") - public static class Nested2 { - @BeforeClass - public static void beforeClass() { - assumeRunningNested(); - throw new Error("beforeclass."); - } - - @Test @Seed("cafebabe") - public void testMethod1() { - } - } - - @Test - public void testBeforeClass() { - FullResult result = checkTestsOutput(0, 0, 1, 0, Nested2.class); - assertEquals(1, result.getFailureCount()); - - Failure f = result.getFailures().get(0); - String seedFromThrowable = RandomizedRunner.seedFromThrowable(f.getException()); - assertNotNull(seedFromThrowable); - assertTrue(f.getTrace(), "[DEADBEEF]".compareToIgnoreCase(seedFromThrowable) == 0); - } - - @RunWith(RandomizedRunner.class) - @Seed("deadbeef") - public static class Nested3 { - @AfterClass - public static void afterClass() { - assumeRunningNested(); - throw new Error("afterclass."); - } - - @Test @Seed("cafebabe") - public void testMethod1() { - } - } - - @Test - public void testAfterClass() { - FullResult result = checkTestsOutput(1, 0, 1, 0, Nested3.class); - - Failure f = result.getFailures().get(0); - String seedFromThrowable = RandomizedRunner.seedFromThrowable(f.getException()); - assertNotNull(seedFromThrowable); - assertTrue(f.getTrace(), "[DEADBEEF]".compareToIgnoreCase(seedFromThrowable) == 0); - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestTargetMethod.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestTargetMethod.java deleted file mode 100644 index 56709f0d..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestTargetMethod.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import org.assertj.core.api.Assertions; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; - -import com.carrotsearch.randomizedtesting.annotations.Repeat; - -public class TestTargetMethod extends WithNestedTestClass { - public static class Nested extends RandomizedTest { - @Before - public void checkInHook() { - assumeRunningNested(); - } - - @Test - @Repeat(iterations = 3) - public void testOne() { - Assertions.assertThat(RandomizedContext.current().getTargetMethod().getName()) - .isEqualTo("testOne"); - } - - @Test - public void testTwo() { - Assertions.assertThat(RandomizedContext.current().getTargetMethod().getName()) - .isEqualTo("testTwo"); - } - - @AfterClass - @BeforeClass - public static void staticHooks() { - Assertions.assertThat(RandomizedContext.current().getTargetMethod()) - .isNull(); - } - } - - @Test - public void testTargetMethodAvailable() { - checkTestsOutput(4, 0, 0, 0, Nested.class); - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestTestCaseInstanceProviders.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestTestCaseInstanceProviders.java deleted file mode 100644 index 1fe1459e..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestTestCaseInstanceProviders.java +++ /dev/null @@ -1,73 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import java.util.Arrays; -import java.util.IdentityHashMap; - -import org.assertj.core.api.Assertions; -import org.junit.Before; -import org.junit.Test; - -import com.carrotsearch.randomizedtesting.annotations.ParametersFactory; -import com.carrotsearch.randomizedtesting.annotations.Repeat; -import com.carrotsearch.randomizedtesting.annotations.Seed; -import com.carrotsearch.randomizedtesting.annotations.Seeds; -import com.carrotsearch.randomizedtesting.annotations.TestCaseInstanceProvider; -import com.carrotsearch.randomizedtesting.annotations.TestCaseInstanceProvider.Type; - -public class TestTestCaseInstanceProviders extends WithNestedTestClass { - private static IdentityHashMap set = new IdentityHashMap<>(); - - @TestCaseInstanceProvider(Type.INSTANCE_PER_CONSTRUCTOR_ARGS) - public static class Nested extends RandomizedTest { - @Before - public void setup() { - assumeRunningNested(); - set.put(this, null); - } - - @Test - @Repeat(iterations = 3) - public void testOne() { - set.put(this, null); - } - - @Test - public void testTwo() { - set.put(this, null); - } - - @Seeds({@Seed("deadbeef"), @Seed("cafebabe")}) - @Test - @Repeat(iterations = 2, useConstantSeed = true) - public void testThree() { - set.put(this, null); - } - } - - @Before - public void setup() { - set.clear(); - } - - @Test - public void testDefaultConstructor() { - checkTestsOutput(3 + 1 + 2 * 2, 0, 0, 0, Nested.class); - Assertions.assertThat(set).hasSize(1); - } - - public static class Nested2 extends Nested { - public Nested2(String arg) { - } - - @ParametersFactory - public static Iterable params() { - return Arrays.asList($("1"), $("2"), $("3")); - } - } - - @Test - public void testParameterProviders() { - checkTestsOutput(3 * (3 + 1 + 2 * 2), 0, 0, 0, Nested2.class); - Assertions.assertThat(set).hasSize(3); - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestTestCaseOrdering.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestTestCaseOrdering.java deleted file mode 100644 index a1318168..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestTestCaseOrdering.java +++ /dev/null @@ -1,103 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Comparator; -import java.util.List; - -import org.junit.Before; -import org.junit.Test; -import com.carrotsearch.randomizedtesting.annotations.ParametersFactory; -import com.carrotsearch.randomizedtesting.annotations.Repeat; -import com.carrotsearch.randomizedtesting.annotations.TestCaseOrdering; - -public class TestTestCaseOrdering extends WithNestedTestClass { - static List buf; - - @TestCaseOrdering(TestCaseOrdering.AlphabeticOrder.class) - public static class Alphabetical extends RandomizedTest { - @Before public void assumeNested() { assumeRunningNested(); } - @Test public void a() { buf.add("a"); } - @Test public void b() { buf.add("b"); } - @Test public void c() { buf.add("c"); } - @Test public void d() { buf.add("d"); } - } - - @TestCaseOrdering(TestCaseOrdering.AlphabeticOrder.class) - @Repeat(iterations = 3) - public static class AlphabeticalWithRepetitions extends RandomizedTest { - @Before public void assumeNested() { assumeRunningNested(); } - @Test public void a() { buf.add("a"); } - @Test public void b() { buf.add("b"); } - @Test public void c() { buf.add("c"); } - @Test public void d() { buf.add("d"); } - } - - public static class CustomOrder implements Comparator { - @Override - public int compare(TestMethodAndParams o1, TestMethodAndParams o2) { - int v = o1.getTestMethod().getName().compareTo( - o2.getTestMethod().getName()); - if (v == 0) { - v = ((String) o1.getInstanceArguments().get(0)).compareTo( - ((String) o2.getInstanceArguments().get(0))); - } - - return v; - } - } - - @TestCaseOrdering(CustomOrder.class) - public static class AlphabeticalWithParameters extends RandomizedTest { - String param; - - public AlphabeticalWithParameters(String param) { - this.param = param; - } - - @Before public void assumeNested() { assumeRunningNested(); } - @Test public void a() { buf.add("a:" + param); } - @Test public void b() { buf.add("b:" + param); } - @Test public void c() { buf.add("c:" + param); } - @Test public void d() { buf.add("d:" + param); } - - @ParametersFactory - public static Iterable params() { - return Arrays.asList($("1"), $("2"), $("3")); - } - } - - @Before - public void clean() { - buf = new ArrayList<>(); - } - - @Test - public void testAlphabetical() { - runTests(Alphabetical.class); - assertThat(buf).containsExactly("a", "b", "c", "d"); - } - - @Test - public void testAlphabeticalWithRepetitions() { - runTests(AlphabeticalWithRepetitions.class); - assertThat(buf).containsExactly( - "a", "a", "a", - "b", "b", "b", - "c", "c", "c", - "d", "d", "d"); - } - - @Test - public void testAlphabeticalWithParameters() { - runTests(AlphabeticalWithParameters.class); - assertThat(buf).containsExactly( - "a:1", "a:2", "a:3", - "b:1", "b:2", "b:3", - "c:1", "c:2", "c:3", - "d:1", "d:2", "d:3"); - } -} - diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestTestFiltering.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestTestFiltering.java deleted file mode 100644 index 946462c3..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestTestFiltering.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import static com.carrotsearch.randomizedtesting.annotations.TestGroup.Utilities.getSysProperty; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Inherited; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; -import java.util.concurrent.atomic.AtomicInteger; - -import org.assertj.core.api.Assertions; -import org.junit.Rule; -import org.junit.Test; - -import com.carrotsearch.randomizedtesting.annotations.TestGroup; -import com.carrotsearch.randomizedtesting.rules.SystemPropertiesRestoreRule; - -/** - * Custom test groups. - */ -public class TestTestFiltering extends WithNestedTestClass { - @Rule - public SystemPropertiesRestoreRule restoreProperties = new SystemPropertiesRestoreRule(); - - @Retention(RetentionPolicy.RUNTIME) - @Target({ElementType.METHOD, ElementType.TYPE}) - @Inherited - @TestGroup(enabled = false) - public static @interface Foo { - } - - static AtomicInteger counter = new AtomicInteger(); - - public static class Nested1 extends RandomizedTest { - @Test @Foo - public void test1() { - counter.incrementAndGet(); - } - } - - @Test - public void filterVsRulePriority() { - System.setProperty(getSysProperty(Foo.class), "false"); - - // Don't run by default (group is disabled by default). - counter.set(0); - System.setProperty(SysGlobals.SYSPROP_TESTFILTER(), ""); - checkTestsOutput(1, 0, 0, 1, Nested1.class); - Assertions.assertThat(counter.get()).isEqualTo(0); - - // Run @foo methods even though the group is disabled (but the filtering rule takes priority). - counter.set(0); - System.setProperty(SysGlobals.SYSPROP_TESTFILTER(), "@foo"); - checkTestsOutput(1, 0, 0, 0, Nested1.class); - Assertions.assertThat(counter.get()).isEqualTo(1); - - // Run the "default" filter. - counter.set(0); - System.setProperty(SysGlobals.SYSPROP_TESTFILTER(), "default"); - checkTestsOutput(0, 0, 0, 0, Nested1.class); - Assertions.assertThat(counter.get()).isEqualTo(0); - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestTestGroups.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestTestGroups.java deleted file mode 100644 index 0b9d5c40..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestTestGroups.java +++ /dev/null @@ -1,187 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import static com.carrotsearch.randomizedtesting.annotations.TestGroup.Utilities.*; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Inherited; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; - -import com.carrotsearch.randomizedtesting.annotations.Nightly; -import com.carrotsearch.randomizedtesting.annotations.TestGroup; - -/** - * Custom test groups. - */ -public class TestTestGroups extends WithNestedTestClass { - @Retention(RetentionPolicy.RUNTIME) - @Target({ElementType.METHOD, ElementType.TYPE}) - @Inherited - @TestGroup(enabled = true) - public static @interface Group1 { - } - - @Retention(RetentionPolicy.RUNTIME) - @Target({ElementType.METHOD, ElementType.TYPE}) - @Inherited - @TestGroup(enabled = false, name = "abc", sysProperty = "custom.abc") - public static @interface Group2 { - } - - public static class Nested1 extends RandomizedTest { - @Test @Group1 @Group2 - public void test1() { - } - - @BeforeClass - public static void beforeClass() { - beforeClassRan = true; - } - - @AfterClass - public static void afterClass() { - afterClassRan = true; - } - } - - public static class Nested3 extends Nested1 { - @Test - public void testUnconditional() { - } - } - - @Group1 @Group2 - public static class Nested2 extends RandomizedTest { - @Test - public void test1() { - } - - @BeforeClass - public static void beforeClass() { - beforeClassRan = true; - } - - @AfterClass - public static void afterClass() { - afterClassRan = true; - } - } - - public static boolean beforeClassRan; - public static boolean afterClassRan; - - @Test - public void checkDefaultNames() { - Assert.assertEquals("group1", getGroupName(Group1.class)); - Assert.assertEquals("abc", getGroupName(Group2.class)); - Assert.assertEquals(SysGlobals.CURRENT_PREFIX() + ".group1", getSysProperty(Group1.class)); - Assert.assertEquals("custom.abc", getSysProperty(Group2.class)); - Assert.assertEquals(SysGlobals.CURRENT_PREFIX() + ".nightly", getSysProperty(Nightly.class)); - Assert.assertEquals("nightly", getGroupName(Nightly.class)); - } - - @Test - public void groupsOnMethods() { - String group1Property = getSysProperty(Group1.class); - String group2Property = getSysProperty(Group2.class); - try { - afterClassRan = beforeClassRan = false; - checkTestsOutput(1, 0, 0, 1, Nested1.class); - Assert.assertFalse(afterClassRan); - Assert.assertFalse(beforeClassRan); - - afterClassRan = beforeClassRan = false; - System.setProperty(group1Property, "true"); - checkTestsOutput(1, 0, 0, 1, Nested1.class); - Assert.assertFalse(afterClassRan); - Assert.assertFalse(beforeClassRan); - - afterClassRan = beforeClassRan = false; - System.setProperty(group2Property, "true"); - checkTestsOutput(1, 0, 0, 0, Nested1.class); - Assert.assertTrue(afterClassRan); - Assert.assertTrue(beforeClassRan); - - afterClassRan = beforeClassRan = false; - System.setProperty(group1Property, "false"); - checkTestsOutput(1, 0, 0, 1, Nested1.class); - Assert.assertFalse(afterClassRan); - Assert.assertFalse(beforeClassRan); - } finally { - System.clearProperty(group1Property); - System.clearProperty(group2Property); - } - } - - @Test - public void groupsOnASubsetOfMethods() { - String group1Property = getSysProperty(Group1.class); - String group2Property = getSysProperty(Group2.class); - try { - afterClassRan = beforeClassRan = false; - checkTestsOutput(2, 0, 0, 1, Nested3.class); - Assert.assertTrue(afterClassRan); - Assert.assertTrue(beforeClassRan); - - afterClassRan = beforeClassRan = false; - System.setProperty(group1Property, "true"); - checkTestsOutput(2, 0, 0, 1, Nested3.class); - Assert.assertTrue(afterClassRan); - Assert.assertTrue(beforeClassRan); - - afterClassRan = beforeClassRan = false; - System.setProperty(group2Property, "true"); - checkTestsOutput(2, 0, 0, 0, Nested3.class); - Assert.assertTrue(afterClassRan); - Assert.assertTrue(beforeClassRan); - - afterClassRan = beforeClassRan = false; - System.setProperty(group1Property, "false"); - checkTestsOutput(2, 0, 0, 1, Nested3.class); - Assert.assertTrue(afterClassRan); - Assert.assertTrue(beforeClassRan); - } finally { - System.clearProperty(group1Property); - System.clearProperty(group2Property); - } - } - - @Test - public void groupsOnClass() { - String group1Property = getSysProperty(Group1.class); - String group2Property = getSysProperty(Group2.class); - try { - afterClassRan = beforeClassRan = false; - checkTestsOutput(1, 0, 0, 1, Nested2.class); - Assert.assertFalse(afterClassRan); - Assert.assertFalse(beforeClassRan); - - afterClassRan = beforeClassRan = false; - System.setProperty(group1Property, "true"); - checkTestsOutput(1, 0, 0, 1, Nested2.class); - Assert.assertFalse(afterClassRan); - Assert.assertFalse(beforeClassRan); - - afterClassRan = beforeClassRan = false; - System.setProperty(group2Property, "true"); - checkTestsOutput(1, 0, 0, 0, Nested2.class); - Assert.assertTrue(afterClassRan); - Assert.assertTrue(beforeClassRan); - - afterClassRan = beforeClassRan = false; - System.setProperty(group1Property, "false"); - checkTestsOutput(1, 0, 0, 1, Nested2.class); - Assert.assertFalse(afterClassRan); - Assert.assertFalse(beforeClassRan); - } finally { - System.clearProperty(group1Property); - System.clearProperty(group2Property); - } - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestTestGroupsOnOverrides.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestTestGroupsOnOverrides.java deleted file mode 100644 index 636330d9..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestTestGroupsOnOverrides.java +++ /dev/null @@ -1,80 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import com.carrotsearch.randomizedtesting.annotations.TestGroup; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; - -import java.lang.annotation.*; -import java.util.ArrayList; -import java.util.List; - -import static org.assertj.core.api.Assertions.assertThat; - -public class TestTestGroupsOnOverrides extends WithNestedTestClass { - static List buf; - - public static class Super extends RandomizedTest { - @Before - public void assumeNested() { - assumeRunningNested(); - } - - @Test - public void method() { - buf.add("super:method"); - } - } - - @Before - public void clean() { - buf = new ArrayList<>(); - } - - public static class Ignored extends Super { - @Ignore - public void method() { - buf.add("sub:method"); - } - } - - @Test - public void testIgnored() { - runTests(Ignored.class); - assertThat(buf).isEmpty(); - } - - @Documented - @Retention(RetentionPolicy.RUNTIME) - @Target({ElementType.METHOD, ElementType.TYPE}) - @Inherited - @TestGroup(enabled = false) - public @interface Disabled { - } - - public static class DisabledGroup extends Super { - @Disabled - public void method() { - buf.add("sub:method"); - } - } - - @Test - public void testDisabledGroup() { - runTests(DisabledGroup.class); - assertThat(buf).isEmpty(); - } - - public static class Normal extends Super { - public void method() { - buf.add("sub:method"); - } - } - - @Test - public void testNormal() { - runTests(Normal.class); - assertThat(buf).containsExactly("sub:method"); - } -} - diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestThreadNameContainsTestName.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestThreadNameContainsTestName.java deleted file mode 100644 index 209c35bd..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestThreadNameContainsTestName.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import org.junit.Test; - -import com.carrotsearch.randomizedtesting.annotations.Timeout; - -import static org.junit.Assert.*; - -/** - * Test {@link Test#expected()}. - */ -public class TestThreadNameContainsTestName extends RandomizedTest { - @Test - public void testMarkerABC() { - String tName = Thread.currentThread().getName(); - assertTrue(tName, tName.contains("testMarkerABC")); - } - - @Test - @Timeout(millis = 0) - public void testMarkerXYZ() { - String tName = Thread.currentThread().getName(); - assertTrue(tName, tName.contains("testMarkerXYZ")); - } - - @Test - @Timeout(millis = 1000) - public void testMarkerKJI() { - String tName = Thread.currentThread().getName(); - assertTrue(tName, tName.contains("testMarkerKJI")); - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestUncaughtExceptionsDuplicated.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestUncaughtExceptionsDuplicated.java deleted file mode 100644 index a6a486ff..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestUncaughtExceptionsDuplicated.java +++ /dev/null @@ -1,119 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.notification.Failure; -import org.junit.Assert; - -public class TestUncaughtExceptionsDuplicated extends WithNestedTestClass { - public static class Nested1 extends RandomizedTest { - @BeforeClass - public static void beforeClass() throws Exception { - assumeRunningNested(); - Thread t = new Thread() { - public void run() { - throw new RuntimeException("foobar"); - } - }; - t.start(); - t.join(); - } - - @Test - public void test() {} - } - - public static class Nested2 extends RandomizedTest { - @BeforeClass - public static void beforeClass() { - assumeRunningNested(); - } - - @Test - public void test1() throws Exception { - Thread t = new Thread() { - public void run() { - throw new RuntimeException("foobar1"); - } - }; - t.start(); - t.join(); - } - - @Test - public void test2() throws Exception { - Thread t = new Thread() { - public void run() { - throw new RuntimeException("foobar2"); - } - }; - t.start(); - t.join(); - } - - @Test - public void test3() throws Exception { - Thread t = new Thread() { - public void run() { - throw new RuntimeException("foobar3"); - } - }; - t.start(); - t.join(); - } - } - - public static class Nested3 extends RandomizedTest { - @Before - public void runBeforeTest() throws Exception { - assumeRunningNested(); - Thread t = new Thread() { - public void run() { - throw new RuntimeException("foobar"); - } - }; - t.start(); - t.join(); - } - - @Test - public void test1() throws Exception { - } - } - - @Test - public void testExceptionInBeforeClassFailsTheTest() { - FullResult r = checkTestsOutput(1, 0, 1, 0, Nested1.class); - Assert.assertTrue(r.getFailures().get(0).getTrace().contains("foobar")); - } - - @Test - public void testExceptionWithinTestFailsTheTest() { - FullResult r = checkTestsOutput(3, 0, 3, 0, Nested2.class); - - ArrayList foobars = new ArrayList(); - for (Failure f : r.getFailures()) { - Matcher m = Pattern.compile("foobar[0-9]+").matcher(f.getTrace()); - while (m.find()) { - foobars.add(m.group()); - } - } - - Collections.sort(foobars); - Assert.assertEquals("[foobar1, foobar2, foobar3]", - Arrays.toString(foobars.toArray())); - } - - @Test - public void testExceptionWithinBeforeFailsTheTest() { - FullResult r = checkTestsOutput(1, 0, 1, 0, Nested3.class); - Assert.assertTrue(r.getFailures().get(0).getTrace().contains("foobar")); - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestValidation.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestValidation.java deleted file mode 100644 index f97bcb45..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/TestValidation.java +++ /dev/null @@ -1,83 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import java.util.Arrays; - -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; - -public class TestValidation extends WithNestedTestClass { - public class SuiteClassNotStatic { - } - - static class SuiteClassNotPublic { - } - - public static class BeforeClassNotStatic { - @BeforeClass - public void beforeClass() { - } - } - - public static class BeforeClassWithArgs { - @BeforeClass - public static void beforeClass(int a) { - } - } - - public static class AfterClassNotStatic { - @AfterClass - public void afterClass() { - } - } - - public static class AfterClassWithArgs { - @AfterClass - public static void afterClass(int a) { - } - } - - public static class BeforeStatic { - @Before - public static void before() { - } - } - - public static class BeforeWithArgs { - @Before - public void before(int a) { - } - } - - public static class AfterStatic { - @After - public static void after() { - } - } - - public static class AfterWithArgs { - @After - public void after(int a) { - } - } - - @Test - public void checkBeforeClass() throws Exception { - for (Class c : Arrays.asList( - SuiteClassNotPublic.class, SuiteClassNotStatic.class, - BeforeClassNotStatic.class, BeforeClassWithArgs.class, - AfterClassNotStatic.class, AfterClassWithArgs.class, - BeforeStatic.class, BeforeWithArgs.class, - AfterStatic.class, AfterWithArgs.class)) { - try { - new RandomizedRunner(c); - Assert.fail("Expected validation failure on: " + c.getName()); - } catch (Exception e) { - // Ok, expected. - } - } - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/Utils.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/Utils.java deleted file mode 100644 index 0e96f4cb..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/Utils.java +++ /dev/null @@ -1,102 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import java.util.Set; -import java.util.logging.Logger; - -import org.assertj.core.api.Assertions; -import org.junit.Assert; -import org.junit.runner.Result; -import org.junit.runner.notification.Failure; - -import com.carrotsearch.randomizedtesting.WithNestedTestClass.FullResult; - -public class Utils { - /** - * Assert a result has at least one failure with message. - */ - public static void assertFailureWithMessage(FullResult r, String message) { - for (Failure f : r.getFailures()) { - if (f.getTrace().contains(message)) { - return; - } - } - - StringBuilder b = new StringBuilder("No failure with message: '" + message + "' (" + - r.getFailures().size() + " failures):"); - for (Failure f : r.getFailures()) { - b.append("\n\t- ").append(f.getTrace()); - } - Logger.getLogger("").severe(b.toString()); - Assert.fail(b.toString()); - } - - public static void assertNoFailureWithMessage(Result r, String message) { - boolean hadMessage = false; - for (Failure f : r.getFailures()) { - if (f.getTrace().contains(message)) { - hadMessage = true; - } - } - - if (!hadMessage) return; - - StringBuilder b = new StringBuilder("Failure with message: '" + message + "' (" + - r.getFailures().size() + " failures):"); - for (Failure f : r.getFailures()) { - b.append("\n\t- ").append(f.getTrace()); - } - Logger.getLogger("").severe(b.toString()); - Assert.fail(b.toString()); - } - - /** - * Check that all thrown failures have been augmented and contain - * a synthetic seed frame. - */ - public static void assertFailuresContainSeeds(FullResult r) { - for (Failure f : r.getFailures()) { - String seed = RandomizedRunner.seedFromThrowable(f.getException()); - Assert.assertTrue("Not augmented: " + f.getTrace(), seed != null); - } - } - - /** - * Package scope test access to {@link RandomizedContext#getRunnerSeed()}. - */ - public static long getRunnerSeed() { - return RandomizedContext.current().getRunnerSeed(); - } - - /** - * Package scope test access to {@link Randomness#getSeed()}. - */ - public static long getSeed(Randomness randomness) { - return randomness.getSeed(); - } - - /** - * Assert no threads with the given substring are present. - */ - public static void assertNoLiveThreadsContaining(String substring) { - for (Thread t : getAllThreads()) { - if (t.isAlive()) { - Assertions.assertThat(t.getName()) - .as("Unexpected live thread").doesNotContain(substring); - } - } - } - - /** - * Expose to non-package scope. - */ - public static Set getAllThreads() { - return Threads.getAllThreads(); - } - - /** - * Expose to non-package scope. - */ - public static ThreadGroup getTopThreadGroup() { - return Threads.getTopThreadGroup(); - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/WithNestedTestClass.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/WithNestedTestClass.java deleted file mode 100644 index 86ace102..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/WithNestedTestClass.java +++ /dev/null @@ -1,361 +0,0 @@ -package com.carrotsearch.randomizedtesting; - -import java.io.IOException; -import java.io.PrintStream; -import java.io.StringWriter; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.logging.Handler; -import java.util.logging.LogRecord; -import java.util.logging.Logger; -import java.util.logging.SimpleFormatter; - -import org.assertj.core.api.Assertions; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Assume; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.ClassRule; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.RuleChain; -import org.junit.rules.TestRule; -import org.junit.runner.Description; -import org.junit.runner.JUnitCore; -import org.junit.runner.Result; -import org.junit.runner.notification.Failure; -import org.junit.runner.notification.RunListener; -import org.junit.runners.model.Statement; - -import com.carrotsearch.randomizedtesting.rules.StatementAdapter; -import com.carrotsearch.randomizedtesting.rules.SystemPropertiesInvariantRule; -import com.carrotsearch.randomizedtesting.rules.TestRuleAdapter; - -/** - * Utility class to surround nested {@link RandomizedRunner} test suites. - */ -public class WithNestedTestClass { - private static boolean runningNested; - - public enum Place { - CLASS_RULE, - BEFORE_CLASS, - CONSTRUCTOR, - TEST_RULE, - BEFORE, - TEST, - AFTER, - AFTER_CLASS, - } - - public static class ApplyAtPlace extends RandomizedTest { - public static Place place; - public static Runnable runnable; - - @ClassRule - public static TestRule classRule = new TestRuleAdapter() { - protected void before() throws Throwable { - ApplyAtPlace.apply(Place.CLASS_RULE); - } - }; - - @BeforeClass - public static void beforeClass() { apply(Place.BEFORE_CLASS); } - - public ApplyAtPlace() { apply(Place.CONSTRUCTOR); } - - @Rule - public TestRule testRule = new TestRuleAdapter() { - protected void before() throws Throwable { - ApplyAtPlace.apply(Place.TEST_RULE); - } - }; - - @Before - public void before() { apply(Place.BEFORE); } - - @Test - public void testMethod() { apply(Place.TEST); } - - @After - public void after() { apply(Place.AFTER); } - - @AfterClass - public static void afterClass() { apply(Place.AFTER_CLASS); } - - private static void apply(Place p) { - if (place == p) { - assumeRunningNested(); - runnable.run(); - } - } - } - - static { - TestRule dumpLoggerOutputOnFailure = new TestRule() { - @Override - public Statement apply(Statement base, final Description description) { - return new StatementAdapter(base) { - protected void afterAlways(java.util.List errors) throws Throwable { - if (!errors.isEmpty()) { - sysout.println("-- " + description); - sysout.println(loggingMessages); - } - } - }; - } - }; - - SystemPropertiesInvariantRule noLeftOverProperties = - new SystemPropertiesInvariantRule(new HashSet(Arrays.asList( - "user.timezone"))); - - ruleChain = RuleChain - .outerRule(noLeftOverProperties) - .around(dumpLoggerOutputOnFailure); - } - - @ClassRule - public final static TestRule ruleChain; - - /** For capturing sysout. */ - protected static PrintStream sysout; - - /** For capturing syserr. */ - protected static PrintStream syserr; - - /** - * Captured sysout/ syserr. - */ - private static StringWriter sw; - - /** - * Captured java logging messages. - */ - private static StringWriter loggingMessages; - - /** - * Master logger. - */ - private static Logger logger; - - /** - * Previous handlers attached to the master. - */ - private static Handler[] handlers; - - /** - * Zombie threads. - */ - private static List zombies = new ArrayList<>(); - - private static volatile Object zombieToken; - - @BeforeClass - public static final void setupNested() throws IOException { - runningNested = true; - zombieToken = new Object(); - - // capture sysout/ syserr. - sw = new StringWriter(); - sysout = System.out; - syserr = System.err; - System.setOut(new PrintStream(new TeeOutputStream(System.out, new WriterOutputStream(sw)))); - System.setErr(new PrintStream(new TeeOutputStream(System.err, new WriterOutputStream(sw)))); - - // Add custom logging handler because java logging keeps a reference to previous System.err. - loggingMessages = new StringWriter(); - logger = Logger.getLogger(""); - handlers = logger.getHandlers(); - for (Handler h : handlers) logger.removeHandler(h); - logger.addHandler(new Handler() { - final SimpleFormatter formatter = new SimpleFormatter(); - - @Override - public void publish(LogRecord record) { - loggingMessages.write(formatter.format(record) + "\n"); - } - - @Override - public void flush() {} - - @Override - public void close() throws SecurityException {} - }); - } - - @AfterClass - public static final void clearNested() throws Exception { - zombieToken = null; - runningNested = false; - ApplyAtPlace.runnable = null; - ApplyAtPlace.place = null; - - System.setOut(sysout); - System.setErr(syserr); - - for (Handler h : logger.getHandlers()) logger.removeHandler(h); - for (Handler h : handlers) logger.addHandler(h); - - for (Thread t : zombies) { - t.interrupt(); - } - for (Thread t : zombies) { - t.join(); - } - } - - @After - public void after() { - // Reset zombie thread marker. - RandomizedRunner.zombieMarker.set(false); - } - - @Before - public void before() { - sw.getBuffer().setLength(0); - loggingMessages.getBuffer().setLength(0); - } - - protected static String getSysouts() { - System.out.flush(); - System.err.flush(); - return sw.toString(); - } - - public static String getLoggingMessages() { - return loggingMessages.toString(); - } - - protected static boolean isRunningNested() { - return runningNested; - } - - protected static void assumeRunningNested() { - Assume.assumeTrue(runningNested); - } - - protected static Thread startZombieThread(String name) { - final CountDownLatch latch = new CountDownLatch(1); - Thread t = new Thread(name) { - private final Object token = zombieToken; - - public void run() { - latch.countDown(); - while (zombieToken == token) { - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - // ignore. - } - } - } - }; - t.start(); - zombies.add(t); - try { - latch.await(); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } - return t; - } - - protected static Thread startThread(String name) { - final CountDownLatch latch = new CountDownLatch(1); - Thread t = new Thread(name) { - public void run() { - latch.countDown(); - sleepForever(); - } - - private void sleepForever() { - while (true) RandomizedTest.sleep(1000); - } - }; - t.start(); - try { - latch.await(); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } - return t; - } - - public static class FullResult { - private AtomicInteger assumptionIgnored = new AtomicInteger(); - private Result result; - - public int getRunCount() { - return result.getRunCount(); - } - - public int getIgnoreCount() { - return result.getIgnoreCount(); - } - - public int getFailureCount() { - return result.getFailureCount(); - } - - public int getAssumptionIgnored() { - return assumptionIgnored.get(); - } - - public List getFailures() { - return result.getFailures(); - } - - public boolean wasSuccessful() { - return result.wasSuccessful(); - } - } - - public static FullResult runTests(final Class... classes) { - try { - final FullResult fullResult = new FullResult(); - - // Run on a separate thread so that it appears as we're not running in an IDE. - Thread thread = new Thread() { - @Override - public void run() { - final JUnitCore core = new JUnitCore(); - core.addListener(new PrintEventListener(sysout)); - core.addListener(new RunListener() { - @Override - public void testAssumptionFailure(Failure failure) { - fullResult.assumptionIgnored.incrementAndGet(); - } - }); - - fullResult.result = core.run(classes); - } - }; - - thread.start(); - thread.join(); - return fullResult; - } catch (InterruptedException e) { - throw new RuntimeException(e); - } - } - - public static FullResult checkTestsOutput(int run, int ignored, int failures, int assumptions, Class classes) { - FullResult result = runTests(classes); - if (result.getRunCount() != run || - result.getIgnoreCount() != ignored || - result.getFailureCount() != failures || - result.getAssumptionIgnored() != assumptions) { - Assertions.fail("Different result. [run,ign,fail,ass] Expected: " - + run + "," + ignored + "," + failures + "," + assumptions + - ", Actual: " + result.getRunCount() + "," + result.getIgnoreCount() + "," + result.getFailureCount() - + "," + result.getAssumptionIgnored()); - } - return result; - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/contracts/TestAnnotationInheritance.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/contracts/TestAnnotationInheritance.java deleted file mode 100644 index 60f4983b..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/contracts/TestAnnotationInheritance.java +++ /dev/null @@ -1,113 +0,0 @@ -package com.carrotsearch.randomizedtesting.contracts; - -import java.util.ArrayList; -import java.util.List; - -import org.assertj.core.api.Assertions; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TestRule; -import org.junit.runner.Description; -import org.junit.runner.JUnitCore; -import org.junit.runner.Request; -import org.junit.runners.model.Statement; - -import com.carrotsearch.randomizedtesting.RandomizedRunner; -import com.carrotsearch.randomizedtesting.WithNestedTestClass; - -/** - * Verify if annotations are inherited. - */ -public class TestAnnotationInheritance extends WithNestedTestClass { - final static List order = new ArrayList<>(); - - public static class Nested1 { - @Rule - public TestRule rules = new TestRule() { - @Override - public Statement apply(final Statement base, Description description) { - return new Statement() { - public void evaluate() throws Throwable { - order.add("rule-before"); - base.evaluate(); - order.add("rule-after"); - } - }; - } - }; - - @BeforeClass - public static void beforeClass() { - order.add("before-class"); - } - - @Before - public void before() { - order.add("before-test"); - } - - @Test - public void testMethod1() { - order.add("testMethod1"); - } - - @After - public void after() { - order.add("after-test"); - } - - @AfterClass - public static void afterClass() { - order.add("after-class"); - } - } - - public static class Nested2 extends Nested1 { - public static void beforeClass() { - order.add("shadowed-before-class"); - } - - @Override - public void before() { - order.add("inherited before-test"); - } - - @Override - public void after() { - order.add("inherited after-test"); - } - - @Override - public void testMethod1() { - order.add("inherited testMethod"); - } - - public static void afterClass() { - order.add("shadowed-after-class"); - } - } - - @Test - public void checkOldMethodRules() throws Exception { - assertSameExecution(Nested2.class); - } - - private void assertSameExecution(Class clazz) throws Exception { - order.clear(); - runTests(clazz); - List order1 = new ArrayList<>(order); - order.clear(); - - new JUnitCore().run(Request.runner(new RandomizedRunner(clazz))); - List order2 = new ArrayList<>(order); - order.clear(); - - String msg = "# JUnit order:\n" + order1 + "\n" + - "# RR order:\n" + order2; - Assertions.assertThat(order2).as(msg).isEqualTo(order1); - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/contracts/TestAssumptionsAtClassLevel.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/contracts/TestAssumptionsAtClassLevel.java deleted file mode 100644 index 39df4443..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/contracts/TestAssumptionsAtClassLevel.java +++ /dev/null @@ -1,88 +0,0 @@ -package com.carrotsearch.randomizedtesting.contracts; - -import static org.junit.Assert.assertEquals; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Assume; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; - -import com.carrotsearch.randomizedtesting.RandomizedTest; -import com.carrotsearch.randomizedtesting.WithNestedTestClass; - -/** - * Check assumptions at suite level (in {@link BeforeClass}). - */ -public class TestAssumptionsAtClassLevel extends WithNestedTestClass { - static final List callOrder = new ArrayList(); - - /** - * Test superclass. - */ - public static class Super extends RandomizedTest { - @BeforeClass - public static void beforeClassSuper() { - assumeRunningNested(); - callOrder.add("beforeClassSuper"); - Assume.assumeTrue(false); - } - - @AfterClass - public static void afterClassSuper() { - callOrder.add("afterClassSuper"); - } - } - - /** - * Test subclass. - */ - public static class SubSub extends Super { - @BeforeClass - public static void beforeClass() { - callOrder.add("beforeClassSub"); - } - - @Before - public void beforeTestSub() { - callOrder.add("beforeTestSub"); - } - - @Test - public void testMethod() { - callOrder.add("testMethodSub"); - } - - @After - public void afterTestSub() { - callOrder.add("afterTestSub"); - } - - @AfterClass - public static void afterClass() { - callOrder.add("afterClassSub"); - } - } - - @Before - public void cleanup() { - callOrder.clear(); - } - - @Test - public void checkOrder() { - checkTestsOutput(0, 1, 0, 1, SubSub.class); - - List expected = Arrays.asList( - "beforeClassSuper", - "afterClassSub", - "afterClassSuper" - ); - assertEquals(expected, callOrder); - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/contracts/TestBeforeAfterMethodOrder.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/contracts/TestBeforeAfterMethodOrder.java deleted file mode 100644 index 2caf8c20..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/contracts/TestBeforeAfterMethodOrder.java +++ /dev/null @@ -1,232 +0,0 @@ -package com.carrotsearch.randomizedtesting.contracts; - -import static org.junit.Assert.assertEquals; - -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; - -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.MethodRule; -import org.junit.rules.RuleChain; -import org.junit.rules.TestRule; -import org.junit.runner.Description; -import org.junit.runner.JUnitCore; -import org.junit.runners.model.FrameworkMethod; -import org.junit.runners.model.Statement; - -import com.carrotsearch.randomizedtesting.RandomizedContext; -import com.carrotsearch.randomizedtesting.RandomizedRunner; -import com.carrotsearch.randomizedtesting.WithNestedTestClass; -import com.carrotsearch.randomizedtesting.annotations.Repeat; -import com.carrotsearch.randomizedtesting.annotations.Seed; - -/** - * Hooks ordering with respect to class hierarchies. - */ -@SuppressWarnings("deprecation") -public class TestBeforeAfterMethodOrder extends WithNestedTestClass { - static final List callOrder = new ArrayList(); - - public static class AppendMethodRule implements MethodRule { - private String text; - - public AppendMethodRule(String text) { - this.text = text; - } - - @Override - public Statement apply(final Statement base, FrameworkMethod method, Object target) { - return new Statement() { - @Override - public void evaluate() throws Throwable { - callOrder.add(text + "-before"); - base.evaluate(); - callOrder.add(text + "-after"); - } - }; - } - } - - public static class AppendRule implements TestRule { - private String text; - - public AppendRule(String text) { - this.text = text; - } - - @Override - public Statement apply(final Statement base, Description description) { - return new Statement() { - @Override - public void evaluate() throws Throwable { - callOrder.add(text + "-before"); - base.evaluate(); - callOrder.add(text + "-after"); - } - }; - } - } - - /** - * Test superclass. - */ - public static class Super { - @BeforeClass - public static void beforeClassSuper() { - callOrder.add("beforeClassSuper"); - } - - @Rule - public TestRule superRule = RuleChain - .outerRule(new AppendRule("superOuterTestRule")) - .around(new AppendRule("superMiddleTestRule")) - .around(new AppendRule("superInnerTestRule")); - - @Rule - public MethodRule superMethodRule = new AppendMethodRule("superMethodRule"); - - @Before - public final void beforeTest() { - callOrder.add("beforeTestSuper"); - } - - protected void testMethod() { - throw new RuntimeException("Should be overridden and public."); - } - - @After - public final void afterTest() { - callOrder.add("afterTestSuper"); - } - - @AfterClass - public static void afterClassSuper() { - callOrder.add("afterClassSuper"); - } - } - - /** - * Test subclass. - */ - public static class SubSub extends Super { - @Rule - public TestRule rule = RuleChain - .outerRule(new AppendRule(" subOuterTestRule")) - .around(new AppendRule(" subMiddleTestRule")) - .around(new AppendRule(" subInnerTestRule")); - - @Rule - public MethodRule methodRule = new AppendMethodRule(" subMethodRule"); - - @BeforeClass - public static void beforeClass() { - callOrder.add(" beforeClassSub"); - } - - @Before - public void beforeTestSub() { - callOrder.add(" beforeTestSub"); - } - - @Test - public void testMethod() { - callOrder.add(" testMethodSub"); - } - - @After - public void afterTestSub() { - callOrder.add(" afterTestSub"); - } - - @AfterClass - public static void afterClass() { - callOrder.add(" afterClassSub"); - } - } - - /** - * Test subclass. - */ - @Seed("deadbeef") - public static class SubSubFixedSeed extends Super { - @BeforeClass - public static void beforeClass() { - callOrder.add("beforeClassSubFS"); - } - - @Before - public void beforeTestSub() { - assumeRunningNested(); - callOrder.add("beforeTestSubFS"); - } - - @Test @Repeat(iterations = 10) - public void testMethod1() { - callOrder.add("testMethodSubFS1 " - + RandomizedContext.current().getRandom().nextInt()); - } - - @Test @Repeat(iterations = 10) - public void testMethod2() { - callOrder.add("testMethodSubFS2 " - + RandomizedContext.current().getRandom().nextInt()); - } - - @After - public void afterTestSub() { - callOrder.add("afterTestSubFS"); - } - - @AfterClass - public static void afterClass() { - callOrder.add("afterClassSubFS"); - } - } - - @Before - public void cleanup() { - callOrder.clear(); - } - - @Test - public void checkOrder() throws Exception { - // Normal JUnit. - checkTestsOutput(1, 0, 0, 0, SubSub.class); - ArrayList junitOrder = new ArrayList(callOrder); - - callOrder.clear(); - new JUnitCore().run(new RandomizedRunner(SubSub.class)); - - if (!callOrder.equals(junitOrder)) { - final int i = junitOrder.size(); - final int j = callOrder.size(); - - System.out.println(String.format(Locale.ROOT, - "%-30s | %-30s", "JUnit4", "RR")); - for (int k = 0; k < Math.max(i, j); k++) { - System.out.println(String.format(Locale.ROOT, - "%-30s | %-30s", - k < i ? junitOrder.get(k) : "--", - k < j ? callOrder.get(k) : "--")); - } - - Assert.fail("JUnit4 and RandomizedRunner differed."); - } - } - - @Test - public void checkOrderFixedSeed() throws Exception { - new JUnitCore().run(new RandomizedRunner(SubSubFixedSeed.class)); - ArrayList order = new ArrayList(callOrder); - callOrder.clear(); - new JUnitCore().run(new RandomizedRunner(SubSubFixedSeed.class)); - assertEquals(order, callOrder); - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/contracts/TestClassLevelIgnore.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/contracts/TestClassLevelIgnore.java deleted file mode 100644 index f830bb6a..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/contracts/TestClassLevelIgnore.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.carrotsearch.randomizedtesting.contracts; - -import org.junit.Ignore; -import org.junit.Test; - -import com.carrotsearch.randomizedtesting.RandomizedTest; -import com.carrotsearch.randomizedtesting.WithNestedTestClass; - -/** - * Class-level {@link Ignore}. - */ -public class TestClassLevelIgnore extends WithNestedTestClass { - @Ignore - public static class Nested extends RandomizedTest { - @Test - public void ignored() { - } - } - - @Test - public void allIgnored() { - checkTestsOutput(0, 1, 0, 0, Nested.class); - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/contracts/TestClassRules.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/contracts/TestClassRules.java deleted file mode 100644 index eeef5373..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/contracts/TestClassRules.java +++ /dev/null @@ -1,75 +0,0 @@ -package com.carrotsearch.randomizedtesting.contracts; - -import java.util.ArrayList; -import java.util.List; - -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.ClassRule; -import org.junit.Test; -import org.junit.rules.RuleChain; -import org.junit.rules.TestRule; -import org.junit.runner.Description; -import org.junit.runner.JUnitCore; -import org.junit.runner.Request; -import org.junit.runners.model.Statement; - -import com.carrotsearch.randomizedtesting.RandomizedRunner; -import com.carrotsearch.randomizedtesting.WithNestedTestClass; - -/** - * {@link ClassRule} support. - */ -public class TestClassRules extends WithNestedTestClass { - final static List order = new ArrayList<>(); - - public static class ClassRuleSupport { - @ClassRule - public static TestRule rules = RuleChain.outerRule(new TestRule() { - @Override - public Statement apply(final Statement base, Description description) { - return new Statement() { - public void evaluate() throws Throwable { - order.add("rule-before"); - base.evaluate(); - order.add("rule-after"); - } - }; - } - }); - - @BeforeClass - public static void beforeClass() { - order.add("before-class"); - } - - @AfterClass - public static void afterClass() { - order.add("after-class"); - } - - @Test - public void passing() { - order.add("passing"); - } - } - - @Test - public void checkOldMethodRules() throws Exception { - assertSameExecution(ClassRuleSupport.class); - } - - private void assertSameExecution(Class clazz) throws Exception { - order.clear(); - runTests(clazz); - List order1 = new ArrayList<>(order); - order.clear(); - - new JUnitCore().run(Request.runner(new RandomizedRunner(clazz))); - List order2 = new ArrayList<>(order); - order.clear(); - - Assert.assertEquals(order1, order2); - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/contracts/TestMethodFilteringInIDEs.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/contracts/TestMethodFilteringInIDEs.java deleted file mode 100644 index fcba3d12..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/contracts/TestMethodFilteringInIDEs.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.carrotsearch.randomizedtesting.contracts; - -import org.junit.Assume; -import org.junit.Ignore; -import org.junit.Test; - -import com.carrotsearch.randomizedtesting.RandomizedTest; -import com.carrotsearch.randomizedtesting.annotations.Repeat; -import com.carrotsearch.randomizedtesting.annotations.Seed; - -@Repeat(iterations = 2, useConstantSeed = false) -@Seed("deadbeef") -public class TestMethodFilteringInIDEs extends RandomizedTest { - @Test - public void testExecuted1() { - } - - @Test - public void testExecuted2() { - } - - @Test - public void testIgnoredByAssumption() { - Assume.assumeTrue(false); - } - - @Ignore - @Test - public void testIgnoredByAnnotation() {} -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/generators/StringGeneratorTestBase.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/generators/StringGeneratorTestBase.java deleted file mode 100644 index 4704de3b..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/generators/StringGeneratorTestBase.java +++ /dev/null @@ -1,69 +0,0 @@ -package com.carrotsearch.randomizedtesting.generators; - -import org.junit.Test; - -import com.carrotsearch.randomizedtesting.RandomizedTest; -import com.carrotsearch.randomizedtesting.annotations.Repeat; - -import static org.junit.Assert.*; - -/** - * Base class for testing {@link StringGenerator}s. - */ -public abstract class StringGeneratorTestBase extends RandomizedTest { - protected final StringGenerator generator; - - protected StringGeneratorTestBase(StringGenerator generator) { - this.generator = generator; - } - - @Test @Repeat(iterations = 10) - public void checkFixedCodePointLength() { - int codepoints = iterationFix(randomIntBetween(1, 100)); - String s = generator.ofCodePointsLength(getRandom(), codepoints, codepoints); - assertEquals(s, codepoints, s.codePointCount(0, s.length())); - } - - @Test @Repeat(iterations = 10) - public void checkRandomCodePointLength() { - int from = iterationFix(randomIntBetween(1, 100)); - int to = from + randomIntBetween(0, 100); - - String s = generator.ofCodePointsLength(getRandom(), from, to); - int codepoints = s.codePointCount(0, s.length()); - assertTrue(codepoints + " not within " + - from + "-" + to, from <= codepoints && codepoints <= to); - } - - @Test @Repeat(iterations = 10) - public void checkFixedCodeUnitLength() { - int codeunits = iterationFix(randomIntBetween(1, 100)); - String s = generator.ofCodeUnitsLength(getRandom(), codeunits, codeunits); - assertEquals(s, codeunits, s.length()); - assertEquals(s, codeunits, s.toCharArray().length); - } - - @Test @Repeat(iterations = 10) - public void checkRandomCodeUnitLength() { - int from = iterationFix(randomIntBetween(1, 100)); - int to = from + randomIntBetween(0, 100); - - String s = generator.ofCodeUnitsLength(getRandom(), from, to); - int codeunits = s.length(); - assertTrue(codeunits + " not within " + - from + "-" + to, from <= codeunits && codeunits <= to); - } - - @Test - public void checkZeroLength() { - assertEquals("", generator.ofCodePointsLength(getRandom(), 0, 0)); - assertEquals("", generator.ofCodeUnitsLength(getRandom(), 0, 0)); - } - - /** - * Correct the count if a given generator doesn't support all possible values (in tests). - */ - protected int iterationFix(int i) { - return i; - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/generators/TestCodepointSetGenerator.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/generators/TestCodepointSetGenerator.java deleted file mode 100644 index 30e4c94c..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/generators/TestCodepointSetGenerator.java +++ /dev/null @@ -1,115 +0,0 @@ -package com.carrotsearch.randomizedtesting.generators; - -import java.util.HashSet; -import java.util.Random; -import java.util.Set; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Suite; -import org.junit.runners.Suite.SuiteClasses; - -import com.carrotsearch.randomizedtesting.RandomizedTest; - -import static org.junit.Assert.*; - -@RunWith(Suite.class) -@SuiteClasses({ - TestCodepointSetGenerator.CodepointSetOnChars.class, - TestCodepointSetGenerator.CodepointSetOnCodePoints.class, - TestCodepointSetGenerator.CodepointSetOnSurrogatesOnly.class -}) -public class TestCodepointSetGenerator extends RandomizedTest { - private final static int [] codepoints = { - 'a', 'b', 'c', 'd', - 0xd7ff, - 0xffff, - 0x10000, - 0x1D11E, - 0x10FFFD, - }; - - private final static int [] surrogates = { - 0x10000, - 0x1D11E, - 0x10FFFD, - }; - - private final static String withSurrogates = new String(codepoints, 0, codepoints.length); - - public static class CodepointSetOnChars extends StringGeneratorTestBase { - public CodepointSetOnChars() { - super(new CodepointSetGenerator(new char[] { - 'a', 'b', 'c', 'd', - 0x100, - 0xd7ff, - 0xffff - })); - } - - @Test - public void testAllCharactersUsed() { - char [] domain = "abcdefABCDEF".toCharArray(); - Set chars = new HashSet(); - for (char chr : domain) { - chars.add(chr); - } - - CodepointSetGenerator gen = new CodepointSetGenerator(domain); - Random r = new Random(randomLong()); - for (int i = 0; i < 1000000 && !chars.isEmpty(); i++) { - for (char ch : gen.ofCodeUnitsLength(r, 100, 100).toCharArray()) { - chars.remove(ch); - } - } - - assertTrue(chars.isEmpty()); - } - - @Test(expected = IllegalArgumentException.class) - public void testSurrogatesInConstructor() { - new CodepointSetGenerator(withSurrogates.toCharArray()); - } - } - - public static class CodepointSetOnCodePoints extends StringGeneratorTestBase { - public CodepointSetOnCodePoints() { - super(new CodepointSetGenerator(withSurrogates)); - } - - @Test - public void testAllCharactersUsed() { - char [] domain = "abcdefABCDEF".toCharArray(); - Set chars = new HashSet(); - for (char chr : domain) { - chars.add(chr); - } - - CodepointSetGenerator gen = new CodepointSetGenerator(new String(domain)); - Random r = new Random(randomLong()); - for (int i = 0; i < 1000000 && !chars.isEmpty(); i++) { - for (char ch : gen.ofCodeUnitsLength(r, 100, 100).toCharArray()) { - chars.remove(ch); - } - } - - assertTrue(chars.isEmpty()); - } - } - - public static class CodepointSetOnSurrogatesOnly extends StringGeneratorTestBase { - public CodepointSetOnSurrogatesOnly() { - super(new CodepointSetGenerator(new String(surrogates, 0, surrogates.length))); - } - - @Test(expected = IllegalArgumentException.class) - public void testOddCodePoints() { - generator.ofCodeUnitsLength(getRandom(), 3, 3); - } - - @Override - protected int iterationFix(int i) { - return i & ~1; // Even only. - } - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/generators/TestRandomBytes.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/generators/TestRandomBytes.java deleted file mode 100644 index 81f47a23..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/generators/TestRandomBytes.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.carrotsearch.randomizedtesting.generators; - -import org.assertj.core.api.Assertions; -import org.junit.Test; - -import com.carrotsearch.randomizedtesting.RandomizedTest; -import com.carrotsearch.randomizedtesting.annotations.Repeat; - -@Repeat(iterations = 100) -public class TestRandomBytes extends RandomizedTest { - @Test - public void testRandomBytes() { - int len = randomIntBetween(0, 100); - Assertions.assertThat(randomBytesOfLength(len)).hasSize(len); - } - - @Test - public void testRandomBytesOfLength() { - int min = randomIntBetween(0, 100); - int max = min + randomIntBetween(0, 10); - - byte[] bytes = randomBytesOfLength(min, max); - Assertions.assertThat(bytes.length >= min).isTrue(); - Assertions.assertThat(bytes.length <= max).isTrue(); - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/generators/TestRandomPicks.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/generators/TestRandomPicks.java deleted file mode 100644 index 02238087..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/generators/TestRandomPicks.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.carrotsearch.randomizedtesting.generators; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashSet; - -import org.junit.Test; - -import com.carrotsearch.randomizedtesting.RandomizedTest; - -import static org.junit.Assert.*; - -public class TestRandomPicks extends RandomizedTest { - @Test(expected = IllegalArgumentException.class) - public void testRandomFromEmptyCollection() { - RandomPicks.randomFrom(getRandom(), new HashSet()); - } - - @Test - public void testRandomFromCollection() { - Object t = new Object(); - Object r = RandomPicks.randomFrom(getRandom(), new HashSet(Arrays.asList(t))); - assertSame(r, t); - } - - @Test(expected = IllegalArgumentException.class) - public void testRandomFromList() { - RandomPicks.randomFrom(getRandom(), new ArrayList()); - } - - @Test(expected = IllegalArgumentException.class) - public void testRandomFromArray() { - RandomPicks.randomFrom(getRandom(), new Object[] {}); - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/generators/TestRealisticUnicodeGenerator.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/generators/TestRealisticUnicodeGenerator.java deleted file mode 100644 index 2c6b6430..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/generators/TestRealisticUnicodeGenerator.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.carrotsearch.randomizedtesting.generators; - -public class TestRealisticUnicodeGenerator extends StringGeneratorTestBase { - public TestRealisticUnicodeGenerator() { - super(new UnicodeGenerator()); - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/generators/TestUnicodeGenerator.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/generators/TestUnicodeGenerator.java deleted file mode 100644 index b14ffd99..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/generators/TestUnicodeGenerator.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.carrotsearch.randomizedtesting.generators; - -public class TestUnicodeGenerator extends StringGeneratorTestBase { - public TestUnicodeGenerator() { - super(new UnicodeGenerator()); - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/inheritance/JUnitAnnotationPropagation.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/inheritance/JUnitAnnotationPropagation.java deleted file mode 100644 index 32c93481..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/inheritance/JUnitAnnotationPropagation.java +++ /dev/null @@ -1,108 +0,0 @@ -package com.carrotsearch.randomizedtesting.inheritance; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import org.assertj.core.api.Assertions; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TestRule; -import org.junit.runner.Description; -import org.junit.runner.JUnitCore; -import org.junit.runner.Request; -import org.junit.runners.model.Statement; - -import com.carrotsearch.randomizedtesting.RandomizedRunner; -import com.carrotsearch.randomizedtesting.WithNestedTestClass; - -public class JUnitAnnotationPropagation { - final static List order = new ArrayList<>(); - - public static class Super { - @Rule - public TestRule rules = new TestRule() { - @Override - public Statement apply(final Statement base, Description description) { - return new Statement() { - public void evaluate() throws Throwable { - order.add("rule-before"); - base.evaluate(); - order.add("rule-after"); - } - }; - } - }; - - @BeforeClass public static void beforeClass1() { order.add("super.beforeclass1"); } - public static void beforeClass2() { order.add("super.beforeclass2"); } - @BeforeClass public static void beforeClass3() { order.add("super.beforeclass3"); } - - @Before public void before1() { order.add("super.before1"); } - public void before2() { order.add("super.before2"); } - @Before public void before3() { order.add("super.before3"); } - - @Test public void testMethod1() { order.add("super.testMethod1"); } - public void testMethod2() { order.add("super.testMethod2"); } - @Test public void testMethod3() { order.add("super.testMethod3"); } - - // Awkward cases of annotations and virtual methods. - @Ignore public void testMethod4() { order.add("super.testMethod4"); } - @Test public void testMethod5() { order.add("super.testMethod5"); } - } - - public static class Sub extends Super { - public static void beforeClass1() { order.add("sub.beforeclass1"); } - @BeforeClass public static void beforeClass2() { order.add("sub.beforeclass2"); } - @BeforeClass public static void beforeClass3() { order.add("sub.beforeclass3"); } - - public void before1() { order.add("sub.before1"); } - @Before public void before2() { order.add("sub.before2"); } - @Before public void before3() { order.add("sub.before3"); } - - public void testMethod1() { order.add("sub.testMethod1"); } - @Test public void testMethod2() { order.add("sub.testMethod2"); } - @Test public void testMethod3() { order.add("sub.testMethod3"); } - - @Test public void testMethod4() { order.add("sub.testMethod4"); } - @Ignore public void testMethod5() { order.add("sub.testMethod5"); } - } - - @Test - public void checkOldMethodRules() throws Exception { - assertSameExecution(Sub.class); - } - - private void assertSameExecution(Class clazz) throws Exception { - order.clear(); - WithNestedTestClass.runTests(clazz); - List order1 = new ArrayList<>(order); - order.clear(); - - new JUnitCore().run(Request.runner(new RandomizedRunner(clazz))); - List order2 = new ArrayList<>(order); - order.clear(); - - String msg = "# JUnit order:\n" + order1 + "\n" + - "# RR order:\n" + order2; - - // Don't care about relative ordering of hook methods. - Assertions.assertThat(noNumbers(order2)).as(msg).isEqualTo(noNumbers(order1)); - - // But do care that all methods show up. - Collections.sort(order1); - Collections.sort(order2); - Assertions.assertThat(order2).as(msg).isEqualTo(order1); - } - - private List noNumbers(List in) { - List out = new ArrayList<>(); - for (String s : in) { - out.add(s.replaceAll("[0-9]+$", "")); - } - return out; - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/inheritance/PrivateHooksPropagation.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/inheritance/PrivateHooksPropagation.java deleted file mode 100644 index ecc032f0..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/inheritance/PrivateHooksPropagation.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.carrotsearch.randomizedtesting.inheritance; - -import java.util.ArrayList; -import java.util.List; - -import org.assertj.core.api.Assertions; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.JUnitCore; -import org.junit.runner.Request; - -import com.carrotsearch.randomizedtesting.RandomizedRunner; -import com.carrotsearch.randomizedtesting.RandomizedTest; - -public class PrivateHooksPropagation { - final static List order = new ArrayList<>(); - - public static class Super extends RandomizedTest { - @BeforeClass private static void beforeClass1() { order.add("super.beforeclass1"); } - @BeforeClass protected static void beforeClass2() { order.add("super.beforeclass2"); } - - @Before private void before1() { order.add("super.before1"); } - @Before protected void before2() { order.add("super.before2"); } - - @Test public void testMethod1() { order.add("super.testMethod1"); } - } - - public static class Sub extends Super { - @BeforeClass private static void beforeClass1() { order.add("sub.beforeclass1"); } - @BeforeClass protected static void beforeClass2() { order.add("sub.beforeclass2"); } - - @Before private void before1() { order.add("sub.before1"); } - @Before protected void before2() { order.add("sub.before2"); } - } - - @Test - public void checkOldMethodRules() throws Exception { - assertSameExecution(Sub.class); - } - - private void assertSameExecution(Class clazz) throws Exception { - new JUnitCore().run(Request.runner(new RandomizedRunner(clazz))); - List order1 = new ArrayList<>(order); - order.clear(); - - String msg = "# RR order:\n" + order1; - Assertions.assertThat(order1).as(msg).containsOnly( - "super.beforeclass1", - "sub.beforeclass1", - "sub.beforeclass2", - "super.before1", - "sub.before1", - "sub.before2", - "super.testMethod1"); - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/rules/TestNoClassHooksShadowingRule.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/rules/TestNoClassHooksShadowingRule.java deleted file mode 100644 index d9f9c738..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/rules/TestNoClassHooksShadowingRule.java +++ /dev/null @@ -1,79 +0,0 @@ -package com.carrotsearch.randomizedtesting.rules; - -import org.assertj.core.api.Assertions; -import org.junit.BeforeClass; -import org.junit.ClassRule; -import org.junit.Test; -import org.junit.rules.RuleChain; -import org.junit.rules.TestRule; -import org.junit.runner.Description; -import org.junit.runners.model.Statement; - -import com.carrotsearch.randomizedtesting.RandomizedTest; -import com.carrotsearch.randomizedtesting.WithNestedTestClass; - -public class TestNoClassHooksShadowingRule extends WithNestedTestClass { - public static class Super extends RandomizedTest { - private static TestRule assumeNotNestedRule = new TestRule() { - public Statement apply(final Statement base, Description description) { - return new Statement() { - public void evaluate() throws Throwable { - assumeRunningNested(); - base.evaluate(); - } - }; - } - }; - - @ClassRule - public static TestRule classRules = - RuleChain - .outerRule(assumeNotNestedRule) - .around(new NoClassHooksShadowingRule()); - - @BeforeClass - public static void before() {} - - @BeforeClass - private static void privateBefore() {} - - @Test - public void testEmpty() {} - } - - public static class Sub1 extends Super { - public static void before() {} - } - - public static class Sub2 extends Super { - @BeforeClass - public static void before() {} - } - - public static class Sub3 extends Super { - @BeforeClass - private static void privateBefore() {} - } - - @Test - public void testShadowingNoAnnotation() { - FullResult runClasses = runTests(Sub1.class); - Assertions.assertThat(runClasses.getFailures()).isNotEmpty(); - Assertions.assertThat(runClasses.getFailures().get(0).getTrace()) - .contains("shadow or override each other"); - } - - @Test - public void testShadowingWithAnnotation() { - FullResult runClasses = runTests(Sub2.class); - Assertions.assertThat(runClasses.getFailures()).isNotEmpty(); - Assertions.assertThat(runClasses.getFailures().get(0).getTrace()) - .contains("shadow or override each other"); - } - - @Test - public void testIndependentChains() { - FullResult runClasses = runTests(Sub3.class); - Assertions.assertThat(runClasses.getFailures()).isEmpty(); - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/rules/TestNoInstanceHooksOverridesRule.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/rules/TestNoInstanceHooksOverridesRule.java deleted file mode 100644 index 01478f99..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/rules/TestNoInstanceHooksOverridesRule.java +++ /dev/null @@ -1,101 +0,0 @@ -package com.carrotsearch.randomizedtesting.rules; - -import java.lang.reflect.Method; - -import org.assertj.core.api.Assertions; -import org.junit.Before; -import org.junit.ClassRule; -import org.junit.Test; -import org.junit.rules.RuleChain; -import org.junit.rules.TestRule; -import org.junit.runner.Description; -import org.junit.runners.model.Statement; - -import com.carrotsearch.randomizedtesting.RandomizedTest; -import com.carrotsearch.randomizedtesting.WithNestedTestClass; - -public class TestNoInstanceHooksOverridesRule extends WithNestedTestClass { - public static class Super extends RandomizedTest { - private static TestRule assumeNotNestedRule = new TestRule() { - public Statement apply(final Statement base, Description description) { - return new Statement() { - public void evaluate() throws Throwable { - assumeRunningNested(); - base.evaluate(); - } - }; - } - }; - - @ClassRule - public static TestRule classRules = - RuleChain - .outerRule(assumeNotNestedRule) - .around(new NoInstanceHooksOverridesRule() { - @Override - protected boolean verify(Method key) { - return !key.getName().equals("setup"); - } - }); - - @Before - public void before() {} - - @Before - private void privateBefore() {} - - @Before - public void setup() {} - - @Test - public void testEmpty() {} - } - - public static class Sub1 extends Super { - public void before() {} - } - - public static class Sub2 extends Super { - @Before - public void before() {} - } - - public static class Sub3 extends Super { - @Before - private void privateBefore() {} - } - - public static class Sub4 extends Super { - @Override - public void setup() {} - } - - @Test - public void testOverrideNoAnnotation() { - - FullResult runClasses = runTests(Sub1.class); - Assertions.assertThat(runClasses.getFailures()).isNotEmpty(); - Assertions.assertThat(runClasses.getFailures().get(0).getTrace()) - .contains("shadow or override each other"); - } - - @Test - public void testOverrideWithAnnotation() { - FullResult runClasses = runTests(Sub2.class); - Assertions.assertThat(runClasses.getFailures()).isNotEmpty(); - Assertions.assertThat(runClasses.getFailures().get(0).getTrace()) - .contains("shadow or override each other"); - } - - @Test - public void testIndependentChains() { - FullResult runClasses = runTests(Sub3.class); - Assertions.assertThat(runClasses.getFailures()).isEmpty(); - } - - @Test - public void testFiltering() { - FullResult runClasses = runTests(Sub4.class); - Assertions.assertThat(runClasses.getFailures()).isEmpty(); - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/rules/TestStaticFieldsInvariantRule.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/rules/TestStaticFieldsInvariantRule.java deleted file mode 100644 index f15c0b5c..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/rules/TestStaticFieldsInvariantRule.java +++ /dev/null @@ -1,146 +0,0 @@ -package com.carrotsearch.randomizedtesting.rules; - -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.HashMap; -import java.util.Map; - -import org.assertj.core.api.Assertions; -import org.junit.BeforeClass; -import org.junit.ClassRule; -import org.junit.Test; -import org.junit.rules.RuleChain; -import org.junit.rules.TestRule; -import org.junit.runner.Description; -import org.junit.runners.model.Statement; - -import com.carrotsearch.randomizedtesting.RandomizedTest; -import com.carrotsearch.randomizedtesting.WithNestedTestClass; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope.Scope; - -public class TestStaticFieldsInvariantRule extends WithNestedTestClass { - static int LEAK_THRESHOLD = 5 * 1024 * 1024; - - @ThreadLeakScope(Scope.SUITE) - public static class Base extends RandomizedTest { - private static TestRule assumeNotNestedRule = new TestRule() { - public Statement apply(final Statement base, Description description) { - return new Statement() { - public void evaluate() throws Throwable { - assumeRunningNested(); - base.evaluate(); - } - }; - } - }; - - @ClassRule - public static TestRule classRules = - RuleChain - .outerRule(assumeNotNestedRule) - .around(new StaticFieldsInvariantRule(LEAK_THRESHOLD, true)); - - @Test - public void testEmpty() {} - } - - public static class Smaller extends Base { - static byte [] field0; - - @BeforeClass - private static void setup() { - field0 = new byte [LEAK_THRESHOLD / 2]; - } - } - - public static class Exceeding extends Smaller { - static byte [] field1; - static byte [] field2; - static int [] field3; - static long field4; - final static long [] field5 = new long [1024]; - - @BeforeClass - private static void setup() { - field1 = new byte [LEAK_THRESHOLD / 2]; - field2 = new byte [100]; - field3 = new int [100]; - } - } - - public static class MultipleReferences extends Base { - static Object ref1, ref2, ref3, - ref4, ref5, ref6; - - static Object ref7 = null; - - static { - Map map = new HashMap(); - map.put("key", new byte [1024 * 1024 * 2]); - ref1 = ref2 = ref3 = ref4 = ref5 = ref6 = map; - } - } - - @Test - public void testReferencesCountedMultipleTimes() { - FullResult runClasses = runTests(MultipleReferences.class); - Assertions.assertThat(runClasses.getFailures()).isEmpty(); - } - - @Test - public void testPassingUnderThreshold() { - FullResult runClasses = runTests(Smaller.class); - Assertions.assertThat(runClasses.getFailures()).isEmpty(); - } - - @Test - public void testFailingAboveThreshold() { - FullResult runClasses = runTests(Exceeding.class); - Assertions.assertThat(runClasses.getFailures()).hasSize(1); - - Assertions.assertThat(runClasses.getFailures().get(0).getTrace()) - .contains(".field0") - .contains(".field1") - .contains(".field2") - .contains(".field3") - .doesNotContain(".field5"); - } - - static class Holder { - private final Path path; - - Holder() { - this.path = Paths.get("."); - final String name = this.path.getClass().getName(); - RandomizedTest.assumeTrue(Path.class.getName() + " is not implemented by internal class in this JVM: " + name, - name.startsWith("sun.") || name.startsWith("jdk.")); - } - } - - public static class FailsJava9 extends Base { - static Holder field0; - - @BeforeClass - private static void setup() throws Exception { - field0 = new Holder(); - } - } - - @Test @org.junit.Ignore - public void testJava9Jigsaw() { - // check if we have Java 9 module system: - try { - Class.class.getMethod("getModule"); - } catch (Exception e) { - RandomizedTest.assumeTrue("This test requires Java 9 module system (Jigsaw)", false); - } - - FullResult runClasses = runTests(FailsJava9.class); - Assertions.assertThat(runClasses.getFailures()).hasSize(1); - - Assertions.assertThat(runClasses.getFailures().get(0).getTrace()) - .contains("sizes cannot be measured due to security restrictions or Java 9") - .contains(".field0"); - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/rules/TestSystemPropertiesInvariantRule.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/rules/TestSystemPropertiesInvariantRule.java deleted file mode 100644 index 3819a189..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/rules/TestSystemPropertiesInvariantRule.java +++ /dev/null @@ -1,134 +0,0 @@ -package com.carrotsearch.randomizedtesting.rules; - -import java.util.Properties; - -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.ClassRule; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.RuleChain; -import org.junit.rules.TestRule; -import org.junit.runner.*; -import org.junit.runner.notification.Failure; -import org.junit.runners.model.Statement; - -import com.carrotsearch.randomizedtesting.WithNestedTestClass; - -public class TestSystemPropertiesInvariantRule extends WithNestedTestClass { - public static final String PROP_KEY1 = "new-property-1"; - public static final String VALUE1 = "new-value-1"; - - public static class Base { - private static TestRule assumeNotNestedRule = new TestRule() { - public Statement apply(final Statement base, Description description) { - return new Statement() { - public void evaluate() throws Throwable { - assumeRunningNested(); - base.evaluate(); - } - }; - } - }; - - @ClassRule - public static TestRule classRules = - RuleChain.outerRule(assumeNotNestedRule).around(new SystemPropertiesInvariantRule()); - - @Rule - public TestRule testRules = - RuleChain.outerRule(new SystemPropertiesInvariantRule()); - - @Test - public void testEmpty() {} - } - - public static class InBeforeClass extends Base { - @BeforeClass - public static void beforeClass() { - System.setProperty(PROP_KEY1, VALUE1); - } - } - - public static class InAfterClass extends Base { - @AfterClass - public static void afterClass() { - System.setProperty(PROP_KEY1, VALUE1); - } - } - - public static class InTestMethod extends Base { - @Test - public void testMethod1() { - if (System.getProperty(PROP_KEY1) != null) { - throw new RuntimeException("Shouldn't be here."); - } - System.setProperty(PROP_KEY1, VALUE1); - } - - @Test - public void testMethod2() { - testMethod1(); - } - } - - public static class NonStringProperties extends Base { - @Test - public void testMethod1() { - if (System.getProperties().get(PROP_KEY1) != null) { - throw new RuntimeException("Will pass."); - } - - Properties properties = System.getProperties(); - properties.put(PROP_KEY1, new Object()); - Assert.assertTrue(System.getProperties().get(PROP_KEY1) != null); - } - - @Test - public void testMethod2() { - testMethod1(); - } - - @AfterClass - public static void cleanup() { - System.getProperties().remove(PROP_KEY1); - } - } - - @Test - public void testRuleInvariantBeforeClass() { - FullResult runClasses = runTests(InBeforeClass.class); - Assert.assertEquals(1, runClasses.getFailureCount()); - Assert.assertTrue(runClasses.getFailures().get(0).getMessage() - .contains(PROP_KEY1)); - Assert.assertNull(System.getProperty(PROP_KEY1)); - } - - @Test - public void testRuleInvariantAfterClass() { - FullResult runClasses = runTests(InAfterClass.class); - Assert.assertEquals(1, runClasses.getFailureCount()); - Assert.assertTrue(runClasses.getFailures().get(0).getMessage() - .contains(PROP_KEY1)); - Assert.assertNull(System.getProperty(PROP_KEY1)); - } - - @Test - public void testRuleInvariantInTestMethod() { - FullResult runClasses = runTests(InTestMethod.class); - Assert.assertEquals(2, runClasses.getFailureCount()); - for (Failure f : runClasses.getFailures()) { - Assert.assertTrue(f.getMessage().contains(PROP_KEY1)); - } - Assert.assertNull(System.getProperty(PROP_KEY1)); - } - - @Test - public void testNonStringProperties() { - FullResult runClasses = runTests(NonStringProperties.class); - Assert.assertEquals(1, runClasses.getFailureCount()); - Assert.assertTrue(runClasses.getFailures().get(0).getMessage().contains("Will pass")); - Assert.assertEquals(3, runClasses.getRunCount()); - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/snippets/TheGoodBadAndUglySnippet.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/snippets/TheGoodBadAndUglySnippet.java deleted file mode 100644 index 3c2471ec..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/snippets/TheGoodBadAndUglySnippet.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.carrotsearch.randomizedtesting.snippets; - -import org.junit.BeforeClass; -import org.junit.Test; - -import com.carrotsearch.randomizedtesting.WithNestedTestClass; -import com.carrotsearch.randomizedtesting.annotations.Repeat; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakAction; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakAction.Action; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakLingering; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope.Scope; - -import static org.junit.Assert.*; - -public class TheGoodBadAndUglySnippet extends WithNestedTestClass { - /** - * This is cheating so that snippets appear to be extending RandomizedTest - * but at the same time snippety tests won't execute in Eclipse. - */ - public static class RandomizedTest extends com.carrotsearch.randomizedtesting.RandomizedTest { - @BeforeClass - public static void runAsTest() { - assumeRunningNested(); - } - } - - // [[[start:goodbadugly]]] - @ThreadLeakScope(Scope.TEST) - @ThreadLeakAction({Action.WARN, Action.INTERRUPT}) - @ThreadLeakLingering(linger = 1000) - public static class TheGoodBadAndUgly extends RandomizedTest { - @Test - public void good() { - // I do nothing and I'm good. - } - - @Test - @Repeat(iterations = 10) - public void bad() { - // I fail randomly, about 20% of the time. - assertFalse(randomIntBetween(1, 100) <= 20); - } - - @Test - public void ugly() { - // I start and abandon a thread which falls - // outside the test's scope. The test will fail. - new Thread() { - public void run() { - RandomizedTest.sleep(5000); - } - }.start(); - } - } - // [[[end:goodbadugly]]] -} \ No newline at end of file diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/timeouts/Test001TimeoutSuite.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/timeouts/Test001TimeoutSuite.java deleted file mode 100644 index 9e2c9a23..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/timeouts/Test001TimeoutSuite.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.carrotsearch.randomizedtesting.timeouts; - -import org.assertj.core.api.Assertions; -import org.junit.Test; - -import com.carrotsearch.randomizedtesting.RandomizedTest; -import com.carrotsearch.randomizedtesting.Utils; -import com.carrotsearch.randomizedtesting.WithNestedTestClass; -import com.carrotsearch.randomizedtesting.annotations.Timeout; -import com.carrotsearch.randomizedtesting.annotations.TimeoutSuite; - -public class Test001TimeoutSuite extends WithNestedTestClass { - /** - * Nested test suite class with {@link TimeoutSuite}. - */ - @TimeoutSuite(millis = 500) - @Timeout(millis = 5000) - public static class Nested extends ApplyAtPlace {} - - @Test public void testClassRule() { check(Place.CLASS_RULE); } - @Test public void testBeforeClass() { check(Place.BEFORE_CLASS); } - @Test public void testConstructor() { check(Place.CONSTRUCTOR); } - @Test public void testTestRule() { check(Place.TEST_RULE); } - @Test public void testBefore() { check(Place.BEFORE); } - @Test public void testTest() { check(Place.TEST); } - @Test public void testAfter() { check(Place.AFTER); } - @Test public void testAfterClass() { check(Place.AFTER_CLASS); } - - /** - * Check a given timeout place. - */ - private void check(Place p) { - ApplyAtPlace.place = p; - ApplyAtPlace.runnable = new Runnable() { - @Override - public void run() { - while (true) RandomizedTest.sleep(10000); - } - }; - - FullResult r = runTests(Nested.class); - Utils.assertFailureWithMessage(r, "Suite timeout exceeded"); - Utils.assertFailuresContainSeeds(r); - - Assertions.assertThat(getLoggingMessages()) - .doesNotContain("Test execution timed out"); - } -} - diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/timeouts/Test002TimeoutMethod.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/timeouts/Test002TimeoutMethod.java deleted file mode 100644 index bae1b276..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/timeouts/Test002TimeoutMethod.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.carrotsearch.randomizedtesting.timeouts; - -import org.junit.Test; - -import com.carrotsearch.randomizedtesting.RandomizedTest; -import com.carrotsearch.randomizedtesting.Utils; -import com.carrotsearch.randomizedtesting.WithNestedTestClass; -import com.carrotsearch.randomizedtesting.annotations.Timeout; - -public class Test002TimeoutMethod extends WithNestedTestClass { - @Timeout(millis = 25) - public static class Nested extends ApplyAtPlace {} - - @Test public void testTestRule() { check(Place.TEST_RULE); } - @Test public void testBefore() { check(Place.BEFORE); } - @Test public void testTest() { check(Place.TEST); } - @Test public void testAfter() { check(Place.AFTER); } - - /** - * Check a given timeout place. - */ - private void check(Place p) { - ApplyAtPlace.place = p; - ApplyAtPlace.runnable = new Runnable() { - @Override - public void run() { - while (true) RandomizedTest.sleep(1000); - } - }; - - FullResult r = runTests(Nested.class); - Utils.assertFailureWithMessage(r, "Test timeout exceeded"); - Utils.assertFailuresContainSeeds(r); - } -} - diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/timeouts/Test003ThreadLeaksMethod.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/timeouts/Test003ThreadLeaksMethod.java deleted file mode 100644 index 2bd3fbbd..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/timeouts/Test003ThreadLeaksMethod.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.carrotsearch.randomizedtesting.timeouts; - -import org.assertj.core.api.Assertions; -import org.junit.Assert; -import org.junit.Test; - -import com.carrotsearch.randomizedtesting.LifecycleScope; -import com.carrotsearch.randomizedtesting.Utils; -import com.carrotsearch.randomizedtesting.WithNestedTestClass; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakAction; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakAction.Action; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakLingering; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope.Scope; - -public class Test003ThreadLeaksMethod extends WithNestedTestClass { - @ThreadLeakScope(Scope.TEST) - @ThreadLeakLingering(linger = 0) - @ThreadLeakAction({Action.WARN, Action.INTERRUPT}) - public static class Nested extends ApplyAtPlace {} - - @Test public void testClassRule() { suiteLeak(Place.CLASS_RULE); } - @Test public void testBeforeClass() { suiteLeak(Place.BEFORE_CLASS); } - @Test public void testConstructor() { suiteLeak(Place.CONSTRUCTOR); } - @Test public void testTestRule() { testLeak(Place.TEST_RULE); } - @Test public void testBefore() { testLeak(Place.BEFORE); } - @Test public void testTest() { testLeak(Place.TEST); } - @Test public void testAfter() { testLeak(Place.AFTER); } - @Test public void testAfterClass() { suiteLeak(Place.AFTER_CLASS); } - - private void testLeak(Place p) { - check(p, LifecycleScope.TEST); - } - - private void suiteLeak(Place p) { - check(p, LifecycleScope.SUITE); - } - - /** - * Check a given timeout place. - */ - private void check(Place p, LifecycleScope scope) { - ApplyAtPlace.place = p; - ApplyAtPlace.runnable = new Runnable() { - @Override - public void run() { - startThread("foobar"); - } - }; - - FullResult r = runTests(Nested.class); - Utils.assertFailureWithMessage(r, "1 thread leaked from " + scope.toString() + " scope at"); - Assert.assertEquals(1, r.getFailureCount()); - Utils.assertFailuresContainSeeds(r); - Utils.assertNoLiveThreadsContaining("foobar"); - - Assertions.assertThat(getLoggingMessages()) - .doesNotContain("Uncaught exception"); - } -} - diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/timeouts/Test004ThreadLeaksSuite.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/timeouts/Test004ThreadLeaksSuite.java deleted file mode 100644 index 8d45e6ad..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/timeouts/Test004ThreadLeaksSuite.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.carrotsearch.randomizedtesting.timeouts; - -import org.assertj.core.api.Assertions; -import org.junit.Assert; -import org.junit.Test; - -import com.carrotsearch.randomizedtesting.Utils; -import com.carrotsearch.randomizedtesting.WithNestedTestClass; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakAction; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakAction.Action; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakLingering; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope.Scope; - -public class Test004ThreadLeaksSuite extends WithNestedTestClass { - @ThreadLeakScope(Scope.SUITE) - @ThreadLeakLingering(linger = 0) - @ThreadLeakAction({Action.WARN, Action.INTERRUPT}) - public static class Nested extends ApplyAtPlace {} - - @Test public void testClassRule() { suiteLeak(Place.CLASS_RULE); } - @Test public void testBeforeClass() { suiteLeak(Place.BEFORE_CLASS); } - @Test public void testConstructor() { suiteLeak(Place.CONSTRUCTOR); } - @Test public void testTestRule() { suiteLeak(Place.TEST_RULE); } - @Test public void testBefore() { suiteLeak(Place.BEFORE); } - @Test public void testTest() { suiteLeak(Place.TEST); } - @Test public void testAfter() { suiteLeak(Place.AFTER); } - @Test public void testAfterClass() { suiteLeak(Place.AFTER_CLASS); } - - /** - * Check a given timeout place. - */ - private void suiteLeak(Place p) { - ApplyAtPlace.place = p; - ApplyAtPlace.runnable = new Runnable() { - @Override - public void run() { - startThread("foobar"); - } - }; - - FullResult r = runTests(Nested.class); - Utils.assertFailureWithMessage(r, "1 thread leaked from SUITE scope at"); - Assert.assertEquals(1, r.getFailureCount()); - Utils.assertFailuresContainSeeds(r); - Utils.assertNoLiveThreadsContaining("foobar"); - - Assertions.assertThat(getLoggingMessages()) - .doesNotContain("Uncaught exception"); - } -} - diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/timeouts/Test005ThreadLeaksSystemThreads.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/timeouts/Test005ThreadLeaksSystemThreads.java deleted file mode 100644 index 3f6214e0..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/timeouts/Test005ThreadLeaksSystemThreads.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.carrotsearch.randomizedtesting.timeouts; - -import java.lang.reflect.Method; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.logging.Level; -import java.util.logging.Logger; - -import org.assertj.core.api.Assertions; -import org.junit.Test; - -import com.carrotsearch.randomizedtesting.RandomizedTest; -import com.carrotsearch.randomizedtesting.WithNestedTestClass; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakGroup; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakGroup.Group; - -/** - * Checks if known demon threads spawned by certain library methods are properly - * handled. - */ -public class Test005ThreadLeaksSystemThreads extends WithNestedTestClass { - - @ThreadLeakGroup(Group.MAIN) - public static class Nested extends RandomizedTest { - @Test - public void tokenPoller() throws Exception { - assumeRunningNested(); - try { - MessageDigest instance = MessageDigest.getInstance("MD5"); - instance.update(randomByte()); - instance.digest(); - } catch (NoSuchAlgorithmException e) { - Logger.getAnonymousLogger().log(Level.SEVERE, "No MD5 in MessageDigest?", e); - } - } - - @Test - public void gcDaemon() throws Exception { - assumeRunningNested(); - - try { - Class clazz = Class.forName("sun.misc.GC"); - Method method = clazz.getDeclaredMethod("requestLatency", new Class[] {long.class}); - method.invoke(null, Long.valueOf(3600000)); - } catch (ClassNotFoundException e) { - // Ignore, must be running under a JVM without this class. - } - } - } - - @Test - public void leftOverThread() throws Throwable { - FullResult r = runTests(Nested.class); - Assertions.assertThat(r.getFailures()).isEmpty(); - - Assertions.assertThat(getLoggingMessages()) - .doesNotContain("java.lang.Thread.sleep") - .doesNotContain("Uncaught exception"); - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/timeouts/Test006TimeoutAndThreadLeak.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/timeouts/Test006TimeoutAndThreadLeak.java deleted file mode 100644 index fa05ff1c..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/timeouts/Test006TimeoutAndThreadLeak.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.carrotsearch.randomizedtesting.timeouts; - -import org.assertj.core.api.Assertions; -import org.junit.Test; - -import com.carrotsearch.randomizedtesting.RandomizedTest; -import com.carrotsearch.randomizedtesting.Utils; -import com.carrotsearch.randomizedtesting.WithNestedTestClass; -import com.carrotsearch.randomizedtesting.annotations.TimeoutSuite; - -public class Test006TimeoutAndThreadLeak extends WithNestedTestClass { - /** - * Nested test suite class with {@link TimeoutSuite}. - */ - @TimeoutSuite(millis = 500) - public static class Nested extends ApplyAtPlace {} - - @Test public void testClassRule() { check(Place.CLASS_RULE); } - @Test public void testBeforeClass() { check(Place.BEFORE_CLASS); } - @Test public void testConstructor() { check(Place.CONSTRUCTOR); } - @Test public void testTestRule() { check(Place.TEST_RULE); } - @Test public void testBefore() { check(Place.BEFORE); } - @Test public void testTest() { check(Place.TEST); } - @Test public void testAfter() { check(Place.AFTER); } - @Test public void testAfterClass() { check(Place.AFTER_CLASS); } - - /** - * Check a given timeout place. - */ - private void check(Place p) { - ApplyAtPlace.place = p; - ApplyAtPlace.runnable = new Runnable() { - @Override - public void run() { - startThread("foobar"); - while (true) RandomizedTest.sleep(1000); - } - }; - - FullResult r = runTests(Nested.class); - Utils.assertFailureWithMessage(r, "Suite timeout exceeded"); - Utils.assertFailuresContainSeeds(r); - Utils.assertNoLiveThreadsContaining("foobar"); - - Assertions.assertThat(getLoggingMessages()) - .doesNotContain("Uncaught exception"); - } -} - diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/timeouts/Test007UncaughtExceptions.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/timeouts/Test007UncaughtExceptions.java deleted file mode 100644 index 8e0aa7a2..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/timeouts/Test007UncaughtExceptions.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.carrotsearch.randomizedtesting.timeouts; - -import org.assertj.core.api.Assertions; -import org.junit.Test; - -import com.carrotsearch.randomizedtesting.RandomizedTest; -import com.carrotsearch.randomizedtesting.Utils; -import com.carrotsearch.randomizedtesting.WithNestedTestClass; - -public class Test007UncaughtExceptions extends WithNestedTestClass { - static ThreadGroup parentGroup; - - public static class Nested extends RandomizedTest { - @Test - public void checkGlobal() throws Exception { - assumeRunningNested(); - - final Thread t = new Thread(parentGroup, "XYZ") { - public void run() { - throw new RuntimeException("Yoda died."); - } - }; - - t.start(); - t.join(); - } - } - - @Test - public void testUncaughtExceptionsAtMainGroup() throws Exception { - ThreadGroup parentTg = Thread.currentThread().getThreadGroup(); - while (parentTg.getParent() != null) - parentTg = parentTg.getParent(); - - parentGroup = parentTg; - check(); - } - - @Test - public void testUncaughtExceptionsAtThreadGroup() throws Exception { - parentGroup = null; - check(); - } - - /** - * Apply assertions. - */ - private void check() throws Exception { - FullResult r = runTests(Nested.class); - - Utils.assertFailureWithMessage(r, "Captured an uncaught exception in thread: "); - Utils.assertFailureWithMessage(r, "Yoda died."); - Utils.assertFailuresContainSeeds(r); - Utils.assertNoLiveThreadsContaining("XYZ"); - - Assertions.assertThat(getLoggingMessages()) - .contains("Uncaught exception") - .contains("Yoda died."); - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/timeouts/Test008SeedsAnnotation.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/timeouts/Test008SeedsAnnotation.java deleted file mode 100644 index 164650a0..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/timeouts/Test008SeedsAnnotation.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.carrotsearch.randomizedtesting.timeouts; - -import static org.assertj.core.data.MapEntry.entry; - -import java.util.ArrayList; -import java.util.HashMap; - -import org.assertj.core.api.Assertions; -import org.junit.Test; -import org.junit.Assert; - -import com.carrotsearch.randomizedtesting.RandomizedTest; -import com.carrotsearch.randomizedtesting.Utils; -import com.carrotsearch.randomizedtesting.WithNestedTestClass; -import com.carrotsearch.randomizedtesting.annotations.Repeat; -import com.carrotsearch.randomizedtesting.annotations.Seed; -import com.carrotsearch.randomizedtesting.annotations.Seeds; - - -/** - * Check {@link Seeds}. - */ -public class Test008SeedsAnnotation extends WithNestedTestClass { - final static ArrayList seeds = new ArrayList(); - - public static class Nested extends RandomizedTest { - @Seeds({ - @Seed("deadbeef"), - @Seed("cafebabe"), - @Seed // Adds a randomized execution too. - }) - @Test - @Repeat(iterations = 2, useConstantSeed = true) - public void testMe() { - assumeRunningNested(); - seeds.add(Long.toHexString(Utils.getSeed(getContext().getRandomness()))); - } - } - - @Test - public void checkSeeds() { - HashMap counts = new HashMap(); - int N = 4; - for (int i = 0; i < N; i++) { - seeds.clear(); - FullResult result = runTests(Nested.class); - Assert.assertEquals(3 * 2, result.getRunCount()); - Assertions.assertThat(result.getFailures()).isEmpty(); - for (String s : seeds) { - if (!counts.containsKey(s)) - counts.put(s, 1L); - else - counts.put(s, counts.get(s) + 1); - } - } - - Assertions.assertThat(counts).contains(entry("deadbeef", N * 2L)); - Assertions.assertThat(counts).contains(entry("cafebabe", N * 2L)); - counts.remove("deadbeef"); - counts.remove("cafebabe"); - - // Allow for a single collision. - Assert.assertTrue(counts.size() >= N - 1); - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/timeouts/Test009TimeoutOrNotIdenticalSequence.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/timeouts/Test009TimeoutOrNotIdenticalSequence.java deleted file mode 100644 index 0fc4110b..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/timeouts/Test009TimeoutOrNotIdenticalSequence.java +++ /dev/null @@ -1,68 +0,0 @@ -package com.carrotsearch.randomizedtesting.timeouts; - -import java.util.ArrayList; -import java.util.List; - -import org.assertj.core.api.Assertions; -import org.junit.Test; -import com.carrotsearch.randomizedtesting.RandomizedTest; -import com.carrotsearch.randomizedtesting.WithNestedTestClass; -import com.carrotsearch.randomizedtesting.annotations.Repeat; -import com.carrotsearch.randomizedtesting.annotations.Seed; -import com.carrotsearch.randomizedtesting.annotations.Timeout; - -/** - * It should not matter for the random sequence whether {@link Timeout} is - * used or not. - */ -public class Test009TimeoutOrNotIdenticalSequence extends WithNestedTestClass { - final static ArrayList seeds = new ArrayList(); - - public static class Nested1 extends RandomizedTest { - @Test - @Seed("deadbeef") - @Repeat(iterations = 2, useConstantSeed = false) - public void testNoTimeout() { - assumeRunningNested(); - seeds.add(randomAsciiLettersOfLength(20)); - } - } - - public static class Nested2 extends Nested1 { - @Override - @Test - @Seed("deadbeef") - @Repeat(iterations = 2, useConstantSeed = false) - @Timeout(millis = 30 * 1000) - public void testNoTimeout() { - super.testNoTimeout(); - } - } - - @Timeout(millis = 30 * 1000) - public static class Nested3 extends Nested1 { - @Override - @Test - @Seed("deadbeef") - @Repeat(iterations = 2, useConstantSeed = false) - @Timeout(millis = 30 * 1000) - public void testNoTimeout() { - super.testNoTimeout(); - } - } - - @Test - public void checkAllRunsIdentical() { - List previous = null; - for (Class c : new Class [] {Nested1.class, Nested2.class, Nested3.class}) { - seeds.clear(); - Assertions.assertThat(runTests(c).wasSuccessful()).isTrue(); - - if (previous != null) { - Assertions.assertThat(seeds).as("Class " + c.getSimpleName()).isEqualTo(previous); - } else { - previous = new ArrayList<>(seeds); - } - } - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/timeouts/Test010Zombies.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/timeouts/Test010Zombies.java deleted file mode 100644 index fb7c3d24..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/timeouts/Test010Zombies.java +++ /dev/null @@ -1,78 +0,0 @@ -package com.carrotsearch.randomizedtesting.timeouts; - -import org.assertj.core.api.Assertions; -import org.junit.Rule; -import org.junit.Test; - -import com.carrotsearch.randomizedtesting.SysGlobals; -import com.carrotsearch.randomizedtesting.Utils; -import com.carrotsearch.randomizedtesting.WithNestedTestClass; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakAction; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakAction.Action; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakLingering; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope.Scope; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakZombies; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakZombies.Consequence; -import com.carrotsearch.randomizedtesting.rules.SystemPropertiesRestoreRule; - -public class Test010Zombies extends WithNestedTestClass { - @ThreadLeakScope(Scope.TEST) - @ThreadLeakLingering(linger = 0) - @ThreadLeakAction({Action.INTERRUPT}) - @ThreadLeakZombies(Consequence.IGNORE_REMAINING_TESTS) - public static class Nested extends ApplyAtPlace {} - - @Test public void testClassRule() { check(Place.CLASS_RULE); } - @Test public void testBeforeClass() { check(Place.BEFORE_CLASS); } - @Test public void testConstructor() { check(Place.CONSTRUCTOR); } - @Test public void testTestRule() { check(Place.TEST_RULE); } - @Test public void testBefore() { check(Place.BEFORE); } - @Test public void testTest() { check(Place.TEST); } - @Test public void testAfter() { check(Place.AFTER); } - @Test public void testAfterClass() { check(Place.AFTER_CLASS); } - - @Rule - public SystemPropertiesRestoreRule restoreProperties = new SystemPropertiesRestoreRule(); - - /** - * Start a zombie thread somewhere. Ensure all suites are ignored afterwards. - */ - private void check(Place p) { - System.setProperty(SysGlobals.SYSPROP_KILLWAIT(), "10"); - System.setProperty(SysGlobals.SYSPROP_KILLATTEMPTS(), "2"); - - ApplyAtPlace.place = p; - ApplyAtPlace.runnable = new Runnable() { - @Override - public void run() { - startZombieThread("foobarZombie"); - } - }; - - // Run a class spawning zombie threads. - FullResult r = runTests(Nested.class); - - Utils.assertFailureWithMessage(r, "1 thread leaked"); - Utils.assertFailureWithMessage(r, "foobarZombie"); - Utils.assertFailuresContainSeeds(r); - - Assertions.assertThat(getLoggingMessages()) - .contains("There are still zombie threads that couldn't be terminated:"); - - // Run another suite. Everything should be ignored because of zombie threads. - for (Place p2 : Place.values()) { - ApplyAtPlace.place = p2; - ApplyAtPlace.runnable = new Runnable() { - @Override - public void run() { - throw new RuntimeException(); - } - }; - - r = runTests(Nested.class); - Assertions.assertThat(r.wasSuccessful()).as("At: " + p2).isTrue(); - } - } -} - diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/timeouts/Test011RunawayThreads.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/timeouts/Test011RunawayThreads.java deleted file mode 100644 index f2116b9c..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/timeouts/Test011RunawayThreads.java +++ /dev/null @@ -1,158 +0,0 @@ -package com.carrotsearch.randomizedtesting.timeouts; - -import java.util.concurrent.*; - -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.*; -import org.junit.runner.notification.Failure; - -import com.carrotsearch.randomizedtesting.RandomizedContext; -import com.carrotsearch.randomizedtesting.RandomizedRunner; -import com.carrotsearch.randomizedtesting.RandomizedTest; -import com.carrotsearch.randomizedtesting.Utils; -import com.carrotsearch.randomizedtesting.WithNestedTestClass; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakLingering; - -@RunWith(RandomizedRunner.class) -public class Test011RunawayThreads extends WithNestedTestClass { - private abstract static class ThreadWithException extends Thread { - public volatile Throwable throwable; - - @Override - public final void run() { - try { - runWrapped(); - } catch (Throwable t) { - throwable = t; - } - } - - public final ThreadWithException startAndJoin() throws Throwable { - this.start(); - try { - this.join(5000); - if (throwable != null) throw throwable; - } catch (InterruptedException e) { - throw e; - } - return this; - } - - protected abstract void runWrapped(); - } - - @Test - public void subThreadContextPropagation() throws Throwable { - final long seed = Utils.getRunnerSeed(); - new ThreadWithException() { - protected void runWrapped() { - RandomizedContext ctx = RandomizedContext.current(); - Assert.assertEquals(seed, Utils.getSeed(ctx.getRandomness())); - } - }.startAndJoin(); - } - - @ThreadLeakLingering(linger = 2000) - @Test - public void ExecutorServiceContextPropagation() throws Throwable { - final long seed = Utils.getRunnerSeed(); - final ExecutorService executor = Executors.newCachedThreadPool(); - try { - executor.submit(new Runnable() { - public void run() { - RandomizedContext ctx = RandomizedContext.current(); - Assert.assertEquals(seed, Utils.getSeed(ctx.getRandomness())); - } - }).get(); - } catch (ExecutionException e) { - throw e.getCause(); - } finally { - executor.shutdown(); - executor.awaitTermination(1, TimeUnit.SECONDS); - } - } - - public static class Nested extends RandomizedTest { - final boolean withJoin; - - public Nested() { - this(true); - } - - protected Nested(boolean withJoin) { - this.withJoin = withJoin; - } - - @Test - public void spinoffAndThrow() throws Exception{ - assumeRunningNested(); - Thread t = new Thread() { - public void run() { - RandomizedTest.sleep(500); - throw new RuntimeException("spinoff exception"); - } - }; - t.start(); - if (withJoin) { - t.join(); - } - } - } - - public static class NestedNoJoin extends Nested { - public NestedNoJoin() { - super(false); - } - } - - @Test - public void subUncaughtExceptionInSpunOffThread() throws Throwable { - FullResult r = runTests(Nested.class); - Assert.assertEquals(1, r.getFailureCount()); - Failure testFailure = r.getFailures().get(0); - Throwable testException = testFailure.getException(); - Throwable threadException = testException.getCause(); - Assert.assertNotNull(RandomizedRunner.seedFromThrowable(testException)); - Assert.assertNotNull(RandomizedRunner.seedFromThrowable(threadException)); - } - - @Test - public void subNotJoined() throws Throwable { - FullResult r = runTests(NestedNoJoin.class); - Assert.assertEquals(1, r.getFailureCount()); - Failure testFailure = r.getFailures().get(0); - Throwable testException = testFailure.getException(); - Assert.assertNotNull(RandomizedRunner.seedFromThrowable(testException)); - } - - public static class NestedClassScope extends RandomizedTest { - @BeforeClass - public static void startThread() { - if (!isRunningNested()) - return; - - new Thread() { - @Override - public void run() { - RandomizedTest.sleep(5000); - } - }.start(); - } - - @Test - public void spinoffAndThrow() throws Exception{ - assumeRunningNested(); - } - } - - @Test - public void subNotJoinOnClassLevel() throws Throwable { - FullResult r = runTests(NestedClassScope.class); - Assert.assertEquals(1, r.getFailureCount()); - Failure testFailure = r.getFailures().get(0); - Throwable testException = testFailure.getException(); - Assert.assertNotNull(RandomizedRunner.seedFromThrowable(testException)); - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/timeouts/Test012RunawayThreadsKilledAtOnce.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/timeouts/Test012RunawayThreadsKilledAtOnce.java deleted file mode 100644 index bf37d0e7..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/timeouts/Test012RunawayThreadsKilledAtOnce.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.carrotsearch.randomizedtesting.timeouts; - -import java.util.concurrent.CountDownLatch; - -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.*; - -import com.carrotsearch.randomizedtesting.RandomizedRunner; -import com.carrotsearch.randomizedtesting.WithNestedTestClass; - -@RunWith(RandomizedRunner.class) -public class Test012RunawayThreadsKilledAtOnce extends WithNestedTestClass { - @RunWith(RandomizedRunner.class) - public static class NestedClass { - @Test - public void lotsOfStubbornThreads() throws Throwable { - assumeRunningNested(); - final CountDownLatch latch = new CountDownLatch(50); - - Thread [] threads = new Thread [(int) latch.getCount()]; - for (int i = 0; i < threads.length; i++) { - threads[i] = new Thread("stubborn-" + i) { - @Override - public void run() { - latch.countDown(); - - try { - Thread.sleep(20000); - } catch (InterruptedException e) { - // Ignore - } - } - }; - threads[i].start(); - } - - // Wait for all threads to be really started. - latch.await(); - } - } - - @Test - public void testLotsOfStubbornThreads() { - long start = System.currentTimeMillis(); - FullResult result = runTests(NestedClass.class); - long end = System.currentTimeMillis(); - - Assert.assertEquals(1, result.getFailureCount()); - Assert.assertTrue((end - start) + " msec?", (end - start) < 1000 * 10); - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/timeouts/Test013ThreadLeaksScopeNone.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/timeouts/Test013ThreadLeaksScopeNone.java deleted file mode 100644 index 656e51d1..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/timeouts/Test013ThreadLeaksScopeNone.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.carrotsearch.randomizedtesting.timeouts; - -import org.assertj.core.api.Assertions; -import org.junit.Assert; -import org.junit.Test; - -import com.carrotsearch.randomizedtesting.WithNestedTestClass; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope.Scope; - -public class Test013ThreadLeaksScopeNone extends WithNestedTestClass { - @ThreadLeakScope(Scope.NONE) - public static class Nested extends ApplyAtPlace {} - - @Test public void testClassRule() { testLeak(Place.CLASS_RULE); } - @Test public void testBeforeClass() { testLeak(Place.BEFORE_CLASS); } - @Test public void testConstructor() { testLeak(Place.CONSTRUCTOR); } - @Test public void testTestRule() { testLeak(Place.TEST_RULE); } - @Test public void testBefore() { testLeak(Place.BEFORE); } - @Test public void testTest() { testLeak(Place.TEST); } - @Test public void testAfter() { testLeak(Place.AFTER); } - @Test public void testAfterClass() { testLeak(Place.AFTER_CLASS); } - - private void testLeak(Place p) { - ApplyAtPlace.place = p; - ApplyAtPlace.runnable = new Runnable() { - @Override - public void run() { - startZombieThread("foobar"); - } - }; - - FullResult r = runTests(Nested.class); - Assert.assertEquals(0, r.getFailureCount()); - - Assertions.assertThat(getLoggingMessages()).isEmpty(); - Assertions.assertThat(getSysouts()).isEmpty(); - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/timeouts/Test014Timeout.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/timeouts/Test014Timeout.java deleted file mode 100644 index 7d91ae75..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/timeouts/Test014Timeout.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.carrotsearch.randomizedtesting.timeouts; - -import org.junit.Test; -import org.junit.Assert; - -import com.carrotsearch.randomizedtesting.RandomizedTest; -import com.carrotsearch.randomizedtesting.WithNestedTestClass; - -/** - * Test {@link Test#timeout()}. - */ -public class Test014Timeout extends WithNestedTestClass { - public static class Nested extends RandomizedTest { - @Test(timeout = 100) - public void testMethod1() { - assumeRunningNested(); - sleep(2000); - } - - @Test(timeout = 100) - public void testMethod2() { - assumeRunningNested(); - while (!Thread.interrupted()) { - // Do nothing. - } - } - } - - @Test - public void testTimeoutInTestAnnotation() { - FullResult result = runTests(Nested.class); - - Assert.assertEquals(0, result.getIgnoreCount()); - Assert.assertEquals(2, result.getRunCount()); - Assert.assertEquals(2, result.getFailureCount()); - Assert.assertEquals(0, result.getAssumptionIgnored()); - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/timeouts/Test015TimeoutOverride.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/timeouts/Test015TimeoutOverride.java deleted file mode 100644 index 52f9d042..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/timeouts/Test015TimeoutOverride.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.carrotsearch.randomizedtesting.timeouts; - -import org.junit.After; -import org.junit.Test; -import org.junit.Assert; - -import com.carrotsearch.randomizedtesting.RandomizedTest; -import com.carrotsearch.randomizedtesting.SysGlobals; -import com.carrotsearch.randomizedtesting.WithNestedTestClass; -import com.carrotsearch.randomizedtesting.annotations.Timeout; - - -/** - * Test global timeout override (-Dtests.timeout=1000!). - */ -public class Test015TimeoutOverride extends WithNestedTestClass { - public static class Nested extends RandomizedTest { - @Test - @Timeout(millis = 5000) - public void testMethod1() { - assumeRunningNested(); - sleep(10000); - } - } - - public static class Nested2 extends RandomizedTest { - @Test - @Timeout(millis = 100) - public void testMethod1() { - assumeRunningNested(); - sleep(1000); - } - } - - @Test - public void testTimeoutOverride() { - System.setProperty(SysGlobals.SYSPROP_TIMEOUT(), "200!"); - long start = System.currentTimeMillis(); - FullResult result = runTests(Nested.class); - long end = System.currentTimeMillis(); - Assert.assertEquals(1, result.getFailureCount()); - Assert.assertTrue(end - start < 3000); - } - - @Test - public void testDisableTimeout() { - System.setProperty(SysGlobals.SYSPROP_TIMEOUT(), "0!"); - - long start = System.currentTimeMillis(); - FullResult result = runTests(Nested2.class); - long end = System.currentTimeMillis(); - Assert.assertEquals(0, result.getFailureCount()); - Assert.assertTrue(end - start > 900); - } - - @After - public void cleanup() { - System.clearProperty(SysGlobals.SYSPROP_TIMEOUT()); - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/timeouts/Test016ThreadLeaksCustomFilters.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/timeouts/Test016ThreadLeaksCustomFilters.java deleted file mode 100644 index 7fecc25f..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/timeouts/Test016ThreadLeaksCustomFilters.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.carrotsearch.randomizedtesting.timeouts; - -import org.assertj.core.api.Assertions; -import org.junit.Test; - -import com.carrotsearch.randomizedtesting.RandomizedTest; -import com.carrotsearch.randomizedtesting.ThreadFilter; -import com.carrotsearch.randomizedtesting.WithNestedTestClass; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakFilters; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope.Scope; - -/** - * Checks custom thread ignore policy. - */ -public class Test016ThreadLeaksCustomFilters extends WithNestedTestClass { - public static class FooBarFilter implements ThreadFilter { - @Override - public boolean reject(Thread t) { - return t.getName().contains("foobar"); - } - } - - @ThreadLeakScope(Scope.TEST) - @ThreadLeakFilters(defaultFilters = true, filters = { - FooBarFilter.class - }) - public static class Nested1 extends RandomizedTest { - @Test - public void testFooBars() throws Exception { - assumeRunningNested(); - for (int i = 0; i < 10; i++) { - startZombieThread("foobar-" + i); - } - } - } - - @Test - public void testFilteredOnly() throws Throwable { - Assertions.assertThat(runTests(Nested1.class).getFailures()).isEmpty(); - - Assertions.assertThat(getLoggingMessages()).isEmpty(); - Assertions.assertThat(getSysouts()).isEmpty(); - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/timeouts/Test017ThreadLeaksCustomFiltersException.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/timeouts/Test017ThreadLeaksCustomFiltersException.java deleted file mode 100644 index 0aafc16d..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/timeouts/Test017ThreadLeaksCustomFiltersException.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.carrotsearch.randomizedtesting.timeouts; - -import org.junit.Test; - -import com.carrotsearch.randomizedtesting.RandomizedTest; -import com.carrotsearch.randomizedtesting.ThreadFilter; -import com.carrotsearch.randomizedtesting.Utils; -import com.carrotsearch.randomizedtesting.WithNestedTestClass; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakFilters; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope.Scope; - -/** - * Checks custom thread ignore policy. - */ -public class Test017ThreadLeaksCustomFiltersException extends WithNestedTestClass { - public static class ExceptionFilter implements ThreadFilter { - @Override - public boolean reject(Thread t) { - if (!isRunningNested()) { - return false; - } - throw new RuntimeException("filter-exception"); - } - } - - @ThreadLeakScope(Scope.TEST) - @ThreadLeakFilters(defaultFilters = true, filters = { - ExceptionFilter.class - }) - public static class Nested1 extends RandomizedTest { - @Test - public void testFooBars() throws Exception { - assumeRunningNested(); - for (int i = 0; i < 10; i++) { - startZombieThread("foobar-" + i); - } - } - } - - @Test - public void testExceptionInFilter() throws Throwable { - FullResult r = runTests(Nested1.class); - Utils.assertFailureWithMessage(r, "filter-exception"); - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/timeouts/Test018TimeoutStacks.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/timeouts/Test018TimeoutStacks.java deleted file mode 100644 index c885917a..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/timeouts/Test018TimeoutStacks.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.carrotsearch.randomizedtesting.timeouts; - -import org.assertj.core.api.Assertions; -import org.junit.Test; -import org.junit.runner.JUnitCore; - -import com.carrotsearch.randomizedtesting.RandomizedRunner; -import com.carrotsearch.randomizedtesting.WithNestedTestClass; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope.Scope; -import com.carrotsearch.randomizedtesting.annotations.TimeoutSuite; - -/** - * Checks custom thread ignore policy. - */ -public class Test018TimeoutStacks extends WithNestedTestClass { - @ThreadLeakScope(Scope.TEST) - @TimeoutSuite(millis = 1000) - public static class Nested1 { - @Test - public void testFooBars() throws Exception { - assumeRunningNested(); - for (int i = 0; i < 5; i++) { - startThread("foobar-" + i); - } - Thread.sleep(5000); - } - } - - @Test - public void testExceptionInFilter() throws Throwable { - new JUnitCore().run(new RandomizedRunner(Nested1.class)); - Assertions.assertThat(getLoggingMessages()).contains("sleepForever("); - // sysout.println(getLoggingMessages()); - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/timeouts/Test019ThreadLeakGroup.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/timeouts/Test019ThreadLeakGroup.java deleted file mode 100644 index 4ea93ce9..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/timeouts/Test019ThreadLeakGroup.java +++ /dev/null @@ -1,83 +0,0 @@ -package com.carrotsearch.randomizedtesting.timeouts; - -import java.util.concurrent.CountDownLatch; - -import org.assertj.core.api.Assertions; -import org.junit.After; -import org.junit.Test; - -import com.carrotsearch.randomizedtesting.RandomizedTest; -import com.carrotsearch.randomizedtesting.Utils; -import com.carrotsearch.randomizedtesting.WithNestedTestClass; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakGroup; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakGroup.Group; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope.Scope; - -/** - * Checks thread leak detection group. - */ -public class Test019ThreadLeakGroup extends WithNestedTestClass { - volatile static Thread t; - - @ThreadLeakScope(Scope.TEST) - @ThreadLeakGroup(Group.TESTGROUP) - public static class Nested1 extends RandomizedTest { - @Test - public void testLeakOutsideOfGroup() throws Exception { - assumeRunningNested(); - - final CountDownLatch latch = new CountDownLatch(1); - ThreadGroup newTopGroup = new ThreadGroup(Utils.getTopThreadGroup(), "foobar-group"); - t = new Thread(newTopGroup, "foobar") { - @Override - public void run() { - try { - latch.countDown(); - Thread.sleep(5000); - } catch (InterruptedException e) {} - } - }; - t.start(); - latch.await(); - } - } - - @ThreadLeakGroup(Group.MAIN) - public static class Nested2 extends Nested1 { - } - - @ThreadLeakGroup(Group.ALL) - public static class Nested3 extends Nested1 { - } - - @Test - public void testTestGroup() throws Throwable { - FullResult r = runTests(Nested1.class); - Assertions.assertThat(r.getFailures()).isEmpty(); - Assertions.assertThat(t != null && t.isAlive()).isTrue(); - } - - @Test - public void testMainGroup() throws Throwable { - FullResult r = runTests(Nested2.class); - Assertions.assertThat(r.getFailures()).isEmpty(); - Assertions.assertThat(t != null && t.isAlive()).isTrue(); - } - - @Test - public void testAll() throws Throwable { - FullResult r = runTests(Nested3.class); - Utils.assertNoLiveThreadsContaining("foobar"); - Utils.assertFailureWithMessage(r, "1 thread leaked from TEST"); - } - - @After - public void cleanup() throws Exception { - if (t != null) { - t.interrupt(); - t.join(); - t = null; - } - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/timeouts/Test020SuiteTimeoutStopsTests.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/timeouts/Test020SuiteTimeoutStopsTests.java deleted file mode 100644 index e61c5f22..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/timeouts/Test020SuiteTimeoutStopsTests.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.carrotsearch.randomizedtesting.timeouts; - -import java.util.concurrent.atomic.AtomicInteger; - -import org.assertj.core.api.Assertions; -import org.junit.BeforeClass; -import org.junit.Test; - -import com.carrotsearch.randomizedtesting.RandomizedTest; -import com.carrotsearch.randomizedtesting.WithNestedTestClass; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakLingering; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope.Scope; -import com.carrotsearch.randomizedtesting.annotations.TimeoutSuite; - -/** - * Checks custom thread ignore policy. - */ -public class Test020SuiteTimeoutStopsTests extends WithNestedTestClass { - @ThreadLeakScope(Scope.SUITE) - @TimeoutSuite(millis = 500) - @ThreadLeakLingering(linger = 0) - public static class Nested1 extends RandomizedTest { - @Test - public void test001() { idle("1"); } - @Test - public void test002() { idle("2"); } - @Test - public void test003() { idle("3"); } - @Test - public void test004() { idle("4"); } - @Test - public void test005() { idle("5"); } - @Test - public void test006() { idle("6"); } - - private static AtomicInteger executedTests; - - @BeforeClass - private static void setup() { - assumeRunningNested(); - executedTests = new AtomicInteger(); - } - - private void idle(String m) { - if (executedTests.getAndIncrement() == 0) { - System.out.println("before timeout(" + m + ")"); - try { - while (true) { Thread.sleep(1000); } - } catch (InterruptedException e) { - System.out.println("suite timeout(" + m + ")"); - // Suite timeout. - return; - } - } else { - System.out.println("after timeout(" + m + ")"); - } - } - } - - @Test - public void testExceptionInFilter() throws Throwable { - runTests(Nested1.class); - Assertions.assertThat(getSysouts()).doesNotContain("after timeout"); - sysout.println(getLoggingMessages()); - } -} diff --git a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/timeouts/Test021SuiteTimeoutHanging.java b/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/timeouts/Test021SuiteTimeoutHanging.java deleted file mode 100644 index 7398e058..00000000 --- a/randomized-runner/src/test/java/com/carrotsearch/randomizedtesting/timeouts/Test021SuiteTimeoutHanging.java +++ /dev/null @@ -1,99 +0,0 @@ -package com.carrotsearch.randomizedtesting.timeouts; - -import com.carrotsearch.randomizedtesting.RandomizedTest; -import com.carrotsearch.randomizedtesting.SysGlobals; -import com.carrotsearch.randomizedtesting.WithNestedTestClass; -import com.carrotsearch.randomizedtesting.annotations.*; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope.Scope; -import org.assertj.core.api.Assertions; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.notification.Failure; - -import java.util.ArrayList; -import java.util.Locale; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicReference; - -/** - * Checks custom thread ignore policy. - */ -public class Test021SuiteTimeoutHanging extends WithNestedTestClass { - private static AtomicBoolean stop; - private static ArrayList waitQueue = new ArrayList<>(); - - @ThreadLeakScope(Scope.SUITE) - @ThreadLeakLingering(linger = 0) - @ThreadLeakAction({ThreadLeakAction.Action.WARN, ThreadLeakAction.Action.INTERRUPT}) - @ThreadLeakZombies(ThreadLeakZombies.Consequence.IGNORE_REMAINING_TESTS) - @TimeoutSuite(millis = 1000) - @TestCaseOrdering(TestCaseOrdering.AlphabeticOrder.class) - public static class Nested1 extends RandomizedTest { - @Test - public void test001() throws Exception { - synchronized (Thread.currentThread()) { - waitQueue.add(Thread.currentThread()); - while (!stop.get()) { - try { - Thread.sleep(250); - } catch (InterruptedException e) { - // If interrupted, just continue. Don't release the lock. - System.out.println("Interrupted."); - } - System.out.println("Still running."); - } - } - } - - @Test - public void test002() throws Exception { - // Should not be executed. - throw new Exception(); - } - - @BeforeClass - private static void setup() { - assumeRunningNested(); - } - } - - @Test - public void testThreadLeakInterruptsIsNotHangingOnJoin() throws Throwable { - stop = new AtomicBoolean(); - - System.setProperty(SysGlobals.SYSPROP_KILLATTEMPTS(), "1"); - AtomicReference result = new AtomicReference<>(); - Thread tester = new Thread(() -> { - waitQueue.add(Thread.currentThread()); - result.set(runTests(Nested1.class)); - }); - tester.start(); - - long deadline = System.currentTimeMillis() + 10000; - while (System.currentTimeMillis() < deadline && tester.isAlive()) { - Thread.sleep(250); - } - - boolean testerAlive = tester.isAlive(); - - // Wait for all threads to die. - stop.set(true); - for (Thread t : waitQueue) { - t.join(); - } - System.clearProperty(SysGlobals.SYSPROP_KILLATTEMPTS()); - - // Make sure the tester was dead when we left the long wait loop. This - // indicates the framework abandoned the thread it couldn't interrupt. - Assertions.assertThat(testerAlive).isFalse(); - - // Only one test executed. - Assertions.assertThat(result.get().getRunCount()).isEqualTo(1); - - // Make sure suite timeouts have been reported. - for (Failure failure : result.get().getFailures()) { - Assertions.assertThat(failure.getMessage().toLowerCase(Locale.ROOT)) - .contains("suite timeout"); - } - } -} diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 00000000..3a343824 --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1,4 @@ +rootProject.name = "randomizedtesting" + +include("core") +include("examples") \ No newline at end of file diff --git a/src/site/site.xml b/src/site/site.xml deleted file mode 100644 index 2d1643b3..00000000 --- a/src/site/site.xml +++ /dev/null @@ -1,30 +0,0 @@ - - - - Randomized Testing - - - - org.apache.maven.skins - maven-fluido-skin - 1.5 - - - - - - - - - - - - - - - - - -