soarez commented on a change in pull request #11440:
URL: https://github.com/apache/kafka/pull/11440#discussion_r737853816



##########
File path: clients/src/main/java/org/apache/kafka/common/utils/Exit.java
##########
@@ -30,16 +33,35 @@
         void addShutdownHook(String name, Runnable runnable);
     }
 
+    private static final Set<String> JUNIT_CLASSS_NAMES = new HashSet<>();
+
+    static {
+        
JUNIT_CLASSS_NAMES.add("org.junit.platform.commons.util.ReflectionUtils");
+        
JUNIT_CLASSS_NAMES.add("org.gradle.api.internal.tasks.testing.junit.AbstractJUnitTestClassProcessor");
+    }
+
+    static void throwIfInJunitTest() {
+        for (StackTraceElement[] elements : 
Thread.getAllStackTraces().values()) {
+            for (StackTraceElement element : elements) {
+                if (JUNIT_CLASSS_NAMES.contains(element.getClassName())) {
+                    throw new RuntimeException("Attempted to terminate the VM 
in a junit test.");
+                }
+            }
+        }
+    }

Review comment:
       Is the intention to allow termination to happen from other threads even 
if still running a test?
   i.e. do we want this test to pass as well?
   
   ```scala
     @Test
     def exitWithoutSettingUpHooks(): Unit = {
       val t = new Thread {
         override def run {
           try {
             Exit.exit(1, None)
           } catch {
             case e: RuntimeException => assertEquals("Attempted to terminate 
the VM in a junit test.", e.getMessage)
           }
         }
       }
       t.start()
       t.join()
     }
   ```
   
   It's also maybe slightly nicer to not have to check the stack frames
   
   ```suggestion
       private static final boolean IN_JUNIT_TEST = Stream.of(
               "org.junit.platform.commons.util.ReflectionUtils",
               
"org.gradle.api.internal.tasks.testing.junit.AbstractJUnitTestClassProcessor"
       ).anyMatch(clazz -> {
           try {
               Class.forName(clazz);
               return true;
           } catch (ClassNotFoundException ignored) {
               return false;
           }
       });
   
       static void throwIfInJunitTest() {
           if (IN_JUNIT_TEST) {
               throw new RuntimeException("Attempted to terminate the VM in a 
junit test.");
           }
       }
   ```




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