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

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

fix #15742 - check downloaded plugin is valid *before* we delete any existing one (patch by ris)

  • Property svn:eol-style set to native
File size: 12.7 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 * Sets a private static field value.
191 * @param cls object class
192 * @param fieldName private field name
193 * @param value replacement value
194 * @throws ReflectiveOperationException if a reflection operation error occurs
195 */
196 public static void setPrivateStaticField(Class<?> cls, String fieldName, final Object value) throws ReflectiveOperationException {
197 Field f = cls.getDeclaredField(fieldName);
198 AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
199 f.setAccessible(true);
200 return null;
201 });
202 f.set(null, value);
203 }
204
205 /**
206 * Returns an instance of {@link AbstractProgressMonitor} which keeps track of the monitor state,
207 * but does not show the progress.
208 * @return a progress monitor
209 */
210 public static ProgressMonitor newTestProgressMonitor() {
211 return new AbstractProgressMonitor(new CancelHandler()) {
212
213 @Override
214 protected void doBeginTask() {
215 }
216
217 @Override
218 protected void doFinishTask() {
219 }
220
221 @Override
222 protected void doSetIntermediate(boolean value) {
223 }
224
225 @Override
226 protected void doSetTitle(String title) {
227 }
228
229 @Override
230 protected void doSetCustomText(String title) {
231 }
232
233 @Override
234 protected void updateProgress(double value) {
235 }
236
237 @Override
238 public void setProgressTaskId(ProgressTaskId taskId) {
239 }
240
241 @Override
242 public ProgressTaskId getProgressTaskId() {
243 return null;
244 }
245
246 @Override
247 public Component getWindowParent() {
248 return null;
249 }
250 };
251 }
252
253 /**
254 * Returns an instance of {@link Graphics2D}.
255 * @return a mockup graphics instance
256 */
257 public static Graphics2D newGraphics() {
258 return new FakeGraphics();
259 }
260
261 /**
262 * Creates a new way with the given tags (see {@link OsmUtils#createPrimitive(java.lang.String)}) and the nodes added
263 *
264 * @param tags the tags to set
265 * @param nodes the nodes to add
266 * @return a new way
267 */
268 public static Way newWay(String tags, Node... nodes) {
269 final Way way = (Way) OsmUtils.createPrimitive("way " + tags);
270 for (Node node : nodes) {
271 way.addNode(node);
272 }
273 return way;
274 }
275
276 /**
277 * Creates a new relation with the given tags (see {@link OsmUtils#createPrimitive(java.lang.String)}) and the members added
278 *
279 * @param tags the tags to set
280 * @param members the members to add
281 * @return a new relation
282 */
283 public static Relation newRelation(String tags, RelationMember... members) {
284 final Relation relation = (Relation) OsmUtils.createPrimitive("relation " + tags);
285 for (RelationMember member : members) {
286 relation.addMember(member);
287 }
288 return relation;
289 }
290
291 /**
292 * Creates a new empty command.
293 * @param ds data set
294 * @return a new empty command
295 */
296 public static Command newCommand(DataSet ds) {
297 return new Command(ds) {
298 @Override
299 public String getDescriptionText() {
300 return "";
301 }
302
303 @Override
304 public void fillModifiedData(Collection<OsmPrimitive> modified, Collection<OsmPrimitive> deleted,
305 Collection<OsmPrimitive> added) {
306 // Do nothing
307 }
308 };
309 }
310
311 /**
312 * Ensures 100% code coverage for enums.
313 * @param enumClass enum class to cover
314 */
315 public static void superficialEnumCodeCoverage(Class<? extends Enum<?>> enumClass) {
316 try {
317 Method values = enumClass.getMethod("values");
318 Method valueOf = enumClass.getMethod("valueOf", String.class);
319 Utils.setObjectsAccessible(values, valueOf);
320 for (Object o : (Object[]) values.invoke(null)) {
321 assertEquals(o, valueOf.invoke(null, ((Enum<?>) o).name()));
322 }
323 } catch (IllegalArgumentException | ReflectiveOperationException | SecurityException e) {
324 throw new JosmRuntimeException(e);
325 }
326 }
327
328 /**
329 * Get a descendant component by name.
330 * @param root The root component to start searching from.
331 * @param name The component name
332 * @return The component with that name or null if it does not exist.
333 * @since 12045
334 */
335 public static Component getComponentByName(Component root, String name) {
336 if (name.equals(root.getName())) {
337 return root;
338 } else if (root instanceof Container) {
339 Container container = (Container) root;
340 return Stream.of(container.getComponents())
341 .map(child -> getComponentByName(child, name))
342 .filter(Objects::nonNull)
343 .findFirst().orElse(null);
344 } else {
345 return null;
346 }
347 }
348
349 /**
350 * Use to assume that EqualsVerifier is working with the current JVM.
351 */
352 public static void assumeWorkingEqualsVerifier() {
353 try {
354 // Workaround to https://github.com/jqno/equalsverifier/issues/177
355 // Inspired by https://issues.apache.org/jira/browse/SOLR-11606
356 nl.jqno.equalsverifier.internal.lib.bytebuddy.ClassFileVersion.ofThisVm();
357 } catch (IllegalArgumentException e) {
358 Assume.assumeNoException(e);
359 }
360 }
361}
Note: See TracBrowser for help on using the repository browser.