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

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

see #15560 - EqualsVerifier does not work with newer Java versions -> disable tests automatically in this case
Workaround to https://github.com/jqno/equalsverifier/issues/177 / https://github.com/raphw/byte-buddy/issues/370
Inspired by https://issues.apache.org/jira/browse/SOLR-11606

  • Property svn:eol-style set to native
File size: 12.1 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm;
3
4import static org.junit.Assert.assertEquals;
5import static org.junit.Assert.fail;
6
7import java.awt.Component;
8import java.awt.Container;
9import java.awt.Graphics2D;
10import java.io.File;
11import java.io.IOException;
12import java.io.InputStream;
13import java.lang.reflect.Field;
14import java.lang.reflect.Method;
15import java.security.AccessController;
16import java.security.PrivilegedAction;
17import java.util.Arrays;
18import java.util.Collection;
19import java.util.Comparator;
20import java.util.Objects;
21import java.util.stream.Stream;
22
23import org.junit.Assume;
24import org.openstreetmap.josm.command.Command;
25import org.openstreetmap.josm.data.osm.DataSet;
26import org.openstreetmap.josm.data.osm.Node;
27import org.openstreetmap.josm.data.osm.OsmPrimitive;
28import org.openstreetmap.josm.data.osm.OsmUtils;
29import org.openstreetmap.josm.data.osm.Relation;
30import org.openstreetmap.josm.data.osm.RelationMember;
31import org.openstreetmap.josm.data.osm.Way;
32import org.openstreetmap.josm.gui.progress.AbstractProgressMonitor;
33import org.openstreetmap.josm.gui.progress.CancelHandler;
34import org.openstreetmap.josm.gui.progress.ProgressMonitor;
35import org.openstreetmap.josm.gui.progress.ProgressTaskId;
36import org.openstreetmap.josm.io.Compression;
37import org.openstreetmap.josm.testutils.FakeGraphics;
38import org.openstreetmap.josm.tools.JosmRuntimeException;
39import org.openstreetmap.josm.tools.Utils;
40
41import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
42
43/**
44 * Various utils, useful for unit tests.
45 */
46public final class TestUtils {
47
48 private TestUtils() {
49 // Hide constructor for utility classes
50 }
51
52 /**
53 * Returns the path to test data root directory.
54 * @return path to test data root directory
55 */
56 public static String getTestDataRoot() {
57 String testDataRoot = System.getProperty("josm.test.data");
58 if (testDataRoot == null || testDataRoot.isEmpty()) {
59 testDataRoot = "test/data";
60 System.out.println("System property josm.test.data is not set, using '" + testDataRoot + "'");
61 }
62 return testDataRoot.endsWith("/") ? testDataRoot : testDataRoot + "/";
63 }
64
65 /**
66 * Gets path to test data directory for given ticket id.
67 * @param ticketid Ticket numeric identifier
68 * @return path to test data directory for given ticket id
69 */
70 public static String getRegressionDataDir(int ticketid) {
71 return TestUtils.getTestDataRoot() + "/regress/" + ticketid;
72 }
73
74 /**
75 * Gets path to given file in test data directory for given ticket id.
76 * @param ticketid Ticket numeric identifier
77 * @param filename File name
78 * @return path to given file in test data directory for given ticket id
79 */
80 public static String getRegressionDataFile(int ticketid, String filename) {
81 return getRegressionDataDir(ticketid) + '/' + filename;
82 }
83
84 /**
85 * Gets input stream to given file in test data directory for given ticket id.
86 * @param ticketid Ticket numeric identifier
87 * @param filename File name
88 * @return path to given file in test data directory for given ticket id
89 * @throws IOException if any I/O error occurs
90 */
91 public static InputStream getRegressionDataStream(int ticketid, String filename) throws IOException {
92 return Compression.getUncompressedFileInputStream(new File(getRegressionDataDir(ticketid), filename));
93 }
94
95 /**
96 * Checks that the given Comparator respects its contract on the given table.
97 * @param <T> type of elements
98 * @param comparator The comparator to test
99 * @param array The array sorted for test purpose
100 */
101 @SuppressFBWarnings(value = "RV_NEGATING_RESULT_OF_COMPARETO")
102 public static <T> void checkComparableContract(Comparator<T> comparator, T[] array) {
103 System.out.println("Validating Comparable contract on array of "+array.length+" elements");
104 // Check each compare possibility
105 for (int i = 0; i < array.length; i++) {
106 T r1 = array[i];
107 for (int j = i; j < array.length; j++) {
108 T r2 = array[j];
109 int a = comparator.compare(r1, r2);
110 int b = comparator.compare(r2, r1);
111 if (i == j || a == b) {
112 if (a != 0 || b != 0) {
113 fail(getFailMessage(r1, r2, a, b));
114 }
115 } else {
116 if (a != -b) {
117 fail(getFailMessage(r1, r2, a, b));
118 }
119 }
120 for (int k = j; k < array.length; k++) {
121 T r3 = array[k];
122 int c = comparator.compare(r1, r3);
123 int d = comparator.compare(r2, r3);
124 if (a > 0 && d > 0) {
125 if (c <= 0) {
126 fail(getFailMessage(r1, r2, r3, a, b, c, d));
127 }
128 } else if (a == 0 && d == 0) {
129 if (c != 0) {
130 fail(getFailMessage(r1, r2, r3, a, b, c, d));
131 }
132 } else if (a < 0 && d < 0) {
133 if (c >= 0) {
134 fail(getFailMessage(r1, r2, r3, a, b, c, d));
135 }
136 }
137 }
138 }
139 }
140 // Sort relation array
141 Arrays.sort(array, comparator);
142 }
143
144 private static <T> String getFailMessage(T o1, T o2, int a, int b) {
145 return new StringBuilder("Compared\no1: ").append(o1).append("\no2: ")
146 .append(o2).append("\ngave: ").append(a).append("/").append(b)
147 .toString();
148 }
149
150 private static <T> String getFailMessage(T o1, T o2, T o3, int a, int b, int c, int d) {
151 return new StringBuilder(getFailMessage(o1, o2, a, b))
152 .append("\nCompared\no1: ").append(o1).append("\no3: ").append(o3).append("\ngave: ").append(c)
153 .append("\nCompared\no2: ").append(o2).append("\no3: ").append(o3).append("\ngave: ").append(d)
154 .toString();
155 }
156
157 /**
158 * Returns a private field value.
159 * @param obj object
160 * @param fieldName private field name
161 * @return private field value
162 * @throws ReflectiveOperationException if a reflection operation error occurs
163 */
164 public static Object getPrivateField(Object obj, String fieldName) throws ReflectiveOperationException {
165 Field f = obj.getClass().getDeclaredField(fieldName);
166 AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
167 f.setAccessible(true);
168 return null;
169 });
170 return f.get(obj);
171 }
172
173 /**
174 * Returns a private static field value.
175 * @param cls object class
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 getPrivateStaticField(Class<?> cls, String fieldName) throws ReflectiveOperationException {
181 Field f = cls.getDeclaredField(fieldName);
182 AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
183 f.setAccessible(true);
184 return null;
185 });
186 return f.get(null);
187 }
188
189 /**
190 * Returns an instance of {@link AbstractProgressMonitor} which keeps track of the monitor state,
191 * but does not show the progress.
192 * @return a progress monitor
193 */
194 public static ProgressMonitor newTestProgressMonitor() {
195 return new AbstractProgressMonitor(new CancelHandler()) {
196
197 @Override
198 protected void doBeginTask() {
199 }
200
201 @Override
202 protected void doFinishTask() {
203 }
204
205 @Override
206 protected void doSetIntermediate(boolean value) {
207 }
208
209 @Override
210 protected void doSetTitle(String title) {
211 }
212
213 @Override
214 protected void doSetCustomText(String title) {
215 }
216
217 @Override
218 protected void updateProgress(double value) {
219 }
220
221 @Override
222 public void setProgressTaskId(ProgressTaskId taskId) {
223 }
224
225 @Override
226 public ProgressTaskId getProgressTaskId() {
227 return null;
228 }
229
230 @Override
231 public Component getWindowParent() {
232 return null;
233 }
234 };
235 }
236
237 /**
238 * Returns an instance of {@link Graphics2D}.
239 * @return a mockup graphics instance
240 */
241 public static Graphics2D newGraphics() {
242 return new FakeGraphics();
243 }
244
245 /**
246 * Creates a new way with the given tags (see {@link OsmUtils#createPrimitive(java.lang.String)}) and the nodes added
247 *
248 * @param tags the tags to set
249 * @param nodes the nodes to add
250 * @return a new way
251 */
252 public static Way newWay(String tags, Node... nodes) {
253 final Way way = (Way) OsmUtils.createPrimitive("way " + tags);
254 for (Node node : nodes) {
255 way.addNode(node);
256 }
257 return way;
258 }
259
260 /**
261 * Creates a new relation with the given tags (see {@link OsmUtils#createPrimitive(java.lang.String)}) and the members added
262 *
263 * @param tags the tags to set
264 * @param members the members to add
265 * @return a new relation
266 */
267 public static Relation newRelation(String tags, RelationMember... members) {
268 final Relation relation = (Relation) OsmUtils.createPrimitive("relation " + tags);
269 for (RelationMember member : members) {
270 relation.addMember(member);
271 }
272 return relation;
273 }
274
275 /**
276 * Creates a new empty command.
277 * @param ds data set
278 * @return a new empty command
279 */
280 public static Command newCommand(DataSet ds) {
281 return new Command(ds) {
282 @Override
283 public String getDescriptionText() {
284 return "";
285 }
286
287 @Override
288 public void fillModifiedData(Collection<OsmPrimitive> modified, Collection<OsmPrimitive> deleted,
289 Collection<OsmPrimitive> added) {
290 // Do nothing
291 }
292 };
293 }
294
295 /**
296 * Ensures 100% code coverage for enums.
297 * @param enumClass enum class to cover
298 */
299 public static void superficialEnumCodeCoverage(Class<? extends Enum<?>> enumClass) {
300 try {
301 Method values = enumClass.getMethod("values");
302 Method valueOf = enumClass.getMethod("valueOf", String.class);
303 Utils.setObjectsAccessible(values, valueOf);
304 for (Object o : (Object[]) values.invoke(null)) {
305 assertEquals(o, valueOf.invoke(null, ((Enum<?>) o).name()));
306 }
307 } catch (IllegalArgumentException | ReflectiveOperationException | SecurityException e) {
308 throw new JosmRuntimeException(e);
309 }
310 }
311
312 /**
313 * Get a descendant component by name.
314 * @param root The root component to start searching from.
315 * @param name The component name
316 * @return The component with that name or null if it does not exist.
317 * @since 12045
318 */
319 public static Component getComponentByName(Component root, String name) {
320 if (name.equals(root.getName())) {
321 return root;
322 } else if (root instanceof Container) {
323 Container container = (Container) root;
324 return Stream.of(container.getComponents())
325 .map(child -> getComponentByName(child, name))
326 .filter(Objects::nonNull)
327 .findFirst().orElse(null);
328 } else {
329 return null;
330 }
331 }
332
333 /**
334 * Use to assume that EqualsVerifier is working with the current JVM.
335 */
336 public static void assumeWorkingEqualsVerifier() {
337 try {
338 // Workaround to https://github.com/jqno/equalsverifier/issues/177
339 // Inspired by https://issues.apache.org/jira/browse/SOLR-11606
340 nl.jqno.equalsverifier.internal.lib.bytebuddy.ClassFileVersion.ofThisVm();
341 } catch (IllegalArgumentException e) {
342 Assume.assumeNoException(e);
343 }
344 }
345}
Note: See TracBrowser for help on using the repository browser.