blob: 959d5d998a48b487beffb26d0264473b731a5389 [file] [log] [blame]
tom931af4e2014-09-13 12:00:57 -07001package org.onlab.junit;
2
3import static com.google.common.base.Preconditions.checkArgument;
4import static org.junit.Assert.fail;
5
6/**
7 * Utilities to aid in producing JUnit tests.
8 */
9public final class TestTools {
10
11 // Prohibit construction
12 private TestTools() {
13 }
14
15 /**
16 * Suspends the current thread for a specified number of millis.
17 *
18 * @param ms number of millis
19 */
20 public static void delay(int ms) {
21 try {
22 Thread.sleep(ms);
23 } catch (InterruptedException e) {
24 fail("test interrupted");
25 }
26 }
27
28 /**
29 * Returns the current time in millis since epoch.
30 *
31 * @return current time
32 */
33 public static long now() {
34 return System.currentTimeMillis();
35 }
36
37 /**
38 * Runs the specified runnable until it completes successfully or until the
39 * specified time expires. If the latter occurs, the first encountered
40 * assertion on the last attempt will be re-thrown. Errors other than
41 * assertion errors will be propagated immediately.
42 * <p>
43 * Assertions attempts will not be closer than 10 millis apart and no
44 * further than 50 millis.
45 * </p>
46 *
47 * @param delay number of millis to delay before the first attempt
48 * @param duration number of milliseconds beyond the current time
49 * @param assertions test assertions runnable
50 */
51 public static void assertAfter(int delay, int duration, Runnable assertions) {
52 checkArgument(delay < duration, "delay >= duration");
53 long start = now();
54 int step = Math.max(Math.min((duration - delay) / 100, 50), 10);
55
56 // Is there an initial delay?
57 if (delay > 0) {
58 delay(delay);
59 }
60
61 // Keep going until the assertions succeed or until time runs-out.
62 while (true) {
63 try {
64 assertions.run();
65 break;
66 } catch (AssertionError e) {
67 // If there was an error and time ran out, re-throw it.
68 if (now() - start > duration) {
69 throw e;
70 }
71 }
72 delay(step);
73 }
74 }
75
76 /**
77 * Runs the specified runnable until it completes successfully or until the
78 * specified time expires. If the latter occurs, the first encountered
79 * assertion on the last attempt will be re-thrown. Errors other than
80 * assertion errors will be propagated immediately.
81 * <p>
82 * Assertions attempts will not be closer than 10 millis apart and no
83 * further than 50 millis.
84 * </p>
85 *
86 * @param duration number of milliseconds beyond the current time
87 * @param assertions test assertions runnable
88 */
89 public static void assertAfter(int duration, Runnable assertions) {
90 assertAfter(0, duration, assertions);
91 }
92
93}