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.81 by jsr166, Sat May 21 06:24:33 2011 UTC vs.
Revision 1.96 by jsr166, Mon Jan 21 19:51:46 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.util.ArrayList;
17   import java.util.Arrays;
18   import java.util.Date;
19 + import java.util.Enumeration;
20 + import java.util.List;
21   import java.util.NoSuchElementException;
22   import java.util.PropertyPermission;
23   import java.util.concurrent.*;
# Line 69 | Line 74 | import java.security.SecurityPermission;
74   *
75   * </ol>
76   *
77 < * <p> <b>Other notes</b>
77 > * <p><b>Other notes</b>
78   * <ul>
79   *
80   * <li> Usually, there is one testcase method per JSR166 method
# Line 142 | Line 147 | public class JSR166TestCase extends Test
147      }
148  
149      /**
150 <     * Runs all JSR166 unit tests using junit.textui.TestRunner
150 >     * Runs all JSR166 unit tests using junit.textui.TestRunner.
151 >     * Optional command line arg provides the number of iterations to
152 >     * repeat running the tests.
153       */
154      public static void main(String[] args) {
155          if (useSecurityManager) {
# Line 260 | Line 267 | public class JSR166TestCase extends Test
267          return 50;
268      }
269  
263
270      /**
271       * Sets delays as multiples of SHORT_DELAY.
272       */
# Line 284 | Line 290 | public class JSR166TestCase extends Test
290       * milliseconds in the future.
291       */
292      Date delayedDate(long delayMillis) {
293 <        return new Date(new Date().getTime() + delayMillis);
293 >        return new Date(System.currentTimeMillis() + delayMillis);
294      }
295  
296      /**
# Line 308 | Line 314 | public class JSR166TestCase extends Test
314      }
315  
316      /**
317 +     * Extra checks that get done for all test cases.
318 +     *
319       * Triggers test case failure if any thread assertions have failed,
320       * by rethrowing, in the test harness thread, any exception recorded
321       * earlier by threadRecordFailure.
322 +     *
323 +     * Triggers test case failure if interrupt status is set in the main thread.
324       */
325      public void tearDown() throws Exception {
326          Throwable t = threadFailure.getAndSet(null);
# Line 328 | Line 338 | public class JSR166TestCase extends Test
338                  throw afe;
339              }
340          }
341 +
342 +        if (Thread.interrupted())
343 +            throw new AssertionFailedError("interrupt status set in main thread");
344      }
345  
346      /**
# Line 459 | Line 472 | public class JSR166TestCase extends Test
472          else {
473              AssertionFailedError afe =
474                  new AssertionFailedError("unexpected exception: " + t);
475 <            t.initCause(t);
475 >            afe.initCause(t);
476              throw afe;
477          }
478      }
# Line 501 | Line 514 | public class JSR166TestCase extends Test
514      }
515  
516      /**
517 +     * A debugging tool to print all stack traces, as jstack does.
518 +     */
519 +    static void printAllStackTraces() {
520 +        for (ThreadInfo info :
521 +                 ManagementFactory.getThreadMXBean()
522 +                 .dumpAllThreads(true, true))
523 +            System.err.print(info);
524 +    }
525 +
526 +    /**
527       * Checks that thread does not terminate within the default
528       * millisecond delay of {@code timeoutMillis()}.
529       */
# Line 522 | Line 545 | public class JSR166TestCase extends Test
545      }
546  
547      /**
548 +     * Checks that the threads do not terminate within the default
549 +     * millisecond delay of {@code timeoutMillis()}.
550 +     */
551 +    void assertThreadsStayAlive(Thread... threads) {
552 +        assertThreadsStayAlive(timeoutMillis(), threads);
553 +    }
554 +
555 +    /**
556 +     * Checks that the threads do not terminate within the given millisecond delay.
557 +     */
558 +    void assertThreadsStayAlive(long millis, Thread... threads) {
559 +        try {
560 +            // No need to optimize the failing case via Thread.join.
561 +            delay(millis);
562 +            for (Thread thread : threads)
563 +                assertTrue(thread.isAlive());
564 +        } catch (InterruptedException ie) {
565 +            fail("Unexpected InterruptedException");
566 +        }
567 +    }
568 +
569 +    /**
570 +     * Checks that future.get times out, with the default timeout of
571 +     * {@code timeoutMillis()}.
572 +     */
573 +    void assertFutureTimesOut(Future future) {
574 +        assertFutureTimesOut(future, timeoutMillis());
575 +    }
576 +
577 +    /**
578 +     * Checks that future.get times out, with the given millisecond timeout.
579 +     */
580 +    void assertFutureTimesOut(Future future, long timeoutMillis) {
581 +        long startTime = System.nanoTime();
582 +        try {
583 +            future.get(timeoutMillis, MILLISECONDS);
584 +            shouldThrow();
585 +        } catch (TimeoutException success) {
586 +        } catch (Exception e) {
587 +            threadUnexpectedException(e);
588 +        } finally { future.cancel(true); }
589 +        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
590 +    }
591 +
592 +    /**
593       * Fails with message "should throw exception".
594       */
595      public void shouldThrow() {
# Line 572 | Line 640 | public class JSR166TestCase extends Test
640          SecurityManager sm = System.getSecurityManager();
641          if (sm == null) {
642              r.run();
643 +        }
644 +        runWithSecurityManagerWithPermissions(r, permissions);
645 +    }
646 +
647 +    /**
648 +     * Runs Runnable r with a security policy that permits precisely
649 +     * the specified permissions.  If there is no current security
650 +     * manager, a temporary one is set for the duration of the
651 +     * Runnable.  We require that any security manager permit
652 +     * getPolicy/setPolicy.
653 +     */
654 +    public void runWithSecurityManagerWithPermissions(Runnable r,
655 +                                                      Permission... permissions) {
656 +        SecurityManager sm = System.getSecurityManager();
657 +        if (sm == null) {
658              Policy savedPolicy = Policy.getPolicy();
659              try {
660                  Policy.setPolicy(permissivePolicy());
661                  System.setSecurityManager(new SecurityManager());
662 <                runWithPermissions(r, permissions);
662 >                runWithSecurityManagerWithPermissions(r, permissions);
663              } finally {
664                  System.setSecurityManager(null);
665                  Policy.setPolicy(savedPolicy);
# Line 624 | Line 707 | public class JSR166TestCase extends Test
707              return perms.implies(p);
708          }
709          public void refresh() {}
710 +        public String toString() {
711 +            List<Permission> ps = new ArrayList<Permission>();
712 +            for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
713 +                ps.add(e.nextElement());
714 +            return "AdjustablePolicy with permissions " + ps;
715 +        }
716      }
717  
718      /**
# Line 661 | Line 750 | public class JSR166TestCase extends Test
750      }
751  
752      /**
753 <     * Waits up to the specified number of milliseconds for the given
753 >     * Spin-waits up to the specified number of milliseconds for the given
754       * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
755       */
756      void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
757 <        long timeoutNanos = timeoutMillis * 1000L * 1000L;
669 <        long t0 = System.nanoTime();
757 >        long startTime = System.nanoTime();
758          for (;;) {
759              Thread.State s = thread.getState();
760              if (s == Thread.State.BLOCKED ||
# Line 675 | Line 763 | public class JSR166TestCase extends Test
763                  return;
764              else if (s == Thread.State.TERMINATED)
765                  fail("Unexpected thread termination");
766 <            else if (System.nanoTime() - t0 > timeoutNanos) {
766 >            else if (millisElapsedSince(startTime) > timeoutMillis) {
767                  threadAssertTrue(thread.isAlive());
768                  return;
769              }
# Line 721 | Line 809 | public class JSR166TestCase extends Test
809          } catch (InterruptedException ie) {
810              threadUnexpectedException(ie);
811          } finally {
812 <            if (t.isAlive()) {
812 >            if (t.getState() != Thread.State.TERMINATED) {
813                  t.interrupt();
814                  fail("Test timed out");
815              }
# Line 876 | Line 964 | public class JSR166TestCase extends Test
964          }
965      }
966  
967 +    public void await(Semaphore semaphore) {
968 +        try {
969 +            assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
970 +        } catch (Throwable t) {
971 +            threadUnexpectedException(t);
972 +        }
973 +    }
974 +
975   //     /**
976   //      * Spin-waits up to LONG_DELAY_MS until flag becomes true.
977   //      */
# Line 1097 | Line 1193 | public class JSR166TestCase extends Test
1193      }
1194  
1195      /**
1196 <     * A CyclicBarrier that fails with AssertionFailedErrors instead
1197 <     * of throwing checked exceptions.
1196 >     * A CyclicBarrier that uses timed await and fails with
1197 >     * AssertionFailedErrors instead of throwing checked exceptions.
1198       */
1199      public class CheckedBarrier extends CyclicBarrier {
1200          public CheckedBarrier(int parties) { super(parties); }
1201  
1202          public int await() {
1203              try {
1204 <                return super.await();
1204 >                return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1205 >            } catch (TimeoutException e) {
1206 >                throw new AssertionFailedError("timed out");
1207              } catch (Exception e) {
1208                  AssertionFailedError afe =
1209                      new AssertionFailedError("Unexpected exception: " + e);
# Line 1142 | Line 1240 | public class JSR166TestCase extends Test
1240          }
1241      }
1242  
1243 <    @SuppressWarnings("unchecked")
1244 <    <T> T serialClone(T o) {
1243 >    void assertSerialEquals(Object x, Object y) {
1244 >        assertTrue(Arrays.equals(serialBytes(x), serialBytes(y)));
1245 >    }
1246 >
1247 >    void assertNotSerialEquals(Object x, Object y) {
1248 >        assertFalse(Arrays.equals(serialBytes(x), serialBytes(y)));
1249 >    }
1250 >
1251 >    byte[] serialBytes(Object o) {
1252          try {
1253              ByteArrayOutputStream bos = new ByteArrayOutputStream();
1254              ObjectOutputStream oos = new ObjectOutputStream(bos);
1255              oos.writeObject(o);
1256              oos.flush();
1257              oos.close();
1258 <            ByteArrayInputStream bin =
1259 <                new ByteArrayInputStream(bos.toByteArray());
1260 <            ObjectInputStream ois = new ObjectInputStream(bin);
1261 <            return (T) ois.readObject();
1258 >            return bos.toByteArray();
1259 >        } catch (Throwable t) {
1260 >            threadUnexpectedException(t);
1261 >            return new byte[0];
1262 >        }
1263 >    }
1264 >
1265 >    @SuppressWarnings("unchecked")
1266 >    <T> T serialClone(T o) {
1267 >        try {
1268 >            ObjectInputStream ois = new ObjectInputStream
1269 >                (new ByteArrayInputStream(serialBytes(o)));
1270 >            T clone = (T) ois.readObject();
1271 >            assertSame(o.getClass(), clone.getClass());
1272 >            return clone;
1273          } catch (Throwable t) {
1274              threadUnexpectedException(t);
1275              return null;

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines