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.80 by jsr166, Fri May 13 21:48:58 2011 UTC vs.
Revision 1.99 by jsr166, Tue Feb 5 03:39:34 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.*;
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 67 | 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 140 | 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 172 | 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 241 | 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 +                "StampedLockTest",
290 +                "ForkJoinPool8Test",
291 +            };
292 +            addNamedTestClasses(suite, java8TestClassNames);
293 +        }
294 +
295 +        return suite;
296      }
297  
298  
# Line 258 | Line 310 | public class JSR166TestCase extends Test
310          return 50;
311      }
312  
261
313      /**
314       * Sets delays as multiples of SHORT_DELAY.
315       */
# Line 270 | Line 321 | public class JSR166TestCase extends Test
321      }
322  
323      /**
324 +     * Returns a timeout in milliseconds to be used in tests that
325 +     * verify that operations block or time out.
326 +     */
327 +    long timeoutMillis() {
328 +        return SHORT_DELAY_MS / 4;
329 +    }
330 +
331 +    /**
332 +     * Returns a new Date instance representing a time delayMillis
333 +     * milliseconds in the future.
334 +     */
335 +    Date delayedDate(long delayMillis) {
336 +        return new Date(System.currentTimeMillis() + delayMillis);
337 +    }
338 +
339 +    /**
340       * The first exception encountered if any threadAssertXXX method fails.
341       */
342      private final AtomicReference<Throwable> threadFailure
# Line 290 | Line 357 | public class JSR166TestCase extends Test
357      }
358  
359      /**
360 +     * Extra checks that get done for all test cases.
361 +     *
362       * Triggers test case failure if any thread assertions have failed,
363       * by rethrowing, in the test harness thread, any exception recorded
364       * earlier by threadRecordFailure.
365 +     *
366 +     * Triggers test case failure if interrupt status is set in the main thread.
367       */
368      public void tearDown() throws Exception {
369          Throwable t = threadFailure.getAndSet(null);
# Line 310 | Line 381 | public class JSR166TestCase extends Test
381                  throw afe;
382              }
383          }
384 +
385 +        if (Thread.interrupted())
386 +            throw new AssertionFailedError("interrupt status set in main thread");
387      }
388  
389      /**
# Line 441 | Line 515 | public class JSR166TestCase extends Test
515          else {
516              AssertionFailedError afe =
517                  new AssertionFailedError("unexpected exception: " + t);
518 <            t.initCause(t);
518 >            afe.initCause(t);
519              throw afe;
520          }
521      }
522  
523      /**
524 <     * Delays, via Thread.sleep for the given millisecond delay, but
524 >     * Delays, via Thread.sleep, for the given millisecond delay, but
525       * if the sleep is shorter than specified, may re-sleep or yield
526       * until time elapses.
527       */
528 <    public static void delay(long millis) throws InterruptedException {
528 >    static void delay(long millis) throws InterruptedException {
529          long startTime = System.nanoTime();
530          long ns = millis * 1000 * 1000;
531          for (;;) {
# Line 470 | Line 544 | public class JSR166TestCase extends Test
544      /**
545       * Waits out termination of a thread pool or fails doing so.
546       */
547 <    public void joinPool(ExecutorService exec) {
547 >    void joinPool(ExecutorService exec) {
548          try {
549              exec.shutdown();
550              assertTrue("ExecutorService did not terminate in a timely manner",
# Line 483 | Line 557 | public class JSR166TestCase extends Test
557      }
558  
559      /**
560 +     * A debugging tool to print all stack traces, as jstack does.
561 +     */
562 +    static void printAllStackTraces() {
563 +        for (ThreadInfo info :
564 +                 ManagementFactory.getThreadMXBean()
565 +                 .dumpAllThreads(true, true))
566 +            System.err.print(info);
567 +    }
568 +
569 +    /**
570 +     * Checks that thread does not terminate within the default
571 +     * millisecond delay of {@code timeoutMillis()}.
572 +     */
573 +    void assertThreadStaysAlive(Thread thread) {
574 +        assertThreadStaysAlive(thread, timeoutMillis());
575 +    }
576 +
577 +    /**
578       * Checks that thread does not terminate within the given millisecond delay.
579       */
580 <    public void assertThreadStaysAlive(Thread thread, long millis) {
580 >    void assertThreadStaysAlive(Thread thread, long millis) {
581          try {
582              // No need to optimize the failing case via Thread.join.
583              delay(millis);
# Line 496 | Line 588 | public class JSR166TestCase extends Test
588      }
589  
590      /**
591 +     * Checks that the threads do not terminate within the default
592 +     * millisecond delay of {@code timeoutMillis()}.
593 +     */
594 +    void assertThreadsStayAlive(Thread... threads) {
595 +        assertThreadsStayAlive(timeoutMillis(), threads);
596 +    }
597 +
598 +    /**
599 +     * Checks that the threads do not terminate within the given millisecond delay.
600 +     */
601 +    void assertThreadsStayAlive(long millis, Thread... threads) {
602 +        try {
603 +            // No need to optimize the failing case via Thread.join.
604 +            delay(millis);
605 +            for (Thread thread : threads)
606 +                assertTrue(thread.isAlive());
607 +        } catch (InterruptedException ie) {
608 +            fail("Unexpected InterruptedException");
609 +        }
610 +    }
611 +
612 +    /**
613 +     * Checks that future.get times out, with the default timeout of
614 +     * {@code timeoutMillis()}.
615 +     */
616 +    void assertFutureTimesOut(Future future) {
617 +        assertFutureTimesOut(future, timeoutMillis());
618 +    }
619 +
620 +    /**
621 +     * Checks that future.get times out, with the given millisecond timeout.
622 +     */
623 +    void assertFutureTimesOut(Future future, long timeoutMillis) {
624 +        long startTime = System.nanoTime();
625 +        try {
626 +            future.get(timeoutMillis, MILLISECONDS);
627 +            shouldThrow();
628 +        } catch (TimeoutException success) {
629 +        } catch (Exception e) {
630 +            threadUnexpectedException(e);
631 +        } finally { future.cancel(true); }
632 +        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
633 +    }
634 +
635 +    /**
636       * Fails with message "should throw exception".
637       */
638      public void shouldThrow() {
# Line 546 | Line 683 | public class JSR166TestCase extends Test
683          SecurityManager sm = System.getSecurityManager();
684          if (sm == null) {
685              r.run();
686 +        }
687 +        runWithSecurityManagerWithPermissions(r, permissions);
688 +    }
689 +
690 +    /**
691 +     * Runs Runnable r with a security policy that permits precisely
692 +     * the specified permissions.  If there is no current security
693 +     * manager, a temporary one is set for the duration of the
694 +     * Runnable.  We require that any security manager permit
695 +     * getPolicy/setPolicy.
696 +     */
697 +    public void runWithSecurityManagerWithPermissions(Runnable r,
698 +                                                      Permission... permissions) {
699 +        SecurityManager sm = System.getSecurityManager();
700 +        if (sm == null) {
701              Policy savedPolicy = Policy.getPolicy();
702              try {
703                  Policy.setPolicy(permissivePolicy());
704                  System.setSecurityManager(new SecurityManager());
705 <                runWithPermissions(r, permissions);
705 >                runWithSecurityManagerWithPermissions(r, permissions);
706              } finally {
707                  System.setSecurityManager(null);
708                  Policy.setPolicy(savedPolicy);
# Line 598 | Line 750 | public class JSR166TestCase extends Test
750              return perms.implies(p);
751          }
752          public void refresh() {}
753 +        public String toString() {
754 +            List<Permission> ps = new ArrayList<Permission>();
755 +            for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
756 +                ps.add(e.nextElement());
757 +            return "AdjustablePolicy with permissions " + ps;
758 +        }
759      }
760  
761      /**
# Line 635 | Line 793 | public class JSR166TestCase extends Test
793      }
794  
795      /**
796 <     * Sleeps until the timeout has elapsed, or interrupted.
639 <     * Does <em>NOT</em> throw InterruptedException.
640 <     */
641 <    void sleepTillInterrupted(long timeoutMillis) {
642 <        try {
643 <            Thread.sleep(timeoutMillis);
644 <        } catch (InterruptedException wakeup) {}
645 <    }
646 <
647 <    /**
648 <     * Waits up to the specified number of milliseconds for the given
796 >     * Spin-waits up to the specified number of milliseconds for the given
797       * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
798       */
799      void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
800 <        long timeoutNanos = timeoutMillis * 1000L * 1000L;
653 <        long t0 = System.nanoTime();
800 >        long startTime = System.nanoTime();
801          for (;;) {
802              Thread.State s = thread.getState();
803              if (s == Thread.State.BLOCKED ||
# Line 659 | Line 806 | public class JSR166TestCase extends Test
806                  return;
807              else if (s == Thread.State.TERMINATED)
808                  fail("Unexpected thread termination");
809 <            else if (System.nanoTime() - t0 > timeoutNanos) {
809 >            else if (millisElapsedSince(startTime) > timeoutMillis) {
810                  threadAssertTrue(thread.isAlive());
811                  return;
812              }
# Line 705 | Line 852 | public class JSR166TestCase extends Test
852          } catch (InterruptedException ie) {
853              threadUnexpectedException(ie);
854          } finally {
855 <            if (t.isAlive()) {
855 >            if (t.getState() != Thread.State.TERMINATED) {
856                  t.interrupt();
857                  fail("Test timed out");
858              }
# Line 783 | Line 930 | public class JSR166TestCase extends Test
930                  realRun();
931                  threadShouldThrow("InterruptedException");
932              } catch (InterruptedException success) {
933 +                threadAssertFalse(Thread.interrupted());
934              } catch (Throwable t) {
935                  threadUnexpectedException(t);
936              }
# Line 812 | Line 960 | public class JSR166TestCase extends Test
960                  threadShouldThrow("InterruptedException");
961                  return result;
962              } catch (InterruptedException success) {
963 +                threadAssertFalse(Thread.interrupted());
964              } catch (Throwable t) {
965                  threadUnexpectedException(t);
966              }
# Line 858 | Line 1007 | public class JSR166TestCase extends Test
1007          }
1008      }
1009  
1010 +    public void await(Semaphore semaphore) {
1011 +        try {
1012 +            assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
1013 +        } catch (Throwable t) {
1014 +            threadUnexpectedException(t);
1015 +        }
1016 +    }
1017 +
1018 + //     /**
1019 + //      * Spin-waits up to LONG_DELAY_MS until flag becomes true.
1020 + //      */
1021 + //     public void await(AtomicBoolean flag) {
1022 + //         await(flag, LONG_DELAY_MS);
1023 + //     }
1024 +
1025 + //     /**
1026 + //      * Spin-waits up to the specified timeout until flag becomes true.
1027 + //      */
1028 + //     public void await(AtomicBoolean flag, long timeoutMillis) {
1029 + //         long startTime = System.nanoTime();
1030 + //         while (!flag.get()) {
1031 + //             if (millisElapsedSince(startTime) > timeoutMillis)
1032 + //                 throw new AssertionFailedError("timed out");
1033 + //             Thread.yield();
1034 + //         }
1035 + //     }
1036 +
1037      public static class NPETask implements Callable<String> {
1038          public String call() { throw new NullPointerException(); }
1039      }
# Line 1060 | Line 1236 | public class JSR166TestCase extends Test
1236      }
1237  
1238      /**
1239 <     * A CyclicBarrier that fails with AssertionFailedErrors instead
1240 <     * of throwing checked exceptions.
1239 >     * A CyclicBarrier that uses timed await and fails with
1240 >     * AssertionFailedErrors instead of throwing checked exceptions.
1241       */
1242      public class CheckedBarrier extends CyclicBarrier {
1243          public CheckedBarrier(int parties) { super(parties); }
1244  
1245          public int await() {
1246              try {
1247 <                return super.await();
1247 >                return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1248 >            } catch (TimeoutException e) {
1249 >                throw new AssertionFailedError("timed out");
1250              } catch (Exception e) {
1251                  AssertionFailedError afe =
1252                      new AssertionFailedError("Unexpected exception: " + e);
# Line 1078 | Line 1256 | public class JSR166TestCase extends Test
1256          }
1257      }
1258  
1259 <    public void checkEmpty(BlockingQueue q) {
1259 >    void checkEmpty(BlockingQueue q) {
1260          try {
1261              assertTrue(q.isEmpty());
1262              assertEquals(0, q.size());
# Line 1105 | Line 1283 | public class JSR166TestCase extends Test
1283          }
1284      }
1285  
1286 <    @SuppressWarnings("unchecked")
1287 <    public <T> T serialClone(T o) {
1286 >    void assertSerialEquals(Object x, Object y) {
1287 >        assertTrue(Arrays.equals(serialBytes(x), serialBytes(y)));
1288 >    }
1289 >
1290 >    void assertNotSerialEquals(Object x, Object y) {
1291 >        assertFalse(Arrays.equals(serialBytes(x), serialBytes(y)));
1292 >    }
1293 >
1294 >    byte[] serialBytes(Object o) {
1295          try {
1296              ByteArrayOutputStream bos = new ByteArrayOutputStream();
1297              ObjectOutputStream oos = new ObjectOutputStream(bos);
1298              oos.writeObject(o);
1299              oos.flush();
1300              oos.close();
1301 <            ByteArrayInputStream bin =
1302 <                new ByteArrayInputStream(bos.toByteArray());
1303 <            ObjectInputStream ois = new ObjectInputStream(bin);
1304 <            return (T) ois.readObject();
1301 >            return bos.toByteArray();
1302 >        } catch (Throwable t) {
1303 >            threadUnexpectedException(t);
1304 >            return new byte[0];
1305 >        }
1306 >    }
1307 >
1308 >    @SuppressWarnings("unchecked")
1309 >    <T> T serialClone(T o) {
1310 >        try {
1311 >            ObjectInputStream ois = new ObjectInputStream
1312 >                (new ByteArrayInputStream(serialBytes(o)));
1313 >            T clone = (T) ois.readObject();
1314 >            assertSame(o.getClass(), clone.getClass());
1315 >            return clone;
1316          } catch (Throwable t) {
1317              threadUnexpectedException(t);
1318              return null;

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines