forked from nus-cs2103-AY1617S1/addressbook-level4
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TestUtil.java
354 lines (308 loc) · 12.8 KB
/
TestUtil.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
package seedu.address.testutil;
import com.google.common.io.Files;
import guitests.guihandles.PersonCardHandle;
import javafx.geometry.Bounds;
import javafx.geometry.Point2D;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyCodeCombination;
import javafx.scene.input.KeyCombination;
import junit.framework.AssertionFailedError;
import org.loadui.testfx.GuiTest;
import org.testfx.api.FxToolkit;
import seedu.address.TestApp;
import seedu.address.commons.exceptions.IllegalValueException;
import seedu.address.commons.util.FileUtil;
import seedu.address.commons.util.XmlUtil;
import seedu.address.model.AddressBook;
import seedu.address.model.person.*;
import seedu.address.model.tag.Tag;
import seedu.address.model.tag.UniqueTagList;
import seedu.address.storage.XmlSerializableAddressBook;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeoutException;
import java.util.stream.Collectors;
/**
* A utility class for test cases.
*/
public class TestUtil {
public static String LS = System.lineSeparator();
public static void assertThrows(Class<? extends Throwable> expected, Runnable executable) {
try {
executable.run();
}
catch (Throwable actualException) {
if (!actualException.getClass().isAssignableFrom(expected)) {
String message = String.format("Expected thrown: %s, actual: %s", expected.getName(),
actualException.getClass().getName());
throw new AssertionFailedError(message);
} else return;
}
throw new AssertionFailedError(
String.format("Expected %s to be thrown, but nothing was thrown.", expected.getName()));
}
/**
* Folder used for temp files created during testing. Ignored by Git.
*/
public static String SANDBOX_FOLDER = FileUtil.getPath("./src/test/data/sandbox/");
public static final Task[] samplePersonData = getSamplePersonData();
private static Task[] getSamplePersonData() {
try {
return new Task[]{
new Task(new Name("Ali Muster"), new Description("Meet for dinner"), new Date(""), new Time(""), new UniqueTagList()),
new Task(new Name("Boris Mueller"), new Description("Meet for lunch"), new Date(""), new Time(""), new UniqueTagList()),
new Task(new Name("Carl Kurz"), new Description("Meet for breakfast"), new Date("11.11.2017"), new Time("2234"), new UniqueTagList()),
new Task(new Name("Daniel Meier"), new Description("Meet for lunch"), new Date("09.09.2017"), new Time("2200"), new UniqueTagList()),
new Task(new Name("Elle Meyer"), new Description("Meet for lunch"), new Date("10.10.2017"), new Time("2300"), new UniqueTagList()),
new Task(new Name("Fiona Kunz"), new Description("Meet for dinner"), new Date("10.10.2017"), new Time("2254"), new UniqueTagList()),
new Task(new Name("George Best"), new Description("Meet for breakfast"), new Date(""), new Time(""), new UniqueTagList()),
new Task(new Name("Hoon Meier"), new Description("Meet for dinner"), new Date("01.01.2017"), new Time("2101"), new UniqueTagList()),
new Task(new Name("Ida Mueller"), new Description("Meet for breakfast"), new Date("09.05.2017"), new Time("2130"), new UniqueTagList())
};
} catch (IllegalValueException e) {
assert false;
//not possible
return null;
}
}
public static final Tag[] sampleTagData = getSampleTagData();
private static Tag[] getSampleTagData() {
try {
return new Tag[]{
new Tag("relatives"),
new Tag("friends")
};
} catch (IllegalValueException e) {
assert false;
return null;
//not possible
}
}
public static List<Task> generateSamplePersonData() {
return Arrays.asList(samplePersonData);
}
/**
* Appends the file name to the sandbox folder path.
* Creates the sandbox folder if it doesn't exist.
* @param fileName
* @return
*/
public static String getFilePathInSandboxFolder(String fileName) {
try {
FileUtil.createDirs(new File(SANDBOX_FOLDER));
} catch (IOException e) {
throw new RuntimeException(e);
}
return SANDBOX_FOLDER + fileName;
}
public static void createDataFileWithSampleData(String filePath) {
createDataFileWithData(generateSampleStorageAddressBook(), filePath);
}
public static <T> void createDataFileWithData(T data, String filePath) {
try {
File saveFileForTesting = new File(filePath);
FileUtil.createIfMissing(saveFileForTesting);
XmlUtil.saveDataToFile(saveFileForTesting, data);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static void main(String... s) {
createDataFileWithSampleData(TestApp.SAVE_LOCATION_FOR_TESTING);
}
public static AddressBook generateEmptyAddressBook() {
return new AddressBook(new UniquePersonList(), new UniquePersonList(), new UniqueTagList());
}
public static XmlSerializableAddressBook generateSampleStorageAddressBook() {
return new XmlSerializableAddressBook(generateEmptyAddressBook());
}
/**
* Tweaks the {@code keyCodeCombination} to resolve the {@code KeyCode.SHORTCUT} to their
* respective platform-specific keycodes
*/
public static KeyCode[] scrub(KeyCodeCombination keyCodeCombination) {
List<KeyCode> keys = new ArrayList<>();
if (keyCodeCombination.getAlt() == KeyCombination.ModifierValue.DOWN) {
keys.add(KeyCode.ALT);
}
if (keyCodeCombination.getShift() == KeyCombination.ModifierValue.DOWN) {
keys.add(KeyCode.SHIFT);
}
if (keyCodeCombination.getMeta() == KeyCombination.ModifierValue.DOWN) {
keys.add(KeyCode.META);
}
if (keyCodeCombination.getControl() == KeyCombination.ModifierValue.DOWN) {
keys.add(KeyCode.CONTROL);
}
keys.add(keyCodeCombination.getCode());
return keys.toArray(new KeyCode[]{});
}
public static boolean isHeadlessEnvironment() {
String headlessProperty = System.getProperty("testfx.headless");
return headlessProperty != null && headlessProperty.equals("true");
}
public static void captureScreenShot(String fileName) {
File file = GuiTest.captureScreenshot();
try {
Files.copy(file, new File(fileName + ".png"));
} catch (IOException e) {
e.printStackTrace();
}
}
public static String descOnFail(Object... comparedObjects) {
return "Comparison failed \n"
+ Arrays.asList(comparedObjects).stream()
.map(Object::toString)
.collect(Collectors.joining("\n"));
}
public static void setFinalStatic(Field field, Object newValue) throws NoSuchFieldException, IllegalAccessException{
field.setAccessible(true);
// remove final modifier from field
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
// ~Modifier.FINAL is used to remove the final modifier from field so that its value is no longer
// final and can be changed
modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(null, newValue);
}
public static void initRuntime() throws TimeoutException {
FxToolkit.registerPrimaryStage();
FxToolkit.hideStage();
}
public static void tearDownRuntime() throws Exception {
FxToolkit.cleanupStages();
}
/**
* Gets private method of a class
* Invoke the method using method.invoke(objectInstance, params...)
*
* Caveat: only find method declared in the current Class, not inherited from supertypes
*/
public static Method getPrivateMethod(Class objectClass, String methodName) throws NoSuchMethodException {
Method method = objectClass.getDeclaredMethod(methodName);
method.setAccessible(true);
return method;
}
public static void renameFile(File file, String newFileName) {
try {
Files.copy(file, new File(newFileName));
} catch (IOException e1) {
e1.printStackTrace();
}
}
/**
* Gets mid point of a node relative to the screen.
* @param node
* @return
*/
public static Point2D getScreenMidPoint(Node node) {
double x = getScreenPos(node).getMinX() + node.getLayoutBounds().getWidth() / 2;
double y = getScreenPos(node).getMinY() + node.getLayoutBounds().getHeight() / 2;
return new Point2D(x,y);
}
/**
* Gets mid point of a node relative to its scene.
* @param node
* @return
*/
public static Point2D getSceneMidPoint(Node node) {
double x = getScenePos(node).getMinX() + node.getLayoutBounds().getWidth() / 2;
double y = getScenePos(node).getMinY() + node.getLayoutBounds().getHeight() / 2;
return new Point2D(x,y);
}
/**
* Gets the bound of the node relative to the parent scene.
* @param node
* @return
*/
public static Bounds getScenePos(Node node) {
return node.localToScene(node.getBoundsInLocal());
}
public static Bounds getScreenPos(Node node) {
return node.localToScreen(node.getBoundsInLocal());
}
public static double getSceneMaxX(Scene scene) {
return scene.getX() + scene.getWidth();
}
public static double getSceneMaxY(Scene scene) {
return scene.getX() + scene.getHeight();
}
public static Object getLastElement(List<?> list) {
return list.get(list.size() - 1);
}
/**
* Removes a subset from the list of persons.
* @param persons The list of persons
* @param personsToRemove The subset of persons.
* @return The modified persons after removal of the subset from persons.
*/
public static TestTask[] removePersonsFromList(final TestTask[] persons, TestTask... personsToRemove) {
List<TestTask> listOfPersons = asList(persons);
listOfPersons.removeAll(asList(personsToRemove));
return listOfPersons.toArray(new TestTask[listOfPersons.size()]);
}
/**
* Returns a copy of the list with the person at specified index removed.
* @param list original list to copy from
* @param targetIndexInOneIndexedFormat e.g. if the first element to be removed, 1 should be given as index.
*/
public static TestTask[] removePersonFromList(final TestTask[] list, int targetIndexInOneIndexedFormat) {
return removePersonsFromList(list, list[targetIndexInOneIndexedFormat-1]);
}
/**
* Replaces persons[i] with a person.
* @param persons The array of persons.
* @param person The replacement person
* @param index The index of the person to be replaced.
* @return
*/
public static TestTask[] replacePersonFromList(TestTask[] persons, TestTask person, int index) {
persons[index] = person;
return persons;
}
/**
* Appends persons to the array of persons.
* @param persons A array of persons.
* @param personsToAdd The persons that are to be appended behind the original array.
* @return The modified array of persons.
*/
public static TestTask[] addPersonsToList(final TestTask[] persons, TestTask... personsToAdd) {
List<TestTask> listOfPersons = asList(persons);
listOfPersons.addAll(asList(personsToAdd));
return listOfPersons.toArray(new TestTask[listOfPersons.size()]);
}
private static <T> List<T> asList(T[] objs) {
List<T> list = new ArrayList<>();
for(T obj : objs) {
list.add(obj);
}
return list;
}
public static boolean compareCardAndPerson(PersonCardHandle card, ReadOnlyTask person) {
return card.isSamePerson(person);
}
public static Tag[] getTagList(String tags) {
if (tags.equals("")) {
return new Tag[]{};
}
final String[] split = tags.split(", ");
final List<Tag> collect = Arrays.asList(split).stream().map(e -> {
try {
return new Tag(e.replaceFirst("Tag: ", ""));
} catch (IllegalValueException e1) {
//not possible
assert false;
return null;
}
}).collect(Collectors.toList());
return collect.toArray(new Tag[split.length]);
}
}