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.118 by jsr166, Mon Jun 16 18:01:38 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.*;
# 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 108 | Line 115 | public class JSR166TestCase extends Test
115      protected static final boolean expensiveTests =
116          Boolean.getBoolean("jsr166.expensiveTests");
117  
118 +    protected static final boolean testImplementationDetails =
119 +        Boolean.getBoolean("jsr166.testImplementationDetails");
120 +
121      /**
122       * If true, report on stdout all "slow" tests, that is, ones that
123       * take more than profileThreshold milliseconds to execute.
# Line 122 | Line 132 | public class JSR166TestCase extends Test
132      private static final long profileThreshold =
133          Long.getLong("jsr166.profileThreshold", 100);
134  
135 +    /**
136 +     * The number of repetitions per test (for tickling rare bugs).
137 +     */
138 +    private static final int runsPerTest =
139 +        Integer.getInteger("jsr166.runsPerTest", 1);
140 +
141 +    /**
142 +     * A filter for tests to run, matching strings of the form
143 +     * methodName(className), e.g. "testInvokeAll5(ForkJoinPoolTest)"
144 +     * Usefully combined with jsr166.runsPerTest.
145 +     */
146 +    private static final Pattern methodFilter = methodFilter();
147 +
148 +    private static Pattern methodFilter() {
149 +        String regex = System.getProperty("jsr166.methodFilter");
150 +        return (regex == null) ? null : Pattern.compile(regex);
151 +    }
152 +
153      protected void runTest() throws Throwable {
154 <        if (profileTests)
155 <            runTestProfiled();
156 <        else
157 <            super.runTest();
154 >        if (methodFilter == null
155 >            || methodFilter.matcher(toString()).find()) {
156 >            for (int i = 0; i < runsPerTest; i++) {
157 >                if (profileTests)
158 >                    runTestProfiled();
159 >                else
160 >                    super.runTest();
161 >            }
162 >        }
163      }
164  
165      protected void runTestProfiled() throws Throwable {
166 +        // Warmup run, notably to trigger all needed classloading.
167 +        super.runTest();
168          long t0 = System.nanoTime();
169          try {
170              super.runTest();
171          } finally {
172 <            long elapsedMillis =
138 <                (System.nanoTime() - t0) / (1000L * 1000L);
172 >            long elapsedMillis = millisElapsedSince(t0);
173              if (elapsedMillis >= profileThreshold)
174                  System.out.printf("%n%s: %d%n", toString(), elapsedMillis);
175          }
176      }
177  
178      /**
179 <     * Runs all JSR166 unit tests using junit.textui.TestRunner
179 >     * Runs all JSR166 unit tests using junit.textui.TestRunner.
180 >     * Optional command line arg provides the number of iterations to
181 >     * repeat running the tests.
182       */
183      public static void main(String[] args) {
184          if (useSecurityManager) {
# Line 174 | Line 210 | public class JSR166TestCase extends Test
210          return suite;
211      }
212  
213 +    public static void addNamedTestClasses(TestSuite suite,
214 +                                           String... testClassNames) {
215 +        for (String testClassName : testClassNames) {
216 +            try {
217 +                Class<?> testClass = Class.forName(testClassName);
218 +                Method m = testClass.getDeclaredMethod("suite",
219 +                                                       new Class<?>[0]);
220 +                suite.addTest(newTestSuite((Test)m.invoke(null)));
221 +            } catch (Exception e) {
222 +                throw new Error("Missing test class", e);
223 +            }
224 +        }
225 +    }
226 +
227 +    public static final double JAVA_CLASS_VERSION;
228 +    public static final String JAVA_SPECIFICATION_VERSION;
229 +    static {
230 +        try {
231 +            JAVA_CLASS_VERSION = java.security.AccessController.doPrivileged(
232 +                new java.security.PrivilegedAction<Double>() {
233 +                public Double run() {
234 +                    return Double.valueOf(System.getProperty("java.class.version"));}});
235 +            JAVA_SPECIFICATION_VERSION = java.security.AccessController.doPrivileged(
236 +                new java.security.PrivilegedAction<String>() {
237 +                public String run() {
238 +                    return System.getProperty("java.specification.version");}});
239 +        } catch (Throwable t) {
240 +            throw new Error(t);
241 +        }
242 +    }
243 +
244 +    public static boolean atLeastJava6() { return JAVA_CLASS_VERSION >= 50.0; }
245 +    public static boolean atLeastJava7() { return JAVA_CLASS_VERSION >= 51.0; }
246 +    public static boolean atLeastJava8() { return JAVA_CLASS_VERSION >= 52.0; }
247 +    public static boolean atLeastJava9() {
248 +        // As of 2014-05, java9 still uses 52.0 class file version
249 +        return JAVA_SPECIFICATION_VERSION.startsWith("1.9");
250 +    }
251 +
252      /**
253       * Collects all JSR166 unit tests as one suite.
254       */
255      public static Test suite() {
256 <        return newTestSuite(
256 >        // Java7+ test classes
257 >        TestSuite suite = newTestSuite(
258              ForkJoinPoolTest.suite(),
259              ForkJoinTaskTest.suite(),
260              RecursiveActionTest.suite(),
# Line 243 | Line 319 | public class JSR166TestCase extends Test
319              TreeSetTest.suite(),
320              TreeSubMapTest.suite(),
321              TreeSubSetTest.suite());
322 +
323 +        // Java8+ test classes
324 +        if (atLeastJava8()) {
325 +            String[] java8TestClassNames = {
326 +                "Atomic8Test",
327 +                "CompletableFutureTest",
328 +                "ConcurrentHashMap8Test",
329 +                "CountedCompleterTest",
330 +                "DoubleAccumulatorTest",
331 +                "DoubleAdderTest",
332 +                "ForkJoinPool8Test",
333 +                "ForkJoinTask8Test",
334 +                "LongAccumulatorTest",
335 +                "LongAdderTest",
336 +                "SplittableRandomTest",
337 +                "StampedLockTest",
338 +                "ThreadLocalRandom8Test",
339 +            };
340 +            addNamedTestClasses(suite, java8TestClassNames);
341 +        }
342 +
343 +        // Java9+ test classes
344 +        if (atLeastJava9()) {
345 +            String[] java9TestClassNames = {
346 +                "ThreadPoolExecutor9Test",
347 +            };
348 +            addNamedTestClasses(suite, java9TestClassNames);
349 +        }
350 +
351 +        return suite;
352      }
353  
354 +    // Delays for timing-dependent tests, in milliseconds.
355  
356      public static long SHORT_DELAY_MS;
357      public static long SMALL_DELAY_MS;
358      public static long MEDIUM_DELAY_MS;
359      public static long LONG_DELAY_MS;
360  
254
361      /**
362       * Returns the shortest timed delay. This could
363       * be reimplemented to use for example a Property.
# Line 334 | Line 440 | public class JSR166TestCase extends Test
440  
441          if (Thread.interrupted())
442              throw new AssertionFailedError("interrupt status set in main thread");
443 +
444 +        checkForkJoinPoolThreadLeaks();
445 +    }
446 +
447 +    /**
448 +     * Find missing try { ... } finally { joinPool(e); }
449 +     */
450 +    void checkForkJoinPoolThreadLeaks() throws InterruptedException {
451 +        Thread[] survivors = new Thread[5];
452 +        int count = Thread.enumerate(survivors);
453 +        for (int i = 0; i < count; i++) {
454 +            Thread thread = survivors[i];
455 +            String name = thread.getName();
456 +            if (name.startsWith("ForkJoinPool-")) {
457 +                // give thread some time to terminate
458 +                thread.join(LONG_DELAY_MS);
459 +                if (!thread.isAlive()) continue;
460 +                thread.stop();
461 +                throw new AssertionFailedError
462 +                    (String.format("Found leaked ForkJoinPool thread test=%s thread=%s%n",
463 +                                   toString(), name));
464 +            }
465 +        }
466      }
467  
468      /**
# Line 507 | Line 636 | public class JSR166TestCase extends Test
636      }
637  
638      /**
639 +     * A debugging tool to print all stack traces, as jstack does.
640 +     */
641 +    static void printAllStackTraces() {
642 +        for (ThreadInfo info :
643 +                 ManagementFactory.getThreadMXBean()
644 +                 .dumpAllThreads(true, true))
645 +            System.err.print(info);
646 +    }
647 +
648 +    /**
649       * Checks that thread does not terminate within the default
650       * millisecond delay of {@code timeoutMillis()}.
651       */
# Line 528 | Line 667 | public class JSR166TestCase extends Test
667      }
668  
669      /**
670 +     * Checks that the threads do not terminate within the default
671 +     * millisecond delay of {@code timeoutMillis()}.
672 +     */
673 +    void assertThreadsStayAlive(Thread... threads) {
674 +        assertThreadsStayAlive(timeoutMillis(), threads);
675 +    }
676 +
677 +    /**
678 +     * Checks that the threads do not terminate within the given millisecond delay.
679 +     */
680 +    void assertThreadsStayAlive(long millis, Thread... threads) {
681 +        try {
682 +            // No need to optimize the failing case via Thread.join.
683 +            delay(millis);
684 +            for (Thread thread : threads)
685 +                assertTrue(thread.isAlive());
686 +        } catch (InterruptedException ie) {
687 +            fail("Unexpected InterruptedException");
688 +        }
689 +    }
690 +
691 +    /**
692       * Checks that future.get times out, with the default timeout of
693       * {@code timeoutMillis()}.
694       */
# Line 589 | Line 750 | public class JSR166TestCase extends Test
750      public static final Integer m6  = new Integer(-6);
751      public static final Integer m10 = new Integer(-10);
752  
592
753      /**
754       * Runs Runnable r with a security policy that permits precisely
755       * the specified permissions.  If there is no current security
# Line 601 | Line 761 | public class JSR166TestCase extends Test
761          SecurityManager sm = System.getSecurityManager();
762          if (sm == null) {
763              r.run();
764 +        }
765 +        runWithSecurityManagerWithPermissions(r, permissions);
766 +    }
767 +
768 +    /**
769 +     * Runs Runnable r with a security policy that permits precisely
770 +     * the specified permissions.  If there is no current security
771 +     * manager, a temporary one is set for the duration of the
772 +     * Runnable.  We require that any security manager permit
773 +     * getPolicy/setPolicy.
774 +     */
775 +    public void runWithSecurityManagerWithPermissions(Runnable r,
776 +                                                      Permission... permissions) {
777 +        SecurityManager sm = System.getSecurityManager();
778 +        if (sm == null) {
779              Policy savedPolicy = Policy.getPolicy();
780              try {
781                  Policy.setPolicy(permissivePolicy());
782                  System.setSecurityManager(new SecurityManager());
783 <                runWithPermissions(r, permissions);
783 >                runWithSecurityManagerWithPermissions(r, permissions);
784              } finally {
785                  System.setSecurityManager(null);
786                  Policy.setPolicy(savedPolicy);
# Line 653 | Line 828 | public class JSR166TestCase extends Test
828              return perms.implies(p);
829          }
830          public void refresh() {}
831 +        public String toString() {
832 +            List<Permission> ps = new ArrayList<Permission>();
833 +            for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
834 +                ps.add(e.nextElement());
835 +            return "AdjustablePolicy with permissions " + ps;
836 +        }
837      }
838  
839      /**
# Line 690 | Line 871 | public class JSR166TestCase extends Test
871      }
872  
873      /**
874 <     * Waits up to the specified number of milliseconds for the given
874 >     * Spin-waits up to the specified number of milliseconds for the given
875       * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
876       */
877      void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
878 <        long timeoutNanos = timeoutMillis * 1000L * 1000L;
698 <        long t0 = System.nanoTime();
878 >        long startTime = System.nanoTime();
879          for (;;) {
880              Thread.State s = thread.getState();
881              if (s == Thread.State.BLOCKED ||
# Line 704 | Line 884 | public class JSR166TestCase extends Test
884                  return;
885              else if (s == Thread.State.TERMINATED)
886                  fail("Unexpected thread termination");
887 <            else if (System.nanoTime() - t0 > timeoutNanos) {
887 >            else if (millisElapsedSince(startTime) > timeoutMillis) {
888                  threadAssertTrue(thread.isAlive());
889                  return;
890              }
# Line 725 | Line 905 | public class JSR166TestCase extends Test
905       * startNanoTime, which must have been previously returned from a
906       * call to {@link System.nanoTime()}.
907       */
908 <    long millisElapsedSince(long startNanoTime) {
908 >    static long millisElapsedSince(long startNanoTime) {
909          return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
910      }
911  
# Line 905 | Line 1085 | public class JSR166TestCase extends Test
1085          }
1086      }
1087  
1088 +    public void await(Semaphore semaphore) {
1089 +        try {
1090 +            assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
1091 +        } catch (Throwable t) {
1092 +            threadUnexpectedException(t);
1093 +        }
1094 +    }
1095 +
1096   //     /**
1097   //      * Spin-waits up to LONG_DELAY_MS until flag becomes true.
1098   //      */
# Line 1092 | Line 1280 | public class JSR166TestCase extends Test
1280      public abstract class CheckedRecursiveAction extends RecursiveAction {
1281          protected abstract void realCompute() throws Throwable;
1282  
1283 <        public final void compute() {
1283 >        @Override protected final void compute() {
1284              try {
1285                  realCompute();
1286              } catch (Throwable t) {
# Line 1107 | Line 1295 | public class JSR166TestCase extends Test
1295      public abstract class CheckedRecursiveTask<T> extends RecursiveTask<T> {
1296          protected abstract T realCompute() throws Throwable;
1297  
1298 <        public final T compute() {
1298 >        @Override protected final T compute() {
1299              try {
1300                  return realCompute();
1301              } catch (Throwable t) {
# Line 1173 | Line 1361 | public class JSR166TestCase extends Test
1361          }
1362      }
1363  
1364 <    @SuppressWarnings("unchecked")
1365 <    <T> T serialClone(T o) {
1364 >    void assertSerialEquals(Object x, Object y) {
1365 >        assertTrue(Arrays.equals(serialBytes(x), serialBytes(y)));
1366 >    }
1367 >
1368 >    void assertNotSerialEquals(Object x, Object y) {
1369 >        assertFalse(Arrays.equals(serialBytes(x), serialBytes(y)));
1370 >    }
1371 >
1372 >    byte[] serialBytes(Object o) {
1373          try {
1374              ByteArrayOutputStream bos = new ByteArrayOutputStream();
1375              ObjectOutputStream oos = new ObjectOutputStream(bos);
1376              oos.writeObject(o);
1377              oos.flush();
1378              oos.close();
1379 +            return bos.toByteArray();
1380 +        } catch (Throwable t) {
1381 +            threadUnexpectedException(t);
1382 +            return new byte[0];
1383 +        }
1384 +    }
1385 +
1386 +    @SuppressWarnings("unchecked")
1387 +    <T> T serialClone(T o) {
1388 +        try {
1389              ObjectInputStream ois = new ObjectInputStream
1390 <                (new ByteArrayInputStream(bos.toByteArray()));
1390 >                (new ByteArrayInputStream(serialBytes(o)));
1391              T clone = (T) ois.readObject();
1392              assertSame(o.getClass(), clone.getClass());
1393              return clone;
# Line 1191 | Line 1396 | public class JSR166TestCase extends Test
1396              return null;
1397          }
1398      }
1399 +
1400 +    public void assertThrows(Class<? extends Throwable> expectedExceptionClass,
1401 +                             Runnable... throwingActions) {
1402 +        for (Runnable throwingAction : throwingActions) {
1403 +            boolean threw = false;
1404 +            try { throwingAction.run(); }
1405 +            catch (Throwable t) {
1406 +                threw = true;
1407 +                if (!expectedExceptionClass.isInstance(t)) {
1408 +                    AssertionFailedError afe =
1409 +                        new AssertionFailedError
1410 +                        ("Expected " + expectedExceptionClass.getName() +
1411 +                         ", got " + t.getClass().getName());
1412 +                    afe.initCause(t);
1413 +                    threadUnexpectedException(afe);
1414 +                }
1415 +            }
1416 +            if (!threw)
1417 +                shouldThrow(expectedExceptionClass.getName());
1418 +        }
1419 +    }
1420   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines