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.102 by jsr166, Wed Feb 6 19:55:06 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 142 | Line 148 | public class JSR166TestCase extends Test
148      }
149  
150      /**
151 <     * Runs all JSR166 unit tests using junit.textui.TestRunner
151 >     * Runs all JSR166 unit tests using junit.textui.TestRunner.
152 >     * Optional command line arg provides the number of iterations to
153 >     * repeat running the tests.
154       */
155      public static void main(String[] args) {
156          if (useSecurityManager) {
# Line 174 | Line 182 | public class JSR166TestCase extends Test
182          return suite;
183      }
184  
185 +    public static void addNamedTestClasses(TestSuite suite,
186 +                                           String... testClassNames) {
187 +        for (String testClassName : testClassNames) {
188 +            try {
189 +                Class<?> testClass = Class.forName(testClassName);
190 +                Method m = testClass.getDeclaredMethod("suite",
191 +                                                       new Class<?>[0]);
192 +                suite.addTest(newTestSuite((Test)m.invoke(null)));
193 +            } catch (Exception e) {
194 +                throw new Error("Missing test class", e);
195 +            }
196 +        }
197 +    }
198 +
199 +    public static final double JAVA_CLASS_VERSION;
200 +    static {
201 +        try {
202 +            JAVA_CLASS_VERSION = java.security.AccessController.doPrivileged(
203 +                new java.security.PrivilegedAction<Double>() {
204 +                public Double run() {
205 +                    return Double.valueOf(System.getProperty("java.class.version"));}});
206 +        } catch (Throwable t) {
207 +            throw new Error(t);
208 +        }
209 +    }
210 +
211 +    public static boolean atLeastJava6() { return JAVA_CLASS_VERSION >= 50.0; }
212 +    public static boolean atLeastJava7() { return JAVA_CLASS_VERSION >= 51.0; }
213 +    public static boolean atLeastJava8() { return JAVA_CLASS_VERSION >= 52.0; }
214 +
215      /**
216       * Collects all JSR166 unit tests as one suite.
217       */
218      public static Test suite() {
219 <        return newTestSuite(
219 >        // Java7+ test classes
220 >        TestSuite suite = newTestSuite(
221              ForkJoinPoolTest.suite(),
222              ForkJoinTaskTest.suite(),
223              RecursiveActionTest.suite(),
# Line 243 | Line 282 | public class JSR166TestCase extends Test
282              TreeSetTest.suite(),
283              TreeSubMapTest.suite(),
284              TreeSubSetTest.suite());
285 +
286 +        // Java8+ test classes
287 +        if (atLeastJava8()) {
288 +            String[] java8TestClassNames = {
289 +                "CompletableFutureTest",
290 +                "ForkJoinPool8Test",
291 +                "StampedLockTest",
292 +            };
293 +            addNamedTestClasses(suite, java8TestClassNames);
294 +        }
295 +
296 +        return suite;
297      }
298  
299  
# Line 334 | Line 385 | public class JSR166TestCase extends Test
385  
386          if (Thread.interrupted())
387              throw new AssertionFailedError("interrupt status set in main thread");
388 +
389 +        checkForkJoinPoolThreadLeaks();
390 +    }
391 +
392 +    /**
393 +     * Find missing try { ... } finally { joinPool(e); }
394 +     */
395 +    void checkForkJoinPoolThreadLeaks() throws InterruptedException {
396 +        Thread[] survivors = new Thread[5];
397 +        int count = Thread.enumerate(survivors);
398 +        for (int i = 0; i < count; i++) {
399 +            Thread thread = survivors[i];
400 +            String name = thread.getName();
401 +            if (name.startsWith("ForkJoinPool-")) {
402 +                // give thread some time to terminate
403 +                thread.join(LONG_DELAY_MS);
404 +                if (!thread.isAlive()) continue;
405 +                thread.stop();
406 +                throw new AssertionFailedError
407 +                    (String.format("Found leaked ForkJoinPool thread test=%s thread=%s%n",
408 +                                   toString(), name));
409 +            }
410 +        }
411      }
412  
413      /**
# Line 507 | Line 581 | public class JSR166TestCase extends Test
581      }
582  
583      /**
584 +     * A debugging tool to print all stack traces, as jstack does.
585 +     */
586 +    static void printAllStackTraces() {
587 +        for (ThreadInfo info :
588 +                 ManagementFactory.getThreadMXBean()
589 +                 .dumpAllThreads(true, true))
590 +            System.err.print(info);
591 +    }
592 +
593 +    /**
594       * Checks that thread does not terminate within the default
595       * millisecond delay of {@code timeoutMillis()}.
596       */
# Line 528 | Line 612 | public class JSR166TestCase extends Test
612      }
613  
614      /**
615 +     * Checks that the threads do not terminate within the default
616 +     * millisecond delay of {@code timeoutMillis()}.
617 +     */
618 +    void assertThreadsStayAlive(Thread... threads) {
619 +        assertThreadsStayAlive(timeoutMillis(), threads);
620 +    }
621 +
622 +    /**
623 +     * Checks that the threads do not terminate within the given millisecond delay.
624 +     */
625 +    void assertThreadsStayAlive(long millis, Thread... threads) {
626 +        try {
627 +            // No need to optimize the failing case via Thread.join.
628 +            delay(millis);
629 +            for (Thread thread : threads)
630 +                assertTrue(thread.isAlive());
631 +        } catch (InterruptedException ie) {
632 +            fail("Unexpected InterruptedException");
633 +        }
634 +    }
635 +
636 +    /**
637       * Checks that future.get times out, with the default timeout of
638       * {@code timeoutMillis()}.
639       */
# Line 601 | Line 707 | public class JSR166TestCase extends Test
707          SecurityManager sm = System.getSecurityManager();
708          if (sm == null) {
709              r.run();
710 +        }
711 +        runWithSecurityManagerWithPermissions(r, permissions);
712 +    }
713 +
714 +    /**
715 +     * Runs Runnable r with a security policy that permits precisely
716 +     * the specified permissions.  If there is no current security
717 +     * manager, a temporary one is set for the duration of the
718 +     * Runnable.  We require that any security manager permit
719 +     * getPolicy/setPolicy.
720 +     */
721 +    public void runWithSecurityManagerWithPermissions(Runnable r,
722 +                                                      Permission... permissions) {
723 +        SecurityManager sm = System.getSecurityManager();
724 +        if (sm == null) {
725              Policy savedPolicy = Policy.getPolicy();
726              try {
727                  Policy.setPolicy(permissivePolicy());
728                  System.setSecurityManager(new SecurityManager());
729 <                runWithPermissions(r, permissions);
729 >                runWithSecurityManagerWithPermissions(r, permissions);
730              } finally {
731                  System.setSecurityManager(null);
732                  Policy.setPolicy(savedPolicy);
# Line 653 | Line 774 | public class JSR166TestCase extends Test
774              return perms.implies(p);
775          }
776          public void refresh() {}
777 +        public String toString() {
778 +            List<Permission> ps = new ArrayList<Permission>();
779 +            for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
780 +                ps.add(e.nextElement());
781 +            return "AdjustablePolicy with permissions " + ps;
782 +        }
783      }
784  
785      /**
# Line 690 | Line 817 | public class JSR166TestCase extends Test
817      }
818  
819      /**
820 <     * Waits up to the specified number of milliseconds for the given
820 >     * Spin-waits up to the specified number of milliseconds for the given
821       * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
822       */
823      void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
824 <        long timeoutNanos = timeoutMillis * 1000L * 1000L;
698 <        long t0 = System.nanoTime();
824 >        long startTime = System.nanoTime();
825          for (;;) {
826              Thread.State s = thread.getState();
827              if (s == Thread.State.BLOCKED ||
# Line 704 | Line 830 | public class JSR166TestCase extends Test
830                  return;
831              else if (s == Thread.State.TERMINATED)
832                  fail("Unexpected thread termination");
833 <            else if (System.nanoTime() - t0 > timeoutNanos) {
833 >            else if (millisElapsedSince(startTime) > timeoutMillis) {
834                  threadAssertTrue(thread.isAlive());
835                  return;
836              }
# Line 905 | Line 1031 | public class JSR166TestCase extends Test
1031          }
1032      }
1033  
1034 +    public void await(Semaphore semaphore) {
1035 +        try {
1036 +            assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
1037 +        } catch (Throwable t) {
1038 +            threadUnexpectedException(t);
1039 +        }
1040 +    }
1041 +
1042   //     /**
1043   //      * Spin-waits up to LONG_DELAY_MS until flag becomes true.
1044   //      */
# Line 1126 | Line 1260 | public class JSR166TestCase extends Test
1260      }
1261  
1262      /**
1263 <     * A CyclicBarrier that fails with AssertionFailedErrors instead
1264 <     * of throwing checked exceptions.
1263 >     * A CyclicBarrier that uses timed await and fails with
1264 >     * AssertionFailedErrors instead of throwing checked exceptions.
1265       */
1266      public class CheckedBarrier extends CyclicBarrier {
1267          public CheckedBarrier(int parties) { super(parties); }
1268  
1269          public int await() {
1270              try {
1271 <                return super.await();
1271 >                return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1272 >            } catch (TimeoutException e) {
1273 >                throw new AssertionFailedError("timed out");
1274              } catch (Exception e) {
1275                  AssertionFailedError afe =
1276                      new AssertionFailedError("Unexpected exception: " + e);
# Line 1171 | Line 1307 | public class JSR166TestCase extends Test
1307          }
1308      }
1309  
1310 <    @SuppressWarnings("unchecked")
1311 <    <T> T serialClone(T o) {
1310 >    void assertSerialEquals(Object x, Object y) {
1311 >        assertTrue(Arrays.equals(serialBytes(x), serialBytes(y)));
1312 >    }
1313 >
1314 >    void assertNotSerialEquals(Object x, Object y) {
1315 >        assertFalse(Arrays.equals(serialBytes(x), serialBytes(y)));
1316 >    }
1317 >
1318 >    byte[] serialBytes(Object o) {
1319          try {
1320              ByteArrayOutputStream bos = new ByteArrayOutputStream();
1321              ObjectOutputStream oos = new ObjectOutputStream(bos);
1322              oos.writeObject(o);
1323              oos.flush();
1324              oos.close();
1325 <            ByteArrayInputStream bin =
1326 <                new ByteArrayInputStream(bos.toByteArray());
1327 <            ObjectInputStream ois = new ObjectInputStream(bin);
1328 <            return (T) ois.readObject();
1325 >            return bos.toByteArray();
1326 >        } catch (Throwable t) {
1327 >            threadUnexpectedException(t);
1328 >            return new byte[0];
1329 >        }
1330 >    }
1331 >
1332 >    @SuppressWarnings("unchecked")
1333 >    <T> T serialClone(T o) {
1334 >        try {
1335 >            ObjectInputStream ois = new ObjectInputStream
1336 >                (new ByteArrayInputStream(serialBytes(o)));
1337 >            T clone = (T) ois.readObject();
1338 >            assertSame(o.getClass(), clone.getClass());
1339 >            return clone;
1340          } catch (Throwable t) {
1341              threadUnexpectedException(t);
1342              return null;

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines