blob: 75e0909eb3c5c5a761bf8bdf0133bd33d2013f63 [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
toma7083182014-09-25 21:38:03 -070015 public static void print(String msg) {
16 System.out.print(msg);
17 }
18
tom931af4e2014-09-13 12:00:57 -070019 /**
20 * Suspends the current thread for a specified number of millis.
21 *
22 * @param ms number of millis
23 */
24 public static void delay(int ms) {
25 try {
26 Thread.sleep(ms);
27 } catch (InterruptedException e) {
28 fail("test interrupted");
29 }
30 }
31
32 /**
33 * Returns the current time in millis since epoch.
34 *
35 * @return current time
36 */
37 public static long now() {
38 return System.currentTimeMillis();
39 }
40
41 /**
42 * Runs the specified runnable until it completes successfully or until the
43 * specified time expires. If the latter occurs, the first encountered
44 * assertion on the last attempt will be re-thrown. Errors other than
45 * assertion errors will be propagated immediately.
46 * <p>
47 * Assertions attempts will not be closer than 10 millis apart and no
48 * further than 50 millis.
49 * </p>
50 *
51 * @param delay number of millis to delay before the first attempt
52 * @param duration number of milliseconds beyond the current time
53 * @param assertions test assertions runnable
54 */
55 public static void assertAfter(int delay, int duration, Runnable assertions) {
56 checkArgument(delay < duration, "delay >= duration");
57 long start = now();
58 int step = Math.max(Math.min((duration - delay) / 100, 50), 10);
59
60 // Is there an initial delay?
61 if (delay > 0) {
62 delay(delay);
63 }
64
65 // Keep going until the assertions succeed or until time runs-out.
66 while (true) {
67 try {
68 assertions.run();
69 break;
70 } catch (AssertionError e) {
71 // If there was an error and time ran out, re-throw it.
72 if (now() - start > duration) {
73 throw e;
74 }
75 }
76 delay(step);
77 }
78 }
79
80 /**
81 * Runs the specified runnable until it completes successfully or until the
82 * specified time expires. If the latter occurs, the first encountered
83 * assertion on the last attempt will be re-thrown. Errors other than
84 * assertion errors will be propagated immediately.
85 * <p>
86 * Assertions attempts will not be closer than 10 millis apart and no
87 * further than 50 millis.
88 * </p>
89 *
90 * @param duration number of milliseconds beyond the current time
91 * @param assertions test assertions runnable
92 */
93 public static void assertAfter(int duration, Runnable assertions) {
94 assertAfter(0, duration, assertions);
95 }
96
97}