Copilot commented on code in PR #3654:
URL: https://github.com/apache/maven-surefire/pull/3654#discussion_r4731143327


##########
surefire-providers/surefire-junit-platform/src/main/java/org/apache/maven/surefire/junitplatform/JUnit4ListenersAdapter.java:
##########
@@ -19,185 +19,262 @@
 package org.apache.maven.surefire.junitplatform;
 
 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.List;
 
 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.Collections.singletonList;
+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();
+
+    // null before JUnit 4.12, no listener is thread safe then
+    private final Class<? extends Annotation> threadSafe = 
threadSafeAnnotation();
+
+    // 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;
     }
 
     @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);
+        if (status == FAILED) {
+            for (Throwable failure : failuresOf(testIdentifier, 
testExecutionResult)) {
+                notifyListeners("testFailure", newFailure(description, 
failure));
             }
-        });
+        } else if (status == ABORTED) {
+            Throwable error = testExecutionResult
+                    .getThrowable()
+                    .orElseGet(() -> new TestAbortedException("Test aborted 
with no cause"));
+            notifyListeners("testAssumptionFailure", newFailure(description, 
error));
+        }
+        if (testIdentifier.isTest()) {
+            notifyListeners("testFinished", description);
+        }
     }
 
     @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) {
-
-        String mainTestClass = extractMainClassName(testPlan);
-        listeners.forEach(runListener -> {
-            try {
-                Class<?> descriptionClass =
-                        
Thread.currentThread().getContextClassLoader().loadClass("org.junit.runner.Description");
-                Method createSuiteDescription = 
descriptionClass.getMethod("createSuiteDescription", Class.class);
-                if (mainTestClass != null) {
-                    Class<?> classToRemove =
-                            
Thread.currentThread().getContextClassLoader().loadClass(mainTestClass);
-                    Object invoke = 
createSuiteDescription.invoke(descriptionClass, classToRemove);
-                    runListener
-                            .getClass()
-                            .getMethod("testRunStarted", descriptionClass)
-                            .invoke(runListener, invoke);
-                    runListener
-                            .getClass()
-                            .getMethod("testSuiteStarted", 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);
-            }
-        });
+        Object suite = describeMainClass(testPlan);
+        if (suite != null) {
+            notifyListeners("testRunStarted", suite);
+            notifyListeners("testSuiteStarted", suite);
+        }
     }
 
     @Override
     public void testPlanExecutionFinished(TestPlan testPlan) {
+        Object suite = describeMainClass(testPlan);
+        if (suite != null) {
+            notifyListeners("testSuiteFinished", suite);
+            notifyListeners("testRunFinished", 
newInstance("org.junit.runner.Result", new Class<?>[0]));
+        }
+    }
+
+    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.
+        if (error.getClass() == MultipleFailuresError.class
+                && 
testIdentifier.getUniqueId().startsWith("[engine:junit-vintage]")) {
+            return ((MultipleFailuresError) error).getFailures();
+        }
+        return singletonList(error);
+    }
+
+    private Object describe(TestIdentifier testIdentifier) {
+        TestSource source = testIdentifier.getSource().orElse(null);
+        String name = testIdentifier.getLegacyReportingName();
+        if (source instanceof MethodSource) {
+            MethodSource method = (MethodSource) source;
+            return testDescription(method.getClassName(), name, 
annotationsOf(method));
+        }
+        if (source instanceof ClassSource) {
+            String className = ((ClassSource) source).getClassName();
+            // Vintage gives some tests a ClassSource, Parameterized ones for 
instance
+            return testIdentifier.isTest()
+                    ? testDescription(className, name, NO_ANNOTATIONS)
+                    : suiteDescription(className);

Review Comment:
   This class-level description is created with `NO_ANNOTATIONS`, so listeners 
receive a `@BeforeClass` failure or class-level ignore without the class's 
annotations. JUnit 4 includes those annotations in its suite descriptions 
([ParentRunner, upstream default 
branch](https://github.com/junit-team/junit4/blob/890f3c972647de378f25e7271d8fbbd9d3456b79/src/main/java/org/junit/runners/ParentRunner.java#L392-L400));
 listeners reading `@Category` or custom metadata from the description will get 
null here. Use the Class-based suite factory, as `describeMainClass()` already 
does, to preserve that metadata.



##########
surefire-providers/surefire-junit-platform/src/main/java/org/apache/maven/surefire/junitplatform/JUnit4ListenersAdapter.java:
##########
@@ -19,185 +19,262 @@
 package org.apache.maven.surefire.junitplatform;
 
 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.List;
 
 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.Collections.singletonList;
+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();
+
+    // null before JUnit 4.12, no listener is thread safe then
+    private final Class<? extends Annotation> threadSafe = 
threadSafeAnnotation();
+
+    // 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;
     }
 
     @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);
+        if (status == FAILED) {
+            for (Throwable failure : failuresOf(testIdentifier, 
testExecutionResult)) {
+                notifyListeners("testFailure", newFailure(description, 
failure));
             }
-        });
+        } else if (status == ABORTED) {
+            Throwable error = testExecutionResult
+                    .getThrowable()
+                    .orElseGet(() -> new TestAbortedException("Test aborted 
with no cause"));
+            notifyListeners("testAssumptionFailure", newFailure(description, 
error));
+        }
+        if (testIdentifier.isTest()) {
+            notifyListeners("testFinished", description);
+        }
     }
 
     @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) {
-
-        String mainTestClass = extractMainClassName(testPlan);
-        listeners.forEach(runListener -> {
-            try {
-                Class<?> descriptionClass =
-                        
Thread.currentThread().getContextClassLoader().loadClass("org.junit.runner.Description");
-                Method createSuiteDescription = 
descriptionClass.getMethod("createSuiteDescription", Class.class);
-                if (mainTestClass != null) {
-                    Class<?> classToRemove =
-                            
Thread.currentThread().getContextClassLoader().loadClass(mainTestClass);
-                    Object invoke = 
createSuiteDescription.invoke(descriptionClass, classToRemove);
-                    runListener
-                            .getClass()
-                            .getMethod("testRunStarted", descriptionClass)
-                            .invoke(runListener, invoke);
-                    runListener
-                            .getClass()
-                            .getMethod("testSuiteStarted", 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);
-            }
-        });
+        Object suite = describeMainClass(testPlan);
+        if (suite != null) {
+            notifyListeners("testRunStarted", suite);
+            notifyListeners("testSuiteStarted", suite);
+        }
     }
 
     @Override
     public void testPlanExecutionFinished(TestPlan testPlan) {
+        Object suite = describeMainClass(testPlan);
+        if (suite != null) {
+            notifyListeners("testSuiteFinished", suite);
+            notifyListeners("testRunFinished", 
newInstance("org.junit.runner.Result", new Class<?>[0]));
+        }
+    }
+
+    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.
+        if (error.getClass() == MultipleFailuresError.class
+                && 
testIdentifier.getUniqueId().startsWith("[engine:junit-vintage]")) {
+            return ((MultipleFailuresError) error).getFailures();

Review Comment:
   This also unwraps a `MultipleFailuresError` thrown directly by a JUnit 4 
test, such as a test using Jupiter's `assertAll`. Vintage [passes a sole 
failure through 
unchanged](https://github.com/junit-team/junit-framework/blob/5e2b5533db587737b06b9091f23cf09926ab55ae/junit-vintage-engine/src/main/java/org/junit/vintage/engine/execution/TestRun.java#L195-L202),
 whereas [JUnit 4 only unwraps 
`MultipleFailureException`](https://github.com/junit-team/junit4/blob/890f3c972647de378f25e7271d8fbbd9d3456b79/src/main/java/org/junit/internal/runners/model/EachTestNotifier.java#L16-L22)
 (both links show default-branch implementations). Consequently, listeners 
receive several failures instead of the original single failure and lose its 
aggregate message. Please distinguish Vintage-generated aggregates from 
test-thrown errors, and add a Vintage regression case to 
`keepsOtherMultipleFailuresAsOneFailure`.



-- 
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]

Reply via email to