ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/JSR166TestCase.java
(Generate patch)

Comparing jsr166/src/test/tck/JSR166TestCase.java (file contents):
Revision 1.123 by jsr166, Wed Dec 31 19:05:42 2014 UTC vs.
Revision 1.140 by dl, Mon Sep 7 17:14:06 2015 UTC

# Line 15 | Line 15 | import java.io.ObjectInputStream;
15   import java.io.ObjectOutputStream;
16   import java.lang.management.ManagementFactory;
17   import java.lang.management.ThreadInfo;
18 + import java.lang.reflect.Constructor;
19   import java.lang.reflect.Method;
20 + import java.lang.reflect.Modifier;
21   import java.security.CodeSource;
22   import java.security.Permission;
23   import java.security.PermissionCollection;
# Line 27 | Line 29 | import java.util.ArrayList;
29   import java.util.Arrays;
30   import java.util.Date;
31   import java.util.Enumeration;
32 + import java.util.Iterator;
33   import java.util.List;
34   import java.util.NoSuchElementException;
35   import java.util.PropertyPermission;
# Line 34 | Line 37 | import java.util.concurrent.BlockingQueu
37   import java.util.concurrent.Callable;
38   import java.util.concurrent.CountDownLatch;
39   import java.util.concurrent.CyclicBarrier;
40 + import java.util.concurrent.ExecutionException;
41 + import java.util.concurrent.Executors;
42   import java.util.concurrent.ExecutorService;
43   import java.util.concurrent.Future;
44   import java.util.concurrent.RecursiveAction;
# Line 49 | Line 54 | import java.util.regex.Pattern;
54   import junit.framework.AssertionFailedError;
55   import junit.framework.Test;
56   import junit.framework.TestCase;
57 + import junit.framework.TestResult;
58   import junit.framework.TestSuite;
59  
60   /**
# Line 159 | Line 165 | public class JSR166TestCase extends Test
165          Integer.getInteger("jsr166.runsPerTest", 1);
166  
167      /**
168 +     * The number of repetitions of the test suite (for finding leaks?).
169 +     */
170 +    private static final int suiteRuns =
171 +        Integer.getInteger("jsr166.suiteRuns", 1);
172 +
173 +    public JSR166TestCase() { super(); }
174 +    public JSR166TestCase(String name) { super(name); }
175 +
176 +    /**
177       * A filter for tests to run, matching strings of the form
178       * methodName(className), e.g. "testInvokeAll5(ForkJoinPoolTest)"
179       * Usefully combined with jsr166.runsPerTest.
# Line 197 | Line 212 | public class JSR166TestCase extends Test
212  
213      /**
214       * Runs all JSR166 unit tests using junit.textui.TestRunner.
200     * Optional command line arg provides the number of iterations to
201     * repeat running the tests.
215       */
216      public static void main(String[] args) {
217 +        main(suite(), args);
218 +    }
219 +
220 +    /**
221 +     * Runs all unit tests in the given test suite.
222 +     * Actual behavior influenced by jsr166.* system properties.
223 +     */
224 +    static void main(Test suite, String[] args) {
225          if (useSecurityManager) {
226              System.err.println("Setting a permissive security manager");
227              Policy.setPolicy(permissivePolicy());
228              System.setSecurityManager(new SecurityManager());
229          }
230 <        int iters = (args.length == 0) ? 1 : Integer.parseInt(args[0]);
231 <
232 <        Test s = suite();
233 <        for (int i = 0; i < iters; ++i) {
213 <            junit.textui.TestRunner.run(s);
230 >        for (int i = 0; i < suiteRuns; i++) {
231 >            TestResult result = junit.textui.TestRunner.run(suite);
232 >            if (!result.wasSuccessful())
233 >                System.exit(1);
234              System.gc();
235              System.runFinalization();
236          }
217        System.exit(0);
237      }
238  
239      public static TestSuite newTestSuite(Object... suiteOrClasses) {
# Line 265 | Line 284 | public class JSR166TestCase extends Test
284      public static boolean atLeastJava7() { return JAVA_CLASS_VERSION >= 51.0; }
285      public static boolean atLeastJava8() { return JAVA_CLASS_VERSION >= 52.0; }
286      public static boolean atLeastJava9() {
287 <        // As of 2014-05, java9 still uses 52.0 class file version
288 <        return JAVA_SPECIFICATION_VERSION.startsWith("1.9");
287 >        return JAVA_CLASS_VERSION >= 53.0
288 >            // As of 2015-09, java9 still uses 52.0 class file version
289 >            || JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?(9|[0-9][0-9])$");
290 >    }
291 >    public static boolean atLeastJava10() {
292 >        return JAVA_CLASS_VERSION >= 54.0
293 >            || JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?[0-9][0-9]$");
294      }
295  
296      /**
# Line 355 | Line 379 | public class JSR166TestCase extends Test
379                  "LongAdderTest",
380                  "SplittableRandomTest",
381                  "StampedLockTest",
382 +                "SubmissionPublisherTest",
383                  "ThreadLocalRandom8Test",
384              };
385              addNamedTestClasses(suite, java8TestClassNames);
# Line 363 | Line 388 | public class JSR166TestCase extends Test
388          // Java9+ test classes
389          if (atLeastJava9()) {
390              String[] java9TestClassNames = {
391 <                "ThreadPoolExecutor9Test",
391 >                // Currently empty
392              };
393              addNamedTestClasses(suite, java9TestClassNames);
394          }
# Line 371 | Line 396 | public class JSR166TestCase extends Test
396          return suite;
397      }
398  
399 +    /** Returns list of junit-style test method names in given class. */
400 +    public static ArrayList<String> testMethodNames(Class<?> testClass) {
401 +        Method[] methods = testClass.getDeclaredMethods();
402 +        ArrayList<String> names = new ArrayList<String>(methods.length);
403 +        for (Method method : methods) {
404 +            if (method.getName().startsWith("test")
405 +                && Modifier.isPublic(method.getModifiers())
406 +                // method.getParameterCount() requires jdk8+
407 +                && method.getParameterTypes().length == 0) {
408 +                names.add(method.getName());
409 +            }
410 +        }
411 +        return names;
412 +    }
413 +
414 +    /**
415 +     * Returns junit-style testSuite for the given test class, but
416 +     * parameterized by passing extra data to each test.
417 +     */
418 +    public static <ExtraData> Test parameterizedTestSuite
419 +        (Class<? extends JSR166TestCase> testClass,
420 +         Class<ExtraData> dataClass,
421 +         ExtraData data) {
422 +        try {
423 +            TestSuite suite = new TestSuite();
424 +            Constructor c =
425 +                testClass.getDeclaredConstructor(dataClass, String.class);
426 +            for (String methodName : testMethodNames(testClass))
427 +                suite.addTest((Test) c.newInstance(data, methodName));
428 +            return suite;
429 +        } catch (Exception e) {
430 +            throw new Error(e);
431 +        }
432 +    }
433 +
434 +    /**
435 +     * Returns junit-style testSuite for the jdk8 extension of the
436 +     * given test class, but parameterized by passing extra data to
437 +     * each test.  Uses reflection to allow compilation in jdk7.
438 +     */
439 +    public static <ExtraData> Test jdk8ParameterizedTestSuite
440 +        (Class<? extends JSR166TestCase> testClass,
441 +         Class<ExtraData> dataClass,
442 +         ExtraData data) {
443 +        if (atLeastJava8()) {
444 +            String name = testClass.getName();
445 +            String name8 = name.replaceAll("Test$", "8Test");
446 +            if (name.equals(name8)) throw new Error(name);
447 +            try {
448 +                return (Test)
449 +                    Class.forName(name8)
450 +                    .getMethod("testSuite", new Class[] { dataClass })
451 +                    .invoke(null, data);
452 +            } catch (Exception e) {
453 +                throw new Error(e);
454 +            }
455 +        } else {
456 +            return new TestSuite();
457 +        }
458 +
459 +    }
460 +
461      // Delays for timing-dependent tests, in milliseconds.
462  
463      public static long SHORT_DELAY_MS;
# Line 405 | Line 492 | public class JSR166TestCase extends Test
492      }
493  
494      /**
495 <     * Returns a new Date instance representing a time delayMillis
496 <     * milliseconds in the future.
495 >     * Returns a new Date instance representing a time at least
496 >     * delayMillis milliseconds in the future.
497       */
498      Date delayedDate(long delayMillis) {
499 <        return new Date(System.currentTimeMillis() + delayMillis);
499 >        // Add 1 because currentTimeMillis is known to round into the past.
500 >        return new Date(System.currentTimeMillis() + delayMillis + 1);
501      }
502  
503      /**
# Line 465 | Line 553 | public class JSR166TestCase extends Test
553      }
554  
555      /**
556 <     * Find missing try { ... } finally { joinPool(e); }
556 >     * Finds missing try { ... } finally { joinPool(e); }
557       */
558      void checkForkJoinPoolThreadLeaks() throws InterruptedException {
559          Thread[] survivors = new Thread[5];
# Line 477 | Line 565 | public class JSR166TestCase extends Test
565                  // give thread some time to terminate
566                  thread.join(LONG_DELAY_MS);
567                  if (!thread.isAlive()) continue;
480                thread.stop();
568                  throw new AssertionFailedError
569                      (String.format("Found leaked ForkJoinPool thread test=%s thread=%s%n",
570                                     toString(), name));
# Line 563 | Line 650 | public class JSR166TestCase extends Test
650      public void threadAssertEquals(Object x, Object y) {
651          try {
652              assertEquals(x, y);
653 <        } catch (AssertionFailedError t) {
654 <            threadRecordFailure(t);
655 <            throw t;
656 <        } catch (Throwable t) {
657 <            threadUnexpectedException(t);
653 >        } catch (AssertionFailedError fail) {
654 >            threadRecordFailure(fail);
655 >            throw fail;
656 >        } catch (Throwable fail) {
657 >            threadUnexpectedException(fail);
658          }
659      }
660  
# Line 579 | Line 666 | public class JSR166TestCase extends Test
666      public void threadAssertSame(Object x, Object y) {
667          try {
668              assertSame(x, y);
669 <        } catch (AssertionFailedError t) {
670 <            threadRecordFailure(t);
671 <            throw t;
669 >        } catch (AssertionFailedError fail) {
670 >            threadRecordFailure(fail);
671 >            throw fail;
672          }
673      }
674  
# Line 643 | Line 730 | public class JSR166TestCase extends Test
730      /**
731       * Waits out termination of a thread pool or fails doing so.
732       */
733 <    void joinPool(ExecutorService exec) {
733 >    void joinPool(ExecutorService pool) {
734          try {
735 <            exec.shutdown();
736 <            if (!exec.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS))
737 <                fail("ExecutorService " + exec +
735 >            pool.shutdown();
736 >            if (!pool.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS))
737 >                fail("ExecutorService " + pool +
738                       " did not terminate in a timely manner");
739          } catch (SecurityException ok) {
740              // Allowed in case test doesn't have privs
741 <        } catch (InterruptedException ie) {
741 >        } catch (InterruptedException fail) {
742              fail("Unexpected InterruptedException");
743          }
744      }
745  
746 +    /** Like Runnable, but with the freedom to throw anything */
747 +    interface Thunk { public void run() throws Throwable; }
748 +
749 +    /**
750 +     * Runs all the given tasks in parallel, failing if any fail.
751 +     * Useful for running multiple variants of tests that are
752 +     * necessarily individually slow because they must block.
753 +     */
754 +    void testInParallel(Thunk ... thunks) {
755 +        ExecutorService pool = Executors.newCachedThreadPool();
756 +        try {
757 +            ArrayList<Future<?>> futures = new ArrayList<>(thunks.length);
758 +            for (final Thunk thunk : thunks)
759 +                futures.add(pool.submit(new CheckedRunnable() {
760 +                    public void realRun() throws Throwable { thunk.run();}}));
761 +            for (Future<?> future : futures)
762 +                try {
763 +                    assertNull(future.get(LONG_DELAY_MS, MILLISECONDS));
764 +                } catch (ExecutionException ex) {
765 +                    threadUnexpectedException(ex.getCause());
766 +                } catch (Exception ex) {
767 +                    threadUnexpectedException(ex);
768 +                }
769 +        } finally {
770 +            joinPool(pool);
771 +        }
772 +    }
773 +
774      /**
775       * A debugging tool to print all stack traces, as jstack does.
776       */
# Line 682 | Line 797 | public class JSR166TestCase extends Test
797              // No need to optimize the failing case via Thread.join.
798              delay(millis);
799              assertTrue(thread.isAlive());
800 <        } catch (InterruptedException ie) {
800 >        } catch (InterruptedException fail) {
801              fail("Unexpected InterruptedException");
802          }
803      }
# Line 704 | Line 819 | public class JSR166TestCase extends Test
819              delay(millis);
820              for (Thread thread : threads)
821                  assertTrue(thread.isAlive());
822 <        } catch (InterruptedException ie) {
822 >        } catch (InterruptedException fail) {
823              fail("Unexpected InterruptedException");
824          }
825      }
# Line 726 | Line 841 | public class JSR166TestCase extends Test
841              future.get(timeoutMillis, MILLISECONDS);
842              shouldThrow();
843          } catch (TimeoutException success) {
844 <        } catch (Exception e) {
845 <            threadUnexpectedException(e);
844 >        } catch (Exception fail) {
845 >            threadUnexpectedException(fail);
846          } finally { future.cancel(true); }
847          assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
848      }
# Line 883 | Line 998 | public class JSR166TestCase extends Test
998      void sleep(long millis) {
999          try {
1000              delay(millis);
1001 <        } catch (InterruptedException ie) {
1001 >        } catch (InterruptedException fail) {
1002              AssertionFailedError afe =
1003                  new AssertionFailedError("Unexpected InterruptedException");
1004 <            afe.initCause(ie);
1004 >            afe.initCause(fail);
1005              throw afe;
1006          }
1007      }
# Line 924 | Line 1039 | public class JSR166TestCase extends Test
1039      /**
1040       * Returns the number of milliseconds since time given by
1041       * startNanoTime, which must have been previously returned from a
1042 <     * call to {@link System.nanoTime()}.
1042 >     * call to {@link System#nanoTime()}.
1043       */
1044      static long millisElapsedSince(long startNanoTime) {
1045          return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
# Line 978 | Line 1093 | public class JSR166TestCase extends Test
1093      void awaitTermination(Thread t, long timeoutMillis) {
1094          try {
1095              t.join(timeoutMillis);
1096 <        } catch (InterruptedException ie) {
1097 <            threadUnexpectedException(ie);
1096 >        } catch (InterruptedException fail) {
1097 >            threadUnexpectedException(fail);
1098          } finally {
1099              if (t.getState() != Thread.State.TERMINATED) {
1100                  t.interrupt();
# Line 1005 | Line 1120 | public class JSR166TestCase extends Test
1120          public final void run() {
1121              try {
1122                  realRun();
1123 <            } catch (Throwable t) {
1124 <                threadUnexpectedException(t);
1123 >            } catch (Throwable fail) {
1124 >                threadUnexpectedException(fail);
1125              }
1126          }
1127      }
# Line 1060 | Line 1175 | public class JSR166TestCase extends Test
1175                  threadShouldThrow("InterruptedException");
1176              } catch (InterruptedException success) {
1177                  threadAssertFalse(Thread.interrupted());
1178 <            } catch (Throwable t) {
1179 <                threadUnexpectedException(t);
1178 >            } catch (Throwable fail) {
1179 >                threadUnexpectedException(fail);
1180              }
1181          }
1182      }
# Line 1072 | Line 1187 | public class JSR166TestCase extends Test
1187          public final T call() {
1188              try {
1189                  return realCall();
1190 <            } catch (Throwable t) {
1191 <                threadUnexpectedException(t);
1190 >            } catch (Throwable fail) {
1191 >                threadUnexpectedException(fail);
1192                  return null;
1193              }
1194          }
# Line 1090 | Line 1205 | public class JSR166TestCase extends Test
1205                  return result;
1206              } catch (InterruptedException success) {
1207                  threadAssertFalse(Thread.interrupted());
1208 <            } catch (Throwable t) {
1209 <                threadUnexpectedException(t);
1208 >            } catch (Throwable fail) {
1209 >                threadUnexpectedException(fail);
1210              }
1211              return null;
1212          }
# Line 1131 | Line 1246 | public class JSR166TestCase extends Test
1246      public void await(CountDownLatch latch) {
1247          try {
1248              assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
1249 <        } catch (Throwable t) {
1250 <            threadUnexpectedException(t);
1249 >        } catch (Throwable fail) {
1250 >            threadUnexpectedException(fail);
1251          }
1252      }
1253  
1254      public void await(Semaphore semaphore) {
1255          try {
1256              assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
1257 <        } catch (Throwable t) {
1258 <            threadUnexpectedException(t);
1257 >        } catch (Throwable fail) {
1258 >            threadUnexpectedException(fail);
1259          }
1260      }
1261  
# Line 1334 | Line 1449 | public class JSR166TestCase extends Test
1449          @Override protected final void compute() {
1450              try {
1451                  realCompute();
1452 <            } catch (Throwable t) {
1453 <                threadUnexpectedException(t);
1452 >            } catch (Throwable fail) {
1453 >                threadUnexpectedException(fail);
1454              }
1455          }
1456      }
# Line 1349 | Line 1464 | public class JSR166TestCase extends Test
1464          @Override protected final T compute() {
1465              try {
1466                  return realCompute();
1467 <            } catch (Throwable t) {
1468 <                threadUnexpectedException(t);
1467 >            } catch (Throwable fail) {
1468 >                threadUnexpectedException(fail);
1469                  return null;
1470              }
1471          }
# Line 1374 | Line 1489 | public class JSR166TestCase extends Test
1489          public int await() {
1490              try {
1491                  return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1492 <            } catch (TimeoutException e) {
1492 >            } catch (TimeoutException timedOut) {
1493                  throw new AssertionFailedError("timed out");
1494 <            } catch (Exception e) {
1494 >            } catch (Exception fail) {
1495                  AssertionFailedError afe =
1496 <                    new AssertionFailedError("Unexpected exception: " + e);
1497 <                afe.initCause(e);
1496 >                    new AssertionFailedError("Unexpected exception: " + fail);
1497 >                afe.initCause(fail);
1498                  throw afe;
1499              }
1500          }
# Line 1407 | Line 1522 | public class JSR166TestCase extends Test
1522                  q.remove();
1523                  shouldThrow();
1524              } catch (NoSuchElementException success) {}
1525 <        } catch (InterruptedException ie) {
1411 <            threadUnexpectedException(ie);
1412 <        }
1525 >        } catch (InterruptedException fail) { threadUnexpectedException(fail); }
1526      }
1527  
1528      void assertSerialEquals(Object x, Object y) {
# Line 1428 | Line 1541 | public class JSR166TestCase extends Test
1541              oos.flush();
1542              oos.close();
1543              return bos.toByteArray();
1544 <        } catch (Throwable t) {
1545 <            threadUnexpectedException(t);
1544 >        } catch (Throwable fail) {
1545 >            threadUnexpectedException(fail);
1546              return new byte[0];
1547          }
1548      }
# Line 1442 | Line 1555 | public class JSR166TestCase extends Test
1555              T clone = (T) ois.readObject();
1556              assertSame(o.getClass(), clone.getClass());
1557              return clone;
1558 <        } catch (Throwable t) {
1559 <            threadUnexpectedException(t);
1558 >        } catch (Throwable fail) {
1559 >            threadUnexpectedException(fail);
1560              return null;
1561          }
1562      }
# Line 1468 | Line 1581 | public class JSR166TestCase extends Test
1581                  shouldThrow(expectedExceptionClass.getName());
1582          }
1583      }
1584 +
1585 +    public void assertIteratorExhausted(Iterator<?> it) {
1586 +        try {
1587 +            it.next();
1588 +            shouldThrow();
1589 +        } catch (NoSuchElementException success) {}
1590 +        assertFalse(it.hasNext());
1591 +    }
1592   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines