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.76 by dl, Fri May 6 11:22:07 2011 UTC vs.
Revision 1.102 by jsr166, Wed Feb 6 19:55:06 2013 UTC

# Line 7 | Line 7
7   */
8  
9   import junit.framework.*;
10 + 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.*;
25 + import java.util.concurrent.atomic.AtomicBoolean;
26   import java.util.concurrent.atomic.AtomicReference;
27   import static java.util.concurrent.TimeUnit.MILLISECONDS;
28   import static java.util.concurrent.TimeUnit.NANOSECONDS;
# Line 63 | 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 136 | Line 148 | public class JSR166TestCase extends Test
148      }
149  
150      /**
151 <     * Runs all JSR166 unit tests using junit.textui.TestRunner
151 >     * Runs all JSR166 unit tests using junit.textui.TestRunner.
152 >     * Optional command line arg provides the number of iterations to
153 >     * repeat running the tests.
154       */
155      public static void main(String[] args) {
156          if (useSecurityManager) {
# Line 168 | Line 182 | public class JSR166TestCase extends Test
182          return suite;
183      }
184  
185 +    public static void addNamedTestClasses(TestSuite suite,
186 +                                           String... testClassNames) {
187 +        for (String testClassName : testClassNames) {
188 +            try {
189 +                Class<?> testClass = Class.forName(testClassName);
190 +                Method m = testClass.getDeclaredMethod("suite",
191 +                                                       new Class<?>[0]);
192 +                suite.addTest(newTestSuite((Test)m.invoke(null)));
193 +            } catch (Exception e) {
194 +                throw new Error("Missing test class", e);
195 +            }
196 +        }
197 +    }
198 +
199 +    public static final double JAVA_CLASS_VERSION;
200 +    static {
201 +        try {
202 +            JAVA_CLASS_VERSION = java.security.AccessController.doPrivileged(
203 +                new java.security.PrivilegedAction<Double>() {
204 +                public Double run() {
205 +                    return Double.valueOf(System.getProperty("java.class.version"));}});
206 +        } catch (Throwable t) {
207 +            throw new Error(t);
208 +        }
209 +    }
210 +
211 +    public static boolean atLeastJava6() { return JAVA_CLASS_VERSION >= 50.0; }
212 +    public static boolean atLeastJava7() { return JAVA_CLASS_VERSION >= 51.0; }
213 +    public static boolean atLeastJava8() { return JAVA_CLASS_VERSION >= 52.0; }
214 +
215      /**
216       * Collects all JSR166 unit tests as one suite.
217       */
218      public static Test suite() {
219 <        return newTestSuite(
219 >        // Java7+ test classes
220 >        TestSuite suite = newTestSuite(
221              ForkJoinPoolTest.suite(),
222              ForkJoinTaskTest.suite(),
223              RecursiveActionTest.suite(),
# Line 237 | Line 282 | public class JSR166TestCase extends Test
282              TreeSetTest.suite(),
283              TreeSubMapTest.suite(),
284              TreeSubSetTest.suite());
285 +
286 +        // Java8+ test classes
287 +        if (atLeastJava8()) {
288 +            String[] java8TestClassNames = {
289 +                "CompletableFutureTest",
290 +                "ForkJoinPool8Test",
291 +                "StampedLockTest",
292 +            };
293 +            addNamedTestClasses(suite, java8TestClassNames);
294 +        }
295 +
296 +        return suite;
297      }
298  
299  
# Line 254 | Line 311 | public class JSR166TestCase extends Test
311          return 50;
312      }
313  
257
314      /**
315       * Sets delays as multiples of SHORT_DELAY.
316       */
# Line 266 | Line 322 | public class JSR166TestCase extends Test
322      }
323  
324      /**
325 +     * Returns a timeout in milliseconds to be used in tests that
326 +     * verify that operations block or time out.
327 +     */
328 +    long timeoutMillis() {
329 +        return SHORT_DELAY_MS / 4;
330 +    }
331 +
332 +    /**
333 +     * Returns a new Date instance representing a time delayMillis
334 +     * milliseconds in the future.
335 +     */
336 +    Date delayedDate(long delayMillis) {
337 +        return new Date(System.currentTimeMillis() + delayMillis);
338 +    }
339 +
340 +    /**
341       * The first exception encountered if any threadAssertXXX method fails.
342       */
343      private final AtomicReference<Throwable> threadFailure
# Line 286 | Line 358 | public class JSR166TestCase extends Test
358      }
359  
360      /**
361 +     * Extra checks that get done for all test cases.
362 +     *
363       * Triggers test case failure if any thread assertions have failed,
364       * by rethrowing, in the test harness thread, any exception recorded
365       * earlier by threadRecordFailure.
366 +     *
367 +     * Triggers test case failure if interrupt status is set in the main thread.
368       */
369      public void tearDown() throws Exception {
370          Throwable t = threadFailure.getAndSet(null);
# Line 306 | Line 382 | public class JSR166TestCase extends Test
382                  throw afe;
383              }
384          }
385 +
386 +        if (Thread.interrupted())
387 +            throw new AssertionFailedError("interrupt status set in main thread");
388 +
389 +        checkForkJoinPoolThreadLeaks();
390 +    }
391 +
392 +    /**
393 +     * Find missing try { ... } finally { joinPool(e); }
394 +     */
395 +    void checkForkJoinPoolThreadLeaks() throws InterruptedException {
396 +        Thread[] survivors = new Thread[5];
397 +        int count = Thread.enumerate(survivors);
398 +        for (int i = 0; i < count; i++) {
399 +            Thread thread = survivors[i];
400 +            String name = thread.getName();
401 +            if (name.startsWith("ForkJoinPool-")) {
402 +                // give thread some time to terminate
403 +                thread.join(LONG_DELAY_MS);
404 +                if (!thread.isAlive()) continue;
405 +                thread.stop();
406 +                throw new AssertionFailedError
407 +                    (String.format("Found leaked ForkJoinPool thread test=%s thread=%s%n",
408 +                                   toString(), name));
409 +            }
410 +        }
411      }
412  
413      /**
# Line 437 | Line 539 | public class JSR166TestCase extends Test
539          else {
540              AssertionFailedError afe =
541                  new AssertionFailedError("unexpected exception: " + t);
542 <            t.initCause(t);
542 >            afe.initCause(t);
543              throw afe;
544          }
545      }
546  
547      /**
548 <     * Delays, via Thread.sleep for the given millisecond delay, but
548 >     * Delays, via Thread.sleep, for the given millisecond delay, but
549       * if the sleep is shorter than specified, may re-sleep or yield
550       * until time elapses.
551       */
552 <    public static void delay(long ms) throws InterruptedException {
552 >    static void delay(long millis) throws InterruptedException {
553          long startTime = System.nanoTime();
554 <        long ns = ms * 1000 * 1000;
554 >        long ns = millis * 1000 * 1000;
555          for (;;) {
556 <            if (ms > 0L)
557 <                Thread.sleep(ms);
556 >            if (millis > 0L)
557 >                Thread.sleep(millis);
558              else // too short to sleep
559                  Thread.yield();
560              long d = ns - (System.nanoTime() - startTime);
561              if (d > 0L)
562 <                ms = d / (1000 * 1000);
562 >                millis = d / (1000 * 1000);
563              else
564                  break;
565          }
# Line 466 | Line 568 | public class JSR166TestCase extends Test
568      /**
569       * Waits out termination of a thread pool or fails doing so.
570       */
571 <    public void joinPool(ExecutorService exec) {
571 >    void joinPool(ExecutorService exec) {
572          try {
573              exec.shutdown();
574              assertTrue("ExecutorService did not terminate in a timely manner",
# Line 478 | Line 580 | public class JSR166TestCase extends Test
580          }
581      }
582  
583 +    /**
584 +     * A debugging tool to print all stack traces, as jstack does.
585 +     */
586 +    static void printAllStackTraces() {
587 +        for (ThreadInfo info :
588 +                 ManagementFactory.getThreadMXBean()
589 +                 .dumpAllThreads(true, true))
590 +            System.err.print(info);
591 +    }
592 +
593 +    /**
594 +     * Checks that thread does not terminate within the default
595 +     * millisecond delay of {@code timeoutMillis()}.
596 +     */
597 +    void assertThreadStaysAlive(Thread thread) {
598 +        assertThreadStaysAlive(thread, timeoutMillis());
599 +    }
600 +
601 +    /**
602 +     * Checks that thread does not terminate within the given millisecond delay.
603 +     */
604 +    void assertThreadStaysAlive(Thread thread, long millis) {
605 +        try {
606 +            // No need to optimize the failing case via Thread.join.
607 +            delay(millis);
608 +            assertTrue(thread.isAlive());
609 +        } catch (InterruptedException ie) {
610 +            fail("Unexpected InterruptedException");
611 +        }
612 +    }
613 +
614 +    /**
615 +     * Checks that the threads do not terminate within the default
616 +     * millisecond delay of {@code timeoutMillis()}.
617 +     */
618 +    void assertThreadsStayAlive(Thread... threads) {
619 +        assertThreadsStayAlive(timeoutMillis(), threads);
620 +    }
621 +
622 +    /**
623 +     * Checks that the threads do not terminate within the given millisecond delay.
624 +     */
625 +    void assertThreadsStayAlive(long millis, Thread... threads) {
626 +        try {
627 +            // No need to optimize the failing case via Thread.join.
628 +            delay(millis);
629 +            for (Thread thread : threads)
630 +                assertTrue(thread.isAlive());
631 +        } catch (InterruptedException ie) {
632 +            fail("Unexpected InterruptedException");
633 +        }
634 +    }
635 +
636 +    /**
637 +     * Checks that future.get times out, with the default timeout of
638 +     * {@code timeoutMillis()}.
639 +     */
640 +    void assertFutureTimesOut(Future future) {
641 +        assertFutureTimesOut(future, timeoutMillis());
642 +    }
643 +
644 +    /**
645 +     * Checks that future.get times out, with the given millisecond timeout.
646 +     */
647 +    void assertFutureTimesOut(Future future, long timeoutMillis) {
648 +        long startTime = System.nanoTime();
649 +        try {
650 +            future.get(timeoutMillis, MILLISECONDS);
651 +            shouldThrow();
652 +        } catch (TimeoutException success) {
653 +        } catch (Exception e) {
654 +            threadUnexpectedException(e);
655 +        } finally { future.cancel(true); }
656 +        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
657 +    }
658  
659      /**
660       * Fails with message "should throw exception".
# Line 530 | Line 707 | public class JSR166TestCase extends Test
707          SecurityManager sm = System.getSecurityManager();
708          if (sm == null) {
709              r.run();
710 +        }
711 +        runWithSecurityManagerWithPermissions(r, permissions);
712 +    }
713 +
714 +    /**
715 +     * Runs Runnable r with a security policy that permits precisely
716 +     * the specified permissions.  If there is no current security
717 +     * manager, a temporary one is set for the duration of the
718 +     * Runnable.  We require that any security manager permit
719 +     * getPolicy/setPolicy.
720 +     */
721 +    public void runWithSecurityManagerWithPermissions(Runnable r,
722 +                                                      Permission... permissions) {
723 +        SecurityManager sm = System.getSecurityManager();
724 +        if (sm == null) {
725              Policy savedPolicy = Policy.getPolicy();
726              try {
727                  Policy.setPolicy(permissivePolicy());
728                  System.setSecurityManager(new SecurityManager());
729 <                runWithPermissions(r, permissions);
729 >                runWithSecurityManagerWithPermissions(r, permissions);
730              } finally {
731                  System.setSecurityManager(null);
732                  Policy.setPolicy(savedPolicy);
# Line 582 | Line 774 | public class JSR166TestCase extends Test
774              return perms.implies(p);
775          }
776          public void refresh() {}
777 +        public String toString() {
778 +            List<Permission> ps = new ArrayList<Permission>();
779 +            for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
780 +                ps.add(e.nextElement());
781 +            return "AdjustablePolicy with permissions " + ps;
782 +        }
783      }
784  
785      /**
# Line 619 | Line 817 | public class JSR166TestCase extends Test
817      }
818  
819      /**
820 <     * Sleeps until the timeout has elapsed, or interrupted.
623 <     * Does <em>NOT</em> throw InterruptedException.
624 <     */
625 <    void sleepTillInterrupted(long timeoutMillis) {
626 <        try {
627 <            Thread.sleep(timeoutMillis);
628 <        } catch (InterruptedException wakeup) {}
629 <    }
630 <
631 <    /**
632 <     * Waits up to the specified number of milliseconds for the given
820 >     * Spin-waits up to the specified number of milliseconds for the given
821       * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
822       */
823      void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
824 <        long timeoutNanos = timeoutMillis * 1000L * 1000L;
637 <        long t0 = System.nanoTime();
824 >        long startTime = System.nanoTime();
825          for (;;) {
826              Thread.State s = thread.getState();
827              if (s == Thread.State.BLOCKED ||
# Line 643 | Line 830 | public class JSR166TestCase extends Test
830                  return;
831              else if (s == Thread.State.TERMINATED)
832                  fail("Unexpected thread termination");
833 <            else if (System.nanoTime() - t0 > timeoutNanos) {
833 >            else if (millisElapsedSince(startTime) > timeoutMillis) {
834                  threadAssertTrue(thread.isAlive());
835                  return;
836              }
# Line 689 | Line 876 | public class JSR166TestCase extends Test
876          } catch (InterruptedException ie) {
877              threadUnexpectedException(ie);
878          } finally {
879 <            if (t.isAlive()) {
879 >            if (t.getState() != Thread.State.TERMINATED) {
880                  t.interrupt();
881                  fail("Test timed out");
882              }
# Line 767 | Line 954 | public class JSR166TestCase extends Test
954                  realRun();
955                  threadShouldThrow("InterruptedException");
956              } catch (InterruptedException success) {
957 +                threadAssertFalse(Thread.interrupted());
958              } catch (Throwable t) {
959                  threadUnexpectedException(t);
960              }
# Line 796 | Line 984 | public class JSR166TestCase extends Test
984                  threadShouldThrow("InterruptedException");
985                  return result;
986              } catch (InterruptedException success) {
987 +                threadAssertFalse(Thread.interrupted());
988              } catch (Throwable t) {
989                  threadUnexpectedException(t);
990              }
# Line 830 | Line 1019 | public class JSR166TestCase extends Test
1019      public Runnable awaiter(final CountDownLatch latch) {
1020          return new CheckedRunnable() {
1021              public void realRun() throws InterruptedException {
1022 <                latch.await();
1022 >                await(latch);
1023              }};
1024      }
1025  
1026 +    public void await(CountDownLatch latch) {
1027 +        try {
1028 +            assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
1029 +        } catch (Throwable t) {
1030 +            threadUnexpectedException(t);
1031 +        }
1032 +    }
1033 +
1034 +    public void await(Semaphore semaphore) {
1035 +        try {
1036 +            assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
1037 +        } catch (Throwable t) {
1038 +            threadUnexpectedException(t);
1039 +        }
1040 +    }
1041 +
1042 + //     /**
1043 + //      * Spin-waits up to LONG_DELAY_MS until flag becomes true.
1044 + //      */
1045 + //     public void await(AtomicBoolean flag) {
1046 + //         await(flag, LONG_DELAY_MS);
1047 + //     }
1048 +
1049 + //     /**
1050 + //      * Spin-waits up to the specified timeout until flag becomes true.
1051 + //      */
1052 + //     public void await(AtomicBoolean flag, long timeoutMillis) {
1053 + //         long startTime = System.nanoTime();
1054 + //         while (!flag.get()) {
1055 + //             if (millisElapsedSince(startTime) > timeoutMillis)
1056 + //                 throw new AssertionFailedError("timed out");
1057 + //             Thread.yield();
1058 + //         }
1059 + //     }
1060 +
1061      public static class NPETask implements Callable<String> {
1062          public String call() { throw new NullPointerException(); }
1063      }
# Line 1036 | Line 1260 | public class JSR166TestCase extends Test
1260      }
1261  
1262      /**
1263 <     * A CyclicBarrier that fails with AssertionFailedErrors instead
1264 <     * of throwing checked exceptions.
1263 >     * A CyclicBarrier that uses timed await and fails with
1264 >     * AssertionFailedErrors instead of throwing checked exceptions.
1265       */
1266      public class CheckedBarrier extends CyclicBarrier {
1267          public CheckedBarrier(int parties) { super(parties); }
1268  
1269          public int await() {
1270              try {
1271 <                return super.await();
1271 >                return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1272 >            } catch (TimeoutException e) {
1273 >                throw new AssertionFailedError("timed out");
1274              } catch (Exception e) {
1275                  AssertionFailedError afe =
1276                      new AssertionFailedError("Unexpected exception: " + e);
# Line 1054 | Line 1280 | public class JSR166TestCase extends Test
1280          }
1281      }
1282  
1283 <    public void checkEmpty(BlockingQueue q) {
1283 >    void checkEmpty(BlockingQueue q) {
1284          try {
1285              assertTrue(q.isEmpty());
1286              assertEquals(0, q.size());
# Line 1081 | Line 1307 | public class JSR166TestCase extends Test
1307          }
1308      }
1309  
1310 +    void assertSerialEquals(Object x, Object y) {
1311 +        assertTrue(Arrays.equals(serialBytes(x), serialBytes(y)));
1312 +    }
1313 +
1314 +    void assertNotSerialEquals(Object x, Object y) {
1315 +        assertFalse(Arrays.equals(serialBytes(x), serialBytes(y)));
1316 +    }
1317 +
1318 +    byte[] serialBytes(Object o) {
1319 +        try {
1320 +            ByteArrayOutputStream bos = new ByteArrayOutputStream();
1321 +            ObjectOutputStream oos = new ObjectOutputStream(bos);
1322 +            oos.writeObject(o);
1323 +            oos.flush();
1324 +            oos.close();
1325 +            return bos.toByteArray();
1326 +        } catch (Throwable t) {
1327 +            threadUnexpectedException(t);
1328 +            return new byte[0];
1329 +        }
1330 +    }
1331 +
1332 +    @SuppressWarnings("unchecked")
1333 +    <T> T serialClone(T o) {
1334 +        try {
1335 +            ObjectInputStream ois = new ObjectInputStream
1336 +                (new ByteArrayInputStream(serialBytes(o)));
1337 +            T clone = (T) ois.readObject();
1338 +            assertSame(o.getClass(), clone.getClass());
1339 +            return clone;
1340 +        } catch (Throwable t) {
1341 +            threadUnexpectedException(t);
1342 +            return null;
1343 +        }
1344 +    }
1345   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines