|
| 1 | +package com.carrotsearch.gradle.junit4 |
| 2 | + |
| 3 | +import com.carrotsearch.ant.tasks.junit4.JUnit4 |
| 4 | +import org.gradle.api.Plugin |
| 5 | +import org.gradle.api.Project |
| 6 | +import org.gradle.api.tasks.TaskContainer |
| 7 | + |
| 8 | +class RandomizedTestingPlugin implements Plugin<Project> { |
| 9 | + |
| 10 | + void apply(Project project) { |
| 11 | + String seed = setupSeed(project) |
| 12 | + createUnitTestTask(project.tasks) |
| 13 | + configureAnt(project.ant, seed) |
| 14 | + } |
| 15 | + |
| 16 | + /** |
| 17 | + * Pins the test seed at configuration time so it isn't different on every |
| 18 | + * {@link RandomizedTestingTask} execution. This is useful if random |
| 19 | + * decisions in one run of {@linkplain RandomizedTestingTask} influence the |
| 20 | + * outcome of subsequent runs. Pinning the seed up front like this makes |
| 21 | + * the reproduction line from one run be useful on another run. |
| 22 | + */ |
| 23 | + static String setupSeed(Project project) { |
| 24 | + if (project.rootProject.ext.has('testSeed')) { |
| 25 | + /* Skip this if we've already pinned the testSeed. It is important |
| 26 | + * that this checks the rootProject so that we know we've only ever |
| 27 | + * initialized one time. */ |
| 28 | + return project.rootProject.ext.testSeed |
| 29 | + } |
| 30 | + String testSeed = System.getProperty('tests.seed') |
| 31 | + if (testSeed == null) { |
| 32 | + long seed = new Random(System.currentTimeMillis()).nextLong() |
| 33 | + testSeed = Long.toUnsignedString(seed, 16).toUpperCase(Locale.ROOT) |
| 34 | + } |
| 35 | + /* Set the testSeed on the root project first so other projects can use |
| 36 | + * it during initialization. */ |
| 37 | + project.rootProject.ext.testSeed = testSeed |
| 38 | + project.rootProject.subprojects { |
| 39 | + project.ext.testSeed = testSeed |
| 40 | + } |
| 41 | + |
| 42 | + return testSeed |
| 43 | + } |
| 44 | + |
| 45 | + static void createUnitTestTask(TaskContainer tasks) { |
| 46 | + // only create a unitTest task if the `test` task exists as some project don't make use of it. |
| 47 | + tasks.matching { it.name == "test" }.all { |
| 48 | + // We don't want to run any tests with the Gradle test runner since we add our own randomized runner |
| 49 | + it.enabled = false |
| 50 | + RandomizedTestingTask unitTest = tasks.create('unitTest', RandomizedTestingTask) |
| 51 | + unitTest.description = 'Runs unit tests with the randomized testing framework' |
| 52 | + it.dependsOn unitTest |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + static void configureAnt(AntBuilder ant, String seed) { |
| 57 | + ant.project.addTaskDefinition('junit4:junit4', JUnit4.class) |
| 58 | + ant.properties.put('tests.seed', seed) |
| 59 | + } |
| 60 | +} |
0 commit comments