ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/JSR166TestCase.java
Revision: 1.180
Committed: Mon Nov 9 05:43:39 2015 UTC (8 years, 5 months ago) by jsr166
Branch: MAIN
Changes since 1.179: +1 -2 lines
Log Message:
whitespace

File Contents

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