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.100 by jsr166, Wed Feb 6 16:55:50 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 +                "StampedLockTest",
290 +                "ForkJoinPool8Test",
291 +            };
292 +            addNamedTestClasses(suite, java8TestClassNames);
293 +        }
294 +
295 +        return suite;
296      }
297  
298  
# Line 334 | Line 384 | public class JSR166TestCase extends Test
384  
385          if (Thread.interrupted())
386              throw new AssertionFailedError("interrupt status set in main thread");
387 +
388 +        checkForkJoinPoolThreadLeaks();
389      }
390  
391      /**
392 +     * Find missing try { ... } finally { joinPool(e); }
393 +     */
394 +    void checkForkJoinPoolThreadLeaks() throws InterruptedException {
395 +        Thread[] survivors = new Thread[5];
396 +        int count = Thread.enumerate(survivors);
397 +        for (int i = 0; i < count; i++) {
398 +            Thread thread = survivors[i];
399 +            String name = thread.getName();
400 +            if (name.startsWith("ForkJoinPool-")) {
401 +                // give thread some time to terminate
402 +                thread.join(LONG_DELAY_MS);
403 +                if (!thread.isAlive()) continue;
404 +                thread.stop();
405 +                throw new AssertionFailedError
406 +                    (String.format("Found leaked ForkJoinPool thread test=%s thread=%s%n",
407 +                                   toString(), name));
408 +            }
409 +        }
410 +    }
411 +        
412 +    /**
413       * Just like fail(reason), but additionally recording (using
414       * threadRecordFailure) any AssertionFailedError thrown, so that
415       * the current testcase will fail.
# Line 507 | Line 580 | public class JSR166TestCase extends Test
580      }
581  
582      /**
583 +     * A debugging tool to print all stack traces, as jstack does.
584 +     */
585 +    static void printAllStackTraces() {
586 +        for (ThreadInfo info :
587 +                 ManagementFactory.getThreadMXBean()
588 +                 .dumpAllThreads(true, true))
589 +            System.err.print(info);
590 +    }
591 +
592 +    /**
593       * Checks that thread does not terminate within the default
594       * millisecond delay of {@code timeoutMillis()}.
595       */
# Line 528 | Line 611 | public class JSR166TestCase extends Test
611      }
612  
613      /**
614 +     * Checks that the threads do not terminate within the default
615 +     * millisecond delay of {@code timeoutMillis()}.
616 +     */
617 +    void assertThreadsStayAlive(Thread... threads) {
618 +        assertThreadsStayAlive(timeoutMillis(), threads);
619 +    }
620 +
621 +    /**
622 +     * Checks that the threads do not terminate within the given millisecond delay.
623 +     */
624 +    void assertThreadsStayAlive(long millis, Thread... threads) {
625 +        try {
626 +            // No need to optimize the failing case via Thread.join.
627 +            delay(millis);
628 +            for (Thread thread : threads)
629 +                assertTrue(thread.isAlive());
630 +        } catch (InterruptedException ie) {
631 +            fail("Unexpected InterruptedException");
632 +        }
633 +    }
634 +
635 +    /**
636       * Checks that future.get times out, with the default timeout of
637       * {@code timeoutMillis()}.
638       */
# Line 601 | Line 706 | public class JSR166TestCase extends Test
706          SecurityManager sm = System.getSecurityManager();
707          if (sm == null) {
708              r.run();
709 +        }
710 +        runWithSecurityManagerWithPermissions(r, permissions);
711 +    }
712 +
713 +    /**
714 +     * Runs Runnable r with a security policy that permits precisely
715 +     * the specified permissions.  If there is no current security
716 +     * manager, a temporary one is set for the duration of the
717 +     * Runnable.  We require that any security manager permit
718 +     * getPolicy/setPolicy.
719 +     */
720 +    public void runWithSecurityManagerWithPermissions(Runnable r,
721 +                                                      Permission... permissions) {
722 +        SecurityManager sm = System.getSecurityManager();
723 +        if (sm == null) {
724              Policy savedPolicy = Policy.getPolicy();
725              try {
726                  Policy.setPolicy(permissivePolicy());
727                  System.setSecurityManager(new SecurityManager());
728 <                runWithPermissions(r, permissions);
728 >                runWithSecurityManagerWithPermissions(r, permissions);
729              } finally {
730                  System.setSecurityManager(null);
731                  Policy.setPolicy(savedPolicy);
# Line 653 | Line 773 | public class JSR166TestCase extends Test
773              return perms.implies(p);
774          }
775          public void refresh() {}
776 +        public String toString() {
777 +            List<Permission> ps = new ArrayList<Permission>();
778 +            for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
779 +                ps.add(e.nextElement());
780 +            return "AdjustablePolicy with permissions " + ps;
781 +        }
782      }
783  
784      /**
# Line 690 | Line 816 | public class JSR166TestCase extends Test
816      }
817  
818      /**
819 <     * Waits up to the specified number of milliseconds for the given
819 >     * Spin-waits up to the specified number of milliseconds for the given
820       * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
821       */
822      void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
823 <        long timeoutNanos = timeoutMillis * 1000L * 1000L;
698 <        long t0 = System.nanoTime();
823 >        long startTime = System.nanoTime();
824          for (;;) {
825              Thread.State s = thread.getState();
826              if (s == Thread.State.BLOCKED ||
# Line 704 | Line 829 | public class JSR166TestCase extends Test
829                  return;
830              else if (s == Thread.State.TERMINATED)
831                  fail("Unexpected thread termination");
832 <            else if (System.nanoTime() - t0 > timeoutNanos) {
832 >            else if (millisElapsedSince(startTime) > timeoutMillis) {
833                  threadAssertTrue(thread.isAlive());
834                  return;
835              }
# Line 905 | Line 1030 | public class JSR166TestCase extends Test
1030          }
1031      }
1032  
1033 +    public void await(Semaphore semaphore) {
1034 +        try {
1035 +            assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
1036 +        } catch (Throwable t) {
1037 +            threadUnexpectedException(t);
1038 +        }
1039 +    }
1040 +
1041   //     /**
1042   //      * Spin-waits up to LONG_DELAY_MS until flag becomes true.
1043   //      */
# Line 1173 | Line 1306 | public class JSR166TestCase extends Test
1306          }
1307      }
1308  
1309 <    @SuppressWarnings("unchecked")
1310 <    <T> T serialClone(T o) {
1309 >    void assertSerialEquals(Object x, Object y) {
1310 >        assertTrue(Arrays.equals(serialBytes(x), serialBytes(y)));
1311 >    }
1312 >
1313 >    void assertNotSerialEquals(Object x, Object y) {
1314 >        assertFalse(Arrays.equals(serialBytes(x), serialBytes(y)));
1315 >    }
1316 >
1317 >    byte[] serialBytes(Object o) {
1318          try {
1319              ByteArrayOutputStream bos = new ByteArrayOutputStream();
1320              ObjectOutputStream oos = new ObjectOutputStream(bos);
1321              oos.writeObject(o);
1322              oos.flush();
1323              oos.close();
1324 <            ByteArrayInputStream bin =
1325 <                new ByteArrayInputStream(bos.toByteArray());
1326 <            ObjectInputStream ois = new ObjectInputStream(bin);
1327 <            return (T) ois.readObject();
1324 >            return bos.toByteArray();
1325 >        } catch (Throwable t) {
1326 >            threadUnexpectedException(t);
1327 >            return new byte[0];
1328 >        }
1329 >    }
1330 >
1331 >    @SuppressWarnings("unchecked")
1332 >    <T> T serialClone(T o) {
1333 >        try {
1334 >            ObjectInputStream ois = new ObjectInputStream
1335 >                (new ByteArrayInputStream(serialBytes(o)));
1336 >            T clone = (T) ois.readObject();
1337 >            assertSame(o.getClass(), clone.getClass());
1338 >            return clone;
1339          } catch (Throwable t) {
1340              threadUnexpectedException(t);
1341              return null;

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines