дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-06 01:57:13 +02:00
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
Цей коміт міститься в:
1 джерело
cdff357fdd
коміт
edc750174b
20 files changed
+657
-210
No files matched your search
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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("]", "|]");
|
||||
}
|
||||
}
|
||||
@@ -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("]", "|]");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Заблокувати користувача