[Aprog]
[aprog.git] / Aprog / test / net / sourceforge / aprog / tools / ToolsTest.java
blob81721a19749d508810cac2a7139b93a5feb102c9
1 /*
2 * The MIT License
3 *
4 * Copyright 2010 Codist Monk.
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
25 package net.sourceforge.aprog.tools;
27 import static org.junit.Assert.*;
29 import static net.sourceforge.aprog.tools.Launcher.*;
31 import java.io.ByteArrayOutputStream;
32 import java.io.File;
33 import java.io.FileInputStream;
34 import java.io.FileNotFoundException;
35 import java.io.FileOutputStream;
36 import java.io.IOException;
37 import java.io.InputStream;
38 import java.io.PrintStream;
39 import java.lang.ref.WeakReference;
40 import java.lang.reflect.Method;
41 import java.util.Arrays;
42 import java.util.Set;
43 import java.util.StringTokenizer;
44 import java.util.concurrent.Callable;
46 import org.junit.Test;
48 /**
49 * Automated tests using JUnit 4 for {@link Tools}.
51 * @author codistmonk (creation 2010-06-11)
53 public final class ToolsTest {
55 @Test
56 public final void testGCAndUsedMemory() {
57 final long usedMemoryBeforeAllocation = Tools.usedMemory();
58 Object object = new int[100000];
59 final long usedMemoryAfterAllocation = Tools.usedMemory();
60 final WeakReference<Object> weakReference = new WeakReference<Object>(object);
62 assertNotNull(weakReference.get());
64 object = null;
66 Tools.gc(100L);
68 final long usedMemoryAfterGC = Tools.usedMemory();
70 assertNull(weakReference.get());
71 assertTrue(usedMemoryBeforeAllocation < usedMemoryAfterAllocation);
72 assertTrue(usedMemoryAfterGC < usedMemoryAfterAllocation);
75 /**
76 * This creates a temporary folder with a name containing a space "tmp dirXXXXXX" (XXXXXX is a random number generated by {@link File#createTempFile(String, String)}.
77 * <br>Into this folder the minimum files needed to run {@link EchoApplicationFile} are copied:<ul>
78 * <li>EchoApplicationFile.class
79 * <li>Tools.class
80 * <li>IllegalInstantiationException.class
81 * </ul>
82 * <br>To make sure that {@link Tools#getApplicationFile()} returns the root for EchoApplicationFile (and not Tools), Tools and IllegalInstantiationException are placed in a different location (a subfolder "aprog").
83 * <br>Now, when running EchoApplicationFile with the temporary classpath, the temporary root folder path should be written to the standard output.
84 * <br>The test makes sure that this result is correct.
86 * @throws Exception If an unexpected error occurs
88 @Test
89 public final void testGetApplicationFile() throws Exception {
90 assertTrue(Tools.getApplicationFile().exists());
92 final File tmpRoot = File.createTempFile("tmp dir", "");
93 final File aprogRoot = new File(tmpRoot, "aprog");
95 assertTrue(tmpRoot.delete());
96 assertTrue(tmpRoot.mkdir());
97 assertTrue(aprogRoot.mkdir());
99 Tools.debugPrint(tmpRoot);
101 copyToTmp(IllegalInstantiationException.class, aprogRoot);
102 copyToTmp(Tools.class, aprogRoot);
103 copyToTmp(EchoApplicationFile.class, tmpRoot);
105 final String[] command = Tools.array("java", "-cp", aprogRoot.toString() + File.pathSeparator + tmpRoot, EchoApplicationFile.class.getCanonicalName());
107 Tools.debugPrint((Object[]) command);
109 final Process process = Runtime.getRuntime().exec(command);
111 final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
113 pipe(process.getInputStream(), new PrintStream(buffer));
114 pipe(process.getErrorStream(), System.err);
116 assertEquals(0, process.waitFor());
118 Tools.debugPrint(buffer);
120 assertEquals(tmpRoot.getCanonicalPath(), buffer.toString().trim());
122 tmpRoot.delete();
125 @Test
126 public final void testCreateTemporaryFile() {
128 final File temporaryFile = Tools.createTemporaryFile("prefix", "suffix", null);
130 assertTrue(temporaryFile.exists());
131 assertTrue(temporaryFile.getName().startsWith("prefix"));
132 assertTrue(temporaryFile.getName().endsWith("suffix"));
133 assertEquals(0L, temporaryFile.length());
136 final File temporaryFile = Tools.createTemporaryFile("prefix", "suffix",
137 Tools.getResourceAsStream(Tools.getThisPackagePath() + "test.txt"));
139 assertTrue(temporaryFile.exists());
140 assertTrue(temporaryFile.getName().startsWith("prefix"));
141 assertTrue(temporaryFile.getName().endsWith("suffix"));
142 assertEquals(2L, temporaryFile.length());
146 @Test
147 public final void testClose() throws IOException {
148 final InputStream input = Tools.getResourceAsStream(Tools.getThisPackagePath() + "test.txt");
150 assertTrue(input.available() > 0);
152 Tools.close(input);
154 try {
155 input.available();
157 fail("This point shouldn't be reached");
158 } catch (final IOException exception) {
159 assertEquals("Stream closed", exception.getMessage());
163 @Test
164 public final void testListAndIterable() {
165 assertEquals(Arrays.asList("42", "33"), Tools.list(Tools.iterable(new StringTokenizer("42 33"))));
168 @Test
169 public final void testArray() {
170 final Object[] array = new Object[] { 42, 33 };
172 assertSame(array, Tools.array(array));
173 assertArrayEquals(array, Tools.array(42, 33));
176 @Test
177 public final void testSet() {
178 final Set<?> set = Tools.set(42, 33, 42);
180 assertArrayEquals(Tools.array(42, 33), set.toArray());
183 @Test
184 public final void testAppend() {
185 final Object[] empty = new Object[0];
187 assertArrayEquals(Tools.array(42, 33, 42), Tools.append(Tools.array(42), Tools.array(33, 42)));
188 assertArrayEquals(Tools.array(42), Tools.append(Tools.array(42), empty));
189 assertArrayEquals(Tools.array(42), Tools.append(empty, Tools.array((Object) 42)));
190 assertArrayEquals(empty, Tools.append(empty, empty));
193 @Test
194 public final void testGetResourceAsStream() {
195 assertNotNull(Tools.getResourceAsStream(Tools.getThisPackagePath() + "test.txt"));
198 @Test
199 public final void testGetResourceURL() {
200 assertNotNull(Tools.getResourceURL(Tools.getThisPackagePath() + "test.txt"));
201 assertEquals(null, Tools.getResourceURL("missing_resource"));
204 @Test
205 public final void testInvoke() {
206 assertEquals(42, Tools.invoke(Integer.class, "parseInt", "42"));
207 assertEquals(42, Tools.invoke(42L, "intValue"));
210 final ObjectWithArbitraryProperties objectWithArbitraryProperties = new ObjectWithArbitraryProperties();
212 assertEquals(null, Tools.invoke(objectWithArbitraryProperties, "setPrivateStringProperty", "42"));
213 assertEquals("42", Tools.invoke(objectWithArbitraryProperties, "getPrivateStringProperty"));
217 @Test
218 public final void testGetGetter() {
219 final ObjectWithArbitraryProperties objectWithArbitraryProperties = new ObjectWithArbitraryProperties();
222 final Method getter = Tools.getGetter(objectWithArbitraryProperties, "intProperty");
224 assertNotNull(getter);
225 assertEquals("getIntProperty", getter.getName());
228 final Method getter = Tools.getGetter(objectWithArbitraryProperties, "booleanProperty1");
230 assertNotNull(getter);
231 assertEquals("isBooleanProperty1", getter.getName());
234 final Method getter = Tools.getGetter(objectWithArbitraryProperties, "booleanProperty2");
236 assertNotNull(getter);
237 assertEquals("hasBooleanProperty2", getter.getName());
240 final Method getter = Tools.getGetter(objectWithArbitraryProperties, "booleanProperty3");
242 assertNotNull(getter);
243 assertEquals("getBooleanProperty3", getter.getName());
246 final Method getter = Tools.getGetter(objectWithArbitraryProperties, "packagePrivateStringProperty");
248 assertNotNull(getter);
249 assertEquals("getPackagePrivateStringProperty", getter.getName());
252 final Method getter = Tools.getGetter(objectWithArbitraryProperties, "privateStringProperty");
254 assertNotNull(getter);
255 assertEquals("getPrivateStringProperty", getter.getName());
259 @Test
260 public final void testGetGetterFailure() {
261 final ObjectWithArbitraryProperties objectWithArbitraryProperties = new ObjectWithArbitraryProperties();
263 try {
264 // Missing property
265 final Method getter = Tools.getGetter(objectWithArbitraryProperties, "missingProperty");
267 fail("getGetter() should have failed but instead returned " + getter);
268 } catch (final RuntimeException expectedException) {
269 // Do nothing
273 try {
274 // Bad casing
275 final Method getter = Tools.getGetter(objectWithArbitraryProperties, "INTPROPERTY");
277 fail("getGetter() should have failed but instead returned " + getter);
278 } catch (final RuntimeException expectedException) {
279 // Do nothing
284 @Test
285 public final void testGetSetter() {
286 final ObjectWithArbitraryProperties objectWithArbitraryProperties = new ObjectWithArbitraryProperties();
289 final Method setter = Tools.getSetter(objectWithArbitraryProperties, "intProperty", int.class);
291 assertNotNull(setter);
292 assertEquals("setIntProperty", setter.getName());
295 final Method setter = Tools.getSetter(objectWithArbitraryProperties, "booleanProperty1", boolean.class);
297 assertNotNull(setter);
298 assertEquals("setBooleanProperty1", setter.getName());
301 final Method setter = Tools.getSetter(objectWithArbitraryProperties, "packagePrivateStringProperty", String.class);
303 assertNotNull(setter);
304 assertEquals("setPackagePrivateStringProperty", setter.getName());
307 final Method setter = Tools.getSetter(objectWithArbitraryProperties, "privateStringProperty", String.class);
309 assertNotNull(setter);
310 assertEquals("setPrivateStringProperty", setter.getName());
314 @Test
315 public final void testGetSetterFailure() {
316 final ObjectWithArbitraryProperties objectWithArbitraryProperties = new ObjectWithArbitraryProperties();
319 try {
320 // Missing property
321 final Method setter = Tools.getGetter(objectWithArbitraryProperties, "missingProperty");
323 fail("getSetter() should have failed but instead returned " + setter);
324 } catch (final RuntimeException expectedException) {
325 Tools.ignore(expectedException);
330 try {
331 // Bad casing
332 final Method setter = Tools.getSetter(objectWithArbitraryProperties, "INTPROPERTY", int.class);
334 fail("getSetter() should have failed but instead returned " + setter);
335 } catch (final RuntimeException expectedException) {
336 Tools.ignore(expectedException);
340 try {
341 // Mismatching parameter type
342 final Method setter = Tools.getSetter(objectWithArbitraryProperties, "intProperty", boolean.class);
344 fail("getSetter() should have failed but instead returned " + setter);
345 } catch (final RuntimeException expectedException) {
346 Tools.ignore(expectedException);
351 @Test
352 public final void testToUpperCamelCase() {
353 assertEquals("CamelCase", Tools.toUpperCamelCase("camelCase"));
356 @Test
357 public final void testEmptyIfNull() {
358 assertEquals("", Tools.emptyIfNull(null));
359 assertSame("", Tools.emptyIfNull(""));
360 assertSame("42", Tools.emptyIfNull("42"));
363 @Test
364 public final void testGetPackagePath() {
365 assertEquals("net/sourceforge/aprog/tools/", Tools.getPackagePath(ToolsTest.class));
368 @Test
369 public final void testGetCallerPackagePath() {
370 assertEquals("net/sourceforge/aprog/tools/", Tools.getThisPackagePath());
373 @Test
374 public final void testGetTopLevelEclosingClass() throws Exception {
375 assertEquals(this.getClass(), new Callable<Class<?>>() {
377 @Override
378 public final Class<?> call() throws Exception {
379 return Tools.getTopLevelEnclosingClass(this.getClass());
382 }.call());
385 @Test
386 public final void testGetCallerClass() {
387 assertEquals(this.getClass(), ToolsTest.getCallerClass());
390 @Test
391 public final void testGetLoggerForThisMethod() {
392 assertTrue(Tools.getLoggerForThisMethod().getName().endsWith("testGetLoggerForThisMethod"));
395 @Test
396 public final void testThrowUnchecked() {
398 final Throwable originalThrowable = new RuntimeException();
400 try {
401 Tools.throwUnchecked(originalThrowable);
402 } catch(final RuntimeException caughtThrowable) {
403 assertSame(originalThrowable, caughtThrowable);
408 final Throwable originalThrowable = new Exception();
410 try {
411 Tools.throwUnchecked(originalThrowable);
412 } catch(final RuntimeException caughtThrowable) {
413 assertNotNull(caughtThrowable.getCause());
414 assertSame(originalThrowable, caughtThrowable.getCause());
419 final Throwable originalThrowable = new Error();
421 try {
422 Tools.throwUnchecked(originalThrowable);
423 } catch(final Error caughtThrowable) {
424 assertSame(originalThrowable, caughtThrowable);
429 final Throwable originalThrowable = new Throwable();
431 try {
432 Tools.throwUnchecked(originalThrowable);
433 } catch(final Throwable caughtThrowable) {
434 assertSame(originalThrowable, caughtThrowable.getCause());
439 @Test
440 public final void testUnchecked() {
442 final Throwable cause = new Throwable();
444 assertSame(cause, Tools.unchecked(cause).getCause());
447 final Throwable cause = new Error();
449 assertSame(cause, Tools.unchecked(cause).getCause());
452 final Throwable cause = new Exception();
454 assertSame(cause, Tools.unchecked(cause).getCause());
457 final Throwable cause = new RuntimeException();
459 assertSame(cause, Tools.unchecked(cause));
463 @Test
464 public final void testCast() {
465 final Object object = "42";
466 final String that = Tools.cast(String.class, object);
468 assertSame(object, that);
470 final Integer badCast = Tools.cast(Integer.class, object);
472 assertNull(badCast);
475 @Test
476 public final void testCastToCurrentClass() {
477 assertNull(Tools.castToCurrentClass(42));
478 assertSame(this, Tools.castToCurrentClass(this));
479 assertNotNull(Tools.castToCurrentClass(new ToolsTest()));
482 @Test
483 public final void testEquals() {
484 final Object object = "42";
486 assertTrue(Tools.equals(null, null));
487 assertFalse(Tools.equals(object, null));
488 assertTrue(Tools.equals(object, object));
489 assertTrue(Tools.equals(new Integer(6 * 7).toString(), object));
490 assertFalse(Tools.equals(object, 42));
493 @Test
494 public final void testHashCode() {
495 final Object object = "42";
497 assertEquals(0, Tools.hashCode(null));
498 assertEquals(object.hashCode(), Tools.hashCode(object));
503 * @return
504 * <br>Maybe null
506 private static final Class<?> getCallerClass() {
507 return Tools.getCallerClass();
512 * @param cls
513 * <br>Not null
514 * @param tmpRoot
515 * <br>Not null
516 * <br>Input-output
517 * @throws FileNotFoundException If an error occurs
519 private static final void copyToTmp(final Class<?> cls, final File tmpRoot) throws FileNotFoundException {
520 File file = tmpRoot;
522 for (final String pathElement : Tools.getThisPackagePath().split("/")) {
523 file = new File(file, pathElement);
525 assertTrue(file.isDirectory() || file.mkdir());
528 final String classFileName = cls.getSimpleName() + ".class";
530 file = new File(file, classFileName);
532 Tools.write(
533 new FileInputStream(Tools.getClassRoot(cls) + File.separator + Tools.getThisPackagePath() + classFileName),
534 new FileOutputStream(file));
540 * @author codistmonk (creation 2010-05-19)
542 class ObjectWithArbitraryProperties {
544 private int intProperty;
546 private boolean booleanProperty1;
548 private boolean booleanProperty2;
550 private boolean booleanProperty3;
552 private String packagePrivateStringProperty;
554 private String privateStringProperty;
557 // The following instruction removes "unused" warnings
558 this.setPrivateStringProperty(this.getPrivateStringProperty());
563 * @return
564 * <br>Range: Any integer
566 public final int getIntProperty() {
567 return this.intProperty;
572 * @param intProperty an arbitrary integer
573 * <br>Range: Any integer
575 public final void setIntProperty(final int intProperty) {
576 this.intProperty = intProperty;
579 public final boolean isBooleanProperty1() {
580 return this.booleanProperty1;
585 * @param booleanProperty1 an arbitrary boolean
587 public final void setBooleanProperty1(final boolean booleanProperty1) {
588 this.booleanProperty1 = booleanProperty1;
591 public final boolean hasBooleanProperty2() {
592 return this.booleanProperty2;
597 * @param booleanProperty2 an arbitrary boolean
599 public final void setBooleanProperty2(final boolean booleanProperty2) {
600 this.booleanProperty2 = booleanProperty2;
603 public final boolean getBooleanProperty3() {
604 return this.booleanProperty3;
609 * @param booleanProperty3 an arbitrary boolean
611 public final void setBooleanProperty3(final boolean booleanProperty3) {
612 this.booleanProperty3 = booleanProperty3;
617 * @return
618 * <br>A possibly null value
619 * <br>A shared value
621 final String getPackagePrivateStringProperty() {
622 return this.packagePrivateStringProperty;
627 * @param packagePrivateStringProperty
628 * <br>Can be null
629 * <br>Shared parameter
631 final void setPackagePrivateStringProperty(final String packagePrivateStringProperty) {
632 this.packagePrivateStringProperty = packagePrivateStringProperty;
637 * @return
638 * <br>A possibly null value
639 * <br>A shared value
641 private final String getPrivateStringProperty() {
642 return this.privateStringProperty;
647 * @param privateStringProperty
648 * <br>Can be null
649 * <br>Shared parameter
651 private final void setPrivateStringProperty(final String privateStringProperty) {
652 this.privateStringProperty = privateStringProperty;