blob: d07d936f672279a24e0b739f0020ebfb1ad164ab [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 Kamath8e9a0e92015-04-28 11:40:00 +0100535 SecurityManager sm = System.getSecurityManager();
536 if (sm == null) {
537 r.run();
538 }
539 runWithSecurityManagerWithPermissions(r, permissions);
Calin Juravle8f0d92b2013-08-01 17:26:00 +0100540 }
541
542 /**
Narayan Kamath8e9a0e92015-04-28 11:40:00 +0100543 * Runs Runnable r with a security policy that permits precisely
544 * the specified permissions. If there is no current security
545 * manager, a temporary one is set for the duration of the
546 * Runnable. We require that any security manager permit
547 * getPolicy/setPolicy.
Calin Juravle8f0d92b2013-08-01 17:26:00 +0100548 */
549 public void runWithSecurityManagerWithPermissions(Runnable r,
550 Permission... permissions) {
Narayan Kamath8e9a0e92015-04-28 11:40:00 +0100551 SecurityManager sm = System.getSecurityManager();
552 if (sm == null) {
553 Policy savedPolicy = Policy.getPolicy();
554 try {
555 Policy.setPolicy(permissivePolicy());
556 System.setSecurityManager(new SecurityManager());
557 runWithSecurityManagerWithPermissions(r, permissions);
558 } finally {
559 System.setSecurityManager(null);
560 Policy.setPolicy(savedPolicy);
561 }
562 } else {
563 Policy savedPolicy = Policy.getPolicy();
564 AdjustablePolicy policy = new AdjustablePolicy(permissions);
565 Policy.setPolicy(policy);
566
567 try {
568 r.run();
569 } finally {
570 policy.addPermission(new SecurityPermission("setPolicy"));
571 Policy.setPolicy(savedPolicy);
572 }
573 }
Calin Juravle8f0d92b2013-08-01 17:26:00 +0100574 }
575
576 /**
577 * Runs a runnable without any permissions.
578 */
579 public void runWithoutPermissions(Runnable r) {
580 runWithPermissions(r);
581 }
582
583 /**
584 * A security policy where new permissions can be dynamically added
585 * or all cleared.
586 */
587 public static class AdjustablePolicy extends java.security.Policy {
588 Permissions perms = new Permissions();
589 AdjustablePolicy(Permission... permissions) {
590 for (Permission permission : permissions)
591 perms.add(permission);
592 }
593 void addPermission(Permission perm) { perms.add(perm); }
594 void clearPermissions() { perms = new Permissions(); }
595 public PermissionCollection getPermissions(CodeSource cs) {
596 return perms;
597 }
598 public PermissionCollection getPermissions(ProtectionDomain pd) {
599 return perms;
600 }
601 public boolean implies(ProtectionDomain pd, Permission p) {
602 return perms.implies(p);
603 }
604 public void refresh() {}
605 public String toString() {
606 List<Permission> ps = new ArrayList<Permission>();
607 for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
608 ps.add(e.nextElement());
609 return "AdjustablePolicy with permissions " + ps;
610 }
611 }
612
613 /**
614 * Returns a policy containing all the permissions we ever need.
615 */
616 public static Policy permissivePolicy() {
617 return new AdjustablePolicy
618 // Permissions j.u.c. needs directly
619 (new RuntimePermission("modifyThread"),
620 new RuntimePermission("getClassLoader"),
621 new RuntimePermission("setContextClassLoader"),
622 // Permissions needed to change permissions!
623 new SecurityPermission("getPolicy"),
624 new SecurityPermission("setPolicy"),
625 new RuntimePermission("setSecurityManager"),
626 // Permissions needed by the junit test harness
627 new RuntimePermission("accessDeclaredMembers"),
628 new PropertyPermission("*", "read"),
629 new java.io.FilePermission("<<ALL FILES>>", "read"));
630 }
631
632 /**
633 * Sleeps until the given time has elapsed.
634 * Throws AssertionFailedError if interrupted.
635 */
636 void sleep(long millis) {
637 try {
638 delay(millis);
Narayan Kamath8e9a0e92015-04-28 11:40:00 +0100639 } catch (InterruptedException fail) {
Calin Juravle8f0d92b2013-08-01 17:26:00 +0100640 AssertionFailedError afe =
641 new AssertionFailedError("Unexpected InterruptedException");
Narayan Kamath8e9a0e92015-04-28 11:40:00 +0100642 afe.initCause(fail);
Calin Juravle8f0d92b2013-08-01 17:26:00 +0100643 throw afe;
644 }
645 }
646
647 /**
648 * Spin-waits up to the specified number of milliseconds for the given
649 * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
650 */
651 void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
652 long startTime = System.nanoTime();
653 for (;;) {
654 Thread.State s = thread.getState();
655 if (s == Thread.State.BLOCKED ||
656 s == Thread.State.WAITING ||
657 s == Thread.State.TIMED_WAITING)
658 return;
659 else if (s == Thread.State.TERMINATED)
660 fail("Unexpected thread termination");
661 else if (millisElapsedSince(startTime) > timeoutMillis) {
662 threadAssertTrue(thread.isAlive());
663 return;
664 }
665 Thread.yield();
666 }
667 }
668
669 /**
670 * Waits up to LONG_DELAY_MS for the given thread to enter a wait
671 * state: BLOCKED, WAITING, or TIMED_WAITING.
672 */
673 void waitForThreadToEnterWaitState(Thread thread) {
674 waitForThreadToEnterWaitState(thread, LONG_DELAY_MS);
675 }
676
677 /**
678 * Returns the number of milliseconds since time given by
679 * startNanoTime, which must have been previously returned from a
Narayan Kamath8e9a0e92015-04-28 11:40:00 +0100680 * call to {@link System#nanoTime()}.
Calin Juravle8f0d92b2013-08-01 17:26:00 +0100681 */
Narayan Kamath8e9a0e92015-04-28 11:40:00 +0100682 static long millisElapsedSince(long startNanoTime) {
Calin Juravle8f0d92b2013-08-01 17:26:00 +0100683 return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
684 }
685
Narayan Kamath8e9a0e92015-04-28 11:40:00 +0100686// void assertTerminatesPromptly(long timeoutMillis, Runnable r) {
687// long startTime = System.nanoTime();
688// try {
689// r.run();
690// } catch (Throwable fail) { threadUnexpectedException(fail); }
691// if (millisElapsedSince(startTime) > timeoutMillis/2)
692// throw new AssertionFailedError("did not return promptly");
693// }
694
695// void assertTerminatesPromptly(Runnable r) {
696// assertTerminatesPromptly(LONG_DELAY_MS/2, r);
697// }
698
699 /**
700 * Checks that timed f.get() returns the expected value, and does not
701 * wait for the timeout to elapse before returning.
702 */
703 <T> void checkTimedGet(Future<T> f, T expectedValue, long timeoutMillis) {
704 long startTime = System.nanoTime();
705 try {
706 assertEquals(expectedValue, f.get(timeoutMillis, MILLISECONDS));
707 } catch (Throwable fail) { threadUnexpectedException(fail); }
708 if (millisElapsedSince(startTime) > timeoutMillis/2)
709 throw new AssertionFailedError("timed get did not return promptly");
710 }
711
712 <T> void checkTimedGet(Future<T> f, T expectedValue) {
713 checkTimedGet(f, expectedValue, LONG_DELAY_MS);
714 }
715
Calin Juravle8f0d92b2013-08-01 17:26:00 +0100716 /**
717 * Returns a new started daemon Thread running the given runnable.
718 */
719 Thread newStartedThread(Runnable runnable) {
720 Thread t = new Thread(runnable);
721 t.setDaemon(true);
722 t.start();
723 return t;
724 }
725
726 /**
727 * Waits for the specified time (in milliseconds) for the thread
728 * to terminate (using {@link Thread#join(long)}), else interrupts
729 * the thread (in the hope that it may terminate later) and fails.
730 */
731 void awaitTermination(Thread t, long timeoutMillis) {
732 try {
733 t.join(timeoutMillis);
Narayan Kamath8e9a0e92015-04-28 11:40:00 +0100734 } catch (InterruptedException fail) {
735 threadUnexpectedException(fail);
Calin Juravle8f0d92b2013-08-01 17:26:00 +0100736 } finally {
737 if (t.getState() != Thread.State.TERMINATED) {
738 t.interrupt();
739 fail("Test timed out");
740 }
741 }
742 }
743
744 /**
745 * Waits for LONG_DELAY_MS milliseconds for the thread to
746 * terminate (using {@link Thread#join(long)}), else interrupts
747 * the thread (in the hope that it may terminate later) and fails.
748 */
749 void awaitTermination(Thread t) {
750 awaitTermination(t, LONG_DELAY_MS);
751 }
752
753 // Some convenient Runnable classes
754
755 public abstract class CheckedRunnable implements Runnable {
756 protected abstract void realRun() throws Throwable;
757
758 public final void run() {
759 try {
760 realRun();
Narayan Kamath8e9a0e92015-04-28 11:40:00 +0100761 } catch (Throwable fail) {
762 threadUnexpectedException(fail);
Calin Juravle8f0d92b2013-08-01 17:26:00 +0100763 }
764 }
765 }
766
767 public abstract class RunnableShouldThrow implements Runnable {
768 protected abstract void realRun() throws Throwable;
769
770 final Class<?> exceptionClass;
771
772 <T extends Throwable> RunnableShouldThrow(Class<T> exceptionClass) {
773 this.exceptionClass = exceptionClass;
774 }
775
776 public final void run() {
777 try {
778 realRun();
779 threadShouldThrow(exceptionClass.getSimpleName());
780 } catch (Throwable t) {
781 if (! exceptionClass.isInstance(t))
782 threadUnexpectedException(t);
783 }
784 }
785 }
786
787 public abstract class ThreadShouldThrow extends Thread {
788 protected abstract void realRun() throws Throwable;
789
790 final Class<?> exceptionClass;
791
792 <T extends Throwable> ThreadShouldThrow(Class<T> exceptionClass) {
793 this.exceptionClass = exceptionClass;
794 }
795
796 public final void run() {
797 try {
798 realRun();
799 threadShouldThrow(exceptionClass.getSimpleName());
800 } catch (Throwable t) {
801 if (! exceptionClass.isInstance(t))
802 threadUnexpectedException(t);
803 }
804 }
805 }
806
807 public abstract class CheckedInterruptedRunnable implements Runnable {
808 protected abstract void realRun() throws Throwable;
809
810 public final void run() {
811 try {
812 realRun();
813 threadShouldThrow("InterruptedException");
814 } catch (InterruptedException success) {
815 threadAssertFalse(Thread.interrupted());
Narayan Kamath8e9a0e92015-04-28 11:40:00 +0100816 } catch (Throwable fail) {
817 threadUnexpectedException(fail);
Calin Juravle8f0d92b2013-08-01 17:26:00 +0100818 }
819 }
820 }
821
822 public abstract class CheckedCallable<T> implements Callable<T> {
823 protected abstract T realCall() throws Throwable;
824
825 public final T call() {
826 try {
827 return realCall();
Narayan Kamath8e9a0e92015-04-28 11:40:00 +0100828 } catch (Throwable fail) {
829 threadUnexpectedException(fail);
Calin Juravle8f0d92b2013-08-01 17:26:00 +0100830 return null;
831 }
832 }
833 }
834
835 public abstract class CheckedInterruptedCallable<T>
836 implements Callable<T> {
837 protected abstract T realCall() throws Throwable;
838
839 public final T call() {
840 try {
841 T result = realCall();
842 threadShouldThrow("InterruptedException");
843 return result;
844 } catch (InterruptedException success) {
845 threadAssertFalse(Thread.interrupted());
Narayan Kamath8e9a0e92015-04-28 11:40:00 +0100846 } catch (Throwable fail) {
847 threadUnexpectedException(fail);
Calin Juravle8f0d92b2013-08-01 17:26:00 +0100848 }
849 return null;
850 }
851 }
852
853 public static class NoOpRunnable implements Runnable {
854 public void run() {}
855 }
856
857 public static class NoOpCallable implements Callable {
858 public Object call() { return Boolean.TRUE; }
859 }
860
861 public static final String TEST_STRING = "a test string";
862
863 public static class StringTask implements Callable<String> {
864 public String call() { return TEST_STRING; }
865 }
866
867 public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) {
868 return new CheckedCallable<String>() {
869 protected String realCall() {
870 try {
871 latch.await();
872 } catch (InterruptedException quittingTime) {}
873 return TEST_STRING;
874 }};
875 }
876
877 public Runnable awaiter(final CountDownLatch latch) {
878 return new CheckedRunnable() {
879 public void realRun() throws InterruptedException {
880 await(latch);
881 }};
882 }
883
884 public void await(CountDownLatch latch) {
885 try {
886 assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
Narayan Kamath8e9a0e92015-04-28 11:40:00 +0100887 } catch (Throwable fail) {
888 threadUnexpectedException(fail);
Calin Juravle8f0d92b2013-08-01 17:26:00 +0100889 }
890 }
891
892 public void await(Semaphore semaphore) {
893 try {
894 assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
Narayan Kamath8e9a0e92015-04-28 11:40:00 +0100895 } catch (Throwable fail) {
896 threadUnexpectedException(fail);
Calin Juravle8f0d92b2013-08-01 17:26:00 +0100897 }
898 }
899
900// /**
901// * Spin-waits up to LONG_DELAY_MS until flag becomes true.
902// */
903// public void await(AtomicBoolean flag) {
904// await(flag, LONG_DELAY_MS);
905// }
906
907// /**
908// * Spin-waits up to the specified timeout until flag becomes true.
909// */
910// public void await(AtomicBoolean flag, long timeoutMillis) {
911// long startTime = System.nanoTime();
912// while (!flag.get()) {
913// if (millisElapsedSince(startTime) > timeoutMillis)
914// throw new AssertionFailedError("timed out");
915// Thread.yield();
916// }
917// }
918
919 public static class NPETask implements Callable<String> {
920 public String call() { throw new NullPointerException(); }
921 }
922
923 public static class CallableOne implements Callable<Integer> {
924 public Integer call() { return one; }
925 }
926
927 public class ShortRunnable extends CheckedRunnable {
928 protected void realRun() throws Throwable {
929 delay(SHORT_DELAY_MS);
930 }
931 }
932
933 public class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
934 protected void realRun() throws InterruptedException {
935 delay(SHORT_DELAY_MS);
936 }
937 }
938
939 public class SmallRunnable extends CheckedRunnable {
940 protected void realRun() throws Throwable {
941 delay(SMALL_DELAY_MS);
942 }
943 }
944
945 public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
946 protected void realRun() {
947 try {
948 delay(SMALL_DELAY_MS);
949 } catch (InterruptedException ok) {}
950 }
951 }
952
953 public class SmallCallable extends CheckedCallable {
954 protected Object realCall() throws InterruptedException {
955 delay(SMALL_DELAY_MS);
956 return Boolean.TRUE;
957 }
958 }
959
960 public class MediumRunnable extends CheckedRunnable {
961 protected void realRun() throws Throwable {
962 delay(MEDIUM_DELAY_MS);
963 }
964 }
965
966 public class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
967 protected void realRun() throws InterruptedException {
968 delay(MEDIUM_DELAY_MS);
969 }
970 }
971
972 public Runnable possiblyInterruptedRunnable(final long timeoutMillis) {
973 return new CheckedRunnable() {
974 protected void realRun() {
975 try {
976 delay(timeoutMillis);
977 } catch (InterruptedException ok) {}
978 }};
979 }
980
981 public class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
982 protected void realRun() {
983 try {
984 delay(MEDIUM_DELAY_MS);
985 } catch (InterruptedException ok) {}
986 }
987 }
988
989 public class LongPossiblyInterruptedRunnable extends CheckedRunnable {
990 protected void realRun() {
991 try {
992 delay(LONG_DELAY_MS);
993 } catch (InterruptedException ok) {}
994 }
995 }
996
997 /**
998 * For use as ThreadFactory in constructors
999 */
1000 public static class SimpleThreadFactory implements ThreadFactory {
1001 public Thread newThread(Runnable r) {
1002 return new Thread(r);
1003 }
1004 }
1005
1006 public interface TrackedRunnable extends Runnable {
1007 boolean isDone();
1008 }
1009
1010 public static TrackedRunnable trackedRunnable(final long timeoutMillis) {
1011 return new TrackedRunnable() {
1012 private volatile boolean done = false;
1013 public boolean isDone() { return done; }
1014 public void run() {
1015 try {
1016 delay(timeoutMillis);
1017 done = true;
1018 } catch (InterruptedException ok) {}
1019 }
1020 };
1021 }
1022
1023 public static class TrackedShortRunnable implements Runnable {
1024 public volatile boolean done = false;
1025 public void run() {
1026 try {
1027 delay(SHORT_DELAY_MS);
1028 done = true;
1029 } catch (InterruptedException ok) {}
1030 }
1031 }
1032
1033 public static class TrackedSmallRunnable implements Runnable {
1034 public volatile boolean done = false;
1035 public void run() {
1036 try {
1037 delay(SMALL_DELAY_MS);
1038 done = true;
1039 } catch (InterruptedException ok) {}
1040 }
1041 }
1042
1043 public static class TrackedMediumRunnable implements Runnable {
1044 public volatile boolean done = false;
1045 public void run() {
1046 try {
1047 delay(MEDIUM_DELAY_MS);
1048 done = true;
1049 } catch (InterruptedException ok) {}
1050 }
1051 }
1052
1053 public static class TrackedLongRunnable implements Runnable {
1054 public volatile boolean done = false;
1055 public void run() {
1056 try {
1057 delay(LONG_DELAY_MS);
1058 done = true;
1059 } catch (InterruptedException ok) {}
1060 }
1061 }
1062
1063 public static class TrackedNoOpRunnable implements Runnable {
1064 public volatile boolean done = false;
1065 public void run() {
1066 done = true;
1067 }
1068 }
1069
1070 public static class TrackedCallable implements Callable {
1071 public volatile boolean done = false;
1072 public Object call() {
1073 try {
1074 delay(SMALL_DELAY_MS);
1075 done = true;
1076 } catch (InterruptedException ok) {}
1077 return Boolean.TRUE;
1078 }
1079 }
1080
1081 /**
1082 * Analog of CheckedRunnable for RecursiveAction
1083 */
1084 public abstract class CheckedRecursiveAction extends RecursiveAction {
1085 protected abstract void realCompute() throws Throwable;
1086
1087 @Override protected final void compute() {
1088 try {
1089 realCompute();
Narayan Kamath8e9a0e92015-04-28 11:40:00 +01001090 } catch (Throwable fail) {
1091 threadUnexpectedException(fail);
Calin Juravle8f0d92b2013-08-01 17:26:00 +01001092 }
1093 }
1094 }
1095
1096 /**
1097 * Analog of CheckedCallable for RecursiveTask
1098 */
1099 public abstract class CheckedRecursiveTask<T> extends RecursiveTask<T> {
1100 protected abstract T realCompute() throws Throwable;
1101
1102 @Override protected final T compute() {
1103 try {
1104 return realCompute();
Narayan Kamath8e9a0e92015-04-28 11:40:00 +01001105 } catch (Throwable fail) {
1106 threadUnexpectedException(fail);
Calin Juravle8f0d92b2013-08-01 17:26:00 +01001107 return null;
1108 }
1109 }
1110 }
1111
1112 /**
1113 * For use as RejectedExecutionHandler in constructors
1114 */
1115 public static class NoOpREHandler implements RejectedExecutionHandler {
1116 public void rejectedExecution(Runnable r,
1117 ThreadPoolExecutor executor) {}
1118 }
1119
1120 /**
1121 * A CyclicBarrier that uses timed await and fails with
1122 * AssertionFailedErrors instead of throwing checked exceptions.
1123 */
1124 public class CheckedBarrier extends CyclicBarrier {
1125 public CheckedBarrier(int parties) { super(parties); }
1126
1127 public int await() {
1128 try {
1129 return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
Narayan Kamath8e9a0e92015-04-28 11:40:00 +01001130 } catch (TimeoutException timedOut) {
Calin Juravle8f0d92b2013-08-01 17:26:00 +01001131 throw new AssertionFailedError("timed out");
Narayan Kamath8e9a0e92015-04-28 11:40:00 +01001132 } catch (Exception fail) {
Calin Juravle8f0d92b2013-08-01 17:26:00 +01001133 AssertionFailedError afe =
Narayan Kamath8e9a0e92015-04-28 11:40:00 +01001134 new AssertionFailedError("Unexpected exception: " + fail);
1135 afe.initCause(fail);
Calin Juravle8f0d92b2013-08-01 17:26:00 +01001136 throw afe;
1137 }
1138 }
1139 }
1140
1141 void checkEmpty(BlockingQueue q) {
1142 try {
1143 assertTrue(q.isEmpty());
1144 assertEquals(0, q.size());
1145 assertNull(q.peek());
1146 assertNull(q.poll());
1147 assertNull(q.poll(0, MILLISECONDS));
1148 assertEquals(q.toString(), "[]");
1149 assertTrue(Arrays.equals(q.toArray(), new Object[0]));
1150 assertFalse(q.iterator().hasNext());
1151 try {
1152 q.element();
1153 shouldThrow();
1154 } catch (NoSuchElementException success) {}
1155 try {
1156 q.iterator().next();
1157 shouldThrow();
1158 } catch (NoSuchElementException success) {}
1159 try {
1160 q.remove();
1161 shouldThrow();
1162 } catch (NoSuchElementException success) {}
Narayan Kamath8e9a0e92015-04-28 11:40:00 +01001163 } catch (InterruptedException fail) { threadUnexpectedException(fail); }
Calin Juravle8f0d92b2013-08-01 17:26:00 +01001164 }
1165
1166 void assertSerialEquals(Object x, Object y) {
1167 assertTrue(Arrays.equals(serialBytes(x), serialBytes(y)));
1168 }
1169
1170 void assertNotSerialEquals(Object x, Object y) {
1171 assertFalse(Arrays.equals(serialBytes(x), serialBytes(y)));
1172 }
1173
1174 byte[] serialBytes(Object o) {
1175 try {
1176 ByteArrayOutputStream bos = new ByteArrayOutputStream();
1177 ObjectOutputStream oos = new ObjectOutputStream(bos);
1178 oos.writeObject(o);
1179 oos.flush();
1180 oos.close();
1181 return bos.toByteArray();
Narayan Kamath8e9a0e92015-04-28 11:40:00 +01001182 } catch (Throwable fail) {
1183 threadUnexpectedException(fail);
Calin Juravle8f0d92b2013-08-01 17:26:00 +01001184 return new byte[0];
1185 }
1186 }
1187
1188 @SuppressWarnings("unchecked")
1189 <T> T serialClone(T o) {
1190 try {
1191 ObjectInputStream ois = new ObjectInputStream
1192 (new ByteArrayInputStream(serialBytes(o)));
1193 T clone = (T) ois.readObject();
1194 assertSame(o.getClass(), clone.getClass());
1195 return clone;
Narayan Kamath8e9a0e92015-04-28 11:40:00 +01001196 } catch (Throwable fail) {
1197 threadUnexpectedException(fail);
Calin Juravle8f0d92b2013-08-01 17:26:00 +01001198 return null;
1199 }
1200 }
1201
1202 public void assertThrows(Class<? extends Throwable> expectedExceptionClass,
1203 Runnable... throwingActions) {
1204 for (Runnable throwingAction : throwingActions) {
1205 boolean threw = false;
1206 try { throwingAction.run(); }
1207 catch (Throwable t) {
1208 threw = true;
1209 if (!expectedExceptionClass.isInstance(t)) {
1210 AssertionFailedError afe =
1211 new AssertionFailedError
1212 ("Expected " + expectedExceptionClass.getName() +
1213 ", got " + t.getClass().getName());
1214 afe.initCause(t);
1215 threadUnexpectedException(afe);
1216 }
1217 }
1218 if (!threw)
1219 shouldThrow(expectedExceptionClass.getName());
1220 }
1221 }
Narayan Kamath8e9a0e92015-04-28 11:40:00 +01001222
1223 public void assertIteratorExhausted(Iterator<?> it) {
1224 try {
1225 it.next();
1226 shouldThrow();
1227 } catch (NoSuchElementException success) {}
1228 assertFalse(it.hasNext());
1229 }
Calin Juravle8f0d92b2013-08-01 17:26:00 +01001230}