ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/JSR166TestCase.java
Revision: 1.178
Committed: Fri Oct 23 17:34:47 2015 UTC (8 years, 6 months ago) by jsr166
Branch: MAIN
Changes since 1.177: +29 -1 lines
Log Message:
pithy junit test reporting

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