feat(run): run JUnit 4 tests from the gutter without Maven (#5949)

Running a JUnit 4 test from the gutter of a Maven module started mvn test, so the Run console showed the whole Maven and Surefire log. OpenIDEA's JUnit runner now runs JUnit 4 and JUnit 3 tests on JUnit 4's own JUnitCore when the classpath has no JUnit Platform (or one without the Vintage engine); JUnit 5 keeps the Platform launcher. The Run console of JVM test runs also shows each test's stdout/stderr and failure trace, which the runner and the Gradle init script report only through service messages.

Fixes #5765
Цей коміт міститься в:
l0ng-ai authored and GitHub committed 2026-11-26 02:14:28 +08:00
1 джерело cdff357fdd
коміт edc750174b
20 files changed
+657 -210

No files matched your search

+12 -7
Переглянути файл
@@ -1,18 +1,23 @@
# JUnit Platform runner
# JUnit runner
`ai.openidea.junit.Runner` runs the JUnit Platform tests named by its arguments
`ai.openidea.junit.Runner` runs the JUnit tests named by its arguments
(`com.acme.OrderTest`, `com.acme.OrderTest#method`; a method selects every overload, so
parameterized tests run too) and prints each test as the TeamCity service messages of
`src/features/run/gradleTests.gradle`, which the Run window's JVM parser already reads. It exits
with 1 when a test failed or none ran.
OpenIDEA starts it for the gutter's JUnit 5 tests of Maven modules (Settings › Maven › Run tests
using: OpenIDEA) as `java -ea -cp <test classpath>:<runner>:<launcher> ai.openidea.junit.Runner …`.
`ide_sdk::java::junit_launcher` picks `junit-platform-launcher` of the engine's version, and
`ide_build::surefire` reads the module's Surefire configuration for the JVM (IDEA's `MavenJUnitPatcher`).
JUnit Platform tests run on the Platform launcher. JUnit 4 and JUnit 3 tests run on JUnit 4's own
`JUnitCore` (`Junit4Runner`) when the classpath has no JUnit Platform, or one without the Vintage
engine, so a JUnit 4 project needs nothing beyond its `junit` dependency.
OpenIDEA starts it for the gutter's JUnit tests of Maven modules (Settings › Maven › Run tests
using: OpenIDEA) as `java -ea -cp <test classpath>:<runner>[:<launcher>] ai.openidea.junit.Runner …`.
`ide_sdk::java::junit_launcher` picks `junit-platform-launcher` of the engine's version (none for
JUnit 4 alone), and `ide_build::surefire` reads the module's Surefire configuration for the JVM
(IDEA's `MavenJUnitPatcher`).
The jar is committed and embedded by `ide-sdk` (`junit_runner_jar`). Rebuild it after changing
the source, and check it against JUnit with:
the source, and check it against JUnit 5 and JUnit 4 with:
```sh
python3 build.py --test
+2
Переглянути файл
@@ -6,3 +6,5 @@ b509448ac506d607319f182537f0b35d71007582ec741832a1f111e5b5b70b38 org/apiguardian
5d8147a60f49453973e250ed68701b7ff055964fe2462fc2cb1ec1d6d44889ba org/junit/jupiter/junit-jupiter-api/5.11.3/junit-jupiter-api-5.11.3.jar
e62420c99f7c0d59a2159a2ef63e61877e9c80bd722c03ca8bf3bdcea050a589 org/junit/jupiter/junit-jupiter-engine/5.11.3/junit-jupiter-engine-5.11.3.jar
0f798ebec744c4e6605fd4f2072f41a8e989e2d469e21db5aa67cf799c0b51ec org/junit/jupiter/junit-jupiter-params/5.11.3/junit-jupiter-params-5.11.3.jar
59721f0805e223d84b90677887d9ff567dc534d7c502ca903c0c2b17f05c116a junit/junit/4.12/junit-4.12.jar
66fdef91e9739348df7a096aa384a5685f4e875584cce89386a7a47251c4d8e9 org/hamcrest/hamcrest-core/1.3/hamcrest-core-1.3.jar
+29 -3
Переглянути файл
@@ -28,8 +28,8 @@ for line in (root / "build-dependencies.sha256").read_text().splitlines():
if hashlib.sha256(jar.read_bytes()).hexdigest() != digest:
sys.exit(f"{jar}: SHA-256 mismatch")
jars.append(str(jar))
# The launcher API only: the runner must not depend on an engine.
api = [j for j in jars if "/junit-platform-" in j or "apiguardian" in j]
# The launcher API and JUnit 4 only: the runner must not depend on an engine.
api = [j for j in jars if "/junit-platform-" in j or "apiguardian" in j or "/junit/junit/" in j]
with tempfile.TemporaryDirectory() as scratch:
classes = Path(scratch) / "classes"
@@ -40,7 +40,7 @@ with tempfile.TemporaryDirectory() as scratch:
sample = Path(scratch) / "sample"
cp = os.pathsep.join(jars)
subprocess.run([tool("javac"), "-encoding", "UTF-8", "-cp", cp, "-d", str(sample),
str(root / "tests" / "SampleTest.java")], check=True)
str(root / "tests" / "SampleTest.java"), str(root / "tests" / "Junit4SampleTest.java")], check=True)
run = subprocess.run([tool("java"), "-cp", os.pathsep.join([str(classes), str(sample), cp]),
"ai.openidea.junit.Runner", "sample.SampleTest"], capture_output=True)
out = run.stdout.decode("utf-8")
@@ -61,6 +61,32 @@ with tempfile.TemporaryDirectory() as scratch:
method = subprocess.run([tool("java"), "-cp", os.pathsep.join([str(classes), str(sample), cp]),
"ai.openidea.junit.Runner", "sample.SampleTest#parameterized"], capture_output=True)
assert method.stdout.decode().count("testStarted") == 2, method.stdout
# JUnit 4 runs on JUnitCore, with the JUnit Platform on the classpath (no Vintage engine) and without it.
junit4 = [j for j in jars if "/junit/junit/" in j or "hamcrest" in j]
for classpath in (cp, os.pathsep.join(junit4)):
run4 = lambda *tests: subprocess.run([tool("java"), "-cp", os.pathsep.join([str(classes), str(sample), classpath]),
"ai.openidea.junit.Runner", *tests], capture_output=True)
four = run4("sample.Junit4SampleTest", "sample.Junit4SampleTest$Params", "sample.Junit4SampleTest$Broken")
out = four.stdout.decode("utf-8")
print(out)
expected = [
"##teamcity[testStarted name='passes' className='sample.Junit4SampleTest']",
"##teamcity[testStdOut name='passes' className='sample.Junit4SampleTest' out='hello |[ünï|]|n']",
"##teamcity[testFailed name='fails' className='sample.Junit4SampleTest' message='java.lang.AssertionError: it|'s wrong expected:<1> but was:<2>'",
"##teamcity[testIgnored name='ignored' className='sample.Junit4SampleTest' message='later']",
"##teamcity[testIgnored name='assumed' className='sample.Junit4SampleTest'",
"##teamcity[testFailed name='parameterized|[1|]' className='sample.Junit4SampleTest$Params'",
"##teamcity[testFailed name='initializationError' className='sample.Junit4SampleTest$Broken' message='java.lang.IllegalStateException: no database'",
"9 tests completed, 3 failed, 2 skipped",
]
missing = [e for e in expected if e not in out]
assert not missing, missing
assert "at ai.openidea.junit." not in out, out
assert four.returncode == 1, four.returncode
method = run4("sample.Junit4SampleTest$Params#parameterized").stdout.decode()
assert method.count("testStarted") == 2 and "other" not in method, method
single = run4("sample.Junit4SampleTest#passes")
assert single.returncode == 0 and "1 test completed" in single.stdout.decode(), single.stdout
print("ok")
sys.exit(0)
with zipfile.ZipFile(root / "openidea-junit-runner.jar", "w") as jar:
Бінарний файл не відображається.
+226
Переглянути файл
@@ -0,0 +1,226 @@
package ai.openidea.junit;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.runner.Description;
import org.junit.runner.JUnitCore;
import org.junit.runner.Request;
import org.junit.runner.manipulation.Filter;
import org.junit.runner.notification.Failure;
import org.junit.runner.notification.RunListener;
/**
* Runs JUnit 4 (and JUnit 3) tests on {@code JUnitCore}, as IDEA's JUnit 4 runner does. Each test's
* stdout and stderr are reported with the test; output outside a test is printed as is.
*/
final class Junit4Runner extends RunListener {
private final Reporter report;
private final Map<Description, Long> started = new HashMap<>();
private final List<Capture> captures = new ArrayList<>();
/** The running test, whose output the captured System.out / System.err belong to. */
private volatile Description current;
private Junit4Runner(Reporter report) {
this.report = report;
}
/** Whether every argument names a JUnit 4 or JUnit 3 test class. */
static boolean handlesAll(String[] args, ClassLoader loader) {
if (args.length == 0) return false;
for (String arg : args) {
try {
if (!isJunit4(Class.forName(className(arg), false, loader))) return false;
} catch (ClassNotFoundException | LinkageError e) {
return false;
}
}
return true;
}
private static boolean isJunit4(Class<?> type) {
for (Annotation a : type.getAnnotations()) {
if (a.annotationType().getName().equals("org.junit.runner.RunWith")) return true;
}
for (Class<?> c = type; c != null && c != Object.class; c = c.getSuperclass()) {
if (c.getName().equals("junit.framework.TestCase")) return true;
for (Method m : c.getDeclaredMethods()) {
for (Annotation a : m.getAnnotations()) {
if (a.annotationType().getName().equals("org.junit.Test")) return true;
}
}
}
return false;
}
static void run(Reporter report, String[] args, ClassLoader loader) throws UnsupportedEncodingException {
Junit4Runner listener = new Junit4Runner(report);
JUnitCore core = new JUnitCore();
core.addListener(listener);
PrintStream stdout = System.out;
PrintStream stderr = System.err;
Capture out = listener.new Capture("testStdOut");
Capture err = listener.new Capture("testStdErr");
System.setOut(new PrintStream(out, true, "UTF-8"));
System.setErr(new PrintStream(err, true, "UTF-8"));
try {
for (String arg : args) core.run(request(arg, loader));
} finally {
System.out.flush();
System.err.flush();
System.setOut(stdout);
System.setErr(stderr);
}
}
private static String className(String arg) {
int hash = arg.indexOf('#');
return hash < 0 ? arg : arg.substring(0, hash);
}
/** The class, or only the methods named after {@code #} (a parameterized method's runs are {@code name[0]}…). */
static Request request(String arg, ClassLoader loader) {
Class<?> type;
try {
type = Class.forName(className(arg), false, loader);
} catch (ClassNotFoundException | LinkageError e) {
return Request.errorReport(Junit4Runner.class, e);
}
Request request = Request.aClass(type);
int hash = arg.indexOf('#');
if (hash < 0) return request;
final String name = arg.substring(hash + 1);
return request.filterWith(new Filter() {
@Override
public boolean shouldRun(Description d) {
if (d.isTest()) {
String method = d.getMethodName();
return method != null && (method.equals(name) || method.startsWith(name + "["));
}
for (Description child : d.getChildren()) if (shouldRun(child)) return true;
return false;
}
@Override
public String describe() {
return "method " + name;
}
});
}
private static String id(Description d) {
String method = d.getMethodName();
return Reporter.attr("name", method != null ? method : "initializationError")
+ Reporter.attr("className", d.getClassName());
}
@Override
public void testStarted(Description d) {
flushCaptured();
started.put(d, System.currentTimeMillis());
current = d;
report.message("testStarted", id(d));
}
@Override
public void testFinished(Description d) {
flushCaptured();
current = null;
Long start = started.remove(d);
report.finished(id(d), start == null ? 0 : System.currentTimeMillis() - start);
}
@Override
public void testFailure(Failure failure) {
Description d = failure.getDescription();
if (started.containsKey(d)) {
report.failed(id(d), failure.getException());
return;
}
// A class whose set-up failed (`@BeforeClass`), or a failure outside any started test.
flushCaptured();
String own = id(d);
report.message("testStarted", own);
report.failed(own, failure.getException());
report.finished(own, 0);
}
@Override
public void testAssumptionFailure(Failure failure) {
Description d = failure.getDescription();
if (started.containsKey(d)) report.skipped(id(d), failure.getMessage());
else for (Description test : tests(d)) report.ignored(id(test), failure.getMessage());
}
@Override
public void testIgnored(Description d) {
for (Description test : tests(d)) report.ignored(id(test), reason(d));
}
private static String reason(Description d) {
for (Annotation a : d.getAnnotations()) {
if (!a.annotationType().getName().equals("org.junit.Ignore")) continue;
try {
Object value = a.annotationType().getMethod("value").invoke(a);
return value == null || value.toString().isEmpty() ? null : value.toString();
} catch (ReflectiveOperationException e) {
return null;
}
}
return null;
}
private static List<Description> tests(Description d) {
List<Description> out = new ArrayList<>();
if (d.isTest()) out.add(d);
else for (Description child : d.getChildren()) out.addAll(tests(child));
return out;
}
private void flushCaptured() {
for (Capture c : captures) c.drain();
}
/** System.out / System.err: buffered, then reported with the running test or printed outside one. */
final class Capture extends OutputStream {
private final String kind;
private final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
Capture(String kind) {
this.kind = kind;
captures.add(this);
}
@Override
public synchronized void write(int b) {
buffer.write(b);
}
@Override
public synchronized void write(byte[] b, int off, int len) {
buffer.write(b, off, len);
}
@Override
public void flush() {
if (current == null) drain();
}
synchronized void drain() {
if (buffer.size() == 0) return;
String text = new String(buffer.toByteArray(), StandardCharsets.UTF_8);
buffer.reset();
Description test = current;
if (test != null) report.message(kind, id(test) + Reporter.attr("out", text));
else report.print(text);
}
}
}
+140
Переглянути файл
@@ -0,0 +1,140 @@
package ai.openidea.junit;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.junit.platform.engine.DiscoverySelector;
import org.junit.platform.engine.TestExecutionResult;
import org.junit.platform.engine.TestSource;
import org.junit.platform.engine.discovery.DiscoverySelectors;
import org.junit.platform.engine.reporting.ReportEntry;
import org.junit.platform.engine.support.descriptor.ClassSource;
import org.junit.platform.engine.support.descriptor.MethodSource;
import org.junit.platform.launcher.Launcher;
import org.junit.platform.launcher.TestExecutionListener;
import org.junit.platform.launcher.TestIdentifier;
import org.junit.platform.launcher.TestPlan;
import org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder;
import org.junit.platform.launcher.core.LauncherFactory;
/** Runs JUnit Platform tests (Jupiter, and JUnit 4 through the Vintage engine when it is on the classpath). */
final class PlatformRunner implements TestExecutionListener {
private final Reporter report;
private final Map<String, Long> started = new HashMap<>();
private TestPlan plan;
private PlatformRunner(Reporter report) {
this.report = report;
}
static void run(Reporter report, String[] args) {
List<DiscoverySelector> selectors = new ArrayList<>();
for (String arg : args) selectors.addAll(selectors(arg));
Launcher launcher = LauncherFactory.create();
launcher.execute(
LauncherDiscoveryRequestBuilder.request()
.selectors(selectors)
.configurationParameter("junit.platform.output.capture.stdout", "true")
.configurationParameter("junit.platform.output.capture.stderr", "true")
.build(),
new PlatformRunner(report));
}
/** Every method named {@code method} (parameterized ones too); the class when there is none. */
static List<DiscoverySelector> selectors(String arg) {
int hash = arg.indexOf('#');
List<DiscoverySelector> out = new ArrayList<>();
if (hash < 0) {
out.add(DiscoverySelectors.selectClass(arg));
return out;
}
String className = arg.substring(0, hash);
String name = arg.substring(hash + 1);
try {
Class<?> type = Class.forName(className, false, Thread.currentThread().getContextClassLoader());
for (Class<?> c = type; c != null && c != Object.class; c = c.getSuperclass()) {
for (Method m : c.getDeclaredMethods()) {
if (m.getName().equals(name) && !m.isSynthetic()) out.add(DiscoverySelectors.selectMethod(type, m));
}
if (!out.isEmpty()) break;
}
} catch (ClassNotFoundException | LinkageError e) {
// Discovery reports the missing class.
}
if (out.isEmpty()) out.add(DiscoverySelectors.selectClass(className));
return out;
}
@Override
public void testPlanExecutionStarted(TestPlan testPlan) {
plan = testPlan;
}
@Override
public void executionStarted(TestIdentifier id) {
if (!id.isTest()) return;
started.put(id.getUniqueId(), System.currentTimeMillis());
report.message("testStarted", id(id));
}
@Override
public void executionSkipped(TestIdentifier id, String reason) {
List<TestIdentifier> skippedTests = new ArrayList<>();
if (id.isTest()) skippedTests.add(id);
else for (TestIdentifier d : plan.getDescendants(id)) if (d.isTest()) skippedTests.add(d);
for (TestIdentifier test : skippedTests) report.ignored(id(test), reason);
}
@Override
public void executionFinished(TestIdentifier id, TestExecutionResult result) {
TestExecutionResult.Status status = result.getStatus();
if (!id.isTest()) {
// A class whose set-up failed (`@BeforeAll`): reported as a test, like JUnit 4's initializationError.
Optional<String> className = className(id);
if (status != TestExecutionResult.Status.FAILED || !className.isPresent()) return;
String own = Reporter.attr("name", "initializationError") + Reporter.attr("className", className.get());
report.message("testStarted", own);
report.failed(own, result.getThrowable().orElse(null));
report.finished(own, 0);
return;
}
String own = id(id);
if (status == TestExecutionResult.Status.FAILED) report.failed(own, result.getThrowable().orElse(null));
else if (status == TestExecutionResult.Status.ABORTED) report.skipped(own, null);
Long start = started.remove(id.getUniqueId());
report.finished(own, start == null ? 0 : System.currentTimeMillis() - start);
}
@Override
public void reportingEntryPublished(TestIdentifier id, ReportEntry entry) {
for (Map.Entry<String, String> e : entry.getKeyValuePairs().entrySet()) {
String kind = e.getKey().equals("stdout") ? "testStdOut" : e.getKey().equals("stderr") ? "testStdErr" : null;
if (kind == null) continue;
// A class's own output (`@BeforeAll`, `@AfterAll`) carries no test name.
String own = id.isTest() ? id(id) : className(id).map(c -> Reporter.attr("className", c)).orElse(null);
if (own != null) report.message(kind, own + Reporter.attr("out", e.getValue()));
}
}
/** `name='method' className='a.B$Nested'`, the method and class of the test or its closest source. */
private String id(TestIdentifier id) {
for (TestIdentifier at = id; at != null; at = plan.getParent(at).orElse(null)) {
TestSource source = at.getSource().orElse(null);
if (source instanceof MethodSource) {
MethodSource m = (MethodSource) source;
return Reporter.attr("name", m.getMethodName()) + Reporter.attr("className", m.getClassName());
}
if (source instanceof ClassSource)
return Reporter.attr("name", id.getLegacyReportingName()) + Reporter.attr("className", ((ClassSource) source).getClassName());
}
return Reporter.attr("name", id.getLegacyReportingName()) + Reporter.attr("className", id.getDisplayName());
}
private Optional<String> className(TestIdentifier id) {
TestSource source = id.getSource().orElse(null);
return source instanceof ClassSource ? Optional.of(((ClassSource) source).getClassName()) : Optional.empty();
}
}
+87
Переглянути файл
@@ -0,0 +1,87 @@
package ai.openidea.junit;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringWriter;
/**
* Prints tests as the TeamCity service messages of OpenIDEA's Gradle test init script
* ({@code gradleTests.gradle}) and counts them for the summary line.
*/
final class Reporter {
private final PrintStream out;
int tests;
int failed;
int skipped;
Reporter(PrintStream out) {
this.out = out;
}
void message(String kind, String attrs) {
synchronized (out) {
out.println("##teamcity[" + kind + attrs + "]");
}
}
/** Output written outside any test. */
void print(String text) {
synchronized (out) {
out.print(text);
out.flush();
}
}
void failed(String own, Throwable error) {
failed++;
StringWriter trace = new StringWriter();
if (error != null) error.printStackTrace(new PrintWriter(trace));
message("testFailed", own + attr("message", error == null ? "" : error.toString()) + attr("details", withoutRunner(trace.toString())));
}
void skipped(String own, String reason) {
skipped++;
message("testIgnored", own + (reason == null ? "" : attr("message", reason)));
}
void finished(String own, long duration) {
tests++;
message("testFinished", own + attr("duration", Long.toString(duration)));
}
/** A test that was skipped without starting (`@Disabled`, `@Ignore`). */
void ignored(String own, String reason) {
message("testStarted", own);
skipped(own, reason);
finished(own, 0);
}
String summary() {
StringBuilder summary = new StringBuilder().append(tests).append(tests == 1 ? " test" : " tests");
summary.append(" completed");
if (failed > 0) summary.append(", ").append(failed).append(" failed");
if (skipped > 0) summary.append(", ").append(skipped).append(" skipped");
return summary.toString();
}
/** The stack trace without the runner's own frames (they end every test's trace). */
static String withoutRunner(String trace) {
StringBuilder out = new StringBuilder(trace.length());
for (String line : trace.split("\n", -1)) {
if (line.trim().startsWith("at ai.openidea.junit.")) continue;
if (out.length() > 0) out.append('\n');
out.append(line);
}
return out.toString();
}
static String attr(String name, String value) {
return " " + name + "='" + escape(value) + "'";
}
static String escape(String s) {
if (s == null) return "";
return s.replace("|", "||").replace("'", "|'").replace("\n", "|n").replace("\r", "|r")
.replace("[", "|[").replace("]", "|]");
}
}
+23 -178
Переглянути файл
@@ -3,196 +3,41 @@ package ai.openidea.junit;
import java.io.FileDescriptor;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.junit.platform.engine.DiscoverySelector;
import org.junit.platform.engine.TestExecutionResult;
import org.junit.platform.engine.TestSource;
import org.junit.platform.engine.discovery.DiscoverySelectors;
import org.junit.platform.engine.reporting.ReportEntry;
import org.junit.platform.engine.support.descriptor.ClassSource;
import org.junit.platform.engine.support.descriptor.MethodSource;
import org.junit.platform.launcher.Launcher;
import org.junit.platform.launcher.TestExecutionListener;
import org.junit.platform.launcher.TestIdentifier;
import org.junit.platform.launcher.TestPlan;
import org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder;
import org.junit.platform.launcher.core.LauncherFactory;
/**
* Runs the JUnit Platform tests given as arguments ({@code com.acme.OrderTest} or
* {@code com.acme.OrderTest#method}) and reports each test as the TeamCity service messages
* OpenIDEA's Gradle test init script prints ({@code gradleTests.gradle}). Exits with 1 when a
* test failed.
* Runs the tests given as arguments ({@code com.acme.OrderTest} or {@code com.acme.OrderTest#method})
* and reports each test as the TeamCity service messages OpenIDEA's Gradle test init script prints
* ({@code gradleTests.gradle}). Exits with 1 when a test failed or none ran.
*
* <p>JUnit Platform tests run on the Platform launcher. JUnit 4 (and 3) tests run on JUnit 4's own
* {@code JUnitCore} when the classpath has no JUnit Platform, or has one without the Vintage engine,
* so a JUnit 4 project needs nothing beyond its {@code junit} dependency.
*/
public final class Runner implements TestExecutionListener {
private final PrintStream out;
private final Map<String, Long> started = new HashMap<>();
private TestPlan plan;
private int tests;
private int failed;
private int skipped;
private Runner(PrintStream out) {
this.out = out;
}
public final class Runner {
private Runner() {}
public static void main(String[] args) throws UnsupportedEncodingException {
// The original stdout: JUnit replaces System.out while it captures a test's output.
// The original stdout: the test frameworks' output capture replaces System.out.
PrintStream out = new PrintStream(new FileOutputStream(FileDescriptor.out), true, "UTF-8");
List<DiscoverySelector> selectors = new ArrayList<>();
for (String arg : args) selectors.addAll(selectors(arg));
Runner runner = new Runner(out);
Launcher launcher = LauncherFactory.create();
launcher.execute(
LauncherDiscoveryRequestBuilder.request()
.selectors(selectors)
.configurationParameter("junit.platform.output.capture.stdout", "true")
.configurationParameter("junit.platform.output.capture.stderr", "true")
.build(),
runner);
StringBuilder summary = new StringBuilder().append(runner.tests).append(runner.tests == 1 ? " test" : " tests");
summary.append(" completed");
if (runner.failed > 0) summary.append(", ").append(runner.failed).append(" failed");
if (runner.skipped > 0) summary.append(", ").append(runner.skipped).append(" skipped");
out.println(summary);
Reporter report = new Reporter(out);
ClassLoader loader = Thread.currentThread().getContextClassLoader();
boolean platform = present(loader, "org.junit.platform.launcher.core.LauncherFactory");
boolean junit4 = present(loader, "org.junit.runner.JUnitCore");
boolean vintage = present(loader, "org.junit.vintage.engine.VintageTestEngine");
if (junit4 && (!platform || (!vintage && Junit4Runner.handlesAll(args, loader)))) Junit4Runner.run(report, args, loader);
else PlatformRunner.run(report, args);
out.println(report.summary());
out.flush();
System.exit(runner.failed > 0 || runner.tests == 0 ? 1 : 0);
System.exit(report.failed > 0 || report.tests == 0 ? 1 : 0);
}
/** Every method named {@code method} (parameterized ones too); the class when there is none. */
static List<DiscoverySelector> selectors(String arg) {
int hash = arg.indexOf('#');
List<DiscoverySelector> out = new ArrayList<>();
if (hash < 0) {
out.add(DiscoverySelectors.selectClass(arg));
return out;
}
String className = arg.substring(0, hash);
String name = arg.substring(hash + 1);
private static boolean present(ClassLoader loader, String name) {
try {
Class<?> type = Class.forName(className, false, Thread.currentThread().getContextClassLoader());
for (Class<?> c = type; c != null && c != Object.class; c = c.getSuperclass()) {
for (Method m : c.getDeclaredMethods()) {
if (m.getName().equals(name) && !m.isSynthetic()) out.add(DiscoverySelectors.selectMethod(type, m));
}
if (!out.isEmpty()) break;
}
Class.forName(name, false, loader);
return true;
} catch (ClassNotFoundException | LinkageError e) {
// Discovery reports the missing class.
return false;
}
if (out.isEmpty()) out.add(DiscoverySelectors.selectClass(className));
return out;
}
@Override
public void testPlanExecutionStarted(TestPlan testPlan) {
plan = testPlan;
}
@Override
public void executionStarted(TestIdentifier id) {
if (!id.isTest()) return;
started.put(id.getUniqueId(), System.currentTimeMillis());
message("testStarted", id(id));
}
@Override
public void executionSkipped(TestIdentifier id, String reason) {
List<TestIdentifier> skippedTests = new ArrayList<>();
if (id.isTest()) skippedTests.add(id);
else for (TestIdentifier d : plan.getDescendants(id)) if (d.isTest()) skippedTests.add(d);
for (TestIdentifier test : skippedTests) {
tests++;
skipped++;
message("testStarted", id(test));
message("testIgnored", id(test) + attr("message", reason));
message("testFinished", id(test) + attr("duration", "0"));
}
}
@Override
public void executionFinished(TestIdentifier id, TestExecutionResult result) {
TestExecutionResult.Status status = result.getStatus();
if (!id.isTest()) {
// A class whose set-up failed (`@BeforeAll`): reported as a test, like JUnit 4's initializationError.
Optional<String> className = className(id);
if (status != TestExecutionResult.Status.FAILED || !className.isPresent()) return;
String own = attr("name", "initializationError") + attr("className", className.get());
message("testStarted", own);
failed(own, result);
message("testFinished", own + attr("duration", "0"));
tests++;
return;
}
tests++;
String own = id(id);
if (status == TestExecutionResult.Status.FAILED) failed(own, result);
else if (status == TestExecutionResult.Status.ABORTED) {
skipped++;
message("testIgnored", own);
}
Long start = started.remove(id.getUniqueId());
long duration = start == null ? 0 : System.currentTimeMillis() - start;
message("testFinished", own + attr("duration", Long.toString(duration)));
}
@Override
public void reportingEntryPublished(TestIdentifier id, ReportEntry entry) {
for (Map.Entry<String, String> e : entry.getKeyValuePairs().entrySet()) {
String kind = e.getKey().equals("stdout") ? "testStdOut" : e.getKey().equals("stderr") ? "testStdErr" : null;
if (kind == null) continue;
// A class's own output (`@BeforeAll`, `@AfterAll`) carries no test name.
String own = id.isTest() ? id(id) : className(id).map(c -> attr("className", c)).orElse(null);
if (own != null) message(kind, own + attr("out", e.getValue()));
}
}
private void failed(String own, TestExecutionResult result) {
failed++;
Throwable error = result.getThrowable().orElse(null);
StringWriter trace = new StringWriter();
if (error != null) error.printStackTrace(new PrintWriter(trace));
message("testFailed", own + attr("message", error == null ? "" : error.toString()) + attr("details", trace.toString()));
}
/** `name='method' className='a.B$Nested'`, the method and class of the test or its closest source. */
private String id(TestIdentifier id) {
for (TestIdentifier at = id; at != null; at = plan.getParent(at).orElse(null)) {
TestSource source = at.getSource().orElse(null);
if (source instanceof MethodSource) {
MethodSource m = (MethodSource) source;
return attr("name", m.getMethodName()) + attr("className", m.getClassName());
}
if (source instanceof ClassSource)
return attr("name", id.getLegacyReportingName()) + attr("className", ((ClassSource) source).getClassName());
}
return attr("name", id.getLegacyReportingName()) + attr("className", id.getDisplayName());
}
private Optional<String> className(TestIdentifier id) {
TestSource source = id.getSource().orElse(null);
return source instanceof ClassSource ? Optional.of(((ClassSource) source).getClassName()) : Optional.empty();
}
private void message(String kind, String attrs) {
out.println("##teamcity[" + kind + attrs + "]");
}
private static String attr(String name, String value) {
return " " + name + "='" + escape(value) + "'";
}
static String escape(String s) {
if (s == null) return "";
return s.replace("|", "||").replace("'", "|'").replace("\n", "|n").replace("\r", "|r")
.replace("[", "|[").replace("]", "|]");
}
}
+65
Переглянути файл
@@ -0,0 +1,65 @@
package sample;
import static org.junit.Assert.assertEquals;
import static org.junit.Assume.assumeTrue;
import java.util.Arrays;
import java.util.Collection;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
public class Junit4SampleTest {
@Test
public void passes() {
System.out.println("hello [ünï]");
}
@Test
public void fails() {
assertEquals("it's wrong", 1, 2);
}
@Test
@Ignore("later")
public void ignored() {}
@Test
public void assumed() {
assumeTrue(false);
}
@RunWith(Parameterized.class)
public static class Params {
@Parameterized.Parameters
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][] {{1}, {2}});
}
private final int n;
public Params(int n) {
this.n = n;
}
@Test
public void parameterized() {
assertEquals(1, n);
}
@Test
public void other() {}
}
public static class Broken {
@BeforeClass
public static void setUp() {
throw new IllegalStateException("no database");
}
@Test
public void never() {}
}
}