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.120 by jsr166, Wed Jun 25 15:32:10 2014 UTC vs.
Revision 1.138 by jsr166, Fri Sep 4 19:35:46 2015 UTC

# Line 6 | Line 6
6   * Pat Fisher, Mike Judd.
7   */
8  
9 < import junit.framework.*;
9 > import static java.util.concurrent.TimeUnit.MILLISECONDS;
10 > import static java.util.concurrent.TimeUnit.NANOSECONDS;
11 >
12   import java.io.ByteArrayInputStream;
13   import java.io.ByteArrayOutputStream;
14   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;
24 + import java.security.Permissions;
25 + import java.security.Policy;
26 + import java.security.ProtectionDomain;
27 + import java.security.SecurityPermission;
28   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;
36 < import java.util.concurrent.*;
37 < import java.util.concurrent.atomic.AtomicBoolean;
36 > import java.util.concurrent.BlockingQueue;
37 > import java.util.concurrent.Callable;
38 > import java.util.concurrent.CountDownLatch;
39 > import java.util.concurrent.CyclicBarrier;
40 > import java.util.concurrent.ExecutorService;
41 > import java.util.concurrent.Future;
42 > import java.util.concurrent.RecursiveAction;
43 > import java.util.concurrent.RecursiveTask;
44 > import java.util.concurrent.RejectedExecutionHandler;
45 > import java.util.concurrent.Semaphore;
46 > import java.util.concurrent.ThreadFactory;
47 > import java.util.concurrent.ThreadPoolExecutor;
48 > import java.util.concurrent.TimeoutException;
49   import java.util.concurrent.atomic.AtomicReference;
27 import static java.util.concurrent.TimeUnit.MILLISECONDS;
28 import static java.util.concurrent.TimeUnit.NANOSECONDS;
50   import java.util.regex.Pattern;
51 < import java.security.CodeSource;
52 < import java.security.Permission;
53 < import java.security.PermissionCollection;
54 < import java.security.Permissions;
55 < import java.security.Policy;
56 < import java.security.ProtectionDomain;
36 < import java.security.SecurityPermission;
51 >
52 > import junit.framework.AssertionFailedError;
53 > import junit.framework.Test;
54 > import junit.framework.TestCase;
55 > import junit.framework.TestResult;
56 > import junit.framework.TestSuite;
57  
58   /**
59   * Base class for JSR166 Junit TCK tests.  Defines some constants,
# Line 143 | Line 163 | public class JSR166TestCase extends Test
163          Integer.getInteger("jsr166.runsPerTest", 1);
164  
165      /**
166 +     * The number of repetitions of the test suite (for finding leaks?).
167 +     */
168 +    private static final int suiteRuns =
169 +        Integer.getInteger("jsr166.suiteRuns", 1);
170 +
171 +    public JSR166TestCase() { super(); }
172 +    public JSR166TestCase(String name) { super(name); }
173 +
174 +    /**
175       * A filter for tests to run, matching strings of the form
176       * methodName(className), e.g. "testInvokeAll5(ForkJoinPoolTest)"
177       * Usefully combined with jsr166.runsPerTest.
# Line 181 | Line 210 | public class JSR166TestCase extends Test
210  
211      /**
212       * Runs all JSR166 unit tests using junit.textui.TestRunner.
184     * Optional command line arg provides the number of iterations to
185     * repeat running the tests.
213       */
214      public static void main(String[] args) {
215 +        main(suite(), args);
216 +    }
217 +
218 +    /**
219 +     * Runs all unit tests in the given test suite.
220 +     * Actual behavior influenced by jsr166.* system properties.
221 +     */
222 +    static void main(Test suite, String[] args) {
223          if (useSecurityManager) {
224              System.err.println("Setting a permissive security manager");
225              Policy.setPolicy(permissivePolicy());
226              System.setSecurityManager(new SecurityManager());
227          }
228 <        int iters = (args.length == 0) ? 1 : Integer.parseInt(args[0]);
229 <
230 <        Test s = suite();
231 <        for (int i = 0; i < iters; ++i) {
197 <            junit.textui.TestRunner.run(s);
228 >        for (int i = 0; i < suiteRuns; i++) {
229 >            TestResult result = junit.textui.TestRunner.run(suite);
230 >            if (!result.wasSuccessful())
231 >                System.exit(1);
232              System.gc();
233              System.runFinalization();
234          }
201        System.exit(0);
235      }
236  
237      public static TestSuite newTestSuite(Object... suiteOrClasses) {
# Line 249 | Line 282 | public class JSR166TestCase extends Test
282      public static boolean atLeastJava7() { return JAVA_CLASS_VERSION >= 51.0; }
283      public static boolean atLeastJava8() { return JAVA_CLASS_VERSION >= 52.0; }
284      public static boolean atLeastJava9() {
285 <        // As of 2014-05, java9 still uses 52.0 class file version
286 <        return JAVA_SPECIFICATION_VERSION.startsWith("1.9");
285 >        return JAVA_CLASS_VERSION >= 53.0
286 >            // As of 2015-09, java9 still uses 52.0 class file version
287 >            || JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?(9|[0-9][0-9])$");
288 >    }
289 >    public static boolean atLeastJava10() {
290 >        return JAVA_CLASS_VERSION >= 54.0
291 >            || JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?[0-9][0-9]$");
292      }
293  
294      /**
# Line 347 | Line 385 | public class JSR166TestCase extends Test
385          // Java9+ test classes
386          if (atLeastJava9()) {
387              String[] java9TestClassNames = {
388 <                "ThreadPoolExecutor9Test",
388 >                // Currently empty
389              };
390              addNamedTestClasses(suite, java9TestClassNames);
391          }
# Line 355 | Line 393 | public class JSR166TestCase extends Test
393          return suite;
394      }
395  
396 +    /** Returns list of junit-style test method names in given class. */
397 +    public static ArrayList<String> testMethodNames(Class<?> testClass) {
398 +        Method[] methods = testClass.getDeclaredMethods();
399 +        ArrayList<String> names = new ArrayList<String>(methods.length);
400 +        for (Method method : methods) {
401 +            if (method.getName().startsWith("test")
402 +                && Modifier.isPublic(method.getModifiers())
403 +                // method.getParameterCount() requires jdk8+
404 +                && method.getParameterTypes().length == 0) {
405 +                names.add(method.getName());
406 +            }
407 +        }
408 +        return names;
409 +    }
410 +
411 +    /**
412 +     * Returns junit-style testSuite for the given test class, but
413 +     * parameterized by passing extra data to each test.
414 +     */
415 +    public static <ExtraData> Test parameterizedTestSuite
416 +        (Class<? extends JSR166TestCase> testClass,
417 +         Class<ExtraData> dataClass,
418 +         ExtraData data) {
419 +        try {
420 +            TestSuite suite = new TestSuite();
421 +            Constructor c =
422 +                testClass.getDeclaredConstructor(dataClass, String.class);
423 +            for (String methodName : testMethodNames(testClass))
424 +                suite.addTest((Test) c.newInstance(data, methodName));
425 +            return suite;
426 +        } catch (Exception e) {
427 +            throw new Error(e);
428 +        }
429 +    }
430 +
431 +    /**
432 +     * Returns junit-style testSuite for the jdk8 extension of the
433 +     * given test class, but parameterized by passing extra data to
434 +     * each test.  Uses reflection to allow compilation in jdk7.
435 +     */
436 +    public static <ExtraData> Test jdk8ParameterizedTestSuite
437 +        (Class<? extends JSR166TestCase> testClass,
438 +         Class<ExtraData> dataClass,
439 +         ExtraData data) {
440 +        if (atLeastJava8()) {
441 +            String name = testClass.getName();
442 +            String name8 = name.replaceAll("Test$", "8Test");
443 +            if (name.equals(name8)) throw new Error(name);
444 +            try {
445 +                return (Test)
446 +                    Class.forName(name8)
447 +                    .getMethod("testSuite", new Class[] { dataClass })
448 +                    .invoke(null, data);
449 +            } catch (Exception e) {
450 +                throw new Error(e);
451 +            }
452 +        } else {
453 +            return new TestSuite();
454 +        }
455 +
456 +    }
457 +
458      // Delays for timing-dependent tests, in milliseconds.
459  
460      public static long SHORT_DELAY_MS;
# Line 389 | Line 489 | public class JSR166TestCase extends Test
489      }
490  
491      /**
492 <     * Returns a new Date instance representing a time delayMillis
493 <     * milliseconds in the future.
492 >     * Returns a new Date instance representing a time at least
493 >     * delayMillis milliseconds in the future.
494       */
495      Date delayedDate(long delayMillis) {
496 <        return new Date(System.currentTimeMillis() + delayMillis);
496 >        // Add 1 because currentTimeMillis is known to round into the past.
497 >        return new Date(System.currentTimeMillis() + delayMillis + 1);
498      }
499  
500      /**
# Line 449 | Line 550 | public class JSR166TestCase extends Test
550      }
551  
552      /**
553 <     * Find missing try { ... } finally { joinPool(e); }
553 >     * Finds missing try { ... } finally { joinPool(e); }
554       */
555      void checkForkJoinPoolThreadLeaks() throws InterruptedException {
556          Thread[] survivors = new Thread[5];
# Line 461 | Line 562 | public class JSR166TestCase extends Test
562                  // give thread some time to terminate
563                  thread.join(LONG_DELAY_MS);
564                  if (!thread.isAlive()) continue;
464                thread.stop();
565                  throw new AssertionFailedError
566                      (String.format("Found leaked ForkJoinPool thread test=%s thread=%s%n",
567                                     toString(), name));
# Line 547 | Line 647 | public class JSR166TestCase extends Test
647      public void threadAssertEquals(Object x, Object y) {
648          try {
649              assertEquals(x, y);
650 <        } catch (AssertionFailedError t) {
651 <            threadRecordFailure(t);
652 <            throw t;
653 <        } catch (Throwable t) {
654 <            threadUnexpectedException(t);
650 >        } catch (AssertionFailedError fail) {
651 >            threadRecordFailure(fail);
652 >            throw fail;
653 >        } catch (Throwable fail) {
654 >            threadUnexpectedException(fail);
655          }
656      }
657  
# Line 563 | Line 663 | public class JSR166TestCase extends Test
663      public void threadAssertSame(Object x, Object y) {
664          try {
665              assertSame(x, y);
666 <        } catch (AssertionFailedError t) {
667 <            threadRecordFailure(t);
668 <            throw t;
666 >        } catch (AssertionFailedError fail) {
667 >            threadRecordFailure(fail);
668 >            throw fail;
669          }
670      }
671  
# Line 630 | Line 730 | public class JSR166TestCase extends Test
730      void joinPool(ExecutorService exec) {
731          try {
732              exec.shutdown();
733 <            assertTrue("ExecutorService did not terminate in a timely manner",
734 <                       exec.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS));
733 >            if (!exec.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS))
734 >                fail("ExecutorService " + exec +
735 >                     " did not terminate in a timely manner");
736          } catch (SecurityException ok) {
737              // Allowed in case test doesn't have privs
738 <        } catch (InterruptedException ie) {
738 >        } catch (InterruptedException fail) {
739              fail("Unexpected InterruptedException");
740          }
741      }
# Line 665 | Line 766 | public class JSR166TestCase extends Test
766              // No need to optimize the failing case via Thread.join.
767              delay(millis);
768              assertTrue(thread.isAlive());
769 <        } catch (InterruptedException ie) {
769 >        } catch (InterruptedException fail) {
770              fail("Unexpected InterruptedException");
771          }
772      }
# Line 687 | Line 788 | public class JSR166TestCase extends Test
788              delay(millis);
789              for (Thread thread : threads)
790                  assertTrue(thread.isAlive());
791 <        } catch (InterruptedException ie) {
791 >        } catch (InterruptedException fail) {
792              fail("Unexpected InterruptedException");
793          }
794      }
# Line 709 | Line 810 | public class JSR166TestCase extends Test
810              future.get(timeoutMillis, MILLISECONDS);
811              shouldThrow();
812          } catch (TimeoutException success) {
813 <        } catch (Exception e) {
814 <            threadUnexpectedException(e);
813 >        } catch (Exception fail) {
814 >            threadUnexpectedException(fail);
815          } finally { future.cancel(true); }
816          assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
817      }
# Line 866 | Line 967 | public class JSR166TestCase extends Test
967      void sleep(long millis) {
968          try {
969              delay(millis);
970 <        } catch (InterruptedException ie) {
970 >        } catch (InterruptedException fail) {
971              AssertionFailedError afe =
972                  new AssertionFailedError("Unexpected InterruptedException");
973 <            afe.initCause(ie);
973 >            afe.initCause(fail);
974              throw afe;
975          }
976      }
# Line 907 | Line 1008 | public class JSR166TestCase extends Test
1008      /**
1009       * Returns the number of milliseconds since time given by
1010       * startNanoTime, which must have been previously returned from a
1011 <     * call to {@link System.nanoTime()}.
1011 >     * call to {@link System#nanoTime()}.
1012       */
1013      static long millisElapsedSince(long startNanoTime) {
1014          return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
# Line 961 | Line 1062 | public class JSR166TestCase extends Test
1062      void awaitTermination(Thread t, long timeoutMillis) {
1063          try {
1064              t.join(timeoutMillis);
1065 <        } catch (InterruptedException ie) {
1066 <            threadUnexpectedException(ie);
1065 >        } catch (InterruptedException fail) {
1066 >            threadUnexpectedException(fail);
1067          } finally {
1068              if (t.getState() != Thread.State.TERMINATED) {
1069                  t.interrupt();
# Line 988 | Line 1089 | public class JSR166TestCase extends Test
1089          public final void run() {
1090              try {
1091                  realRun();
1092 <            } catch (Throwable t) {
1093 <                threadUnexpectedException(t);
1092 >            } catch (Throwable fail) {
1093 >                threadUnexpectedException(fail);
1094              }
1095          }
1096      }
# Line 1043 | Line 1144 | public class JSR166TestCase extends Test
1144                  threadShouldThrow("InterruptedException");
1145              } catch (InterruptedException success) {
1146                  threadAssertFalse(Thread.interrupted());
1147 <            } catch (Throwable t) {
1148 <                threadUnexpectedException(t);
1147 >            } catch (Throwable fail) {
1148 >                threadUnexpectedException(fail);
1149              }
1150          }
1151      }
# Line 1055 | Line 1156 | public class JSR166TestCase extends Test
1156          public final T call() {
1157              try {
1158                  return realCall();
1159 <            } catch (Throwable t) {
1160 <                threadUnexpectedException(t);
1159 >            } catch (Throwable fail) {
1160 >                threadUnexpectedException(fail);
1161                  return null;
1162              }
1163          }
# Line 1073 | Line 1174 | public class JSR166TestCase extends Test
1174                  return result;
1175              } catch (InterruptedException success) {
1176                  threadAssertFalse(Thread.interrupted());
1177 <            } catch (Throwable t) {
1178 <                threadUnexpectedException(t);
1177 >            } catch (Throwable fail) {
1178 >                threadUnexpectedException(fail);
1179              }
1180              return null;
1181          }
# Line 1114 | Line 1215 | public class JSR166TestCase extends Test
1215      public void await(CountDownLatch latch) {
1216          try {
1217              assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
1218 <        } catch (Throwable t) {
1219 <            threadUnexpectedException(t);
1218 >        } catch (Throwable fail) {
1219 >            threadUnexpectedException(fail);
1220          }
1221      }
1222  
1223      public void await(Semaphore semaphore) {
1224          try {
1225              assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
1226 <        } catch (Throwable t) {
1227 <            threadUnexpectedException(t);
1226 >        } catch (Throwable fail) {
1227 >            threadUnexpectedException(fail);
1228          }
1229      }
1230  
# Line 1317 | Line 1418 | public class JSR166TestCase extends Test
1418          @Override protected final void compute() {
1419              try {
1420                  realCompute();
1421 <            } catch (Throwable t) {
1422 <                threadUnexpectedException(t);
1421 >            } catch (Throwable fail) {
1422 >                threadUnexpectedException(fail);
1423              }
1424          }
1425      }
# Line 1332 | Line 1433 | public class JSR166TestCase extends Test
1433          @Override protected final T compute() {
1434              try {
1435                  return realCompute();
1436 <            } catch (Throwable t) {
1437 <                threadUnexpectedException(t);
1436 >            } catch (Throwable fail) {
1437 >                threadUnexpectedException(fail);
1438                  return null;
1439              }
1440          }
# Line 1357 | Line 1458 | public class JSR166TestCase extends Test
1458          public int await() {
1459              try {
1460                  return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1461 <            } catch (TimeoutException e) {
1461 >            } catch (TimeoutException timedOut) {
1462                  throw new AssertionFailedError("timed out");
1463 <            } catch (Exception e) {
1463 >            } catch (Exception fail) {
1464                  AssertionFailedError afe =
1465 <                    new AssertionFailedError("Unexpected exception: " + e);
1466 <                afe.initCause(e);
1465 >                    new AssertionFailedError("Unexpected exception: " + fail);
1466 >                afe.initCause(fail);
1467                  throw afe;
1468              }
1469          }
# Line 1390 | Line 1491 | public class JSR166TestCase extends Test
1491                  q.remove();
1492                  shouldThrow();
1493              } catch (NoSuchElementException success) {}
1494 <        } catch (InterruptedException ie) {
1394 <            threadUnexpectedException(ie);
1395 <        }
1494 >        } catch (InterruptedException fail) { threadUnexpectedException(fail); }
1495      }
1496  
1497      void assertSerialEquals(Object x, Object y) {
# Line 1411 | Line 1510 | public class JSR166TestCase extends Test
1510              oos.flush();
1511              oos.close();
1512              return bos.toByteArray();
1513 <        } catch (Throwable t) {
1514 <            threadUnexpectedException(t);
1513 >        } catch (Throwable fail) {
1514 >            threadUnexpectedException(fail);
1515              return new byte[0];
1516          }
1517      }
# Line 1425 | Line 1524 | public class JSR166TestCase extends Test
1524              T clone = (T) ois.readObject();
1525              assertSame(o.getClass(), clone.getClass());
1526              return clone;
1527 <        } catch (Throwable t) {
1528 <            threadUnexpectedException(t);
1527 >        } catch (Throwable fail) {
1528 >            threadUnexpectedException(fail);
1529              return null;
1530          }
1531      }
# Line 1451 | Line 1550 | public class JSR166TestCase extends Test
1550                  shouldThrow(expectedExceptionClass.getName());
1551          }
1552      }
1553 +
1554 +    public void assertIteratorExhausted(Iterator<?> it) {
1555 +        try {
1556 +            it.next();
1557 +            shouldThrow();
1558 +        } catch (NoSuchElementException success) {}
1559 +        assertFalse(it.hasNext());
1560 +    }
1561   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines