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

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

see #16688 - skip some unit tests if preconditions are not met

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