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.88 by jsr166, Tue May 31 15:01:24 2011 UTC vs.
Revision 1.130 by jsr166, Tue Apr 21 05:00:23 2015 UTC

# Line 6 | Line 6
6   * Pat Fisher, Mike Judd.
7   */
8  
9 < import junit.framework.*;
9 > import static java.util.concurrent.TimeUnit.MILLISECONDS;
10 > import static java.util.concurrent.TimeUnit.NANOSECONDS;
11 >
12   import java.io.ByteArrayInputStream;
13   import java.io.ByteArrayOutputStream;
14   import java.io.ObjectInputStream;
15   import java.io.ObjectOutputStream;
16 < import java.util.Arrays;
17 < import java.util.Date;
18 < import java.util.NoSuchElementException;
17 < import java.util.PropertyPermission;
18 < import java.util.concurrent.*;
19 < import java.util.concurrent.atomic.AtomicBoolean;
20 < import java.util.concurrent.atomic.AtomicReference;
21 < import static java.util.concurrent.TimeUnit.MILLISECONDS;
22 < import static java.util.concurrent.TimeUnit.NANOSECONDS;
16 > import java.lang.management.ManagementFactory;
17 > import java.lang.management.ThreadInfo;
18 > import java.lang.reflect.Method;
19   import java.security.CodeSource;
20   import java.security.Permission;
21   import java.security.PermissionCollection;
# Line 27 | Line 23 | import java.security.Permissions;
23   import java.security.Policy;
24   import java.security.ProtectionDomain;
25   import java.security.SecurityPermission;
26 + import java.util.ArrayList;
27 + import java.util.Arrays;
28 + import java.util.Date;
29 + import java.util.Enumeration;
30 + import java.util.Iterator;
31 + import java.util.List;
32 + import java.util.NoSuchElementException;
33 + import java.util.PropertyPermission;
34 + import java.util.concurrent.BlockingQueue;
35 + import java.util.concurrent.Callable;
36 + import java.util.concurrent.CountDownLatch;
37 + import java.util.concurrent.CyclicBarrier;
38 + import java.util.concurrent.ExecutorService;
39 + import java.util.concurrent.Future;
40 + import java.util.concurrent.RecursiveAction;
41 + import java.util.concurrent.RecursiveTask;
42 + import java.util.concurrent.RejectedExecutionHandler;
43 + import java.util.concurrent.Semaphore;
44 + import java.util.concurrent.ThreadFactory;
45 + import java.util.concurrent.ThreadPoolExecutor;
46 + import java.util.concurrent.TimeoutException;
47 + import java.util.concurrent.atomic.AtomicReference;
48 + import java.util.regex.Pattern;
49 +
50 + import junit.framework.AssertionFailedError;
51 + import junit.framework.Test;
52 + import junit.framework.TestCase;
53 + import junit.framework.TestSuite;
54  
55   /**
56   * Base class for JSR166 Junit TCK tests.  Defines some constants,
# Line 69 | Line 93 | import java.security.SecurityPermission;
93   *
94   * </ol>
95   *
96 < * <p> <b>Other notes</b>
96 > * <p><b>Other notes</b>
97   * <ul>
98   *
99   * <li> Usually, there is one testcase method per JSR166 method
# Line 109 | Line 133 | public class JSR166TestCase extends Test
133          Boolean.getBoolean("jsr166.expensiveTests");
134  
135      /**
136 +     * If true, also run tests that are not part of the official tck
137 +     * because they test unspecified implementation details.
138 +     */
139 +    protected static final boolean testImplementationDetails =
140 +        Boolean.getBoolean("jsr166.testImplementationDetails");
141 +
142 +    /**
143       * If true, report on stdout all "slow" tests, that is, ones that
144       * take more than profileThreshold milliseconds to execute.
145       */
# Line 122 | Line 153 | public class JSR166TestCase extends Test
153      private static final long profileThreshold =
154          Long.getLong("jsr166.profileThreshold", 100);
155  
156 +    /**
157 +     * The number of repetitions per test (for tickling rare bugs).
158 +     */
159 +    private static final int runsPerTest =
160 +        Integer.getInteger("jsr166.runsPerTest", 1);
161 +
162 +    /**
163 +     * A filter for tests to run, matching strings of the form
164 +     * methodName(className), e.g. "testInvokeAll5(ForkJoinPoolTest)"
165 +     * Usefully combined with jsr166.runsPerTest.
166 +     */
167 +    private static final Pattern methodFilter = methodFilter();
168 +
169 +    private static Pattern methodFilter() {
170 +        String regex = System.getProperty("jsr166.methodFilter");
171 +        return (regex == null) ? null : Pattern.compile(regex);
172 +    }
173 +
174      protected void runTest() throws Throwable {
175 <        if (profileTests)
176 <            runTestProfiled();
177 <        else
178 <            super.runTest();
175 >        if (methodFilter == null
176 >            || methodFilter.matcher(toString()).find()) {
177 >            for (int i = 0; i < runsPerTest; i++) {
178 >                if (profileTests)
179 >                    runTestProfiled();
180 >                else
181 >                    super.runTest();
182 >            }
183 >        }
184      }
185  
186      protected void runTestProfiled() throws Throwable {
187 +        // Warmup run, notably to trigger all needed classloading.
188 +        super.runTest();
189          long t0 = System.nanoTime();
190          try {
191              super.runTest();
192          } finally {
193 <            long elapsedMillis =
138 <                (System.nanoTime() - t0) / (1000L * 1000L);
193 >            long elapsedMillis = millisElapsedSince(t0);
194              if (elapsedMillis >= profileThreshold)
195                  System.out.printf("%n%s: %d%n", toString(), elapsedMillis);
196          }
197      }
198  
199      /**
200 <     * Runs all JSR166 unit tests using junit.textui.TestRunner
200 >     * 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.
203       */
204      public static void main(String[] args) {
205          if (useSecurityManager) {
# Line 174 | Line 231 | public class JSR166TestCase extends Test
231          return suite;
232      }
233  
234 +    public static void addNamedTestClasses(TestSuite suite,
235 +                                           String... testClassNames) {
236 +        for (String testClassName : testClassNames) {
237 +            try {
238 +                Class<?> testClass = Class.forName(testClassName);
239 +                Method m = testClass.getDeclaredMethod("suite",
240 +                                                       new Class<?>[0]);
241 +                suite.addTest(newTestSuite((Test)m.invoke(null)));
242 +            } catch (Exception e) {
243 +                throw new Error("Missing test class", e);
244 +            }
245 +        }
246 +    }
247 +
248 +    public static final double JAVA_CLASS_VERSION;
249 +    public static final String JAVA_SPECIFICATION_VERSION;
250 +    static {
251 +        try {
252 +            JAVA_CLASS_VERSION = java.security.AccessController.doPrivileged(
253 +                new java.security.PrivilegedAction<Double>() {
254 +                public Double run() {
255 +                    return Double.valueOf(System.getProperty("java.class.version"));}});
256 +            JAVA_SPECIFICATION_VERSION = java.security.AccessController.doPrivileged(
257 +                new java.security.PrivilegedAction<String>() {
258 +                public String run() {
259 +                    return System.getProperty("java.specification.version");}});
260 +        } catch (Throwable t) {
261 +            throw new Error(t);
262 +        }
263 +    }
264 +
265 +    public static boolean atLeastJava6() { return JAVA_CLASS_VERSION >= 50.0; }
266 +    public static boolean atLeastJava7() { return JAVA_CLASS_VERSION >= 51.0; }
267 +    public static boolean atLeastJava8() { return JAVA_CLASS_VERSION >= 52.0; }
268 +    public static boolean atLeastJava9() { return JAVA_CLASS_VERSION >= 53.0; }
269 +
270      /**
271       * Collects all JSR166 unit tests as one suite.
272       */
273      public static Test suite() {
274 <        return newTestSuite(
274 >        // Java7+ test classes
275 >        TestSuite suite = newTestSuite(
276              ForkJoinPoolTest.suite(),
277              ForkJoinTaskTest.suite(),
278              RecursiveActionTest.suite(),
# Line 243 | Line 337 | public class JSR166TestCase extends Test
337              TreeSetTest.suite(),
338              TreeSubMapTest.suite(),
339              TreeSubSetTest.suite());
340 +
341 +        // Java8+ test classes
342 +        if (atLeastJava8()) {
343 +            String[] java8TestClassNames = {
344 +                "Atomic8Test",
345 +                "CompletableFutureTest",
346 +                "ConcurrentHashMap8Test",
347 +                "CountedCompleterTest",
348 +                "DoubleAccumulatorTest",
349 +                "DoubleAdderTest",
350 +                "ForkJoinPool8Test",
351 +                "ForkJoinTask8Test",
352 +                "LongAccumulatorTest",
353 +                "LongAdderTest",
354 +                "SplittableRandomTest",
355 +                "StampedLockTest",
356 +                "ThreadLocalRandom8Test",
357 +            };
358 +            addNamedTestClasses(suite, java8TestClassNames);
359 +        }
360 +
361 +        // Java9+ test classes
362 +        if (atLeastJava9()) {
363 +            String[] java9TestClassNames = {
364 +                "ThreadPoolExecutor9Test",
365 +            };
366 +            addNamedTestClasses(suite, java9TestClassNames);
367 +        }
368 +
369 +        return suite;
370      }
371  
372 +    // Delays for timing-dependent tests, in milliseconds.
373  
374      public static long SHORT_DELAY_MS;
375      public static long SMALL_DELAY_MS;
376      public static long MEDIUM_DELAY_MS;
377      public static long LONG_DELAY_MS;
378  
254
379      /**
380       * Returns the shortest timed delay. This could
381       * be reimplemented to use for example a Property.
# Line 334 | Line 458 | public class JSR166TestCase extends Test
458  
459          if (Thread.interrupted())
460              throw new AssertionFailedError("interrupt status set in main thread");
461 +
462 +        checkForkJoinPoolThreadLeaks();
463 +    }
464 +
465 +    /**
466 +     * Finds missing try { ... } finally { joinPool(e); }
467 +     */
468 +    void checkForkJoinPoolThreadLeaks() throws InterruptedException {
469 +        Thread[] survivors = new Thread[5];
470 +        int count = Thread.enumerate(survivors);
471 +        for (int i = 0; i < count; i++) {
472 +            Thread thread = survivors[i];
473 +            String name = thread.getName();
474 +            if (name.startsWith("ForkJoinPool-")) {
475 +                // give thread some time to terminate
476 +                thread.join(LONG_DELAY_MS);
477 +                if (!thread.isAlive()) continue;
478 +                thread.stop();
479 +                throw new AssertionFailedError
480 +                    (String.format("Found leaked ForkJoinPool thread test=%s thread=%s%n",
481 +                                   toString(), name));
482 +            }
483 +        }
484      }
485  
486      /**
# Line 414 | Line 561 | public class JSR166TestCase extends Test
561      public void threadAssertEquals(Object x, Object y) {
562          try {
563              assertEquals(x, y);
564 <        } catch (AssertionFailedError t) {
565 <            threadRecordFailure(t);
566 <            throw t;
567 <        } catch (Throwable t) {
568 <            threadUnexpectedException(t);
564 >        } catch (AssertionFailedError fail) {
565 >            threadRecordFailure(fail);
566 >            throw fail;
567 >        } catch (Throwable fail) {
568 >            threadUnexpectedException(fail);
569          }
570      }
571  
# Line 430 | Line 577 | public class JSR166TestCase extends Test
577      public void threadAssertSame(Object x, Object y) {
578          try {
579              assertSame(x, y);
580 <        } catch (AssertionFailedError t) {
581 <            threadRecordFailure(t);
582 <            throw t;
580 >        } catch (AssertionFailedError fail) {
581 >            threadRecordFailure(fail);
582 >            throw fail;
583          }
584      }
585  
# Line 497 | Line 644 | public class JSR166TestCase extends Test
644      void joinPool(ExecutorService exec) {
645          try {
646              exec.shutdown();
647 <            assertTrue("ExecutorService did not terminate in a timely manner",
648 <                       exec.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS));
647 >            if (!exec.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS))
648 >                fail("ExecutorService " + exec +
649 >                     " did not terminate in a timely manner");
650          } catch (SecurityException ok) {
651              // Allowed in case test doesn't have privs
652 <        } catch (InterruptedException ie) {
652 >        } catch (InterruptedException fail) {
653              fail("Unexpected InterruptedException");
654          }
655      }
656  
657      /**
658 +     * A debugging tool to print all stack traces, as jstack does.
659 +     */
660 +    static void printAllStackTraces() {
661 +        for (ThreadInfo info :
662 +                 ManagementFactory.getThreadMXBean()
663 +                 .dumpAllThreads(true, true))
664 +            System.err.print(info);
665 +    }
666 +
667 +    /**
668       * Checks that thread does not terminate within the default
669       * millisecond delay of {@code timeoutMillis()}.
670       */
# Line 522 | Line 680 | public class JSR166TestCase extends Test
680              // No need to optimize the failing case via Thread.join.
681              delay(millis);
682              assertTrue(thread.isAlive());
683 <        } catch (InterruptedException ie) {
683 >        } catch (InterruptedException fail) {
684 >            fail("Unexpected InterruptedException");
685 >        }
686 >    }
687 >
688 >    /**
689 >     * Checks that the threads do not terminate within the default
690 >     * millisecond delay of {@code timeoutMillis()}.
691 >     */
692 >    void assertThreadsStayAlive(Thread... threads) {
693 >        assertThreadsStayAlive(timeoutMillis(), threads);
694 >    }
695 >
696 >    /**
697 >     * Checks that the threads do not terminate within the given millisecond delay.
698 >     */
699 >    void assertThreadsStayAlive(long millis, Thread... threads) {
700 >        try {
701 >            // No need to optimize the failing case via Thread.join.
702 >            delay(millis);
703 >            for (Thread thread : threads)
704 >                assertTrue(thread.isAlive());
705 >        } catch (InterruptedException fail) {
706              fail("Unexpected InterruptedException");
707          }
708      }
# Line 544 | Line 724 | public class JSR166TestCase extends Test
724              future.get(timeoutMillis, MILLISECONDS);
725              shouldThrow();
726          } catch (TimeoutException success) {
727 <        } catch (Exception e) {
728 <            threadUnexpectedException(e);
727 >        } catch (Exception fail) {
728 >            threadUnexpectedException(fail);
729          } finally { future.cancel(true); }
730          assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
731      }
# Line 589 | Line 769 | public class JSR166TestCase extends Test
769      public static final Integer m6  = new Integer(-6);
770      public static final Integer m10 = new Integer(-10);
771  
592
772      /**
773       * Runs Runnable r with a security policy that permits precisely
774       * the specified permissions.  If there is no current security
# Line 601 | Line 780 | public class JSR166TestCase extends Test
780          SecurityManager sm = System.getSecurityManager();
781          if (sm == null) {
782              r.run();
783 +        }
784 +        runWithSecurityManagerWithPermissions(r, permissions);
785 +    }
786 +
787 +    /**
788 +     * Runs Runnable r with a security policy that permits precisely
789 +     * the specified permissions.  If there is no current security
790 +     * manager, a temporary one is set for the duration of the
791 +     * Runnable.  We require that any security manager permit
792 +     * getPolicy/setPolicy.
793 +     */
794 +    public void runWithSecurityManagerWithPermissions(Runnable r,
795 +                                                      Permission... permissions) {
796 +        SecurityManager sm = System.getSecurityManager();
797 +        if (sm == null) {
798              Policy savedPolicy = Policy.getPolicy();
799              try {
800                  Policy.setPolicy(permissivePolicy());
801                  System.setSecurityManager(new SecurityManager());
802 <                runWithPermissions(r, permissions);
802 >                runWithSecurityManagerWithPermissions(r, permissions);
803              } finally {
804                  System.setSecurityManager(null);
805                  Policy.setPolicy(savedPolicy);
# Line 653 | Line 847 | public class JSR166TestCase extends Test
847              return perms.implies(p);
848          }
849          public void refresh() {}
850 +        public String toString() {
851 +            List<Permission> ps = new ArrayList<Permission>();
852 +            for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
853 +                ps.add(e.nextElement());
854 +            return "AdjustablePolicy with permissions " + ps;
855 +        }
856      }
857  
858      /**
# Line 681 | Line 881 | public class JSR166TestCase extends Test
881      void sleep(long millis) {
882          try {
883              delay(millis);
884 <        } catch (InterruptedException ie) {
884 >        } catch (InterruptedException fail) {
885              AssertionFailedError afe =
886                  new AssertionFailedError("Unexpected InterruptedException");
887 <            afe.initCause(ie);
887 >            afe.initCause(fail);
888              throw afe;
889          }
890      }
# Line 722 | Line 922 | public class JSR166TestCase extends Test
922      /**
923       * Returns the number of milliseconds since time given by
924       * startNanoTime, which must have been previously returned from a
925 <     * call to {@link System.nanoTime()}.
925 >     * call to {@link System#nanoTime()}.
926       */
927 <    long millisElapsedSince(long startNanoTime) {
927 >    static long millisElapsedSince(long startNanoTime) {
928          return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
929      }
930  
931 + //     void assertTerminatesPromptly(long timeoutMillis, Runnable r) {
932 + //         long startTime = System.nanoTime();
933 + //         try {
934 + //             r.run();
935 + //         } catch (Throwable fail) { threadUnexpectedException(fail); }
936 + //         if (millisElapsedSince(startTime) > timeoutMillis/2)
937 + //             throw new AssertionFailedError("did not return promptly");
938 + //     }
939 +
940 + //     void assertTerminatesPromptly(Runnable r) {
941 + //         assertTerminatesPromptly(LONG_DELAY_MS/2, r);
942 + //     }
943 +
944 +    /**
945 +     * Checks that timed f.get() returns the expected value, and does not
946 +     * wait for the timeout to elapse before returning.
947 +     */
948 +    <T> void checkTimedGet(Future<T> f, T expectedValue, long timeoutMillis) {
949 +        long startTime = System.nanoTime();
950 +        try {
951 +            assertEquals(expectedValue, f.get(timeoutMillis, MILLISECONDS));
952 +        } catch (Throwable fail) { threadUnexpectedException(fail); }
953 +        if (millisElapsedSince(startTime) > timeoutMillis/2)
954 +            throw new AssertionFailedError("timed get did not return promptly");
955 +    }
956 +
957 +    <T> void checkTimedGet(Future<T> f, T expectedValue) {
958 +        checkTimedGet(f, expectedValue, LONG_DELAY_MS);
959 +    }
960 +
961      /**
962       * Returns a new started daemon Thread running the given runnable.
963       */
# Line 746 | Line 976 | public class JSR166TestCase extends Test
976      void awaitTermination(Thread t, long timeoutMillis) {
977          try {
978              t.join(timeoutMillis);
979 <        } catch (InterruptedException ie) {
980 <            threadUnexpectedException(ie);
979 >        } catch (InterruptedException fail) {
980 >            threadUnexpectedException(fail);
981          } finally {
982              if (t.getState() != Thread.State.TERMINATED) {
983                  t.interrupt();
# Line 773 | Line 1003 | public class JSR166TestCase extends Test
1003          public final void run() {
1004              try {
1005                  realRun();
1006 <            } catch (Throwable t) {
1007 <                threadUnexpectedException(t);
1006 >            } catch (Throwable fail) {
1007 >                threadUnexpectedException(fail);
1008              }
1009          }
1010      }
# Line 828 | Line 1058 | public class JSR166TestCase extends Test
1058                  threadShouldThrow("InterruptedException");
1059              } catch (InterruptedException success) {
1060                  threadAssertFalse(Thread.interrupted());
1061 <            } catch (Throwable t) {
1062 <                threadUnexpectedException(t);
1061 >            } catch (Throwable fail) {
1062 >                threadUnexpectedException(fail);
1063              }
1064          }
1065      }
# Line 840 | Line 1070 | public class JSR166TestCase extends Test
1070          public final T call() {
1071              try {
1072                  return realCall();
1073 <            } catch (Throwable t) {
1074 <                threadUnexpectedException(t);
1073 >            } catch (Throwable fail) {
1074 >                threadUnexpectedException(fail);
1075                  return null;
1076              }
1077          }
# Line 858 | Line 1088 | public class JSR166TestCase extends Test
1088                  return result;
1089              } catch (InterruptedException success) {
1090                  threadAssertFalse(Thread.interrupted());
1091 <            } catch (Throwable t) {
1092 <                threadUnexpectedException(t);
1091 >            } catch (Throwable fail) {
1092 >                threadUnexpectedException(fail);
1093              }
1094              return null;
1095          }
# Line 899 | Line 1129 | public class JSR166TestCase extends Test
1129      public void await(CountDownLatch latch) {
1130          try {
1131              assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
1132 <        } catch (Throwable t) {
1133 <            threadUnexpectedException(t);
1132 >        } catch (Throwable fail) {
1133 >            threadUnexpectedException(fail);
1134 >        }
1135 >    }
1136 >
1137 >    public void await(Semaphore semaphore) {
1138 >        try {
1139 >            assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
1140 >        } catch (Throwable fail) {
1141 >            threadUnexpectedException(fail);
1142          }
1143      }
1144  
# Line 1091 | Line 1329 | public class JSR166TestCase extends Test
1329      public abstract class CheckedRecursiveAction extends RecursiveAction {
1330          protected abstract void realCompute() throws Throwable;
1331  
1332 <        public final void compute() {
1332 >        @Override protected final void compute() {
1333              try {
1334                  realCompute();
1335 <            } catch (Throwable t) {
1336 <                threadUnexpectedException(t);
1335 >            } catch (Throwable fail) {
1336 >                threadUnexpectedException(fail);
1337              }
1338          }
1339      }
# Line 1106 | Line 1344 | public class JSR166TestCase extends Test
1344      public abstract class CheckedRecursiveTask<T> extends RecursiveTask<T> {
1345          protected abstract T realCompute() throws Throwable;
1346  
1347 <        public final T compute() {
1347 >        @Override protected final T compute() {
1348              try {
1349                  return realCompute();
1350 <            } catch (Throwable t) {
1351 <                threadUnexpectedException(t);
1350 >            } catch (Throwable fail) {
1351 >                threadUnexpectedException(fail);
1352                  return null;
1353              }
1354          }
# Line 1134 | Line 1372 | public class JSR166TestCase extends Test
1372          public int await() {
1373              try {
1374                  return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1375 <            } catch (TimeoutException e) {
1375 >            } catch (TimeoutException timedOut) {
1376                  throw new AssertionFailedError("timed out");
1377 <            } catch (Exception e) {
1377 >            } catch (Exception fail) {
1378                  AssertionFailedError afe =
1379 <                    new AssertionFailedError("Unexpected exception: " + e);
1380 <                afe.initCause(e);
1379 >                    new AssertionFailedError("Unexpected exception: " + fail);
1380 >                afe.initCause(fail);
1381                  throw afe;
1382              }
1383          }
# Line 1167 | Line 1405 | public class JSR166TestCase extends Test
1405                  q.remove();
1406                  shouldThrow();
1407              } catch (NoSuchElementException success) {}
1408 <        } catch (InterruptedException ie) {
1171 <            threadUnexpectedException(ie);
1172 <        }
1408 >        } catch (InterruptedException fail) { threadUnexpectedException(fail); }
1409      }
1410  
1411 <    @SuppressWarnings("unchecked")
1412 <    <T> T serialClone(T o) {
1411 >    void assertSerialEquals(Object x, Object y) {
1412 >        assertTrue(Arrays.equals(serialBytes(x), serialBytes(y)));
1413 >    }
1414 >
1415 >    void assertNotSerialEquals(Object x, Object y) {
1416 >        assertFalse(Arrays.equals(serialBytes(x), serialBytes(y)));
1417 >    }
1418 >
1419 >    byte[] serialBytes(Object o) {
1420          try {
1421              ByteArrayOutputStream bos = new ByteArrayOutputStream();
1422              ObjectOutputStream oos = new ObjectOutputStream(bos);
1423              oos.writeObject(o);
1424              oos.flush();
1425              oos.close();
1426 +            return bos.toByteArray();
1427 +        } catch (Throwable fail) {
1428 +            threadUnexpectedException(fail);
1429 +            return new byte[0];
1430 +        }
1431 +    }
1432 +
1433 +    @SuppressWarnings("unchecked")
1434 +    <T> T serialClone(T o) {
1435 +        try {
1436              ObjectInputStream ois = new ObjectInputStream
1437 <                (new ByteArrayInputStream(bos.toByteArray()));
1437 >                (new ByteArrayInputStream(serialBytes(o)));
1438              T clone = (T) ois.readObject();
1439              assertSame(o.getClass(), clone.getClass());
1440              return clone;
1441 <        } catch (Throwable t) {
1442 <            threadUnexpectedException(t);
1441 >        } catch (Throwable fail) {
1442 >            threadUnexpectedException(fail);
1443              return null;
1444          }
1445      }
1446 +
1447 +    public void assertThrows(Class<? extends Throwable> expectedExceptionClass,
1448 +                             Runnable... throwingActions) {
1449 +        for (Runnable throwingAction : throwingActions) {
1450 +            boolean threw = false;
1451 +            try { throwingAction.run(); }
1452 +            catch (Throwable t) {
1453 +                threw = true;
1454 +                if (!expectedExceptionClass.isInstance(t)) {
1455 +                    AssertionFailedError afe =
1456 +                        new AssertionFailedError
1457 +                        ("Expected " + expectedExceptionClass.getName() +
1458 +                         ", got " + t.getClass().getName());
1459 +                    afe.initCause(t);
1460 +                    threadUnexpectedException(afe);
1461 +                }
1462 +            }
1463 +            if (!threw)
1464 +                shouldThrow(expectedExceptionClass.getName());
1465 +        }
1466 +    }
1467 +
1468 +    public void assertIteratorExhausted(Iterator<?> it) {
1469 +        try {
1470 +            it.next();
1471 +            shouldThrow();
1472 +        } catch (NoSuchElementException success) {}
1473 +        assertFalse(it.hasNext());
1474 +    }
1475   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines