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

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

see #16073 - handle ignore list

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