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.120 by jsr166, Wed Jun 25 15:32:10 2014 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;
29 + import java.util.regex.Pattern;
30   import java.security.CodeSource;
31   import java.security.Permission;
32   import java.security.PermissionCollection;
# Line 67 | Line 76 | import java.security.SecurityPermission;
76   *
77   * </ol>
78   *
79 < * <p> <b>Other notes</b>
79 > * <p><b>Other notes</b>
80   * <ul>
81   *
82   * <li> Usually, there is one testcase method per JSR166 method
# Line 107 | Line 116 | public class JSR166TestCase extends Test
116          Boolean.getBoolean("jsr166.expensiveTests");
117  
118      /**
119 +     * If true, also run tests that are not part of the official tck
120 +     * because they test unspecified implementation details.
121 +     */
122 +    protected static final boolean testImplementationDetails =
123 +        Boolean.getBoolean("jsr166.testImplementationDetails");
124 +
125 +    /**
126       * If true, report on stdout all "slow" tests, that is, ones that
127       * take more than profileThreshold milliseconds to execute.
128       */
# Line 120 | Line 136 | public class JSR166TestCase extends Test
136      private static final long profileThreshold =
137          Long.getLong("jsr166.profileThreshold", 100);
138  
139 +    /**
140 +     * The number of repetitions per test (for tickling rare bugs).
141 +     */
142 +    private static final int runsPerTest =
143 +        Integer.getInteger("jsr166.runsPerTest", 1);
144 +
145 +    /**
146 +     * A filter for tests to run, matching strings of the form
147 +     * methodName(className), e.g. "testInvokeAll5(ForkJoinPoolTest)"
148 +     * Usefully combined with jsr166.runsPerTest.
149 +     */
150 +    private static final Pattern methodFilter = methodFilter();
151 +
152 +    private static Pattern methodFilter() {
153 +        String regex = System.getProperty("jsr166.methodFilter");
154 +        return (regex == null) ? null : Pattern.compile(regex);
155 +    }
156 +
157      protected void runTest() throws Throwable {
158 <        if (profileTests)
159 <            runTestProfiled();
160 <        else
161 <            super.runTest();
158 >        if (methodFilter == null
159 >            || methodFilter.matcher(toString()).find()) {
160 >            for (int i = 0; i < runsPerTest; i++) {
161 >                if (profileTests)
162 >                    runTestProfiled();
163 >                else
164 >                    super.runTest();
165 >            }
166 >        }
167      }
168  
169      protected void runTestProfiled() throws Throwable {
170 +        // Warmup run, notably to trigger all needed classloading.
171 +        super.runTest();
172          long t0 = System.nanoTime();
173          try {
174              super.runTest();
175          } finally {
176 <            long elapsedMillis =
136 <                (System.nanoTime() - t0) / (1000L * 1000L);
176 >            long elapsedMillis = millisElapsedSince(t0);
177              if (elapsedMillis >= profileThreshold)
178                  System.out.printf("%n%s: %d%n", toString(), elapsedMillis);
179          }
180      }
181  
182      /**
183 <     * Runs all JSR166 unit tests using junit.textui.TestRunner
183 >     * Runs all JSR166 unit tests using junit.textui.TestRunner.
184 >     * Optional command line arg provides the number of iterations to
185 >     * repeat running the tests.
186       */
187      public static void main(String[] args) {
188          if (useSecurityManager) {
# Line 172 | Line 214 | public class JSR166TestCase extends Test
214          return suite;
215      }
216  
217 +    public static void addNamedTestClasses(TestSuite suite,
218 +                                           String... testClassNames) {
219 +        for (String testClassName : testClassNames) {
220 +            try {
221 +                Class<?> testClass = Class.forName(testClassName);
222 +                Method m = testClass.getDeclaredMethod("suite",
223 +                                                       new Class<?>[0]);
224 +                suite.addTest(newTestSuite((Test)m.invoke(null)));
225 +            } catch (Exception e) {
226 +                throw new Error("Missing test class", e);
227 +            }
228 +        }
229 +    }
230 +
231 +    public static final double JAVA_CLASS_VERSION;
232 +    public static final String JAVA_SPECIFICATION_VERSION;
233 +    static {
234 +        try {
235 +            JAVA_CLASS_VERSION = java.security.AccessController.doPrivileged(
236 +                new java.security.PrivilegedAction<Double>() {
237 +                public Double run() {
238 +                    return Double.valueOf(System.getProperty("java.class.version"));}});
239 +            JAVA_SPECIFICATION_VERSION = java.security.AccessController.doPrivileged(
240 +                new java.security.PrivilegedAction<String>() {
241 +                public String run() {
242 +                    return System.getProperty("java.specification.version");}});
243 +        } catch (Throwable t) {
244 +            throw new Error(t);
245 +        }
246 +    }
247 +
248 +    public static boolean atLeastJava6() { return JAVA_CLASS_VERSION >= 50.0; }
249 +    public static boolean atLeastJava7() { return JAVA_CLASS_VERSION >= 51.0; }
250 +    public static boolean atLeastJava8() { return JAVA_CLASS_VERSION >= 52.0; }
251 +    public static boolean atLeastJava9() {
252 +        // As of 2014-05, java9 still uses 52.0 class file version
253 +        return JAVA_SPECIFICATION_VERSION.startsWith("1.9");
254 +    }
255 +
256      /**
257       * Collects all JSR166 unit tests as one suite.
258       */
259      public static Test suite() {
260 <        return newTestSuite(
260 >        // Java7+ test classes
261 >        TestSuite suite = newTestSuite(
262              ForkJoinPoolTest.suite(),
263              ForkJoinTaskTest.suite(),
264              RecursiveActionTest.suite(),
# Line 241 | Line 323 | public class JSR166TestCase extends Test
323              TreeSetTest.suite(),
324              TreeSubMapTest.suite(),
325              TreeSubSetTest.suite());
326 +
327 +        // Java8+ test classes
328 +        if (atLeastJava8()) {
329 +            String[] java8TestClassNames = {
330 +                "Atomic8Test",
331 +                "CompletableFutureTest",
332 +                "ConcurrentHashMap8Test",
333 +                "CountedCompleterTest",
334 +                "DoubleAccumulatorTest",
335 +                "DoubleAdderTest",
336 +                "ForkJoinPool8Test",
337 +                "ForkJoinTask8Test",
338 +                "LongAccumulatorTest",
339 +                "LongAdderTest",
340 +                "SplittableRandomTest",
341 +                "StampedLockTest",
342 +                "ThreadLocalRandom8Test",
343 +            };
344 +            addNamedTestClasses(suite, java8TestClassNames);
345 +        }
346 +
347 +        // Java9+ test classes
348 +        if (atLeastJava9()) {
349 +            String[] java9TestClassNames = {
350 +                "ThreadPoolExecutor9Test",
351 +            };
352 +            addNamedTestClasses(suite, java9TestClassNames);
353 +        }
354 +
355 +        return suite;
356      }
357  
358 +    // Delays for timing-dependent tests, in milliseconds.
359  
360      public static long SHORT_DELAY_MS;
361      public static long SMALL_DELAY_MS;
362      public static long MEDIUM_DELAY_MS;
363      public static long LONG_DELAY_MS;
364  
252
365      /**
366       * Returns the shortest timed delay. This could
367       * be reimplemented to use for example a Property.
# Line 258 | Line 370 | public class JSR166TestCase extends Test
370          return 50;
371      }
372  
261
373      /**
374       * Sets delays as multiples of SHORT_DELAY.
375       */
# Line 270 | Line 381 | public class JSR166TestCase extends Test
381      }
382  
383      /**
384 +     * Returns a timeout in milliseconds to be used in tests that
385 +     * verify that operations block or time out.
386 +     */
387 +    long timeoutMillis() {
388 +        return SHORT_DELAY_MS / 4;
389 +    }
390 +
391 +    /**
392 +     * Returns a new Date instance representing a time delayMillis
393 +     * milliseconds in the future.
394 +     */
395 +    Date delayedDate(long delayMillis) {
396 +        return new Date(System.currentTimeMillis() + delayMillis);
397 +    }
398 +
399 +    /**
400       * The first exception encountered if any threadAssertXXX method fails.
401       */
402      private final AtomicReference<Throwable> threadFailure
# Line 290 | Line 417 | public class JSR166TestCase extends Test
417      }
418  
419      /**
420 +     * Extra checks that get done for all test cases.
421 +     *
422       * Triggers test case failure if any thread assertions have failed,
423       * by rethrowing, in the test harness thread, any exception recorded
424       * earlier by threadRecordFailure.
425 +     *
426 +     * Triggers test case failure if interrupt status is set in the main thread.
427       */
428      public void tearDown() throws Exception {
429          Throwable t = threadFailure.getAndSet(null);
# Line 310 | Line 441 | public class JSR166TestCase extends Test
441                  throw afe;
442              }
443          }
444 +
445 +        if (Thread.interrupted())
446 +            throw new AssertionFailedError("interrupt status set in main thread");
447 +
448 +        checkForkJoinPoolThreadLeaks();
449 +    }
450 +
451 +    /**
452 +     * Find missing try { ... } finally { joinPool(e); }
453 +     */
454 +    void checkForkJoinPoolThreadLeaks() throws InterruptedException {
455 +        Thread[] survivors = new Thread[5];
456 +        int count = Thread.enumerate(survivors);
457 +        for (int i = 0; i < count; i++) {
458 +            Thread thread = survivors[i];
459 +            String name = thread.getName();
460 +            if (name.startsWith("ForkJoinPool-")) {
461 +                // give thread some time to terminate
462 +                thread.join(LONG_DELAY_MS);
463 +                if (!thread.isAlive()) continue;
464 +                thread.stop();
465 +                throw new AssertionFailedError
466 +                    (String.format("Found leaked ForkJoinPool thread test=%s thread=%s%n",
467 +                                   toString(), name));
468 +            }
469 +        }
470      }
471  
472      /**
# Line 441 | Line 598 | public class JSR166TestCase extends Test
598          else {
599              AssertionFailedError afe =
600                  new AssertionFailedError("unexpected exception: " + t);
601 <            t.initCause(t);
601 >            afe.initCause(t);
602              throw afe;
603          }
604      }
605  
606      /**
607 <     * Delays, via Thread.sleep for the given millisecond delay, but
607 >     * Delays, via Thread.sleep, for the given millisecond delay, but
608       * if the sleep is shorter than specified, may re-sleep or yield
609       * until time elapses.
610       */
611 <    public static void delay(long ms) throws InterruptedException {
611 >    static void delay(long millis) throws InterruptedException {
612          long startTime = System.nanoTime();
613 <        long ns = ms * 1000 * 1000;
613 >        long ns = millis * 1000 * 1000;
614          for (;;) {
615 <            if (ms > 0L)
616 <                Thread.sleep(ms);
615 >            if (millis > 0L)
616 >                Thread.sleep(millis);
617              else // too short to sleep
618                  Thread.yield();
619              long d = ns - (System.nanoTime() - startTime);
620              if (d > 0L)
621 <                ms = d / (1000 * 1000);
621 >                millis = d / (1000 * 1000);
622              else
623                  break;
624          }
# Line 470 | Line 627 | public class JSR166TestCase extends Test
627      /**
628       * Waits out termination of a thread pool or fails doing so.
629       */
630 <    public void joinPool(ExecutorService exec) {
630 >    void joinPool(ExecutorService exec) {
631          try {
632              exec.shutdown();
633              assertTrue("ExecutorService did not terminate in a timely manner",
# Line 483 | Line 640 | public class JSR166TestCase extends Test
640      }
641  
642      /**
643 <     * Checks that thread does not terminate within timeoutMillis
644 <     * milliseconds (that is, Thread.join times out).
643 >     * A debugging tool to print all stack traces, as jstack does.
644 >     */
645 >    static void printAllStackTraces() {
646 >        for (ThreadInfo info :
647 >                 ManagementFactory.getThreadMXBean()
648 >                 .dumpAllThreads(true, true))
649 >            System.err.print(info);
650 >    }
651 >
652 >    /**
653 >     * Checks that thread does not terminate within the default
654 >     * millisecond delay of {@code timeoutMillis()}.
655 >     */
656 >    void assertThreadStaysAlive(Thread thread) {
657 >        assertThreadStaysAlive(thread, timeoutMillis());
658 >    }
659 >
660 >    /**
661 >     * Checks that thread does not terminate within the given millisecond delay.
662       */
663 <    public void assertThreadJoinTimesOut(Thread thread, long timeoutMillis) {
663 >    void assertThreadStaysAlive(Thread thread, long millis) {
664          try {
665 <            long startTime = System.nanoTime();
666 <            thread.join(timeoutMillis);
665 >            // No need to optimize the failing case via Thread.join.
666 >            delay(millis);
667              assertTrue(thread.isAlive());
494            assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
668          } catch (InterruptedException ie) {
669              fail("Unexpected InterruptedException");
670          }
671      }
672  
673      /**
674 +     * Checks that the threads do not terminate within the default
675 +     * millisecond delay of {@code timeoutMillis()}.
676 +     */
677 +    void assertThreadsStayAlive(Thread... threads) {
678 +        assertThreadsStayAlive(timeoutMillis(), threads);
679 +    }
680 +
681 +    /**
682 +     * Checks that the threads do not terminate within the given millisecond delay.
683 +     */
684 +    void assertThreadsStayAlive(long millis, Thread... threads) {
685 +        try {
686 +            // No need to optimize the failing case via Thread.join.
687 +            delay(millis);
688 +            for (Thread thread : threads)
689 +                assertTrue(thread.isAlive());
690 +        } catch (InterruptedException ie) {
691 +            fail("Unexpected InterruptedException");
692 +        }
693 +    }
694 +
695 +    /**
696 +     * Checks that future.get times out, with the default timeout of
697 +     * {@code timeoutMillis()}.
698 +     */
699 +    void assertFutureTimesOut(Future future) {
700 +        assertFutureTimesOut(future, timeoutMillis());
701 +    }
702 +
703 +    /**
704 +     * Checks that future.get times out, with the given millisecond timeout.
705 +     */
706 +    void assertFutureTimesOut(Future future, long timeoutMillis) {
707 +        long startTime = System.nanoTime();
708 +        try {
709 +            future.get(timeoutMillis, MILLISECONDS);
710 +            shouldThrow();
711 +        } catch (TimeoutException success) {
712 +        } catch (Exception e) {
713 +            threadUnexpectedException(e);
714 +        } finally { future.cancel(true); }
715 +        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
716 +    }
717 +
718 +    /**
719       * Fails with message "should throw exception".
720       */
721      public void shouldThrow() {
# Line 536 | Line 754 | public class JSR166TestCase extends Test
754      public static final Integer m6  = new Integer(-6);
755      public static final Integer m10 = new Integer(-10);
756  
539
757      /**
758       * Runs Runnable r with a security policy that permits precisely
759       * the specified permissions.  If there is no current security
# Line 548 | Line 765 | public class JSR166TestCase extends Test
765          SecurityManager sm = System.getSecurityManager();
766          if (sm == null) {
767              r.run();
768 +        }
769 +        runWithSecurityManagerWithPermissions(r, permissions);
770 +    }
771 +
772 +    /**
773 +     * Runs Runnable r with a security policy that permits precisely
774 +     * the specified permissions.  If there is no current security
775 +     * manager, a temporary one is set for the duration of the
776 +     * Runnable.  We require that any security manager permit
777 +     * getPolicy/setPolicy.
778 +     */
779 +    public void runWithSecurityManagerWithPermissions(Runnable r,
780 +                                                      Permission... permissions) {
781 +        SecurityManager sm = System.getSecurityManager();
782 +        if (sm == null) {
783              Policy savedPolicy = Policy.getPolicy();
784              try {
785                  Policy.setPolicy(permissivePolicy());
786                  System.setSecurityManager(new SecurityManager());
787 <                runWithPermissions(r, permissions);
787 >                runWithSecurityManagerWithPermissions(r, permissions);
788              } finally {
789                  System.setSecurityManager(null);
790                  Policy.setPolicy(savedPolicy);
# Line 600 | Line 832 | public class JSR166TestCase extends Test
832              return perms.implies(p);
833          }
834          public void refresh() {}
835 +        public String toString() {
836 +            List<Permission> ps = new ArrayList<Permission>();
837 +            for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
838 +                ps.add(e.nextElement());
839 +            return "AdjustablePolicy with permissions " + ps;
840 +        }
841      }
842  
843      /**
# Line 637 | Line 875 | public class JSR166TestCase extends Test
875      }
876  
877      /**
878 <     * 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
878 >     * Spin-waits up to the specified number of milliseconds for the given
879       * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
880       */
881      void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
882 <        long timeoutNanos = timeoutMillis * 1000L * 1000L;
655 <        long t0 = System.nanoTime();
882 >        long startTime = System.nanoTime();
883          for (;;) {
884              Thread.State s = thread.getState();
885              if (s == Thread.State.BLOCKED ||
# Line 661 | Line 888 | public class JSR166TestCase extends Test
888                  return;
889              else if (s == Thread.State.TERMINATED)
890                  fail("Unexpected thread termination");
891 <            else if (System.nanoTime() - t0 > timeoutNanos) {
891 >            else if (millisElapsedSince(startTime) > timeoutMillis) {
892                  threadAssertTrue(thread.isAlive());
893                  return;
894              }
# Line 682 | Line 909 | public class JSR166TestCase extends Test
909       * startNanoTime, which must have been previously returned from a
910       * call to {@link System.nanoTime()}.
911       */
912 <    long millisElapsedSince(long startNanoTime) {
912 >    static long millisElapsedSince(long startNanoTime) {
913          return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
914      }
915  
916 + //     void assertTerminatesPromptly(long timeoutMillis, Runnable r) {
917 + //         long startTime = System.nanoTime();
918 + //         try {
919 + //             r.run();
920 + //         } catch (Throwable fail) { threadUnexpectedException(fail); }
921 + //         if (millisElapsedSince(startTime) > timeoutMillis/2)
922 + //             throw new AssertionFailedError("did not return promptly");
923 + //     }
924 +
925 + //     void assertTerminatesPromptly(Runnable r) {
926 + //         assertTerminatesPromptly(LONG_DELAY_MS/2, r);
927 + //     }
928 +
929 +    /**
930 +     * Checks that timed f.get() returns the expected value, and does not
931 +     * wait for the timeout to elapse before returning.
932 +     */
933 +    <T> void checkTimedGet(Future<T> f, T expectedValue, long timeoutMillis) {
934 +        long startTime = System.nanoTime();
935 +        try {
936 +            assertEquals(expectedValue, f.get(timeoutMillis, MILLISECONDS));
937 +        } catch (Throwable fail) { threadUnexpectedException(fail); }
938 +        if (millisElapsedSince(startTime) > timeoutMillis/2)
939 +            throw new AssertionFailedError("timed get did not return promptly");
940 +    }
941 +
942 +    <T> void checkTimedGet(Future<T> f, T expectedValue) {
943 +        checkTimedGet(f, expectedValue, LONG_DELAY_MS);
944 +    }
945 +
946      /**
947       * Returns a new started daemon Thread running the given runnable.
948       */
# Line 707 | Line 964 | public class JSR166TestCase extends Test
964          } catch (InterruptedException ie) {
965              threadUnexpectedException(ie);
966          } finally {
967 <            if (t.isAlive()) {
967 >            if (t.getState() != Thread.State.TERMINATED) {
968                  t.interrupt();
969                  fail("Test timed out");
970              }
# Line 785 | Line 1042 | public class JSR166TestCase extends Test
1042                  realRun();
1043                  threadShouldThrow("InterruptedException");
1044              } catch (InterruptedException success) {
1045 +                threadAssertFalse(Thread.interrupted());
1046              } catch (Throwable t) {
1047                  threadUnexpectedException(t);
1048              }
# Line 814 | Line 1072 | public class JSR166TestCase extends Test
1072                  threadShouldThrow("InterruptedException");
1073                  return result;
1074              } catch (InterruptedException success) {
1075 +                threadAssertFalse(Thread.interrupted());
1076              } catch (Throwable t) {
1077                  threadUnexpectedException(t);
1078              }
# Line 860 | Line 1119 | public class JSR166TestCase extends Test
1119          }
1120      }
1121  
1122 +    public void await(Semaphore semaphore) {
1123 +        try {
1124 +            assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
1125 +        } catch (Throwable t) {
1126 +            threadUnexpectedException(t);
1127 +        }
1128 +    }
1129 +
1130 + //     /**
1131 + //      * Spin-waits up to LONG_DELAY_MS until flag becomes true.
1132 + //      */
1133 + //     public void await(AtomicBoolean flag) {
1134 + //         await(flag, LONG_DELAY_MS);
1135 + //     }
1136 +
1137 + //     /**
1138 + //      * Spin-waits up to the specified timeout until flag becomes true.
1139 + //      */
1140 + //     public void await(AtomicBoolean flag, long timeoutMillis) {
1141 + //         long startTime = System.nanoTime();
1142 + //         while (!flag.get()) {
1143 + //             if (millisElapsedSince(startTime) > timeoutMillis)
1144 + //                 throw new AssertionFailedError("timed out");
1145 + //             Thread.yield();
1146 + //         }
1147 + //     }
1148 +
1149      public static class NPETask implements Callable<String> {
1150          public String call() { throw new NullPointerException(); }
1151      }
# Line 1028 | Line 1314 | public class JSR166TestCase extends Test
1314      public abstract class CheckedRecursiveAction extends RecursiveAction {
1315          protected abstract void realCompute() throws Throwable;
1316  
1317 <        public final void compute() {
1317 >        @Override protected final void compute() {
1318              try {
1319                  realCompute();
1320              } catch (Throwable t) {
# Line 1043 | Line 1329 | public class JSR166TestCase extends Test
1329      public abstract class CheckedRecursiveTask<T> extends RecursiveTask<T> {
1330          protected abstract T realCompute() throws Throwable;
1331  
1332 <        public final T compute() {
1332 >        @Override protected final T compute() {
1333              try {
1334                  return realCompute();
1335              } catch (Throwable t) {
# Line 1062 | Line 1348 | public class JSR166TestCase extends Test
1348      }
1349  
1350      /**
1351 <     * A CyclicBarrier that fails with AssertionFailedErrors instead
1352 <     * of throwing checked exceptions.
1351 >     * A CyclicBarrier that uses timed await and fails with
1352 >     * AssertionFailedErrors instead of throwing checked exceptions.
1353       */
1354      public class CheckedBarrier extends CyclicBarrier {
1355          public CheckedBarrier(int parties) { super(parties); }
1356  
1357          public int await() {
1358              try {
1359 <                return super.await();
1359 >                return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1360 >            } catch (TimeoutException e) {
1361 >                throw new AssertionFailedError("timed out");
1362              } catch (Exception e) {
1363                  AssertionFailedError afe =
1364                      new AssertionFailedError("Unexpected exception: " + e);
# Line 1080 | Line 1368 | public class JSR166TestCase extends Test
1368          }
1369      }
1370  
1371 <    public void checkEmpty(BlockingQueue q) {
1371 >    void checkEmpty(BlockingQueue q) {
1372          try {
1373              assertTrue(q.isEmpty());
1374              assertEquals(0, q.size());
# Line 1107 | Line 1395 | public class JSR166TestCase extends Test
1395          }
1396      }
1397  
1398 <    @SuppressWarnings("unchecked")
1399 <    public <T> T serialClone(T o) {
1398 >    void assertSerialEquals(Object x, Object y) {
1399 >        assertTrue(Arrays.equals(serialBytes(x), serialBytes(y)));
1400 >    }
1401 >
1402 >    void assertNotSerialEquals(Object x, Object y) {
1403 >        assertFalse(Arrays.equals(serialBytes(x), serialBytes(y)));
1404 >    }
1405 >
1406 >    byte[] serialBytes(Object o) {
1407          try {
1408              ByteArrayOutputStream bos = new ByteArrayOutputStream();
1409              ObjectOutputStream oos = new ObjectOutputStream(bos);
1410              oos.writeObject(o);
1411              oos.flush();
1412              oos.close();
1413 <            ByteArrayInputStream bin =
1414 <                new ByteArrayInputStream(bos.toByteArray());
1415 <            ObjectInputStream ois = new ObjectInputStream(bin);
1416 <            return (T) ois.readObject();
1413 >            return bos.toByteArray();
1414 >        } catch (Throwable t) {
1415 >            threadUnexpectedException(t);
1416 >            return new byte[0];
1417 >        }
1418 >    }
1419 >
1420 >    @SuppressWarnings("unchecked")
1421 >    <T> T serialClone(T o) {
1422 >        try {
1423 >            ObjectInputStream ois = new ObjectInputStream
1424 >                (new ByteArrayInputStream(serialBytes(o)));
1425 >            T clone = (T) ois.readObject();
1426 >            assertSame(o.getClass(), clone.getClass());
1427 >            return clone;
1428          } catch (Throwable t) {
1429              threadUnexpectedException(t);
1430              return null;
1431          }
1432      }
1433 +
1434 +    public void assertThrows(Class<? extends Throwable> expectedExceptionClass,
1435 +                             Runnable... throwingActions) {
1436 +        for (Runnable throwingAction : throwingActions) {
1437 +            boolean threw = false;
1438 +            try { throwingAction.run(); }
1439 +            catch (Throwable t) {
1440 +                threw = true;
1441 +                if (!expectedExceptionClass.isInstance(t)) {
1442 +                    AssertionFailedError afe =
1443 +                        new AssertionFailedError
1444 +                        ("Expected " + expectedExceptionClass.getName() +
1445 +                         ", got " + t.getClass().getName());
1446 +                    afe.initCause(t);
1447 +                    threadUnexpectedException(afe);
1448 +                }
1449 +            }
1450 +            if (!threw)
1451 +                shouldThrow(expectedExceptionClass.getName());
1452 +        }
1453 +    }
1454   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines