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

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

drop FEST library. This project seems to have vanished years ago, and we don't use it a lot

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