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.85 by jsr166, Sun May 29 14:18:52 2011 UTC vs.
Revision 1.114 by jsr166, Tue Sep 17 06:38:36 2013 UTC

# Line 11 | Line 11 | import java.io.ByteArrayInputStream;
11   import java.io.ByteArrayOutputStream;
12   import java.io.ObjectInputStream;
13   import java.io.ObjectOutputStream;
14 + import java.lang.management.ManagementFactory;
15 + import java.lang.management.ThreadInfo;
16 + import java.lang.reflect.Method;
17 + import java.util.ArrayList;
18   import java.util.Arrays;
19   import java.util.Date;
20 + import java.util.Enumeration;
21 + import java.util.List;
22   import java.util.NoSuchElementException;
23   import java.util.PropertyPermission;
24   import java.util.concurrent.*;
# Line 20 | Line 26 | import java.util.concurrent.atomic.Atomi
26   import java.util.concurrent.atomic.AtomicReference;
27   import static java.util.concurrent.TimeUnit.MILLISECONDS;
28   import static java.util.concurrent.TimeUnit.NANOSECONDS;
29 + import java.util.regex.Pattern;
30   import java.security.CodeSource;
31   import java.security.Permission;
32   import java.security.PermissionCollection;
# Line 69 | Line 76 | import java.security.SecurityPermission;
76   *
77   * </ol>
78   *
79 < * <p> <b>Other notes</b>
79 > * <p><b>Other notes</b>
80   * <ul>
81   *
82   * <li> Usually, there is one testcase method per JSR166 method
# Line 122 | Line 129 | public class JSR166TestCase extends Test
129      private static final long profileThreshold =
130          Long.getLong("jsr166.profileThreshold", 100);
131  
132 +    /**
133 +     * The number of repetitions per test (for tickling rare bugs).
134 +     */
135 +    private static final int runsPerTest =
136 +        Integer.getInteger("jsr166.runsPerTest", 1);
137 +
138 +    /**
139 +     * A filter for tests to run, matching strings of the form
140 +     * methodName(className), e.g. "testInvokeAll5(ForkJoinPoolTest)"
141 +     * Usefully combined with jsr166.runsPerTest.
142 +     */
143 +    private static final Pattern methodFilter = methodFilter();
144 +
145 +    private static Pattern methodFilter() {
146 +        String regex = System.getProperty("jsr166.methodFilter");
147 +        return (regex == null) ? null : Pattern.compile(regex);
148 +    }
149 +
150      protected void runTest() throws Throwable {
151 <        if (profileTests)
152 <            runTestProfiled();
153 <        else
154 <            super.runTest();
151 >        if (methodFilter == null
152 >            || methodFilter.matcher(toString()).find()) {
153 >            for (int i = 0; i < runsPerTest; i++) {
154 >                if (profileTests)
155 >                    runTestProfiled();
156 >                else
157 >                    super.runTest();
158 >            }
159 >        }
160      }
161  
162      protected void runTestProfiled() throws Throwable {
# Line 142 | Line 172 | public class JSR166TestCase extends Test
172      }
173  
174      /**
175 <     * Runs all JSR166 unit tests using junit.textui.TestRunner
175 >     * Runs all JSR166 unit tests using junit.textui.TestRunner.
176 >     * Optional command line arg provides the number of iterations to
177 >     * repeat running the tests.
178       */
179      public static void main(String[] args) {
180          if (useSecurityManager) {
# Line 174 | Line 206 | public class JSR166TestCase extends Test
206          return suite;
207      }
208  
209 +    public static void addNamedTestClasses(TestSuite suite,
210 +                                           String... testClassNames) {
211 +        for (String testClassName : testClassNames) {
212 +            try {
213 +                Class<?> testClass = Class.forName(testClassName);
214 +                Method m = testClass.getDeclaredMethod("suite",
215 +                                                       new Class<?>[0]);
216 +                suite.addTest(newTestSuite((Test)m.invoke(null)));
217 +            } catch (Exception e) {
218 +                throw new Error("Missing test class", e);
219 +            }
220 +        }
221 +    }
222 +
223 +    public static final double JAVA_CLASS_VERSION;
224 +    static {
225 +        try {
226 +            JAVA_CLASS_VERSION = java.security.AccessController.doPrivileged(
227 +                new java.security.PrivilegedAction<Double>() {
228 +                public Double run() {
229 +                    return Double.valueOf(System.getProperty("java.class.version"));}});
230 +        } catch (Throwable t) {
231 +            throw new Error(t);
232 +        }
233 +    }
234 +
235 +    public static boolean atLeastJava6() { return JAVA_CLASS_VERSION >= 50.0; }
236 +    public static boolean atLeastJava7() { return JAVA_CLASS_VERSION >= 51.0; }
237 +    public static boolean atLeastJava8() { return JAVA_CLASS_VERSION >= 52.0; }
238 +
239      /**
240       * Collects all JSR166 unit tests as one suite.
241       */
242      public static Test suite() {
243 <        return newTestSuite(
243 >        // Java7+ test classes
244 >        TestSuite suite = newTestSuite(
245              ForkJoinPoolTest.suite(),
246              ForkJoinTaskTest.suite(),
247              RecursiveActionTest.suite(),
# Line 243 | Line 306 | public class JSR166TestCase extends Test
306              TreeSetTest.suite(),
307              TreeSubMapTest.suite(),
308              TreeSubSetTest.suite());
309 +
310 +        // Java8+ test classes
311 +        if (atLeastJava8()) {
312 +            String[] java8TestClassNames = {
313 +                "Atomic8Test",
314 +                "CompletableFutureTest",
315 +                "ConcurrentHashMap8Test",
316 +                "CountedCompleterTest",
317 +                "DoubleAccumulatorTest",
318 +                "DoubleAdderTest",
319 +                "ForkJoinPool8Test",
320 +                "ForkJoinTask8Test",
321 +                "LongAccumulatorTest",
322 +                "LongAdderTest",
323 +                "SplittableRandomTest",
324 +                "StampedLockTest",
325 +                "ThreadLocalRandom8Test",
326 +            };
327 +            addNamedTestClasses(suite, java8TestClassNames);
328 +        }
329 +
330 +        return suite;
331      }
332  
333 +    // Delays for timing-dependent tests, in milliseconds.
334  
335      public static long SHORT_DELAY_MS;
336      public static long SMALL_DELAY_MS;
337      public static long MEDIUM_DELAY_MS;
338      public static long LONG_DELAY_MS;
339  
254
340      /**
341       * Returns the shortest timed delay. This could
342       * be reimplemented to use for example a Property.
# Line 334 | Line 419 | public class JSR166TestCase extends Test
419  
420          if (Thread.interrupted())
421              throw new AssertionFailedError("interrupt status set in main thread");
422 +
423 +        checkForkJoinPoolThreadLeaks();
424 +    }
425 +
426 +    /**
427 +     * Find missing try { ... } finally { joinPool(e); }
428 +     */
429 +    void checkForkJoinPoolThreadLeaks() throws InterruptedException {
430 +        Thread[] survivors = new Thread[5];
431 +        int count = Thread.enumerate(survivors);
432 +        for (int i = 0; i < count; i++) {
433 +            Thread thread = survivors[i];
434 +            String name = thread.getName();
435 +            if (name.startsWith("ForkJoinPool-")) {
436 +                // give thread some time to terminate
437 +                thread.join(LONG_DELAY_MS);
438 +                if (!thread.isAlive()) continue;
439 +                thread.stop();
440 +                throw new AssertionFailedError
441 +                    (String.format("Found leaked ForkJoinPool thread test=%s thread=%s%n",
442 +                                   toString(), name));
443 +            }
444 +        }
445      }
446  
447      /**
# Line 507 | Line 615 | public class JSR166TestCase extends Test
615      }
616  
617      /**
618 +     * A debugging tool to print all stack traces, as jstack does.
619 +     */
620 +    static void printAllStackTraces() {
621 +        for (ThreadInfo info :
622 +                 ManagementFactory.getThreadMXBean()
623 +                 .dumpAllThreads(true, true))
624 +            System.err.print(info);
625 +    }
626 +
627 +    /**
628       * Checks that thread does not terminate within the default
629       * millisecond delay of {@code timeoutMillis()}.
630       */
# Line 528 | Line 646 | public class JSR166TestCase extends Test
646      }
647  
648      /**
649 +     * Checks that the threads do not terminate within the default
650 +     * millisecond delay of {@code timeoutMillis()}.
651 +     */
652 +    void assertThreadsStayAlive(Thread... threads) {
653 +        assertThreadsStayAlive(timeoutMillis(), threads);
654 +    }
655 +
656 +    /**
657 +     * Checks that the threads do not terminate within the given millisecond delay.
658 +     */
659 +    void assertThreadsStayAlive(long millis, Thread... threads) {
660 +        try {
661 +            // No need to optimize the failing case via Thread.join.
662 +            delay(millis);
663 +            for (Thread thread : threads)
664 +                assertTrue(thread.isAlive());
665 +        } catch (InterruptedException ie) {
666 +            fail("Unexpected InterruptedException");
667 +        }
668 +    }
669 +
670 +    /**
671       * Checks that future.get times out, with the default timeout of
672       * {@code timeoutMillis()}.
673       */
# Line 589 | Line 729 | public class JSR166TestCase extends Test
729      public static final Integer m6  = new Integer(-6);
730      public static final Integer m10 = new Integer(-10);
731  
592
732      /**
733       * Runs Runnable r with a security policy that permits precisely
734       * the specified permissions.  If there is no current security
# Line 601 | Line 740 | public class JSR166TestCase extends Test
740          SecurityManager sm = System.getSecurityManager();
741          if (sm == null) {
742              r.run();
743 +        }
744 +        runWithSecurityManagerWithPermissions(r, permissions);
745 +    }
746 +
747 +    /**
748 +     * Runs Runnable r with a security policy that permits precisely
749 +     * the specified permissions.  If there is no current security
750 +     * manager, a temporary one is set for the duration of the
751 +     * Runnable.  We require that any security manager permit
752 +     * getPolicy/setPolicy.
753 +     */
754 +    public void runWithSecurityManagerWithPermissions(Runnable r,
755 +                                                      Permission... permissions) {
756 +        SecurityManager sm = System.getSecurityManager();
757 +        if (sm == null) {
758              Policy savedPolicy = Policy.getPolicy();
759              try {
760                  Policy.setPolicy(permissivePolicy());
761                  System.setSecurityManager(new SecurityManager());
762 <                runWithPermissions(r, permissions);
762 >                runWithSecurityManagerWithPermissions(r, permissions);
763              } finally {
764                  System.setSecurityManager(null);
765                  Policy.setPolicy(savedPolicy);
# Line 653 | Line 807 | public class JSR166TestCase extends Test
807              return perms.implies(p);
808          }
809          public void refresh() {}
810 +        public String toString() {
811 +            List<Permission> ps = new ArrayList<Permission>();
812 +            for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
813 +                ps.add(e.nextElement());
814 +            return "AdjustablePolicy with permissions " + ps;
815 +        }
816      }
817  
818      /**
# Line 690 | Line 850 | public class JSR166TestCase extends Test
850      }
851  
852      /**
853 <     * Waits up to the specified number of milliseconds for the given
853 >     * Spin-waits up to the specified number of milliseconds for the given
854       * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
855       */
856      void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
857 <        long timeoutNanos = timeoutMillis * 1000L * 1000L;
698 <        long t0 = System.nanoTime();
857 >        long startTime = System.nanoTime();
858          for (;;) {
859              Thread.State s = thread.getState();
860              if (s == Thread.State.BLOCKED ||
# Line 704 | Line 863 | public class JSR166TestCase extends Test
863                  return;
864              else if (s == Thread.State.TERMINATED)
865                  fail("Unexpected thread termination");
866 <            else if (System.nanoTime() - t0 > timeoutNanos) {
866 >            else if (millisElapsedSince(startTime) > timeoutMillis) {
867                  threadAssertTrue(thread.isAlive());
868                  return;
869              }
# Line 905 | Line 1064 | public class JSR166TestCase extends Test
1064          }
1065      }
1066  
1067 +    public void await(Semaphore semaphore) {
1068 +        try {
1069 +            assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
1070 +        } catch (Throwable t) {
1071 +            threadUnexpectedException(t);
1072 +        }
1073 +    }
1074 +
1075   //     /**
1076   //      * Spin-waits up to LONG_DELAY_MS until flag becomes true.
1077   //      */
# Line 1092 | Line 1259 | public class JSR166TestCase extends Test
1259      public abstract class CheckedRecursiveAction extends RecursiveAction {
1260          protected abstract void realCompute() throws Throwable;
1261  
1262 <        public final void compute() {
1262 >        @Override protected final void compute() {
1263              try {
1264                  realCompute();
1265              } catch (Throwable t) {
# Line 1107 | Line 1274 | public class JSR166TestCase extends Test
1274      public abstract class CheckedRecursiveTask<T> extends RecursiveTask<T> {
1275          protected abstract T realCompute() throws Throwable;
1276  
1277 <        public final T compute() {
1277 >        @Override protected final T compute() {
1278              try {
1279                  return realCompute();
1280              } catch (Throwable t) {
# Line 1126 | Line 1293 | public class JSR166TestCase extends Test
1293      }
1294  
1295      /**
1296 <     * A CyclicBarrier that fails with AssertionFailedErrors instead
1297 <     * of throwing checked exceptions.
1296 >     * A CyclicBarrier that uses timed await and fails with
1297 >     * AssertionFailedErrors instead of throwing checked exceptions.
1298       */
1299      public class CheckedBarrier extends CyclicBarrier {
1300          public CheckedBarrier(int parties) { super(parties); }
1301  
1302          public int await() {
1303              try {
1304 <                return super.await();
1304 >                return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1305 >            } catch (TimeoutException e) {
1306 >                throw new AssertionFailedError("timed out");
1307              } catch (Exception e) {
1308                  AssertionFailedError afe =
1309                      new AssertionFailedError("Unexpected exception: " + e);
# Line 1171 | Line 1340 | public class JSR166TestCase extends Test
1340          }
1341      }
1342  
1343 <    @SuppressWarnings("unchecked")
1344 <    <T> T serialClone(T o) {
1343 >    void assertSerialEquals(Object x, Object y) {
1344 >        assertTrue(Arrays.equals(serialBytes(x), serialBytes(y)));
1345 >    }
1346 >
1347 >    void assertNotSerialEquals(Object x, Object y) {
1348 >        assertFalse(Arrays.equals(serialBytes(x), serialBytes(y)));
1349 >    }
1350 >
1351 >    byte[] serialBytes(Object o) {
1352          try {
1353              ByteArrayOutputStream bos = new ByteArrayOutputStream();
1354              ObjectOutputStream oos = new ObjectOutputStream(bos);
1355              oos.writeObject(o);
1356              oos.flush();
1357              oos.close();
1358 <            ByteArrayInputStream bin =
1359 <                new ByteArrayInputStream(bos.toByteArray());
1360 <            ObjectInputStream ois = new ObjectInputStream(bin);
1361 <            return (T) ois.readObject();
1358 >            return bos.toByteArray();
1359 >        } catch (Throwable t) {
1360 >            threadUnexpectedException(t);
1361 >            return new byte[0];
1362 >        }
1363 >    }
1364 >
1365 >    @SuppressWarnings("unchecked")
1366 >    <T> T serialClone(T o) {
1367 >        try {
1368 >            ObjectInputStream ois = new ObjectInputStream
1369 >                (new ByteArrayInputStream(serialBytes(o)));
1370 >            T clone = (T) ois.readObject();
1371 >            assertSame(o.getClass(), clone.getClass());
1372 >            return clone;
1373          } catch (Throwable t) {
1374              threadUnexpectedException(t);
1375              return null;
1376          }
1377      }
1378 +
1379 +    public void assertThrows(Class<? extends Throwable> expectedExceptionClass,
1380 +                             Runnable... throwingActions) {
1381 +        for (Runnable throwingAction : throwingActions) {
1382 +            boolean threw = false;
1383 +            try { throwingAction.run(); }
1384 +            catch (Throwable t) {
1385 +                threw = true;
1386 +                if (!expectedExceptionClass.isInstance(t)) {
1387 +                    AssertionFailedError afe =
1388 +                        new AssertionFailedError
1389 +                        ("Expected " + expectedExceptionClass.getName() +
1390 +                         ", got " + t.getClass().getName());
1391 +                    afe.initCause(t);
1392 +                    threadUnexpectedException(afe);
1393 +                }
1394 +            }
1395 +            if (!threw)
1396 +                shouldThrow(expectedExceptionClass.getName());
1397 +        }
1398 +    }
1399   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines