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.130 by jsr166, Tue Apr 21 05:00:23 2015 UTC vs.
Revision 1.139 by jsr166, Sun Sep 6 21:14:12 2015 UTC

# Line 15 | Line 15 | import java.io.ObjectInputStream;
15   import java.io.ObjectOutputStream;
16   import java.lang.management.ManagementFactory;
17   import java.lang.management.ThreadInfo;
18 + import java.lang.reflect.Constructor;
19   import java.lang.reflect.Method;
20 + import java.lang.reflect.Modifier;
21   import java.security.CodeSource;
22   import java.security.Permission;
23   import java.security.PermissionCollection;
# Line 35 | Line 37 | import java.util.concurrent.BlockingQueu
37   import java.util.concurrent.Callable;
38   import java.util.concurrent.CountDownLatch;
39   import java.util.concurrent.CyclicBarrier;
40 + import java.util.concurrent.ExecutionException;
41 + import java.util.concurrent.Executors;
42   import java.util.concurrent.ExecutorService;
43   import java.util.concurrent.Future;
44   import java.util.concurrent.RecursiveAction;
# Line 50 | Line 54 | import java.util.regex.Pattern;
54   import junit.framework.AssertionFailedError;
55   import junit.framework.Test;
56   import junit.framework.TestCase;
57 + import junit.framework.TestResult;
58   import junit.framework.TestSuite;
59  
60   /**
# Line 160 | Line 165 | public class JSR166TestCase extends Test
165          Integer.getInteger("jsr166.runsPerTest", 1);
166  
167      /**
168 +     * The number of repetitions of the test suite (for finding leaks?).
169 +     */
170 +    private static final int suiteRuns =
171 +        Integer.getInteger("jsr166.suiteRuns", 1);
172 +
173 +    public JSR166TestCase() { super(); }
174 +    public JSR166TestCase(String name) { super(name); }
175 +
176 +    /**
177       * A filter for tests to run, matching strings of the form
178       * methodName(className), e.g. "testInvokeAll5(ForkJoinPoolTest)"
179       * Usefully combined with jsr166.runsPerTest.
# Line 198 | Line 212 | public class JSR166TestCase extends Test
212  
213      /**
214       * Runs all JSR166 unit tests using junit.textui.TestRunner.
201     * Optional command line arg provides the number of iterations to
202     * repeat running the tests.
215       */
216      public static void main(String[] args) {
217 +        main(suite(), args);
218 +    }
219 +
220 +    /**
221 +     * Runs all unit tests in the given test suite.
222 +     * Actual behavior influenced by jsr166.* system properties.
223 +     */
224 +    static void main(Test suite, String[] args) {
225          if (useSecurityManager) {
226              System.err.println("Setting a permissive security manager");
227              Policy.setPolicy(permissivePolicy());
228              System.setSecurityManager(new SecurityManager());
229          }
230 <        int iters = (args.length == 0) ? 1 : Integer.parseInt(args[0]);
231 <
232 <        Test s = suite();
233 <        for (int i = 0; i < iters; ++i) {
214 <            junit.textui.TestRunner.run(s);
230 >        for (int i = 0; i < suiteRuns; i++) {
231 >            TestResult result = junit.textui.TestRunner.run(suite);
232 >            if (!result.wasSuccessful())
233 >                System.exit(1);
234              System.gc();
235              System.runFinalization();
236          }
218        System.exit(0);
237      }
238  
239      public static TestSuite newTestSuite(Object... suiteOrClasses) {
# Line 265 | Line 283 | public class JSR166TestCase extends Test
283      public static boolean atLeastJava6() { return JAVA_CLASS_VERSION >= 50.0; }
284      public static boolean atLeastJava7() { return JAVA_CLASS_VERSION >= 51.0; }
285      public static boolean atLeastJava8() { return JAVA_CLASS_VERSION >= 52.0; }
286 <    public static boolean atLeastJava9() { return JAVA_CLASS_VERSION >= 53.0; }
286 >    public static boolean atLeastJava9() {
287 >        return JAVA_CLASS_VERSION >= 53.0
288 >            // As of 2015-09, java9 still uses 52.0 class file version
289 >            || JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?(9|[0-9][0-9])$");
290 >    }
291 >    public static boolean atLeastJava10() {
292 >        return JAVA_CLASS_VERSION >= 54.0
293 >            || JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?[0-9][0-9]$");
294 >    }
295  
296      /**
297       * Collects all JSR166 unit tests as one suite.
# Line 361 | Line 387 | public class JSR166TestCase extends Test
387          // Java9+ test classes
388          if (atLeastJava9()) {
389              String[] java9TestClassNames = {
390 <                "ThreadPoolExecutor9Test",
390 >                // Currently empty
391              };
392              addNamedTestClasses(suite, java9TestClassNames);
393          }
# Line 369 | Line 395 | public class JSR166TestCase extends Test
395          return suite;
396      }
397  
398 +    /** Returns list of junit-style test method names in given class. */
399 +    public static ArrayList<String> testMethodNames(Class<?> testClass) {
400 +        Method[] methods = testClass.getDeclaredMethods();
401 +        ArrayList<String> names = new ArrayList<String>(methods.length);
402 +        for (Method method : methods) {
403 +            if (method.getName().startsWith("test")
404 +                && Modifier.isPublic(method.getModifiers())
405 +                // method.getParameterCount() requires jdk8+
406 +                && method.getParameterTypes().length == 0) {
407 +                names.add(method.getName());
408 +            }
409 +        }
410 +        return names;
411 +    }
412 +
413 +    /**
414 +     * Returns junit-style testSuite for the given test class, but
415 +     * parameterized by passing extra data to each test.
416 +     */
417 +    public static <ExtraData> Test parameterizedTestSuite
418 +        (Class<? extends JSR166TestCase> testClass,
419 +         Class<ExtraData> dataClass,
420 +         ExtraData data) {
421 +        try {
422 +            TestSuite suite = new TestSuite();
423 +            Constructor c =
424 +                testClass.getDeclaredConstructor(dataClass, String.class);
425 +            for (String methodName : testMethodNames(testClass))
426 +                suite.addTest((Test) c.newInstance(data, methodName));
427 +            return suite;
428 +        } catch (Exception e) {
429 +            throw new Error(e);
430 +        }
431 +    }
432 +
433 +    /**
434 +     * Returns junit-style testSuite for the jdk8 extension of the
435 +     * given test class, but parameterized by passing extra data to
436 +     * each test.  Uses reflection to allow compilation in jdk7.
437 +     */
438 +    public static <ExtraData> Test jdk8ParameterizedTestSuite
439 +        (Class<? extends JSR166TestCase> testClass,
440 +         Class<ExtraData> dataClass,
441 +         ExtraData data) {
442 +        if (atLeastJava8()) {
443 +            String name = testClass.getName();
444 +            String name8 = name.replaceAll("Test$", "8Test");
445 +            if (name.equals(name8)) throw new Error(name);
446 +            try {
447 +                return (Test)
448 +                    Class.forName(name8)
449 +                    .getMethod("testSuite", new Class[] { dataClass })
450 +                    .invoke(null, data);
451 +            } catch (Exception e) {
452 +                throw new Error(e);
453 +            }
454 +        } else {
455 +            return new TestSuite();
456 +        }
457 +
458 +    }
459 +
460      // Delays for timing-dependent tests, in milliseconds.
461  
462      public static long SHORT_DELAY_MS;
# Line 403 | Line 491 | public class JSR166TestCase extends Test
491      }
492  
493      /**
494 <     * Returns a new Date instance representing a time delayMillis
495 <     * milliseconds in the future.
494 >     * Returns a new Date instance representing a time at least
495 >     * delayMillis milliseconds in the future.
496       */
497      Date delayedDate(long delayMillis) {
498 <        return new Date(System.currentTimeMillis() + delayMillis);
498 >        // Add 1 because currentTimeMillis is known to round into the past.
499 >        return new Date(System.currentTimeMillis() + delayMillis + 1);
500      }
501  
502      /**
# Line 475 | Line 564 | public class JSR166TestCase extends Test
564                  // give thread some time to terminate
565                  thread.join(LONG_DELAY_MS);
566                  if (!thread.isAlive()) continue;
478                thread.stop();
567                  throw new AssertionFailedError
568                      (String.format("Found leaked ForkJoinPool thread test=%s thread=%s%n",
569                                     toString(), name));
# Line 641 | Line 729 | public class JSR166TestCase extends Test
729      /**
730       * Waits out termination of a thread pool or fails doing so.
731       */
732 <    void joinPool(ExecutorService exec) {
732 >    void joinPool(ExecutorService pool) {
733          try {
734 <            exec.shutdown();
735 <            if (!exec.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS))
736 <                fail("ExecutorService " + exec +
734 >            pool.shutdown();
735 >            if (!pool.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS))
736 >                fail("ExecutorService " + pool +
737                       " did not terminate in a timely manner");
738          } catch (SecurityException ok) {
739              // Allowed in case test doesn't have privs
# Line 654 | Line 742 | public class JSR166TestCase extends Test
742          }
743      }
744  
745 +    /** Like Runnable, but with the freedom to throw anything */
746 +    interface Thunk { public void run() throws Throwable; }
747 +
748 +    /**
749 +     * Runs all the given tasks in parallel, failing if any fail.
750 +     * Useful for running multiple variants of tests that are
751 +     * necessarily individually slow because they must block.
752 +     */
753 +    void testInParallel(Thunk ... thunks) {
754 +        ExecutorService pool = Executors.newCachedThreadPool();
755 +        try {
756 +            ArrayList<Future<?>> futures = new ArrayList<>(thunks.length);
757 +            for (final Thunk thunk : thunks)
758 +                futures.add(pool.submit(new CheckedRunnable() {
759 +                    public void realRun() throws Throwable { thunk.run();}}));
760 +            for (Future<?> future : futures)
761 +                try {
762 +                    assertNull(future.get(LONG_DELAY_MS, MILLISECONDS));
763 +                } catch (ExecutionException ex) {
764 +                    threadUnexpectedException(ex.getCause());
765 +                } catch (Exception ex) {
766 +                    threadUnexpectedException(ex);
767 +                }
768 +        } finally {
769 +            joinPool(pool);
770 +        }
771 +    }
772 +
773      /**
774       * A debugging tool to print all stack traces, as jstack does.
775       */

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines