blob: 40e8686c942e83b021bb812e40f01d7919e8e9e9 [file] [log] [blame]
Thomas Vachuska24c849c2014-10-27 09:53:05 -07001/*
Ray Milkey34c95902015-04-15 09:47:53 -07002 * Copyright 2014-2015 Open Networking Laboratory
Thomas Vachuska24c849c2014-10-27 09:53:05 -07003 *
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07004 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
Thomas Vachuska24c849c2014-10-27 09:53:05 -07007 *
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07008 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
Thomas Vachuska24c849c2014-10-27 09:53:05 -070015 */
tom931af4e2014-09-13 12:00:57 -070016package org.onlab.junit;
17
Thomas Vachuska02aeb032015-01-06 22:36:30 -080018import com.google.common.collect.ImmutableList;
19import com.google.common.io.Files;
20
21import java.io.File;
22import java.io.IOException;
Ray Milkey7f9e0202015-11-04 17:14:09 -080023import java.net.ServerSocket;
Thomas Vachuska02aeb032015-01-06 22:36:30 -080024import java.util.List;
25import java.util.Random;
26
tom931af4e2014-09-13 12:00:57 -070027import static com.google.common.base.Preconditions.checkArgument;
28import static org.junit.Assert.fail;
29
30/**
31 * Utilities to aid in producing JUnit tests.
32 */
33public final class TestTools {
34
Thomas Vachuska02aeb032015-01-06 22:36:30 -080035 private static final Random RANDOM = new Random();
36
tom931af4e2014-09-13 12:00:57 -070037 // Prohibit construction
38 private TestTools() {
39 }
40
toma7083182014-09-25 21:38:03 -070041 public static void print(String msg) {
42 System.out.print(msg);
43 }
44
tom931af4e2014-09-13 12:00:57 -070045 /**
46 * Suspends the current thread for a specified number of millis.
47 *
48 * @param ms number of millis
49 */
50 public static void delay(int ms) {
51 try {
52 Thread.sleep(ms);
53 } catch (InterruptedException e) {
54 fail("test interrupted");
55 }
56 }
57
58 /**
59 * Returns the current time in millis since epoch.
60 *
61 * @return current time
62 */
63 public static long now() {
64 return System.currentTimeMillis();
65 }
66
67 /**
68 * Runs the specified runnable until it completes successfully or until the
69 * specified time expires. If the latter occurs, the first encountered
70 * assertion on the last attempt will be re-thrown. Errors other than
71 * assertion errors will be propagated immediately.
72 * <p>
73 * Assertions attempts will not be closer than 10 millis apart and no
74 * further than 50 millis.
75 * </p>
76 *
77 * @param delay number of millis to delay before the first attempt
78 * @param duration number of milliseconds beyond the current time
79 * @param assertions test assertions runnable
80 */
81 public static void assertAfter(int delay, int duration, Runnable assertions) {
82 checkArgument(delay < duration, "delay >= duration");
83 long start = now();
84 int step = Math.max(Math.min((duration - delay) / 100, 50), 10);
85
86 // Is there an initial delay?
87 if (delay > 0) {
88 delay(delay);
89 }
90
91 // Keep going until the assertions succeed or until time runs-out.
92 while (true) {
93 try {
94 assertions.run();
95 break;
96 } catch (AssertionError e) {
97 // If there was an error and time ran out, re-throw it.
98 if (now() - start > duration) {
99 throw e;
100 }
101 }
102 delay(step);
103 }
104 }
105
106 /**
107 * Runs the specified runnable until it completes successfully or until the
108 * specified time expires. If the latter occurs, the first encountered
109 * assertion on the last attempt will be re-thrown. Errors other than
110 * assertion errors will be propagated immediately.
111 * <p>
112 * Assertions attempts will not be closer than 10 millis apart and no
113 * further than 50 millis.
114 * </p>
115 *
116 * @param duration number of milliseconds beyond the current time
117 * @param assertions test assertions runnable
118 */
119 public static void assertAfter(int duration, Runnable assertions) {
120 assertAfter(0, duration, assertions);
121 }
122
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800123
124 /**
125 * Creates a directory tree of test files. To signify creating a directory
126 * file path should end with '/'.
127 *
128 * @param paths list of file paths
129 * @return list of created files
130 * @throws java.io.IOException if there is an issue
131 */
132 public static List<File> createTestFiles(List<String> paths) throws IOException {
133 return createTestFiles(paths, 32, 1024);
134 }
135
136 /**
137 * Creates a directory tree of test files. To signify creating a directory
138 * file path should end with '/'.
139 *
140 * @param paths list of file paths
141 * @param minSize minimum file size in bytes
142 * @param maxSize maximum file size in bytes
143 * @return list of created files
144 * @throws java.io.IOException if there is an issue
145 */
146 public static List<File> createTestFiles(List<String> paths,
147 int minSize, int maxSize) throws IOException {
148 ImmutableList.Builder<File> files = ImmutableList.builder();
149 for (String p : paths) {
150 File f = new File(p);
151 if (p.endsWith("/")) {
152 if (f.mkdirs()) {
153 files.add(f);
154 }
155 } else {
156 Files.createParentDirs(f);
157 if (f.createNewFile()) {
158 writeRandomFile(f, minSize, maxSize);
159 files.add(f);
160 }
161 }
162 }
163 return files.build();
164 }
165
166 /**
167 * Writes random binary content into the specified file. The number of
168 * bytes will be random between the given minimum and maximum.
169 *
170 * @param file file to write data to
171 * @param minSize minimum number of bytes to write
172 * @param maxSize maximum number of bytes to write
173 * @throws IOException if there is an issue
174 */
175 public static void writeRandomFile(File file, int minSize, int maxSize) throws IOException {
176 int size = minSize + (minSize == maxSize ? 0 : RANDOM.nextInt(maxSize - minSize));
177 byte[] data = new byte[size];
178 tweakBytes(RANDOM, data, size / 4);
179 Files.write(data, file);
180 }
181
182
183 /**
184 * Tweaks the given number of bytes in a byte array.
185 *
186 * @param random random number generator
187 * @param data byte array to be tweaked
188 * @param count number of bytes to tweak
189 */
190 public static void tweakBytes(Random random, byte[] data, int count) {
191 tweakBytes(random, data, count, 0, data.length);
192 }
193
194 /**
195 * Tweaks the given number of bytes in the specified range of a byte array.
196 *
197 * @param random random number generator
198 * @param data byte array to be tweaked
199 * @param count number of bytes to tweak
200 * @param start index at beginning of range (inclusive)
201 * @param end index at end of range (exclusive)
202 */
203 public static void tweakBytes(Random random, byte[] data, int count,
204 int start, int end) {
205 int len = end - start;
206 for (int i = 0; i < count; i++) {
207 data[start + random.nextInt(len)] = (byte) random.nextInt();
208 }
209 }
210
Ray Milkey7f9e0202015-11-04 17:14:09 -0800211 /*
212 * Finds an available port that a test can bind to.
213 */
214 public static int findAvailablePort(int defaultPort) {
215 try {
216 ServerSocket socket = new ServerSocket(0);
217 socket.setReuseAddress(true);
218 int port = socket.getLocalPort();
219 socket.close();
220 return port;
221 } catch (IOException ex) {
222 return defaultPort;
223 }
224 }
225
226
tom931af4e2014-09-13 12:00:57 -0700227}