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.82 by jsr166, Tue May 24 23:34:03 2011 UTC vs.
Revision 1.113 by dl, Sun Sep 8 23:00:36 2013 UTC

# Line 11 | Line 11 | import java.io.ByteArrayInputStream;
11   import java.io.ByteArrayOutputStream;
12   import java.io.ObjectInputStream;
13   import java.io.ObjectOutputStream;
14 + import java.lang.management.ManagementFactory;
15 + import java.lang.management.ThreadInfo;
16 + import java.lang.reflect.Method;
17 + import java.util.ArrayList;
18   import java.util.Arrays;
19   import java.util.Date;
20 + import java.util.Enumeration;
21 + import java.util.List;
22   import java.util.NoSuchElementException;
23   import java.util.PropertyPermission;
24   import java.util.concurrent.*;
# Line 69 | Line 75 | import java.security.SecurityPermission;
75   *
76   * </ol>
77   *
78 < * <p> <b>Other notes</b>
78 > * <p><b>Other notes</b>
79   * <ul>
80   *
81   * <li> Usually, there is one testcase method per JSR166 method
# Line 122 | Line 128 | public class JSR166TestCase extends Test
128      private static final long profileThreshold =
129          Long.getLong("jsr166.profileThreshold", 100);
130  
131 +    /**
132 +     * The number of repetitions per test (for tickling rare bugs).
133 +     */
134 +    private static final int runsPerTest =
135 +        Integer.getInteger("jsr166.runsPerTest", 1);
136 +
137      protected void runTest() throws Throwable {
138 <        if (profileTests)
139 <            runTestProfiled();
140 <        else
141 <            super.runTest();
138 >        for (int i = 0; i < runsPerTest; i++) {
139 >            if (profileTests)
140 >                runTestProfiled();
141 >            else
142 >                super.runTest();
143 >        }
144      }
145  
146      protected void runTestProfiled() throws Throwable {
# Line 142 | Line 156 | public class JSR166TestCase extends Test
156      }
157  
158      /**
159 <     * Runs all JSR166 unit tests using junit.textui.TestRunner
159 >     * Runs all JSR166 unit tests using junit.textui.TestRunner.
160 >     * Optional command line arg provides the number of iterations to
161 >     * repeat running the tests.
162       */
163      public static void main(String[] args) {
164          if (useSecurityManager) {
# Line 174 | Line 190 | public class JSR166TestCase extends Test
190          return suite;
191      }
192  
193 +    public static void addNamedTestClasses(TestSuite suite,
194 +                                           String... testClassNames) {
195 +        for (String testClassName : testClassNames) {
196 +            try {
197 +                Class<?> testClass = Class.forName(testClassName);
198 +                Method m = testClass.getDeclaredMethod("suite",
199 +                                                       new Class<?>[0]);
200 +                suite.addTest(newTestSuite((Test)m.invoke(null)));
201 +            } catch (Exception e) {
202 +                throw new Error("Missing test class", e);
203 +            }
204 +        }
205 +    }
206 +
207 +    public static final double JAVA_CLASS_VERSION;
208 +    static {
209 +        try {
210 +            JAVA_CLASS_VERSION = java.security.AccessController.doPrivileged(
211 +                new java.security.PrivilegedAction<Double>() {
212 +                public Double run() {
213 +                    return Double.valueOf(System.getProperty("java.class.version"));}});
214 +        } catch (Throwable t) {
215 +            throw new Error(t);
216 +        }
217 +    }
218 +
219 +    public static boolean atLeastJava6() { return JAVA_CLASS_VERSION >= 50.0; }
220 +    public static boolean atLeastJava7() { return JAVA_CLASS_VERSION >= 51.0; }
221 +    public static boolean atLeastJava8() { return JAVA_CLASS_VERSION >= 52.0; }
222 +
223      /**
224       * Collects all JSR166 unit tests as one suite.
225       */
226      public static Test suite() {
227 <        return newTestSuite(
227 >        // Java7+ test classes
228 >        TestSuite suite = newTestSuite(
229              ForkJoinPoolTest.suite(),
230              ForkJoinTaskTest.suite(),
231              RecursiveActionTest.suite(),
# Line 243 | Line 290 | public class JSR166TestCase extends Test
290              TreeSetTest.suite(),
291              TreeSubMapTest.suite(),
292              TreeSubSetTest.suite());
293 +
294 +        // Java8+ test classes
295 +        if (atLeastJava8()) {
296 +            String[] java8TestClassNames = {
297 +                "Atomic8Test",
298 +                "CompletableFutureTest",
299 +                "ConcurrentHashMap8Test",
300 +                "CountedCompleterTest",
301 +                "DoubleAccumulatorTest",
302 +                "DoubleAdderTest",
303 +                "ForkJoinPool8Test",
304 +                "ForkJoinTask8Test",
305 +                "LongAccumulatorTest",
306 +                "LongAdderTest",
307 +                "SplittableRandomTest",
308 +                "StampedLockTest",
309 +                "ThreadLocalRandom8Test",
310 +            };
311 +            addNamedTestClasses(suite, java8TestClassNames);
312 +        }
313 +
314 +        return suite;
315      }
316  
317 +    // Delays for timing-dependent tests, in milliseconds.
318  
319      public static long SHORT_DELAY_MS;
320      public static long SMALL_DELAY_MS;
321      public static long MEDIUM_DELAY_MS;
322      public static long LONG_DELAY_MS;
323  
254
324      /**
325       * Returns the shortest timed delay. This could
326       * be reimplemented to use for example a Property.
# Line 260 | Line 329 | public class JSR166TestCase extends Test
329          return 50;
330      }
331  
263
332      /**
333       * Sets delays as multiples of SHORT_DELAY.
334       */
# Line 284 | Line 352 | public class JSR166TestCase extends Test
352       * milliseconds in the future.
353       */
354      Date delayedDate(long delayMillis) {
355 <        return new Date(new Date().getTime() + delayMillis);
355 >        return new Date(System.currentTimeMillis() + delayMillis);
356      }
357  
358      /**
# Line 308 | Line 376 | public class JSR166TestCase extends Test
376      }
377  
378      /**
379 +     * Extra checks that get done for all test cases.
380 +     *
381       * Triggers test case failure if any thread assertions have failed,
382       * by rethrowing, in the test harness thread, any exception recorded
383       * earlier by threadRecordFailure.
384 +     *
385 +     * Triggers test case failure if interrupt status is set in the main thread.
386       */
387      public void tearDown() throws Exception {
388          Throwable t = threadFailure.getAndSet(null);
# Line 328 | Line 400 | public class JSR166TestCase extends Test
400                  throw afe;
401              }
402          }
403 +
404 +        if (Thread.interrupted())
405 +            throw new AssertionFailedError("interrupt status set in main thread");
406 +
407 +        checkForkJoinPoolThreadLeaks();
408 +    }
409 +
410 +    /**
411 +     * Find missing try { ... } finally { joinPool(e); }
412 +     */
413 +    void checkForkJoinPoolThreadLeaks() throws InterruptedException {
414 +        Thread[] survivors = new Thread[5];
415 +        int count = Thread.enumerate(survivors);
416 +        for (int i = 0; i < count; i++) {
417 +            Thread thread = survivors[i];
418 +            String name = thread.getName();
419 +            if (name.startsWith("ForkJoinPool-")) {
420 +                // give thread some time to terminate
421 +                thread.join(LONG_DELAY_MS);
422 +                if (!thread.isAlive()) continue;
423 +                thread.stop();
424 +                throw new AssertionFailedError
425 +                    (String.format("Found leaked ForkJoinPool thread test=%s thread=%s%n",
426 +                                   toString(), name));
427 +            }
428 +        }
429      }
430  
431      /**
# Line 501 | Line 599 | public class JSR166TestCase extends Test
599      }
600  
601      /**
602 +     * A debugging tool to print all stack traces, as jstack does.
603 +     */
604 +    static void printAllStackTraces() {
605 +        for (ThreadInfo info :
606 +                 ManagementFactory.getThreadMXBean()
607 +                 .dumpAllThreads(true, true))
608 +            System.err.print(info);
609 +    }
610 +
611 +    /**
612       * Checks that thread does not terminate within the default
613       * millisecond delay of {@code timeoutMillis()}.
614       */
# Line 522 | Line 630 | public class JSR166TestCase extends Test
630      }
631  
632      /**
633 +     * Checks that the threads do not terminate within the default
634 +     * millisecond delay of {@code timeoutMillis()}.
635 +     */
636 +    void assertThreadsStayAlive(Thread... threads) {
637 +        assertThreadsStayAlive(timeoutMillis(), threads);
638 +    }
639 +
640 +    /**
641 +     * Checks that the threads do not terminate within the given millisecond delay.
642 +     */
643 +    void assertThreadsStayAlive(long millis, Thread... threads) {
644 +        try {
645 +            // No need to optimize the failing case via Thread.join.
646 +            delay(millis);
647 +            for (Thread thread : threads)
648 +                assertTrue(thread.isAlive());
649 +        } catch (InterruptedException ie) {
650 +            fail("Unexpected InterruptedException");
651 +        }
652 +    }
653 +
654 +    /**
655 +     * Checks that future.get times out, with the default timeout of
656 +     * {@code timeoutMillis()}.
657 +     */
658 +    void assertFutureTimesOut(Future future) {
659 +        assertFutureTimesOut(future, timeoutMillis());
660 +    }
661 +
662 +    /**
663 +     * Checks that future.get times out, with the given millisecond timeout.
664 +     */
665 +    void assertFutureTimesOut(Future future, long timeoutMillis) {
666 +        long startTime = System.nanoTime();
667 +        try {
668 +            future.get(timeoutMillis, MILLISECONDS);
669 +            shouldThrow();
670 +        } catch (TimeoutException success) {
671 +        } catch (Exception e) {
672 +            threadUnexpectedException(e);
673 +        } finally { future.cancel(true); }
674 +        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
675 +    }
676 +
677 +    /**
678       * Fails with message "should throw exception".
679       */
680      public void shouldThrow() {
# Line 560 | Line 713 | public class JSR166TestCase extends Test
713      public static final Integer m6  = new Integer(-6);
714      public static final Integer m10 = new Integer(-10);
715  
563
716      /**
717       * Runs Runnable r with a security policy that permits precisely
718       * the specified permissions.  If there is no current security
# Line 572 | Line 724 | public class JSR166TestCase extends Test
724          SecurityManager sm = System.getSecurityManager();
725          if (sm == null) {
726              r.run();
727 +        }
728 +        runWithSecurityManagerWithPermissions(r, permissions);
729 +    }
730 +
731 +    /**
732 +     * Runs Runnable r with a security policy that permits precisely
733 +     * the specified permissions.  If there is no current security
734 +     * manager, a temporary one is set for the duration of the
735 +     * Runnable.  We require that any security manager permit
736 +     * getPolicy/setPolicy.
737 +     */
738 +    public void runWithSecurityManagerWithPermissions(Runnable r,
739 +                                                      Permission... permissions) {
740 +        SecurityManager sm = System.getSecurityManager();
741 +        if (sm == null) {
742              Policy savedPolicy = Policy.getPolicy();
743              try {
744                  Policy.setPolicy(permissivePolicy());
745                  System.setSecurityManager(new SecurityManager());
746 <                runWithPermissions(r, permissions);
746 >                runWithSecurityManagerWithPermissions(r, permissions);
747              } finally {
748                  System.setSecurityManager(null);
749                  Policy.setPolicy(savedPolicy);
# Line 624 | Line 791 | public class JSR166TestCase extends Test
791              return perms.implies(p);
792          }
793          public void refresh() {}
794 +        public String toString() {
795 +            List<Permission> ps = new ArrayList<Permission>();
796 +            for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
797 +                ps.add(e.nextElement());
798 +            return "AdjustablePolicy with permissions " + ps;
799 +        }
800      }
801  
802      /**
# Line 661 | Line 834 | public class JSR166TestCase extends Test
834      }
835  
836      /**
837 <     * Waits up to the specified number of milliseconds for the given
837 >     * Spin-waits up to the specified number of milliseconds for the given
838       * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
839       */
840      void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
841 <        long timeoutNanos = timeoutMillis * 1000L * 1000L;
669 <        long t0 = System.nanoTime();
841 >        long startTime = System.nanoTime();
842          for (;;) {
843              Thread.State s = thread.getState();
844              if (s == Thread.State.BLOCKED ||
# Line 675 | Line 847 | public class JSR166TestCase extends Test
847                  return;
848              else if (s == Thread.State.TERMINATED)
849                  fail("Unexpected thread termination");
850 <            else if (System.nanoTime() - t0 > timeoutNanos) {
850 >            else if (millisElapsedSince(startTime) > timeoutMillis) {
851                  threadAssertTrue(thread.isAlive());
852                  return;
853              }
# Line 721 | Line 893 | public class JSR166TestCase extends Test
893          } catch (InterruptedException ie) {
894              threadUnexpectedException(ie);
895          } finally {
896 <            if (t.isAlive()) {
896 >            if (t.getState() != Thread.State.TERMINATED) {
897                  t.interrupt();
898                  fail("Test timed out");
899              }
# Line 876 | Line 1048 | public class JSR166TestCase extends Test
1048          }
1049      }
1050  
1051 +    public void await(Semaphore semaphore) {
1052 +        try {
1053 +            assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
1054 +        } catch (Throwable t) {
1055 +            threadUnexpectedException(t);
1056 +        }
1057 +    }
1058 +
1059   //     /**
1060   //      * Spin-waits up to LONG_DELAY_MS until flag becomes true.
1061   //      */
# Line 1063 | Line 1243 | public class JSR166TestCase extends Test
1243      public abstract class CheckedRecursiveAction extends RecursiveAction {
1244          protected abstract void realCompute() throws Throwable;
1245  
1246 <        public final void compute() {
1246 >        @Override protected final void compute() {
1247              try {
1248                  realCompute();
1249              } catch (Throwable t) {
# Line 1078 | Line 1258 | public class JSR166TestCase extends Test
1258      public abstract class CheckedRecursiveTask<T> extends RecursiveTask<T> {
1259          protected abstract T realCompute() throws Throwable;
1260  
1261 <        public final T compute() {
1261 >        @Override protected final T compute() {
1262              try {
1263                  return realCompute();
1264              } catch (Throwable t) {
# Line 1097 | Line 1277 | public class JSR166TestCase extends Test
1277      }
1278  
1279      /**
1280 <     * A CyclicBarrier that fails with AssertionFailedErrors instead
1281 <     * of throwing checked exceptions.
1280 >     * A CyclicBarrier that uses timed await and fails with
1281 >     * AssertionFailedErrors instead of throwing checked exceptions.
1282       */
1283      public class CheckedBarrier extends CyclicBarrier {
1284          public CheckedBarrier(int parties) { super(parties); }
1285  
1286          public int await() {
1287              try {
1288 <                return super.await();
1288 >                return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1289 >            } catch (TimeoutException e) {
1290 >                throw new AssertionFailedError("timed out");
1291              } catch (Exception e) {
1292                  AssertionFailedError afe =
1293                      new AssertionFailedError("Unexpected exception: " + e);
# Line 1142 | Line 1324 | public class JSR166TestCase extends Test
1324          }
1325      }
1326  
1327 <    @SuppressWarnings("unchecked")
1328 <    <T> T serialClone(T o) {
1327 >    void assertSerialEquals(Object x, Object y) {
1328 >        assertTrue(Arrays.equals(serialBytes(x), serialBytes(y)));
1329 >    }
1330 >
1331 >    void assertNotSerialEquals(Object x, Object y) {
1332 >        assertFalse(Arrays.equals(serialBytes(x), serialBytes(y)));
1333 >    }
1334 >
1335 >    byte[] serialBytes(Object o) {
1336          try {
1337              ByteArrayOutputStream bos = new ByteArrayOutputStream();
1338              ObjectOutputStream oos = new ObjectOutputStream(bos);
1339              oos.writeObject(o);
1340              oos.flush();
1341              oos.close();
1342 <            ByteArrayInputStream bin =
1343 <                new ByteArrayInputStream(bos.toByteArray());
1344 <            ObjectInputStream ois = new ObjectInputStream(bin);
1345 <            return (T) ois.readObject();
1342 >            return bos.toByteArray();
1343 >        } catch (Throwable t) {
1344 >            threadUnexpectedException(t);
1345 >            return new byte[0];
1346 >        }
1347 >    }
1348 >
1349 >    @SuppressWarnings("unchecked")
1350 >    <T> T serialClone(T o) {
1351 >        try {
1352 >            ObjectInputStream ois = new ObjectInputStream
1353 >                (new ByteArrayInputStream(serialBytes(o)));
1354 >            T clone = (T) ois.readObject();
1355 >            assertSame(o.getClass(), clone.getClass());
1356 >            return clone;
1357          } catch (Throwable t) {
1358              threadUnexpectedException(t);
1359              return null;
1360          }
1361      }
1362 +
1363 +    public void assertThrows(Class<? extends Throwable> expectedExceptionClass,
1364 +                             Runnable... throwingActions) {
1365 +        for (Runnable throwingAction : throwingActions) {
1366 +            boolean threw = false;
1367 +            try { throwingAction.run(); }
1368 +            catch (Throwable t) {
1369 +                threw = true;
1370 +                if (!expectedExceptionClass.isInstance(t)) {
1371 +                    AssertionFailedError afe =
1372 +                        new AssertionFailedError
1373 +                        ("Expected " + expectedExceptionClass.getName() +
1374 +                         ", got " + t.getClass().getName());
1375 +                    afe.initCause(t);
1376 +                    threadUnexpectedException(afe);
1377 +                }
1378 +            }
1379 +            if (!threw)
1380 +                shouldThrow(expectedExceptionClass.getName());
1381 +        }
1382 +    }
1383   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines