source: josm/trunk/test/unit/org/openstreetmap/josm/TestUtils.java@ 14138

Last change on this file since 14138 was 14100, checked in by Don-vip, 6 years ago

increase test coverage

  • Property svn:eol-style set to native
File size: 18.9 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm;
3
4import static org.junit.Assert.assertArrayEquals;
5import static org.junit.Assert.assertEquals;
6import static org.junit.Assert.assertTrue;
7import static org.junit.Assert.fail;
8
9import java.awt.Component;
10import java.awt.Container;
11import java.awt.Graphics2D;
12import java.io.File;
13import java.io.FileInputStream;
14import java.io.IOException;
15import java.io.InputStream;
16import java.lang.reflect.Field;
17import java.lang.reflect.Method;
18import java.security.AccessController;
19import java.security.PrivilegedAction;
20import java.time.Instant;
21import java.time.ZoneOffset;
22import java.time.format.DateTimeFormatter;
23import java.time.temporal.Temporal;
24import java.util.Arrays;
25import java.util.Collection;
26import java.util.Comparator;
27import java.util.Objects;
28import java.util.Set;
29import java.util.concurrent.ExecutionException;
30import java.util.concurrent.ThreadPoolExecutor;
31import java.util.stream.Stream;
32
33import org.junit.Assume;
34import org.openstreetmap.josm.command.Command;
35import org.openstreetmap.josm.data.osm.DataSet;
36import org.openstreetmap.josm.data.osm.Node;
37import org.openstreetmap.josm.data.osm.OsmPrimitive;
38import org.openstreetmap.josm.data.osm.OsmUtils;
39import org.openstreetmap.josm.data.osm.Relation;
40import org.openstreetmap.josm.data.osm.RelationMember;
41import org.openstreetmap.josm.data.osm.Way;
42import org.openstreetmap.josm.gui.MainApplication;
43import org.openstreetmap.josm.gui.progress.AbstractProgressMonitor;
44import org.openstreetmap.josm.gui.progress.CancelHandler;
45import org.openstreetmap.josm.gui.progress.ProgressMonitor;
46import org.openstreetmap.josm.gui.progress.ProgressTaskId;
47import org.openstreetmap.josm.gui.util.GuiHelper;
48import org.openstreetmap.josm.io.Compression;
49import org.openstreetmap.josm.testutils.FakeGraphics;
50import org.openstreetmap.josm.testutils.mockers.WindowMocker;
51import org.openstreetmap.josm.tools.JosmRuntimeException;
52import org.openstreetmap.josm.tools.Utils;
53import org.reflections.Reflections;
54
55import com.github.tomakehurst.wiremock.WireMockServer;
56import com.github.tomakehurst.wiremock.core.WireMockConfiguration;
57import com.google.common.io.ByteStreams;
58
59import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
60
61/**
62 * Various utils, useful for unit tests.
63 */
64public final class TestUtils {
65
66 private TestUtils() {
67 // Hide constructor for utility classes
68 }
69
70 /**
71 * Returns the path to test data root directory.
72 * @return path to test data root directory
73 */
74 public static String getTestDataRoot() {
75 String testDataRoot = System.getProperty("josm.test.data");
76 if (testDataRoot == null || testDataRoot.isEmpty()) {
77 testDataRoot = "test/data";
78 System.out.println("System property josm.test.data is not set, using '" + testDataRoot + "'");
79 }
80 return testDataRoot.endsWith("/") ? testDataRoot : testDataRoot + "/";
81 }
82
83 /**
84 * Gets path to test data directory for given ticket id.
85 * @param ticketid Ticket numeric identifier
86 * @return path to test data directory for given ticket id
87 */
88 public static String getRegressionDataDir(int ticketid) {
89 return TestUtils.getTestDataRoot() + "/regress/" + ticketid;
90 }
91
92 /**
93 * Gets path to given file in test data directory for given ticket id.
94 * @param ticketid Ticket numeric identifier
95 * @param filename File name
96 * @return path to given file in test data directory for given ticket id
97 */
98 public static String getRegressionDataFile(int ticketid, String filename) {
99 return getRegressionDataDir(ticketid) + '/' + filename;
100 }
101
102 /**
103 * Gets input stream to given file in test data directory for given ticket id.
104 * @param ticketid Ticket numeric identifier
105 * @param filename File name
106 * @return path to given file in test data directory for given ticket id
107 * @throws IOException if any I/O error occurs
108 */
109 public static InputStream getRegressionDataStream(int ticketid, String filename) throws IOException {
110 return Compression.getUncompressedFileInputStream(new File(getRegressionDataDir(ticketid), filename));
111 }
112
113 /**
114 * Checks that the given Comparator respects its contract on the given table.
115 * @param <T> type of elements
116 * @param comparator The comparator to test
117 * @param array The array sorted for test purpose
118 */
119 @SuppressFBWarnings(value = "RV_NEGATING_RESULT_OF_COMPARETO")
120 public static <T> void checkComparableContract(Comparator<T> comparator, T[] array) {
121 System.out.println("Validating Comparable contract on array of "+array.length+" elements");
122 // Check each compare possibility
123 for (int i = 0; i < array.length; i++) {
124 T r1 = array[i];
125 for (int j = i; j < array.length; j++) {
126 T r2 = array[j];
127 int a = comparator.compare(r1, r2);
128 int b = comparator.compare(r2, r1);
129 if (i == j || a == b) {
130 if (a != 0 || b != 0) {
131 fail(getFailMessage(r1, r2, a, b));
132 }
133 } else {
134 if (a != -b) {
135 fail(getFailMessage(r1, r2, a, b));
136 }
137 }
138 for (int k = j; k < array.length; k++) {
139 T r3 = array[k];
140 int c = comparator.compare(r1, r3);
141 int d = comparator.compare(r2, r3);
142 if (a > 0 && d > 0) {
143 if (c <= 0) {
144 fail(getFailMessage(r1, r2, r3, a, b, c, d));
145 }
146 } else if (a == 0 && d == 0) {
147 if (c != 0) {
148 fail(getFailMessage(r1, r2, r3, a, b, c, d));
149 }
150 } else if (a < 0 && d < 0) {
151 if (c >= 0) {
152 fail(getFailMessage(r1, r2, r3, a, b, c, d));
153 }
154 }
155 }
156 }
157 }
158 // Sort relation array
159 Arrays.sort(array, comparator);
160 }
161
162 private static <T> String getFailMessage(T o1, T o2, int a, int b) {
163 return new StringBuilder("Compared\no1: ").append(o1).append("\no2: ")
164 .append(o2).append("\ngave: ").append(a).append("/").append(b)
165 .toString();
166 }
167
168 private static <T> String getFailMessage(T o1, T o2, T o3, int a, int b, int c, int d) {
169 return new StringBuilder(getFailMessage(o1, o2, a, b))
170 .append("\nCompared\no1: ").append(o1).append("\no3: ").append(o3).append("\ngave: ").append(c)
171 .append("\nCompared\no2: ").append(o2).append("\no3: ").append(o3).append("\ngave: ").append(d)
172 .toString();
173 }
174
175 /**
176 * Returns a private field value.
177 * @param obj object
178 * @param fieldName private field name
179 * @return private field value
180 * @throws ReflectiveOperationException if a reflection operation error occurs
181 */
182 public static Object getPrivateField(Object obj, String fieldName) throws ReflectiveOperationException {
183 return getPrivateField(obj.getClass(), obj, fieldName);
184 }
185
186 /**
187 * Returns a private field value.
188 * @param cls object class
189 * @param obj object
190 * @param fieldName private field name
191 * @return private field value
192 * @throws ReflectiveOperationException if a reflection operation error occurs
193 */
194 public static Object getPrivateField(Class<?> cls, Object obj, String fieldName) throws ReflectiveOperationException {
195 Field f = cls.getDeclaredField(fieldName);
196 AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
197 f.setAccessible(true);
198 return null;
199 });
200 return f.get(obj);
201 }
202
203 /**
204 * Returns a private static field value.
205 * @param cls object class
206 * @param fieldName private field name
207 * @return private field value
208 * @throws ReflectiveOperationException if a reflection operation error occurs
209 */
210 public static Object getPrivateStaticField(Class<?> cls, String fieldName) throws ReflectiveOperationException {
211 Field f = cls.getDeclaredField(fieldName);
212 AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
213 f.setAccessible(true);
214 return null;
215 });
216 return f.get(null);
217 }
218
219 /**
220 * Sets a private static field value.
221 * @param cls object class
222 * @param fieldName private field name
223 * @param value replacement value
224 * @throws ReflectiveOperationException if a reflection operation error occurs
225 */
226 public static void setPrivateStaticField(Class<?> cls, String fieldName, final Object value) throws ReflectiveOperationException {
227 Field f = cls.getDeclaredField(fieldName);
228 AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
229 f.setAccessible(true);
230 return null;
231 });
232 f.set(null, value);
233 }
234
235 /**
236 * Returns an instance of {@link AbstractProgressMonitor} which keeps track of the monitor state,
237 * but does not show the progress.
238 * @return a progress monitor
239 */
240 public static ProgressMonitor newTestProgressMonitor() {
241 return new AbstractProgressMonitor(new CancelHandler()) {
242
243 @Override
244 protected void doBeginTask() {
245 }
246
247 @Override
248 protected void doFinishTask() {
249 }
250
251 @Override
252 protected void doSetIntermediate(boolean value) {
253 }
254
255 @Override
256 protected void doSetTitle(String title) {
257 }
258
259 @Override
260 protected void doSetCustomText(String title) {
261 }
262
263 @Override
264 protected void updateProgress(double value) {
265 }
266
267 @Override
268 public void setProgressTaskId(ProgressTaskId taskId) {
269 }
270
271 @Override
272 public ProgressTaskId getProgressTaskId() {
273 return null;
274 }
275
276 @Override
277 public Component getWindowParent() {
278 return null;
279 }
280 };
281 }
282
283 /**
284 * Returns an instance of {@link Graphics2D}.
285 * @return a mockup graphics instance
286 */
287 public static Graphics2D newGraphics() {
288 return new FakeGraphics();
289 }
290
291 /**
292 * Makes sure the given primitive belongs to a data set.
293 * @param <T> OSM primitive type
294 * @param osm OSM primitive
295 * @return OSM primitive, attached to a new {@code DataSet}
296 */
297 public static <T extends OsmPrimitive> T addFakeDataSet(T osm) {
298 new DataSet(osm);
299 return osm;
300 }
301
302 /**
303 * Creates a new node with the given tags (see {@link OsmUtils#createPrimitive(java.lang.String)})
304 *
305 * @param tags the tags to set
306 * @return a new node
307 */
308 public static Node newNode(String tags) {
309 return (Node) OsmUtils.createPrimitive("node " + tags);
310 }
311
312 /**
313 * Creates a new way with the given tags (see {@link OsmUtils#createPrimitive(java.lang.String)}) and the nodes added
314 *
315 * @param tags the tags to set
316 * @param nodes the nodes to add
317 * @return a new way
318 */
319 public static Way newWay(String tags, Node... nodes) {
320 final Way way = (Way) OsmUtils.createPrimitive("way " + tags);
321 for (Node node : nodes) {
322 way.addNode(node);
323 }
324 return way;
325 }
326
327 /**
328 * Creates a new relation with the given tags (see {@link OsmUtils#createPrimitive(java.lang.String)}) and the members added
329 *
330 * @param tags the tags to set
331 * @param members the members to add
332 * @return a new relation
333 */
334 public static Relation newRelation(String tags, RelationMember... members) {
335 final Relation relation = (Relation) OsmUtils.createPrimitive("relation " + tags);
336 for (RelationMember member : members) {
337 relation.addMember(member);
338 }
339 return relation;
340 }
341
342 /**
343 * Creates a new empty command.
344 * @param ds data set
345 * @return a new empty command
346 */
347 public static Command newCommand(DataSet ds) {
348 return new Command(ds) {
349 @Override
350 public String getDescriptionText() {
351 return "";
352 }
353
354 @Override
355 public void fillModifiedData(Collection<OsmPrimitive> modified, Collection<OsmPrimitive> deleted,
356 Collection<OsmPrimitive> added) {
357 // Do nothing
358 }
359 };
360 }
361
362 /**
363 * Ensures 100% code coverage for enums.
364 * @param enumClass enum class to cover
365 */
366 public static void superficialEnumCodeCoverage(Class<? extends Enum<?>> enumClass) {
367 try {
368 Method values = enumClass.getMethod("values");
369 Method valueOf = enumClass.getMethod("valueOf", String.class);
370 Utils.setObjectsAccessible(values, valueOf);
371 for (Object o : (Object[]) values.invoke(null)) {
372 assertEquals(o, valueOf.invoke(null, ((Enum<?>) o).name()));
373 }
374 } catch (IllegalArgumentException | ReflectiveOperationException | SecurityException e) {
375 throw new JosmRuntimeException(e);
376 }
377 }
378
379 /**
380 * Get a descendant component by name.
381 * @param root The root component to start searching from.
382 * @param name The component name
383 * @return The component with that name or null if it does not exist.
384 * @since 12045
385 */
386 public static Component getComponentByName(Component root, String name) {
387 if (name.equals(root.getName())) {
388 return root;
389 } else if (root instanceof Container) {
390 Container container = (Container) root;
391 return Stream.of(container.getComponents())
392 .map(child -> getComponentByName(child, name))
393 .filter(Objects::nonNull)
394 .findFirst().orElse(null);
395 } else {
396 return null;
397 }
398 }
399
400 /**
401 * Use to assume that EqualsVerifier is working with the current JVM.
402 */
403 public static void assumeWorkingEqualsVerifier() {
404 try {
405 // Workaround to https://github.com/jqno/equalsverifier/issues/177
406 // Inspired by https://issues.apache.org/jira/browse/SOLR-11606
407 nl.jqno.equalsverifier.internal.lib.bytebuddy.ClassFileVersion.ofThisVm();
408 } catch (IllegalArgumentException e) {
409 Assume.assumeNoException(e);
410 }
411 }
412
413 /**
414 * Use to assume that JMockit is working with the current JVM.
415 */
416 public static void assumeWorkingJMockit() {
417 try {
418 // Workaround to https://github.com/jmockit/jmockit1/issues/534
419 // Inspired by https://issues.apache.org/jira/browse/SOLR-11606
420 new WindowMocker();
421 } catch (UnsupportedOperationException e) {
422 Assume.assumeNoException(e);
423 }
424 }
425
426 /**
427 * Return WireMock server serving files under ticker directory
428 * @param ticketId Ticket numeric identifier
429 * @return WireMock HTTP server on dynamic port
430 */
431 public static WireMockServer getWireMockServer(int ticketId) {
432 return new WireMockServer(
433 WireMockConfiguration.options()
434 .dynamicPort()
435 .usingFilesUnderDirectory(getRegressionDataDir(ticketId))
436 );
437 }
438
439 /**
440 * Return WireMock server serving files under ticker directory
441 * @return WireMock HTTP server on dynamic port
442 */
443 public static WireMockServer getWireMockServer() {
444 return new WireMockServer(
445 WireMockConfiguration.options()
446 .dynamicPort()
447 );
448 }
449
450 /**
451 * Renders Temporal to RFC 1123 Date Time
452 * @param time to convert
453 * @return string representation according to RFC1123 of time
454 */
455 public static String getHTTPDate(Temporal time) {
456 return DateTimeFormatter.RFC_1123_DATE_TIME.withZone(ZoneOffset.UTC).format(time);
457 }
458
459 /**
460 * Renders java time stamp to RFC 1123 Date Time
461 * @param time java timestamp (milliseconds from Epoch)
462 * @return string representation according to RFC1123 of time
463 */
464 public static String getHTTPDate(long time) {
465 return getHTTPDate(Instant.ofEpochMilli(time));
466 }
467
468 /**
469 * Throws AssertionError if contents of both files are not equal
470 * @param fileA File A
471 * @param fileB File B
472 */
473 public static void assertFileContentsEqual(final File fileA, final File fileB) {
474 assertTrue(fileA.exists());
475 assertTrue(fileA.canRead());
476 assertTrue(fileB.exists());
477 assertTrue(fileB.canRead());
478 try {
479 try (
480 FileInputStream streamA = new FileInputStream(fileA);
481 FileInputStream streamB = new FileInputStream(fileB);
482 ) {
483 assertArrayEquals(
484 ByteStreams.toByteArray(streamA),
485 ByteStreams.toByteArray(streamB)
486 );
487 }
488 } catch (IOException e) {
489 throw new RuntimeException(e);
490 }
491 }
492
493 /**
494 * Waits until any asynchronous operations launched by the test on the EDT or worker threads have
495 * (almost certainly) completed.
496 */
497 public static void syncEDTAndWorkerThreads() {
498 boolean workerQueueEmpty = false;
499 while (!workerQueueEmpty) {
500 try {
501 // once our own task(s) have made it to the front of their respective queue(s),
502 // they're both executing at the same time and we know there aren't any outstanding
503 // worker tasks, then presumably the only way there could be incomplete operations
504 // is if the EDT had launched a deferred task to run on itself or perhaps set up a
505 // swing timer - neither are particularly common patterns in JOSM (?)
506 //
507 // there shouldn't be a risk of creating a deadlock in doing this as there shouldn't
508 // (...couldn't?) be EDT operations waiting on the results of a worker task.
509 workerQueueEmpty = MainApplication.worker.submit(
510 () -> GuiHelper.runInEDTAndWaitAndReturn(
511 () -> ((ThreadPoolExecutor) MainApplication.worker).getQueue().isEmpty()
512 )
513 ).get();
514 } catch (InterruptedException | ExecutionException e) {
515 // inconclusive - retry...
516 workerQueueEmpty = false;
517 }
518 }
519 }
520
521 /**
522 * Returns all JOSM subtypes of the given class.
523 * @param <T> class
524 * @param superClass class
525 * @return all JOSM subtypes of the given class
526 */
527 public static <T> Set<Class<? extends T>> getJosmSubtypes(Class<T> superClass) {
528 return new Reflections("org.openstreetmap.josm").getSubTypesOf(superClass);
529 }
530}
Note: See TracBrowser for help on using the repository browser.