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.55 by jsr166, Mon Sep 20 20:42:37 2010 UTC vs.
Revision 1.119 by jsr166, Mon Jun 16 20:13:54 2014 UTC

# Line 1 | Line 1
1   /*
2   * Written by Doug Lea with assistance from members of JCP JSR-166
3   * Expert Group and released to the public domain, as explained at
4 < * http://creativecommons.org/licenses/publicdomain
4 > * http://creativecommons.org/publicdomain/zero/1.0/
5   * Other contributors include Andrew Wright, Jeffrey Hayes,
6   * Pat Fisher, Mike Judd.
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;
29 + import java.util.regex.Pattern;
30   import java.security.CodeSource;
31   import java.security.Permission;
32   import java.security.PermissionCollection;
# Line 60 | 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 96 | Line 112 | public class JSR166TestCase extends Test
112      private static final boolean useSecurityManager =
113          Boolean.getBoolean("jsr166.useSecurityManager");
114  
115 +    protected static final boolean expensiveTests =
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 +     */
129 +    private static final boolean profileTests =
130 +        Boolean.getBoolean("jsr166.profileTests");
131 +
132 +    /**
133 +     * The number of milliseconds that tests are permitted for
134 +     * execution without being reported, when profileTests is set.
135 +     */
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 (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 = 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 105 | Line 190 | public class JSR166TestCase extends Test
190              Policy.setPolicy(permissivePolicy());
191              System.setSecurityManager(new SecurityManager());
192          }
193 <        int iters = 1;
194 <        if (args.length > 0)
110 <            iters = Integer.parseInt(args[0]);
193 >        int iters = (args.length == 0) ? 1 : Integer.parseInt(args[0]);
194 >
195          Test s = suite();
196          for (int i = 0; i < iters; ++i) {
197              junit.textui.TestRunner.run(s);
# Line 117 | Line 201 | public class JSR166TestCase extends Test
201          System.exit(0);
202      }
203  
204 +    public static TestSuite newTestSuite(Object... suiteOrClasses) {
205 +        TestSuite suite = new TestSuite();
206 +        for (Object suiteOrClass : suiteOrClasses) {
207 +            if (suiteOrClass instanceof TestSuite)
208 +                suite.addTest((TestSuite) suiteOrClass);
209 +            else if (suiteOrClass instanceof Class)
210 +                suite.addTest(new TestSuite((Class<?>) suiteOrClass));
211 +            else
212 +                throw new ClassCastException("not a test suite or class");
213 +        }
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
257 >     * Collects all JSR166 unit tests as one suite.
258       */
259      public static Test suite() {
260 <        TestSuite suite = new TestSuite("JSR166 Unit Tests");
261 <
262 <        suite.addTest(new TestSuite(ForkJoinPoolTest.class));
263 <        suite.addTest(new TestSuite(ForkJoinTaskTest.class));
264 <        suite.addTest(new TestSuite(RecursiveActionTest.class));
265 <        suite.addTest(new TestSuite(RecursiveTaskTest.class));
266 <        suite.addTest(new TestSuite(LinkedTransferQueueTest.class));
267 <        suite.addTest(new TestSuite(PhaserTest.class));
268 <        suite.addTest(new TestSuite(ThreadLocalRandomTest.class));
269 <        suite.addTest(new TestSuite(AbstractExecutorServiceTest.class));
270 <        suite.addTest(new TestSuite(AbstractQueueTest.class));
271 <        suite.addTest(new TestSuite(AbstractQueuedSynchronizerTest.class));
272 <        suite.addTest(new TestSuite(AbstractQueuedLongSynchronizerTest.class));
273 <        suite.addTest(new TestSuite(ArrayBlockingQueueTest.class));
274 <        suite.addTest(new TestSuite(ArrayDequeTest.class));
275 <        suite.addTest(new TestSuite(AtomicBooleanTest.class));
276 <        suite.addTest(new TestSuite(AtomicIntegerArrayTest.class));
277 <        suite.addTest(new TestSuite(AtomicIntegerFieldUpdaterTest.class));
278 <        suite.addTest(new TestSuite(AtomicIntegerTest.class));
279 <        suite.addTest(new TestSuite(AtomicLongArrayTest.class));
280 <        suite.addTest(new TestSuite(AtomicLongFieldUpdaterTest.class));
281 <        suite.addTest(new TestSuite(AtomicLongTest.class));
282 <        suite.addTest(new TestSuite(AtomicMarkableReferenceTest.class));
283 <        suite.addTest(new TestSuite(AtomicReferenceArrayTest.class));
284 <        suite.addTest(new TestSuite(AtomicReferenceFieldUpdaterTest.class));
285 <        suite.addTest(new TestSuite(AtomicReferenceTest.class));
286 <        suite.addTest(new TestSuite(AtomicStampedReferenceTest.class));
287 <        suite.addTest(new TestSuite(ConcurrentHashMapTest.class));
288 <        suite.addTest(new TestSuite(ConcurrentLinkedDequeTest.class));
289 <        suite.addTest(new TestSuite(ConcurrentLinkedQueueTest.class));
290 <        suite.addTest(new TestSuite(ConcurrentSkipListMapTest.class));
291 <        suite.addTest(new TestSuite(ConcurrentSkipListSubMapTest.class));
292 <        suite.addTest(new TestSuite(ConcurrentSkipListSetTest.class));
293 <        suite.addTest(new TestSuite(ConcurrentSkipListSubSetTest.class));
294 <        suite.addTest(new TestSuite(CopyOnWriteArrayListTest.class));
295 <        suite.addTest(new TestSuite(CopyOnWriteArraySetTest.class));
296 <        suite.addTest(new TestSuite(CountDownLatchTest.class));
297 <        suite.addTest(new TestSuite(CyclicBarrierTest.class));
298 <        suite.addTest(new TestSuite(DelayQueueTest.class));
299 <        suite.addTest(new TestSuite(EntryTest.class));
300 <        suite.addTest(new TestSuite(ExchangerTest.class));
301 <        suite.addTest(new TestSuite(ExecutorsTest.class));
302 <        suite.addTest(new TestSuite(ExecutorCompletionServiceTest.class));
303 <        suite.addTest(new TestSuite(FutureTaskTest.class));
304 <        suite.addTest(new TestSuite(LinkedBlockingDequeTest.class));
305 <        suite.addTest(new TestSuite(LinkedBlockingQueueTest.class));
306 <        suite.addTest(new TestSuite(LinkedListTest.class));
307 <        suite.addTest(new TestSuite(LockSupportTest.class));
308 <        suite.addTest(new TestSuite(PriorityBlockingQueueTest.class));
309 <        suite.addTest(new TestSuite(PriorityQueueTest.class));
310 <        suite.addTest(new TestSuite(ReentrantLockTest.class));
311 <        suite.addTest(new TestSuite(ReentrantReadWriteLockTest.class));
312 <        suite.addTest(new TestSuite(ScheduledExecutorTest.class));
313 <        suite.addTest(new TestSuite(ScheduledExecutorSubclassTest.class));
314 <        suite.addTest(new TestSuite(SemaphoreTest.class));
315 <        suite.addTest(new TestSuite(SynchronousQueueTest.class));
316 <        suite.addTest(new TestSuite(SystemTest.class));
317 <        suite.addTest(new TestSuite(ThreadLocalTest.class));
318 <        suite.addTest(new TestSuite(ThreadPoolExecutorTest.class));
319 <        suite.addTest(new TestSuite(ThreadPoolExecutorSubclassTest.class));
320 <        suite.addTest(new TestSuite(ThreadTest.class));
321 <        suite.addTest(new TestSuite(TimeUnitTest.class));
322 <        suite.addTest(new TestSuite(TreeMapTest.class));
323 <        suite.addTest(new TestSuite(TreeSetTest.class));
324 <        suite.addTest(new TestSuite(TreeSubMapTest.class));
325 <        suite.addTest(new TestSuite(TreeSubSetTest.class));
260 >        // Java7+ test classes
261 >        TestSuite suite = newTestSuite(
262 >            ForkJoinPoolTest.suite(),
263 >            ForkJoinTaskTest.suite(),
264 >            RecursiveActionTest.suite(),
265 >            RecursiveTaskTest.suite(),
266 >            LinkedTransferQueueTest.suite(),
267 >            PhaserTest.suite(),
268 >            ThreadLocalRandomTest.suite(),
269 >            AbstractExecutorServiceTest.suite(),
270 >            AbstractQueueTest.suite(),
271 >            AbstractQueuedSynchronizerTest.suite(),
272 >            AbstractQueuedLongSynchronizerTest.suite(),
273 >            ArrayBlockingQueueTest.suite(),
274 >            ArrayDequeTest.suite(),
275 >            AtomicBooleanTest.suite(),
276 >            AtomicIntegerArrayTest.suite(),
277 >            AtomicIntegerFieldUpdaterTest.suite(),
278 >            AtomicIntegerTest.suite(),
279 >            AtomicLongArrayTest.suite(),
280 >            AtomicLongFieldUpdaterTest.suite(),
281 >            AtomicLongTest.suite(),
282 >            AtomicMarkableReferenceTest.suite(),
283 >            AtomicReferenceArrayTest.suite(),
284 >            AtomicReferenceFieldUpdaterTest.suite(),
285 >            AtomicReferenceTest.suite(),
286 >            AtomicStampedReferenceTest.suite(),
287 >            ConcurrentHashMapTest.suite(),
288 >            ConcurrentLinkedDequeTest.suite(),
289 >            ConcurrentLinkedQueueTest.suite(),
290 >            ConcurrentSkipListMapTest.suite(),
291 >            ConcurrentSkipListSubMapTest.suite(),
292 >            ConcurrentSkipListSetTest.suite(),
293 >            ConcurrentSkipListSubSetTest.suite(),
294 >            CopyOnWriteArrayListTest.suite(),
295 >            CopyOnWriteArraySetTest.suite(),
296 >            CountDownLatchTest.suite(),
297 >            CyclicBarrierTest.suite(),
298 >            DelayQueueTest.suite(),
299 >            EntryTest.suite(),
300 >            ExchangerTest.suite(),
301 >            ExecutorsTest.suite(),
302 >            ExecutorCompletionServiceTest.suite(),
303 >            FutureTaskTest.suite(),
304 >            LinkedBlockingDequeTest.suite(),
305 >            LinkedBlockingQueueTest.suite(),
306 >            LinkedListTest.suite(),
307 >            LockSupportTest.suite(),
308 >            PriorityBlockingQueueTest.suite(),
309 >            PriorityQueueTest.suite(),
310 >            ReentrantLockTest.suite(),
311 >            ReentrantReadWriteLockTest.suite(),
312 >            ScheduledExecutorTest.suite(),
313 >            ScheduledExecutorSubclassTest.suite(),
314 >            SemaphoreTest.suite(),
315 >            SynchronousQueueTest.suite(),
316 >            SystemTest.suite(),
317 >            ThreadLocalTest.suite(),
318 >            ThreadPoolExecutorTest.suite(),
319 >            ThreadPoolExecutorSubclassTest.suite(),
320 >            ThreadTest.suite(),
321 >            TimeUnitTest.suite(),
322 >            TreeMapTest.suite(),
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  
200
365      /**
366       * Returns the shortest timed delay. This could
367       * be reimplemented to use for example a Property.
# Line 206 | Line 370 | public class JSR166TestCase extends Test
370          return 50;
371      }
372  
209
373      /**
374       * Sets delays as multiples of SHORT_DELAY.
375       */
# Line 214 | Line 377 | public class JSR166TestCase extends Test
377          SHORT_DELAY_MS = getShortDelay();
378          SMALL_DELAY_MS  = SHORT_DELAY_MS * 5;
379          MEDIUM_DELAY_MS = SHORT_DELAY_MS * 10;
380 <        LONG_DELAY_MS   = SHORT_DELAY_MS * 50;
380 >        LONG_DELAY_MS   = SHORT_DELAY_MS * 200;
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      /**
# Line 238 | 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.get();
429 >        Throwable t = threadFailure.getAndSet(null);
430          if (t != null) {
431              if (t instanceof Error)
432                  throw (Error) t;
# Line 251 | Line 434 | public class JSR166TestCase extends Test
434                  throw (RuntimeException) t;
435              else if (t instanceof Exception)
436                  throw (Exception) t;
437 <            else
438 <                throw new AssertionError(t);
437 >            else {
438 >                AssertionFailedError afe =
439 >                    new AssertionFailedError(t.toString());
440 >                afe.initCause(t);
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      /**
473       * Just like fail(reason), but additionally recording (using
474 <     * threadRecordFailure) any AssertionError thrown, so that the current
475 <     * testcase will fail.
474 >     * threadRecordFailure) any AssertionFailedError thrown, so that
475 >     * the current testcase will fail.
476       */
477      public void threadFail(String reason) {
478          try {
479              fail(reason);
480 <        } catch (Throwable t) {
480 >        } catch (AssertionFailedError t) {
481              threadRecordFailure(t);
482              fail(reason);
483          }
# Line 272 | Line 485 | public class JSR166TestCase extends Test
485  
486      /**
487       * Just like assertTrue(b), but additionally recording (using
488 <     * threadRecordFailure) any AssertionError thrown, so that the current
489 <     * testcase will fail.
488 >     * threadRecordFailure) any AssertionFailedError thrown, so that
489 >     * the current testcase will fail.
490       */
491      public void threadAssertTrue(boolean b) {
492          try {
493              assertTrue(b);
494 <        } catch (AssertionError t) {
494 >        } catch (AssertionFailedError t) {
495              threadRecordFailure(t);
496              throw t;
497          }
# Line 286 | Line 499 | public class JSR166TestCase extends Test
499  
500      /**
501       * Just like assertFalse(b), but additionally recording (using
502 <     * threadRecordFailure) any AssertionError thrown, so that the
503 <     * current testcase will fail.
502 >     * threadRecordFailure) any AssertionFailedError thrown, so that
503 >     * the current testcase will fail.
504       */
505      public void threadAssertFalse(boolean b) {
506          try {
507              assertFalse(b);
508 <        } catch (AssertionError t) {
508 >        } catch (AssertionFailedError t) {
509              threadRecordFailure(t);
510              throw t;
511          }
# Line 300 | Line 513 | public class JSR166TestCase extends Test
513  
514      /**
515       * Just like assertNull(x), but additionally recording (using
516 <     * threadRecordFailure) any AssertionError thrown, so that the
517 <     * current testcase will fail.
516 >     * threadRecordFailure) any AssertionFailedError thrown, so that
517 >     * the current testcase will fail.
518       */
519      public void threadAssertNull(Object x) {
520          try {
521              assertNull(x);
522 <        } catch (AssertionError t) {
522 >        } catch (AssertionFailedError t) {
523              threadRecordFailure(t);
524              throw t;
525          }
# Line 314 | Line 527 | public class JSR166TestCase extends Test
527  
528      /**
529       * Just like assertEquals(x, y), but additionally recording (using
530 <     * threadRecordFailure) any AssertionError thrown, so that the
531 <     * current testcase will fail.
530 >     * threadRecordFailure) any AssertionFailedError thrown, so that
531 >     * the current testcase will fail.
532       */
533      public void threadAssertEquals(long x, long y) {
534          try {
535              assertEquals(x, y);
536 <        } catch (AssertionError t) {
536 >        } catch (AssertionFailedError t) {
537              threadRecordFailure(t);
538              throw t;
539          }
# Line 328 | Line 541 | public class JSR166TestCase extends Test
541  
542      /**
543       * Just like assertEquals(x, y), but additionally recording (using
544 <     * threadRecordFailure) any AssertionError thrown, so that the
545 <     * current testcase will fail.
544 >     * threadRecordFailure) any AssertionFailedError thrown, so that
545 >     * the current testcase will fail.
546       */
547      public void threadAssertEquals(Object x, Object y) {
548          try {
549              assertEquals(x, y);
550 <        } catch (AssertionError t) {
550 >        } catch (AssertionFailedError t) {
551              threadRecordFailure(t);
552              throw t;
553 +        } catch (Throwable t) {
554 +            threadUnexpectedException(t);
555          }
556      }
557  
558      /**
559       * Just like assertSame(x, y), but additionally recording (using
560 <     * threadRecordFailure) any AssertionError thrown, so that the
561 <     * current testcase will fail.
560 >     * threadRecordFailure) any AssertionFailedError thrown, so that
561 >     * the current testcase will fail.
562       */
563      public void threadAssertSame(Object x, Object y) {
564          try {
565              assertSame(x, y);
566 <        } catch (AssertionError t) {
566 >        } catch (AssertionFailedError t) {
567              threadRecordFailure(t);
568              throw t;
569          }
# Line 369 | Line 584 | public class JSR166TestCase extends Test
584      }
585  
586      /**
587 <     * Calls threadFail with message "Unexpected exception" + ex.
587 >     * Records the given exception using {@link #threadRecordFailure},
588 >     * then rethrows the exception, wrapping it in an
589 >     * AssertionFailedError if necessary.
590       */
591      public void threadUnexpectedException(Throwable t) {
592          threadRecordFailure(t);
593          t.printStackTrace();
377        // Rethrow, wrapping in an AssertionError if necessary
594          if (t instanceof RuntimeException)
595              throw (RuntimeException) t;
596          else if (t instanceof Error)
597              throw (Error) t;
598          else {
599 <            AssertionError ae = new AssertionError("unexpected exception: " + t);
600 <            t.initCause(t);
601 <            throw ae;
599 >            AssertionFailedError afe =
600 >                new AssertionFailedError("unexpected exception: " + t);
601 >            afe.initCause(t);
602 >            throw afe;
603 >        }
604 >    }
605 >
606 >    /**
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 >    static void delay(long millis) throws InterruptedException {
612 >        long startTime = System.nanoTime();
613 >        long ns = millis * 1000 * 1000;
614 >        for (;;) {
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 >                millis = d / (1000 * 1000);
622 >            else
623 >                break;
624          }
625      }
626  
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",
634 <                       exec.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
634 >                       exec.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS));
635          } catch (SecurityException ok) {
636              // Allowed in case test doesn't have privs
637          } catch (InterruptedException ie) {
# Line 401 | Line 639 | public class JSR166TestCase extends Test
639          }
640      }
641  
642 +    /**
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 +    void assertThreadStaysAlive(Thread thread, long millis) {
664 +        try {
665 +            // No need to optimize the failing case via Thread.join.
666 +            delay(millis);
667 +            assertTrue(thread.isAlive());
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".
# Line 417 | Line 730 | public class JSR166TestCase extends Test
730      }
731  
732      /**
420     * Fails with message "Unexpected exception: " + ex.
421     */
422    public void unexpectedException(Throwable ex) {
423        ex.printStackTrace();
424        fail("Unexpected exception: " + ex);
425    }
426
427
428    /**
733       * The number of elements to place in collections, arrays, etc.
734       */
735      public static final int SIZE = 20;
# Line 450 | 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  
453
757      /**
758       * Runs Runnable r with a security policy that permits precisely
759       * the specified permissions.  If there is no current security
# Line 462 | 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 514 | 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 536 | Line 860 | public class JSR166TestCase extends Test
860      }
861  
862      /**
863 <     * Sleep until the timeout has elapsed, or interrupted.
864 <     * Does <em>NOT</em> throw InterruptedException.
863 >     * Sleeps until the given time has elapsed.
864 >     * Throws AssertionFailedError if interrupted.
865       */
866 <    void sleepTillInterrupted(long timeoutMillis) {
866 >    void sleep(long millis) {
867          try {
868 <            Thread.sleep(timeoutMillis);
869 <        } catch (InterruptedException wakeup) {}
868 >            delay(millis);
869 >        } catch (InterruptedException ie) {
870 >            AssertionFailedError afe =
871 >                new AssertionFailedError("Unexpected InterruptedException");
872 >            afe.initCause(ie);
873 >            throw afe;
874 >        }
875 >    }
876 >
877 >    /**
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 startTime = System.nanoTime();
883 >        for (;;) {
884 >            Thread.State s = thread.getState();
885 >            if (s == Thread.State.BLOCKED ||
886 >                s == Thread.State.WAITING ||
887 >                s == Thread.State.TIMED_WAITING)
888 >                return;
889 >            else if (s == Thread.State.TERMINATED)
890 >                fail("Unexpected thread termination");
891 >            else if (millisElapsedSince(startTime) > timeoutMillis) {
892 >                threadAssertTrue(thread.isAlive());
893 >                return;
894 >            }
895 >            Thread.yield();
896 >        }
897      }
898  
899      /**
900 <     * Returns a new started Thread running the given runnable.
900 >     * Waits up to LONG_DELAY_MS for the given thread to enter a wait
901 >     * state: BLOCKED, WAITING, or TIMED_WAITING.
902 >     */
903 >    void waitForThreadToEnterWaitState(Thread thread) {
904 >        waitForThreadToEnterWaitState(thread, LONG_DELAY_MS);
905 >    }
906 >
907 >    /**
908 >     * Returns the number of milliseconds since time given by
909 >     * startNanoTime, which must have been previously returned from a
910 >     * call to {@link System.nanoTime()}.
911 >     */
912 >    static long millisElapsedSince(long startNanoTime) {
913 >        return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
914 >    }
915 >
916 >    /**
917 >     * Returns a new started daemon Thread running the given runnable.
918       */
919      Thread newStartedThread(Runnable runnable) {
920          Thread t = new Thread(runnable);
921 +        t.setDaemon(true);
922          t.start();
923          return t;
924      }
925  
926 +    /**
927 +     * Waits for the specified time (in milliseconds) for the thread
928 +     * to terminate (using {@link Thread#join(long)}), else interrupts
929 +     * the thread (in the hope that it may terminate later) and fails.
930 +     */
931 +    void awaitTermination(Thread t, long timeoutMillis) {
932 +        try {
933 +            t.join(timeoutMillis);
934 +        } catch (InterruptedException ie) {
935 +            threadUnexpectedException(ie);
936 +        } finally {
937 +            if (t.getState() != Thread.State.TERMINATED) {
938 +                t.interrupt();
939 +                fail("Test timed out");
940 +            }
941 +        }
942 +    }
943 +
944 +    /**
945 +     * Waits for LONG_DELAY_MS milliseconds for the thread to
946 +     * terminate (using {@link Thread#join(long)}), else interrupts
947 +     * the thread (in the hope that it may terminate later) and fails.
948 +     */
949 +    void awaitTermination(Thread t) {
950 +        awaitTermination(t, LONG_DELAY_MS);
951 +    }
952 +
953      // Some convenient Runnable classes
954  
955      public abstract class CheckedRunnable implements Runnable {
# Line 616 | Line 1012 | public class JSR166TestCase extends Test
1012                  realRun();
1013                  threadShouldThrow("InterruptedException");
1014              } catch (InterruptedException success) {
1015 +                threadAssertFalse(Thread.interrupted());
1016              } catch (Throwable t) {
1017                  threadUnexpectedException(t);
1018              }
# Line 645 | Line 1042 | public class JSR166TestCase extends Test
1042                  threadShouldThrow("InterruptedException");
1043                  return result;
1044              } catch (InterruptedException success) {
1045 +                threadAssertFalse(Thread.interrupted());
1046              } catch (Throwable t) {
1047                  threadUnexpectedException(t);
1048              }
# Line 668 | Line 1066 | public class JSR166TestCase extends Test
1066  
1067      public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) {
1068          return new CheckedCallable<String>() {
1069 <            public String realCall() {
1069 >            protected String realCall() {
1070                  try {
1071                      latch.await();
1072                  } catch (InterruptedException quittingTime) {}
# Line 676 | Line 1074 | public class JSR166TestCase extends Test
1074              }};
1075      }
1076  
1077 +    public Runnable awaiter(final CountDownLatch latch) {
1078 +        return new CheckedRunnable() {
1079 +            public void realRun() throws InterruptedException {
1080 +                await(latch);
1081 +            }};
1082 +    }
1083 +
1084 +    public void await(CountDownLatch latch) {
1085 +        try {
1086 +            assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
1087 +        } catch (Throwable t) {
1088 +            threadUnexpectedException(t);
1089 +        }
1090 +    }
1091 +
1092 +    public void await(Semaphore semaphore) {
1093 +        try {
1094 +            assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
1095 +        } catch (Throwable t) {
1096 +            threadUnexpectedException(t);
1097 +        }
1098 +    }
1099 +
1100 + //     /**
1101 + //      * Spin-waits up to LONG_DELAY_MS until flag becomes true.
1102 + //      */
1103 + //     public void await(AtomicBoolean flag) {
1104 + //         await(flag, LONG_DELAY_MS);
1105 + //     }
1106 +
1107 + //     /**
1108 + //      * Spin-waits up to the specified timeout until flag becomes true.
1109 + //      */
1110 + //     public void await(AtomicBoolean flag, long timeoutMillis) {
1111 + //         long startTime = System.nanoTime();
1112 + //         while (!flag.get()) {
1113 + //             if (millisElapsedSince(startTime) > timeoutMillis)
1114 + //                 throw new AssertionFailedError("timed out");
1115 + //             Thread.yield();
1116 + //         }
1117 + //     }
1118 +
1119      public static class NPETask implements Callable<String> {
1120          public String call() { throw new NullPointerException(); }
1121      }
# Line 686 | Line 1126 | public class JSR166TestCase extends Test
1126  
1127      public class ShortRunnable extends CheckedRunnable {
1128          protected void realRun() throws Throwable {
1129 <            Thread.sleep(SHORT_DELAY_MS);
1129 >            delay(SHORT_DELAY_MS);
1130          }
1131      }
1132  
1133      public class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
1134          protected void realRun() throws InterruptedException {
1135 <            Thread.sleep(SHORT_DELAY_MS);
1135 >            delay(SHORT_DELAY_MS);
1136          }
1137      }
1138  
1139      public class SmallRunnable extends CheckedRunnable {
1140          protected void realRun() throws Throwable {
1141 <            Thread.sleep(SMALL_DELAY_MS);
1141 >            delay(SMALL_DELAY_MS);
1142          }
1143      }
1144  
1145      public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
1146          protected void realRun() {
1147              try {
1148 <                Thread.sleep(SMALL_DELAY_MS);
1148 >                delay(SMALL_DELAY_MS);
1149              } catch (InterruptedException ok) {}
1150          }
1151      }
1152  
1153      public class SmallCallable extends CheckedCallable {
1154          protected Object realCall() throws InterruptedException {
1155 <            Thread.sleep(SMALL_DELAY_MS);
1155 >            delay(SMALL_DELAY_MS);
1156              return Boolean.TRUE;
1157          }
1158      }
1159  
720    public class SmallInterruptedRunnable extends CheckedInterruptedRunnable {
721        protected void realRun() throws InterruptedException {
722            Thread.sleep(SMALL_DELAY_MS);
723        }
724    }
725
1160      public class MediumRunnable extends CheckedRunnable {
1161          protected void realRun() throws Throwable {
1162 <            Thread.sleep(MEDIUM_DELAY_MS);
1162 >            delay(MEDIUM_DELAY_MS);
1163          }
1164      }
1165  
1166      public class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
1167          protected void realRun() throws InterruptedException {
1168 <            Thread.sleep(MEDIUM_DELAY_MS);
1168 >            delay(MEDIUM_DELAY_MS);
1169          }
1170      }
1171  
1172 +    public Runnable possiblyInterruptedRunnable(final long timeoutMillis) {
1173 +        return new CheckedRunnable() {
1174 +            protected void realRun() {
1175 +                try {
1176 +                    delay(timeoutMillis);
1177 +                } catch (InterruptedException ok) {}
1178 +            }};
1179 +    }
1180 +
1181      public class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
1182          protected void realRun() {
1183              try {
1184 <                Thread.sleep(MEDIUM_DELAY_MS);
1184 >                delay(MEDIUM_DELAY_MS);
1185              } catch (InterruptedException ok) {}
1186          }
1187      }
# Line 746 | Line 1189 | public class JSR166TestCase extends Test
1189      public class LongPossiblyInterruptedRunnable extends CheckedRunnable {
1190          protected void realRun() {
1191              try {
1192 <                Thread.sleep(LONG_DELAY_MS);
1192 >                delay(LONG_DELAY_MS);
1193              } catch (InterruptedException ok) {}
1194          }
1195      }
# Line 760 | Line 1203 | public class JSR166TestCase extends Test
1203          }
1204      }
1205  
1206 +    public interface TrackedRunnable extends Runnable {
1207 +        boolean isDone();
1208 +    }
1209 +
1210 +    public static TrackedRunnable trackedRunnable(final long timeoutMillis) {
1211 +        return new TrackedRunnable() {
1212 +                private volatile boolean done = false;
1213 +                public boolean isDone() { return done; }
1214 +                public void run() {
1215 +                    try {
1216 +                        delay(timeoutMillis);
1217 +                        done = true;
1218 +                    } catch (InterruptedException ok) {}
1219 +                }
1220 +            };
1221 +    }
1222 +
1223      public static class TrackedShortRunnable implements Runnable {
1224          public volatile boolean done = false;
1225          public void run() {
1226              try {
1227 <                Thread.sleep(SMALL_DELAY_MS);
1227 >                delay(SHORT_DELAY_MS);
1228 >                done = true;
1229 >            } catch (InterruptedException ok) {}
1230 >        }
1231 >    }
1232 >
1233 >    public static class TrackedSmallRunnable implements Runnable {
1234 >        public volatile boolean done = false;
1235 >        public void run() {
1236 >            try {
1237 >                delay(SMALL_DELAY_MS);
1238                  done = true;
1239              } catch (InterruptedException ok) {}
1240          }
# Line 774 | Line 1244 | public class JSR166TestCase extends Test
1244          public volatile boolean done = false;
1245          public void run() {
1246              try {
1247 <                Thread.sleep(MEDIUM_DELAY_MS);
1247 >                delay(MEDIUM_DELAY_MS);
1248                  done = true;
1249              } catch (InterruptedException ok) {}
1250          }
# Line 784 | Line 1254 | public class JSR166TestCase extends Test
1254          public volatile boolean done = false;
1255          public void run() {
1256              try {
1257 <                Thread.sleep(LONG_DELAY_MS);
1257 >                delay(LONG_DELAY_MS);
1258                  done = true;
1259              } catch (InterruptedException ok) {}
1260          }
# Line 801 | Line 1271 | public class JSR166TestCase extends Test
1271          public volatile boolean done = false;
1272          public Object call() {
1273              try {
1274 <                Thread.sleep(SMALL_DELAY_MS);
1274 >                delay(SMALL_DELAY_MS);
1275                  done = true;
1276              } catch (InterruptedException ok) {}
1277              return Boolean.TRUE;
# Line 814 | Line 1284 | public class JSR166TestCase extends Test
1284      public abstract class CheckedRecursiveAction extends RecursiveAction {
1285          protected abstract void realCompute() throws Throwable;
1286  
1287 <        public final void compute() {
1287 >        @Override protected final void compute() {
1288              try {
1289                  realCompute();
1290              } catch (Throwable t) {
# Line 829 | Line 1299 | public class JSR166TestCase extends Test
1299      public abstract class CheckedRecursiveTask<T> extends RecursiveTask<T> {
1300          protected abstract T realCompute() throws Throwable;
1301  
1302 <        public final T compute() {
1302 >        @Override protected final T compute() {
1303              try {
1304                  return realCompute();
1305              } catch (Throwable t) {
# Line 847 | Line 1317 | public class JSR166TestCase extends Test
1317                                        ThreadPoolExecutor executor) {}
1318      }
1319  
1320 +    /**
1321 +     * A CyclicBarrier that uses timed await and fails with
1322 +     * AssertionFailedErrors instead of throwing checked exceptions.
1323 +     */
1324 +    public class CheckedBarrier extends CyclicBarrier {
1325 +        public CheckedBarrier(int parties) { super(parties); }
1326 +
1327 +        public int await() {
1328 +            try {
1329 +                return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1330 +            } catch (TimeoutException e) {
1331 +                throw new AssertionFailedError("timed out");
1332 +            } catch (Exception e) {
1333 +                AssertionFailedError afe =
1334 +                    new AssertionFailedError("Unexpected exception: " + e);
1335 +                afe.initCause(e);
1336 +                throw afe;
1337 +            }
1338 +        }
1339 +    }
1340 +
1341 +    void checkEmpty(BlockingQueue q) {
1342 +        try {
1343 +            assertTrue(q.isEmpty());
1344 +            assertEquals(0, q.size());
1345 +            assertNull(q.peek());
1346 +            assertNull(q.poll());
1347 +            assertNull(q.poll(0, MILLISECONDS));
1348 +            assertEquals(q.toString(), "[]");
1349 +            assertTrue(Arrays.equals(q.toArray(), new Object[0]));
1350 +            assertFalse(q.iterator().hasNext());
1351 +            try {
1352 +                q.element();
1353 +                shouldThrow();
1354 +            } catch (NoSuchElementException success) {}
1355 +            try {
1356 +                q.iterator().next();
1357 +                shouldThrow();
1358 +            } catch (NoSuchElementException success) {}
1359 +            try {
1360 +                q.remove();
1361 +                shouldThrow();
1362 +            } catch (NoSuchElementException success) {}
1363 +        } catch (InterruptedException ie) {
1364 +            threadUnexpectedException(ie);
1365 +        }
1366 +    }
1367 +
1368 +    void assertSerialEquals(Object x, Object y) {
1369 +        assertTrue(Arrays.equals(serialBytes(x), serialBytes(y)));
1370 +    }
1371 +
1372 +    void assertNotSerialEquals(Object x, Object y) {
1373 +        assertFalse(Arrays.equals(serialBytes(x), serialBytes(y)));
1374 +    }
1375 +
1376 +    byte[] serialBytes(Object o) {
1377 +        try {
1378 +            ByteArrayOutputStream bos = new ByteArrayOutputStream();
1379 +            ObjectOutputStream oos = new ObjectOutputStream(bos);
1380 +            oos.writeObject(o);
1381 +            oos.flush();
1382 +            oos.close();
1383 +            return bos.toByteArray();
1384 +        } catch (Throwable t) {
1385 +            threadUnexpectedException(t);
1386 +            return new byte[0];
1387 +        }
1388 +    }
1389 +
1390 +    @SuppressWarnings("unchecked")
1391 +    <T> T serialClone(T o) {
1392 +        try {
1393 +            ObjectInputStream ois = new ObjectInputStream
1394 +                (new ByteArrayInputStream(serialBytes(o)));
1395 +            T clone = (T) ois.readObject();
1396 +            assertSame(o.getClass(), clone.getClass());
1397 +            return clone;
1398 +        } catch (Throwable t) {
1399 +            threadUnexpectedException(t);
1400 +            return null;
1401 +        }
1402 +    }
1403 +
1404 +    public void assertThrows(Class<? extends Throwable> expectedExceptionClass,
1405 +                             Runnable... throwingActions) {
1406 +        for (Runnable throwingAction : throwingActions) {
1407 +            boolean threw = false;
1408 +            try { throwingAction.run(); }
1409 +            catch (Throwable t) {
1410 +                threw = true;
1411 +                if (!expectedExceptionClass.isInstance(t)) {
1412 +                    AssertionFailedError afe =
1413 +                        new AssertionFailedError
1414 +                        ("Expected " + expectedExceptionClass.getName() +
1415 +                         ", got " + t.getClass().getName());
1416 +                    afe.initCause(t);
1417 +                    threadUnexpectedException(afe);
1418 +                }
1419 +            }
1420 +            if (!threw)
1421 +                shouldThrow(expectedExceptionClass.getName());
1422 +        }
1423 +    }
1424   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines