smrunner: dependency on ruby module removed
[fedora-idea.git] / platform / testFramework / src / com / intellij / testFramework / UsefulTestCase.java
blob5591659087a810706ea3fe908a1cd484a388fe50
1 /*
2 * Copyright (c) 2000-2006 JetBrains s.r.o. All Rights Reserved.
3 */
4 package com.intellij.testFramework;
6 import com.intellij.codeInsight.CodeInsightSettings;
7 import com.intellij.openapi.Disposable;
8 import com.intellij.openapi.application.ApplicationManager;
9 import com.intellij.openapi.command.CommandProcessor;
10 import com.intellij.openapi.fileTypes.StdFileTypes;
11 import com.intellij.openapi.project.Project;
12 import com.intellij.openapi.util.Disposer;
13 import com.intellij.openapi.util.JDOMExternalizable;
14 import com.intellij.openapi.util.JDOMUtil;
15 import com.intellij.openapi.util.Key;
16 import com.intellij.openapi.util.io.FileUtil;
17 import com.intellij.openapi.util.text.StringUtil;
18 import com.intellij.psi.PsiDocumentManager;
19 import com.intellij.psi.codeStyle.CodeStyleSettings;
20 import com.intellij.psi.codeStyle.CodeStyleSettingsManager;
21 import com.intellij.psi.impl.source.PostprocessReformattingAspect;
22 import com.intellij.util.Consumer;
23 import com.intellij.util.Function;
24 import com.intellij.util.containers.ContainerUtil;
25 import com.intellij.refactoring.rename.inplace.VariableInplaceRenamer;
26 import com.intellij.testFramework.exceptionCases.AbstractExceptionCase;
27 import gnu.trove.THashSet;
28 import junit.framework.Assert;
29 import junit.framework.AssertionFailedError;
30 import junit.framework.TestCase;
31 import org.jdom.Element;
32 import org.jetbrains.annotations.NonNls;
33 import org.jetbrains.annotations.Nullable;
35 import java.io.FileReader;
36 import java.io.IOException;
37 import java.lang.reflect.Field;
38 import java.lang.reflect.Method;
39 import java.lang.reflect.Modifier;
40 import java.util.*;
42 /**
43 * @author peter
45 public abstract class UsefulTestCase extends TestCase {
46 protected final Disposable myTestRootDisposable = new Disposable() {
47 public void dispose() {
50 private static final String DEFAULT_SETTINGS_EXTERNALIZED;
51 private static CodeStyleSettings myOldCodeStyleSettings;
53 protected static final Key<String> CREATION_PLACE = Key.create("CREATION_PLACE");
55 static {
56 try {
57 CodeInsightSettings defaultSettings = new CodeInsightSettings();
58 Element oldS = new Element("temp");
59 defaultSettings.writeExternal(oldS);
60 DEFAULT_SETTINGS_EXTERNALIZED = JDOMUtil.writeElement(oldS, "\n");
62 catch (Exception e) {
63 throw new RuntimeException(e);
67 protected void tearDown() throws Exception {
68 Disposer.dispose(myTestRootDisposable);
69 cleanupSwingDataStructures();
70 super.tearDown();
73 private static void cleanupSwingDataStructures() throws Exception {
74 Class<?> aClass = Class.forName("javax.swing.KeyboardManager");
76 Method get = aClass.getMethod("getCurrentManager");
77 get.setAccessible(true);
78 Object manager = get.invoke(null);
80 Field mapF = aClass.getDeclaredField("componentKeyStrokeMap");
81 mapF.setAccessible(true);
82 Object map = mapF.get(manager);
83 ((Map)map).clear();
86 Field mapF = aClass.getDeclaredField("containerMap");
87 mapF.setAccessible(true);
88 Object map = mapF.get(manager);
89 ((Map)map).clear();
92 //Constructor<?> ctr = aClass.getDeclaredConstructor();
93 //ctr.setAccessible(true);
94 //Object newManager = ctr.newInstance();
95 //Method setter = aClass.getDeclaredMethod("setCurrentManager", aClass);
96 //setter.setAccessible(true);
97 //setter.invoke(null, newManager);
100 protected void checkForSettingsDamage() throws Exception {
101 if (isPerformanceTest() || ApplicationManager.getApplication() == null) {
102 return;
104 final CodeInsightSettings settings = CodeInsightSettings.getInstance();
105 Element newS = new Element("temp");
106 settings.writeExternal(newS);
107 Assert.assertEquals("Code insight settings damaged", DEFAULT_SETTINGS_EXTERNALIZED, JDOMUtil.writeElement(newS, "\n"));
110 CodeStyleSettings codeStyleSettings = getCurrentCodeStyleSettings();
111 codeStyleSettings.getIndentOptions(StdFileTypes.JAVA);
112 checkSettingsEqual(myOldCodeStyleSettings, codeStyleSettings, "Code style settings damaged");
113 codeStyleSettings.clearCodeStyleSettings();
114 myOldCodeStyleSettings = null;
116 VariableInplaceRenamer.checkCleared();
119 protected void storeSettings() {
120 if (!isPerformanceTest() && ApplicationManager.getApplication() != null) {
121 myOldCodeStyleSettings = getCurrentCodeStyleSettings().clone();
122 myOldCodeStyleSettings.getIndentOptions(StdFileTypes.JAVA);
126 protected CodeStyleSettings getCurrentCodeStyleSettings() {
127 return CodeStyleSettingsManager.getInstance().getCurrentSettings();
130 protected Disposable getTestRootDisposable() {
131 return myTestRootDisposable;
134 @NonNls
135 public static String toString(Collection<?> collection) {
136 if (collection.isEmpty()) {
137 return "<empty>";
140 final StringBuilder builder = new StringBuilder();
141 for (final Object o : collection) {
142 if (o instanceof THashSet) {
143 builder.append(new TreeSet<Object>((Collection<Object>)o));
145 else {
146 builder.append(o);
148 builder.append("\n");
150 return builder.toString();
153 public static <T> void assertOrderedEquals(T[] actual, T... expected) {
154 assertOrderedEquals(Arrays.asList(actual), expected);
157 public static <T> void assertOrderedEquals(Collection<T> actual, T... expected) {
158 assertOrderedEquals(null, actual, expected);
161 public static <T> void assertOrderedEquals(final String errorMsg, Collection<T> actual, T... expected) {
162 Assert.assertNotNull(actual);
163 Assert.assertNotNull(expected);
164 assertOrderedEquals(errorMsg, actual, Arrays.asList(expected));
167 public static <T> void assertOrderedEquals(final Collection<? extends T> actual, final Collection<? extends T> expected) {
168 assertOrderedEquals(null, actual, expected);
171 public static <T> void assertOrderedEquals(final String erroMsg, final Collection<? extends T> actual, final Collection<? extends T> expected) {
172 if (!new ArrayList<T>(actual).equals(new ArrayList<T>(expected))) {
173 Assert.assertEquals(erroMsg, toString(expected), toString(actual));
174 Assert.fail();
178 public static <T> void assertOrderedCollection(T[] collection, Consumer<T>... checkers) {
179 Assert.assertNotNull(collection);
180 assertOrderedCollection(Arrays.asList(collection), checkers);
183 public static <T> void assertSameElements(T[] collection, T... expected) {
184 assertSameElements(Arrays.asList(collection), expected);
187 public static <T> void assertSameElements(Collection<? extends T> collection, T... expected) {
188 assertSameElements(collection, Arrays.asList(expected));
190 public static <T> void assertSameElements(Collection<? extends T> collection, Collection<T> expected) {
191 if (collection.size() != expected.size() || !new HashSet<T>(expected).equals(new HashSet<T>(collection))) {
192 Assert.assertEquals(toString(expected, "\n"), toString(collection, "\n"));
193 Assert.assertEquals(new HashSet<T>(expected), new HashSet<T>(collection));
197 public static String toString(Object[] collection, String separator) {
198 return toString(Arrays.asList(collection), separator);
201 public static String toString(Collection<?> collection, String separator) {
202 List<String> list = ContainerUtil.map2List(collection, new Function<Object,String>() {
203 public String fun(final Object o) {
204 return String.valueOf(o);
207 Collections.sort(list);
208 StringBuilder builder = new StringBuilder();
209 boolean flag = false;
210 for (final String o : list) {
211 if (flag) {
212 builder.append(separator);
214 builder.append(o);
215 flag = true;
217 return builder.toString();
220 public static <T> void assertOrderedCollection(Collection<? extends T> collection, Consumer<T>... checkers) {
221 Assert.assertNotNull(collection);
222 if (collection.size() != checkers.length) {
223 Assert.fail(toString(collection));
225 int i = 0;
226 for (final T actual : collection) {
227 try {
228 checkers[i].consume(actual);
230 catch (AssertionFailedError e) {
231 System.out.println(i + ": " + actual);
232 throw e;
234 i++;
238 public static <T> void assertUnorderedCollection(T[] collection, Consumer<T>... checkers) {
239 assertUnorderedCollection(Arrays.asList(collection), checkers);
242 public static <T> void assertUnorderedCollection(Collection<? extends T> collection, Consumer<T>... checkers) {
243 Assert.assertNotNull(collection);
244 if (collection.size() != checkers.length) {
245 Assert.fail(toString(collection));
247 Set<Consumer<T>> checkerSet = new HashSet<Consumer<T>>(Arrays.asList(checkers));
248 int i = 0;
249 Throwable lastError = null;
250 for (final T actual : collection) {
251 boolean flag = true;
252 for (final Consumer<T> condition : checkerSet) {
253 Throwable error = accepts(condition, actual);
254 if (error == null) {
255 checkerSet.remove(condition);
256 flag = false;
257 break;
259 else {
260 lastError = error;
263 if (flag) {
264 lastError.printStackTrace();
265 Assert.fail("Incorrect element(" + i + "): " + actual);
267 i++;
271 private static <T> Throwable accepts(final Consumer<T> condition, final T actual) {
272 try {
273 condition.consume(actual);
274 return null;
276 catch (Throwable e) {
277 return e;
281 public static <T> T assertInstanceOf(Object o, Class<T> aClass) {
282 Assert.assertNotNull(o);
283 Assert.assertTrue(o.getClass().getName(), aClass.isInstance(o));
284 return (T)o;
287 public static <T> T assertOneElement(Collection<T> collection) {
288 Assert.assertNotNull(collection);
289 Assert.assertEquals(toString(collection), 1, collection.size());
290 return collection.iterator().next();
293 public static <T> T assertOneElement(T[] ts) {
294 Assert.assertNotNull(ts);
295 Assert.assertEquals(1, ts.length);
296 return ts[0];
299 public static void printThreadDump() {
300 final Map<Thread,StackTraceElement[]> traces = Thread.getAllStackTraces();
301 for (final Map.Entry<Thread, StackTraceElement[]> entry : traces.entrySet()) {
302 System.out.println("\n" + entry.getKey().getName() + "\n");
303 final StackTraceElement[] value = entry.getValue();
304 for (final StackTraceElement stackTraceElement : value) {
305 System.out.println(" at "+stackTraceElement);
310 public static void assertEmpty(final Object[] array) {
311 assertOrderedEquals(array);
314 public static void assertEmpty(final Collection<?> collection) {
315 assertEmpty(null, collection);
318 public static void assertEmpty(final String errorMsg, final Collection<?> collection) {
319 assertOrderedEquals(errorMsg, collection);
322 protected <T extends Disposable> T disposeOnTearDown(final T disposable) {
323 Disposer.register(myTestRootDisposable, disposable);
324 return disposable;
327 public static void assertSameLines(String expected, String actual) {
328 String expectedText = StringUtil.convertLineSeparators(expected.trim());
329 String actualText = StringUtil.convertLineSeparators(actual.trim());
330 Assert.assertEquals(expectedText, actualText);
333 protected String getTestName(boolean lowercaseFirstLetter) {
334 String name = getName();
335 name = StringUtil.trimStart(name, "test");
336 if (StringUtil.isEmpty(name)) {
337 return "";
339 if (lowercaseFirstLetter) {
340 name = Character.toLowerCase(name.charAt(0)) + name.substring(1);
342 return name;
345 protected String getTestDirectoryName() {
346 final String testName = getTestName(true);
347 return testName.replaceAll("_.*", "");
350 protected static void assertSameLinesWithFile(final String filePath, final String actualText) {
351 String fileText;
352 try {
353 final FileReader reader = new FileReader(filePath);
354 fileText = FileUtil.loadTextAndClose(reader);
356 catch (IOException e) {
357 throw new RuntimeException(e);
359 assertSameLines(fileText, actualText);
362 public static void clearFields(final Object test) throws IllegalAccessException {
363 Class aClass = test.getClass();
364 while (aClass != null) {
365 clearDeclaredFields(test, aClass);
366 aClass = aClass.getSuperclass();
370 public static void clearDeclaredFields(Object test, Class aClass) throws IllegalAccessException {
371 if (aClass == null) return;
372 for (final Field field : aClass.getDeclaredFields()) {
373 @NonNls final String name = field.getDeclaringClass().getName();
374 if (!name.startsWith("junit.framework.") && !name.startsWith("com.intellij.testFramework.")) {
375 final int modifiers = field.getModifiers();
376 if ((modifiers & Modifier.FINAL) == 0 && (modifiers & Modifier.STATIC) == 0 && !field.getType().isPrimitive()) {
377 field.setAccessible(true);
378 field.set(test, null);
384 protected static void checkSettingsEqual(JDOMExternalizable expected, JDOMExternalizable settings, String message) throws Exception {
385 if (expected == null) {
386 return;
388 if (settings == null) {
389 return;
391 Element oldS = new Element("temp");
392 expected.writeExternal(oldS);
393 Element newS = new Element("temp");
394 settings.writeExternal(newS);
396 String newString = JDOMUtil.writeElement(newS, "\n");
397 String oldString = JDOMUtil.writeElement(oldS, "\n");
398 Assert.assertEquals(message, oldString, newString);
401 public boolean isPerformanceTest() {
402 String name = getName();
403 return name != null && name.contains("Performance") || getClass().getName().contains("Performance");
406 public static void doPostponedFormatting(final Project project) {
407 try {
408 CommandProcessor.getInstance().runUndoTransparentAction(new Runnable() {
409 public void run() {
410 ApplicationManager.getApplication().runWriteAction(new Runnable() {
411 public void run() {
412 PsiDocumentManager.getInstance(project).commitAllDocuments();
413 PostprocessReformattingAspect.getInstance(project).doPostponedFormatting();
419 catch (Throwable e) {
420 // Way to go...
424 protected static void checkAllTimersAreDisposed() throws Exception {
425 Class<?> aClass = Class.forName("javax.swing.TimerQueue");
427 Method inst = aClass.getDeclaredMethod("sharedInstance");
428 inst.setAccessible(true);
429 Object queue = inst.invoke(null);
430 Field field = aClass.getDeclaredField("firstTimer");
431 field.setAccessible(true);
432 Object firstTimer = field.get(queue);
433 if (firstTimer != null) {
434 try {
435 fail("Not disposed Timer: "+firstTimer.toString()+"; queue:"+queue);
437 finally {
438 field.set(queue, null);
444 * Checks that code block throw corresponding exception.
445 * @param exceptionCase Block annotated with some exception type
446 * @throws Throwable
448 protected void assertException(final AbstractExceptionCase exceptionCase) throws Throwable {
449 assertException(exceptionCase, null);
453 * Checks that code block throw corresponding exception with expected error msg.
454 * If expected error message is null it will not be checked.
455 * @param exceptionCase Block annotated with some exception type
456 * @param expectedErrorMsg expected error messge
457 * @throws Throwable
459 protected void assertException(final AbstractExceptionCase exceptionCase,
460 @Nullable final String expectedErrorMsg) throws Throwable {
461 assertExceptionOccurred(true, exceptionCase, expectedErrorMsg);
465 * Checks that code block doesn't throw corresponding exception.
466 * @param exceptionCase Block annotated with some exception type
467 * @throws Throwable
469 protected void assertNoException(final AbstractExceptionCase exceptionCase) throws Throwable {
470 assertExceptionOccurred(false, exceptionCase, null);
473 protected void assertNoThrowable(final Runnable closure) {
474 String throwableName = null;
475 try{
476 closure.run();
477 } catch (Throwable thr) {
478 throwableName = thr.getClass().getName();
480 assertNull(throwableName);
483 private void assertExceptionOccurred(boolean shouldOccur,
484 AbstractExceptionCase exceptionCase,
485 String expectedErrorMsg) throws Throwable {
486 boolean wasThrown = false;
487 try {
488 exceptionCase.tryClosure();
489 } catch (Throwable e) {
490 if (shouldOccur) {
491 wasThrown = true;
492 final String errorMessage = exceptionCase.getAssertionErrorMessage();
493 assertEquals(errorMessage, exceptionCase.getExpectedExceptionClass(), e.getClass());
494 if (expectedErrorMsg != null) {
495 assertEquals("Compare error messages", expectedErrorMsg, e.getMessage());
497 } else if (exceptionCase.getExpectedExceptionClass().equals(e.getClass())) {
498 wasThrown = true;
500 System.out.println("");
501 e.printStackTrace(System.out);
503 fail("Exception isn't expected here. Exception message: " + e.getMessage());
504 } else {
505 throw e;
507 } finally {
508 if (shouldOccur && !wasThrown) {
509 fail(exceptionCase.getAssertionErrorMessage());