Debian Codegraph @

src/test/java/ezvcard/util/TestUtils.java

raw symbols SCIP
1 package ezvcard.util;
2
3 import static org.junit.Assert.assertEquals;
4 import static org.junit.Assert.assertFalse;
5 import static org.junit.Assert.assertNotEquals;
6 import static org.junit.Assert.assertNull;
7 import static org.junit.Assert.assertTrue;
8 import static org.junit.Assert.fail;
9
10 import java.io.IOException;
11 import java.io.UncheckedIOException;
12 import java.util.ArrayList;
13 import java.util.Arrays;
14 import java.util.Collection;
15 import java.util.HashMap;
16 import java.util.HashSet;
17 import java.util.List;
18 import java.util.Map;
19 import java.util.Set;
20 import java.util.SimpleTimeZone;
21 import java.util.TimeZone;
22
23 import ezvcard.VCard;
24 import ezvcard.VCardVersion;
25 import ezvcard.ValidationWarning;
26 import ezvcard.ValidationWarnings;
27 import ezvcard.io.ParseWarning;
28 import ezvcard.io.StreamReader;
29 import ezvcard.property.VCardProperty;
30
31 /*
32 Copyright (c) 2012-2023, Michael Angstadt
33 All rights reserved.
34
35 Redistribution and use in source and binary forms, with or without
36 modification, are permitted provided that the following conditions are met:
37
38 1. Redistributions of source code must retain the above copyright notice, this
39 list of conditions and the following disclaimer.
40 2. Redistributions in binary form must reproduce the above copyright notice,
41 this list of conditions and the following disclaimer in the documentation
42 and/or other materials provided with the distribution.
43
44 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
45 ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
46 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
47 DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
48 ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
49 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
50 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
51 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
52 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
53 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
54
55 The views and conclusions contained in the software and documentation are those
56 of the authors and should not be interpreted as representing official policies,
57 either expressed or implied, of the FreeBSD Project.
58 */
59
60 /**
61 * Utility classes for unit tests.
62 * @author Michael Angstadt
63 */
64 public class TestUtils {
65 /**
66 * Tests the version assigned to a {@link VCard} object.
67 * @param expected the expected version
68 * @param vcard the vCard object
69 */
70 public static void assertVersion(VCardVersion expected, VCard vcard) {
71 VCardVersion actual = vcard.getVersion();
72 assertEquals(expected, actual);
73 }
74
75 /**
76 * Tests how many properties are in a vCard.
77 * @param expected the expected number of properties
78 * @param vcard the vCard
79 */
80 public static void assertPropertyCount(int expected, VCard vcard) {
81 int actual = vcard.getProperties().size();
82 assertEquals(expected, actual);
83 }
84
85 /**
86 * Tests to make sure there are no more vCards on a data stream.
87 * @param reader the data stream
88 */
89 public static void assertNoMoreVCards(StreamReader reader) {
90 try {
91 assertNull(reader.readNext());
92 } catch (IOException e) {
93 throw new UncheckedIOException(e);
94 }
95 }
96
97 /**
98 * Asserts a list of parse warnings.
99 * @param warnings the parse warnings
100 * @param expectedCodes the expected warning codes (order does not matter,
101 * use "null" for warnings that do not have a code)
102 */
103 public static void assertParseWarnings(List<ParseWarning> warnings, Integer... expectedCodes) {
104 List<Integer> expectedWarnings = new ArrayList<>(Arrays.asList(expectedCodes));
105 List<Integer> actualWarnings = new ArrayList<>(warnings.size());
106 for (ParseWarning warning : warnings) {
107 actualWarnings.add(warning.getCode());
108 }
109
110 for (Integer actualWarning : actualWarnings) {
111 if (!expectedWarnings.remove(actualWarning)) {
112 fail("Expected these warnings " + expectedWarnings + ", but was this: " + actualWarnings + ". Actual warnings: " + warnings);
113 }
114 }
115 }
116
117 /**
118 * Asserts the parse warnings of a {@link StreamReader}.
119 * @param reader the {@link StreamReader}
120 * @param expectedCodes the expected warning codes (order does not matter,
121 * use "null" for warnings that do not have a code)
122 */
123 public static void assertParseWarnings(StreamReader reader, Integer... expectedCodes) {
124 assertParseWarnings(reader.getWarnings(), expectedCodes);
125 }
126
127 /**
128 * Asserts that a list is a certain size.
129 * @param expectedSize the expected size of the list
130 * @param list the list
131 */
132 public static void assertListSize(int expectedSize, List<?> list) {
133 int actualSize = list.size();
134 assertEquals(list.toString(), expectedSize, actualSize);
135 }
136
137 public static boolean checkCodes(List<ValidationWarning> warnings, Integer... expectedCodes) {
138 if (warnings.size() != expectedCodes.length) {
139 return false;
140 }
141
142 /*
143 * Don't use a Set because there can be multiple warnings with the same
144 * code.
145 */
146 List<Integer> expected = new ArrayList<>(Arrays.asList(expectedCodes));
147
148 for (ValidationWarning warning : warnings) {
149 Integer code = warning.getCode();
150 boolean removed = expected.remove((Object) code);
151 if (!removed) {
152 return false;
153 }
154 }
155 return true;
156 }
157
158 public static void assertValidate(List<ValidationWarning> warnings, Integer... expectedCodes) {
159 boolean passed = checkCodes(warnings, expectedCodes);
160 if (!passed) {
161 fail("Expected codes were " + Arrays.toString(expectedCodes) + " but were actually:\n" + warnings);
162 }
163 }
164
165 public static VCardValidateChecker assertValidate(VCard vcard) {
166 return new VCardValidateChecker(vcard);
167 }
168
169 public static class VCardValidateChecker {
170 private final VCard vcard;
171 private VCardVersion versions[] = VCardVersion.values();
172 private Map<VCardProperty, Integer[]> expectedPropCodes = new HashMap<>();
173
174 public VCardValidateChecker(VCard vcard) {
175 this.vcard = vcard;
176 }
177
178 /**
179 * Defines the versions to check (defaults to all versions).
180 * @param versions the versions to check
181 * @return this
182 */
183 public VCardValidateChecker versions(VCardVersion... versions) {
184 this.versions = versions;
185 return this;
186 }
187
188 /**
189 * Assigns the warning codes that a property is expected to generate.
190 * @param property the property or null to represent the vCard warnings
191 * @param expectedCodes the expected warning codes
192 * @return this
193 */
194 public VCardValidateChecker prop(VCardProperty property, Integer... expectedCodes) {
195 expectedPropCodes.put(property, expectedCodes);
196 return this;
197 }
198
199 /**
200 * Performs the validation check.
201 */
202 public void run() {
203 for (VCardVersion version : versions) {
204 Map<VCardProperty, Integer[]> expectedPropCodes = new HashMap<>(this.expectedPropCodes);
205 ValidationWarnings warnings = vcard.validate(version);
206 for (Map.Entry<VCardProperty, List<ValidationWarning>> entry : warnings) {
207 VCardProperty property = entry.getKey();
208 List<ValidationWarning> actualWarnings = entry.getValue();
209
210 Integer[] expectedCodes = expectedPropCodes.remove(property);
211 if (expectedCodes == null) {
212 String className = (property == null) ? "vCard" : property.getClass().getSimpleName();
213 fail("For version " + version + ", " + className + " had " + actualWarnings.size() + " warnings, but none were expected. Actual warnings:\n" + warnings);
214 }
215
216 boolean passed = checkCodes(actualWarnings, expectedCodes);
217 if (!passed) {
218 fail("For version " + version + ", expected validation warnings did not match actual warnings. Actual warnings:\n" + warnings);
219 }
220 }
221
222 if (!expectedPropCodes.isEmpty()) {
223 List<String> lines = new ArrayList<>();
224 for (Map.Entry<VCardProperty, Integer[]> entry : expectedPropCodes.entrySet()) {
225 VCardProperty property = entry.getKey();
226 String className = (property == null) ? null : property.getClass().getSimpleName();
227 Integer[] expectedCodes = entry.getValue();
228 lines.add(className + ": " + Arrays.toString(expectedCodes));
229 }
230 fail("For version " + version + ", the following validation warnings were expected, but NOT thrown:\n" + lines + "\nActual warnings:\n" + warnings);
231 }
232 }
233 }
234 }
235
236 /**
237 * Asserts the value of an {@link Integer} object.
238 * @param expected the expected value
239 * @param actual the actual value
240 */
241 public static void assertIntEquals(int expected, Integer actual) {
242 assertEquals(Integer.valueOf(expected), actual);
243 }
244
245 /**
246 * Asserts the contents of a collection. Does not check for order.
247 * @param actual the actual collection
248 * @param expectedElements the elements that are expected to be in the
249 * collection (order does not matter)
250 */
251 public static <T> void assertCollectionContains(Collection<T> actual, T... expectedElements) {
252 assertEquals(expectedElements.length, actual.size());
253
254 Collection<T> actualCopy = new ArrayList<>(actual);
255 for (T expectedElement : expectedElements) {
256 assertTrue("Collection did not contain: " + expectedElement, actualCopy.remove(expectedElement));
257 }
258 }
259
260 /**
261 * Builds a timezone object with the given offset.
262 * @param hours the hour offset
263 * @param minutes the minute offset
264 * @return the timezone object
265 */
266 public static TimeZone buildTimezone(int hours, int minutes) {
267 int hourMillis = 1000 * 60 * 60 * hours;
268
269 int minuteMillis = 1000 * 60 * minutes;
270 if (hours < 0) {
271 minuteMillis *= -1;
272 }
273
274 return new SimpleTimeZone(hourMillis + minuteMillis, "");
275 }
276
277 /**
278 * Asserts the contents of a set.
279 * @param actualSet the actual set
280 * @param expectedElements the elements that are expected to be in the set
281 */
282 public static <T> void assertSetEquals(Set<T> actualSet, T... expectedElements) {
283 Set<T> expectedSet = new HashSet<>(expectedElements.length);
284 expectedSet.addAll(Arrays.asList(expectedElements));
285 assertEquals(expectedSet, actualSet);
286 }
287
288 /**
289 * Creates a GMT timezone.
290 * @param offsetMillis the offset in milliseconds
291 * @return the timezone
292 */
293 public static TimeZone gmtTz(long offsetMillis) {
294 long totalMinutes = Math.abs(offsetMillis / 1000 / 60);
295 long hours = totalMinutes / 60;
296 long minutes = totalMinutes % 60;
297
298 StringBuilder tzid = new StringBuilder("GMT");
299 tzid.append((offsetMillis >= 0) ? '+' : '-');
300
301 if (hours < 10) {
302 tzid.append('0');
303 }
304 tzid.append(hours);
305
306 tzid.append(':');
307
308 if (minutes < 10) {
309 tzid.append('0');
310 }
311 tzid.append(minutes);
312
313 return TimeZone.getTimeZone(tzid.toString());
314 }
315
316 /**
317 * <p>
318 * Asserts some of the basic rules for the equals() method:
319 * </p>
320 * <ul>
321 * <li>The same object instance is equal to itself.</li>
322 * <li>Passing {@code null} into the method returns false.</li>
323 * <li>Passing an instance of a different class into the method returns
324 * false.</li>
325 * </ul>
326 * @param object an instance of the class to test.
327 */
328 public static void assertEqualsMethodEssentials(Object object) {
329 assertEquals(object, object);
330 assertFalse(object.equals(null));
331 assertFalse(object.equals("other class"));
332 }
333
334 /**
335 * Asserts that two objects are equal according to their equals() method.
336 * Also asserts that their hash codes are the same.
337 * @param one the first object
338 * @param two the second object
339 */
340 public static void assertEqualsAndHash(Object one, Object two) {
341 assertEquals(one, two);
342 assertEquals(two, one);
343 assertEquals(one.hashCode(), two.hashCode());
344 }
345
346 /**
347 * Asserts that calling {@code one.equals(two)} and {@code two.equals(one)}
348 * will both return false.
349 * @param one the first object
350 * @param two the second object
351 */
352 public static void assertNotEqualsBothWays(Object one, Object two) {
353 assertNotEquals(one, two);
354 assertNotEquals(two, one);
355 }
356
357 /**
358 * Asserts that none of the given objects are equal to each other.
359 * @param objects the objects
360 */
361 public static void assertNothingIsEqual(Object... objects) {
362 assertNothingIsEqual(Arrays.asList(objects));
363 }
364
365 /**
366 * Asserts that none of the given objects are equal to each other.
367 * @param objects the objects
368 */
369 public static void assertNothingIsEqual(Iterable<Object> objects) {
370 for (Object object1 : objects) {
371 for (Object object2 : objects) {
372 if (object1 != object2) {
373 assertNotEquals("Objects should not be equal:\n" + object1 + "\n" + object2, object1, object2);
374 }
375 }
376 }
377 }
378
379 public static <T> T[] each(T... t) {
380 return t;
381 }
382
383 private TestUtils() {
384 //hide
385 }
386 }