olamy commented on code in PR #3654:
URL: https://github.com/apache/maven-surefire/pull/3654#discussion_r4761975880
##########
surefire-providers/surefire-junit-platform/src/main/java/org/apache/maven/surefire/junitplatform/JUnit4ListenersAdapter.java:
##########
@@ -20,184 +20,334 @@
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
+import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
import java.util.List;
+import java.util.Map;
+import org.apache.maven.surefire.api.util.SurefireReflectionException;
import org.junit.platform.engine.TestExecutionResult;
+import org.junit.platform.engine.TestExecutionResult.Status;
+import org.junit.platform.engine.TestSource;
import org.junit.platform.engine.support.descriptor.ClassSource;
+import org.junit.platform.engine.support.descriptor.MethodSource;
import org.junit.platform.launcher.TestExecutionListener;
import org.junit.platform.launcher.TestIdentifier;
import org.junit.platform.launcher.TestPlan;
+import org.opentest4j.MultipleFailuresError;
+import org.opentest4j.TestAbortedException;
+import static java.util.Arrays.asList;
+import static java.util.Collections.singletonList;
+import static
org.apache.maven.surefire.api.util.ReflectionUtils.getConstructor;
+import static org.apache.maven.surefire.api.util.ReflectionUtils.getMethod;
+import static
org.apache.maven.surefire.api.util.ReflectionUtils.invokeMethodWithArray;
+import static
org.apache.maven.surefire.api.util.ReflectionUtils.invokeMethodWithArray2;
+import static org.apache.maven.surefire.api.util.ReflectionUtils.loadClass;
+import static org.apache.maven.surefire.api.util.ReflectionUtils.newInstance;
+import static org.apache.maven.surefire.api.util.ReflectionUtils.tryGetMethod;
+import static org.apache.maven.surefire.api.util.ReflectionUtils.tryLoadClass;
+import static org.junit.platform.engine.TestExecutionResult.Status.ABORTED;
+import static org.junit.platform.engine.TestExecutionResult.Status.FAILED;
+import static org.junit.platform.engine.TestExecutionResult.Status.SUCCESSFUL;
+
+/**
+ * Calls JUnit 4 {@code RunListener}s the way JUnit 4 does: start and finish
of each test, its failure,
+ * assumption failure or ignore. JUnit 4 is only on the test classpath, so it
all goes through reflection.
+ */
public class JUnit4ListenersAdapter implements TestExecutionListener {
+ private static final Annotation[] NO_ANNOTATIONS = new Annotation[0];
+
private final List<Object> listeners;
+ // the loader the listeners come from, events can arrive on other threads
+ private final ClassLoader classLoader =
Thread.currentThread().getContextClassLoader();
+
+ // the JUnit 4 API, looked up once
+ private final Method createTestDescription;
+
+ private final Method createClassDescription;
+
+ private final Method createSuiteDescription;
+
+ private final Constructor<?> newFailure;
+
+ private final Constructor<?> newResult;
+
+ private final Object testMechanism;
+
+ // RunListener methods by name, testSuiteStarted and testSuiteFinished
only came with JUnit 4.13
+ private final Map<String, Method> listenerMethods = new HashMap<>();
+
+ // null before JUnit 4.12, no listener is thread safe then
+ private final Class<? extends Annotation> threadSafe;
+
+ // like JUnit 4, listeners not marked thread safe are called one at a time
+ private final Object lock = new Object();
+
public JUnit4ListenersAdapter(List<Object> runListener) {
this.listeners = runListener;
+ Class<?> description = loadClass(classLoader,
"org.junit.runner.Description");
+ Class<?> failure = loadClass(classLoader,
"org.junit.runner.notification.Failure");
+ Class<?> result = loadClass(classLoader, "org.junit.runner.Result");
+ Class<?> listener = loadClass(classLoader,
"org.junit.runner.notification.RunListener");
+ createTestDescription =
+ getMethod(description, "createTestDescription", String.class,
String.class, Annotation[].class);
+ createClassDescription = getMethod(description,
"createSuiteDescription", Class.class);
+ createSuiteDescription = getMethod(description,
"createSuiteDescription", String.class, Annotation[].class);
+ newFailure = getConstructor(failure, description, Throwable.class);
+ newResult = getConstructor(result);
+ try {
+ testMechanism = description.getField("TEST_MECHANISM").get(null);
+ } catch (ReflectiveOperationException e) {
+ throw new SurefireReflectionException(e);
+ }
+ for (String name : asList(
+ "testRunStarted",
+ "testSuiteStarted",
+ "testStarted",
+ "testFinished",
+ "testIgnored",
+ "testSuiteFinished")) {
+ addListenerMethod(listener, name, description);
+ }
+ addListenerMethod(listener, "testFailure", failure);
+ addListenerMethod(listener, "testAssumptionFailure", failure);
+ addListenerMethod(listener, "testRunFinished", result);
+ Class<?> threadSafeClass = tryLoadClass(classLoader,
"org.junit.runner.notification.RunListener$ThreadSafe");
+ threadSafe = threadSafeClass == null ? null :
threadSafeClass.asSubclass(Annotation.class);
+ }
+
+ private void addListenerMethod(Class<?> listener, String name, Class<?>
argument) {
+ Method method = tryGetMethod(listener, name, argument);
+ if (method != null) {
+ listenerMethods.put(name, method);
+ }
}
@Override
public void executionStarted(TestIdentifier testIdentifier) {
- listeners.forEach(runListener -> {
- try {
- Class<?> descriptionClass =
-
Thread.currentThread().getContextClassLoader().loadClass("org.junit.runner.Description");
- Method createTestDescription = descriptionClass.getMethod(
- "createTestDescription", String.class, String.class,
Annotation[].class);
- if (testIdentifier.getSource().isPresent()
- && testIdentifier.getSource().get() instanceof
ClassSource) {
- String className = ((ClassSource)
testIdentifier.getSource().get()).getClassName();
- Class<?> classToRemove =
-
Thread.currentThread().getContextClassLoader().loadClass(className);
- Object invoke = createTestDescription.invoke(
- descriptionClass, classToRemove.getName(),
testIdentifier.getDisplayName(), null);
- runListener
- .getClass()
- .getMethod("testRunStarted", descriptionClass)
- .invoke(runListener, (Object) null);
- runListener
- .getClass()
- .getMethod("testStarted", descriptionClass)
- .invoke(runListener, invoke);
- }
- } catch (NoSuchMethodException e) {
- // ignore as the RunListener might not have implemented any of
those methods
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- });
+ if (testIdentifier.isTest()) {
+ notifyListeners("testStarted", describe(testIdentifier));
+ }
}
@Override
public void executionFinished(TestIdentifier testIdentifier,
TestExecutionResult testExecutionResult) {
- listeners.forEach(runListener -> {
- try {
- Class<?> descriptionClass =
-
Thread.currentThread().getContextClassLoader().loadClass("org.junit.runner.Description");
- Method createTestDescription = descriptionClass.getMethod(
- "createTestDescription", String.class, String.class,
Annotation[].class);
- if (testIdentifier.getSource().isPresent()
- && testIdentifier.getSource().get() instanceof
ClassSource) {
- String className = ((ClassSource)
testIdentifier.getSource().get()).getClassName();
- Class<?> classToRemove =
-
Thread.currentThread().getContextClassLoader().loadClass(className);
- Object invoke = createTestDescription.invoke(
- descriptionClass, classToRemove.getName(),
testIdentifier.getDisplayName(), null);
-
- Class<?> resultClass =
-
Thread.currentThread().getContextClassLoader().loadClass("org.junit.runner.Result");
-
- runListener
- .getClass()
- .getMethod("testRunFinished", resultClass)
- .invoke(runListener,
resultClass.getConstructor().newInstance());
-
- runListener
- .getClass()
- .getMethod("testFinished", descriptionClass)
- .invoke(runListener, invoke);
- }
- } catch (NoSuchMethodException e) {
- // ignore as the RunListener might not have implemented any of
those methods
- } catch (Exception e) {
- throw new RuntimeException(e);
+ Status status = testExecutionResult.getStatus();
+ // like in JUnit 4, a class only shows up when it fails, for example
in @BeforeClass
+ if (!testIdentifier.isTest() && status == SUCCESSFUL) {
+ return;
+ }
+ Object description = describe(testIdentifier);
+ List<Runnable> calls = new ArrayList<>();
+ if (status == FAILED) {
+ for (Throwable failure : failuresOf(testIdentifier,
testExecutionResult)) {
+ calls.add(() -> notifyListeners("testFailure",
newFailure(description, failure)));
}
- });
+ } else if (status == ABORTED) {
+ Throwable error = testExecutionResult
+ .getThrowable()
+ .orElseGet(() -> new TestAbortedException("Test aborted
with no cause"));
+ calls.add(() -> notifyListeners("testAssumptionFailure",
newFailure(description, error)));
+ }
+ if (testIdentifier.isTest()) {
+ calls.add(() -> notifyListeners("testFinished", description));
+ }
+ callAll(calls);
}
@Override
public void executionSkipped(TestIdentifier testIdentifier, String reason)
{
- listeners.forEach(runListener -> {
- try {
- Class<?> descriptionClass =
-
Thread.currentThread().getContextClassLoader().loadClass("org.junit.runner.Description");
- Method createTestDescription = descriptionClass.getMethod(
- "createTestDescription", String.class, String.class,
Annotation[].class);
- if (testIdentifier.getSource().isPresent()
- && testIdentifier.getSource().get() instanceof
ClassSource) {
- String className = ((ClassSource)
testIdentifier.getSource().get()).getClassName();
- Class<?> classToRemove =
-
Thread.currentThread().getContextClassLoader().loadClass(className);
- Object invoke = createTestDescription.invoke(
- descriptionClass, classToRemove.getName(),
testIdentifier.getDisplayName(), null);
- runListener
- .getClass()
- .getMethod("testIgnored", descriptionClass)
- .invoke(runListener, invoke);
- }
- } catch (NoSuchMethodException e) {
- // ignore as the RunListener might not have implemented any of
those methods
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- });
+ notifyListeners("testIgnored", describe(testIdentifier));
}
@Override
public void testPlanExecutionStarted(TestPlan testPlan) {
+ Object suite = describeMainClass(testPlan);
+ if (suite != null) {
+ callAll(asList(
+ () -> notifyListeners("testRunStarted", suite), () ->
notifyListeners("testSuiteStarted", suite)));
+ }
+ }
- String mainTestClass = extractMainClassName(testPlan);
- listeners.forEach(runListener -> {
+ @Override
+ public void testPlanExecutionFinished(TestPlan testPlan) {
+ Object suite = describeMainClass(testPlan);
+ if (suite != null) {
+ callAll(asList(
+ () -> notifyListeners("testSuiteFinished", suite),
+ () -> notifyListeners("testRunFinished",
newInstance(newResult))));
+ }
+ }
+
+ private static List<Throwable> failuresOf(TestIdentifier testIdentifier,
TestExecutionResult result) {
+ // listeners call Failure.getMessage(), which needs an exception
+ Throwable error = result.getThrowable().orElseGet(() -> new
AssertionError("Test failed with no cause"));
+ // Vintage wraps all failures of a test, say in its body and @After,
in one error. JUnit 4 reports each.
+ // Only this exact class: AssertJ soft assertions subclass it and are
one failure, like assertAll.
+ // Vintage can run inside another engine too, like the suite engine.
+ if (error.getClass() == MultipleFailuresError.class
+ &&
testIdentifier.getUniqueId().contains("[engine:junit-vintage]")
+ && madeByVintage((MultipleFailuresError) error,
testClassOf(testIdentifier))) {
+ return ((MultipleFailuresError) error).getFailures();
+ }
+ return singletonList(error);
+ }
+
+ // Vintage wraps two or more failures in an error of its own, once the
test returned. So unlike one the test
+ // threw itself, like assertAll, it has no frame of the test class. Frames
of a runner, Mockito's say, can stay.
+ private static boolean madeByVintage(MultipleFailuresError error, String
testClass) {
+ return error.getFailures().size() > 1
+ && testClass != null
+ && Arrays.stream(error.getStackTrace())
+ .map(StackTraceElement::getClassName)
+ .noneMatch(frame -> frame.equals(testClass) ||
frame.startsWith(testClass + '$'));
Review Comment:
Good catch, fixed in 7a660ec72. The check now looks at the whole hierarchy
of the concrete test class, Object excluded, instead of only the class
declaring the test method. So an error thrown by an inherited `@Before`,
`@After` or test method stays one failure and keeps its heading. If the class
doesn't load, it falls back to the class name Vintage gives.
`keepsAMultipleFailuresErrorOfAnInheritedFixtureAsOneFailure` covers the
inherited fixture, next to the inherited-test regression.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]