дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-03 16:51:16 +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
@@ -902,7 +902,8 @@ pub async fn java_build_workspace(
|
||||
|
||||
/// The JVM of OpenIDEA's JUnit runner for the module at `module`, given its resolved test classpath:
|
||||
/// the classpath with the runner and `junit-platform-launcher` of the engine's version (unless the
|
||||
/// classpath has one; from the engine's repository, else downloaded once from Maven Central), and,
|
||||
/// classpath has one, or has JUnit 4 alone; from the engine's repository, else downloaded once from
|
||||
/// Maven Central), and,
|
||||
/// for a Maven module, what its Surefire configuration gives the forked test JVM.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn java_junit_runner(
|
||||
@@ -926,13 +927,13 @@ pub async fn java_junit_runner(
|
||||
let runner = ide_sdk::java::junit_runner_jar(&data_dir)
|
||||
.ok_or_else(|| IdeError::internal("Cannot install the JUnit runner"))?;
|
||||
let launcher = match ide_sdk::java::junit_launcher(&class_paths) {
|
||||
ide_sdk::java::JunitLauncher::OnClasspath => None,
|
||||
ide_sdk::java::JunitLauncher::OnClasspath | ide_sdk::java::JunitLauncher::Junit4 => None,
|
||||
ide_sdk::java::JunitLauncher::Found(path) => Some(path),
|
||||
ide_sdk::java::JunitLauncher::Missing(version) => Some(download_junit_launcher(&data_dir, &version)?),
|
||||
ide_sdk::java::JunitLauncher::NoPlatform => {
|
||||
return Err(IdeError::unavailable(
|
||||
"No JUnit Platform (junit-platform-engine) on the test classpath. To run these tests through \
|
||||
Maven, set Settings › Build Tools › Maven › Run tests using to Maven.",
|
||||
"Neither JUnit 5 (junit-platform-engine) nor JUnit 4 is on the test classpath. To run these tests \
|
||||
through Maven, set Settings › Build Tools › Maven › Run tests using to Maven.",
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1644,7 +1644,7 @@ pub fn jdbc_bridge_jar(data_dir: &Path) -> Option<PathBuf> {
|
||||
)
|
||||
}
|
||||
|
||||
/// Extracts the JUnit Platform test runner (`java/junit-runner`) into the application's data directory.
|
||||
/// Extracts the JUnit test runner (`java/junit-runner`; JUnit Platform and JUnit 4) into the application's data directory.
|
||||
pub fn junit_runner_jar(data_dir: &Path) -> Option<PathBuf> {
|
||||
install_bundle(
|
||||
data_dir,
|
||||
@@ -1680,7 +1680,9 @@ pub enum JunitLauncher {
|
||||
Found(PathBuf),
|
||||
/// Not found locally: the engine's version, to download.
|
||||
Missing(String),
|
||||
/// No `junit-platform-engine` on the classpath (JUnit 4 alone, TestNG).
|
||||
/// No `junit-platform-engine`, but JUnit 4: the runner uses JUnit 4's own `JUnitCore`.
|
||||
Junit4,
|
||||
/// Neither the JUnit Platform nor JUnit 4 on the classpath (TestNG alone).
|
||||
NoPlatform,
|
||||
}
|
||||
|
||||
@@ -1697,7 +1699,11 @@ pub fn junit_launcher(class_paths: &[String]) -> JunitLauncher {
|
||||
let version = name(p).strip_prefix("junit-platform-engine-")?.strip_suffix(".jar")?.to_owned();
|
||||
Some((PathBuf::from(p), version))
|
||||
}) else {
|
||||
return JunitLauncher::NoPlatform;
|
||||
let junit4 = class_paths.iter().any(|p| {
|
||||
let name = name(p);
|
||||
(name.starts_with("junit-4.") || name.starts_with("junit-dep-4.")) && name.ends_with(".jar")
|
||||
});
|
||||
return if junit4 { JunitLauncher::Junit4 } else { JunitLauncher::NoPlatform };
|
||||
};
|
||||
let jar = format!("junit-platform-launcher-{version}.jar");
|
||||
let artifact = engine.ancestors().find(|a| a.file_name().is_some_and(|n| n == "junit-platform-engine"));
|
||||
@@ -1741,7 +1747,8 @@ mod junit_launcher_tests {
|
||||
junit_launcher(&[s(&other), "/x/junit-platform-launcher-1.9.0.jar".into()]),
|
||||
JunitLauncher::OnClasspath
|
||||
);
|
||||
assert_eq!(junit_launcher(&["/x/junit-4.13.2.jar".into()]), JunitLauncher::NoPlatform);
|
||||
assert_eq!(junit_launcher(&["/x/junit-4.13.2.jar".into()]), JunitLauncher::Junit4);
|
||||
assert_eq!(junit_launcher(&["/x/testng-7.10.2.jar".into()]), JunitLauncher::NoPlatform);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
@@ -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:
|
||||
|
||||
Бінарний файл не відображається.
@@ -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("]", "|]");
|
||||
}
|
||||
}
|
||||
@@ -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() {}
|
||||
}
|
||||
}
|
||||
@@ -847,7 +847,8 @@ export const commands = {
|
||||
/**
|
||||
* The JVM of OpenIDEA's JUnit runner for the module at `module`, given its resolved test classpath:
|
||||
* the classpath with the runner and `junit-platform-launcher` of the engine's version (unless the
|
||||
* classpath has one; from the engine's repository, else downloaded once from Maven Central), and,
|
||||
* classpath has one, or has JUnit 4 alone; from the engine's repository, else downloaded once from
|
||||
* Maven Central), and,
|
||||
* for a Maven module, what its Surefire configuration gives the forked test JVM.
|
||||
*/
|
||||
javaJunitRunner: (module: string, classPaths: string[]) => typedError<JunitLaunch, IdeError>(__TAURI_INVOKE("java_junit_runner", { module, classPaths })),
|
||||
|
||||
@@ -84,12 +84,12 @@ export function jvmTestConfig(fileConfig: RunConfig, className: string, method:
|
||||
return null;
|
||||
}
|
||||
|
||||
/** A test file of JUnit Jupiter (JUnit 5): OpenIDEA's runner handles JUnit Platform engines only. */
|
||||
const JUPITER_IMPORT = /^\s*import\s+(?:static\s+)?org\.junit\.jupiter\./m;
|
||||
/** A JUnit test file (JUnit 5 Jupiter, JUnit 4 or JUnit 3): OpenIDEA's runner handles all of them, TestNG goes to Maven. */
|
||||
const JUNIT_IMPORT = /^\s*import\s+(?:static\s+)?(?:org\.junit\.|junit\.framework\.)/m;
|
||||
|
||||
/** Settings › Build Tools › Maven › Run tests using: OpenIDEA (the default), not Surefire. */
|
||||
export function runsJunitInIde(fileConfig: RunConfig, content: string | undefined): boolean {
|
||||
if (fileConfig.kind !== "maven" || !content || !JUPITER_IMPORT.test(content)) return false;
|
||||
if (fileConfig.kind !== "maven" || !content || !JUNIT_IMPORT.test(content)) return false;
|
||||
return useProject.getState().settings?.languages?.java?.maven?.runTestsUsing !== "maven";
|
||||
}
|
||||
|
||||
|
||||
@@ -290,7 +290,7 @@ describe("application configurations", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("JUnit 5 through OpenIDEA's runner (Maven › Run tests using)", () => {
|
||||
describe("JUnit through OpenIDEA's runner (Maven › Run tests using)", () => {
|
||||
const rel = "shop/src/test/java/a/OrderTest.java";
|
||||
const jupiter = `package a;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -299,6 +299,7 @@ class OrderTest {
|
||||
void adds() {}
|
||||
}`;
|
||||
const junit4 = jupiter.replace("org.junit.jupiter.api.Test", "org.junit.Test");
|
||||
const testng = jupiter.replace("org.junit.jupiter.api.Test", "org.testng.annotations.Test");
|
||||
const maven = [cfg({ id: "maven:test", kind: "maven", args: ["test"], cwd: "shop", isTest: true })];
|
||||
const gradle = [cfg({ id: "gradle:test", kind: "gradle", args: ["test"], cwd: "shop", isTest: true })];
|
||||
const target = (src: string, name: string) =>
|
||||
@@ -324,11 +325,19 @@ class OrderTest {
|
||||
expect(targetConfig(target(jupiter, "OrderTest"), rel, maven, jupiter)!.args.at(-1)).toBe("a.OrderTest");
|
||||
});
|
||||
|
||||
it("keeps Surefire for the Maven setting, JUnit 4 and Gradle", () => {
|
||||
it("runs JUnit 4 tests with the runner too", () => {
|
||||
expect(targetConfig(target(junit4, "adds"), rel, maven, junit4)).toMatchObject({
|
||||
kind: "application",
|
||||
args: ["-ea", "-cp", "${testClasspath}", "ai.openidea.junit.Runner", "a.OrderTest#adds"],
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps Surefire for the Maven setting, TestNG and Gradle", () => {
|
||||
useTests("maven");
|
||||
expect(targetConfig(target(jupiter, "adds"), rel, maven, jupiter)!.kind).toBe("maven");
|
||||
useTests("ide");
|
||||
expect(targetConfig(target(junit4, "adds"), rel, maven, junit4)!.kind).toBe("maven");
|
||||
useTests("ide");
|
||||
expect(targetConfig(target(testng, "adds"), rel, maven, testng)!.kind).toBe("maven");
|
||||
expect(targetConfig(target(jupiter, "adds"), rel, gradle, jupiter)!.kind).toBe("gradle");
|
||||
});
|
||||
|
||||
|
||||
@@ -788,7 +788,7 @@ function newRuntime(config: RunConfig): SessionRuntime {
|
||||
framework === "go"
|
||||
? new GoTestOutput(feed)
|
||||
: framework === "phpunit" || framework === "jvm"
|
||||
? new TeamcityOutput(feed)
|
||||
? new TeamcityOutput(feed, framework === "jvm")
|
||||
: framework === "ruby" && config.kind !== "rspec"
|
||||
? new RubyTestOutput(feed)
|
||||
: framework === "node-test" || framework === "mocha"
|
||||
|
||||
@@ -120,6 +120,26 @@ describe("TeamcityOutput", () => {
|
||||
expect(shown).toBe("PHPUnit 11.5 by Sebastian Bergmann\nOK (1 test\n");
|
||||
expect(results.counts()).toMatchObject({ passed: 1 });
|
||||
});
|
||||
|
||||
it("shows a test's own output and failures in the console when asked (JVM runs)", () => {
|
||||
const lines = [
|
||||
"##teamcity[testStarted name='prints' className='demo.GreeterTest']",
|
||||
"##teamcity[testStdOut name='prints' className='demo.GreeterTest' out='输出结果:OpenIdea|n']",
|
||||
"##teamcity[testStdErr name='prints' className='demo.GreeterTest' out='warn |[x|]|n']",
|
||||
"##teamcity[testFinished name='prints' className='demo.GreeterTest' duration='3']",
|
||||
"##teamcity[testStarted name='fails' className='demo.GreeterTest']",
|
||||
"##teamcity[testFailed name='fails' className='demo.GreeterTest' message='java.lang.AssertionError: no' details='java.lang.AssertionError: no|n\tat demo.GreeterTest.fails(GreeterTest.java:15)|n']",
|
||||
"##teamcity[testFinished name='fails' className='demo.GreeterTest' duration='1']",
|
||||
"1 test completed",
|
||||
"",
|
||||
].join("\n");
|
||||
const fed: string[] = [];
|
||||
expect(new TeamcityOutput((line) => fed.push(line), true).feed(lines)).toBe(
|
||||
"输出结果:OpenIdea\nwarn [x]\njava.lang.AssertionError: no\n\tat demo.GreeterTest.fails(GreeterTest.java:15)\n1 test completed\n",
|
||||
);
|
||||
expect(fed).toHaveLength(8);
|
||||
expect(new TeamcityOutput(() => {}).feed(lines)).toBe("1 test completed\n");
|
||||
});
|
||||
});
|
||||
|
||||
describe("command lines", () => {
|
||||
|
||||
@@ -29,9 +29,22 @@ export function serviceMessage(line: string): ServiceMessage | null {
|
||||
return { kind: m[1]!, attrs };
|
||||
}
|
||||
|
||||
/** Console text of a run reporting through service messages: the messages only feed the test tree. */
|
||||
/**
|
||||
* Console text of a run reporting through service messages: the messages feed the test tree. With
|
||||
* `testOutput`, a test's own stdout / stderr (`testStdOut`, `testStdErr`) and its failure are shown in
|
||||
* the console too, so the run reads like the program's output with no test selected (OpenIDEA's JUnit
|
||||
* runner and the Gradle init script report them only through these messages).
|
||||
*/
|
||||
export class TeamcityOutput extends TestStdout {
|
||||
constructor(feedLine: (line: string) => void) {
|
||||
super(feedLine, (line) => (MESSAGE_RE.test(line) ? "" : line + "\n"));
|
||||
constructor(feedLine: (line: string) => void, testOutput = false) {
|
||||
super(feedLine, (line) => {
|
||||
if (!MESSAGE_RE.test(line)) return line + "\n";
|
||||
if (!testOutput) return "";
|
||||
const message = serviceMessage(line);
|
||||
if (message?.kind === "testStdOut" || message?.kind === "testStdErr") return message.attrs.out ?? "";
|
||||
if (message?.kind !== "testFailed") return "";
|
||||
const failure = (message.attrs.details || message.attrs.message || "").replace(/\n$/, "");
|
||||
return failure ? failure + "\n" : "";
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -677,7 +677,7 @@ export function MavenPage() {
|
||||
/>
|
||||
<Row
|
||||
label="Run tests using"
|
||||
hint="OpenIDEA runs a JUnit 5 test from the gutter on the Java language server's test classpath, without starting Maven, with the POM's Surefire configuration (argLine, system properties, environment variables, working directory). Maven runs it through Surefire, with filtered test resources."
|
||||
hint="OpenIDEA runs a JUnit 4 or JUnit 5 test from the gutter on the Java language server's test classpath, without starting Maven, with the POM's Surefire configuration (argLine, system properties, environment variables, working directory). Maven runs it through Surefire, with filtered test resources."
|
||||
>
|
||||
<Select
|
||||
value={runTestsUsing || "ide"}
|
||||
|
||||
@@ -2296,7 +2296,7 @@
|
||||
"Delegate IDE build/run actions to Maven": "Delegate IDE build/run actions to Maven",
|
||||
"Run tests using": "Run tests using",
|
||||
"Applying the Surefire configuration: {list}": "Applying the Surefire configuration: {list}",
|
||||
"OpenIDEA runs a JUnit 5 test from the gutter on the Java language server's test classpath, without starting Maven, with the POM's Surefire configuration (argLine, system properties, environment variables, working directory). Maven runs it through Surefire, with filtered test resources.": "OpenIDEA runs a JUnit 5 test from the gutter on the Java language server's test classpath, without starting Maven, with the POM's Surefire configuration (argLine, system properties, environment variables, working directory). Maven runs it through Surefire, with filtered test resources.",
|
||||
"OpenIDEA runs a JUnit 4 or JUnit 5 test from the gutter on the Java language server's test classpath, without starting Maven, with the POM's Surefire configuration (argLine, system properties, environment variables, working directory). Maven runs it through Surefire, with filtered test resources.": "OpenIDEA runs a JUnit 4 or JUnit 5 test from the gutter on the Java language server's test classpath, without starting Maven, with the POM's Surefire configuration (argLine, system properties, environment variables, working directory). Maven runs it through Surefire, with filtered test resources.",
|
||||
"Automatically download sources": "Automatically download sources",
|
||||
"The Java language server downloads the sources of all dependencies when it imports the project. When off, a library class opens decompiled and its Download Sources banner fetches the sources of that library only.": "The Java language server downloads the sources of all dependencies when it imports the project. When off, a library class opens decompiled and its Download Sources banner fetches the sources of that library only.",
|
||||
"Run and Debug build Maven modules with Maven (the project's javac) instead of the Java language server. Editor problems still come from the language server.": "Run and Debug build Maven modules with Maven (the project's javac) instead of the Java language server. Editor problems still come from the language server.",
|
||||
|
||||
@@ -8778,7 +8778,7 @@
|
||||
"Delegate IDE build/run actions to Maven": "将 IDE 构建/运行操作委托给 Maven",
|
||||
"Run tests using": "运行测试使用",
|
||||
"Applying the Surefire configuration: {list}": "正在应用 Surefire 配置:{list}",
|
||||
"OpenIDEA runs a JUnit 5 test from the gutter on the Java language server's test classpath, without starting Maven, with the POM's Surefire configuration (argLine, system properties, environment variables, working directory). Maven runs it through Surefire, with filtered test resources.": "OpenIDEA 在 Java 语言服务器的测试类路径上直接运行装订区域中的 JUnit 5 测试,不启动 Maven,并应用 POM 里的 Surefire 配置(argLine、系统属性、环境变量、工作目录)。Maven 则通过 Surefire 运行,并使用过滤后的测试资源。",
|
||||
"OpenIDEA runs a JUnit 4 or JUnit 5 test from the gutter on the Java language server's test classpath, without starting Maven, with the POM's Surefire configuration (argLine, system properties, environment variables, working directory). Maven runs it through Surefire, with filtered test resources.": "OpenIDEA 在 Java 语言服务器的测试类路径上直接运行装订区域中的 JUnit 4 或 JUnit 5 测试,不启动 Maven,并应用 POM 里的 Surefire 配置(argLine、系统属性、环境变量、工作目录)。Maven 则通过 Surefire 运行,并使用过滤后的测试资源。",
|
||||
"Automatically download sources": "自动下载源代码",
|
||||
"The Java language server downloads the sources of all dependencies when it imports the project. When off, a library class opens decompiled and its Download Sources banner fetches the sources of that library only.": "Java 语言服务器导入项目时下载所有依赖的源代码。关闭时,库中的类以反编译形式打开,可在其“下载源代码”横幅中只下载该库的源代码。",
|
||||
"Run and Debug build Maven modules with Maven (the project's javac) instead of the Java language server. Editor problems still come from the language server.": "运行和调试时用 Maven(项目的 javac)构建 Maven 模块,而不是用 Java 语言服务器。编辑器中的问题仍来自语言服务器。",
|
||||
|
||||
Reference in new issue
Заблокувати користувача