blob: 46be906c0c080e69ecf19e23cb44bdd7e463bc9b [file] [log] [blame]
Calin Juravle8f0d92b2013-08-01 17:26:00 +01001/*
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
9package jsr166;
10
Narayan Kamath8e9a0e92015-04-28 11:40:00 +010011import static java.util.concurrent.TimeUnit.MILLISECONDS;
12import static java.util.concurrent.TimeUnit.NANOSECONDS;
13
Calin Juravle8f0d92b2013-08-01 17:26:00 +010014import java.io.ByteArrayInputStream;
15import java.io.ByteArrayOutputStream;
16import java.io.ObjectInputStream;
17import java.io.ObjectOutputStream;
18import java.lang.reflect.Method;
Calin Juravle8f0d92b2013-08-01 17:26:00 +010019import java.security.CodeSource;
20import java.security.Permission;
21import java.security.PermissionCollection;
22import java.security.Permissions;
23import java.security.Policy;
24import java.security.ProtectionDomain;
25import java.security.SecurityPermission;
Narayan Kamath8e9a0e92015-04-28 11:40:00 +010026import java.util.ArrayList;
27import java.util.Arrays;
28import java.util.Date;
29import java.util.Enumeration;
30import java.util.Iterator;
31import java.util.List;
32import java.util.NoSuchElementException;
33import java.util.PropertyPermission;
34import java.util.concurrent.BlockingQueue;
35import java.util.concurrent.Callable;
36import java.util.concurrent.CountDownLatch;
37import java.util.concurrent.CyclicBarrier;
38import java.util.concurrent.ExecutorService;
39import java.util.concurrent.Future;
40import java.util.concurrent.RecursiveAction;
41import java.util.concurrent.RecursiveTask;
42import java.util.concurrent.RejectedExecutionHandler;
43import java.util.concurrent.Semaphore;
44import java.util.concurrent.ThreadFactory;
45import java.util.concurrent.ThreadPoolExecutor;
46import java.util.concurrent.TimeoutException;
47import java.util.concurrent.atomic.AtomicReference;
48import java.util.regex.Pattern;
49
50import junit.framework.AssertionFailedError;
51import junit.framework.Test;
52import junit.framework.TestCase;
53import junit.framework.TestSuite;
Calin Juravle8f0d92b2013-08-01 17:26:00 +010054
55/**
56 * Base class for JSR166 Junit TCK tests. Defines some constants,
57 * utility methods and classes, as well as a simple framework for
58 * helping to make sure that assertions failing in generated threads
59 * cause the associated test that generated them to itself fail (which
60 * JUnit does not otherwise arrange). The rules for creating such
61 * tests are:
62 *
63 * <ol>
64 *
65 * <li> All assertions in code running in generated threads must use
66 * the forms {@link #threadFail}, {@link #threadAssertTrue}, {@link
67 * #threadAssertEquals}, or {@link #threadAssertNull}, (not
68 * {@code fail}, {@code assertTrue}, etc.) It is OK (but not
69 * particularly recommended) for other code to use these forms too.
70 * Only the most typically used JUnit assertion methods are defined
71 * this way, but enough to live with.</li>
72 *
73 * <li> If you override {@link #setUp} or {@link #tearDown}, make sure
74 * to invoke {@code super.setUp} and {@code super.tearDown} within
75 * them. These methods are used to clear and check for thread
76 * assertion failures.</li>
77 *
78 * <li>All delays and timeouts must use one of the constants {@code
79 * SHORT_DELAY_MS}, {@code SMALL_DELAY_MS}, {@code MEDIUM_DELAY_MS},
80 * {@code LONG_DELAY_MS}. The idea here is that a SHORT is always
81 * discriminable from zero time, and always allows enough time for the
82 * small amounts of computation (creating a thread, calling a few
83 * methods, etc) needed to reach a timeout point. Similarly, a SMALL
84 * is always discriminable as larger than SHORT and smaller than
85 * MEDIUM. And so on. These constants are set to conservative values,
86 * but even so, if there is ever any doubt, they can all be increased
87 * in one spot to rerun tests on slower platforms.</li>
88 *
89 * <li> All threads generated must be joined inside each test case
90 * method (or {@code fail} to do so) before returning from the
91 * method. The {@code joinPool} method can be used to do this when
92 * using Executors.</li>
93 *
94 * </ol>
95 *
96 * <p><b>Other notes</b>
97 * <ul>
98 *
99 * <li> Usually, there is one testcase method per JSR166 method
100 * covering "normal" operation, and then as many exception-testing
101 * methods as there are exceptions the method can throw. Sometimes
102 * there are multiple tests per JSR166 method when the different
103 * "normal" behaviors differ significantly. And sometimes testcases
104 * cover multiple methods when they cannot be tested in
105 * isolation.</li>
106 *
107 * <li> The documentation style for testcases is to provide as javadoc
108 * a simple sentence or two describing the property that the testcase
109 * method purports to test. The javadocs do not say anything about how
110 * the property is tested. To find out, read the code.</li>
111 *
112 * <li> These tests are "conformance tests", and do not attempt to
113 * test throughput, latency, scalability or other performance factors
114 * (see the separate "jtreg" tests for a set intended to check these
115 * for the most central aspects of functionality.) So, most tests use
116 * the smallest sensible numbers of threads, collection sizes, etc
117 * needed to check basic conformance.</li>
118 *
119 * <li>The test classes currently do not declare inclusion in
120 * any particular package to simplify things for people integrating
121 * them in TCK test suites.</li>
122 *
123 * <li> As a convenience, the {@code main} of this class (JSR166TestCase)
124 * runs all JSR166 unit tests.</li>
125 *
126 * </ul>
127 */
128public class JSR166TestCase extends TestCase {
Narayan Kamath8e9a0e92015-04-28 11:40:00 +0100129 // Delays for timing-dependent tests, in milliseconds.
Calin Juravle8f0d92b2013-08-01 17:26:00 +0100130
131 protected static final boolean expensiveTests = false;
132
133 public static long SHORT_DELAY_MS;
134 public static long SMALL_DELAY_MS;
135 public static long MEDIUM_DELAY_MS;
136 public static long LONG_DELAY_MS;
137
Calin Juravle8f0d92b2013-08-01 17:26:00 +0100138 /**
139 * Returns the shortest timed delay. This could
140 * be reimplemented to use for example a Property.
141 */
142 protected long getShortDelay() {
143 return 50;
144 }
145
146 /**
147 * Sets delays as multiples of SHORT_DELAY.
148 */
149 protected void setDelays() {
150 SHORT_DELAY_MS = getShortDelay();
151 SMALL_DELAY_MS = SHORT_DELAY_MS * 5;
152 MEDIUM_DELAY_MS = SHORT_DELAY_MS * 10;
153 LONG_DELAY_MS = SHORT_DELAY_MS * 200;
154 }
155
156 /**
157 * Returns a timeout in milliseconds to be used in tests that
158 * verify that operations block or time out.
159 */
160 long timeoutMillis() {
161 return SHORT_DELAY_MS / 4;
162 }
163
164 /**
165 * Returns a new Date instance representing a time delayMillis
166 * milliseconds in the future.
167 */
168 Date delayedDate(long delayMillis) {
169 return new Date(System.currentTimeMillis() + delayMillis);
170 }
171
172 /**
173 * The first exception encountered if any threadAssertXXX method fails.
174 */
175 private final AtomicReference<Throwable> threadFailure
176 = new AtomicReference<Throwable>(null);
177
178 /**
179 * Records an exception so that it can be rethrown later in the test
180 * harness thread, triggering a test case failure. Only the first
181 * failure is recorded; subsequent calls to this method from within
182 * the same test have no effect.
183 */
184 public void threadRecordFailure(Throwable t) {
185 threadFailure.compareAndSet(null, t);
186 }
187
188 public void setUp() {
189 setDelays();
190 }
191
192 /**
193 * Extra checks that get done for all test cases.
194 *
195 * Triggers test case failure if any thread assertions have failed,
196 * by rethrowing, in the test harness thread, any exception recorded
197 * earlier by threadRecordFailure.
198 *
199 * Triggers test case failure if interrupt status is set in the main thread.
200 */
201 public void tearDown() throws Exception {
202 Throwable t = threadFailure.getAndSet(null);
203 if (t != null) {
204 if (t instanceof Error)
205 throw (Error) t;
206 else if (t instanceof RuntimeException)
207 throw (RuntimeException) t;
208 else if (t instanceof Exception)
209 throw (Exception) t;
210 else {
211 AssertionFailedError afe =
212 new AssertionFailedError(t.toString());
213 afe.initCause(t);
214 throw afe;
215 }
216 }
217
218 if (Thread.interrupted())
219 throw new AssertionFailedError("interrupt status set in main thread");
220
221 checkForkJoinPoolThreadLeaks();
222 }
223
224 /**
Narayan Kamath8e9a0e92015-04-28 11:40:00 +0100225 * Finds missing try { ... } finally { joinPool(e); }
Calin Juravle8f0d92b2013-08-01 17:26:00 +0100226 */
227 void checkForkJoinPoolThreadLeaks() throws InterruptedException {
228 Thread[] survivors = new Thread[5];
229 int count = Thread.enumerate(survivors);
230 for (int i = 0; i < count; i++) {
231 Thread thread = survivors[i];
232 String name = thread.getName();
233 if (name.startsWith("ForkJoinPool-")) {
234 // give thread some time to terminate
235 thread.join(LONG_DELAY_MS);
236 if (!thread.isAlive()) continue;
237 thread.stop();
238 throw new AssertionFailedError
239 (String.format("Found leaked ForkJoinPool thread test=%s thread=%s%n",
240 toString(), name));
241 }
242 }
243 }
244
245 /**
246 * Just like fail(reason), but additionally recording (using
247 * threadRecordFailure) any AssertionFailedError thrown, so that
248 * the current testcase will fail.
249 */
250 public void threadFail(String reason) {
251 try {
252 fail(reason);
253 } catch (AssertionFailedError t) {
254 threadRecordFailure(t);
255 fail(reason);
256 }
257 }
258
259 /**
260 * Just like assertTrue(b), but additionally recording (using
261 * threadRecordFailure) any AssertionFailedError thrown, so that
262 * the current testcase will fail.
263 */
264 public void threadAssertTrue(boolean b) {
265 try {
266 assertTrue(b);
267 } catch (AssertionFailedError t) {
268 threadRecordFailure(t);
269 throw t;
270 }
271 }
272
273 /**
274 * Just like assertFalse(b), but additionally recording (using
275 * threadRecordFailure) any AssertionFailedError thrown, so that
276 * the current testcase will fail.
277 */
278 public void threadAssertFalse(boolean b) {
279 try {
280 assertFalse(b);
281 } catch (AssertionFailedError t) {
282 threadRecordFailure(t);
283 throw t;
284 }
285 }
286
287 /**
288 * Just like assertNull(x), but additionally recording (using
289 * threadRecordFailure) any AssertionFailedError thrown, so that
290 * the current testcase will fail.
291 */
292 public void threadAssertNull(Object x) {
293 try {
294 assertNull(x);
295 } catch (AssertionFailedError t) {
296 threadRecordFailure(t);
297 throw t;
298 }
299 }
300
301 /**
302 * Just like assertEquals(x, y), but additionally recording (using
303 * threadRecordFailure) any AssertionFailedError thrown, so that
304 * the current testcase will fail.
305 */
306 public void threadAssertEquals(long x, long y) {
307 try {
308 assertEquals(x, y);
309 } catch (AssertionFailedError t) {
310 threadRecordFailure(t);
311 throw t;
312 }
313 }
314
315 /**
316 * Just like assertEquals(x, y), but additionally recording (using
317 * threadRecordFailure) any AssertionFailedError thrown, so that
318 * the current testcase will fail.
319 */
320 public void threadAssertEquals(Object x, Object y) {
321 try {
322 assertEquals(x, y);
Narayan Kamath8e9a0e92015-04-28 11:40:00 +0100323 } catch (AssertionFailedError fail) {
324 threadRecordFailure(fail);
325 throw fail;
326 } catch (Throwable fail) {
327 threadUnexpectedException(fail);
Calin Juravle8f0d92b2013-08-01 17:26:00 +0100328 }
329 }
330
331 /**
332 * Just like assertSame(x, y), but additionally recording (using
333 * threadRecordFailure) any AssertionFailedError thrown, so that
334 * the current testcase will fail.
335 */
336 public void threadAssertSame(Object x, Object y) {
337 try {
338 assertSame(x, y);
Narayan Kamath8e9a0e92015-04-28 11:40:00 +0100339 } catch (AssertionFailedError fail) {
340 threadRecordFailure(fail);
341 throw fail;
Calin Juravle8f0d92b2013-08-01 17:26:00 +0100342 }
343 }
344
345 /**
346 * Calls threadFail with message "should throw exception".
347 */
348 public void threadShouldThrow() {
349 threadFail("should throw exception");
350 }
351
352 /**
353 * Calls threadFail with message "should throw" + exceptionName.
354 */
355 public void threadShouldThrow(String exceptionName) {
356 threadFail("should throw " + exceptionName);
357 }
358
359 /**
360 * Records the given exception using {@link #threadRecordFailure},
361 * then rethrows the exception, wrapping it in an
362 * AssertionFailedError if necessary.
363 */
364 public void threadUnexpectedException(Throwable t) {
365 threadRecordFailure(t);
366 t.printStackTrace();
367 if (t instanceof RuntimeException)
368 throw (RuntimeException) t;
369 else if (t instanceof Error)
370 throw (Error) t;
371 else {
372 AssertionFailedError afe =
373 new AssertionFailedError("unexpected exception: " + t);
374 afe.initCause(t);
375 throw afe;
376 }
377 }
378
379 /**
380 * Delays, via Thread.sleep, for the given millisecond delay, but
381 * if the sleep is shorter than specified, may re-sleep or yield
382 * until time elapses.
383 */
384 static void delay(long millis) throws InterruptedException {
385 long startTime = System.nanoTime();
386 long ns = millis * 1000 * 1000;
387 for (;;) {
388 if (millis > 0L)
389 Thread.sleep(millis);
390 else // too short to sleep
391 Thread.yield();
392 long d = ns - (System.nanoTime() - startTime);
393 if (d > 0L)
394 millis = d / (1000 * 1000);
395 else
396 break;
397 }
398 }
399
400 /**
401 * Waits out termination of a thread pool or fails doing so.
402 */
403 void joinPool(ExecutorService exec) {
404 try {
405 exec.shutdown();
Narayan Kamath8e9a0e92015-04-28 11:40:00 +0100406 if (!exec.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS))
407 fail("ExecutorService " + exec +
408 " did not terminate in a timely manner");
Calin Juravle8f0d92b2013-08-01 17:26:00 +0100409 } catch (SecurityException ok) {
410 // Allowed in case test doesn't have privs
Narayan Kamath8e9a0e92015-04-28 11:40:00 +0100411 } catch (InterruptedException fail) {
Calin Juravle8f0d92b2013-08-01 17:26:00 +0100412 fail("Unexpected InterruptedException");
413 }
414 }
415
416 /**
Narayan Kamath8e9a0e92015-04-28 11:40:00 +0100417 * A debugging tool to print all stack traces, as jstack does.
418 */
419 static void printAllStackTraces() {
420 }
421
422 /**
Calin Juravle8f0d92b2013-08-01 17:26:00 +0100423 * Checks that thread does not terminate within the default
424 * millisecond delay of {@code timeoutMillis()}.
425 */
426 void assertThreadStaysAlive(Thread thread) {
427 assertThreadStaysAlive(thread, timeoutMillis());
428 }
429
430 /**
431 * Checks that thread does not terminate within the given millisecond delay.
432 */
433 void assertThreadStaysAlive(Thread thread, long millis) {
434 try {
435 // No need to optimize the failing case via Thread.join.
436 delay(millis);
437 assertTrue(thread.isAlive());
Narayan Kamath8e9a0e92015-04-28 11:40:00 +0100438 } catch (InterruptedException fail) {
Calin Juravle8f0d92b2013-08-01 17:26:00 +0100439 fail("Unexpected InterruptedException");
440 }
441 }
442
443 /**
444 * Checks that the threads do not terminate within the default
445 * millisecond delay of {@code timeoutMillis()}.
446 */
447 void assertThreadsStayAlive(Thread... threads) {
448 assertThreadsStayAlive(timeoutMillis(), threads);
449 }
450
451 /**
452 * Checks that the threads do not terminate within the given millisecond delay.
453 */
454 void assertThreadsStayAlive(long millis, Thread... threads) {
455 try {
456 // No need to optimize the failing case via Thread.join.
457 delay(millis);
458 for (Thread thread : threads)
459 assertTrue(thread.isAlive());
Narayan Kamath8e9a0e92015-04-28 11:40:00 +0100460 } catch (InterruptedException fail) {
Calin Juravle8f0d92b2013-08-01 17:26:00 +0100461 fail("Unexpected InterruptedException");
462 }
463 }
464
465 /**
466 * Checks that future.get times out, with the default timeout of
467 * {@code timeoutMillis()}.
468 */
469 void assertFutureTimesOut(Future future) {
470 assertFutureTimesOut(future, timeoutMillis());
471 }
472
473 /**
474 * Checks that future.get times out, with the given millisecond timeout.
475 */
476 void assertFutureTimesOut(Future future, long timeoutMillis) {
477 long startTime = System.nanoTime();
478 try {
479 future.get(timeoutMillis, MILLISECONDS);
480 shouldThrow();
481 } catch (TimeoutException success) {
Narayan Kamath8e9a0e92015-04-28 11:40:00 +0100482 } catch (Exception fail) {
483 threadUnexpectedException(fail);
Calin Juravle8f0d92b2013-08-01 17:26:00 +0100484 } finally { future.cancel(true); }
485 assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
486 }
487
488 /**
489 * Fails with message "should throw exception".
490 */
491 public void shouldThrow() {
492 fail("Should throw exception");
493 }
494
495 /**
496 * Fails with message "should throw " + exceptionName.
497 */
498 public void shouldThrow(String exceptionName) {
499 fail("Should throw " + exceptionName);
500 }
501
502 /**
503 * The number of elements to place in collections, arrays, etc.
504 */
505 public static final int SIZE = 20;
506
507 // Some convenient Integer constants
508
509 public static final Integer zero = new Integer(0);
510 public static final Integer one = new Integer(1);
511 public static final Integer two = new Integer(2);
512 public static final Integer three = new Integer(3);
513 public static final Integer four = new Integer(4);
514 public static final Integer five = new Integer(5);
515 public static final Integer six = new Integer(6);
516 public static final Integer seven = new Integer(7);
517 public static final Integer eight = new Integer(8);
518 public static final Integer nine = new Integer(9);
519 public static final Integer m1 = new Integer(-1);
520 public static final Integer m2 = new Integer(-2);
521 public static final Integer m3 = new Integer(-3);
522 public static final Integer m4 = new Integer(-4);
523 public static final Integer m5 = new Integer(-5);
524 public static final Integer m6 = new Integer(-6);
525 public static final Integer m10 = new Integer(-10);
526
Calin Juravle8f0d92b2013-08-01 17:26:00 +0100527 /**
Narayan Kamath8e9a0e92015-04-28 11:40:00 +0100528 * Runs Runnable r with a security policy that permits precisely
529 * the specified permissions. If there is no current security
530 * manager, the runnable is run twice, both with and without a
531 * security manager. We require that any security manager permit
532 * getPolicy/setPolicy.
Calin Juravle8f0d92b2013-08-01 17:26:00 +0100533 */
534 public void runWithPermissions(Runnable r, Permission... permissions) {
Narayan Kamath05fd64a2015-04-30 10:36:15 +0100535 r.run();
Calin Juravle8f0d92b2013-08-01 17:26:00 +0100536 }
537
538 /**
Narayan Kamath8e9a0e92015-04-28 11:40:00 +0100539 * Runs Runnable r with a security policy that permits precisely
540 * the specified permissions. If there is no current security
541 * manager, a temporary one is set for the duration of the
542 * Runnable. We require that any security manager permit
543 * getPolicy/setPolicy.
Calin Juravle8f0d92b2013-08-01 17:26:00 +0100544 */
545 public void runWithSecurityManagerWithPermissions(Runnable r,
546 Permission... permissions) {
Narayan Kamath05fd64a2015-04-30 10:36:15 +0100547 r.run();
Calin Juravle8f0d92b2013-08-01 17:26:00 +0100548 }
549
550 /**
551 * Runs a runnable without any permissions.
552 */
553 public void runWithoutPermissions(Runnable r) {
554 runWithPermissions(r);
555 }
556
557 /**
558 * A security policy where new permissions can be dynamically added
559 * or all cleared.
560 */
561 public static class AdjustablePolicy extends java.security.Policy {
562 Permissions perms = new Permissions();
563 AdjustablePolicy(Permission... permissions) {
564 for (Permission permission : permissions)
565 perms.add(permission);
566 }
567 void addPermission(Permission perm) { perms.add(perm); }
568 void clearPermissions() { perms = new Permissions(); }
569 public PermissionCollection getPermissions(CodeSource cs) {
570 return perms;
571 }
572 public PermissionCollection getPermissions(ProtectionDomain pd) {
573 return perms;
574 }
575 public boolean implies(ProtectionDomain pd, Permission p) {
576 return perms.implies(p);
577 }
578 public void refresh() {}
579 public String toString() {
580 List<Permission> ps = new ArrayList<Permission>();
581 for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
582 ps.add(e.nextElement());
583 return "AdjustablePolicy with permissions " + ps;
584 }
585 }
586
587 /**
588 * Returns a policy containing all the permissions we ever need.
589 */
590 public static Policy permissivePolicy() {
591 return new AdjustablePolicy
592 // Permissions j.u.c. needs directly
593 (new RuntimePermission("modifyThread"),
594 new RuntimePermission("getClassLoader"),
595 new RuntimePermission("setContextClassLoader"),
596 // Permissions needed to change permissions!
597 new SecurityPermission("getPolicy"),
598 new SecurityPermission("setPolicy"),
599 new RuntimePermission("setSecurityManager"),
600 // Permissions needed by the junit test harness
601 new RuntimePermission("accessDeclaredMembers"),
602 new PropertyPermission("*", "read"),
603 new java.io.FilePermission("<<ALL FILES>>", "read"));
604 }
605
606 /**
607 * Sleeps until the given time has elapsed.
608 * Throws AssertionFailedError if interrupted.
609 */
610 void sleep(long millis) {
611 try {
612 delay(millis);
Narayan Kamath8e9a0e92015-04-28 11:40:00 +0100613 } catch (InterruptedException fail) {
Calin Juravle8f0d92b2013-08-01 17:26:00 +0100614 AssertionFailedError afe =
615 new AssertionFailedError("Unexpected InterruptedException");
Narayan Kamath8e9a0e92015-04-28 11:40:00 +0100616 afe.initCause(fail);
Calin Juravle8f0d92b2013-08-01 17:26:00 +0100617 throw afe;
618 }
619 }
620
621 /**
622 * Spin-waits up to the specified number of milliseconds for the given
623 * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
624 */
625 void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
626 long startTime = System.nanoTime();
627 for (;;) {
628 Thread.State s = thread.getState();
629 if (s == Thread.State.BLOCKED ||
630 s == Thread.State.WAITING ||
631 s == Thread.State.TIMED_WAITING)
632 return;
633 else if (s == Thread.State.TERMINATED)
634 fail("Unexpected thread termination");
635 else if (millisElapsedSince(startTime) > timeoutMillis) {
636 threadAssertTrue(thread.isAlive());
637 return;
638 }
639 Thread.yield();
640 }
641 }
642
643 /**
644 * Waits up to LONG_DELAY_MS for the given thread to enter a wait
645 * state: BLOCKED, WAITING, or TIMED_WAITING.
646 */
647 void waitForThreadToEnterWaitState(Thread thread) {
648 waitForThreadToEnterWaitState(thread, LONG_DELAY_MS);
649 }
650
Hiroshi Yamauchi12b0b5b2016-01-05 17:53:01 -0800651 void waitForThreadToEnterWaitStateNoTimeout(Thread thread) {
652 for (;;) {
653 Thread.State s = thread.getState();
654 if (s == Thread.State.BLOCKED ||
655 s == Thread.State.WAITING ||
656 s == Thread.State.TIMED_WAITING)
657 return;
658 else if (s == Thread.State.TERMINATED)
659 fail("Unexpected thread termination");
660 Thread.yield();
661 }
662 }
663
Calin Juravle8f0d92b2013-08-01 17:26:00 +0100664 /**
665 * Returns the number of milliseconds since time given by
666 * startNanoTime, which must have been previously returned from a
Narayan Kamath8e9a0e92015-04-28 11:40:00 +0100667 * call to {@link System#nanoTime()}.
Calin Juravle8f0d92b2013-08-01 17:26:00 +0100668 */
Narayan Kamath8e9a0e92015-04-28 11:40:00 +0100669 static long millisElapsedSince(long startNanoTime) {
Calin Juravle8f0d92b2013-08-01 17:26:00 +0100670 return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
671 }
672
Narayan Kamath8e9a0e92015-04-28 11:40:00 +0100673// void assertTerminatesPromptly(long timeoutMillis, Runnable r) {
674// long startTime = System.nanoTime();
675// try {
676// r.run();
677// } catch (Throwable fail) { threadUnexpectedException(fail); }
678// if (millisElapsedSince(startTime) > timeoutMillis/2)
679// throw new AssertionFailedError("did not return promptly");
680// }
681
682// void assertTerminatesPromptly(Runnable r) {
683// assertTerminatesPromptly(LONG_DELAY_MS/2, r);
684// }
685
686 /**
687 * Checks that timed f.get() returns the expected value, and does not
688 * wait for the timeout to elapse before returning.
689 */
690 <T> void checkTimedGet(Future<T> f, T expectedValue, long timeoutMillis) {
691 long startTime = System.nanoTime();
692 try {
693 assertEquals(expectedValue, f.get(timeoutMillis, MILLISECONDS));
694 } catch (Throwable fail) { threadUnexpectedException(fail); }
695 if (millisElapsedSince(startTime) > timeoutMillis/2)
696 throw new AssertionFailedError("timed get did not return promptly");
697 }
698
699 <T> void checkTimedGet(Future<T> f, T expectedValue) {
700 checkTimedGet(f, expectedValue, LONG_DELAY_MS);
701 }
702
Calin Juravle8f0d92b2013-08-01 17:26:00 +0100703 /**
704 * Returns a new started daemon Thread running the given runnable.
705 */
706 Thread newStartedThread(Runnable runnable) {
707 Thread t = new Thread(runnable);
708 t.setDaemon(true);
709 t.start();
710 return t;
711 }
712
713 /**
714 * Waits for the specified time (in milliseconds) for the thread
715 * to terminate (using {@link Thread#join(long)}), else interrupts
716 * the thread (in the hope that it may terminate later) and fails.
717 */
718 void awaitTermination(Thread t, long timeoutMillis) {
719 try {
720 t.join(timeoutMillis);
Narayan Kamath8e9a0e92015-04-28 11:40:00 +0100721 } catch (InterruptedException fail) {
722 threadUnexpectedException(fail);
Calin Juravle8f0d92b2013-08-01 17:26:00 +0100723 } finally {
724 if (t.getState() != Thread.State.TERMINATED) {
725 t.interrupt();
726 fail("Test timed out");
727 }
728 }
729 }
730
731 /**
732 * Waits for LONG_DELAY_MS milliseconds for the thread to
733 * terminate (using {@link Thread#join(long)}), else interrupts
734 * the thread (in the hope that it may terminate later) and fails.
735 */
736 void awaitTermination(Thread t) {
737 awaitTermination(t, LONG_DELAY_MS);
738 }
739
740 // Some convenient Runnable classes
741
742 public abstract class CheckedRunnable implements Runnable {
743 protected abstract void realRun() throws Throwable;
744
745 public final void run() {
746 try {
747 realRun();
Narayan Kamath8e9a0e92015-04-28 11:40:00 +0100748 } catch (Throwable fail) {
749 threadUnexpectedException(fail);
Calin Juravle8f0d92b2013-08-01 17:26:00 +0100750 }
751 }
752 }
753
754 public abstract class RunnableShouldThrow implements Runnable {
755 protected abstract void realRun() throws Throwable;
756
757 final Class<?> exceptionClass;
758
759 <T extends Throwable> RunnableShouldThrow(Class<T> exceptionClass) {
760 this.exceptionClass = exceptionClass;
761 }
762
763 public final void run() {
764 try {
765 realRun();
766 threadShouldThrow(exceptionClass.getSimpleName());
767 } catch (Throwable t) {
768 if (! exceptionClass.isInstance(t))
769 threadUnexpectedException(t);
770 }
771 }
772 }
773
774 public abstract class ThreadShouldThrow extends Thread {
775 protected abstract void realRun() throws Throwable;
776
777 final Class<?> exceptionClass;
778
779 <T extends Throwable> ThreadShouldThrow(Class<T> exceptionClass) {
780 this.exceptionClass = exceptionClass;
781 }
782
783 public final void run() {
784 try {
785 realRun();
786 threadShouldThrow(exceptionClass.getSimpleName());
787 } catch (Throwable t) {
788 if (! exceptionClass.isInstance(t))
789 threadUnexpectedException(t);
790 }
791 }
792 }
793
794 public abstract class CheckedInterruptedRunnable implements Runnable {
795 protected abstract void realRun() throws Throwable;
796
797 public final void run() {
798 try {
799 realRun();
800 threadShouldThrow("InterruptedException");
801 } catch (InterruptedException success) {
802 threadAssertFalse(Thread.interrupted());
Narayan Kamath8e9a0e92015-04-28 11:40:00 +0100803 } catch (Throwable fail) {
804 threadUnexpectedException(fail);
Calin Juravle8f0d92b2013-08-01 17:26:00 +0100805 }
806 }
807 }
808
809 public abstract class CheckedCallable<T> implements Callable<T> {
810 protected abstract T realCall() throws Throwable;
811
812 public final T call() {
813 try {
814 return realCall();
Narayan Kamath8e9a0e92015-04-28 11:40:00 +0100815 } catch (Throwable fail) {
816 threadUnexpectedException(fail);
Calin Juravle8f0d92b2013-08-01 17:26:00 +0100817 return null;
818 }
819 }
820 }
821
822 public abstract class CheckedInterruptedCallable<T>
823 implements Callable<T> {
824 protected abstract T realCall() throws Throwable;
825
826 public final T call() {
827 try {
828 T result = realCall();
829 threadShouldThrow("InterruptedException");
830 return result;
831 } catch (InterruptedException success) {
832 threadAssertFalse(Thread.interrupted());
Narayan Kamath8e9a0e92015-04-28 11:40:00 +0100833 } catch (Throwable fail) {
834 threadUnexpectedException(fail);
Calin Juravle8f0d92b2013-08-01 17:26:00 +0100835 }
836 return null;
837 }
838 }
839
840 public static class NoOpRunnable implements Runnable {
841 public void run() {}
842 }
843
844 public static class NoOpCallable implements Callable {
845 public Object call() { return Boolean.TRUE; }
846 }
847
848 public static final String TEST_STRING = "a test string";
849
850 public static class StringTask implements Callable<String> {
851 public String call() { return TEST_STRING; }
852 }
853
854 public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) {
855 return new CheckedCallable<String>() {
856 protected String realCall() {
857 try {
858 latch.await();
859 } catch (InterruptedException quittingTime) {}
860 return TEST_STRING;
861 }};
862 }
863
864 public Runnable awaiter(final CountDownLatch latch) {
865 return new CheckedRunnable() {
866 public void realRun() throws InterruptedException {
867 await(latch);
868 }};
869 }
870
871 public void await(CountDownLatch latch) {
872 try {
873 assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
Narayan Kamath8e9a0e92015-04-28 11:40:00 +0100874 } catch (Throwable fail) {
875 threadUnexpectedException(fail);
Calin Juravle8f0d92b2013-08-01 17:26:00 +0100876 }
877 }
878
879 public void await(Semaphore semaphore) {
880 try {
881 assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
Narayan Kamath8e9a0e92015-04-28 11:40:00 +0100882 } catch (Throwable fail) {
883 threadUnexpectedException(fail);
Calin Juravle8f0d92b2013-08-01 17:26:00 +0100884 }
885 }
886
887// /**
888// * Spin-waits up to LONG_DELAY_MS until flag becomes true.
889// */
890// public void await(AtomicBoolean flag) {
891// await(flag, LONG_DELAY_MS);
892// }
893
894// /**
895// * Spin-waits up to the specified timeout until flag becomes true.
896// */
897// public void await(AtomicBoolean flag, long timeoutMillis) {
898// long startTime = System.nanoTime();
899// while (!flag.get()) {
900// if (millisElapsedSince(startTime) > timeoutMillis)
901// throw new AssertionFailedError("timed out");
902// Thread.yield();
903// }
904// }
905
906 public static class NPETask implements Callable<String> {
907 public String call() { throw new NullPointerException(); }
908 }
909
910 public static class CallableOne implements Callable<Integer> {
911 public Integer call() { return one; }
912 }
913
914 public class ShortRunnable extends CheckedRunnable {
915 protected void realRun() throws Throwable {
916 delay(SHORT_DELAY_MS);
917 }
918 }
919
920 public class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
921 protected void realRun() throws InterruptedException {
922 delay(SHORT_DELAY_MS);
923 }
924 }
925
926 public class SmallRunnable extends CheckedRunnable {
927 protected void realRun() throws Throwable {
928 delay(SMALL_DELAY_MS);
929 }
930 }
931
932 public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
933 protected void realRun() {
934 try {
935 delay(SMALL_DELAY_MS);
936 } catch (InterruptedException ok) {}
937 }
938 }
939
940 public class SmallCallable extends CheckedCallable {
941 protected Object realCall() throws InterruptedException {
942 delay(SMALL_DELAY_MS);
943 return Boolean.TRUE;
944 }
945 }
946
947 public class MediumRunnable extends CheckedRunnable {
948 protected void realRun() throws Throwable {
949 delay(MEDIUM_DELAY_MS);
950 }
951 }
952
953 public class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
954 protected void realRun() throws InterruptedException {
955 delay(MEDIUM_DELAY_MS);
956 }
957 }
958
959 public Runnable possiblyInterruptedRunnable(final long timeoutMillis) {
960 return new CheckedRunnable() {
961 protected void realRun() {
962 try {
963 delay(timeoutMillis);
964 } catch (InterruptedException ok) {}
965 }};
966 }
967
968 public class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
969 protected void realRun() {
970 try {
971 delay(MEDIUM_DELAY_MS);
972 } catch (InterruptedException ok) {}
973 }
974 }
975
976 public class LongPossiblyInterruptedRunnable extends CheckedRunnable {
977 protected void realRun() {
978 try {
979 delay(LONG_DELAY_MS);
980 } catch (InterruptedException ok) {}
981 }
982 }
983
984 /**
985 * For use as ThreadFactory in constructors
986 */
987 public static class SimpleThreadFactory implements ThreadFactory {
988 public Thread newThread(Runnable r) {
989 return new Thread(r);
990 }
991 }
992
993 public interface TrackedRunnable extends Runnable {
994 boolean isDone();
995 }
996
997 public static TrackedRunnable trackedRunnable(final long timeoutMillis) {
998 return new TrackedRunnable() {
999 private volatile boolean done = false;
1000 public boolean isDone() { return done; }
1001 public void run() {
1002 try {
1003 delay(timeoutMillis);
1004 done = true;
1005 } catch (InterruptedException ok) {}
1006 }
1007 };
1008 }
1009
1010 public static class TrackedShortRunnable implements Runnable {
1011 public volatile boolean done = false;
1012 public void run() {
1013 try {
1014 delay(SHORT_DELAY_MS);
1015 done = true;
1016 } catch (InterruptedException ok) {}
1017 }
1018 }
1019
1020 public static class TrackedSmallRunnable implements Runnable {
1021 public volatile boolean done = false;
1022 public void run() {
1023 try {
1024 delay(SMALL_DELAY_MS);
1025 done = true;
1026 } catch (InterruptedException ok) {}
1027 }
1028 }
1029
1030 public static class TrackedMediumRunnable implements Runnable {
1031 public volatile boolean done = false;
1032 public void run() {
1033 try {
1034 delay(MEDIUM_DELAY_MS);
1035 done = true;
1036 } catch (InterruptedException ok) {}
1037 }
1038 }
1039
1040 public static class TrackedLongRunnable implements Runnable {
1041 public volatile boolean done = false;
1042 public void run() {
1043 try {
1044 delay(LONG_DELAY_MS);
1045 done = true;
1046 } catch (InterruptedException ok) {}
1047 }
1048 }
1049
1050 public static class TrackedNoOpRunnable implements Runnable {
1051 public volatile boolean done = false;
1052 public void run() {
1053 done = true;
1054 }
1055 }
1056
1057 public static class TrackedCallable implements Callable {
1058 public volatile boolean done = false;
1059 public Object call() {
1060 try {
1061 delay(SMALL_DELAY_MS);
1062 done = true;
1063 } catch (InterruptedException ok) {}
1064 return Boolean.TRUE;
1065 }
1066 }
1067
1068 /**
1069 * Analog of CheckedRunnable for RecursiveAction
1070 */
1071 public abstract class CheckedRecursiveAction extends RecursiveAction {
1072 protected abstract void realCompute() throws Throwable;
1073
1074 @Override protected final void compute() {
1075 try {
1076 realCompute();
Narayan Kamath8e9a0e92015-04-28 11:40:00 +01001077 } catch (Throwable fail) {
1078 threadUnexpectedException(fail);
Calin Juravle8f0d92b2013-08-01 17:26:00 +01001079 }
1080 }
1081 }
1082
1083 /**
1084 * Analog of CheckedCallable for RecursiveTask
1085 */
1086 public abstract class CheckedRecursiveTask<T> extends RecursiveTask<T> {
1087 protected abstract T realCompute() throws Throwable;
1088
1089 @Override protected final T compute() {
1090 try {
1091 return realCompute();
Narayan Kamath8e9a0e92015-04-28 11:40:00 +01001092 } catch (Throwable fail) {
1093 threadUnexpectedException(fail);
Calin Juravle8f0d92b2013-08-01 17:26:00 +01001094 return null;
1095 }
1096 }
1097 }
1098
1099 /**
1100 * For use as RejectedExecutionHandler in constructors
1101 */
1102 public static class NoOpREHandler implements RejectedExecutionHandler {
1103 public void rejectedExecution(Runnable r,
1104 ThreadPoolExecutor executor) {}
1105 }
1106
1107 /**
1108 * A CyclicBarrier that uses timed await and fails with
1109 * AssertionFailedErrors instead of throwing checked exceptions.
1110 */
1111 public class CheckedBarrier extends CyclicBarrier {
1112 public CheckedBarrier(int parties) { super(parties); }
1113
1114 public int await() {
1115 try {
1116 return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
Narayan Kamath8e9a0e92015-04-28 11:40:00 +01001117 } catch (TimeoutException timedOut) {
Calin Juravle8f0d92b2013-08-01 17:26:00 +01001118 throw new AssertionFailedError("timed out");
Narayan Kamath8e9a0e92015-04-28 11:40:00 +01001119 } catch (Exception fail) {
Calin Juravle8f0d92b2013-08-01 17:26:00 +01001120 AssertionFailedError afe =
Narayan Kamath8e9a0e92015-04-28 11:40:00 +01001121 new AssertionFailedError("Unexpected exception: " + fail);
1122 afe.initCause(fail);
Calin Juravle8f0d92b2013-08-01 17:26:00 +01001123 throw afe;
1124 }
1125 }
1126 }
1127
1128 void checkEmpty(BlockingQueue q) {
1129 try {
1130 assertTrue(q.isEmpty());
1131 assertEquals(0, q.size());
1132 assertNull(q.peek());
1133 assertNull(q.poll());
1134 assertNull(q.poll(0, MILLISECONDS));
1135 assertEquals(q.toString(), "[]");
1136 assertTrue(Arrays.equals(q.toArray(), new Object[0]));
1137 assertFalse(q.iterator().hasNext());
1138 try {
1139 q.element();
1140 shouldThrow();
1141 } catch (NoSuchElementException success) {}
1142 try {
1143 q.iterator().next();
1144 shouldThrow();
1145 } catch (NoSuchElementException success) {}
1146 try {
1147 q.remove();
1148 shouldThrow();
1149 } catch (NoSuchElementException success) {}
Narayan Kamath8e9a0e92015-04-28 11:40:00 +01001150 } catch (InterruptedException fail) { threadUnexpectedException(fail); }
Calin Juravle8f0d92b2013-08-01 17:26:00 +01001151 }
1152
1153 void assertSerialEquals(Object x, Object y) {
1154 assertTrue(Arrays.equals(serialBytes(x), serialBytes(y)));
1155 }
1156
1157 void assertNotSerialEquals(Object x, Object y) {
1158 assertFalse(Arrays.equals(serialBytes(x), serialBytes(y)));
1159 }
1160
1161 byte[] serialBytes(Object o) {
1162 try {
1163 ByteArrayOutputStream bos = new ByteArrayOutputStream();
1164 ObjectOutputStream oos = new ObjectOutputStream(bos);
1165 oos.writeObject(o);
1166 oos.flush();
1167 oos.close();
1168 return bos.toByteArray();
Narayan Kamath8e9a0e92015-04-28 11:40:00 +01001169 } catch (Throwable fail) {
1170 threadUnexpectedException(fail);
Calin Juravle8f0d92b2013-08-01 17:26:00 +01001171 return new byte[0];
1172 }
1173 }
1174
1175 @SuppressWarnings("unchecked")
1176 <T> T serialClone(T o) {
1177 try {
1178 ObjectInputStream ois = new ObjectInputStream
1179 (new ByteArrayInputStream(serialBytes(o)));
1180 T clone = (T) ois.readObject();
1181 assertSame(o.getClass(), clone.getClass());
1182 return clone;
Narayan Kamath8e9a0e92015-04-28 11:40:00 +01001183 } catch (Throwable fail) {
1184 threadUnexpectedException(fail);
Calin Juravle8f0d92b2013-08-01 17:26:00 +01001185 return null;
1186 }
1187 }
1188
1189 public void assertThrows(Class<? extends Throwable> expectedExceptionClass,
1190 Runnable... throwingActions) {
1191 for (Runnable throwingAction : throwingActions) {
1192 boolean threw = false;
1193 try { throwingAction.run(); }
1194 catch (Throwable t) {
1195 threw = true;
1196 if (!expectedExceptionClass.isInstance(t)) {
1197 AssertionFailedError afe =
1198 new AssertionFailedError
1199 ("Expected " + expectedExceptionClass.getName() +
1200 ", got " + t.getClass().getName());
1201 afe.initCause(t);
1202 threadUnexpectedException(afe);
1203 }
1204 }
1205 if (!threw)
1206 shouldThrow(expectedExceptionClass.getName());
1207 }
1208 }
Narayan Kamath8e9a0e92015-04-28 11:40:00 +01001209
1210 public void assertIteratorExhausted(Iterator<?> it) {
1211 try {
1212 it.next();
1213 shouldThrow();
1214 } catch (NoSuchElementException success) {}
1215 assertFalse(it.hasNext());
1216 }
Calin Juravle8f0d92b2013-08-01 17:26:00 +01001217}