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.53 by jsr166, Thu Sep 16 00:52:49 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 {
# Line 334 | Line 402 | public class JSR166TestCase extends Test
402  
403  
404      /**
405 <     * fail with message "should throw exception"
405 >     * Fails with message "should throw exception".
406       */
407      public void shouldThrow() {
408          fail("Should throw exception");
409      }
410  
411      /**
412 <     * fail with message "should throw " + exceptionName
412 >     * Fails with message "should throw " + exceptionName.
413       */
414      public void shouldThrow(String exceptionName) {
415          fail("Should throw " + exceptionName);
416      }
417  
418      /**
419 <     * 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
419 >     * Fails with message "Unexpected exception: " + ex.
420       */
421      public void unexpectedException(Throwable ex) {
422          ex.printStackTrace();
# Line 390 | Line 451 | public class JSR166TestCase extends Test
451  
452  
453      /**
454 +     * Runs Runnable r with a security policy that permits precisely
455 +     * the specified permissions.  If there is no current security
456 +     * manager, the runnable is run twice, both with and without a
457 +     * security manager.  We require that any security manager permit
458 +     * getPolicy/setPolicy.
459 +     */
460 +    public void runWithPermissions(Runnable r, Permission... permissions) {
461 +        SecurityManager sm = System.getSecurityManager();
462 +        if (sm == null) {
463 +            r.run();
464 +            Policy savedPolicy = Policy.getPolicy();
465 +            try {
466 +                Policy.setPolicy(permissivePolicy());
467 +                System.setSecurityManager(new SecurityManager());
468 +                runWithPermissions(r, permissions);
469 +            } finally {
470 +                System.setSecurityManager(null);
471 +                Policy.setPolicy(savedPolicy);
472 +            }
473 +        } else {
474 +            Policy savedPolicy = Policy.getPolicy();
475 +            AdjustablePolicy policy = new AdjustablePolicy(permissions);
476 +            Policy.setPolicy(policy);
477 +
478 +            try {
479 +                r.run();
480 +            } finally {
481 +                policy.addPermission(new SecurityPermission("setPolicy"));
482 +                Policy.setPolicy(savedPolicy);
483 +            }
484 +        }
485 +    }
486 +
487 +    /**
488 +     * Runs a runnable without any permissions.
489 +     */
490 +    public void runWithoutPermissions(Runnable r) {
491 +        runWithPermissions(r);
492 +    }
493 +
494 +    /**
495       * A security policy where new permissions can be dynamically added
496       * or all cleared.
497       */
498      public static class AdjustablePolicy extends java.security.Policy {
499          Permissions perms = new Permissions();
500 <        AdjustablePolicy() { }
500 >        AdjustablePolicy(Permission... permissions) {
501 >            for (Permission permission : permissions)
502 >                perms.add(permission);
503 >        }
504          void addPermission(Permission perm) { perms.add(perm); }
505          void clearPermissions() { perms = new Permissions(); }
506          public PermissionCollection getPermissions(CodeSource cs) {
# Line 411 | Line 516 | public class JSR166TestCase extends Test
516      }
517  
518      /**
519 +     * Returns a policy containing all the permissions we ever need.
520 +     */
521 +    public static Policy permissivePolicy() {
522 +        return new AdjustablePolicy
523 +            // Permissions j.u.c. needs directly
524 +            (new RuntimePermission("modifyThread"),
525 +             new RuntimePermission("getClassLoader"),
526 +             new RuntimePermission("setContextClassLoader"),
527 +             // Permissions needed to change permissions!
528 +             new SecurityPermission("getPolicy"),
529 +             new SecurityPermission("setPolicy"),
530 +             new RuntimePermission("setSecurityManager"),
531 +             // Permissions needed by the junit test harness
532 +             new RuntimePermission("accessDeclaredMembers"),
533 +             new PropertyPermission("*", "read"),
534 +             new java.io.FilePermission("<<ALL FILES>>", "read"));
535 +    }
536 +
537 +    /**
538       * Sleep until the timeout has elapsed, or interrupted.
539       * Does <em>NOT</em> throw InterruptedException.
540       */
# Line 505 | Line 629 | public class JSR166TestCase extends Test
629                  return realCall();
630              } catch (Throwable t) {
631                  threadUnexpectedException(t);
632 +                return null;
633              }
509            return null;
634          }
635      }
636  
637 <    public abstract class CheckedInterruptedCallable<T> implements Callable<T> {
637 >    public abstract class CheckedInterruptedCallable<T>
638 >        implements Callable<T> {
639          protected abstract T realCall() throws Throwable;
640  
641          public final T call() {
# Line 540 | Line 665 | public class JSR166TestCase extends Test
665          public String call() { return TEST_STRING; }
666      }
667  
668 +    public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) {
669 +        return new CheckedCallable<String>() {
670 +            public String realCall() {
671 +                try {
672 +                    latch.await();
673 +                } catch (InterruptedException quittingTime) {}
674 +                return TEST_STRING;
675 +            }};
676 +    }
677 +
678      public static class NPETask implements Callable<String> {
679          public String call() { throw new NullPointerException(); }
680      }
# Line 672 | Line 807 | public class JSR166TestCase extends Test
807          }
808      }
809  
810 +    /**
811 +     * Analog of CheckedRunnable for RecursiveAction
812 +     */
813 +    public abstract class CheckedRecursiveAction extends RecursiveAction {
814 +        protected abstract void realCompute() throws Throwable;
815 +
816 +        public final void compute() {
817 +            try {
818 +                realCompute();
819 +            } catch (Throwable t) {
820 +                threadUnexpectedException(t);
821 +            }
822 +        }
823 +    }
824 +
825 +    /**
826 +     * Analog of CheckedCallable for RecursiveTask
827 +     */
828 +    public abstract class CheckedRecursiveTask<T> extends RecursiveTask<T> {
829 +        protected abstract T realCompute() throws Throwable;
830 +
831 +        public final T compute() {
832 +            try {
833 +                return realCompute();
834 +            } catch (Throwable t) {
835 +                threadUnexpectedException(t);
836 +                return null;
837 +            }
838 +        }
839 +    }
840  
841      /**
842       * For use as RejectedExecutionHandler in constructors

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines