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