aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/java_tools/junitrunner
diff options
context:
space:
mode:
authorGravatar Kush Chakraborty <kush@google.com>2017-02-23 06:17:21 +0000
committerGravatar Yue Gan <yueg@google.com>2017-02-23 11:32:55 +0000
commit786cfa2ed980e278c42ee474408844f7e3720385 (patch)
tree3d5e69262a4ac9d59e4bb4bb10ff431ded4263bd /src/java_tools/junitrunner
parentc9333b4996679c7f7120ff6dad087790b34908f6 (diff)
Separate the classpaths of the TestRunner with the test target, and use a separate Classloader to load the test target's classes. This enables a clean separation of the classes of the TestRunner with the target under test.
This is achieved with the following steps: 1. Start the test runner with only the bare bones classpaths to the Test Runner's classes which are used by the system ClassLoader. 2. Have all the classpaths required to load the test target's classes in a TEST_TARGET_CLASSPATH environment variable exported by the stub script. 3. Use a new classloader to load all the test target's classes using the paths in TEST_TARGET_CLASSPATH. This additionally enables the persistent test runner (currently experimental), to reload all the target's classes for every subsequent test run, so it can pick up any changes to the classes in between runs. The persistent test runner can be used by adding the argument --test_strategy=experimental_worker to the bazel test command. Tested this against: 1. gerrit/gerrit-common:client_tests: Dismal avg. improvement of 580ms to 557ms (just 23ms) 2. intellij/intellij/base:unit_tests: Somewhat modest avg. improvement 1661ms to 913ms (748 ms) RELNOTES: 1) Java tests and suites will now have to explicitly declare JUnit dependency 2) All non-legacy java_tests will now be run in a -- PiperOrigin-RevId: 148309979 MOS_MIGRATED_REVID=148309979
Diffstat (limited to 'src/java_tools/junitrunner')
-rw-r--r--src/java_tools/junitrunner/java/com/google/testing/junit/runner/BUILD1
-rw-r--r--src/java_tools/junitrunner/java/com/google/testing/junit/runner/BazelTestRunner.java123
-rw-r--r--src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/BUILD14
-rwxr-xr-xsrc/java_tools/junitrunner/javatests/com/google/testing/junit/runner/antxmlresultwriter_integration_test.sh4
-rwxr-xr-xsrc/java_tools/junitrunner/javatests/com/google/testing/junit/runner/junit4_testbridge_integration_tests.sh7
-rwxr-xr-xsrc/java_tools/junitrunner/javatests/com/google/testing/junit/runner/utf8_test_log_test.sh4
6 files changed, 141 insertions, 12 deletions
diff --git a/src/java_tools/junitrunner/java/com/google/testing/junit/runner/BUILD b/src/java_tools/junitrunner/java/com/google/testing/junit/runner/BUILD
index 1699cb882b..71a715a85a 100644
--- a/src/java_tools/junitrunner/java/com/google/testing/junit/runner/BUILD
+++ b/src/java_tools/junitrunner/java/com/google/testing/junit/runner/BUILD
@@ -17,6 +17,7 @@ java_library(
"//src/java_tools/junitrunner/java/com/google/testing/junit/runner/model",
"//src/java_tools/junitrunner/java/com/google/testing/junit/runner/sharding",
"//src/java_tools/junitrunner/java/com/google/testing/junit/runner/util",
+ "//src/main/protobuf:worker_protocol_java_proto",
"//third_party:junit4",
],
)
diff --git a/src/java_tools/junitrunner/java/com/google/testing/junit/runner/BazelTestRunner.java b/src/java_tools/junitrunner/java/com/google/testing/junit/runner/BazelTestRunner.java
index 74a6826f88..3f4c966d94 100644
--- a/src/java_tools/junitrunner/java/com/google/testing/junit/runner/BazelTestRunner.java
+++ b/src/java_tools/junitrunner/java/com/google/testing/junit/runner/BazelTestRunner.java
@@ -14,13 +14,20 @@
package com.google.testing.junit.runner;
+import com.google.devtools.build.lib.worker.WorkerProtocol.WorkRequest;
+import com.google.devtools.build.lib.worker.WorkerProtocol.WorkResponse;
import com.google.testing.junit.runner.internal.StackTraces;
import com.google.testing.junit.runner.junit4.JUnit4InstanceModules.Config;
import com.google.testing.junit.runner.junit4.JUnit4InstanceModules.SuiteClass;
import com.google.testing.junit.runner.junit4.JUnit4Runner;
import com.google.testing.junit.runner.model.AntXmlResultWriter;
import com.google.testing.junit.runner.model.XmlResultWriter;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
import java.io.PrintStream;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.net.URLClassLoader;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
@@ -48,6 +55,9 @@ public class BazelTestRunner {
*/
static final String TEST_SUITE_PROPERTY_NAME = "bazel.test_suite";
+ private static URL[] classpaths = null;
+ private static URLClassLoader targetClassLoader;
+
private BazelTestRunner() {
// utility class; should not be instantiated
}
@@ -72,9 +82,8 @@ public class BazelTestRunner {
String suiteClassName = System.getProperty(TEST_SUITE_PROPERTY_NAME);
- if (args.length >= 1 && args[args.length - 1].equals("--persistent_test_runner")) {
- System.err.println("Requested test strategy is currently unsupported.");
- System.exit(1);
+ if ("true".equals(System.getenv("PERSISTENT_TEST_RUNNER"))) {
+ System.exit(runPersistentTestRunner(suiteClassName));
}
if (!checkTestSuiteProperty(suiteClassName)) {
@@ -126,7 +135,7 @@ public class BazelTestRunner {
}
private static int runTestsInSuite(String suiteClassName, String[] args) {
- Class<?> suite = getTestClass(suiteClassName);
+ Class<?> suite = getTargetSuiteClass(suiteClassName);
if (suite == null) {
// No class found corresponding to the system property passed in from Bazel
@@ -136,29 +145,123 @@ public class BazelTestRunner {
}
}
- // TODO(kush): Use a new classloader for the following instantiation.
JUnit4Runner runner =
JUnit4Bazel.builder()
.suiteClass(new SuiteClass(suite))
.config(new Config(args))
.build()
.runner();
- return runner.run().wasSuccessful() ? 0 : 1;
+
+ // Some frameworks such as Mockito use the Thread's context classloader.
+ Thread.currentThread().setContextClassLoader(targetClassLoader);
+
+ int result = 1;
+ try {
+ result = runner.run().wasSuccessful() ? 0 : 1;
+ } catch (RuntimeException e) {
+ System.err.println("Test run failed with exception");
+ e.printStackTrace();
+ }
+ return result;
}
- private static Class<?> getTestClass(String name) {
- if (name == null) {
+ /**
+ * Run in a loop awaiting instructions for the next test run.
+ *
+ * @param suiteClassName name of the class which is passed on to JUnit to determine the test suite
+ * @return 0 when we encounter an EOF from input, or non-zero values if we encounter an
+ * unrecoverable error.
+ */
+ private static int runPersistentTestRunner(String suiteClassName) {
+ PrintStream originalStdOut = System.out;
+ PrintStream originalStdErr = System.err;
+
+ while (true) {
+ try {
+ WorkRequest request = WorkRequest.parseDelimitedFrom(System.in);
+
+ if (request == null) {
+ break;
+ }
+ ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
+ PrintStream printStream = new PrintStream(outputStream, true);
+ System.setOut(printStream);
+ System.setErr(printStream);
+ String[] arguments = request.getArgumentsList().toArray(new String[0]);
+ int exitCode = -1;
+ try {
+ exitCode = runTestsInSuite(suiteClassName, arguments);
+ } finally {
+ System.setOut(originalStdOut);
+ System.setErr(originalStdErr);
+ }
+
+ WorkResponse response =
+ WorkResponse
+ .newBuilder()
+ .setOutput(outputStream.toString())
+ .setExitCode(exitCode)
+ .build();
+ response.writeDelimitedTo(System.out);
+ System.out.flush();
+
+ } catch (IOException e) {
+ e.printStackTrace();
+ return 1;
+ }
+ }
+ return 0;
+ }
+
+ /**
+ * Get the actual Test Suite class corresponding to the given name.
+ */
+ private static Class<?> getTargetSuiteClass(String suiteClassName) {
+ if (suiteClassName == null) {
return null;
}
try {
- return Class.forName(name);
- } catch (ClassNotFoundException e) {
+ targetClassLoader = new URLClassLoader(getClasspaths());
+ Class<?> targetSuiteClass = targetClassLoader.loadClass(suiteClassName);
+ System.out.printf(
+ "Running test suites for class: %s, created by classLoader: %s%n",
+ targetSuiteClass, targetSuiteClass.getClassLoader());
+ return targetSuiteClass;
+ } catch (ClassNotFoundException | MalformedURLException e) {
+ System.err.println("Exception in loading class:" + e.getMessage());
return null;
}
}
/**
+ * Used to get the classpaths which should be used to load the classes of the test target.
+ *
+ * @throws MalformedURLException when we are unable to create a given classpath.
+ * @return array of URLs containing the classpaths or null if classpaths could not be located.
+ */
+ private static URL[] getClasspaths() throws MalformedURLException {
+ // TODO(kush): WARNING THIS DOES NOT RELOAD CLASSPATHS FOR EVERY TEST RUN. b/34712039
+ if (classpaths != null) {
+ return classpaths;
+ }
+ String testTargetsClaspaths = System.getenv("TEST_TARGET_CLASSPATH");
+ if (testTargetsClaspaths == null || testTargetsClaspaths.isEmpty()) {
+ throw new IllegalStateException(
+ "Target's classpath not present in TEST_TARGET_CLASSPATH environment variable");
+ }
+
+ String[] targetClassPaths = testTargetsClaspaths.split(":");
+
+ classpaths = new URL[targetClassPaths.length];
+ String workingDir = System.getProperty("user.dir");
+ for (int index = 0; index < targetClassPaths.length; index++) {
+ classpaths[index] = new URL("file://" + workingDir + "/" + targetClassPaths[index]);
+ }
+ return classpaths;
+ }
+
+ /**
* Prints out stack traces if the JVM does not exit quickly. This can help detect shutdown hooks
* that are preventing the JVM from exiting quickly.
*
diff --git a/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/BUILD b/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/BUILD
index 95327df8ab..3ba2806cf2 100644
--- a/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/BUILD
+++ b/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/BUILD
@@ -68,8 +68,12 @@ sh_test(
args = [
"$(location :TestbedBinary)",
"bazel.test_suite",
+ "$(location //src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/testbed:libtestbed.jar)",
+ ],
+ data = [
+ ":TestbedBinary",
+ "//src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/testbed:libtestbed.jar",
],
- data = [":TestbedBinary"],
shard_count = 0,
deps = [":testenv"],
)
@@ -81,8 +85,12 @@ sh_test(
args = [
"$(location :TestbedBinary)",
"bazel.test_suite",
+ "$(location //src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/testbed:libtestbed.jar)",
+ ],
+ data = [
+ ":TestbedBinary",
+ "//src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/testbed:libtestbed.jar",
],
- data = [":TestbedBinary"],
shard_count = 0,
deps = [":testenv"],
)
@@ -95,10 +103,12 @@ sh_test(
"$(location :TestbedBinary)",
"$(location //src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/testbed:XmlOutputExercises.ant.xml)",
"bazel.test_suite",
+ "$(location //src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/testbed:libtestbed.jar)",
],
data = [
":TestbedBinary",
"//src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/testbed:XmlOutputExercises.ant.xml",
+ "//src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/testbed:libtestbed.jar",
],
shard_count = 0,
deps = [":testenv"],
diff --git a/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/antxmlresultwriter_integration_test.sh b/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/antxmlresultwriter_integration_test.sh
index 609518a6bf..b79ccf14fe 100755
--- a/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/antxmlresultwriter_integration_test.sh
+++ b/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/antxmlresultwriter_integration_test.sh
@@ -25,6 +25,7 @@ XML_OUTPUT_FILE="${TEST_TMPDIR}/test.xml"
SUITE_PARAMETER="$3"
SUITE="com.google.testing.junit.runner.testbed.XmlOutputExercises"
SUITE_FLAG="-D${SUITE_PARAMETER}=${SUITE}"
+TESTBED_LIB_LOCATION="${PWD}/$4"
shift 3
source ${DIR}/testenv.sh || { echo "testenv.sh not found!" >&2; exit 1; }
@@ -32,6 +33,9 @@ source ${DIR}/testenv.sh || { echo "testenv.sh not found!" >&2; exit 1; }
function test_XmlOutputExercises() {
cd $TEST_TMPDIR
+ # Pass the test target classpath through the environment variable
+ declare -x TEST_TARGET_CLASSPATH="$TESTBED_LIB_LOCATION"
+
$TESTBED --jvm_flag=${SUITE_FLAG} || true # Test failures
# Remove timestamps and test runtime from the XML files as they will always differ and cause a
diff --git a/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/junit4_testbridge_integration_tests.sh b/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/junit4_testbridge_integration_tests.sh
index b44c34783b..470fece506 100755
--- a/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/junit4_testbridge_integration_tests.sh
+++ b/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/junit4_testbridge_integration_tests.sh
@@ -25,6 +25,7 @@ DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
TESTBED="${PWD}/$1"
SUITE_PARAMETER="$2"
+TESTBED_LIB_LOCATION="${PWD}/$3"
SUITE_FLAG="-D${SUITE_PARAMETER}=com.google.testing.junit.runner.testbed.JUnit4TestbridgeExercises"
XML_OUTPUT_FILE="${TEST_TMPDIR}/test.xml"
@@ -42,6 +43,9 @@ function set_up() {
function test_Junit4() {
cd $TEST_TMPDIR
+ # Pass the test target classpath through the environment variable
+ declare -x TEST_TARGET_CLASSPATH="$TESTBED_LIB_LOCATION"
+
# Run the test without environment flag; it should fail.
declare +x TESTBRIDGE_TEST_ONLY
$TESTBED --jvm_flag=${SUITE_FLAG} >& $TEST_log && fail "Expected failure"
@@ -66,6 +70,9 @@ function test_Junit4() {
function test_Junit4FlagOverridesEnv() {
cd $TEST_TMPDIR
+ # Pass the test target classpath through the environment variable
+ declare -x TEST_TARGET_CLASSPATH="$TESTBED_LIB_LOCATION"
+
# Run the test with both environment and command line flags.
declare -x TESTBRIDGE_TEST_ONLY="doNotRun"
$TESTBED --jvm_flag=${SUITE_FLAG} --test_filter doRun >& $TEST_log || \
diff --git a/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/utf8_test_log_test.sh b/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/utf8_test_log_test.sh
index 3b2c47c7bb..96dfaee784 100755
--- a/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/utf8_test_log_test.sh
+++ b/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/utf8_test_log_test.sh
@@ -23,6 +23,7 @@ TESTBED="${PWD}/$1"
SUITE_PARAMETER="$2"
SUITE_FLAG="-D${SUITE_PARAMETER}=com.google.testing.junit.runner.testbed.InternationalCharsTest"
XML_OUTPUT_FILE="${TEST_TMPDIR}/test.xml"
+TESTBED_LIB_LOCATION="${PWD}/$3"
unset TEST_PREMATURE_EXIT_FILE
shift 2
@@ -35,6 +36,9 @@ function expect_log() {
}
function test_utf8_log() {
+ # Pass the test target classpath through the environment variable
+ declare -x TEST_TARGET_CLASSPATH="$TESTBED_LIB_LOCATION"
+
$TESTBED --jvm_flag=${SUITE_FLAG} > $TEST_log && fail "Expected failure"
expect_log 'expected:<Test [Japan].> but was:<Test [日本].>'