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.79 by jsr166, Mon May 9 20:00:19 2011 UTC vs.
Revision 1.95 by jsr166, Mon Jan 21 19:43:52 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.util.ArrayList;
15   import java.util.Arrays;
16 + import java.util.Date;
17 + import java.util.Enumeration;
18 + import java.util.List;
19   import java.util.NoSuchElementException;
20   import java.util.PropertyPermission;
21   import java.util.concurrent.*;
22 + import java.util.concurrent.atomic.AtomicBoolean;
23   import java.util.concurrent.atomic.AtomicReference;
24   import static java.util.concurrent.TimeUnit.MILLISECONDS;
25   import static java.util.concurrent.TimeUnit.NANOSECONDS;
# Line 67 | Line 72 | import java.security.SecurityPermission;
72   *
73   * </ol>
74   *
75 < * <p> <b>Other notes</b>
75 > * <p><b>Other notes</b>
76   * <ul>
77   *
78   * <li> Usually, there is one testcase method per JSR166 method
# Line 140 | Line 145 | public class JSR166TestCase extends Test
145      }
146  
147      /**
148 <     * Runs all JSR166 unit tests using junit.textui.TestRunner
148 >     * Runs all JSR166 unit tests using junit.textui.TestRunner.
149 >     * Optional command line arg provides the number of iterations to
150 >     * repeat running the tests.
151       */
152      public static void main(String[] args) {
153          if (useSecurityManager) {
# Line 258 | Line 265 | public class JSR166TestCase extends Test
265          return 50;
266      }
267  
261
268      /**
269       * Sets delays as multiples of SHORT_DELAY.
270       */
# Line 270 | Line 276 | public class JSR166TestCase extends Test
276      }
277  
278      /**
279 +     * Returns a timeout in milliseconds to be used in tests that
280 +     * verify that operations block or time out.
281 +     */
282 +    long timeoutMillis() {
283 +        return SHORT_DELAY_MS / 4;
284 +    }
285 +
286 +    /**
287 +     * Returns a new Date instance representing a time delayMillis
288 +     * milliseconds in the future.
289 +     */
290 +    Date delayedDate(long delayMillis) {
291 +        return new Date(System.currentTimeMillis() + delayMillis);
292 +    }
293 +
294 +    /**
295       * The first exception encountered if any threadAssertXXX method fails.
296       */
297      private final AtomicReference<Throwable> threadFailure
# Line 290 | Line 312 | public class JSR166TestCase extends Test
312      }
313  
314      /**
315 +     * Extra checks that get done for all test cases.
316 +     *
317       * Triggers test case failure if any thread assertions have failed,
318       * by rethrowing, in the test harness thread, any exception recorded
319       * earlier by threadRecordFailure.
320 +     *
321 +     * Triggers test case failure if interrupt status is set in the main thread.
322       */
323      public void tearDown() throws Exception {
324          Throwable t = threadFailure.getAndSet(null);
# Line 310 | Line 336 | public class JSR166TestCase extends Test
336                  throw afe;
337              }
338          }
339 +
340 +        if (Thread.interrupted())
341 +            throw new AssertionFailedError("interrupt status set in main thread");
342      }
343  
344      /**
# Line 441 | Line 470 | public class JSR166TestCase extends Test
470          else {
471              AssertionFailedError afe =
472                  new AssertionFailedError("unexpected exception: " + t);
473 <            t.initCause(t);
473 >            afe.initCause(t);
474              throw afe;
475          }
476      }
477  
478      /**
479 <     * Delays, via Thread.sleep for the given millisecond delay, but
479 >     * Delays, via Thread.sleep, for the given millisecond delay, but
480       * if the sleep is shorter than specified, may re-sleep or yield
481       * until time elapses.
482       */
483 <    public static void delay(long ms) throws InterruptedException {
483 >    static void delay(long millis) throws InterruptedException {
484          long startTime = System.nanoTime();
485 <        long ns = ms * 1000 * 1000;
485 >        long ns = millis * 1000 * 1000;
486          for (;;) {
487 <            if (ms > 0L)
488 <                Thread.sleep(ms);
487 >            if (millis > 0L)
488 >                Thread.sleep(millis);
489              else // too short to sleep
490                  Thread.yield();
491              long d = ns - (System.nanoTime() - startTime);
492              if (d > 0L)
493 <                ms = d / (1000 * 1000);
493 >                millis = d / (1000 * 1000);
494              else
495                  break;
496          }
# Line 470 | Line 499 | public class JSR166TestCase extends Test
499      /**
500       * Waits out termination of a thread pool or fails doing so.
501       */
502 <    public void joinPool(ExecutorService exec) {
502 >    void joinPool(ExecutorService exec) {
503          try {
504              exec.shutdown();
505              assertTrue("ExecutorService did not terminate in a timely manner",
# Line 483 | Line 512 | public class JSR166TestCase extends Test
512      }
513  
514      /**
515 <     * Checks that thread does not terminate within timeoutMillis
487 <     * milliseconds (that is, Thread.join times out).
515 >     * A debugging tool to print all stack traces, as jstack does.
516       */
517 <    public void assertThreadJoinTimesOut(Thread thread, long timeoutMillis) {
517 >    void printAllStackTraces() {
518 >        System.err.println(
519 >            Arrays.toString(
520 >                java.lang.management.ManagementFactory.getThreadMXBean()
521 >                .dumpAllThreads(true, true)));
522 >    }
523 >
524 >    /**
525 >     * Checks that thread does not terminate within the default
526 >     * millisecond delay of {@code timeoutMillis()}.
527 >     */
528 >    void assertThreadStaysAlive(Thread thread) {
529 >        assertThreadStaysAlive(thread, timeoutMillis());
530 >    }
531 >
532 >    /**
533 >     * Checks that thread does not terminate within the given millisecond delay.
534 >     */
535 >    void assertThreadStaysAlive(Thread thread, long millis) {
536          try {
537 <            long startTime = System.nanoTime();
538 <            thread.join(timeoutMillis);
537 >            // No need to optimize the failing case via Thread.join.
538 >            delay(millis);
539              assertTrue(thread.isAlive());
494            assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
540          } catch (InterruptedException ie) {
541              fail("Unexpected InterruptedException");
542          }
543      }
544  
545      /**
546 +     * Checks that the threads do not terminate within the default
547 +     * millisecond delay of {@code timeoutMillis()}.
548 +     */
549 +    void assertThreadsStayAlive(Thread... threads) {
550 +        assertThreadsStayAlive(timeoutMillis(), threads);
551 +    }
552 +
553 +    /**
554 +     * Checks that the threads do not terminate within the given millisecond delay.
555 +     */
556 +    void assertThreadsStayAlive(long millis, Thread... threads) {
557 +        try {
558 +            // No need to optimize the failing case via Thread.join.
559 +            delay(millis);
560 +            for (Thread thread : threads)
561 +                assertTrue(thread.isAlive());
562 +        } catch (InterruptedException ie) {
563 +            fail("Unexpected InterruptedException");
564 +        }
565 +    }
566 +
567 +    /**
568 +     * Checks that future.get times out, with the default timeout of
569 +     * {@code timeoutMillis()}.
570 +     */
571 +    void assertFutureTimesOut(Future future) {
572 +        assertFutureTimesOut(future, timeoutMillis());
573 +    }
574 +
575 +    /**
576 +     * Checks that future.get times out, with the given millisecond timeout.
577 +     */
578 +    void assertFutureTimesOut(Future future, long timeoutMillis) {
579 +        long startTime = System.nanoTime();
580 +        try {
581 +            future.get(timeoutMillis, MILLISECONDS);
582 +            shouldThrow();
583 +        } catch (TimeoutException success) {
584 +        } catch (Exception e) {
585 +            threadUnexpectedException(e);
586 +        } finally { future.cancel(true); }
587 +        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
588 +    }
589 +
590 +    /**
591       * Fails with message "should throw exception".
592       */
593      public void shouldThrow() {
# Line 548 | Line 638 | public class JSR166TestCase extends Test
638          SecurityManager sm = System.getSecurityManager();
639          if (sm == null) {
640              r.run();
641 +        }
642 +        runWithSecurityManagerWithPermissions(r, permissions);
643 +    }
644 +
645 +    /**
646 +     * Runs Runnable r with a security policy that permits precisely
647 +     * the specified permissions.  If there is no current security
648 +     * manager, a temporary one is set for the duration of the
649 +     * Runnable.  We require that any security manager permit
650 +     * getPolicy/setPolicy.
651 +     */
652 +    public void runWithSecurityManagerWithPermissions(Runnable r,
653 +                                                      Permission... permissions) {
654 +        SecurityManager sm = System.getSecurityManager();
655 +        if (sm == null) {
656              Policy savedPolicy = Policy.getPolicy();
657              try {
658                  Policy.setPolicy(permissivePolicy());
659                  System.setSecurityManager(new SecurityManager());
660 <                runWithPermissions(r, permissions);
660 >                runWithSecurityManagerWithPermissions(r, permissions);
661              } finally {
662                  System.setSecurityManager(null);
663                  Policy.setPolicy(savedPolicy);
# Line 600 | Line 705 | public class JSR166TestCase extends Test
705              return perms.implies(p);
706          }
707          public void refresh() {}
708 +        public String toString() {
709 +            List<Permission> ps = new ArrayList<Permission>();
710 +            for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
711 +                ps.add(e.nextElement());
712 +            return "AdjustablePolicy with permissions " + ps;
713 +        }
714      }
715  
716      /**
# Line 637 | Line 748 | public class JSR166TestCase extends Test
748      }
749  
750      /**
751 <     * Sleeps until the timeout has elapsed, or interrupted.
641 <     * Does <em>NOT</em> throw InterruptedException.
642 <     */
643 <    void sleepTillInterrupted(long timeoutMillis) {
644 <        try {
645 <            Thread.sleep(timeoutMillis);
646 <        } catch (InterruptedException wakeup) {}
647 <    }
648 <
649 <    /**
650 <     * Waits up to the specified number of milliseconds for the given
751 >     * Spin-waits up to the specified number of milliseconds for the given
752       * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
753       */
754      void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
755 <        long timeoutNanos = timeoutMillis * 1000L * 1000L;
655 <        long t0 = System.nanoTime();
755 >        long startTime = System.nanoTime();
756          for (;;) {
757              Thread.State s = thread.getState();
758              if (s == Thread.State.BLOCKED ||
# Line 661 | Line 761 | public class JSR166TestCase extends Test
761                  return;
762              else if (s == Thread.State.TERMINATED)
763                  fail("Unexpected thread termination");
764 <            else if (System.nanoTime() - t0 > timeoutNanos) {
764 >            else if (millisElapsedSince(startTime) > timeoutMillis) {
765                  threadAssertTrue(thread.isAlive());
766                  return;
767              }
# Line 707 | Line 807 | public class JSR166TestCase extends Test
807          } catch (InterruptedException ie) {
808              threadUnexpectedException(ie);
809          } finally {
810 <            if (t.isAlive()) {
810 >            if (t.getState() != Thread.State.TERMINATED) {
811                  t.interrupt();
812                  fail("Test timed out");
813              }
# Line 785 | Line 885 | public class JSR166TestCase extends Test
885                  realRun();
886                  threadShouldThrow("InterruptedException");
887              } catch (InterruptedException success) {
888 +                threadAssertFalse(Thread.interrupted());
889              } catch (Throwable t) {
890                  threadUnexpectedException(t);
891              }
# Line 814 | Line 915 | public class JSR166TestCase extends Test
915                  threadShouldThrow("InterruptedException");
916                  return result;
917              } catch (InterruptedException success) {
918 +                threadAssertFalse(Thread.interrupted());
919              } catch (Throwable t) {
920                  threadUnexpectedException(t);
921              }
# Line 860 | Line 962 | public class JSR166TestCase extends Test
962          }
963      }
964  
965 +    public void await(Semaphore semaphore) {
966 +        try {
967 +            assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
968 +        } catch (Throwable t) {
969 +            threadUnexpectedException(t);
970 +        }
971 +    }
972 +
973 + //     /**
974 + //      * Spin-waits up to LONG_DELAY_MS until flag becomes true.
975 + //      */
976 + //     public void await(AtomicBoolean flag) {
977 + //         await(flag, LONG_DELAY_MS);
978 + //     }
979 +
980 + //     /**
981 + //      * Spin-waits up to the specified timeout until flag becomes true.
982 + //      */
983 + //     public void await(AtomicBoolean flag, long timeoutMillis) {
984 + //         long startTime = System.nanoTime();
985 + //         while (!flag.get()) {
986 + //             if (millisElapsedSince(startTime) > timeoutMillis)
987 + //                 throw new AssertionFailedError("timed out");
988 + //             Thread.yield();
989 + //         }
990 + //     }
991 +
992      public static class NPETask implements Callable<String> {
993          public String call() { throw new NullPointerException(); }
994      }
# Line 1062 | Line 1191 | public class JSR166TestCase extends Test
1191      }
1192  
1193      /**
1194 <     * A CyclicBarrier that fails with AssertionFailedErrors instead
1195 <     * of throwing checked exceptions.
1194 >     * A CyclicBarrier that uses timed await and fails with
1195 >     * AssertionFailedErrors instead of throwing checked exceptions.
1196       */
1197      public class CheckedBarrier extends CyclicBarrier {
1198          public CheckedBarrier(int parties) { super(parties); }
1199  
1200          public int await() {
1201              try {
1202 <                return super.await();
1202 >                return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1203 >            } catch (TimeoutException e) {
1204 >                throw new AssertionFailedError("timed out");
1205              } catch (Exception e) {
1206                  AssertionFailedError afe =
1207                      new AssertionFailedError("Unexpected exception: " + e);
# Line 1080 | Line 1211 | public class JSR166TestCase extends Test
1211          }
1212      }
1213  
1214 <    public void checkEmpty(BlockingQueue q) {
1214 >    void checkEmpty(BlockingQueue q) {
1215          try {
1216              assertTrue(q.isEmpty());
1217              assertEquals(0, q.size());
# Line 1107 | Line 1238 | public class JSR166TestCase extends Test
1238          }
1239      }
1240  
1241 <    @SuppressWarnings("unchecked")
1242 <    public <T> T serialClone(T o) {
1241 >    void assertSerialEquals(Object x, Object y) {
1242 >        assertTrue(Arrays.equals(serialBytes(x), serialBytes(y)));
1243 >    }
1244 >
1245 >    void assertNotSerialEquals(Object x, Object y) {
1246 >        assertFalse(Arrays.equals(serialBytes(x), serialBytes(y)));
1247 >    }
1248 >
1249 >    byte[] serialBytes(Object o) {
1250          try {
1251              ByteArrayOutputStream bos = new ByteArrayOutputStream();
1252              ObjectOutputStream oos = new ObjectOutputStream(bos);
1253              oos.writeObject(o);
1254              oos.flush();
1255              oos.close();
1256 <            ByteArrayInputStream bin =
1257 <                new ByteArrayInputStream(bos.toByteArray());
1258 <            ObjectInputStream ois = new ObjectInputStream(bin);
1259 <            return (T) ois.readObject();
1256 >            return bos.toByteArray();
1257 >        } catch (Throwable t) {
1258 >            threadUnexpectedException(t);
1259 >            return new byte[0];
1260 >        }
1261 >    }
1262 >
1263 >    @SuppressWarnings("unchecked")
1264 >    <T> T serialClone(T o) {
1265 >        try {
1266 >            ObjectInputStream ois = new ObjectInputStream
1267 >                (new ByteArrayInputStream(serialBytes(o)));
1268 >            T clone = (T) ois.readObject();
1269 >            assertSame(o.getClass(), clone.getClass());
1270 >            return clone;
1271          } catch (Throwable t) {
1272              threadUnexpectedException(t);
1273              return null;

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines