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.87 by jsr166, Mon May 30 22:53:21 2011 UTC vs.
Revision 1.122 by jsr166, Wed Dec 31 16:44:02 2014 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.*;
19 import java.util.concurrent.atomic.AtomicBoolean;
25   import java.util.concurrent.atomic.AtomicReference;
26   import static java.util.concurrent.TimeUnit.MILLISECONDS;
27   import static java.util.concurrent.TimeUnit.NANOSECONDS;
28 + import java.util.regex.Pattern;
29   import java.security.CodeSource;
30   import java.security.Permission;
31   import java.security.PermissionCollection;
# 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 109 | Line 115 | public class JSR166TestCase extends Test
115          Boolean.getBoolean("jsr166.expensiveTests");
116  
117      /**
118 +     * If true, also run tests that are not part of the official tck
119 +     * because they test unspecified implementation details.
120 +     */
121 +    protected static final boolean testImplementationDetails =
122 +        Boolean.getBoolean("jsr166.testImplementationDetails");
123 +
124 +    /**
125       * If true, report on stdout all "slow" tests, that is, ones that
126       * take more than profileThreshold milliseconds to execute.
127       */
# Line 122 | Line 135 | public class JSR166TestCase extends Test
135      private static final long profileThreshold =
136          Long.getLong("jsr166.profileThreshold", 100);
137  
138 +    /**
139 +     * The number of repetitions per test (for tickling rare bugs).
140 +     */
141 +    private static final int runsPerTest =
142 +        Integer.getInteger("jsr166.runsPerTest", 1);
143 +
144 +    /**
145 +     * A filter for tests to run, matching strings of the form
146 +     * methodName(className), e.g. "testInvokeAll5(ForkJoinPoolTest)"
147 +     * Usefully combined with jsr166.runsPerTest.
148 +     */
149 +    private static final Pattern methodFilter = methodFilter();
150 +
151 +    private static Pattern methodFilter() {
152 +        String regex = System.getProperty("jsr166.methodFilter");
153 +        return (regex == null) ? null : Pattern.compile(regex);
154 +    }
155 +
156      protected void runTest() throws Throwable {
157 <        if (profileTests)
158 <            runTestProfiled();
159 <        else
160 <            super.runTest();
157 >        if (methodFilter == null
158 >            || methodFilter.matcher(toString()).find()) {
159 >            for (int i = 0; i < runsPerTest; i++) {
160 >                if (profileTests)
161 >                    runTestProfiled();
162 >                else
163 >                    super.runTest();
164 >            }
165 >        }
166      }
167  
168      protected void runTestProfiled() throws Throwable {
169 +        // Warmup run, notably to trigger all needed classloading.
170 +        super.runTest();
171          long t0 = System.nanoTime();
172          try {
173              super.runTest();
174          } finally {
175 <            long elapsedMillis =
138 <                (System.nanoTime() - t0) / (1000L * 1000L);
175 >            long elapsedMillis = millisElapsedSince(t0);
176              if (elapsedMillis >= profileThreshold)
177                  System.out.printf("%n%s: %d%n", toString(), elapsedMillis);
178          }
179      }
180  
181      /**
182 <     * Runs all JSR166 unit tests using junit.textui.TestRunner
182 >     * Runs all JSR166 unit tests using junit.textui.TestRunner.
183 >     * Optional command line arg provides the number of iterations to
184 >     * repeat running the tests.
185       */
186      public static void main(String[] args) {
187          if (useSecurityManager) {
# Line 174 | Line 213 | public class JSR166TestCase extends Test
213          return suite;
214      }
215  
216 +    public static void addNamedTestClasses(TestSuite suite,
217 +                                           String... testClassNames) {
218 +        for (String testClassName : testClassNames) {
219 +            try {
220 +                Class<?> testClass = Class.forName(testClassName);
221 +                Method m = testClass.getDeclaredMethod("suite",
222 +                                                       new Class<?>[0]);
223 +                suite.addTest(newTestSuite((Test)m.invoke(null)));
224 +            } catch (Exception e) {
225 +                throw new Error("Missing test class", e);
226 +            }
227 +        }
228 +    }
229 +
230 +    public static final double JAVA_CLASS_VERSION;
231 +    public static final String JAVA_SPECIFICATION_VERSION;
232 +    static {
233 +        try {
234 +            JAVA_CLASS_VERSION = java.security.AccessController.doPrivileged(
235 +                new java.security.PrivilegedAction<Double>() {
236 +                public Double run() {
237 +                    return Double.valueOf(System.getProperty("java.class.version"));}});
238 +            JAVA_SPECIFICATION_VERSION = java.security.AccessController.doPrivileged(
239 +                new java.security.PrivilegedAction<String>() {
240 +                public String run() {
241 +                    return System.getProperty("java.specification.version");}});
242 +        } catch (Throwable t) {
243 +            throw new Error(t);
244 +        }
245 +    }
246 +
247 +    public static boolean atLeastJava6() { return JAVA_CLASS_VERSION >= 50.0; }
248 +    public static boolean atLeastJava7() { return JAVA_CLASS_VERSION >= 51.0; }
249 +    public static boolean atLeastJava8() { return JAVA_CLASS_VERSION >= 52.0; }
250 +    public static boolean atLeastJava9() {
251 +        // As of 2014-05, java9 still uses 52.0 class file version
252 +        return JAVA_SPECIFICATION_VERSION.startsWith("1.9");
253 +    }
254 +
255      /**
256       * Collects all JSR166 unit tests as one suite.
257       */
258      public static Test suite() {
259 <        return newTestSuite(
259 >        // Java7+ test classes
260 >        TestSuite suite = newTestSuite(
261              ForkJoinPoolTest.suite(),
262              ForkJoinTaskTest.suite(),
263              RecursiveActionTest.suite(),
# Line 243 | Line 322 | public class JSR166TestCase extends Test
322              TreeSetTest.suite(),
323              TreeSubMapTest.suite(),
324              TreeSubSetTest.suite());
325 +
326 +        // Java8+ test classes
327 +        if (atLeastJava8()) {
328 +            String[] java8TestClassNames = {
329 +                "Atomic8Test",
330 +                "CompletableFutureTest",
331 +                "ConcurrentHashMap8Test",
332 +                "CountedCompleterTest",
333 +                "DoubleAccumulatorTest",
334 +                "DoubleAdderTest",
335 +                "ForkJoinPool8Test",
336 +                "ForkJoinTask8Test",
337 +                "LongAccumulatorTest",
338 +                "LongAdderTest",
339 +                "SplittableRandomTest",
340 +                "StampedLockTest",
341 +                "ThreadLocalRandom8Test",
342 +            };
343 +            addNamedTestClasses(suite, java8TestClassNames);
344 +        }
345 +
346 +        // Java9+ test classes
347 +        if (atLeastJava9()) {
348 +            String[] java9TestClassNames = {
349 +                "ThreadPoolExecutor9Test",
350 +            };
351 +            addNamedTestClasses(suite, java9TestClassNames);
352 +        }
353 +
354 +        return suite;
355      }
356  
357 +    // Delays for timing-dependent tests, in milliseconds.
358  
359      public static long SHORT_DELAY_MS;
360      public static long SMALL_DELAY_MS;
361      public static long MEDIUM_DELAY_MS;
362      public static long LONG_DELAY_MS;
363  
254
364      /**
365       * Returns the shortest timed delay. This could
366       * be reimplemented to use for example a Property.
# Line 334 | Line 443 | public class JSR166TestCase extends Test
443  
444          if (Thread.interrupted())
445              throw new AssertionFailedError("interrupt status set in main thread");
446 +
447 +        checkForkJoinPoolThreadLeaks();
448 +    }
449 +
450 +    /**
451 +     * Find missing try { ... } finally { joinPool(e); }
452 +     */
453 +    void checkForkJoinPoolThreadLeaks() throws InterruptedException {
454 +        Thread[] survivors = new Thread[5];
455 +        int count = Thread.enumerate(survivors);
456 +        for (int i = 0; i < count; i++) {
457 +            Thread thread = survivors[i];
458 +            String name = thread.getName();
459 +            if (name.startsWith("ForkJoinPool-")) {
460 +                // give thread some time to terminate
461 +                thread.join(LONG_DELAY_MS);
462 +                if (!thread.isAlive()) continue;
463 +                thread.stop();
464 +                throw new AssertionFailedError
465 +                    (String.format("Found leaked ForkJoinPool thread test=%s thread=%s%n",
466 +                                   toString(), name));
467 +            }
468 +        }
469      }
470  
471      /**
# Line 497 | Line 629 | public class JSR166TestCase extends Test
629      void joinPool(ExecutorService exec) {
630          try {
631              exec.shutdown();
632 <            assertTrue("ExecutorService did not terminate in a timely manner",
633 <                       exec.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS));
632 >            if (!exec.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS))
633 >                fail("ExecutorService " + exec +
634 >                     " did not terminate in a timely manner");
635          } catch (SecurityException ok) {
636              // Allowed in case test doesn't have privs
637          } catch (InterruptedException ie) {
# Line 507 | Line 640 | public class JSR166TestCase extends Test
640      }
641  
642      /**
643 +     * A debugging tool to print all stack traces, as jstack does.
644 +     */
645 +    static void printAllStackTraces() {
646 +        for (ThreadInfo info :
647 +                 ManagementFactory.getThreadMXBean()
648 +                 .dumpAllThreads(true, true))
649 +            System.err.print(info);
650 +    }
651 +
652 +    /**
653       * Checks that thread does not terminate within the default
654       * millisecond delay of {@code timeoutMillis()}.
655       */
# Line 528 | Line 671 | public class JSR166TestCase extends Test
671      }
672  
673      /**
674 +     * Checks that the threads do not terminate within the default
675 +     * millisecond delay of {@code timeoutMillis()}.
676 +     */
677 +    void assertThreadsStayAlive(Thread... threads) {
678 +        assertThreadsStayAlive(timeoutMillis(), threads);
679 +    }
680 +
681 +    /**
682 +     * Checks that the threads do not terminate within the given millisecond delay.
683 +     */
684 +    void assertThreadsStayAlive(long millis, Thread... threads) {
685 +        try {
686 +            // No need to optimize the failing case via Thread.join.
687 +            delay(millis);
688 +            for (Thread thread : threads)
689 +                assertTrue(thread.isAlive());
690 +        } catch (InterruptedException ie) {
691 +            fail("Unexpected InterruptedException");
692 +        }
693 +    }
694 +
695 +    /**
696       * Checks that future.get times out, with the default timeout of
697       * {@code timeoutMillis()}.
698       */
# Line 589 | Line 754 | public class JSR166TestCase extends Test
754      public static final Integer m6  = new Integer(-6);
755      public static final Integer m10 = new Integer(-10);
756  
592
757      /**
758       * Runs Runnable r with a security policy that permits precisely
759       * the specified permissions.  If there is no current security
# Line 601 | Line 765 | public class JSR166TestCase extends Test
765          SecurityManager sm = System.getSecurityManager();
766          if (sm == null) {
767              r.run();
768 +        }
769 +        runWithSecurityManagerWithPermissions(r, permissions);
770 +    }
771 +
772 +    /**
773 +     * Runs Runnable r with a security policy that permits precisely
774 +     * the specified permissions.  If there is no current security
775 +     * manager, a temporary one is set for the duration of the
776 +     * Runnable.  We require that any security manager permit
777 +     * getPolicy/setPolicy.
778 +     */
779 +    public void runWithSecurityManagerWithPermissions(Runnable r,
780 +                                                      Permission... permissions) {
781 +        SecurityManager sm = System.getSecurityManager();
782 +        if (sm == null) {
783              Policy savedPolicy = Policy.getPolicy();
784              try {
785                  Policy.setPolicy(permissivePolicy());
786                  System.setSecurityManager(new SecurityManager());
787 <                runWithPermissions(r, permissions);
787 >                runWithSecurityManagerWithPermissions(r, permissions);
788              } finally {
789                  System.setSecurityManager(null);
790                  Policy.setPolicy(savedPolicy);
# Line 653 | Line 832 | public class JSR166TestCase extends Test
832              return perms.implies(p);
833          }
834          public void refresh() {}
835 +        public String toString() {
836 +            List<Permission> ps = new ArrayList<Permission>();
837 +            for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
838 +                ps.add(e.nextElement());
839 +            return "AdjustablePolicy with permissions " + ps;
840 +        }
841      }
842  
843      /**
# Line 690 | Line 875 | public class JSR166TestCase extends Test
875      }
876  
877      /**
878 <     * Waits up to the specified number of milliseconds for the given
878 >     * Spin-waits up to the specified number of milliseconds for the given
879       * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
880       */
881      void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
882 <        long timeoutNanos = timeoutMillis * 1000L * 1000L;
698 <        long t0 = System.nanoTime();
882 >        long startTime = System.nanoTime();
883          for (;;) {
884              Thread.State s = thread.getState();
885              if (s == Thread.State.BLOCKED ||
# Line 704 | Line 888 | public class JSR166TestCase extends Test
888                  return;
889              else if (s == Thread.State.TERMINATED)
890                  fail("Unexpected thread termination");
891 <            else if (System.nanoTime() - t0 > timeoutNanos) {
891 >            else if (millisElapsedSince(startTime) > timeoutMillis) {
892                  threadAssertTrue(thread.isAlive());
893                  return;
894              }
# Line 725 | Line 909 | public class JSR166TestCase extends Test
909       * startNanoTime, which must have been previously returned from a
910       * call to {@link System.nanoTime()}.
911       */
912 <    long millisElapsedSince(long startNanoTime) {
912 >    static long millisElapsedSince(long startNanoTime) {
913          return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
914      }
915  
916 + //     void assertTerminatesPromptly(long timeoutMillis, Runnable r) {
917 + //         long startTime = System.nanoTime();
918 + //         try {
919 + //             r.run();
920 + //         } catch (Throwable fail) { threadUnexpectedException(fail); }
921 + //         if (millisElapsedSince(startTime) > timeoutMillis/2)
922 + //             throw new AssertionFailedError("did not return promptly");
923 + //     }
924 +
925 + //     void assertTerminatesPromptly(Runnable r) {
926 + //         assertTerminatesPromptly(LONG_DELAY_MS/2, r);
927 + //     }
928 +
929 +    /**
930 +     * Checks that timed f.get() returns the expected value, and does not
931 +     * wait for the timeout to elapse before returning.
932 +     */
933 +    <T> void checkTimedGet(Future<T> f, T expectedValue, long timeoutMillis) {
934 +        long startTime = System.nanoTime();
935 +        try {
936 +            assertEquals(expectedValue, f.get(timeoutMillis, MILLISECONDS));
937 +        } catch (Throwable fail) { threadUnexpectedException(fail); }
938 +        if (millisElapsedSince(startTime) > timeoutMillis/2)
939 +            throw new AssertionFailedError("timed get did not return promptly");
940 +    }
941 +
942 +    <T> void checkTimedGet(Future<T> f, T expectedValue) {
943 +        checkTimedGet(f, expectedValue, LONG_DELAY_MS);
944 +    }
945 +
946      /**
947       * Returns a new started daemon Thread running the given runnable.
948       */
# Line 905 | Line 1119 | public class JSR166TestCase extends Test
1119          }
1120      }
1121  
1122 +    public void await(Semaphore semaphore) {
1123 +        try {
1124 +            assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
1125 +        } catch (Throwable t) {
1126 +            threadUnexpectedException(t);
1127 +        }
1128 +    }
1129 +
1130   //     /**
1131   //      * Spin-waits up to LONG_DELAY_MS until flag becomes true.
1132   //      */
# Line 1092 | Line 1314 | public class JSR166TestCase extends Test
1314      public abstract class CheckedRecursiveAction extends RecursiveAction {
1315          protected abstract void realCompute() throws Throwable;
1316  
1317 <        public final void compute() {
1317 >        @Override protected final void compute() {
1318              try {
1319                  realCompute();
1320              } catch (Throwable t) {
# Line 1107 | Line 1329 | public class JSR166TestCase extends Test
1329      public abstract class CheckedRecursiveTask<T> extends RecursiveTask<T> {
1330          protected abstract T realCompute() throws Throwable;
1331  
1332 <        public final T compute() {
1332 >        @Override protected final T compute() {
1333              try {
1334                  return realCompute();
1335              } catch (Throwable t) {
# Line 1173 | Line 1395 | public class JSR166TestCase extends Test
1395          }
1396      }
1397  
1398 <    @SuppressWarnings("unchecked")
1399 <    <T> T serialClone(T o) {
1398 >    void assertSerialEquals(Object x, Object y) {
1399 >        assertTrue(Arrays.equals(serialBytes(x), serialBytes(y)));
1400 >    }
1401 >
1402 >    void assertNotSerialEquals(Object x, Object y) {
1403 >        assertFalse(Arrays.equals(serialBytes(x), serialBytes(y)));
1404 >    }
1405 >
1406 >    byte[] serialBytes(Object o) {
1407          try {
1408              ByteArrayOutputStream bos = new ByteArrayOutputStream();
1409              ObjectOutputStream oos = new ObjectOutputStream(bos);
1410              oos.writeObject(o);
1411              oos.flush();
1412              oos.close();
1413 +            return bos.toByteArray();
1414 +        } catch (Throwable t) {
1415 +            threadUnexpectedException(t);
1416 +            return new byte[0];
1417 +        }
1418 +    }
1419 +
1420 +    @SuppressWarnings("unchecked")
1421 +    <T> T serialClone(T o) {
1422 +        try {
1423              ObjectInputStream ois = new ObjectInputStream
1424 <                (new ByteArrayInputStream(bos.toByteArray()));
1424 >                (new ByteArrayInputStream(serialBytes(o)));
1425              T clone = (T) ois.readObject();
1426              assertSame(o.getClass(), clone.getClass());
1427              return clone;
# Line 1191 | Line 1430 | public class JSR166TestCase extends Test
1430              return null;
1431          }
1432      }
1433 +
1434 +    public void assertThrows(Class<? extends Throwable> expectedExceptionClass,
1435 +                             Runnable... throwingActions) {
1436 +        for (Runnable throwingAction : throwingActions) {
1437 +            boolean threw = false;
1438 +            try { throwingAction.run(); }
1439 +            catch (Throwable t) {
1440 +                threw = true;
1441 +                if (!expectedExceptionClass.isInstance(t)) {
1442 +                    AssertionFailedError afe =
1443 +                        new AssertionFailedError
1444 +                        ("Expected " + expectedExceptionClass.getName() +
1445 +                         ", got " + t.getClass().getName());
1446 +                    afe.initCause(t);
1447 +                    threadUnexpectedException(afe);
1448 +                }
1449 +            }
1450 +            if (!threw)
1451 +                shouldThrow(expectedExceptionClass.getName());
1452 +        }
1453 +    }
1454   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines