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.241 by jsr166, Sun Jan 28 16:20:42 2018 UTC vs.
Revision 1.249 by jsr166, Sat Nov 24 21:41:20 2018 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 448 | Line 459 | public class JSR166TestCase extends Test
459      public static boolean atLeastJava8()  { return JAVA_CLASS_VERSION >= 52.0; }
460      public static boolean atLeastJava9()  { return JAVA_CLASS_VERSION >= 53.0; }
461      public static boolean atLeastJava10() { return JAVA_CLASS_VERSION >= 54.0; }
462 +    public static boolean atLeastJava11() { return JAVA_CLASS_VERSION >= 55.0; }
463  
464      /**
465       * Collects all JSR166 unit tests as one suite.
# Line 1287 | Line 1299 | public class JSR166TestCase extends Test
1299      /**
1300       * Spin-waits up to the specified number of milliseconds for the given
1301       * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
1302 +     * @param waitingForGodot if non-null, an additional condition to satisfy
1303       */
1304 <    void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
1305 <        long startTime = 0L;
1306 <        for (;;) {
1307 <            Thread.State s = thread.getState();
1308 <            if (s == Thread.State.BLOCKED ||
1309 <                s == Thread.State.WAITING ||
1310 <                s == Thread.State.TIMED_WAITING)
1311 <                return;
1312 <            else if (s == Thread.State.TERMINATED)
1304 >    void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis,
1305 >                                       Callable<Boolean> waitingForGodot) {
1306 >        for (long startTime = 0L;;) {
1307 >            switch (thread.getState()) {
1308 >            case BLOCKED: case WAITING: case TIMED_WAITING:
1309 >                try {
1310 >                    if (waitingForGodot == null || waitingForGodot.call())
1311 >                        return;
1312 >                } catch (Throwable fail) { threadUnexpectedException(fail); }
1313 >                break;
1314 >            case TERMINATED:
1315                  fail("Unexpected thread termination");
1316 <            else if (startTime == 0L)
1316 >            }
1317 >
1318 >            if (startTime == 0L)
1319                  startTime = System.nanoTime();
1320              else if (millisElapsedSince(startTime) > timeoutMillis) {
1321 <                threadAssertTrue(thread.isAlive());
1322 <                fail("timed out waiting for thread to enter wait state");
1321 >                assertTrue(thread.isAlive());
1322 >                if (waitingForGodot == null
1323 >                    || thread.getState() == Thread.State.RUNNABLE)
1324 >                    fail("timed out waiting for thread to enter wait state");
1325 >                else
1326 >                    fail("timed out waiting for condition, thread state="
1327 >                         + thread.getState());
1328              }
1329              Thread.yield();
1330          }
# Line 1310 | Line 1332 | public class JSR166TestCase extends Test
1332  
1333      /**
1334       * Spin-waits up to the specified number of milliseconds for the given
1335 <     * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING,
1314 <     * and additionally satisfy the given condition.
1335 >     * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
1336       */
1337 <    void waitForThreadToEnterWaitState(
1338 <        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 <        }
1337 >    void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
1338 >        waitForThreadToEnterWaitState(thread, timeoutMillis, null);
1339      }
1340  
1341      /**
# Line 1343 | Line 1343 | public class JSR166TestCase extends Test
1343       * enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
1344       */
1345      void waitForThreadToEnterWaitState(Thread thread) {
1346 <        waitForThreadToEnterWaitState(thread, LONG_DELAY_MS);
1346 >        waitForThreadToEnterWaitState(thread, LONG_DELAY_MS, null);
1347      }
1348  
1349      /**
# Line 1351 | Line 1351 | public class JSR166TestCase extends Test
1351       * enter a wait state: BLOCKED, WAITING, or TIMED_WAITING,
1352       * and additionally satisfy the given condition.
1353       */
1354 <    void waitForThreadToEnterWaitState(
1355 <        Thread thread, Callable<Boolean> waitingForGodot) {
1354 >    void waitForThreadToEnterWaitState(Thread thread,
1355 >                                       Callable<Boolean> waitingForGodot) {
1356          waitForThreadToEnterWaitState(thread, LONG_DELAY_MS, waitingForGodot);
1357      }
1358  
# Line 1384 | Line 1384 | public class JSR166TestCase extends Test
1384       */
1385      <T> void checkTimedGet(Future<T> f, T expectedValue, long timeoutMillis) {
1386          long startTime = System.nanoTime();
1387 +        T actual = null;
1388          try {
1389 <            assertEquals(expectedValue, f.get(timeoutMillis, MILLISECONDS));
1389 >            actual = f.get(timeoutMillis, MILLISECONDS);
1390          } catch (Throwable fail) { threadUnexpectedException(fail); }
1391 +        assertEquals(expectedValue, actual);
1392          if (millisElapsedSince(startTime) > timeoutMillis/2)
1393              throw new AssertionError("timed get did not return promptly");
1394      }
# Line 1446 | Line 1448 | public class JSR166TestCase extends Test
1448          }
1449      }
1450  
1449    public abstract class RunnableShouldThrow implements Runnable {
1450        protected abstract void realRun() throws Throwable;
1451
1452        final Class<?> exceptionClass;
1453
1454        <T extends Throwable> RunnableShouldThrow(Class<T> exceptionClass) {
1455            this.exceptionClass = exceptionClass;
1456        }
1457
1458        public final void run() {
1459            try {
1460                realRun();
1461                threadShouldThrow(exceptionClass.getSimpleName());
1462            } catch (Throwable t) {
1463                if (! exceptionClass.isInstance(t))
1464                    threadUnexpectedException(t);
1465            }
1466        }
1467    }
1468
1451      public abstract class ThreadShouldThrow extends Thread {
1452          protected abstract void realRun() throws Throwable;
1453  
# Line 1478 | Line 1460 | public class JSR166TestCase extends Test
1460          public final void run() {
1461              try {
1462                  realRun();
1481                threadShouldThrow(exceptionClass.getSimpleName());
1463              } catch (Throwable t) {
1464                  if (! exceptionClass.isInstance(t))
1465                      threadUnexpectedException(t);
1466 +                return;
1467              }
1468 +            threadShouldThrow(exceptionClass.getSimpleName());
1469          }
1470      }
1471  
# Line 1492 | Line 1475 | public class JSR166TestCase extends Test
1475          public final void run() {
1476              try {
1477                  realRun();
1495                threadShouldThrow("InterruptedException");
1478              } catch (InterruptedException success) {
1479                  threadAssertFalse(Thread.interrupted());
1480 +                return;
1481              } catch (Throwable fail) {
1482                  threadUnexpectedException(fail);
1483              }
1484 +            threadShouldThrow("InterruptedException");
1485          }
1486      }
1487  
# Line 1509 | Line 1493 | public class JSR166TestCase extends Test
1493                  return realCall();
1494              } catch (Throwable fail) {
1495                  threadUnexpectedException(fail);
1512                return null;
1513            }
1514        }
1515    }
1516
1517    public abstract class CheckedInterruptedCallable<T>
1518        implements Callable<T> {
1519        protected abstract T realCall() throws Throwable;
1520
1521        public final T call() {
1522            try {
1523                T result = realCall();
1524                threadShouldThrow("InterruptedException");
1525                return result;
1526            } catch (InterruptedException success) {
1527                threadAssertFalse(Thread.interrupted());
1528            } catch (Throwable fail) {
1529                threadUnexpectedException(fail);
1496              }
1497 <            return null;
1497 >            throw new AssertionError("unreached");
1498          }
1499      }
1500  
# Line 1585 | Line 1551 | public class JSR166TestCase extends Test
1551      }
1552  
1553      public void await(CountDownLatch latch, long timeoutMillis) {
1554 +        boolean timedOut = false;
1555          try {
1556 <            if (!latch.await(timeoutMillis, MILLISECONDS))
1590 <                fail("timed out waiting for CountDownLatch for "
1591 <                     + (timeoutMillis/1000) + " sec");
1556 >            timedOut = !latch.await(timeoutMillis, MILLISECONDS);
1557          } catch (Throwable fail) {
1558              threadUnexpectedException(fail);
1559          }
1560 +        if (timedOut)
1561 +            fail("timed out waiting for CountDownLatch for "
1562 +                 + (timeoutMillis/1000) + " sec");
1563      }
1564  
1565      public void await(CountDownLatch latch) {
# Line 1599 | Line 1567 | public class JSR166TestCase extends Test
1567      }
1568  
1569      public void await(Semaphore semaphore) {
1570 +        boolean timedOut = false;
1571          try {
1572 <            if (!semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS))
1604 <                fail("timed out waiting for Semaphore for "
1605 <                     + (LONG_DELAY_MS/1000) + " sec");
1572 >            timedOut = !semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS);
1573          } catch (Throwable fail) {
1574              threadUnexpectedException(fail);
1575          }
1576 +        if (timedOut)
1577 +            fail("timed out waiting for Semaphore for "
1578 +                 + (LONG_DELAY_MS/1000) + " sec");
1579      }
1580  
1581      public void await(CyclicBarrier barrier) {
# Line 1639 | Line 1609 | public class JSR166TestCase extends Test
1609          public String call() { throw new NullPointerException(); }
1610      }
1611  
1642    public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
1643        protected void realRun() {
1644            try {
1645                delay(SMALL_DELAY_MS);
1646            } catch (InterruptedException ok) {}
1647        }
1648    }
1649
1612      public Runnable possiblyInterruptedRunnable(final long timeoutMillis) {
1613          return new CheckedRunnable() {
1614              protected void realRun() {
# Line 1702 | Line 1664 | public class JSR166TestCase extends Test
1664                  return realCompute();
1665              } catch (Throwable fail) {
1666                  threadUnexpectedException(fail);
1705                return null;
1667              }
1668 +            throw new AssertionError("unreached");
1669          }
1670      }
1671  
# Line 1791 | Line 1753 | public class JSR166TestCase extends Test
1753  
1754      @SuppressWarnings("unchecked")
1755      <T> T serialClone(T o) {
1756 +        T clone = null;
1757          try {
1758              ObjectInputStream ois = new ObjectInputStream
1759                  (new ByteArrayInputStream(serialBytes(o)));
1760 <            T clone = (T) ois.readObject();
1798 <            if (o == clone) assertImmutable(o);
1799 <            assertSame(o.getClass(), clone.getClass());
1800 <            return clone;
1760 >            clone = (T) ois.readObject();
1761          } catch (Throwable fail) {
1762              threadUnexpectedException(fail);
1803            return null;
1763          }
1764 +        if (o == clone) assertImmutable(o);
1765 +        else assertSame(o.getClass(), clone.getClass());
1766 +        return clone;
1767      }
1768  
1769      /**
# Line 1820 | Line 1782 | public class JSR166TestCase extends Test
1782              (new ByteArrayInputStream(bos.toByteArray()));
1783          T clone = (T) ois.readObject();
1784          if (o == clone) assertImmutable(o);
1785 <        assertSame(o.getClass(), clone.getClass());
1785 >        else assertSame(o.getClass(), clone.getClass());
1786          return clone;
1787      }
1788  
# Line 2071 | Line 2033 | public class JSR166TestCase extends Test
2033          assertEquals(savedCompletedTaskCount, p.getCompletedTaskCount());
2034          assertEquals(savedQueueSize, p.getQueue().size());
2035      }
2036 +
2037 +    void assertCollectionsEquals(Collection<?> x, Collection<?> y) {
2038 +        assertEquals(x, y);
2039 +        assertEquals(y, x);
2040 +        assertEquals(x.isEmpty(), y.isEmpty());
2041 +        assertEquals(x.size(), y.size());
2042 +        if (x instanceof List) {
2043 +            assertEquals(x.toString(), y.toString());
2044 +        }
2045 +        if (x instanceof List || x instanceof Set) {
2046 +            assertEquals(x.hashCode(), y.hashCode());
2047 +        }
2048 +        if (x instanceof List || x instanceof Deque) {
2049 +            assertTrue(Arrays.equals(x.toArray(), y.toArray()));
2050 +            assertTrue(Arrays.equals(x.toArray(new Object[0]),
2051 +                                     y.toArray(new Object[0])));
2052 +        }
2053 +    }
2054 +
2055 +    /**
2056 +     * A weaker form of assertCollectionsEquals which does not insist
2057 +     * that the two collections satisfy Object#equals(Object), since
2058 +     * they may use identity semantics as Deques do.
2059 +     */
2060 +    void assertCollectionsEquivalent(Collection<?> x, Collection<?> y) {
2061 +        if (x instanceof List || x instanceof Set)
2062 +            assertCollectionsEquals(x, y);
2063 +        else {
2064 +            assertEquals(x.isEmpty(), y.isEmpty());
2065 +            assertEquals(x.size(), y.size());
2066 +            assertEquals(new HashSet(x), new HashSet(y));
2067 +            if (x instanceof Deque) {
2068 +                assertTrue(Arrays.equals(x.toArray(), y.toArray()));
2069 +                assertTrue(Arrays.equals(x.toArray(new Object[0]),
2070 +                                         y.toArray(new Object[0])));
2071 +            }
2072 +        }
2073 +    }
2074   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines