KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > tc > test > TCTestCase


1 /**
2  * All content copyright (c) 2003-2006 Terracotta, Inc., except as may otherwise be noted in a separate copyright
3  * notice. All rights reserved.
4  */

5 package com.tc.test;
6
7 import org.apache.commons.lang.exception.ExceptionUtils;
8
9 import EDU.oswego.cs.dl.util.concurrent.SynchronizedBoolean;
10 import EDU.oswego.cs.dl.util.concurrent.SynchronizedRef;
11
12 import com.tc.exception.TCRuntimeException;
13 import com.tc.logging.TCLogging;
14 import com.tc.test.collections.CollectionAssert;
15 import com.tc.util.Assert;
16 import com.tc.util.EqualityComparator;
17 import com.tc.util.SameObjectEqualityComparator;
18 import com.tc.util.StandardStringifier;
19 import com.tc.util.Stringifier;
20 import com.tc.util.TCTimerImpl;
21 import com.tc.util.diff.Difference;
22 import com.tc.util.diff.DifferenceBuilder;
23 import com.tc.util.diff.Differenceable;
24 import com.tc.util.runtime.ThreadDump;
25
26 import java.io.ByteArrayInputStream JavaDoc;
27 import java.io.ByteArrayOutputStream JavaDoc;
28 import java.io.File JavaDoc;
29 import java.io.IOException JavaDoc;
30 import java.io.ObjectInputStream JavaDoc;
31 import java.io.ObjectOutputStream JavaDoc;
32 import java.text.DateFormat JavaDoc;
33 import java.text.ParseException JavaDoc;
34 import java.text.SimpleDateFormat JavaDoc;
35 import java.util.Arrays JavaDoc;
36 import java.util.Comparator JavaDoc;
37 import java.util.Date JavaDoc;
38 import java.util.Hashtable JavaDoc;
39 import java.util.List JavaDoc;
40 import java.util.Map JavaDoc;
41 import java.util.Timer JavaDoc;
42 import java.util.TimerTask JavaDoc;
43
44 import junit.framework.AssertionFailedError;
45 import junit.framework.TestCase;
46
47 /**
48  * A base for all Terracotta tests.
49  */

50 public class TCTestCase extends TestCase {
51
52   private static final long DEFAULT_TIMEOUT_THRESHOLD = 60000;
53   private static final DateFormat JavaDoc DATE_FORMAT = new SimpleDateFormat JavaDoc("yyyy-MM-dd");
54
55   private final SynchronizedRef beforeTimeoutException = new SynchronizedRef(null);
56
57   private DataDirectoryHelper dataDirectoryHelper;
58   private TempDirectoryHelper tempDirectoryHelper;
59
60   private Date JavaDoc allDisabledUntil;
61   private final Map JavaDoc disabledUntil = new Hashtable JavaDoc();
62
63   // This stuff is static since Junit new()'s up an instance of the test case for each test method,
64
// and the timeout covers the entire test case (ie. all methods). It wouldn't be very effective to start
65
// the timer for each test method given this
66
private static final Timer JavaDoc timeoutTimer = new TCTimerImpl("Timeout Thread", true);
67   private static final SynchronizedBoolean timeoutTaskAdded = new SynchronizedBoolean(false);
68
69   // If you want to customize this, you have to do it in the constructor of your test case (setUp() is too late)
70
private long timeoutThreshold = DEFAULT_TIMEOUT_THRESHOLD;
71
72   // controls for thread dumping.
73
private boolean dumpThreadsOnTimeout = true;
74   private int numThreadDumps = 3;
75   private long dumpInterval = 500;
76
77   // a way to ensure that system clock moves forward...
78
private long previousSystemMillis = 0;
79
80   public TCTestCase() {
81     super();
82
83     TCLogging.disableLocking();
84   }
85
86   public TCTestCase(String JavaDoc arg0) {
87     super(arg0);
88
89     TCLogging.disableLocking();
90   }
91
92   // called by timer thread (ie. NOT the main thread of test case)
93
private void timeoutCallback() {
94     String JavaDoc bar = "***************************************";
95     System.err.println("\n" + bar + "\n+ TCTestCase timeout alarm going off at " + new Date JavaDoc() + "\n" + bar + "\n");
96     System.err.flush();
97
98     doDumpServerDetails();
99     if (dumpThreadsOnTimeout) {
100       try {
101         doThreadDump();
102       } catch (Throwable JavaDoc t) {
103         // don't fail the test b/c of this
104
t.printStackTrace();
105       }
106     }
107
108     try {
109       beforeTimeout();
110     } catch (Throwable JavaDoc t) {
111       this.beforeTimeoutException.set(t);
112     }
113   }
114
115   protected void doDumpServerDetails() {
116   // NOP - Overridden by subclasses
117
}
118
119   // override this method if you want to do something before your test times out
120
protected void beforeTimeout() throws Throwable JavaDoc {
121     if (false) throw new AssertionError JavaDoc(); // silence compiler warning
122
}
123
124   public void runBare() throws Throwable JavaDoc {
125     if (isAllDisabled()) {
126       System.out.println("NOTE: ALL tests in " + this.getClass().getName() + " are disabled until "
127           + this.allDisabledUntil);
128       System.out.flush();
129       return;
130     }
131
132     final String JavaDoc testMethod = getName();
133     if (isTestDisabled(testMethod)) {
134       System.out.println("NOTE: Test method " + testMethod + "() is disabled until "
135           + this.disabledUntil.get(testMethod));
136       System.out.flush();
137       return;
138     }
139
140     // don't move this stuff to runTest(), you want the timeout timer to catch hangs in setUp() too.
141
// Yes it means you can't customize the timeout threshold in setUp() -- take a deep breath and
142
// set your value in the constructor of your test case instead of setUp()
143
if (timeoutTaskAdded.commit(false, true)) {
144       scheduleTimeoutTask();
145     }
146
147     Throwable JavaDoc testException = null;
148     try {
149       super.runBare();
150     } catch (Throwable JavaDoc t) {
151       testException = t;
152     }
153
154     Throwable JavaDoc exceptionInTimeoutCallback = (Throwable JavaDoc) beforeTimeoutException.get();
155
156     // favor the "real" exception to make test fail. If there was a exception in the timeout callback,
157
// make that able to fail the test too
158
if (testException != null) {
159       if (exceptionInTimeoutCallback != null) {
160         exceptionInTimeoutCallback.printStackTrace();
161       }
162       throw testException;
163     }
164
165     if (exceptionInTimeoutCallback != null) { throw exceptionInTimeoutCallback; }
166
167     // no errors -- woo-hoo!
168
return;
169   }
170
171   private void scheduleTimeoutTask() throws IOException JavaDoc {
172     // enforce some sanity
173
final int MINIMUM = 30;
174     long junitTimeout = this.getTimeoutValueInSeconds();
175
176     if (junitTimeout < MINIMUM) { throw new IllegalArgumentException JavaDoc("Junit timeout cannot be less than " + MINIMUM
177         + " seconds"); }
178
179     final int MIN_THRESH = 15000;
180     junitTimeout *= 1000;
181     if ((junitTimeout - timeoutThreshold) < MIN_THRESH) {
182       System.err.println("ERROR: Cannot apply timeout threshold of " + timeoutThreshold + ", using " + MIN_THRESH
183           + " instead");
184       System.err.flush();
185       timeoutThreshold = MIN_THRESH;
186     }
187
188     long delay = junitTimeout - timeoutThreshold;
189
190     timeoutTimer.schedule(new TimerTask JavaDoc() {
191       public void run() {
192         timeoutCallback();
193       }
194     }, delay);
195   }
196
197   public void setThreadDumpInterval(long interval) {
198     this.dumpInterval = interval;
199   }
200
201   public void setDumpThreadsOnTimeout(boolean dump) {
202     this.dumpThreadsOnTimeout = dump;
203   }
204
205   public void setNumThreadDumps(int dumps) {
206     this.numThreadDumps = dumps;
207   }
208
209   public void setTimeoutThreshold(long threshold) {
210     this.timeoutThreshold = threshold;
211   }
212
213   protected final synchronized TempDirectoryHelper getTempDirectoryHelper() {
214     if (tempDirectoryHelper == null) {
215       try {
216         tempDirectoryHelper = new TempDirectoryHelper(getClass(), cleanTempDir());
217       } catch (IOException JavaDoc ioe) {
218         throw new TCRuntimeException("Can't get configuration for temp directory", ioe);
219       }
220     }
221
222     return tempDirectoryHelper;
223   }
224
225   protected boolean cleanTempDir() {
226     return true;
227   }
228
229   protected final synchronized DataDirectoryHelper getDataDirectoryHelper() {
230     if (dataDirectoryHelper == null) {
231       try {
232         dataDirectoryHelper = new DataDirectoryHelper(getClass());
233       } catch (IOException JavaDoc ioe) {
234         throw new TCRuntimeException(ioe.getLocalizedMessage(), ioe);
235       }
236     }
237
238     return dataDirectoryHelper;
239   }
240
241   protected final File JavaDoc getDataDirectory() throws IOException JavaDoc {
242     return getDataDirectoryHelper().getDirectory();
243   }
244
245   protected final File JavaDoc getDataFile(String JavaDoc fileName) throws IOException JavaDoc {
246     return getDataDirectoryHelper().getFile(fileName);
247   }
248
249   protected final File JavaDoc getTempDirectory() throws IOException JavaDoc {
250     return getTempDirectoryHelper().getDirectory();
251   }
252
253   protected final File JavaDoc getTempFile(String JavaDoc fileName) throws IOException JavaDoc {
254     return getTempDirectoryHelper().getFile(fileName);
255   }
256
257   /**
258    * Disable ALL tests until the given date. This method should be called in the constructor of your unit test
259    */

260   protected final void disableAllUntil(Date JavaDoc theDate) {
261     Assert.eval(theDate != null);
262     this.allDisabledUntil = theDate;
263   }
264
265   /**
266    * Disable ALL tests until the given date. This method should be called in the constructor of your unit test
267    */

268   protected final void disableAllUntil(String JavaDoc theDate) {
269     disableAllUntil(parseDate(theDate));
270   }
271
272   /**
273    * Disable ALL tests until the given date. This method should be called in the constructor of your unit test Only
274    * specified platforms ("windows", "linux", "solaris") will take effect.
275    */

276   protected final void disableAllUntil(String JavaDoc theDate, String JavaDoc[] platforms) {
277     List JavaDoc platform_list = Arrays.asList(platforms);
278     try {
279       String JavaDoc platform = TestConfigObject.getInstance().platform();
280       if (platform_list.contains(platform)) {
281         disableAllUntil(parseDate(theDate));
282       }
283     } catch (IOException JavaDoc e) {
284       e.printStackTrace();
285     }
286   }
287
288   /**
289    * Disable the given test method until the given date. This method should be called in the constructor of your unit
290    * test
291    */

292   protected final void disableTestUntil(String JavaDoc method, String JavaDoc date) {
293     this.disabledUntil.put(method, parseDate(date));
294   }
295
296   /**
297    * Disable the given test method until the given date. This method should be called in the constructor of your unit
298    * test. Only specified platforms ("windows", "linux", "solaris") take effect.
299    */

300   protected final void disableTestUntil(String JavaDoc method, String JavaDoc date, String JavaDoc[] platforms) {
301     List JavaDoc platform_list = Arrays.asList(platforms);
302     try {
303       String JavaDoc platform = TestConfigObject.getInstance().platform();
304       if (platform_list.contains(platform)) {
305         this.disabledUntil.put(method, parseDate(date));
306       }
307     } catch (IOException JavaDoc e) {
308       e.printStackTrace();
309     }
310   }
311
312   /**
313    * Disable the given test method until the given date. This method should be called in the constructor of your unit
314    * test
315    */

316   protected final void disableTestUntil(String JavaDoc method, Date JavaDoc date) {
317     this.disabledUntil.put(method, date);
318   }
319
320   protected final void assertSameOrdered(Object JavaDoc one, Object JavaDoc two) {
321     assertEqualsOrdered(one, two, SameObjectEqualityComparator.INSTANCE);
322   }
323
324   protected final void assertEqualsOrdered(Object JavaDoc one, Object JavaDoc two) {
325     CollectionAssert.assertEqualOrdered(one, two);
326   }
327
328   protected final void assertEqualsOrdered(Object JavaDoc one, Object JavaDoc two, EqualityComparator comparator) {
329     CollectionAssert.assertEqualOrdered(one, two, comparator);
330   }
331
332   protected final void assertSameUnordered(Object JavaDoc one, Object JavaDoc two) {
333     assertEqualsUnordered(one, two, SameObjectEqualityComparator.INSTANCE);
334   }
335
336   protected final void assertEqualsUnordered(Object JavaDoc one, Object JavaDoc two) {
337     CollectionAssert.assertEqualUnordered(one, two);
338   }
339
340   protected final void assertEqualsUnordered(Object JavaDoc one, Object JavaDoc two, EqualityComparator comparator) {
341     CollectionAssert.assertEqualUnordered(one, two, comparator);
342   }
343
344   protected final void assertSameUnorderedUncounted(Object JavaDoc one, Object JavaDoc two) {
345     assertEqualsUnorderedUncounted(one, two, SameObjectEqualityComparator.INSTANCE);
346   }
347
348   protected final void assertEqualsUnorderedUncounted(Object JavaDoc one, Object JavaDoc two) {
349     CollectionAssert.assertEqualUnorderedUncounted(one, two);
350   }
351
352   protected final void assertEqualsUnorderedUncounted(Object JavaDoc one, Object JavaDoc two, EqualityComparator comparator) {
353     CollectionAssert.assertEqualUnorderedUncounted(one, two, comparator);
354   }
355
356   protected final void assertEqualsVerbose(Object JavaDoc one, Object JavaDoc two) {
357     assertEqualsVerbose(null, one, two, StandardStringifier.INSTANCE, false);
358   }
359
360   protected final void assertEqualsVerbose(Object JavaDoc one, Object JavaDoc two, Stringifier stringifier) {
361     assertEqualsVerbose(null, one, two, stringifier, false);
362   }
363
364   protected final void assertEqualsVerbose(Object JavaDoc one, Object JavaDoc two, boolean showObjects) {
365     assertEqualsVerbose(null, one, two, StandardStringifier.INSTANCE, showObjects);
366   }
367
368   protected final void assertEqualsVerbose(String JavaDoc message, Object JavaDoc one, Object JavaDoc two) {
369     assertEqualsVerbose(message, one, two, StandardStringifier.INSTANCE, false);
370   }
371
372   protected final void assertEqualsVerbose(String JavaDoc message, Object JavaDoc one, Object JavaDoc two, Stringifier stringifier) {
373     assertEqualsVerbose(message, one, two, stringifier, false);
374   }
375
376   protected final void assertEqualsVerbose(String JavaDoc message, Object JavaDoc one, Object JavaDoc two, boolean showObjects) {
377     assertEqualsVerbose(message, one, two, StandardStringifier.INSTANCE, showObjects);
378   }
379
380   protected final void assertContainsIgnoreCase(String JavaDoc expected, String JavaDoc actual) {
381     assertContainsIgnoreCase(null, expected, actual);
382   }
383
384   protected final void assertContainsIgnoreCase(String JavaDoc message, String JavaDoc expected, String JavaDoc actual) {
385     assertContains(message, expected != null ? expected.toLowerCase() : null, actual != null ? actual.toLowerCase()
386         : null);
387   }
388
389   protected final void assertContains(String JavaDoc expected, String JavaDoc actual) {
390     assertContains(null, expected, actual);
391   }
392
393   protected final void assertContains(String JavaDoc message, String JavaDoc expected, String JavaDoc actual) {
394     if ((expected == null) != (actual == null)) {
395       message = (message == null ? "" : message + ": ");
396       fail(message + "Expected was " + (expected == null ? "<null>" : "'" + expected + "'") + ", but actual was "
397           + (actual == null ? "<null>" : "'" + actual + "'"));
398     }
399
400     if (expected != null) {
401       if (actual.indexOf(expected) < 0) {
402         message = (message == null ? "" : message + ": ");
403         fail(message + "Actual string '" + actual + "' does not contain expected string '" + expected + "'");
404       }
405     }
406   }
407
408   protected final void assertEqualsVerbose(String JavaDoc message, Object JavaDoc one, Object JavaDoc two, Stringifier stringifier,
409                                            boolean showObjects) {
410     if (one != null && two != null && (one instanceof Differenceable) && (two instanceof Differenceable)
411         && (one.getClass().equals(two.getClass())) && (!one.equals(two))) {
412       Difference[] differences = DifferenceBuilder.getDifferencesAsArray((Differenceable) one, (Differenceable) two);
413       Assert.eval(differences.length > 0); // since we know they're not equal
414

415       StringBuffer JavaDoc descrip = new StringBuffer JavaDoc();
416       descrip.append((message != null ? (message + ": ") : "") + "objects not equal");
417       descrip.append(DifferenceBuilder.describeDifferences((Differenceable) one, (Differenceable) two));
418
419       if (showObjects) {
420         descrip.append("\nexpected:\n");
421         descrip.append(one.toString());
422         descrip.append("\nbut was:\n");
423         descrip.append(two.toString());
424         descrip.append("\n");
425       }
426
427       throw new AssertionFailedError(descrip.toString());
428     } else {
429       assertEquals(one, two);
430     }
431   }
432
433   protected final void fail(Throwable JavaDoc t) {
434     fail("FAILURE", t);
435   }
436
437   protected final void fail(String JavaDoc message, Throwable JavaDoc t) {
438     fail((message == null ? "" : (message + "\n")) + "Exception:\n" + ExceptionUtils.getFullStackTrace(t));
439   }
440
441   private Date JavaDoc parseDate(String JavaDoc date) {
442     try {
443       return DATE_FORMAT.parse(date);
444     } catch (ParseException JavaDoc e) {
445       // throwing runtime exception should cause each test case to fail
446
// (provided you're disabling from the constructor
447
// as directed)
448
throw new TCRuntimeException(e);
449     }
450   }
451
452   private boolean isAllDisabled() {
453     return this.allDisabledUntil != null && new Date JavaDoc().before(this.allDisabledUntil);
454   }
455
456   private boolean isTestDisabled(String JavaDoc testMethod) {
457     Date JavaDoc until = (Date JavaDoc) disabledUntil.get(testMethod);
458     return until != null && new Date JavaDoc().before(until);
459   }
460
461   protected void checkComparator(Object JavaDoc smaller, Object JavaDoc bigger, Object JavaDoc equalToBigger, Comparator c) {
462     // test null's
463
assertTrue(c.compare(null, bigger) < 0);
464     assertTrue(c.compare(bigger, null) > 0);
465     assertTrue(c.compare(null, null) == 0);
466
467     // test less-than
468
assertTrue(c.compare(smaller, bigger) < 0);
469
470     // test greater-than
471
assertTrue(c.compare(bigger, smaller) > 0);
472
473     // test equal
474
assertTrue(c.compare(bigger, equalToBigger) == 0);
475     assertTrue(c.compare(equalToBigger, bigger) == 0);
476   }
477
478   protected void assertNotEquals(int i1, int i2) {
479     assertFalse("Values are equal: " + i1, i1 == i2);
480   }
481
482   protected void assertEquals(byte[] b1, byte[] b2) {
483     boolean rv = (b1 == null) ? b2 == null : Arrays.equals(b1, b2);
484     assertTrue("Values are not equals", rv);
485   }
486
487   protected void assertNotEquals(Object JavaDoc o1, Object JavaDoc o2) {
488     assertFalse("Values are equal: " + o1 + ", " + o2, o1 == o2);
489     if (o1 != null && o2 != null) {
490       assertFalse("Values are equal: " + o1 + ", " + o2, o1.equals(o2));
491       assertFalse("Values are equal: " + o1 + ", " + o2, o2.equals(o1));
492     }
493   }
494
495   protected void assertSerializable(Object JavaDoc obj) {
496     assertSerializable(obj, true, true);
497   }
498
499   protected void assertSerializable(Object JavaDoc obj, boolean checkEquals, boolean checkHashCode) {
500     assertNotNull(obj);
501     ByteArrayOutputStream JavaDoc baos = new ByteArrayOutputStream JavaDoc();
502     ObjectOutputStream JavaDoc oos;
503     Object JavaDoc deserializedObj = null;
504     try {
505       oos = new ObjectOutputStream JavaDoc(baos);
506       oos.writeObject(obj);
507       oos.close();
508       ObjectInputStream JavaDoc ois = new ObjectInputStream JavaDoc(new ByteArrayInputStream JavaDoc(baos.toByteArray()));
509       deserializedObj = ois.readObject();
510     } catch (IOException JavaDoc ioe) {
511       throw Assert.failure("Object failed to serialize", ioe);
512     } catch (ClassNotFoundException JavaDoc cnfe) {
513       throw Assert.failure("Object failed to serialize", cnfe);
514     }
515     assertNotNull(obj);
516     if (checkEquals) {
517       assertEquals("Object and [de]serialized object failed equals() comparison", obj, deserializedObj);
518     }
519     if (checkHashCode) {
520       assertEquals("Object and [de]serialized object failed hashCode() comparison", obj.hashCode(), deserializedObj
521           .hashCode());
522     }
523   }
524
525   protected synchronized void assertTimeDirection() {
526     long currentMillis = System.currentTimeMillis();
527     assertTrue("System Clock Moved Backwards! [current=" + currentMillis + ", previous=" + previousSystemMillis + "]",
528         currentMillis >= previousSystemMillis);
529     previousSystemMillis = currentMillis;
530   }
531
532   private void doThreadDump() {
533     ThreadDump.dumpThreadsMany(numThreadDumps, dumpInterval);
534   }
535
536   /**
537    * Returns the timeout value
538    */

539   public int getTimeoutValueInSeconds() {
540     try {
541       return TestConfigObject.getInstance().getJunitTimeoutInSeconds();
542     } catch (IOException JavaDoc e) {
543       throw new RuntimeException JavaDoc(e);
544     }
545   }
546 }
547
Popular Tags