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.242 by jsr166, Mon Feb 19 16:12:11 2018 UTC vs.
Revision 1.255 by jsr166, Sun Jul 28 18:09:25 2019 UTC

# Line 66 | Line 66 | import java.util.Arrays;
66   import java.util.Collection;
67   import java.util.Collections;
68   import java.util.Date;
69 + import java.util.Deque;
70   import java.util.Enumeration;
71 + import java.util.HashSet;
72   import java.util.Iterator;
73   import java.util.List;
74   import java.util.NoSuchElementException;
75   import java.util.PropertyPermission;
76 + import java.util.Set;
77   import java.util.concurrent.BlockingQueue;
78   import java.util.concurrent.Callable;
79   import java.util.concurrent.CountDownLatch;
# Line 114 | Line 117 | import junit.framework.TestSuite;
117   *
118   * <ol>
119   *
120 < * <li>All assertions in code running in generated threads must use
121 < * the forms {@link #threadFail}, {@link #threadAssertTrue}, {@link
122 < * #threadAssertEquals}, or {@link #threadAssertNull}, (not
123 < * {@code fail}, {@code assertTrue}, etc.) It is OK (but not
124 < * particularly recommended) for other code to use these forms too.
125 < * Only the most typically used JUnit assertion methods are defined
126 < * this way, but enough to live with.
120 > * <li>All code not running in the main test thread (manually spawned threads
121 > * or the common fork join pool) must be checked for failure (and completion!).
122 > * Mechanisms that can be used to ensure this are:
123 > *   <ol>
124 > *   <li>Signalling via a synchronizer like AtomicInteger or CountDownLatch
125 > *    that the task completed normally, which is checked before returning from
126 > *    the test method in the main thread.
127 > *   <li>Using the forms {@link #threadFail}, {@link #threadAssertTrue},
128 > *    or {@link #threadAssertNull}, (not {@code fail}, {@code assertTrue}, etc.)
129 > *    Only the most typically used JUnit assertion methods are defined
130 > *    this way, but enough to live with.
131 > *   <li>Recording failure explicitly using {@link #threadUnexpectedException}
132 > *    or {@link #threadRecordFailure}.
133 > *   <li>Using a wrapper like CheckedRunnable that uses one the mechanisms above.
134 > *   </ol>
135   *
136   * <li>If you override {@link #setUp} or {@link #tearDown}, make sure
137   * to invoke {@code super.setUp} and {@code super.tearDown} within
# Line 277 | Line 288 | public class JSR166TestCase extends Test
288              // Avoid spurious reports with enormous runsPerTest.
289              // A single test case run should never take more than 1 second.
290              // But let's cap it at the high end too ...
291 <            final int timeoutMinutes =
292 <                Math.min(15, Math.max(runsPerTest / 60, 1));
291 >            final int timeoutMinutesMin = Math.max(runsPerTest / 60, 1)
292 >                * Math.max((int) delayFactor, 1);
293 >            final int timeoutMinutes = Math.min(15, timeoutMinutesMin);
294              for (TestCase lastTestCase = currentTestCase;;) {
295                  try { MINUTES.sleep(timeoutMinutes); }
296                  catch (InterruptedException unexpected) { break; }
# Line 448 | Line 460 | public class JSR166TestCase extends Test
460      public static boolean atLeastJava8()  { return JAVA_CLASS_VERSION >= 52.0; }
461      public static boolean atLeastJava9()  { return JAVA_CLASS_VERSION >= 53.0; }
462      public static boolean atLeastJava10() { return JAVA_CLASS_VERSION >= 54.0; }
463 +    public static boolean atLeastJava11() { return JAVA_CLASS_VERSION >= 55.0; }
464 +    public static boolean atLeastJava12() { return JAVA_CLASS_VERSION >= 56.0; }
465 +    public static boolean atLeastJava13() { return JAVA_CLASS_VERSION >= 57.0; }
466 +    public static boolean atLeastJava14() { return JAVA_CLASS_VERSION >= 58.0; }
467 +    public static boolean atLeastJava15() { return JAVA_CLASS_VERSION >= 59.0; }
468 +    public static boolean atLeastJava16() { return JAVA_CLASS_VERSION >= 60.0; }
469 +    public static boolean atLeastJava17() { return JAVA_CLASS_VERSION >= 61.0; }
470  
471      /**
472       * Collects all JSR166 unit tests as one suite.
# Line 499 | Line 518 | public class JSR166TestCase extends Test
518              ExecutorsTest.suite(),
519              ExecutorCompletionServiceTest.suite(),
520              FutureTaskTest.suite(),
521 +            HashtableTest.suite(),
522              LinkedBlockingDequeTest.suite(),
523              LinkedBlockingQueueTest.suite(),
524              LinkedListTest.suite(),
# Line 538 | Line 558 | public class JSR166TestCase extends Test
558                  "HashMapTest",
559                  "LinkedBlockingDeque8Test",
560                  "LinkedBlockingQueue8Test",
561 +                "LinkedHashMapTest",
562                  "LongAccumulatorTest",
563                  "LongAdderTest",
564                  "SplittableRandomTest",
# Line 1287 | Line 1308 | public class JSR166TestCase extends Test
1308      /**
1309       * Spin-waits up to the specified number of milliseconds for the given
1310       * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
1311 +     * @param waitingForGodot if non-null, an additional condition to satisfy
1312       */
1313 <    void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
1314 <        long startTime = 0L;
1315 <        for (;;) {
1316 <            Thread.State s = thread.getState();
1317 <            if (s == Thread.State.BLOCKED ||
1318 <                s == Thread.State.WAITING ||
1319 <                s == Thread.State.TIMED_WAITING)
1320 <                return;
1321 <            else if (s == Thread.State.TERMINATED)
1313 >    void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis,
1314 >                                       Callable<Boolean> waitingForGodot) {
1315 >        for (long startTime = 0L;;) {
1316 >            switch (thread.getState()) {
1317 >            default: break;
1318 >            case BLOCKED: case WAITING: case TIMED_WAITING:
1319 >                try {
1320 >                    if (waitingForGodot == null || waitingForGodot.call())
1321 >                        return;
1322 >                } catch (Throwable fail) { threadUnexpectedException(fail); }
1323 >                break;
1324 >            case TERMINATED:
1325                  fail("Unexpected thread termination");
1326 <            else if (startTime == 0L)
1326 >            }
1327 >
1328 >            if (startTime == 0L)
1329                  startTime = System.nanoTime();
1330              else if (millisElapsedSince(startTime) > timeoutMillis) {
1331 <                threadAssertTrue(thread.isAlive());
1332 <                fail("timed out waiting for thread to enter wait state");
1331 >                assertTrue(thread.isAlive());
1332 >                if (waitingForGodot == null
1333 >                    || thread.getState() == Thread.State.RUNNABLE)
1334 >                    fail("timed out waiting for thread to enter wait state");
1335 >                else
1336 >                    fail("timed out waiting for condition, thread state="
1337 >                         + thread.getState());
1338              }
1339              Thread.yield();
1340          }
# Line 1310 | Line 1342 | public class JSR166TestCase extends Test
1342  
1343      /**
1344       * Spin-waits up to the specified number of milliseconds for the given
1345 <     * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING,
1314 <     * and additionally satisfy the given condition.
1345 >     * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
1346       */
1347 <    void waitForThreadToEnterWaitState(
1348 <        Thread thread, long timeoutMillis, Callable<Boolean> waitingForGodot) {
1318 <        long startTime = 0L;
1319 <        for (;;) {
1320 <            Thread.State s = thread.getState();
1321 <            if (s == Thread.State.BLOCKED ||
1322 <                s == Thread.State.WAITING ||
1323 <                s == Thread.State.TIMED_WAITING) {
1324 <                try {
1325 <                    if (waitingForGodot.call())
1326 <                        return;
1327 <                } catch (Throwable fail) { threadUnexpectedException(fail); }
1328 <            }
1329 <            else if (s == Thread.State.TERMINATED)
1330 <                fail("Unexpected thread termination");
1331 <            else if (startTime == 0L)
1332 <                startTime = System.nanoTime();
1333 <            else if (millisElapsedSince(startTime) > timeoutMillis) {
1334 <                threadAssertTrue(thread.isAlive());
1335 <                fail("timed out waiting for thread to enter wait state");
1336 <            }
1337 <            Thread.yield();
1338 <        }
1347 >    void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
1348 >        waitForThreadToEnterWaitState(thread, timeoutMillis, null);
1349      }
1350  
1351      /**
# Line 1343 | Line 1353 | public class JSR166TestCase extends Test
1353       * enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
1354       */
1355      void waitForThreadToEnterWaitState(Thread thread) {
1356 <        waitForThreadToEnterWaitState(thread, LONG_DELAY_MS);
1356 >        waitForThreadToEnterWaitState(thread, LONG_DELAY_MS, null);
1357      }
1358  
1359      /**
# Line 1351 | Line 1361 | public class JSR166TestCase extends Test
1361       * enter a wait state: BLOCKED, WAITING, or TIMED_WAITING,
1362       * and additionally satisfy the given condition.
1363       */
1364 <    void waitForThreadToEnterWaitState(
1365 <        Thread thread, Callable<Boolean> waitingForGodot) {
1364 >    void waitForThreadToEnterWaitState(Thread thread,
1365 >                                       Callable<Boolean> waitingForGodot) {
1366          waitForThreadToEnterWaitState(thread, LONG_DELAY_MS, waitingForGodot);
1367      }
1368  
# Line 1384 | Line 1394 | public class JSR166TestCase extends Test
1394       */
1395      <T> void checkTimedGet(Future<T> f, T expectedValue, long timeoutMillis) {
1396          long startTime = System.nanoTime();
1397 +        T actual = null;
1398          try {
1399 <            assertEquals(expectedValue, f.get(timeoutMillis, MILLISECONDS));
1399 >            actual = f.get(timeoutMillis, MILLISECONDS);
1400          } catch (Throwable fail) { threadUnexpectedException(fail); }
1401 +        assertEquals(expectedValue, actual);
1402          if (millisElapsedSince(startTime) > timeoutMillis/2)
1403              throw new AssertionError("timed get did not return promptly");
1404      }
# Line 1458 | Line 1470 | public class JSR166TestCase extends Test
1470          public final void run() {
1471              try {
1472                  realRun();
1461                threadShouldThrow(exceptionClass.getSimpleName());
1473              } catch (Throwable t) {
1474                  if (! exceptionClass.isInstance(t))
1475                      threadUnexpectedException(t);
1476 +                return;
1477              }
1478 +            threadShouldThrow(exceptionClass.getSimpleName());
1479          }
1480      }
1481  
# Line 1472 | Line 1485 | public class JSR166TestCase extends Test
1485          public final void run() {
1486              try {
1487                  realRun();
1475                threadShouldThrow("InterruptedException");
1488              } catch (InterruptedException success) {
1489                  threadAssertFalse(Thread.interrupted());
1490 +                return;
1491              } catch (Throwable fail) {
1492                  threadUnexpectedException(fail);
1493              }
1494 +            threadShouldThrow("InterruptedException");
1495          }
1496      }
1497  
# Line 1489 | Line 1503 | public class JSR166TestCase extends Test
1503                  return realCall();
1504              } catch (Throwable fail) {
1505                  threadUnexpectedException(fail);
1492                return null;
1493            }
1494        }
1495    }
1496
1497    public abstract class CheckedInterruptedCallable<T>
1498        implements Callable<T> {
1499        protected abstract T realCall() throws Throwable;
1500
1501        public final T call() {
1502            try {
1503                T result = realCall();
1504                threadShouldThrow("InterruptedException");
1505                return result;
1506            } catch (InterruptedException success) {
1507                threadAssertFalse(Thread.interrupted());
1508            } catch (Throwable fail) {
1509                threadUnexpectedException(fail);
1506              }
1507 <            return null;
1507 >            throw new AssertionError("unreached");
1508          }
1509      }
1510  
# Line 1565 | Line 1561 | public class JSR166TestCase extends Test
1561      }
1562  
1563      public void await(CountDownLatch latch, long timeoutMillis) {
1564 +        boolean timedOut = false;
1565          try {
1566 <            if (!latch.await(timeoutMillis, MILLISECONDS))
1570 <                fail("timed out waiting for CountDownLatch for "
1571 <                     + (timeoutMillis/1000) + " sec");
1566 >            timedOut = !latch.await(timeoutMillis, MILLISECONDS);
1567          } catch (Throwable fail) {
1568              threadUnexpectedException(fail);
1569          }
1570 +        if (timedOut)
1571 +            fail("timed out waiting for CountDownLatch for "
1572 +                 + (timeoutMillis/1000) + " sec");
1573      }
1574  
1575      public void await(CountDownLatch latch) {
# Line 1579 | Line 1577 | public class JSR166TestCase extends Test
1577      }
1578  
1579      public void await(Semaphore semaphore) {
1580 +        boolean timedOut = false;
1581          try {
1582 <            if (!semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS))
1584 <                fail("timed out waiting for Semaphore for "
1585 <                     + (LONG_DELAY_MS/1000) + " sec");
1582 >            timedOut = !semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS);
1583          } catch (Throwable fail) {
1584              threadUnexpectedException(fail);
1585          }
1586 +        if (timedOut)
1587 +            fail("timed out waiting for Semaphore for "
1588 +                 + (LONG_DELAY_MS/1000) + " sec");
1589      }
1590  
1591      public void await(CyclicBarrier barrier) {
# Line 1619 | Line 1619 | public class JSR166TestCase extends Test
1619          public String call() { throw new NullPointerException(); }
1620      }
1621  
1622    public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
1623        protected void realRun() {
1624            try {
1625                delay(SMALL_DELAY_MS);
1626            } catch (InterruptedException ok) {}
1627        }
1628    }
1629
1622      public Runnable possiblyInterruptedRunnable(final long timeoutMillis) {
1623          return new CheckedRunnable() {
1624              protected void realRun() {
# Line 1682 | Line 1674 | public class JSR166TestCase extends Test
1674                  return realCompute();
1675              } catch (Throwable fail) {
1676                  threadUnexpectedException(fail);
1685                return null;
1677              }
1678 +            throw new AssertionError("unreached");
1679          }
1680      }
1681  
# Line 1760 | Line 1752 | public class JSR166TestCase extends Test
1752          }
1753      }
1754  
1755 <    void assertImmutable(final Object o) {
1755 >    void assertImmutable(Object o) {
1756          if (o instanceof Collection) {
1757              assertThrows(
1758                  UnsupportedOperationException.class,
1759 <                new Runnable() { public void run() {
1768 <                        ((Collection) o).add(null);}});
1759 >                () -> ((Collection) o).add(null));
1760          }
1761      }
1762  
1763      @SuppressWarnings("unchecked")
1764      <T> T serialClone(T o) {
1765 +        T clone = null;
1766          try {
1767              ObjectInputStream ois = new ObjectInputStream
1768                  (new ByteArrayInputStream(serialBytes(o)));
1769 <            T clone = (T) ois.readObject();
1778 <            if (o == clone) assertImmutable(o);
1779 <            assertSame(o.getClass(), clone.getClass());
1780 <            return clone;
1769 >            clone = (T) ois.readObject();
1770          } catch (Throwable fail) {
1771              threadUnexpectedException(fail);
1783            return null;
1772          }
1773 +        if (o == clone) assertImmutable(o);
1774 +        else assertSame(o.getClass(), clone.getClass());
1775 +        return clone;
1776      }
1777  
1778      /**
# Line 1800 | Line 1791 | public class JSR166TestCase extends Test
1791              (new ByteArrayInputStream(bos.toByteArray()));
1792          T clone = (T) ois.readObject();
1793          if (o == clone) assertImmutable(o);
1794 <        assertSame(o.getClass(), clone.getClass());
1794 >        else assertSame(o.getClass(), clone.getClass());
1795          return clone;
1796      }
1797  
# Line 1825 | Line 1816 | public class JSR166TestCase extends Test
1816      }
1817  
1818      public void assertThrows(Class<? extends Throwable> expectedExceptionClass,
1819 <                             Runnable... throwingActions) {
1820 <        for (Runnable throwingAction : throwingActions) {
1819 >                             Action... throwingActions) {
1820 >        for (Action throwingAction : throwingActions) {
1821              boolean threw = false;
1822              try { throwingAction.run(); }
1823              catch (Throwable t) {
# Line 2051 | Line 2042 | public class JSR166TestCase extends Test
2042          assertEquals(savedCompletedTaskCount, p.getCompletedTaskCount());
2043          assertEquals(savedQueueSize, p.getQueue().size());
2044      }
2045 +
2046 +    void assertCollectionsEquals(Collection<?> x, Collection<?> y) {
2047 +        assertEquals(x, y);
2048 +        assertEquals(y, x);
2049 +        assertEquals(x.isEmpty(), y.isEmpty());
2050 +        assertEquals(x.size(), y.size());
2051 +        if (x instanceof List) {
2052 +            assertEquals(x.toString(), y.toString());
2053 +        }
2054 +        if (x instanceof List || x instanceof Set) {
2055 +            assertEquals(x.hashCode(), y.hashCode());
2056 +        }
2057 +        if (x instanceof List || x instanceof Deque) {
2058 +            assertTrue(Arrays.equals(x.toArray(), y.toArray()));
2059 +            assertTrue(Arrays.equals(x.toArray(new Object[0]),
2060 +                                     y.toArray(new Object[0])));
2061 +        }
2062 +    }
2063 +
2064 +    /**
2065 +     * A weaker form of assertCollectionsEquals which does not insist
2066 +     * that the two collections satisfy Object#equals(Object), since
2067 +     * they may use identity semantics as Deques do.
2068 +     */
2069 +    void assertCollectionsEquivalent(Collection<?> x, Collection<?> y) {
2070 +        if (x instanceof List || x instanceof Set)
2071 +            assertCollectionsEquals(x, y);
2072 +        else {
2073 +            assertEquals(x.isEmpty(), y.isEmpty());
2074 +            assertEquals(x.size(), y.size());
2075 +            assertEquals(new HashSet(x), new HashSet(y));
2076 +            if (x instanceof Deque) {
2077 +                assertTrue(Arrays.equals(x.toArray(), y.toArray()));
2078 +                assertTrue(Arrays.equals(x.toArray(new Object[0]),
2079 +                                         y.toArray(new Object[0])));
2080 +            }
2081 +        }
2082 +    }
2083   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines