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.86 by jsr166, Mon May 30 22:42:22 2011 UTC vs.
Revision 1.111 by dl, Sun Jul 21 22:24:18 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 69 | Line 75 | import java.security.SecurityPermission;
75   *
76   * </ol>
77   *
78 < * <p> <b>Other notes</b>
78 > * <p><b>Other notes</b>
79   * <ul>
80   *
81   * <li> Usually, there is one testcase method per JSR166 method
# Line 122 | Line 128 | public class JSR166TestCase extends Test
128      private static final long profileThreshold =
129          Long.getLong("jsr166.profileThreshold", 100);
130  
131 +    /**
132 +     * The number of repetitions per test (for tickling rare bugs).
133 +     */
134 +    private static final int runsPerTest =
135 +        Integer.getInteger("jsr166.runsPerTest", 1);
136 +
137      protected void runTest() throws Throwable {
138 <        if (profileTests)
139 <            runTestProfiled();
140 <        else
141 <            super.runTest();
138 >        for (int i = 0; i < runsPerTest; i++) {
139 >            if (profileTests)
140 >                runTestProfiled();
141 >            else
142 >                super.runTest();
143 >        }
144      }
145  
146      protected void runTestProfiled() throws Throwable {
# Line 142 | Line 156 | public class JSR166TestCase extends Test
156      }
157  
158      /**
159 <     * Runs all JSR166 unit tests using junit.textui.TestRunner
159 >     * Runs all JSR166 unit tests using junit.textui.TestRunner.
160 >     * Optional command line arg provides the number of iterations to
161 >     * repeat running the tests.
162       */
163      public static void main(String[] args) {
164          if (useSecurityManager) {
# Line 174 | Line 190 | public class JSR166TestCase extends Test
190          return suite;
191      }
192  
193 +    public static void addNamedTestClasses(TestSuite suite,
194 +                                           String... testClassNames) {
195 +        for (String testClassName : testClassNames) {
196 +            try {
197 +                Class<?> testClass = Class.forName(testClassName);
198 +                Method m = testClass.getDeclaredMethod("suite",
199 +                                                       new Class<?>[0]);
200 +                suite.addTest(newTestSuite((Test)m.invoke(null)));
201 +            } catch (Exception e) {
202 +                throw new Error("Missing test class", e);
203 +            }
204 +        }
205 +    }
206 +
207 +    public static final double JAVA_CLASS_VERSION;
208 +    static {
209 +        try {
210 +            JAVA_CLASS_VERSION = java.security.AccessController.doPrivileged(
211 +                new java.security.PrivilegedAction<Double>() {
212 +                public Double run() {
213 +                    return Double.valueOf(System.getProperty("java.class.version"));}});
214 +        } catch (Throwable t) {
215 +            throw new Error(t);
216 +        }
217 +    }
218 +
219 +    public static boolean atLeastJava6() { return JAVA_CLASS_VERSION >= 50.0; }
220 +    public static boolean atLeastJava7() { return JAVA_CLASS_VERSION >= 51.0; }
221 +    public static boolean atLeastJava8() { return JAVA_CLASS_VERSION >= 52.0; }
222 +
223      /**
224       * Collects all JSR166 unit tests as one suite.
225       */
226      public static Test suite() {
227 <        return newTestSuite(
227 >        // Java7+ test classes
228 >        TestSuite suite = newTestSuite(
229              ForkJoinPoolTest.suite(),
230              ForkJoinTaskTest.suite(),
231              RecursiveActionTest.suite(),
# Line 243 | Line 290 | public class JSR166TestCase extends Test
290              TreeSetTest.suite(),
291              TreeSubMapTest.suite(),
292              TreeSubSetTest.suite());
293 +
294 +        // Java8+ test classes
295 +        if (atLeastJava8()) {
296 +            String[] java8TestClassNames = {
297 +                "CompletableFutureTest",
298 +                "ConcurrentHashMap8Test",
299 +                "CountedCompleterTest",
300 +                "DoubleAccumulatorTest",
301 +                "DoubleAdderTest",
302 +                "ForkJoinPool8Test",
303 +                "ForkJoinTask8Test",
304 +                "LongAccumulatorTest",
305 +                "LongAdderTest",
306 +                "SplittableRandomTest",
307 +                "StampedLockTest",
308 +            };
309 +            addNamedTestClasses(suite, java8TestClassNames);
310 +        }
311 +
312 +        return suite;
313      }
314  
315 +    // Delays for timing-dependent tests, in milliseconds.
316  
317      public static long SHORT_DELAY_MS;
318      public static long SMALL_DELAY_MS;
319      public static long MEDIUM_DELAY_MS;
320      public static long LONG_DELAY_MS;
321  
254
322      /**
323       * Returns the shortest timed delay. This could
324       * be reimplemented to use for example a Property.
# Line 334 | Line 401 | public class JSR166TestCase extends Test
401  
402          if (Thread.interrupted())
403              throw new AssertionFailedError("interrupt status set in main thread");
404 +
405 +        checkForkJoinPoolThreadLeaks();
406 +    }
407 +
408 +    /**
409 +     * Find missing try { ... } finally { joinPool(e); }
410 +     */
411 +    void checkForkJoinPoolThreadLeaks() throws InterruptedException {
412 +        Thread[] survivors = new Thread[5];
413 +        int count = Thread.enumerate(survivors);
414 +        for (int i = 0; i < count; i++) {
415 +            Thread thread = survivors[i];
416 +            String name = thread.getName();
417 +            if (name.startsWith("ForkJoinPool-")) {
418 +                // give thread some time to terminate
419 +                thread.join(LONG_DELAY_MS);
420 +                if (!thread.isAlive()) continue;
421 +                thread.stop();
422 +                throw new AssertionFailedError
423 +                    (String.format("Found leaked ForkJoinPool thread test=%s thread=%s%n",
424 +                                   toString(), name));
425 +            }
426 +        }
427      }
428  
429      /**
# Line 507 | Line 597 | public class JSR166TestCase extends Test
597      }
598  
599      /**
600 +     * A debugging tool to print all stack traces, as jstack does.
601 +     */
602 +    static void printAllStackTraces() {
603 +        for (ThreadInfo info :
604 +                 ManagementFactory.getThreadMXBean()
605 +                 .dumpAllThreads(true, true))
606 +            System.err.print(info);
607 +    }
608 +
609 +    /**
610       * Checks that thread does not terminate within the default
611       * millisecond delay of {@code timeoutMillis()}.
612       */
# Line 528 | Line 628 | public class JSR166TestCase extends Test
628      }
629  
630      /**
631 +     * Checks that the threads do not terminate within the default
632 +     * millisecond delay of {@code timeoutMillis()}.
633 +     */
634 +    void assertThreadsStayAlive(Thread... threads) {
635 +        assertThreadsStayAlive(timeoutMillis(), threads);
636 +    }
637 +
638 +    /**
639 +     * Checks that the threads do not terminate within the given millisecond delay.
640 +     */
641 +    void assertThreadsStayAlive(long millis, Thread... threads) {
642 +        try {
643 +            // No need to optimize the failing case via Thread.join.
644 +            delay(millis);
645 +            for (Thread thread : threads)
646 +                assertTrue(thread.isAlive());
647 +        } catch (InterruptedException ie) {
648 +            fail("Unexpected InterruptedException");
649 +        }
650 +    }
651 +
652 +    /**
653       * Checks that future.get times out, with the default timeout of
654       * {@code timeoutMillis()}.
655       */
# Line 589 | Line 711 | public class JSR166TestCase extends Test
711      public static final Integer m6  = new Integer(-6);
712      public static final Integer m10 = new Integer(-10);
713  
592
714      /**
715       * Runs Runnable r with a security policy that permits precisely
716       * the specified permissions.  If there is no current security
# Line 601 | Line 722 | public class JSR166TestCase extends Test
722          SecurityManager sm = System.getSecurityManager();
723          if (sm == null) {
724              r.run();
725 +        }
726 +        runWithSecurityManagerWithPermissions(r, permissions);
727 +    }
728 +
729 +    /**
730 +     * Runs Runnable r with a security policy that permits precisely
731 +     * the specified permissions.  If there is no current security
732 +     * manager, a temporary one is set for the duration of the
733 +     * Runnable.  We require that any security manager permit
734 +     * getPolicy/setPolicy.
735 +     */
736 +    public void runWithSecurityManagerWithPermissions(Runnable r,
737 +                                                      Permission... permissions) {
738 +        SecurityManager sm = System.getSecurityManager();
739 +        if (sm == null) {
740              Policy savedPolicy = Policy.getPolicy();
741              try {
742                  Policy.setPolicy(permissivePolicy());
743                  System.setSecurityManager(new SecurityManager());
744 <                runWithPermissions(r, permissions);
744 >                runWithSecurityManagerWithPermissions(r, permissions);
745              } finally {
746                  System.setSecurityManager(null);
747                  Policy.setPolicy(savedPolicy);
# Line 653 | Line 789 | public class JSR166TestCase extends Test
789              return perms.implies(p);
790          }
791          public void refresh() {}
792 +        public String toString() {
793 +            List<Permission> ps = new ArrayList<Permission>();
794 +            for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
795 +                ps.add(e.nextElement());
796 +            return "AdjustablePolicy with permissions " + ps;
797 +        }
798      }
799  
800      /**
# Line 690 | Line 832 | public class JSR166TestCase extends Test
832      }
833  
834      /**
835 <     * Waits up to the specified number of milliseconds for the given
835 >     * Spin-waits up to the specified number of milliseconds for the given
836       * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
837       */
838      void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
839 <        long timeoutNanos = timeoutMillis * 1000L * 1000L;
698 <        long t0 = System.nanoTime();
839 >        long startTime = System.nanoTime();
840          for (;;) {
841              Thread.State s = thread.getState();
842              if (s == Thread.State.BLOCKED ||
# Line 704 | Line 845 | public class JSR166TestCase extends Test
845                  return;
846              else if (s == Thread.State.TERMINATED)
847                  fail("Unexpected thread termination");
848 <            else if (System.nanoTime() - t0 > timeoutNanos) {
848 >            else if (millisElapsedSince(startTime) > timeoutMillis) {
849                  threadAssertTrue(thread.isAlive());
850                  return;
851              }
# Line 905 | Line 1046 | public class JSR166TestCase extends Test
1046          }
1047      }
1048  
1049 +    public void await(Semaphore semaphore) {
1050 +        try {
1051 +            assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
1052 +        } catch (Throwable t) {
1053 +            threadUnexpectedException(t);
1054 +        }
1055 +    }
1056 +
1057   //     /**
1058   //      * Spin-waits up to LONG_DELAY_MS until flag becomes true.
1059   //      */
# Line 1092 | Line 1241 | public class JSR166TestCase extends Test
1241      public abstract class CheckedRecursiveAction extends RecursiveAction {
1242          protected abstract void realCompute() throws Throwable;
1243  
1244 <        public final void compute() {
1244 >        @Override protected final void compute() {
1245              try {
1246                  realCompute();
1247              } catch (Throwable t) {
# Line 1107 | Line 1256 | public class JSR166TestCase extends Test
1256      public abstract class CheckedRecursiveTask<T> extends RecursiveTask<T> {
1257          protected abstract T realCompute() throws Throwable;
1258  
1259 <        public final T compute() {
1259 >        @Override protected final T compute() {
1260              try {
1261                  return realCompute();
1262              } catch (Throwable t) {
# Line 1173 | Line 1322 | public class JSR166TestCase extends Test
1322          }
1323      }
1324  
1325 <    @SuppressWarnings("unchecked")
1326 <    <T> T serialClone(T o) {
1325 >    void assertSerialEquals(Object x, Object y) {
1326 >        assertTrue(Arrays.equals(serialBytes(x), serialBytes(y)));
1327 >    }
1328 >
1329 >    void assertNotSerialEquals(Object x, Object y) {
1330 >        assertFalse(Arrays.equals(serialBytes(x), serialBytes(y)));
1331 >    }
1332 >
1333 >    byte[] serialBytes(Object o) {
1334          try {
1335              ByteArrayOutputStream bos = new ByteArrayOutputStream();
1336              ObjectOutputStream oos = new ObjectOutputStream(bos);
1337              oos.writeObject(o);
1338              oos.flush();
1339              oos.close();
1340 <            ByteArrayInputStream bin =
1341 <                new ByteArrayInputStream(bos.toByteArray());
1342 <            ObjectInputStream ois = new ObjectInputStream(bin);
1343 <            return (T) ois.readObject();
1340 >            return bos.toByteArray();
1341 >        } catch (Throwable t) {
1342 >            threadUnexpectedException(t);
1343 >            return new byte[0];
1344 >        }
1345 >    }
1346 >
1347 >    @SuppressWarnings("unchecked")
1348 >    <T> T serialClone(T o) {
1349 >        try {
1350 >            ObjectInputStream ois = new ObjectInputStream
1351 >                (new ByteArrayInputStream(serialBytes(o)));
1352 >            T clone = (T) ois.readObject();
1353 >            assertSame(o.getClass(), clone.getClass());
1354 >            return clone;
1355          } catch (Throwable t) {
1356              threadUnexpectedException(t);
1357              return null;
1358          }
1359      }
1360 +
1361 +    public void assertThrows(Class<? extends Throwable> expectedExceptionClass,
1362 +                             Runnable... throwingActions) {
1363 +        for (Runnable throwingAction : throwingActions) {
1364 +            boolean threw = false;
1365 +            try { throwingAction.run(); }
1366 +            catch (Throwable t) {
1367 +                threw = true;
1368 +                if (!expectedExceptionClass.isInstance(t)) {
1369 +                    AssertionFailedError afe =
1370 +                        new AssertionFailedError
1371 +                        ("Expected " + expectedExceptionClass.getName() +
1372 +                         ", got " + t.getClass().getName());
1373 +                    afe.initCause(t);
1374 +                    threadUnexpectedException(afe);
1375 +                }
1376 +            }
1377 +            if (!threw)
1378 +                shouldThrow(expectedExceptionClass.getName());
1379 +        }
1380 +    }
1381   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines