1 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 ; 27 import java.io.ByteArrayOutputStream ; 28 import java.io.File ; 29 import java.io.IOException ; 30 import java.io.ObjectInputStream ; 31 import java.io.ObjectOutputStream ; 32 import java.text.DateFormat ; 33 import java.text.ParseException ; 34 import java.text.SimpleDateFormat ; 35 import java.util.Arrays ; 36 import java.util.Comparator ; 37 import java.util.Date ; 38 import java.util.Hashtable ; 39 import java.util.List ; 40 import java.util.Map ; 41 import java.util.Timer ; 42 import java.util.TimerTask ; 43 44 import junit.framework.AssertionFailedError; 45 import junit.framework.TestCase; 46 47 50 public class TCTestCase extends TestCase { 51 52 private static final long DEFAULT_TIMEOUT_THRESHOLD = 60000; 53 private static final DateFormat DATE_FORMAT = new SimpleDateFormat ("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 allDisabledUntil; 61 private final Map disabledUntil = new Hashtable (); 62 63 private static final Timer timeoutTimer = new TCTimerImpl("Timeout Thread", true); 67 private static final SynchronizedBoolean timeoutTaskAdded = new SynchronizedBoolean(false); 68 69 private long timeoutThreshold = DEFAULT_TIMEOUT_THRESHOLD; 71 72 private boolean dumpThreadsOnTimeout = true; 74 private int numThreadDumps = 3; 75 private long dumpInterval = 500; 76 77 private long previousSystemMillis = 0; 79 80 public TCTestCase() { 81 super(); 82 83 TCLogging.disableLocking(); 84 } 85 86 public TCTestCase(String arg0) { 87 super(arg0); 88 89 TCLogging.disableLocking(); 90 } 91 92 private void timeoutCallback() { 94 String bar = "***************************************"; 95 System.err.println("\n" + bar + "\n+ TCTestCase timeout alarm going off at " + new Date () + "\n" + bar + "\n"); 96 System.err.flush(); 97 98 doDumpServerDetails(); 99 if (dumpThreadsOnTimeout) { 100 try { 101 doThreadDump(); 102 } catch (Throwable t) { 103 t.printStackTrace(); 105 } 106 } 107 108 try { 109 beforeTimeout(); 110 } catch (Throwable t) { 111 this.beforeTimeoutException.set(t); 112 } 113 } 114 115 protected void doDumpServerDetails() { 116 } 118 119 protected void beforeTimeout() throws Throwable { 121 if (false) throw new AssertionError (); } 123 124 public void runBare() throws Throwable { 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 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 if (timeoutTaskAdded.commit(false, true)) { 144 scheduleTimeoutTask(); 145 } 146 147 Throwable testException = null; 148 try { 149 super.runBare(); 150 } catch (Throwable t) { 151 testException = t; 152 } 153 154 Throwable exceptionInTimeoutCallback = (Throwable ) beforeTimeoutException.get(); 155 156 if (testException != null) { 159 if (exceptionInTimeoutCallback != null) { 160 exceptionInTimeoutCallback.printStackTrace(); 161 } 162 throw testException; 163 } 164 165 if (exceptionInTimeoutCallback != null) { throw exceptionInTimeoutCallback; } 166 167 return; 169 } 170 171 private void scheduleTimeoutTask() throws IOException { 172 final int MINIMUM = 30; 174 long junitTimeout = this.getTimeoutValueInSeconds(); 175 176 if (junitTimeout < MINIMUM) { throw new IllegalArgumentException ("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 () { 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 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 ioe) { 234 throw new TCRuntimeException(ioe.getLocalizedMessage(), ioe); 235 } 236 } 237 238 return dataDirectoryHelper; 239 } 240 241 protected final File getDataDirectory() throws IOException { 242 return getDataDirectoryHelper().getDirectory(); 243 } 244 245 protected final File getDataFile(String fileName) throws IOException { 246 return getDataDirectoryHelper().getFile(fileName); 247 } 248 249 protected final File getTempDirectory() throws IOException { 250 return getTempDirectoryHelper().getDirectory(); 251 } 252 253 protected final File getTempFile(String fileName) throws IOException { 254 return getTempDirectoryHelper().getFile(fileName); 255 } 256 257 260 protected final void disableAllUntil(Date theDate) { 261 Assert.eval(theDate != null); 262 this.allDisabledUntil = theDate; 263 } 264 265 268 protected final void disableAllUntil(String theDate) { 269 disableAllUntil(parseDate(theDate)); 270 } 271 272 276 protected final void disableAllUntil(String theDate, String [] platforms) { 277 List platform_list = Arrays.asList(platforms); 278 try { 279 String platform = TestConfigObject.getInstance().platform(); 280 if (platform_list.contains(platform)) { 281 disableAllUntil(parseDate(theDate)); 282 } 283 } catch (IOException e) { 284 e.printStackTrace(); 285 } 286 } 287 288 292 protected final void disableTestUntil(String method, String date) { 293 this.disabledUntil.put(method, parseDate(date)); 294 } 295 296 300 protected final void disableTestUntil(String method, String date, String [] platforms) { 301 List platform_list = Arrays.asList(platforms); 302 try { 303 String platform = TestConfigObject.getInstance().platform(); 304 if (platform_list.contains(platform)) { 305 this.disabledUntil.put(method, parseDate(date)); 306 } 307 } catch (IOException e) { 308 e.printStackTrace(); 309 } 310 } 311 312 316 protected final void disableTestUntil(String method, Date date) { 317 this.disabledUntil.put(method, date); 318 } 319 320 protected final void assertSameOrdered(Object one, Object two) { 321 assertEqualsOrdered(one, two, SameObjectEqualityComparator.INSTANCE); 322 } 323 324 protected final void assertEqualsOrdered(Object one, Object two) { 325 CollectionAssert.assertEqualOrdered(one, two); 326 } 327 328 protected final void assertEqualsOrdered(Object one, Object two, EqualityComparator comparator) { 329 CollectionAssert.assertEqualOrdered(one, two, comparator); 330 } 331 332 protected final void assertSameUnordered(Object one, Object two) { 333 assertEqualsUnordered(one, two, SameObjectEqualityComparator.INSTANCE); 334 } 335 336 protected final void assertEqualsUnordered(Object one, Object two) { 337 CollectionAssert.assertEqualUnordered(one, two); 338 } 339 340 protected final void assertEqualsUnordered(Object one, Object two, EqualityComparator comparator) { 341 CollectionAssert.assertEqualUnordered(one, two, comparator); 342 } 343 344 protected final void assertSameUnorderedUncounted(Object one, Object two) { 345 assertEqualsUnorderedUncounted(one, two, SameObjectEqualityComparator.INSTANCE); 346 } 347 348 protected final void assertEqualsUnorderedUncounted(Object one, Object two) { 349 CollectionAssert.assertEqualUnorderedUncounted(one, two); 350 } 351 352 protected final void assertEqualsUnorderedUncounted(Object one, Object two, EqualityComparator comparator) { 353 CollectionAssert.assertEqualUnorderedUncounted(one, two, comparator); 354 } 355 356 protected final void assertEqualsVerbose(Object one, Object two) { 357 assertEqualsVerbose(null, one, two, StandardStringifier.INSTANCE, false); 358 } 359 360 protected final void assertEqualsVerbose(Object one, Object two, Stringifier stringifier) { 361 assertEqualsVerbose(null, one, two, stringifier, false); 362 } 363 364 protected final void assertEqualsVerbose(Object one, Object two, boolean showObjects) { 365 assertEqualsVerbose(null, one, two, StandardStringifier.INSTANCE, showObjects); 366 } 367 368 protected final void assertEqualsVerbose(String message, Object one, Object two) { 369 assertEqualsVerbose(message, one, two, StandardStringifier.INSTANCE, false); 370 } 371 372 protected final void assertEqualsVerbose(String message, Object one, Object two, Stringifier stringifier) { 373 assertEqualsVerbose(message, one, two, stringifier, false); 374 } 375 376 protected final void assertEqualsVerbose(String message, Object one, Object two, boolean showObjects) { 377 assertEqualsVerbose(message, one, two, StandardStringifier.INSTANCE, showObjects); 378 } 379 380 protected final void assertContainsIgnoreCase(String expected, String actual) { 381 assertContainsIgnoreCase(null, expected, actual); 382 } 383 384 protected final void assertContainsIgnoreCase(String message, String expected, String actual) { 385 assertContains(message, expected != null ? expected.toLowerCase() : null, actual != null ? actual.toLowerCase() 386 : null); 387 } 388 389 protected final void assertContains(String expected, String actual) { 390 assertContains(null, expected, actual); 391 } 392 393 protected final void assertContains(String message, String expected, String 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 message, Object one, Object 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); 415 StringBuffer descrip = new StringBuffer (); 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 t) { 434 fail("FAILURE", t); 435 } 436 437 protected final void fail(String message, Throwable t) { 438 fail((message == null ? "" : (message + "\n")) + "Exception:\n" + ExceptionUtils.getFullStackTrace(t)); 439 } 440 441 private Date parseDate(String date) { 442 try { 443 return DATE_FORMAT.parse(date); 444 } catch (ParseException e) { 445 throw new TCRuntimeException(e); 449 } 450 } 451 452 private boolean isAllDisabled() { 453 return this.allDisabledUntil != null && new Date ().before(this.allDisabledUntil); 454 } 455 456 private boolean isTestDisabled(String testMethod) { 457 Date until = (Date ) disabledUntil.get(testMethod); 458 return until != null && new Date ().before(until); 459 } 460 461 protected void checkComparator(Object smaller, Object bigger, Object equalToBigger, Comparator c) { 462 assertTrue(c.compare(null, bigger) < 0); 464 assertTrue(c.compare(bigger, null) > 0); 465 assertTrue(c.compare(null, null) == 0); 466 467 assertTrue(c.compare(smaller, bigger) < 0); 469 470 assertTrue(c.compare(bigger, smaller) > 0); 472 473 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 o1, Object 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 obj) { 496 assertSerializable(obj, true, true); 497 } 498 499 protected void assertSerializable(Object obj, boolean checkEquals, boolean checkHashCode) { 500 assertNotNull(obj); 501 ByteArrayOutputStream baos = new ByteArrayOutputStream (); 502 ObjectOutputStream oos; 503 Object deserializedObj = null; 504 try { 505 oos = new ObjectOutputStream (baos); 506 oos.writeObject(obj); 507 oos.close(); 508 ObjectInputStream ois = new ObjectInputStream (new ByteArrayInputStream (baos.toByteArray())); 509 deserializedObj = ois.readObject(); 510 } catch (IOException ioe) { 511 throw Assert.failure("Object failed to serialize", ioe); 512 } catch (ClassNotFoundException 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 539 public int getTimeoutValueInSeconds() { 540 try { 541 return TestConfigObject.getInstance().getJunitTimeoutInSeconds(); 542 } catch (IOException e) { 543 throw new RuntimeException (e); 544 } 545 } 546 } 547 | Popular Tags |