ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/JSR166TestCase.java
(Generate patch)

Comparing jsr166/src/test/tck/JSR166TestCase.java (file contents):
Revision 1.47 by jsr166, Tue Dec 1 06:47:14 2009 UTC vs.
Revision 1.54 by jsr166, Fri Sep 17 00:52:36 2010 UTC

# Line 7 | Line 7
7   */
8  
9   import junit.framework.*;
10 < import java.util.*;
10 > import java.util.PropertyPermission;
11   import java.util.concurrent.*;
12 + import java.util.concurrent.atomic.AtomicReference;
13   import static java.util.concurrent.TimeUnit.MILLISECONDS;
14 < import java.io.*;
15 < import java.security.*;
14 > import java.security.CodeSource;
15 > import java.security.Permission;
16 > import java.security.PermissionCollection;
17 > import java.security.Permissions;
18 > import java.security.Policy;
19 > import java.security.ProtectionDomain;
20 > import java.security.SecurityPermission;
21  
22   /**
23   * Base class for JSR166 Junit TCK tests.  Defines some constants,
# Line 26 | Line 32 | import java.security.*;
32   * <li> All assertions in code running in generated threads must use
33   * the forms {@link #threadFail}, {@link #threadAssertTrue}, {@link
34   * #threadAssertEquals}, or {@link #threadAssertNull}, (not
35 < * <tt>fail</tt>, <tt>assertTrue</tt>, etc.) It is OK (but not
35 > * {@code fail}, {@code assertTrue}, etc.) It is OK (but not
36   * particularly recommended) for other code to use these forms too.
37   * Only the most typically used JUnit assertion methods are defined
38   * this way, but enough to live with.</li>
39   *
40   * <li> If you override {@link #setUp} or {@link #tearDown}, make sure
41 < * to invoke <tt>super.setUp</tt> and <tt>super.tearDown</tt> within
41 > * to invoke {@code super.setUp} and {@code super.tearDown} within
42   * them. These methods are used to clear and check for thread
43   * assertion failures.</li>
44   *
45 < * <li>All delays and timeouts must use one of the constants <tt>
46 < * SHORT_DELAY_MS</tt>, <tt> SMALL_DELAY_MS</tt>, <tt> MEDIUM_DELAY_MS</tt>,
47 < * <tt> LONG_DELAY_MS</tt>. The idea here is that a SHORT is always
45 > * <li>All delays and timeouts must use one of the constants {@code
46 > * SHORT_DELAY_MS}, {@code SMALL_DELAY_MS}, {@code MEDIUM_DELAY_MS},
47 > * {@code LONG_DELAY_MS}. The idea here is that a SHORT is always
48   * discriminable from zero time, and always allows enough time for the
49   * small amounts of computation (creating a thread, calling a few
50   * methods, etc) needed to reach a timeout point. Similarly, a SMALL
# Line 48 | Line 54 | import java.security.*;
54   * in one spot to rerun tests on slower platforms.</li>
55   *
56   * <li> All threads generated must be joined inside each test case
57 < * method (or <tt>fail</tt> to do so) before returning from the
58 < * method. The <tt> joinPool</tt> method can be used to do this when
57 > * method (or {@code fail} to do so) before returning from the
58 > * method. The {@code joinPool} method can be used to do this when
59   * using Executors.</li>
60   *
61   * </ol>
# Line 81 | Line 87 | import java.security.*;
87   * any particular package to simplify things for people integrating
88   * them in TCK test suites.</li>
89   *
90 < * <li> As a convenience, the <tt>main</tt> of this class (JSR166TestCase)
90 > * <li> As a convenience, the {@code main} of this class (JSR166TestCase)
91   * runs all JSR166 unit tests.</li>
92   *
93   * </ul>
94   */
95   public class JSR166TestCase extends TestCase {
96 +    private static final boolean useSecurityManager =
97 +        Boolean.getBoolean("jsr166.useSecurityManager");
98 +
99      /**
100       * Runs all JSR166 unit tests using junit.textui.TestRunner
101       */
102      public static void main(String[] args) {
103 +        if (useSecurityManager) {
104 +            System.err.println("Setting a permissive security manager");
105 +            Policy.setPolicy(permissivePolicy());
106 +            System.setSecurityManager(new SecurityManager());
107 +        }
108          int iters = 1;
109          if (args.length > 0)
110              iters = Integer.parseInt(args[0]);
# Line 135 | Line 149 | public class JSR166TestCase extends Test
149          suite.addTest(new TestSuite(AtomicReferenceTest.class));
150          suite.addTest(new TestSuite(AtomicStampedReferenceTest.class));
151          suite.addTest(new TestSuite(ConcurrentHashMapTest.class));
152 +        suite.addTest(new TestSuite(ConcurrentLinkedDequeTest.class));
153          suite.addTest(new TestSuite(ConcurrentLinkedQueueTest.class));
154          suite.addTest(new TestSuite(ConcurrentSkipListMapTest.class));
155          suite.addTest(new TestSuite(ConcurrentSkipListSubMapTest.class));
# Line 197 | Line 212 | public class JSR166TestCase extends Test
212       */
213      protected void setDelays() {
214          SHORT_DELAY_MS = getShortDelay();
215 <        SMALL_DELAY_MS = SHORT_DELAY_MS * 5;
215 >        SMALL_DELAY_MS  = SHORT_DELAY_MS * 5;
216          MEDIUM_DELAY_MS = SHORT_DELAY_MS * 10;
217 <        LONG_DELAY_MS = SHORT_DELAY_MS * 50;
217 >        LONG_DELAY_MS   = SHORT_DELAY_MS * 50;
218      }
219  
220      /**
221 <     * Flag set true if any threadAssert methods fail
221 >     * The first exception encountered if any threadAssertXXX method fails.
222       */
223 <    volatile boolean threadFailed;
223 >    private final AtomicReference<Throwable> threadFailure
224 >        = new AtomicReference<Throwable>(null);
225  
226      /**
227 <     * Initializes test to indicate that no thread assertions have failed
227 >     * Records an exception so that it can be rethrown later in the test
228 >     * harness thread, triggering a test case failure.  Only the first
229 >     * failure is recorded; subsequent calls to this method from within
230 >     * the same test have no effect.
231       */
232 +    public void threadRecordFailure(Throwable t) {
233 +        threadFailure.compareAndSet(null, t);
234 +    }
235 +
236      public void setUp() {
237          setDelays();
215        threadFailed = false;
238      }
239  
240      /**
241 <     * Triggers test case failure if any thread assertions have failed
242 <     */
243 <    public void tearDown() {
244 <        assertFalse(threadFailed);
241 >     * Triggers test case failure if any thread assertions have failed,
242 >     * by rethrowing, in the test harness thread, any exception recorded
243 >     * earlier by threadRecordFailure.
244 >     */
245 >    public void tearDown() throws Exception {
246 >        Throwable t = threadFailure.get();
247 >        if (t != null) {
248 >            if (t instanceof Error)
249 >                throw (Error) t;
250 >            else if (t instanceof RuntimeException)
251 >                throw (RuntimeException) t;
252 >            else if (t instanceof Exception)
253 >                throw (Exception) t;
254 >            else
255 >                throw new AssertionError(t);
256 >        }
257      }
258  
259      /**
260 <     * Fail, also setting status to indicate current testcase should fail
260 >     * Just like fail(reason), but additionally recording (using
261 >     * threadRecordFailure) any AssertionError thrown, so that the current
262 >     * testcase will fail.
263       */
264      public void threadFail(String reason) {
265 <        threadFailed = true;
266 <        fail(reason);
265 >        try {
266 >            fail(reason);
267 >        } catch (Throwable t) {
268 >            threadRecordFailure(t);
269 >            fail(reason);
270 >        }
271      }
272  
273      /**
274 <     * If expression not true, set status to indicate current testcase
275 <     * should fail
274 >     * Just like assertTrue(b), but additionally recording (using
275 >     * threadRecordFailure) any AssertionError thrown, so that the current
276 >     * testcase will fail.
277       */
278      public void threadAssertTrue(boolean b) {
279 <        if (!b) {
239 <            threadFailed = true;
279 >        try {
280              assertTrue(b);
281 +        } catch (AssertionError t) {
282 +            threadRecordFailure(t);
283 +            throw t;
284          }
285      }
286  
287      /**
288 <     * If expression not false, set status to indicate current testcase
289 <     * should fail
288 >     * Just like assertFalse(b), but additionally recording (using
289 >     * threadRecordFailure) any AssertionError thrown, so that the
290 >     * current testcase will fail.
291       */
292      public void threadAssertFalse(boolean b) {
293 <        if (b) {
250 <            threadFailed = true;
293 >        try {
294              assertFalse(b);
295 +        } catch (AssertionError t) {
296 +            threadRecordFailure(t);
297 +            throw t;
298          }
299      }
300  
301      /**
302 <     * If argument not null, set status to indicate current testcase
303 <     * should fail
302 >     * Just like assertNull(x), but additionally recording (using
303 >     * threadRecordFailure) any AssertionError thrown, so that the
304 >     * current testcase will fail.
305       */
306      public void threadAssertNull(Object x) {
307 <        if (x != null) {
261 <            threadFailed = true;
307 >        try {
308              assertNull(x);
309 +        } catch (AssertionError t) {
310 +            threadRecordFailure(t);
311 +            throw t;
312          }
313      }
314  
315      /**
316 <     * If arguments not equal, set status to indicate current testcase
317 <     * should fail
316 >     * Just like assertEquals(x, y), but additionally recording (using
317 >     * threadRecordFailure) any AssertionError thrown, so that the
318 >     * current testcase will fail.
319       */
320      public void threadAssertEquals(long x, long y) {
321 <        if (x != y) {
272 <            threadFailed = true;
321 >        try {
322              assertEquals(x, y);
323 +        } catch (AssertionError t) {
324 +            threadRecordFailure(t);
325 +            throw t;
326          }
327      }
328  
329      /**
330 <     * If arguments not equal, set status to indicate current testcase
331 <     * should fail
330 >     * Just like assertEquals(x, y), but additionally recording (using
331 >     * threadRecordFailure) any AssertionError thrown, so that the
332 >     * current testcase will fail.
333       */
334      public void threadAssertEquals(Object x, Object y) {
335 <        if (x != y && (x == null || !x.equals(y))) {
283 <            threadFailed = true;
335 >        try {
336              assertEquals(x, y);
337 +        } catch (AssertionError t) {
338 +            threadRecordFailure(t);
339 +            throw t;
340          }
341      }
342  
343      /**
344 <     * threadFail with message "should throw exception"
344 >     * Just like assertSame(x, y), but additionally recording (using
345 >     * threadRecordFailure) any AssertionError thrown, so that the
346 >     * current testcase will fail.
347       */
348 <    public void threadShouldThrow() {
349 <        threadFailed = true;
350 <        fail("should throw exception");
348 >    public void threadAssertSame(Object x, Object y) {
349 >        try {
350 >            assertSame(x, y);
351 >        } catch (AssertionError t) {
352 >            threadRecordFailure(t);
353 >            throw t;
354 >        }
355      }
356  
357      /**
358 <     * threadFail with message "should throw" + exceptionName
358 >     * Calls threadFail with message "should throw exception".
359       */
360 <    public void threadShouldThrow(String exceptionName) {
361 <        threadFailed = true;
301 <        fail("should throw " + exceptionName);
360 >    public void threadShouldThrow() {
361 >        threadFail("should throw exception");
362      }
363  
364      /**
365 <     * threadFail with message "Unexpected exception"
365 >     * Calls threadFail with message "should throw" + exceptionName.
366       */
367 <    public void threadUnexpectedException() {
368 <        threadFailed = true;
309 <        fail("Unexpected exception");
367 >    public void threadShouldThrow(String exceptionName) {
368 >        threadFail("should throw " + exceptionName);
369      }
370  
371      /**
372 <     * threadFail with message "Unexpected exception", with argument
372 >     * Calls threadFail with message "Unexpected exception" + ex.
373       */
374 <    public void threadUnexpectedException(Throwable ex) {
375 <        threadFailed = true;
376 <        ex.printStackTrace();
377 <        fail("Unexpected exception: " + ex);
374 >    public void threadUnexpectedException(Throwable t) {
375 >        threadRecordFailure(t);
376 >        t.printStackTrace();
377 >        // Rethrow, wrapping in an AssertionError if necessary
378 >        if (t instanceof RuntimeException)
379 >            throw (RuntimeException) t;
380 >        else if (t instanceof Error)
381 >            throw (Error) t;
382 >        else {
383 >            AssertionError ae = new AssertionError("unexpected exception: " + t);
384 >            t.initCause(t);
385 >            throw ae;
386 >        }            
387      }
388  
389      /**
390 <     * Wait out termination of a thread pool or fail doing so
390 >     * Waits out termination of a thread pool or fails doing so.
391       */
392      public void joinPool(ExecutorService exec) {
393          try {
394              exec.shutdown();
395 <            assertTrue(exec.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
395 >            assertTrue("ExecutorService did not terminate in a timely manner",
396 >                       exec.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
397          } catch (SecurityException ok) {
398              // Allowed in case test doesn't have privs
399          } catch (InterruptedException ie) {
# Line 334 | Line 403 | public class JSR166TestCase extends Test
403  
404  
405      /**
406 <     * fail with message "should throw exception"
406 >     * Fails with message "should throw exception".
407       */
408      public void shouldThrow() {
409          fail("Should throw exception");
410      }
411  
412      /**
413 <     * fail with message "should throw " + exceptionName
413 >     * Fails with message "should throw " + exceptionName.
414       */
415      public void shouldThrow(String exceptionName) {
416          fail("Should throw " + exceptionName);
417      }
418  
419      /**
420 <     * fail with message "Unexpected exception"
352 <     */
353 <    public void unexpectedException() {
354 <        fail("Unexpected exception");
355 <    }
356 <
357 <    /**
358 <     * fail with message "Unexpected exception", with argument
420 >     * Fails with message "Unexpected exception: " + ex.
421       */
422      public void unexpectedException(Throwable ex) {
423          ex.printStackTrace();
# Line 390 | Line 452 | public class JSR166TestCase extends Test
452  
453  
454      /**
455 +     * Runs Runnable r with a security policy that permits precisely
456 +     * the specified permissions.  If there is no current security
457 +     * manager, the runnable is run twice, both with and without a
458 +     * security manager.  We require that any security manager permit
459 +     * getPolicy/setPolicy.
460 +     */
461 +    public void runWithPermissions(Runnable r, Permission... permissions) {
462 +        SecurityManager sm = System.getSecurityManager();
463 +        if (sm == null) {
464 +            r.run();
465 +            Policy savedPolicy = Policy.getPolicy();
466 +            try {
467 +                Policy.setPolicy(permissivePolicy());
468 +                System.setSecurityManager(new SecurityManager());
469 +                runWithPermissions(r, permissions);
470 +            } finally {
471 +                System.setSecurityManager(null);
472 +                Policy.setPolicy(savedPolicy);
473 +            }
474 +        } else {
475 +            Policy savedPolicy = Policy.getPolicy();
476 +            AdjustablePolicy policy = new AdjustablePolicy(permissions);
477 +            Policy.setPolicy(policy);
478 +
479 +            try {
480 +                r.run();
481 +            } finally {
482 +                policy.addPermission(new SecurityPermission("setPolicy"));
483 +                Policy.setPolicy(savedPolicy);
484 +            }
485 +        }
486 +    }
487 +
488 +    /**
489 +     * Runs a runnable without any permissions.
490 +     */
491 +    public void runWithoutPermissions(Runnable r) {
492 +        runWithPermissions(r);
493 +    }
494 +
495 +    /**
496       * A security policy where new permissions can be dynamically added
497       * or all cleared.
498       */
499      public static class AdjustablePolicy extends java.security.Policy {
500          Permissions perms = new Permissions();
501 <        AdjustablePolicy() { }
501 >        AdjustablePolicy(Permission... permissions) {
502 >            for (Permission permission : permissions)
503 >                perms.add(permission);
504 >        }
505          void addPermission(Permission perm) { perms.add(perm); }
506          void clearPermissions() { perms = new Permissions(); }
507          public PermissionCollection getPermissions(CodeSource cs) {
# Line 411 | Line 517 | public class JSR166TestCase extends Test
517      }
518  
519      /**
520 +     * Returns a policy containing all the permissions we ever need.
521 +     */
522 +    public static Policy permissivePolicy() {
523 +        return new AdjustablePolicy
524 +            // Permissions j.u.c. needs directly
525 +            (new RuntimePermission("modifyThread"),
526 +             new RuntimePermission("getClassLoader"),
527 +             new RuntimePermission("setContextClassLoader"),
528 +             // Permissions needed to change permissions!
529 +             new SecurityPermission("getPolicy"),
530 +             new SecurityPermission("setPolicy"),
531 +             new RuntimePermission("setSecurityManager"),
532 +             // Permissions needed by the junit test harness
533 +             new RuntimePermission("accessDeclaredMembers"),
534 +             new PropertyPermission("*", "read"),
535 +             new java.io.FilePermission("<<ALL FILES>>", "read"));
536 +    }
537 +
538 +    /**
539       * Sleep until the timeout has elapsed, or interrupted.
540       * Does <em>NOT</em> throw InterruptedException.
541       */
# Line 505 | Line 630 | public class JSR166TestCase extends Test
630                  return realCall();
631              } catch (Throwable t) {
632                  threadUnexpectedException(t);
633 +                return null;
634              }
509            return null;
635          }
636      }
637  
638 <    public abstract class CheckedInterruptedCallable<T> implements Callable<T> {
638 >    public abstract class CheckedInterruptedCallable<T>
639 >        implements Callable<T> {
640          protected abstract T realCall() throws Throwable;
641  
642          public final T call() {
# Line 540 | Line 666 | public class JSR166TestCase extends Test
666          public String call() { return TEST_STRING; }
667      }
668  
669 +    public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) {
670 +        return new CheckedCallable<String>() {
671 +            public String realCall() {
672 +                try {
673 +                    latch.await();
674 +                } catch (InterruptedException quittingTime) {}
675 +                return TEST_STRING;
676 +            }};
677 +    }
678 +
679      public static class NPETask implements Callable<String> {
680          public String call() { throw new NullPointerException(); }
681      }
# Line 672 | Line 808 | public class JSR166TestCase extends Test
808          }
809      }
810  
811 +    /**
812 +     * Analog of CheckedRunnable for RecursiveAction
813 +     */
814 +    public abstract class CheckedRecursiveAction extends RecursiveAction {
815 +        protected abstract void realCompute() throws Throwable;
816 +
817 +        public final void compute() {
818 +            try {
819 +                realCompute();
820 +            } catch (Throwable t) {
821 +                threadUnexpectedException(t);
822 +            }
823 +        }
824 +    }
825 +
826 +    /**
827 +     * Analog of CheckedCallable for RecursiveTask
828 +     */
829 +    public abstract class CheckedRecursiveTask<T> extends RecursiveTask<T> {
830 +        protected abstract T realCompute() throws Throwable;
831 +
832 +        public final T compute() {
833 +            try {
834 +                return realCompute();
835 +            } catch (Throwable t) {
836 +                threadUnexpectedException(t);
837 +                return null;
838 +            }
839 +        }
840 +    }
841  
842      /**
843       * For use as RejectedExecutionHandler in constructors

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines