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.77 by jsr166, Fri May 6 17:26:29 2011 UTC vs.
Revision 1.97 by jsr166, Fri Feb 1 19:07:36 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 +    static void addTestReflectively(TestSuite suite, String testClassName) {
186 +        try {
187 +            Class klazz = Class.forName(testClassName);
188 +            Method m = klazz.getDeclaredMethod("suite", new Class<?>[0]);
189 +            suite.addTest(newTestSuite((Test)m.invoke(null)));
190 +        } catch (Exception e) {
191 +            throw new Error(e);
192 +        }
193 +    }
194 +
195 +    public static final double JAVA_CLASS_VERSION;
196 +    static {
197 +        try {
198 +            JAVA_CLASS_VERSION = java.security.AccessController.doPrivileged(
199 +                new java.security.PrivilegedAction<Double>() {
200 +                public Double run() {
201 +                    return Double.valueOf(System.getProperty("java.class.version"));}});
202 +        } catch (Throwable t) {
203 +            throw new Error(t);
204 +        }
205 +    }
206 +
207 +    public static boolean isAtLeastJdk6() { return JAVA_CLASS_VERSION >= 50.0; }
208 +    public static boolean isAtLeastJdk7() { return JAVA_CLASS_VERSION >= 51.0; }
209 +    public static boolean isAtLeastJdk8() { return JAVA_CLASS_VERSION >= 52.0; }
210 +
211      /**
212       * Collects all JSR166 unit tests as one suite.
213       */
214      public static Test suite() {
215 <        return newTestSuite(
215 >        TestSuite suite = newTestSuite(
216              ForkJoinPoolTest.suite(),
217              ForkJoinTaskTest.suite(),
218              RecursiveActionTest.suite(),
# Line 237 | Line 277 | public class JSR166TestCase extends Test
277              TreeSetTest.suite(),
278              TreeSubMapTest.suite(),
279              TreeSubSetTest.suite());
280 +        if (isAtLeastJdk8()) {
281 +            addTestReflectively(suite, "StampedLockTest");
282 +        }
283 +        return suite;
284      }
285  
286  
# Line 254 | Line 298 | public class JSR166TestCase extends Test
298          return 50;
299      }
300  
257
301      /**
302       * Sets delays as multiples of SHORT_DELAY.
303       */
# Line 266 | Line 309 | public class JSR166TestCase extends Test
309      }
310  
311      /**
312 +     * Returns a timeout in milliseconds to be used in tests that
313 +     * verify that operations block or time out.
314 +     */
315 +    long timeoutMillis() {
316 +        return SHORT_DELAY_MS / 4;
317 +    }
318 +
319 +    /**
320 +     * Returns a new Date instance representing a time delayMillis
321 +     * milliseconds in the future.
322 +     */
323 +    Date delayedDate(long delayMillis) {
324 +        return new Date(System.currentTimeMillis() + delayMillis);
325 +    }
326 +
327 +    /**
328       * The first exception encountered if any threadAssertXXX method fails.
329       */
330      private final AtomicReference<Throwable> threadFailure
# Line 286 | Line 345 | public class JSR166TestCase extends Test
345      }
346  
347      /**
348 +     * Extra checks that get done for all test cases.
349 +     *
350       * Triggers test case failure if any thread assertions have failed,
351       * by rethrowing, in the test harness thread, any exception recorded
352       * earlier by threadRecordFailure.
353 +     *
354 +     * Triggers test case failure if interrupt status is set in the main thread.
355       */
356      public void tearDown() throws Exception {
357          Throwable t = threadFailure.getAndSet(null);
# Line 306 | Line 369 | public class JSR166TestCase extends Test
369                  throw afe;
370              }
371          }
372 +
373 +        if (Thread.interrupted())
374 +            throw new AssertionFailedError("interrupt status set in main thread");
375      }
376  
377      /**
# Line 437 | Line 503 | public class JSR166TestCase extends Test
503          else {
504              AssertionFailedError afe =
505                  new AssertionFailedError("unexpected exception: " + t);
506 <            t.initCause(t);
506 >            afe.initCause(t);
507              throw afe;
508          }
509      }
510  
511      /**
512 <     * Delays, via Thread.sleep for the given millisecond delay, but
512 >     * Delays, via Thread.sleep, for the given millisecond delay, but
513       * if the sleep is shorter than specified, may re-sleep or yield
514       * until time elapses.
515       */
516 <    public static void delay(long ms) throws InterruptedException {
516 >    static void delay(long millis) throws InterruptedException {
517          long startTime = System.nanoTime();
518 <        long ns = ms * 1000 * 1000;
518 >        long ns = millis * 1000 * 1000;
519          for (;;) {
520 <            if (ms > 0L)
521 <                Thread.sleep(ms);
520 >            if (millis > 0L)
521 >                Thread.sleep(millis);
522              else // too short to sleep
523                  Thread.yield();
524              long d = ns - (System.nanoTime() - startTime);
525              if (d > 0L)
526 <                ms = d / (1000 * 1000);
526 >                millis = d / (1000 * 1000);
527              else
528                  break;
529          }
# Line 466 | Line 532 | public class JSR166TestCase extends Test
532      /**
533       * Waits out termination of a thread pool or fails doing so.
534       */
535 <    public void joinPool(ExecutorService exec) {
535 >    void joinPool(ExecutorService exec) {
536          try {
537              exec.shutdown();
538              assertTrue("ExecutorService did not terminate in a timely manner",
# Line 478 | Line 544 | public class JSR166TestCase extends Test
544          }
545      }
546  
547 +    /**
548 +     * A debugging tool to print all stack traces, as jstack does.
549 +     */
550 +    static void printAllStackTraces() {
551 +        for (ThreadInfo info :
552 +                 ManagementFactory.getThreadMXBean()
553 +                 .dumpAllThreads(true, true))
554 +            System.err.print(info);
555 +    }
556 +
557 +    /**
558 +     * Checks that thread does not terminate within the default
559 +     * millisecond delay of {@code timeoutMillis()}.
560 +     */
561 +    void assertThreadStaysAlive(Thread thread) {
562 +        assertThreadStaysAlive(thread, timeoutMillis());
563 +    }
564 +
565 +    /**
566 +     * Checks that thread does not terminate within the given millisecond delay.
567 +     */
568 +    void assertThreadStaysAlive(Thread thread, long millis) {
569 +        try {
570 +            // No need to optimize the failing case via Thread.join.
571 +            delay(millis);
572 +            assertTrue(thread.isAlive());
573 +        } catch (InterruptedException ie) {
574 +            fail("Unexpected InterruptedException");
575 +        }
576 +    }
577 +
578 +    /**
579 +     * Checks that the threads do not terminate within the default
580 +     * millisecond delay of {@code timeoutMillis()}.
581 +     */
582 +    void assertThreadsStayAlive(Thread... threads) {
583 +        assertThreadsStayAlive(timeoutMillis(), threads);
584 +    }
585 +
586 +    /**
587 +     * Checks that the threads do not terminate within the given millisecond delay.
588 +     */
589 +    void assertThreadsStayAlive(long millis, Thread... threads) {
590 +        try {
591 +            // No need to optimize the failing case via Thread.join.
592 +            delay(millis);
593 +            for (Thread thread : threads)
594 +                assertTrue(thread.isAlive());
595 +        } catch (InterruptedException ie) {
596 +            fail("Unexpected InterruptedException");
597 +        }
598 +    }
599 +
600 +    /**
601 +     * Checks that future.get times out, with the default timeout of
602 +     * {@code timeoutMillis()}.
603 +     */
604 +    void assertFutureTimesOut(Future future) {
605 +        assertFutureTimesOut(future, timeoutMillis());
606 +    }
607 +
608 +    /**
609 +     * Checks that future.get times out, with the given millisecond timeout.
610 +     */
611 +    void assertFutureTimesOut(Future future, long timeoutMillis) {
612 +        long startTime = System.nanoTime();
613 +        try {
614 +            future.get(timeoutMillis, MILLISECONDS);
615 +            shouldThrow();
616 +        } catch (TimeoutException success) {
617 +        } catch (Exception e) {
618 +            threadUnexpectedException(e);
619 +        } finally { future.cancel(true); }
620 +        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
621 +    }
622  
623      /**
624       * Fails with message "should throw exception".
# Line 530 | Line 671 | public class JSR166TestCase extends Test
671          SecurityManager sm = System.getSecurityManager();
672          if (sm == null) {
673              r.run();
674 +        }
675 +        runWithSecurityManagerWithPermissions(r, permissions);
676 +    }
677 +
678 +    /**
679 +     * Runs Runnable r with a security policy that permits precisely
680 +     * the specified permissions.  If there is no current security
681 +     * manager, a temporary one is set for the duration of the
682 +     * Runnable.  We require that any security manager permit
683 +     * getPolicy/setPolicy.
684 +     */
685 +    public void runWithSecurityManagerWithPermissions(Runnable r,
686 +                                                      Permission... permissions) {
687 +        SecurityManager sm = System.getSecurityManager();
688 +        if (sm == null) {
689              Policy savedPolicy = Policy.getPolicy();
690              try {
691                  Policy.setPolicy(permissivePolicy());
692                  System.setSecurityManager(new SecurityManager());
693 <                runWithPermissions(r, permissions);
693 >                runWithSecurityManagerWithPermissions(r, permissions);
694              } finally {
695                  System.setSecurityManager(null);
696                  Policy.setPolicy(savedPolicy);
# Line 582 | Line 738 | public class JSR166TestCase extends Test
738              return perms.implies(p);
739          }
740          public void refresh() {}
741 +        public String toString() {
742 +            List<Permission> ps = new ArrayList<Permission>();
743 +            for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
744 +                ps.add(e.nextElement());
745 +            return "AdjustablePolicy with permissions " + ps;
746 +        }
747      }
748  
749      /**
# Line 619 | Line 781 | public class JSR166TestCase extends Test
781      }
782  
783      /**
784 <     * 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
784 >     * Spin-waits up to the specified number of milliseconds for the given
785       * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
786       */
787      void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
788 <        long timeoutNanos = timeoutMillis * 1000L * 1000L;
637 <        long t0 = System.nanoTime();
788 >        long startTime = System.nanoTime();
789          for (;;) {
790              Thread.State s = thread.getState();
791              if (s == Thread.State.BLOCKED ||
# Line 643 | Line 794 | public class JSR166TestCase extends Test
794                  return;
795              else if (s == Thread.State.TERMINATED)
796                  fail("Unexpected thread termination");
797 <            else if (System.nanoTime() - t0 > timeoutNanos) {
797 >            else if (millisElapsedSince(startTime) > timeoutMillis) {
798                  threadAssertTrue(thread.isAlive());
799                  return;
800              }
# Line 689 | Line 840 | public class JSR166TestCase extends Test
840          } catch (InterruptedException ie) {
841              threadUnexpectedException(ie);
842          } finally {
843 <            if (t.isAlive()) {
843 >            if (t.getState() != Thread.State.TERMINATED) {
844                  t.interrupt();
845                  fail("Test timed out");
846              }
# Line 767 | Line 918 | public class JSR166TestCase extends Test
918                  realRun();
919                  threadShouldThrow("InterruptedException");
920              } catch (InterruptedException success) {
921 +                threadAssertFalse(Thread.interrupted());
922              } catch (Throwable t) {
923                  threadUnexpectedException(t);
924              }
# Line 796 | Line 948 | public class JSR166TestCase extends Test
948                  threadShouldThrow("InterruptedException");
949                  return result;
950              } catch (InterruptedException success) {
951 +                threadAssertFalse(Thread.interrupted());
952              } catch (Throwable t) {
953                  threadUnexpectedException(t);
954              }
# Line 830 | Line 983 | public class JSR166TestCase extends Test
983      public Runnable awaiter(final CountDownLatch latch) {
984          return new CheckedRunnable() {
985              public void realRun() throws InterruptedException {
986 <                latch.await();
986 >                await(latch);
987              }};
988      }
989  
990 +    public void await(CountDownLatch latch) {
991 +        try {
992 +            assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
993 +        } catch (Throwable t) {
994 +            threadUnexpectedException(t);
995 +        }
996 +    }
997 +
998 +    public void await(Semaphore semaphore) {
999 +        try {
1000 +            assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
1001 +        } catch (Throwable t) {
1002 +            threadUnexpectedException(t);
1003 +        }
1004 +    }
1005 +
1006 + //     /**
1007 + //      * Spin-waits up to LONG_DELAY_MS until flag becomes true.
1008 + //      */
1009 + //     public void await(AtomicBoolean flag) {
1010 + //         await(flag, LONG_DELAY_MS);
1011 + //     }
1012 +
1013 + //     /**
1014 + //      * Spin-waits up to the specified timeout until flag becomes true.
1015 + //      */
1016 + //     public void await(AtomicBoolean flag, long timeoutMillis) {
1017 + //         long startTime = System.nanoTime();
1018 + //         while (!flag.get()) {
1019 + //             if (millisElapsedSince(startTime) > timeoutMillis)
1020 + //                 throw new AssertionFailedError("timed out");
1021 + //             Thread.yield();
1022 + //         }
1023 + //     }
1024 +
1025      public static class NPETask implements Callable<String> {
1026          public String call() { throw new NullPointerException(); }
1027      }
# Line 1036 | Line 1224 | public class JSR166TestCase extends Test
1224      }
1225  
1226      /**
1227 <     * A CyclicBarrier that fails with AssertionFailedErrors instead
1228 <     * of throwing checked exceptions.
1227 >     * A CyclicBarrier that uses timed await and fails with
1228 >     * AssertionFailedErrors instead of throwing checked exceptions.
1229       */
1230      public class CheckedBarrier extends CyclicBarrier {
1231          public CheckedBarrier(int parties) { super(parties); }
1232  
1233          public int await() {
1234              try {
1235 <                return super.await();
1235 >                return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1236 >            } catch (TimeoutException e) {
1237 >                throw new AssertionFailedError("timed out");
1238              } catch (Exception e) {
1239                  AssertionFailedError afe =
1240                      new AssertionFailedError("Unexpected exception: " + e);
# Line 1054 | Line 1244 | public class JSR166TestCase extends Test
1244          }
1245      }
1246  
1247 <    public void checkEmpty(BlockingQueue q) {
1247 >    void checkEmpty(BlockingQueue q) {
1248          try {
1249              assertTrue(q.isEmpty());
1250              assertEquals(0, q.size());
# Line 1081 | Line 1271 | public class JSR166TestCase extends Test
1271          }
1272      }
1273  
1274 +    void assertSerialEquals(Object x, Object y) {
1275 +        assertTrue(Arrays.equals(serialBytes(x), serialBytes(y)));
1276 +    }
1277 +
1278 +    void assertNotSerialEquals(Object x, Object y) {
1279 +        assertFalse(Arrays.equals(serialBytes(x), serialBytes(y)));
1280 +    }
1281 +
1282 +    byte[] serialBytes(Object o) {
1283 +        try {
1284 +            ByteArrayOutputStream bos = new ByteArrayOutputStream();
1285 +            ObjectOutputStream oos = new ObjectOutputStream(bos);
1286 +            oos.writeObject(o);
1287 +            oos.flush();
1288 +            oos.close();
1289 +            return bos.toByteArray();
1290 +        } catch (Throwable t) {
1291 +            threadUnexpectedException(t);
1292 +            return new byte[0];
1293 +        }
1294 +    }
1295 +
1296 +    @SuppressWarnings("unchecked")
1297 +    <T> T serialClone(T o) {
1298 +        try {
1299 +            ObjectInputStream ois = new ObjectInputStream
1300 +                (new ByteArrayInputStream(serialBytes(o)));
1301 +            T clone = (T) ois.readObject();
1302 +            assertSame(o.getClass(), clone.getClass());
1303 +            return clone;
1304 +        } catch (Throwable t) {
1305 +            threadUnexpectedException(t);
1306 +            return null;
1307 +        }
1308 +    }
1309   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines