ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/JSR166TestCase.java
Revision: 1.136
Committed: Fri Sep 4 18:16:28 2015 UTC (8 years, 8 months ago) by jsr166
Branch: MAIN
Changes since 1.135: +8 -1 lines
Log Message:
Fix (broken) atLeastJava9, and boldly try to add atLeastJava10

File Contents

# Content
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/publicdomain/zero/1.0/
5 * Other contributors include Andrew Wright, Jeffrey Hayes,
6 * Pat Fisher, Mike Judd.
7 */
8
9 import static java.util.concurrent.TimeUnit.MILLISECONDS;
10 import static java.util.concurrent.TimeUnit.NANOSECONDS;
11
12 import java.io.ByteArrayInputStream;
13 import java.io.ByteArrayOutputStream;
14 import java.io.ObjectInputStream;
15 import java.io.ObjectOutputStream;
16 import java.lang.management.ManagementFactory;
17 import java.lang.management.ThreadInfo;
18 import java.lang.reflect.Constructor;
19 import java.lang.reflect.Method;
20 import java.lang.reflect.Modifier;
21 import java.security.CodeSource;
22 import java.security.Permission;
23 import java.security.PermissionCollection;
24 import java.security.Permissions;
25 import java.security.Policy;
26 import java.security.ProtectionDomain;
27 import java.security.SecurityPermission;
28 import java.util.ArrayList;
29 import java.util.Arrays;
30 import java.util.Date;
31 import java.util.Enumeration;
32 import java.util.Iterator;
33 import java.util.List;
34 import java.util.NoSuchElementException;
35 import java.util.PropertyPermission;
36 import java.util.concurrent.BlockingQueue;
37 import java.util.concurrent.Callable;
38 import java.util.concurrent.CountDownLatch;
39 import java.util.concurrent.CyclicBarrier;
40 import java.util.concurrent.ExecutorService;
41 import java.util.concurrent.Future;
42 import java.util.concurrent.RecursiveAction;
43 import java.util.concurrent.RecursiveTask;
44 import java.util.concurrent.RejectedExecutionHandler;
45 import java.util.concurrent.Semaphore;
46 import java.util.concurrent.ThreadFactory;
47 import java.util.concurrent.ThreadPoolExecutor;
48 import java.util.concurrent.TimeoutException;
49 import java.util.concurrent.atomic.AtomicReference;
50 import java.util.regex.Pattern;
51
52 import junit.framework.AssertionFailedError;
53 import junit.framework.Test;
54 import junit.framework.TestCase;
55 import junit.framework.TestResult;
56 import junit.framework.TestSuite;
57
58 /**
59 * Base class for JSR166 Junit TCK tests. Defines some constants,
60 * utility methods and classes, as well as a simple framework for
61 * helping to make sure that assertions failing in generated threads
62 * cause the associated test that generated them to itself fail (which
63 * JUnit does not otherwise arrange). The rules for creating such
64 * tests are:
65 *
66 * <ol>
67 *
68 * <li> All assertions in code running in generated threads must use
69 * the forms {@link #threadFail}, {@link #threadAssertTrue}, {@link
70 * #threadAssertEquals}, or {@link #threadAssertNull}, (not
71 * {@code fail}, {@code assertTrue}, etc.) It is OK (but not
72 * particularly recommended) for other code to use these forms too.
73 * Only the most typically used JUnit assertion methods are defined
74 * this way, but enough to live with.</li>
75 *
76 * <li> If you override {@link #setUp} or {@link #tearDown}, make sure
77 * to invoke {@code super.setUp} and {@code super.tearDown} within
78 * them. These methods are used to clear and check for thread
79 * assertion failures.</li>
80 *
81 * <li>All delays and timeouts must use one of the constants {@code
82 * SHORT_DELAY_MS}, {@code SMALL_DELAY_MS}, {@code MEDIUM_DELAY_MS},
83 * {@code LONG_DELAY_MS}. The idea here is that a SHORT is always
84 * discriminable from zero time, and always allows enough time for the
85 * small amounts of computation (creating a thread, calling a few
86 * methods, etc) needed to reach a timeout point. Similarly, a SMALL
87 * is always discriminable as larger than SHORT and smaller than
88 * MEDIUM. And so on. These constants are set to conservative values,
89 * but even so, if there is ever any doubt, they can all be increased
90 * in one spot to rerun tests on slower platforms.</li>
91 *
92 * <li> All threads generated must be joined inside each test case
93 * method (or {@code fail} to do so) before returning from the
94 * method. The {@code joinPool} method can be used to do this when
95 * using Executors.</li>
96 *
97 * </ol>
98 *
99 * <p><b>Other notes</b>
100 * <ul>
101 *
102 * <li> Usually, there is one testcase method per JSR166 method
103 * covering "normal" operation, and then as many exception-testing
104 * methods as there are exceptions the method can throw. Sometimes
105 * there are multiple tests per JSR166 method when the different
106 * "normal" behaviors differ significantly. And sometimes testcases
107 * cover multiple methods when they cannot be tested in
108 * isolation.</li>
109 *
110 * <li> The documentation style for testcases is to provide as javadoc
111 * a simple sentence or two describing the property that the testcase
112 * method purports to test. The javadocs do not say anything about how
113 * the property is tested. To find out, read the code.</li>
114 *
115 * <li> These tests are "conformance tests", and do not attempt to
116 * test throughput, latency, scalability or other performance factors
117 * (see the separate "jtreg" tests for a set intended to check these
118 * for the most central aspects of functionality.) So, most tests use
119 * the smallest sensible numbers of threads, collection sizes, etc
120 * needed to check basic conformance.</li>
121 *
122 * <li>The test classes currently do not declare inclusion in
123 * any particular package to simplify things for people integrating
124 * them in TCK test suites.</li>
125 *
126 * <li> As a convenience, the {@code main} of this class (JSR166TestCase)
127 * runs all JSR166 unit tests.</li>
128 *
129 * </ul>
130 */
131 public class JSR166TestCase extends TestCase {
132 private static final boolean useSecurityManager =
133 Boolean.getBoolean("jsr166.useSecurityManager");
134
135 protected static final boolean expensiveTests =
136 Boolean.getBoolean("jsr166.expensiveTests");
137
138 /**
139 * If true, also run tests that are not part of the official tck
140 * because they test unspecified implementation details.
141 */
142 protected static final boolean testImplementationDetails =
143 Boolean.getBoolean("jsr166.testImplementationDetails");
144
145 /**
146 * If true, report on stdout all "slow" tests, that is, ones that
147 * take more than profileThreshold milliseconds to execute.
148 */
149 private static final boolean profileTests =
150 Boolean.getBoolean("jsr166.profileTests");
151
152 /**
153 * The number of milliseconds that tests are permitted for
154 * execution without being reported, when profileTests is set.
155 */
156 private static final long profileThreshold =
157 Long.getLong("jsr166.profileThreshold", 100);
158
159 /**
160 * The number of repetitions per test (for tickling rare bugs).
161 */
162 private static final int runsPerTest =
163 Integer.getInteger("jsr166.runsPerTest", 1);
164
165 /**
166 * The number of repetitions of the test suite (for finding leaks?).
167 */
168 private static final int suiteRuns =
169 Integer.getInteger("jsr166.suiteRuns", 1);
170
171 public JSR166TestCase() { super(); }
172 public JSR166TestCase(String name) { super(name); }
173
174 /**
175 * A filter for tests to run, matching strings of the form
176 * methodName(className), e.g. "testInvokeAll5(ForkJoinPoolTest)"
177 * Usefully combined with jsr166.runsPerTest.
178 */
179 private static final Pattern methodFilter = methodFilter();
180
181 private static Pattern methodFilter() {
182 String regex = System.getProperty("jsr166.methodFilter");
183 return (regex == null) ? null : Pattern.compile(regex);
184 }
185
186 protected void runTest() throws Throwable {
187 if (methodFilter == null
188 || methodFilter.matcher(toString()).find()) {
189 for (int i = 0; i < runsPerTest; i++) {
190 if (profileTests)
191 runTestProfiled();
192 else
193 super.runTest();
194 }
195 }
196 }
197
198 protected void runTestProfiled() throws Throwable {
199 // Warmup run, notably to trigger all needed classloading.
200 super.runTest();
201 long t0 = System.nanoTime();
202 try {
203 super.runTest();
204 } finally {
205 long elapsedMillis = millisElapsedSince(t0);
206 if (elapsedMillis >= profileThreshold)
207 System.out.printf("%n%s: %d%n", toString(), elapsedMillis);
208 }
209 }
210
211 /**
212 * Runs all JSR166 unit tests using junit.textui.TestRunner.
213 */
214 public static void main(String[] args) {
215 main(suite(), args);
216 }
217
218 /**
219 * Runs all unit tests in the given test suite.
220 * Actual behavior influenced by jsr166.* system properties.
221 */
222 static void main(Test suite, String[] args) {
223 if (useSecurityManager) {
224 System.err.println("Setting a permissive security manager");
225 Policy.setPolicy(permissivePolicy());
226 System.setSecurityManager(new SecurityManager());
227 }
228 for (int i = 0; i < suiteRuns; i++) {
229 TestResult result = junit.textui.TestRunner.run(suite);
230 if (!result.wasSuccessful())
231 System.exit(1);
232 System.gc();
233 System.runFinalization();
234 }
235 }
236
237 public static TestSuite newTestSuite(Object... suiteOrClasses) {
238 TestSuite suite = new TestSuite();
239 for (Object suiteOrClass : suiteOrClasses) {
240 if (suiteOrClass instanceof TestSuite)
241 suite.addTest((TestSuite) suiteOrClass);
242 else if (suiteOrClass instanceof Class)
243 suite.addTest(new TestSuite((Class<?>) suiteOrClass));
244 else
245 throw new ClassCastException("not a test suite or class");
246 }
247 return suite;
248 }
249
250 public static void addNamedTestClasses(TestSuite suite,
251 String... testClassNames) {
252 for (String testClassName : testClassNames) {
253 try {
254 Class<?> testClass = Class.forName(testClassName);
255 Method m = testClass.getDeclaredMethod("suite",
256 new Class<?>[0]);
257 suite.addTest(newTestSuite((Test)m.invoke(null)));
258 } catch (Exception e) {
259 throw new Error("Missing test class", e);
260 }
261 }
262 }
263
264 public static final double JAVA_CLASS_VERSION;
265 public static final String JAVA_SPECIFICATION_VERSION;
266 static {
267 try {
268 JAVA_CLASS_VERSION = java.security.AccessController.doPrivileged(
269 new java.security.PrivilegedAction<Double>() {
270 public Double run() {
271 return Double.valueOf(System.getProperty("java.class.version"));}});
272 JAVA_SPECIFICATION_VERSION = java.security.AccessController.doPrivileged(
273 new java.security.PrivilegedAction<String>() {
274 public String run() {
275 return System.getProperty("java.specification.version");}});
276 } catch (Throwable t) {
277 throw new Error(t);
278 }
279 }
280
281 public static boolean atLeastJava6() { return JAVA_CLASS_VERSION >= 50.0; }
282 public static boolean atLeastJava7() { return JAVA_CLASS_VERSION >= 51.0; }
283 public static boolean atLeastJava8() { return JAVA_CLASS_VERSION >= 52.0; }
284 public static boolean atLeastJava9() {
285 // As of 2015-09, java9 still uses 52.0 class file version
286 return JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?(9|[0-9][0-9])$");
287 }
288 // public static boolean atLeastJava9() { return JAVA_CLASS_VERSION >= 53.0; }
289 public static boolean atLeastJava10() {
290 return JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?[0-9][0-9]$");
291 }
292
293 /**
294 * Collects all JSR166 unit tests as one suite.
295 */
296 public static Test suite() {
297 // Java7+ test classes
298 TestSuite suite = newTestSuite(
299 ForkJoinPoolTest.suite(),
300 ForkJoinTaskTest.suite(),
301 RecursiveActionTest.suite(),
302 RecursiveTaskTest.suite(),
303 LinkedTransferQueueTest.suite(),
304 PhaserTest.suite(),
305 ThreadLocalRandomTest.suite(),
306 AbstractExecutorServiceTest.suite(),
307 AbstractQueueTest.suite(),
308 AbstractQueuedSynchronizerTest.suite(),
309 AbstractQueuedLongSynchronizerTest.suite(),
310 ArrayBlockingQueueTest.suite(),
311 ArrayDequeTest.suite(),
312 AtomicBooleanTest.suite(),
313 AtomicIntegerArrayTest.suite(),
314 AtomicIntegerFieldUpdaterTest.suite(),
315 AtomicIntegerTest.suite(),
316 AtomicLongArrayTest.suite(),
317 AtomicLongFieldUpdaterTest.suite(),
318 AtomicLongTest.suite(),
319 AtomicMarkableReferenceTest.suite(),
320 AtomicReferenceArrayTest.suite(),
321 AtomicReferenceFieldUpdaterTest.suite(),
322 AtomicReferenceTest.suite(),
323 AtomicStampedReferenceTest.suite(),
324 ConcurrentHashMapTest.suite(),
325 ConcurrentLinkedDequeTest.suite(),
326 ConcurrentLinkedQueueTest.suite(),
327 ConcurrentSkipListMapTest.suite(),
328 ConcurrentSkipListSubMapTest.suite(),
329 ConcurrentSkipListSetTest.suite(),
330 ConcurrentSkipListSubSetTest.suite(),
331 CopyOnWriteArrayListTest.suite(),
332 CopyOnWriteArraySetTest.suite(),
333 CountDownLatchTest.suite(),
334 CyclicBarrierTest.suite(),
335 DelayQueueTest.suite(),
336 EntryTest.suite(),
337 ExchangerTest.suite(),
338 ExecutorsTest.suite(),
339 ExecutorCompletionServiceTest.suite(),
340 FutureTaskTest.suite(),
341 LinkedBlockingDequeTest.suite(),
342 LinkedBlockingQueueTest.suite(),
343 LinkedListTest.suite(),
344 LockSupportTest.suite(),
345 PriorityBlockingQueueTest.suite(),
346 PriorityQueueTest.suite(),
347 ReentrantLockTest.suite(),
348 ReentrantReadWriteLockTest.suite(),
349 ScheduledExecutorTest.suite(),
350 ScheduledExecutorSubclassTest.suite(),
351 SemaphoreTest.suite(),
352 SynchronousQueueTest.suite(),
353 SystemTest.suite(),
354 ThreadLocalTest.suite(),
355 ThreadPoolExecutorTest.suite(),
356 ThreadPoolExecutorSubclassTest.suite(),
357 ThreadTest.suite(),
358 TimeUnitTest.suite(),
359 TreeMapTest.suite(),
360 TreeSetTest.suite(),
361 TreeSubMapTest.suite(),
362 TreeSubSetTest.suite());
363
364 // Java8+ test classes
365 if (atLeastJava8()) {
366 String[] java8TestClassNames = {
367 "Atomic8Test",
368 "CompletableFutureTest",
369 "ConcurrentHashMap8Test",
370 "CountedCompleterTest",
371 "DoubleAccumulatorTest",
372 "DoubleAdderTest",
373 "ForkJoinPool8Test",
374 "ForkJoinTask8Test",
375 "LongAccumulatorTest",
376 "LongAdderTest",
377 "SplittableRandomTest",
378 "StampedLockTest",
379 "ThreadLocalRandom8Test",
380 };
381 addNamedTestClasses(suite, java8TestClassNames);
382 }
383
384 // Java9+ test classes
385 if (atLeastJava9()) {
386 String[] java9TestClassNames = {
387 "ThreadPoolExecutor9Test",
388 };
389 addNamedTestClasses(suite, java9TestClassNames);
390 }
391
392 return suite;
393 }
394
395 /** Returns list of junit-style test method names in given class. */
396 public static ArrayList<String> testMethodNames(Class<?> testClass) {
397 Method[] methods = testClass.getDeclaredMethods();
398 ArrayList<String> names = new ArrayList<String>(methods.length);
399 for (Method method : methods) {
400 if (method.getName().startsWith("test")
401 && Modifier.isPublic(method.getModifiers())
402 // method.getParameterCount() requires jdk8+
403 && method.getParameterTypes().length == 0) {
404 names.add(method.getName());
405 }
406 }
407 return names;
408 }
409
410 /**
411 * Returns junit-style testSuite for the given test class, but
412 * parameterized by passing extra data to each test.
413 */
414 public static <ExtraData> Test parameterizedTestSuite
415 (Class<? extends JSR166TestCase> testClass,
416 Class<ExtraData> dataClass,
417 ExtraData data) {
418 try {
419 TestSuite suite = new TestSuite();
420 Constructor c =
421 testClass.getDeclaredConstructor(dataClass, String.class);
422 for (String methodName : testMethodNames(testClass))
423 suite.addTest((Test) c.newInstance(data, methodName));
424 return suite;
425 } catch (Exception e) {
426 throw new Error(e);
427 }
428 }
429
430 /**
431 * Returns junit-style testSuite for the jdk8 extension of the
432 * given test class, but parameterized by passing extra data to
433 * each test. Uses reflection to allow compilation in jdk7.
434 */
435 public static <ExtraData> Test jdk8ParameterizedTestSuite
436 (Class<? extends JSR166TestCase> testClass,
437 Class<ExtraData> dataClass,
438 ExtraData data) {
439 if (atLeastJava8()) {
440 String name = testClass.getName();
441 String name8 = name.replaceAll("Test$", "8Test");
442 if (name.equals(name8)) throw new Error(name);
443 try {
444 return (Test)
445 Class.forName(name8)
446 .getMethod("testSuite", new Class[] { dataClass })
447 .invoke(null, data);
448 } catch (Exception e) {
449 throw new Error(e);
450 }
451 } else {
452 return new TestSuite();
453 }
454
455 }
456
457 // Delays for timing-dependent tests, in milliseconds.
458
459 public static long SHORT_DELAY_MS;
460 public static long SMALL_DELAY_MS;
461 public static long MEDIUM_DELAY_MS;
462 public static long LONG_DELAY_MS;
463
464 /**
465 * Returns the shortest timed delay. This could
466 * be reimplemented to use for example a Property.
467 */
468 protected long getShortDelay() {
469 return 50;
470 }
471
472 /**
473 * Sets delays as multiples of SHORT_DELAY.
474 */
475 protected void setDelays() {
476 SHORT_DELAY_MS = getShortDelay();
477 SMALL_DELAY_MS = SHORT_DELAY_MS * 5;
478 MEDIUM_DELAY_MS = SHORT_DELAY_MS * 10;
479 LONG_DELAY_MS = SHORT_DELAY_MS * 200;
480 }
481
482 /**
483 * Returns a timeout in milliseconds to be used in tests that
484 * verify that operations block or time out.
485 */
486 long timeoutMillis() {
487 return SHORT_DELAY_MS / 4;
488 }
489
490 /**
491 * Returns a new Date instance representing a time at least
492 * delayMillis milliseconds in the future.
493 */
494 Date delayedDate(long delayMillis) {
495 // Add 1 because currentTimeMillis is known to round into the past.
496 return new Date(System.currentTimeMillis() + delayMillis + 1);
497 }
498
499 /**
500 * The first exception encountered if any threadAssertXXX method fails.
501 */
502 private final AtomicReference<Throwable> threadFailure
503 = new AtomicReference<Throwable>(null);
504
505 /**
506 * Records an exception so that it can be rethrown later in the test
507 * harness thread, triggering a test case failure. Only the first
508 * failure is recorded; subsequent calls to this method from within
509 * the same test have no effect.
510 */
511 public void threadRecordFailure(Throwable t) {
512 threadFailure.compareAndSet(null, t);
513 }
514
515 public void setUp() {
516 setDelays();
517 }
518
519 /**
520 * Extra checks that get done for all test cases.
521 *
522 * Triggers test case failure if any thread assertions have failed,
523 * by rethrowing, in the test harness thread, any exception recorded
524 * earlier by threadRecordFailure.
525 *
526 * Triggers test case failure if interrupt status is set in the main thread.
527 */
528 public void tearDown() throws Exception {
529 Throwable t = threadFailure.getAndSet(null);
530 if (t != null) {
531 if (t instanceof Error)
532 throw (Error) t;
533 else if (t instanceof RuntimeException)
534 throw (RuntimeException) t;
535 else if (t instanceof Exception)
536 throw (Exception) t;
537 else {
538 AssertionFailedError afe =
539 new AssertionFailedError(t.toString());
540 afe.initCause(t);
541 throw afe;
542 }
543 }
544
545 if (Thread.interrupted())
546 throw new AssertionFailedError("interrupt status set in main thread");
547
548 checkForkJoinPoolThreadLeaks();
549 }
550
551 /**
552 * Finds missing try { ... } finally { joinPool(e); }
553 */
554 void checkForkJoinPoolThreadLeaks() throws InterruptedException {
555 Thread[] survivors = new Thread[5];
556 int count = Thread.enumerate(survivors);
557 for (int i = 0; i < count; i++) {
558 Thread thread = survivors[i];
559 String name = thread.getName();
560 if (name.startsWith("ForkJoinPool-")) {
561 // give thread some time to terminate
562 thread.join(LONG_DELAY_MS);
563 if (!thread.isAlive()) continue;
564 throw new AssertionFailedError
565 (String.format("Found leaked ForkJoinPool thread test=%s thread=%s%n",
566 toString(), name));
567 }
568 }
569 }
570
571 /**
572 * Just like fail(reason), but additionally recording (using
573 * threadRecordFailure) any AssertionFailedError thrown, so that
574 * the current testcase will fail.
575 */
576 public void threadFail(String reason) {
577 try {
578 fail(reason);
579 } catch (AssertionFailedError t) {
580 threadRecordFailure(t);
581 fail(reason);
582 }
583 }
584
585 /**
586 * Just like assertTrue(b), but additionally recording (using
587 * threadRecordFailure) any AssertionFailedError thrown, so that
588 * the current testcase will fail.
589 */
590 public void threadAssertTrue(boolean b) {
591 try {
592 assertTrue(b);
593 } catch (AssertionFailedError t) {
594 threadRecordFailure(t);
595 throw t;
596 }
597 }
598
599 /**
600 * Just like assertFalse(b), but additionally recording (using
601 * threadRecordFailure) any AssertionFailedError thrown, so that
602 * the current testcase will fail.
603 */
604 public void threadAssertFalse(boolean b) {
605 try {
606 assertFalse(b);
607 } catch (AssertionFailedError t) {
608 threadRecordFailure(t);
609 throw t;
610 }
611 }
612
613 /**
614 * Just like assertNull(x), but additionally recording (using
615 * threadRecordFailure) any AssertionFailedError thrown, so that
616 * the current testcase will fail.
617 */
618 public void threadAssertNull(Object x) {
619 try {
620 assertNull(x);
621 } catch (AssertionFailedError t) {
622 threadRecordFailure(t);
623 throw t;
624 }
625 }
626
627 /**
628 * Just like assertEquals(x, y), but additionally recording (using
629 * threadRecordFailure) any AssertionFailedError thrown, so that
630 * the current testcase will fail.
631 */
632 public void threadAssertEquals(long x, long y) {
633 try {
634 assertEquals(x, y);
635 } catch (AssertionFailedError t) {
636 threadRecordFailure(t);
637 throw t;
638 }
639 }
640
641 /**
642 * Just like assertEquals(x, y), but additionally recording (using
643 * threadRecordFailure) any AssertionFailedError thrown, so that
644 * the current testcase will fail.
645 */
646 public void threadAssertEquals(Object x, Object y) {
647 try {
648 assertEquals(x, y);
649 } catch (AssertionFailedError fail) {
650 threadRecordFailure(fail);
651 throw fail;
652 } catch (Throwable fail) {
653 threadUnexpectedException(fail);
654 }
655 }
656
657 /**
658 * Just like assertSame(x, y), but additionally recording (using
659 * threadRecordFailure) any AssertionFailedError thrown, so that
660 * the current testcase will fail.
661 */
662 public void threadAssertSame(Object x, Object y) {
663 try {
664 assertSame(x, y);
665 } catch (AssertionFailedError fail) {
666 threadRecordFailure(fail);
667 throw fail;
668 }
669 }
670
671 /**
672 * Calls threadFail with message "should throw exception".
673 */
674 public void threadShouldThrow() {
675 threadFail("should throw exception");
676 }
677
678 /**
679 * Calls threadFail with message "should throw" + exceptionName.
680 */
681 public void threadShouldThrow(String exceptionName) {
682 threadFail("should throw " + exceptionName);
683 }
684
685 /**
686 * Records the given exception using {@link #threadRecordFailure},
687 * then rethrows the exception, wrapping it in an
688 * AssertionFailedError if necessary.
689 */
690 public void threadUnexpectedException(Throwable t) {
691 threadRecordFailure(t);
692 t.printStackTrace();
693 if (t instanceof RuntimeException)
694 throw (RuntimeException) t;
695 else if (t instanceof Error)
696 throw (Error) t;
697 else {
698 AssertionFailedError afe =
699 new AssertionFailedError("unexpected exception: " + t);
700 afe.initCause(t);
701 throw afe;
702 }
703 }
704
705 /**
706 * Delays, via Thread.sleep, for the given millisecond delay, but
707 * if the sleep is shorter than specified, may re-sleep or yield
708 * until time elapses.
709 */
710 static void delay(long millis) throws InterruptedException {
711 long startTime = System.nanoTime();
712 long ns = millis * 1000 * 1000;
713 for (;;) {
714 if (millis > 0L)
715 Thread.sleep(millis);
716 else // too short to sleep
717 Thread.yield();
718 long d = ns - (System.nanoTime() - startTime);
719 if (d > 0L)
720 millis = d / (1000 * 1000);
721 else
722 break;
723 }
724 }
725
726 /**
727 * Waits out termination of a thread pool or fails doing so.
728 */
729 void joinPool(ExecutorService exec) {
730 try {
731 exec.shutdown();
732 if (!exec.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS))
733 fail("ExecutorService " + exec +
734 " did not terminate in a timely manner");
735 } catch (SecurityException ok) {
736 // Allowed in case test doesn't have privs
737 } catch (InterruptedException fail) {
738 fail("Unexpected InterruptedException");
739 }
740 }
741
742 /**
743 * A debugging tool to print all stack traces, as jstack does.
744 */
745 static void printAllStackTraces() {
746 for (ThreadInfo info :
747 ManagementFactory.getThreadMXBean()
748 .dumpAllThreads(true, true))
749 System.err.print(info);
750 }
751
752 /**
753 * Checks that thread does not terminate within the default
754 * millisecond delay of {@code timeoutMillis()}.
755 */
756 void assertThreadStaysAlive(Thread thread) {
757 assertThreadStaysAlive(thread, timeoutMillis());
758 }
759
760 /**
761 * Checks that thread does not terminate within the given millisecond delay.
762 */
763 void assertThreadStaysAlive(Thread thread, long millis) {
764 try {
765 // No need to optimize the failing case via Thread.join.
766 delay(millis);
767 assertTrue(thread.isAlive());
768 } catch (InterruptedException fail) {
769 fail("Unexpected InterruptedException");
770 }
771 }
772
773 /**
774 * Checks that the threads do not terminate within the default
775 * millisecond delay of {@code timeoutMillis()}.
776 */
777 void assertThreadsStayAlive(Thread... threads) {
778 assertThreadsStayAlive(timeoutMillis(), threads);
779 }
780
781 /**
782 * Checks that the threads do not terminate within the given millisecond delay.
783 */
784 void assertThreadsStayAlive(long millis, Thread... threads) {
785 try {
786 // No need to optimize the failing case via Thread.join.
787 delay(millis);
788 for (Thread thread : threads)
789 assertTrue(thread.isAlive());
790 } catch (InterruptedException fail) {
791 fail("Unexpected InterruptedException");
792 }
793 }
794
795 /**
796 * Checks that future.get times out, with the default timeout of
797 * {@code timeoutMillis()}.
798 */
799 void assertFutureTimesOut(Future future) {
800 assertFutureTimesOut(future, timeoutMillis());
801 }
802
803 /**
804 * Checks that future.get times out, with the given millisecond timeout.
805 */
806 void assertFutureTimesOut(Future future, long timeoutMillis) {
807 long startTime = System.nanoTime();
808 try {
809 future.get(timeoutMillis, MILLISECONDS);
810 shouldThrow();
811 } catch (TimeoutException success) {
812 } catch (Exception fail) {
813 threadUnexpectedException(fail);
814 } finally { future.cancel(true); }
815 assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
816 }
817
818 /**
819 * Fails with message "should throw exception".
820 */
821 public void shouldThrow() {
822 fail("Should throw exception");
823 }
824
825 /**
826 * Fails with message "should throw " + exceptionName.
827 */
828 public void shouldThrow(String exceptionName) {
829 fail("Should throw " + exceptionName);
830 }
831
832 /**
833 * The number of elements to place in collections, arrays, etc.
834 */
835 public static final int SIZE = 20;
836
837 // Some convenient Integer constants
838
839 public static final Integer zero = new Integer(0);
840 public static final Integer one = new Integer(1);
841 public static final Integer two = new Integer(2);
842 public static final Integer three = new Integer(3);
843 public static final Integer four = new Integer(4);
844 public static final Integer five = new Integer(5);
845 public static final Integer six = new Integer(6);
846 public static final Integer seven = new Integer(7);
847 public static final Integer eight = new Integer(8);
848 public static final Integer nine = new Integer(9);
849 public static final Integer m1 = new Integer(-1);
850 public static final Integer m2 = new Integer(-2);
851 public static final Integer m3 = new Integer(-3);
852 public static final Integer m4 = new Integer(-4);
853 public static final Integer m5 = new Integer(-5);
854 public static final Integer m6 = new Integer(-6);
855 public static final Integer m10 = new Integer(-10);
856
857 /**
858 * Runs Runnable r with a security policy that permits precisely
859 * the specified permissions. If there is no current security
860 * manager, the runnable is run twice, both with and without a
861 * security manager. We require that any security manager permit
862 * getPolicy/setPolicy.
863 */
864 public void runWithPermissions(Runnable r, Permission... permissions) {
865 SecurityManager sm = System.getSecurityManager();
866 if (sm == null) {
867 r.run();
868 }
869 runWithSecurityManagerWithPermissions(r, permissions);
870 }
871
872 /**
873 * Runs Runnable r with a security policy that permits precisely
874 * the specified permissions. If there is no current security
875 * manager, a temporary one is set for the duration of the
876 * Runnable. We require that any security manager permit
877 * getPolicy/setPolicy.
878 */
879 public void runWithSecurityManagerWithPermissions(Runnable r,
880 Permission... permissions) {
881 SecurityManager sm = System.getSecurityManager();
882 if (sm == null) {
883 Policy savedPolicy = Policy.getPolicy();
884 try {
885 Policy.setPolicy(permissivePolicy());
886 System.setSecurityManager(new SecurityManager());
887 runWithSecurityManagerWithPermissions(r, permissions);
888 } finally {
889 System.setSecurityManager(null);
890 Policy.setPolicy(savedPolicy);
891 }
892 } else {
893 Policy savedPolicy = Policy.getPolicy();
894 AdjustablePolicy policy = new AdjustablePolicy(permissions);
895 Policy.setPolicy(policy);
896
897 try {
898 r.run();
899 } finally {
900 policy.addPermission(new SecurityPermission("setPolicy"));
901 Policy.setPolicy(savedPolicy);
902 }
903 }
904 }
905
906 /**
907 * Runs a runnable without any permissions.
908 */
909 public void runWithoutPermissions(Runnable r) {
910 runWithPermissions(r);
911 }
912
913 /**
914 * A security policy where new permissions can be dynamically added
915 * or all cleared.
916 */
917 public static class AdjustablePolicy extends java.security.Policy {
918 Permissions perms = new Permissions();
919 AdjustablePolicy(Permission... permissions) {
920 for (Permission permission : permissions)
921 perms.add(permission);
922 }
923 void addPermission(Permission perm) { perms.add(perm); }
924 void clearPermissions() { perms = new Permissions(); }
925 public PermissionCollection getPermissions(CodeSource cs) {
926 return perms;
927 }
928 public PermissionCollection getPermissions(ProtectionDomain pd) {
929 return perms;
930 }
931 public boolean implies(ProtectionDomain pd, Permission p) {
932 return perms.implies(p);
933 }
934 public void refresh() {}
935 public String toString() {
936 List<Permission> ps = new ArrayList<Permission>();
937 for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
938 ps.add(e.nextElement());
939 return "AdjustablePolicy with permissions " + ps;
940 }
941 }
942
943 /**
944 * Returns a policy containing all the permissions we ever need.
945 */
946 public static Policy permissivePolicy() {
947 return new AdjustablePolicy
948 // Permissions j.u.c. needs directly
949 (new RuntimePermission("modifyThread"),
950 new RuntimePermission("getClassLoader"),
951 new RuntimePermission("setContextClassLoader"),
952 // Permissions needed to change permissions!
953 new SecurityPermission("getPolicy"),
954 new SecurityPermission("setPolicy"),
955 new RuntimePermission("setSecurityManager"),
956 // Permissions needed by the junit test harness
957 new RuntimePermission("accessDeclaredMembers"),
958 new PropertyPermission("*", "read"),
959 new java.io.FilePermission("<<ALL FILES>>", "read"));
960 }
961
962 /**
963 * Sleeps until the given time has elapsed.
964 * Throws AssertionFailedError if interrupted.
965 */
966 void sleep(long millis) {
967 try {
968 delay(millis);
969 } catch (InterruptedException fail) {
970 AssertionFailedError afe =
971 new AssertionFailedError("Unexpected InterruptedException");
972 afe.initCause(fail);
973 throw afe;
974 }
975 }
976
977 /**
978 * Spin-waits up to the specified number of milliseconds for the given
979 * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
980 */
981 void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
982 long startTime = System.nanoTime();
983 for (;;) {
984 Thread.State s = thread.getState();
985 if (s == Thread.State.BLOCKED ||
986 s == Thread.State.WAITING ||
987 s == Thread.State.TIMED_WAITING)
988 return;
989 else if (s == Thread.State.TERMINATED)
990 fail("Unexpected thread termination");
991 else if (millisElapsedSince(startTime) > timeoutMillis) {
992 threadAssertTrue(thread.isAlive());
993 return;
994 }
995 Thread.yield();
996 }
997 }
998
999 /**
1000 * Waits up to LONG_DELAY_MS for the given thread to enter a wait
1001 * state: BLOCKED, WAITING, or TIMED_WAITING.
1002 */
1003 void waitForThreadToEnterWaitState(Thread thread) {
1004 waitForThreadToEnterWaitState(thread, LONG_DELAY_MS);
1005 }
1006
1007 /**
1008 * Returns the number of milliseconds since time given by
1009 * startNanoTime, which must have been previously returned from a
1010 * call to {@link System#nanoTime()}.
1011 */
1012 static long millisElapsedSince(long startNanoTime) {
1013 return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
1014 }
1015
1016 // void assertTerminatesPromptly(long timeoutMillis, Runnable r) {
1017 // long startTime = System.nanoTime();
1018 // try {
1019 // r.run();
1020 // } catch (Throwable fail) { threadUnexpectedException(fail); }
1021 // if (millisElapsedSince(startTime) > timeoutMillis/2)
1022 // throw new AssertionFailedError("did not return promptly");
1023 // }
1024
1025 // void assertTerminatesPromptly(Runnable r) {
1026 // assertTerminatesPromptly(LONG_DELAY_MS/2, r);
1027 // }
1028
1029 /**
1030 * Checks that timed f.get() returns the expected value, and does not
1031 * wait for the timeout to elapse before returning.
1032 */
1033 <T> void checkTimedGet(Future<T> f, T expectedValue, long timeoutMillis) {
1034 long startTime = System.nanoTime();
1035 try {
1036 assertEquals(expectedValue, f.get(timeoutMillis, MILLISECONDS));
1037 } catch (Throwable fail) { threadUnexpectedException(fail); }
1038 if (millisElapsedSince(startTime) > timeoutMillis/2)
1039 throw new AssertionFailedError("timed get did not return promptly");
1040 }
1041
1042 <T> void checkTimedGet(Future<T> f, T expectedValue) {
1043 checkTimedGet(f, expectedValue, LONG_DELAY_MS);
1044 }
1045
1046 /**
1047 * Returns a new started daemon Thread running the given runnable.
1048 */
1049 Thread newStartedThread(Runnable runnable) {
1050 Thread t = new Thread(runnable);
1051 t.setDaemon(true);
1052 t.start();
1053 return t;
1054 }
1055
1056 /**
1057 * Waits for the specified time (in milliseconds) for the thread
1058 * to terminate (using {@link Thread#join(long)}), else interrupts
1059 * the thread (in the hope that it may terminate later) and fails.
1060 */
1061 void awaitTermination(Thread t, long timeoutMillis) {
1062 try {
1063 t.join(timeoutMillis);
1064 } catch (InterruptedException fail) {
1065 threadUnexpectedException(fail);
1066 } finally {
1067 if (t.getState() != Thread.State.TERMINATED) {
1068 t.interrupt();
1069 fail("Test timed out");
1070 }
1071 }
1072 }
1073
1074 /**
1075 * Waits for LONG_DELAY_MS milliseconds for the thread to
1076 * terminate (using {@link Thread#join(long)}), else interrupts
1077 * the thread (in the hope that it may terminate later) and fails.
1078 */
1079 void awaitTermination(Thread t) {
1080 awaitTermination(t, LONG_DELAY_MS);
1081 }
1082
1083 // Some convenient Runnable classes
1084
1085 public abstract class CheckedRunnable implements Runnable {
1086 protected abstract void realRun() throws Throwable;
1087
1088 public final void run() {
1089 try {
1090 realRun();
1091 } catch (Throwable fail) {
1092 threadUnexpectedException(fail);
1093 }
1094 }
1095 }
1096
1097 public abstract class RunnableShouldThrow implements Runnable {
1098 protected abstract void realRun() throws Throwable;
1099
1100 final Class<?> exceptionClass;
1101
1102 <T extends Throwable> RunnableShouldThrow(Class<T> exceptionClass) {
1103 this.exceptionClass = exceptionClass;
1104 }
1105
1106 public final void run() {
1107 try {
1108 realRun();
1109 threadShouldThrow(exceptionClass.getSimpleName());
1110 } catch (Throwable t) {
1111 if (! exceptionClass.isInstance(t))
1112 threadUnexpectedException(t);
1113 }
1114 }
1115 }
1116
1117 public abstract class ThreadShouldThrow extends Thread {
1118 protected abstract void realRun() throws Throwable;
1119
1120 final Class<?> exceptionClass;
1121
1122 <T extends Throwable> ThreadShouldThrow(Class<T> exceptionClass) {
1123 this.exceptionClass = exceptionClass;
1124 }
1125
1126 public final void run() {
1127 try {
1128 realRun();
1129 threadShouldThrow(exceptionClass.getSimpleName());
1130 } catch (Throwable t) {
1131 if (! exceptionClass.isInstance(t))
1132 threadUnexpectedException(t);
1133 }
1134 }
1135 }
1136
1137 public abstract class CheckedInterruptedRunnable implements Runnable {
1138 protected abstract void realRun() throws Throwable;
1139
1140 public final void run() {
1141 try {
1142 realRun();
1143 threadShouldThrow("InterruptedException");
1144 } catch (InterruptedException success) {
1145 threadAssertFalse(Thread.interrupted());
1146 } catch (Throwable fail) {
1147 threadUnexpectedException(fail);
1148 }
1149 }
1150 }
1151
1152 public abstract class CheckedCallable<T> implements Callable<T> {
1153 protected abstract T realCall() throws Throwable;
1154
1155 public final T call() {
1156 try {
1157 return realCall();
1158 } catch (Throwable fail) {
1159 threadUnexpectedException(fail);
1160 return null;
1161 }
1162 }
1163 }
1164
1165 public abstract class CheckedInterruptedCallable<T>
1166 implements Callable<T> {
1167 protected abstract T realCall() throws Throwable;
1168
1169 public final T call() {
1170 try {
1171 T result = realCall();
1172 threadShouldThrow("InterruptedException");
1173 return result;
1174 } catch (InterruptedException success) {
1175 threadAssertFalse(Thread.interrupted());
1176 } catch (Throwable fail) {
1177 threadUnexpectedException(fail);
1178 }
1179 return null;
1180 }
1181 }
1182
1183 public static class NoOpRunnable implements Runnable {
1184 public void run() {}
1185 }
1186
1187 public static class NoOpCallable implements Callable {
1188 public Object call() { return Boolean.TRUE; }
1189 }
1190
1191 public static final String TEST_STRING = "a test string";
1192
1193 public static class StringTask implements Callable<String> {
1194 public String call() { return TEST_STRING; }
1195 }
1196
1197 public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) {
1198 return new CheckedCallable<String>() {
1199 protected String realCall() {
1200 try {
1201 latch.await();
1202 } catch (InterruptedException quittingTime) {}
1203 return TEST_STRING;
1204 }};
1205 }
1206
1207 public Runnable awaiter(final CountDownLatch latch) {
1208 return new CheckedRunnable() {
1209 public void realRun() throws InterruptedException {
1210 await(latch);
1211 }};
1212 }
1213
1214 public void await(CountDownLatch latch) {
1215 try {
1216 assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
1217 } catch (Throwable fail) {
1218 threadUnexpectedException(fail);
1219 }
1220 }
1221
1222 public void await(Semaphore semaphore) {
1223 try {
1224 assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
1225 } catch (Throwable fail) {
1226 threadUnexpectedException(fail);
1227 }
1228 }
1229
1230 // /**
1231 // * Spin-waits up to LONG_DELAY_MS until flag becomes true.
1232 // */
1233 // public void await(AtomicBoolean flag) {
1234 // await(flag, LONG_DELAY_MS);
1235 // }
1236
1237 // /**
1238 // * Spin-waits up to the specified timeout until flag becomes true.
1239 // */
1240 // public void await(AtomicBoolean flag, long timeoutMillis) {
1241 // long startTime = System.nanoTime();
1242 // while (!flag.get()) {
1243 // if (millisElapsedSince(startTime) > timeoutMillis)
1244 // throw new AssertionFailedError("timed out");
1245 // Thread.yield();
1246 // }
1247 // }
1248
1249 public static class NPETask implements Callable<String> {
1250 public String call() { throw new NullPointerException(); }
1251 }
1252
1253 public static class CallableOne implements Callable<Integer> {
1254 public Integer call() { return one; }
1255 }
1256
1257 public class ShortRunnable extends CheckedRunnable {
1258 protected void realRun() throws Throwable {
1259 delay(SHORT_DELAY_MS);
1260 }
1261 }
1262
1263 public class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
1264 protected void realRun() throws InterruptedException {
1265 delay(SHORT_DELAY_MS);
1266 }
1267 }
1268
1269 public class SmallRunnable extends CheckedRunnable {
1270 protected void realRun() throws Throwable {
1271 delay(SMALL_DELAY_MS);
1272 }
1273 }
1274
1275 public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
1276 protected void realRun() {
1277 try {
1278 delay(SMALL_DELAY_MS);
1279 } catch (InterruptedException ok) {}
1280 }
1281 }
1282
1283 public class SmallCallable extends CheckedCallable {
1284 protected Object realCall() throws InterruptedException {
1285 delay(SMALL_DELAY_MS);
1286 return Boolean.TRUE;
1287 }
1288 }
1289
1290 public class MediumRunnable extends CheckedRunnable {
1291 protected void realRun() throws Throwable {
1292 delay(MEDIUM_DELAY_MS);
1293 }
1294 }
1295
1296 public class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
1297 protected void realRun() throws InterruptedException {
1298 delay(MEDIUM_DELAY_MS);
1299 }
1300 }
1301
1302 public Runnable possiblyInterruptedRunnable(final long timeoutMillis) {
1303 return new CheckedRunnable() {
1304 protected void realRun() {
1305 try {
1306 delay(timeoutMillis);
1307 } catch (InterruptedException ok) {}
1308 }};
1309 }
1310
1311 public class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
1312 protected void realRun() {
1313 try {
1314 delay(MEDIUM_DELAY_MS);
1315 } catch (InterruptedException ok) {}
1316 }
1317 }
1318
1319 public class LongPossiblyInterruptedRunnable extends CheckedRunnable {
1320 protected void realRun() {
1321 try {
1322 delay(LONG_DELAY_MS);
1323 } catch (InterruptedException ok) {}
1324 }
1325 }
1326
1327 /**
1328 * For use as ThreadFactory in constructors
1329 */
1330 public static class SimpleThreadFactory implements ThreadFactory {
1331 public Thread newThread(Runnable r) {
1332 return new Thread(r);
1333 }
1334 }
1335
1336 public interface TrackedRunnable extends Runnable {
1337 boolean isDone();
1338 }
1339
1340 public static TrackedRunnable trackedRunnable(final long timeoutMillis) {
1341 return new TrackedRunnable() {
1342 private volatile boolean done = false;
1343 public boolean isDone() { return done; }
1344 public void run() {
1345 try {
1346 delay(timeoutMillis);
1347 done = true;
1348 } catch (InterruptedException ok) {}
1349 }
1350 };
1351 }
1352
1353 public static class TrackedShortRunnable implements Runnable {
1354 public volatile boolean done = false;
1355 public void run() {
1356 try {
1357 delay(SHORT_DELAY_MS);
1358 done = true;
1359 } catch (InterruptedException ok) {}
1360 }
1361 }
1362
1363 public static class TrackedSmallRunnable implements Runnable {
1364 public volatile boolean done = false;
1365 public void run() {
1366 try {
1367 delay(SMALL_DELAY_MS);
1368 done = true;
1369 } catch (InterruptedException ok) {}
1370 }
1371 }
1372
1373 public static class TrackedMediumRunnable implements Runnable {
1374 public volatile boolean done = false;
1375 public void run() {
1376 try {
1377 delay(MEDIUM_DELAY_MS);
1378 done = true;
1379 } catch (InterruptedException ok) {}
1380 }
1381 }
1382
1383 public static class TrackedLongRunnable implements Runnable {
1384 public volatile boolean done = false;
1385 public void run() {
1386 try {
1387 delay(LONG_DELAY_MS);
1388 done = true;
1389 } catch (InterruptedException ok) {}
1390 }
1391 }
1392
1393 public static class TrackedNoOpRunnable implements Runnable {
1394 public volatile boolean done = false;
1395 public void run() {
1396 done = true;
1397 }
1398 }
1399
1400 public static class TrackedCallable implements Callable {
1401 public volatile boolean done = false;
1402 public Object call() {
1403 try {
1404 delay(SMALL_DELAY_MS);
1405 done = true;
1406 } catch (InterruptedException ok) {}
1407 return Boolean.TRUE;
1408 }
1409 }
1410
1411 /**
1412 * Analog of CheckedRunnable for RecursiveAction
1413 */
1414 public abstract class CheckedRecursiveAction extends RecursiveAction {
1415 protected abstract void realCompute() throws Throwable;
1416
1417 @Override protected final void compute() {
1418 try {
1419 realCompute();
1420 } catch (Throwable fail) {
1421 threadUnexpectedException(fail);
1422 }
1423 }
1424 }
1425
1426 /**
1427 * Analog of CheckedCallable for RecursiveTask
1428 */
1429 public abstract class CheckedRecursiveTask<T> extends RecursiveTask<T> {
1430 protected abstract T realCompute() throws Throwable;
1431
1432 @Override protected final T compute() {
1433 try {
1434 return realCompute();
1435 } catch (Throwable fail) {
1436 threadUnexpectedException(fail);
1437 return null;
1438 }
1439 }
1440 }
1441
1442 /**
1443 * For use as RejectedExecutionHandler in constructors
1444 */
1445 public static class NoOpREHandler implements RejectedExecutionHandler {
1446 public void rejectedExecution(Runnable r,
1447 ThreadPoolExecutor executor) {}
1448 }
1449
1450 /**
1451 * A CyclicBarrier that uses timed await and fails with
1452 * AssertionFailedErrors instead of throwing checked exceptions.
1453 */
1454 public class CheckedBarrier extends CyclicBarrier {
1455 public CheckedBarrier(int parties) { super(parties); }
1456
1457 public int await() {
1458 try {
1459 return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1460 } catch (TimeoutException timedOut) {
1461 throw new AssertionFailedError("timed out");
1462 } catch (Exception fail) {
1463 AssertionFailedError afe =
1464 new AssertionFailedError("Unexpected exception: " + fail);
1465 afe.initCause(fail);
1466 throw afe;
1467 }
1468 }
1469 }
1470
1471 void checkEmpty(BlockingQueue q) {
1472 try {
1473 assertTrue(q.isEmpty());
1474 assertEquals(0, q.size());
1475 assertNull(q.peek());
1476 assertNull(q.poll());
1477 assertNull(q.poll(0, MILLISECONDS));
1478 assertEquals(q.toString(), "[]");
1479 assertTrue(Arrays.equals(q.toArray(), new Object[0]));
1480 assertFalse(q.iterator().hasNext());
1481 try {
1482 q.element();
1483 shouldThrow();
1484 } catch (NoSuchElementException success) {}
1485 try {
1486 q.iterator().next();
1487 shouldThrow();
1488 } catch (NoSuchElementException success) {}
1489 try {
1490 q.remove();
1491 shouldThrow();
1492 } catch (NoSuchElementException success) {}
1493 } catch (InterruptedException fail) { threadUnexpectedException(fail); }
1494 }
1495
1496 void assertSerialEquals(Object x, Object y) {
1497 assertTrue(Arrays.equals(serialBytes(x), serialBytes(y)));
1498 }
1499
1500 void assertNotSerialEquals(Object x, Object y) {
1501 assertFalse(Arrays.equals(serialBytes(x), serialBytes(y)));
1502 }
1503
1504 byte[] serialBytes(Object o) {
1505 try {
1506 ByteArrayOutputStream bos = new ByteArrayOutputStream();
1507 ObjectOutputStream oos = new ObjectOutputStream(bos);
1508 oos.writeObject(o);
1509 oos.flush();
1510 oos.close();
1511 return bos.toByteArray();
1512 } catch (Throwable fail) {
1513 threadUnexpectedException(fail);
1514 return new byte[0];
1515 }
1516 }
1517
1518 @SuppressWarnings("unchecked")
1519 <T> T serialClone(T o) {
1520 try {
1521 ObjectInputStream ois = new ObjectInputStream
1522 (new ByteArrayInputStream(serialBytes(o)));
1523 T clone = (T) ois.readObject();
1524 assertSame(o.getClass(), clone.getClass());
1525 return clone;
1526 } catch (Throwable fail) {
1527 threadUnexpectedException(fail);
1528 return null;
1529 }
1530 }
1531
1532 public void assertThrows(Class<? extends Throwable> expectedExceptionClass,
1533 Runnable... throwingActions) {
1534 for (Runnable throwingAction : throwingActions) {
1535 boolean threw = false;
1536 try { throwingAction.run(); }
1537 catch (Throwable t) {
1538 threw = true;
1539 if (!expectedExceptionClass.isInstance(t)) {
1540 AssertionFailedError afe =
1541 new AssertionFailedError
1542 ("Expected " + expectedExceptionClass.getName() +
1543 ", got " + t.getClass().getName());
1544 afe.initCause(t);
1545 threadUnexpectedException(afe);
1546 }
1547 }
1548 if (!threw)
1549 shouldThrow(expectedExceptionClass.getName());
1550 }
1551 }
1552
1553 public void assertIteratorExhausted(Iterator<?> it) {
1554 try {
1555 it.next();
1556 shouldThrow();
1557 } catch (NoSuchElementException success) {}
1558 assertFalse(it.hasNext());
1559 }
1560 }