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

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

Update TestUtils.assumeWorkingJMockit - two tests are not skipped with current implementation

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