attempt as many tearDown activities as possible despite exceptions appcode/171.557 clion/171.556
authorpeter <peter@jetbrains.com>
Sat, 29 Oct 2016 08:51:24 +0000 (10:51 +0200)
committerpeter <peter@jetbrains.com>
Sat, 29 Oct 2016 08:51:24 +0000 (10:51 +0200)
platform/testFramework/src/com/intellij/testFramework/LightPlatformTestCase.java
platform/testFramework/src/com/intellij/testFramework/PlatformTestCase.java
platform/testFramework/src/com/intellij/testFramework/UsefulTestCase.java
platform/testFramework/src/com/intellij/testFramework/fixtures/impl/HeavyIdeaTestFixtureImpl.java
platform/testFramework/src/com/intellij/testFramework/fixtures/impl/LightIdeaTestFixtureImpl.java
platform/util/src/com/intellij/util/lang/CompoundRuntimeException.java

index acd884a43280cff728944d7615e35f451b0ad167..812d1eda30d3eeff4b7ff51475d43d879e71e1a1 100644 (file)
@@ -85,12 +85,15 @@ import com.intellij.psi.impl.PsiDocumentManagerImpl;
 import com.intellij.psi.impl.PsiManagerImpl;
 import com.intellij.psi.impl.source.tree.injected.InjectedLanguageManagerImpl;
 import com.intellij.psi.templateLanguages.TemplateDataLanguageMappings;
-import com.intellij.util.*;
+import com.intellij.util.GCUtil;
+import com.intellij.util.IncorrectOperationException;
+import com.intellij.util.LocalTimeCounter;
+import com.intellij.util.ReflectionUtil;
 import com.intellij.util.containers.ContainerUtil;
 import com.intellij.util.indexing.UnindexedFilesUpdater;
-import com.intellij.util.lang.CompoundRuntimeException;
 import com.intellij.util.messages.MessageBusConnection;
 import com.intellij.util.ui.UIUtil;
+import junit.framework.AssertionFailedError;
 import junit.framework.TestCase;
 import org.jetbrains.annotations.NonNls;
 import org.jetbrains.annotations.NotNull;
@@ -104,9 +107,11 @@ import java.io.IOException;
 import java.io.PrintStream;
 import java.lang.management.GarbageCollectorMXBean;
 import java.lang.management.ManagementFactory;
+import java.lang.reflect.Method;
 import java.util.Arrays;
-import java.util.List;
-import java.util.function.Consumer;
+import java.util.concurrent.DelayQueue;
+import java.util.concurrent.Delayed;
+import java.util.concurrent.TimeUnit;
 
 /**
  * @author yole
@@ -355,120 +360,103 @@ public abstract class LightPlatformTestCase extends UsefulTestCase implements Da
   @Override
   protected void tearDown() throws Exception {
     Project project = getProject();
-    List<Throwable> errors = new SmartList<>();
-    Consumer<ThrowableRunnable<?>> runSafe = c -> {
-      try {
-        c.run();
-      }
-      catch (Throwable e) {
-        errors.add(e);
-      }
-    };
-    try {
-      runSafe.accept(() -> CodeStyleSettingsManager.getInstance(project).dropTemporarySettings());
-      runSafe.accept(() -> checkForSettingsDamage(errors));
-      runSafe.accept(() -> doTearDown(project, ourApplication, true, errors));
-      runSafe.accept(super::tearDown);
-      runSafe.accept(() -> myThreadTracker.checkLeak());
-      runSafe.accept(() -> InjectedLanguageManagerImpl.checkInjectorsAreDisposed(project));
-      runSafe.accept(() -> ((VirtualFilePointerManagerImpl)VirtualFilePointerManager.getInstance()).assertPointersAreDisposed());
-    }
-    catch (Throwable e) {
-      errors.add(e);
-    }
-    finally {
-      CompoundRuntimeException.throwIfNotEmpty(errors);
-    }
-  }
-
-  public static void doTearDown(@NotNull final Project project, @NotNull IdeaTestApplication application, boolean checkForEditors, @NotNull List<Throwable> exceptions) throws Exception {
-    PsiDocumentManagerImpl documentManager;
-    try {
-      ((FileTypeManagerImpl)FileTypeManager.getInstance()).drainReDetectQueue();
-      DocumentCommitThread.getInstance().clearQueue();
-      CodeStyleSettingsManager.getInstance(project).dropTemporarySettings();
 
-      checkJavaSwingTimersAreDisposed(exceptions);
-
-      UsefulTestCase.doPostponedFormatting(project);
-
-      LookupManager lookupManager = LookupManager.getInstance(project);
-      if (lookupManager != null) {
-        lookupManager.hideActiveLookup();
-      }
-      ((StartupManagerImpl)StartupManager.getInstance(project)).prepareForNextTest();
-      if (ProjectManager.getInstance() == null) {
-        exceptions.add(new AssertionError("Application components damaged"));
-      }
-
-      ContainerUtil.addIfNotNull(exceptions, new WriteCommandAction.Simple(project) {
-        @Override
-        protected void run() throws Throwable {
-          if (ourSourceRoot != null) {
-            try {
-              final VirtualFile[] children = ourSourceRoot.getChildren();
-              for (VirtualFile child : children) {
-                child.delete(this);
-              }
-            }
-            catch (IOException e) {
-              //noinspection CallToPrintStackTrace
-              e.printStackTrace();
+    new RunAll(
+      () -> CodeStyleSettingsManager.getInstance(project).dropTemporarySettings(),
+      () -> checkForSettingsDamage(),
+      () -> doTearDown(project, ourApplication, true),
+      super::tearDown,
+      () -> myThreadTracker.checkLeak(),
+      () -> InjectedLanguageManagerImpl.checkInjectorsAreDisposed(project),
+      () -> ((VirtualFilePointerManagerImpl)VirtualFilePointerManager.getInstance()).assertPointersAreDisposed()
+    ).run();
+  }
+
+  public static void doTearDown(@NotNull final Project project, @NotNull IdeaTestApplication application, boolean checkForEditors) throws Exception {
+    new RunAll().
+      append(() -> ((FileTypeManagerImpl)FileTypeManager.getInstance()).drainReDetectQueue()).
+      append(() -> CodeStyleSettingsManager.getInstance(project).dropTemporarySettings()).
+      append(() -> checkJavaSwingTimersAreDisposed()).
+      append(() -> UsefulTestCase.doPostponedFormatting(project)).
+      append(() -> LookupManager.getInstance(project).hideActiveLookup()).
+      append(() -> ((StartupManagerImpl)StartupManager.getInstance(project)).prepareForNextTest()).
+      append(() -> { if (ProjectManager.getInstance() == null) throw new AssertionError("Application components damaged"); }).
+      append(() -> WriteCommandAction.runWriteCommandAction(project, () -> {
+        if (ourSourceRoot != null) {
+          try {
+            for (VirtualFile child : ourSourceRoot.getChildren()) {
+              child.delete(LightPlatformTestCase.class);
             }
           }
-          EncodingManager encodingManager = EncodingManager.getInstance();
-          if (encodingManager instanceof EncodingManagerImpl) ((EncodingManagerImpl)encodingManager).clearDocumentQueue();
+          catch (IOException e) {
+            //noinspection CallToPrintStackTrace
+            e.printStackTrace();
+          }
+        }
+        EncodingManager encodingManager = EncodingManager.getInstance();
+        if (encodingManager instanceof EncodingManagerImpl) ((EncodingManagerImpl)encodingManager).clearDocumentQueue();
 
-          FileDocumentManager manager = FileDocumentManager.getInstance();
+        FileDocumentManager manager = FileDocumentManager.getInstance();
 
-          ApplicationManager.getApplication().runWriteAction(EmptyRunnable.getInstance()); // Flush postponed formatting if any.
-          manager.saveAllDocuments();
-          if (manager instanceof FileDocumentManagerImpl) {
-            ((FileDocumentManagerImpl)manager).dropAllUnsavedDocuments();
+        ApplicationManager.getApplication().runWriteAction(EmptyRunnable.getInstance()); // Flush postponed formatting if any.
+        manager.saveAllDocuments();
+        if (manager instanceof FileDocumentManagerImpl) {
+          ((FileDocumentManagerImpl)manager).dropAllUnsavedDocuments();
+        }
+      })).
+      append(() -> assertFalse(PsiManager.getInstance(project).isDisposed())).
+      append(() -> {
+        if (!ourAssertionsInTestDetected) {
+          if (IdeaLogger.ourErrorsOccurred != null) {
+            throw IdeaLogger.ourErrorsOccurred;
           }
         }
-      }.execute().getThrowable());
-
-      assertFalse(PsiManager.getInstance(project).isDisposed());
-      if (!ourAssertionsInTestDetected) {
-        if (IdeaLogger.ourErrorsOccurred != null) {
-          throw IdeaLogger.ourErrorsOccurred;
+      }).
+      append(() -> clearUncommittedDocuments(project)).
+      append(() -> ((HintManagerImpl)HintManager.getInstance()).cleanup()).
+      append(() -> DocumentCommitThread.getInstance().clearQueue()).
+      append(() -> ((UndoManagerImpl)UndoManager.getGlobalInstance()).dropHistoryInTests()).
+      append(() -> ((UndoManagerImpl)UndoManager.getInstance(project)).dropHistoryInTests()).
+      append(() -> UIUtil.dispatchAllInvocationEvents()).
+      append(() -> TemplateDataLanguageMappings.getInstance(project).cleanupForNextTest()).
+      append(() -> ProjectManagerEx.getInstanceEx().closeTestProject(project)).
+      append(() -> application.setDataProvider(null)).
+      append(() -> ourTestCase = null).
+      append(() -> ((PsiManagerImpl)PsiManager.getInstance(project)).cleanupForNextTest()).
+      append(() -> CompletionProgressIndicator.cleanupForNextTest()).
+      append(() -> {
+        if (checkForEditors) {
+          checkEditorsReleased();
         }
-      }
-      documentManager = clearUncommittedDocuments(project);
-      ((HintManagerImpl)HintManager.getInstance()).cleanup();
-      DocumentCommitThread.getInstance().clearQueue();
-
-      EdtTestUtil.runInEdtAndWait(() -> {
-        ((UndoManagerImpl)UndoManager.getGlobalInstance()).dropHistoryInTests();
-        ((UndoManagerImpl)UndoManager.getInstance(project)).dropHistoryInTests();
+      }).
+      append(() -> {
+        if (ourTestCount++ % 100 == 0) {
+          // some tests are written in Groovy, and running all of them may result in some 40M of memory wasted on bean infos
+          // so let's clear the cache every now and then to ensure it doesn't grow too large
+          GCUtil.clearBeanInfoCache();
+        }
+      }).
+      run();
+  }
+  
+  private static int ourTestCount;
 
-        UIUtil.dispatchAllInvocationEvents();
-      });
+  private static void checkJavaSwingTimersAreDisposed() throws Exception {
+    Class<?> TimerQueueClass = Class.forName("javax.swing.TimerQueue");
+    Method sharedInstance = ReflectionUtil.getMethod(TimerQueueClass, "sharedInstance");
 
-      TemplateDataLanguageMappings.getInstance(project).cleanupForNextTest();
-    }
-    finally {
-      ProjectManagerEx.getInstanceEx().closeTestProject(project);
-      application.setDataProvider(null);
-      ourTestCase = null;
-      ((PsiManagerImpl)PsiManager.getInstance(project)).cleanupForNextTest();
-      CompletionProgressIndicator.cleanupForNextTest();
-    }
-
-    if (checkForEditors) {
-      checkEditorsReleased(exceptions);
-    }
-    documentManager.clearUncommittedDocuments();
-    
-    if (ourTestCount++ % 100 == 0) {
-      // some tests are written in Groovy, and running all of them may result in some 40M of memory wasted on bean infos
-      // so let's clear the cache every now and then to ensure it doesn't grow too large
-      GCUtil.clearBeanInfoCache();
+    Object timerQueue = sharedInstance.invoke(null);
+    DelayQueue delayQueue = ReflectionUtil.getField(TimerQueueClass, timerQueue, DelayQueue.class, "queue");
+    Delayed timer = delayQueue.peek();
+    if (timer != null) {
+      long delay = timer.getDelay(TimeUnit.MILLISECONDS);
+      String text = "(delayed for " + delay + "ms)";
+      Method getTimer = ReflectionUtil.getDeclaredMethod(timer.getClass(), "getTimer");
+      Timer swingTimer = (Timer)getTimer.invoke(timer);
+      text = "Timer (listeners: "+Arrays.asList(swingTimer.getActionListeners()) + ") "+text;
+      throw new AssertionFailedError("Not disposed java.swing.Timer: " + text + "; queue:" + timerQueue);
     }
   }
-  
-  private static int ourTestCount;
 
   public static PsiDocumentManagerImpl clearUncommittedDocuments(@NotNull Project project) {
     PsiDocumentManagerImpl documentManager = (PsiDocumentManagerImpl)PsiDocumentManager.getInstance(project);
@@ -482,30 +470,21 @@ public abstract class LightPlatformTestCase extends UsefulTestCase implements Da
     return documentManager;
   }
 
-  public static void checkEditorsReleased(@NotNull List<Throwable> exceptions) {
+  public static void checkEditorsReleased() {
     Editor[] allEditors = EditorFactory.getInstance().getAllEditors();
     if (allEditors.length == 0) {
       return;
     }
-
+    RunAll runAll = new RunAll();
     for (Editor editor : allEditors) {
-      try {
-        EditorFactoryImpl.throwNotReleasedError(editor);
-      }
-      catch (Throwable e) {
-        exceptions.add(e);
-      }
-      finally {
-        EditorFactory.getInstance().releaseEditor(editor);
-      }
+      runAll = runAll
+        .append(() -> EditorFactoryImpl.throwNotReleasedError(editor))
+        .append(() -> EditorFactory.getInstance().releaseEditor(editor));
     }
 
-    try {
-      ((EditorImpl)allEditors[0]).throwDisposalError("Unreleased editors: " + allEditors.length);
-    }
-    catch (Throwable e) {
-      exceptions.add(e);
-    }
+    runAll
+      .append(() -> ((EditorImpl)allEditors[0]).throwDisposalError("Unreleased editors: " + allEditors.length))
+      .run();
   }
 
   @SuppressWarnings("AssignmentToStaticFieldFromInstanceMethod")
index 328653faaf83aaccf08484df9dfd25eeffef4b79..d59d83fef025f8f7a9a483c37f3f4eebf6293abe 100644 (file)
@@ -66,11 +66,13 @@ import com.intellij.psi.codeStyle.CodeStyleSettingsManager;
 import com.intellij.psi.impl.DocumentCommitThread;
 import com.intellij.psi.impl.PsiManagerImpl;
 import com.intellij.psi.impl.source.tree.injected.InjectedLanguageManagerImpl;
-import com.intellij.util.*;
+import com.intellij.util.MemoryDumpHelper;
+import com.intellij.util.PathUtilRt;
+import com.intellij.util.PlatformUtils;
+import com.intellij.util.ThrowableRunnable;
 import com.intellij.util.indexing.FileBasedIndex;
 import com.intellij.util.indexing.FileBasedIndexImpl;
 import com.intellij.util.indexing.IndexableSetContributor;
-import com.intellij.util.lang.CompoundRuntimeException;
 import com.intellij.util.ui.UIUtil;
 import junit.framework.TestCase;
 import org.jetbrains.annotations.NonNls;
@@ -91,7 +93,6 @@ import java.net.URL;
 import java.nio.charset.Charset;
 import java.util.Collection;
 import java.util.HashSet;
-import java.util.List;
 import java.util.Set;
 
 /**
@@ -427,144 +428,88 @@ public abstract class PlatformTestCase extends UsefulTestCase implements DataPro
     }
   }
 
+  @SuppressWarnings("MethodDoesntCallSuperMethod")
   @Override
   protected void tearDown() throws Exception {
-    List<Throwable> exceptions = new SmartList<>();
     Project project = myProject;
-    if (project != null) {
-      try {
-        LightPlatformTestCase.doTearDown(project, ourApplication, false, exceptions);
-      }
-      catch (Throwable e) {
-        exceptions.add(e);
-      }
 
-      disposeProject(exceptions);
-    }
-
-    try {
-      checkForSettingsDamage(exceptions);
-    }
-    catch (Throwable e) {
-      exceptions.add(e);
-    }
-    try {
-      if (project != null) {
-        try {
-          InjectedLanguageManagerImpl.checkInjectorsAreDisposed(project);
+    new RunAll()
+      .append(() -> {
+        if (project != null) {
+          LightPlatformTestCase.doTearDown(project, ourApplication, false);
         }
-        catch (AssertionError e) {
-          exceptions.add(e);
+      })
+      .append(() -> disposeProject())
+      .append(() -> checkForSettingsDamage())
+      .append(() -> {
+        if (project != null) {
+          InjectedLanguageManagerImpl.checkInjectorsAreDisposed(project);
         }
-      }
-      try {
+      })
+      .append(() -> {
         for (final File fileToDelete : myFilesToDelete) {
           delete(fileToDelete);
         }
         LocalFileSystem.getInstance().refreshIoFiles(myFilesToDelete);
-      }
-      catch (Throwable e) {
-        exceptions.add(e);
-      }
-
-      if (!myAssertionsInTestDetected) {
-        if (IdeaLogger.ourErrorsOccurred != null) {
-          exceptions.add(IdeaLogger.ourErrorsOccurred);
+      })
+      .append(() -> {
+        if (!myAssertionsInTestDetected) {
+          if (IdeaLogger.ourErrorsOccurred != null) {
+            throw IdeaLogger.ourErrorsOccurred;
+          }
         }
-      }
-
-      try {
-        super.tearDown();
-      }
-      catch (Throwable e) {
-        exceptions.add(e);
-      }
-
-      try {
+      })
+      .append(super::tearDown)
+      .append(() -> {
         if (myEditorListenerTracker != null) {
           myEditorListenerTracker.checkListenersLeak();
         }
-      }
-      catch (AssertionError error) {
-        exceptions.add(error);
-      }
-      try {
+      })
+      .append(() -> {
         if (myThreadTracker != null) {
           myThreadTracker.checkLeak();
         }
-      }
-      catch (AssertionError error) {
-        exceptions.add(error);
-      }
-      try {
-        LightPlatformTestCase.checkEditorsReleased(exceptions);
-      }
-      catch (Throwable error) {
-        exceptions.add(error);
-      }
-    }
-    finally {
-      myProjectManager = null;
-      myProject = null;
-      myModule = null;
-      myFilesToDelete.clear();
-      myEditorListenerTracker = null;
-      myThreadTracker = null;
-      ourTestCase = null;
-
-      CompoundRuntimeException.throwIfNotEmpty(exceptions);
-    }
-  }
-
-  private void disposeProject(@NotNull List<Throwable> exceptions) {
-    try {
+      })
+      .append(() -> LightPlatformTestCase.checkEditorsReleased())
+      .append(() -> {
+        myProjectManager = null;
+        myProject = null;
+        myModule = null;
+        myFilesToDelete.clear();
+        myEditorListenerTracker = null;
+        myThreadTracker = null;
+        //noinspection AssignmentToStaticFieldFromInstanceMethod
+        ourTestCase = null;
+      })
+      .run();
+  }
+
+  private void disposeProject() {
+    new RunAll(() -> {
       DocumentCommitThread.getInstance().clearQueue();
       // sometimes SwingUtilities maybe confused about EDT at this point
       if (SwingUtilities.isEventDispatchThread()) {
         UIUtil.dispatchAllInvocationEvents();
       }
-    }
-    catch (Throwable e) {
-      exceptions.add(e);
-    }
-
-    Project project = myProject;
-    if (project == null) {
-      return;
-    }
-
-    closeAndDisposeProjectAndCheckThatNoOpenProjects(project, exceptions);
-    myProject = null;
+    }, () -> {
+      if (myProject != null) {
+        closeAndDisposeProjectAndCheckThatNoOpenProjects(myProject);
+        myProject = null;
+      }
+    }).run();
   }
 
-  public static void closeAndDisposeProjectAndCheckThatNoOpenProjects(@NotNull final Project projectToClose, @NotNull final List<Throwable> exceptions) {
-    try {
-      ProjectManagerEx projectManager = ProjectManagerEx.getInstanceEx();
-      if (projectManager instanceof ProjectManagerImpl) {
-        for (Project project : projectManager.closeTestProject(projectToClose)) {
-          exceptions.add(new IllegalStateException("Test project is not disposed: " + project + ";\n created in: " + getCreationPlace(project)));
-          try {
-            ((ProjectManagerImpl)projectManager).closeProject(project, false, true, false);
-          }
-          catch (Throwable e) {
-            exceptions.add(e);
-          }
-        }
+  public static void closeAndDisposeProjectAndCheckThatNoOpenProjects(@NotNull final Project projectToClose) {
+    RunAll runAll = new RunAll();
+    ProjectManagerEx projectManager = ProjectManagerEx.getInstanceEx();
+    if (projectManager instanceof ProjectManagerImpl) {
+      for (Project project : projectManager.closeTestProject(projectToClose)) {
+        runAll = runAll
+          .append(() -> { throw new IllegalStateException("Test project is not disposed: " + project + ";\n created in: " + getCreationPlace(project)); })
+          .append(() -> ((ProjectManagerImpl)projectManager).closeProject(project, false, true, false));
       }
     }
-    catch (Throwable e) {
-      exceptions.add(e);
-    }
-    finally {
-      ApplicationManager.getApplication().runWriteAction(() -> {
-        try {
-          Disposer.dispose(projectToClose);
-        }
-        catch (Throwable e) {
-          exceptions.add(e);
-        }
-      });
-    }
+    runAll.append(() -> WriteAction.run(() -> Disposer.dispose(projectToClose))).run();
   }
 
   protected void resetAllFields() {
index f86a15f2d6fe19fdb53d091c3cdd02cb48887cbb..4b733a9646b7cddc30b4fea35fd319a4630956dc 100644 (file)
@@ -58,7 +58,6 @@ import org.jetbrains.annotations.Nullable;
 import org.junit.Assert;
 
 import javax.swing.*;
-import javax.swing.Timer;
 import java.awt.*;
 import java.io.File;
 import java.io.FileNotFoundException;
@@ -69,9 +68,6 @@ import java.lang.reflect.Method;
 import java.lang.reflect.Modifier;
 import java.util.*;
 import java.util.List;
-import java.util.concurrent.DelayQueue;
-import java.util.concurrent.Delayed;
-import java.util.concurrent.TimeUnit;
 import java.util.regex.Pattern;
 
 /**
@@ -242,7 +238,7 @@ public abstract class UsefulTestCase extends TestCase {
     containerMap.clear();
   }
 
-  protected void checkForSettingsDamage(@NotNull List<Throwable> exceptions) {
+  protected void checkForSettingsDamage() {
     Application app = ApplicationManager.getApplication();
     if (isPerformanceTest() || app == null || app instanceof MockApplication) {
       return;
@@ -255,53 +251,43 @@ public abstract class UsefulTestCase extends TestCase {
 
     myOldCodeStyleSettings = null;
 
-    doCheckForSettingsDamage(oldCodeStyleSettings, getCurrentCodeStyleSettings(), exceptions);
+    doCheckForSettingsDamage(oldCodeStyleSettings, getCurrentCodeStyleSettings());
   }
 
   public static void doCheckForSettingsDamage(@NotNull CodeStyleSettings oldCodeStyleSettings,
-                                              @NotNull CodeStyleSettings currentCodeStyleSettings,
-                                              @NotNull List<Throwable> exceptions) {
+                                              @NotNull CodeStyleSettings currentCodeStyleSettings) {
     final CodeInsightSettings settings = CodeInsightSettings.getInstance();
-    try {
-      Element newS = new Element("temp");
-      settings.writeExternal(newS);
-      Assert.assertEquals("Code insight settings damaged", DEFAULT_SETTINGS_EXTERNALIZED, JDOMUtil.writeElement(newS, "\n"));
-    }
-    catch (AssertionError error) {
-      CodeInsightSettings clean = new CodeInsightSettings();
-      for (Field field : clean.getClass().getFields()) {
+    new RunAll()
+      .append(() -> {
         try {
-          ReflectionUtil.copyFieldValue(clean, settings, field);
+          Element newS = new Element("temp");
+          settings.writeExternal(newS);
+          Assert.assertEquals("Code insight settings damaged", DEFAULT_SETTINGS_EXTERNALIZED, JDOMUtil.writeElement(newS, "\n"));
         }
-        catch (Exception ignored) {
+        catch (AssertionError error) {
+          CodeInsightSettings clean = new CodeInsightSettings();
+          for (Field field : clean.getClass().getFields()) {
+            try {
+              ReflectionUtil.copyFieldValue(clean, settings, field);
+            }
+            catch (Exception ignored) {
+            }
+          }
+          throw error;
         }
-      }
-      exceptions.add(error);
-    }
-
-    currentCodeStyleSettings.getIndentOptions(StdFileTypes.JAVA);
-    try {
-      checkSettingsEqual(oldCodeStyleSettings, currentCodeStyleSettings, "Code style settings damaged");
-    }
-    catch (Throwable e) {
-      exceptions.add(e);
-    }
-    finally {
-      currentCodeStyleSettings.clearCodeStyleSettings();
-    }
-
-    try {
-      InplaceRefactoring.checkCleared();
-    }
-    catch (AssertionError e) {
-      exceptions.add(e);
-    }
-    try {
-      StartMarkAction.checkCleared();
-    }
-    catch (AssertionError e) {
-      exceptions.add(e);
-    }
+      })
+      .append(() -> {
+        currentCodeStyleSettings.getIndentOptions(StdFileTypes.JAVA);
+        try {
+          checkSettingsEqual(oldCodeStyleSettings, currentCodeStyleSettings, "Code style settings damaged");
+        }
+        finally {
+          currentCodeStyleSettings.clearCodeStyleSettings();
+        }
+      })
+      .append(() -> InplaceRefactoring.checkCleared())
+      .append(() -> StartMarkAction.checkCleared())
+      .run();
   }
 
   void storeSettings() {
@@ -845,28 +831,6 @@ public abstract class UsefulTestCase extends TestCase {
     });
   }
 
-  static void checkJavaSwingTimersAreDisposed(@NotNull List<Throwable> exceptions) {
-    try {
-      Class<?> TimerQueueClass = Class.forName("javax.swing.TimerQueue");
-      Method sharedInstance = ReflectionUtil.getMethod(TimerQueueClass, "sharedInstance");
-
-      Object timerQueue = sharedInstance.invoke(null);
-      DelayQueue delayQueue = ReflectionUtil.getField(TimerQueueClass, timerQueue, DelayQueue.class, "queue");
-      Delayed timer = delayQueue.peek();
-      if (timer != null) {
-        long delay = timer.getDelay(TimeUnit.MILLISECONDS);
-        String text = "(delayed for " + delay + "ms)";
-        Method getTimer = ReflectionUtil.getDeclaredMethod(timer.getClass(), "getTimer");
-        Timer swingTimer = (Timer)getTimer.invoke(timer);
-        text = "Timer (listeners: "+Arrays.asList(swingTimer.getActionListeners()) + ") "+text;
-        exceptions.add(new AssertionFailedError("Not disposed java.swing.Timer: " + text + "; queue:" + timerQueue));
-      }
-    }
-    catch (Throwable e) {
-      exceptions.add(e);
-    }
-  }
-
   /**
    * Checks that code block throw corresponding exception.
    *
index 9ac857d7bb761aff7c55efbf36e44dc29bd8fcf7..54a56552c142c015870e246697dcd16c6c6203d0 100644 (file)
@@ -22,7 +22,7 @@ import com.intellij.idea.IdeaTestApplication;
 import com.intellij.openapi.actionSystem.CommonDataKeys;
 import com.intellij.openapi.actionSystem.DataProvider;
 import com.intellij.openapi.actionSystem.LangDataKeys;
-import com.intellij.openapi.application.ApplicationManager;
+import com.intellij.openapi.application.ReadAction;
 import com.intellij.openapi.command.WriteCommandAction;
 import com.intellij.openapi.editor.Editor;
 import com.intellij.openapi.fileEditor.FileEditorManager;
@@ -35,7 +35,6 @@ import com.intellij.openapi.module.ModuleManager;
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.project.ex.ProjectManagerEx;
 import com.intellij.openapi.roots.ProjectRootManager;
-import com.intellij.openapi.util.Computable;
 import com.intellij.openapi.util.io.FileUtil;
 import com.intellij.openapi.util.text.StringUtil;
 import com.intellij.openapi.vfs.LocalFileSystem;
@@ -47,9 +46,8 @@ import com.intellij.psi.impl.source.tree.injected.InjectedLanguageManagerImpl;
 import com.intellij.testFramework.*;
 import com.intellij.testFramework.builders.ModuleFixtureBuilder;
 import com.intellij.testFramework.fixtures.HeavyIdeaTestFixture;
+import com.intellij.util.ObjectUtils;
 import com.intellij.util.PathUtil;
-import com.intellij.util.SmartList;
-import com.intellij.util.lang.CompoundRuntimeException;
 import org.jetbrains.annotations.NonNls;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
@@ -61,7 +59,6 @@ import java.io.IOException;
 import java.io.PrintStream;
 import java.util.HashSet;
 import java.util.LinkedHashSet;
-import java.util.List;
 import java.util.Set;
 
 /**
@@ -102,49 +99,39 @@ class HeavyIdeaTestFixtureImpl extends BaseFixture implements HeavyIdeaTestFixtu
   @Override
   public void tearDown() throws Exception {
     final Project project = getProject();
-    final List<Throwable> exceptions = new SmartList<>();
-    try {
-      LightPlatformTestCase.doTearDown(project, myApplication, false, exceptions);
 
-      for (ModuleFixtureBuilder moduleFixtureBuilder : myModuleFixtureBuilders) {
-        moduleFixtureBuilder.getFixture().tearDown();
-      }
-
-      EdtTestUtil.runInEdtAndWait(() -> PlatformTestCase.closeAndDisposeProjectAndCheckThatNoOpenProjects(project, exceptions));
-      myProject = null;
+    RunAll runAll = new RunAll()
+      .append(() -> LightPlatformTestCase.doTearDown(project, myApplication, false))
+      .append(() -> {
+        for (ModuleFixtureBuilder moduleFixtureBuilder : myModuleFixtureBuilders) {
+          moduleFixtureBuilder.getFixture().tearDown();
+        }
+      })
+      .append(() -> EdtTestUtil.runInEdtAndWait(() -> PlatformTestCase.closeAndDisposeProjectAndCheckThatNoOpenProjects(project)))
+      .append(() -> myProject = null);
 
-      for (File fileToDelete : myFilesToDelete) {
+    for (File fileToDelete : myFilesToDelete) {
+      runAll = runAll.append(() -> {
         if (!FileUtil.delete(fileToDelete)) {
-          exceptions.add(new IOException("Can't delete " + fileToDelete));
+          throw new IOException("Can't delete " + fileToDelete);
         }
-      }
-    }
-    catch (Throwable e) {
-      exceptions.add(e);
+      });
     }
 
-    try {
-      super.tearDown();
-    }
-    catch (Throwable e) {
-      exceptions.add(e);
-    }
-
-    try {
-      myEditorListenerTracker.checkListenersLeak();
-      myThreadTracker.checkLeak();
-      LightPlatformTestCase.checkEditorsReleased(exceptions);
-      PlatformTestCase.cleanupApplicationCaches(project);
-      InjectedLanguageManagerImpl.checkInjectorsAreDisposed(project);
-    }
-    finally {
-      CompoundRuntimeException.throwIfNotEmpty(exceptions);
-    }
+    runAll
+      .append(super::tearDown)
+      .append(() -> myEditorListenerTracker.checkListenersLeak())
+      .append(() -> myThreadTracker.checkLeak())
+      .append(() -> LightPlatformTestCase.checkEditorsReleased())
+      .append(() -> PlatformTestCase.cleanupApplicationCaches(project))
+      .append(() -> InjectedLanguageManagerImpl.checkInjectorsAreDisposed(project))
+      .run();
   }
 
   private void setUpProject() throws IOException {
     File tempDirectory = FileUtil.createTempDirectory(myName, "");
-    PlatformTestCase.synchronizeTempDirVfs(LocalFileSystem.getInstance().refreshAndFindFileByIoFile(tempDirectory));
+    PlatformTestCase
+      .synchronizeTempDirVfs(ObjectUtils.assertNotNull(LocalFileSystem.getInstance().refreshAndFindFileByIoFile(tempDirectory)));
     myFilesToDelete.add(tempDirectory);
 
     String projectPath = FileUtil.toSystemIndependentName(tempDirectory.getPath()) + "/" + myName + ProjectFileType.DOT_DEFAULT_EXTENSION;
@@ -239,11 +226,6 @@ class HeavyIdeaTestFixtureImpl extends BaseFixture implements HeavyIdeaTestFixtu
         PsiDocumentManager.getInstance(getProject()).commitAllDocuments();
       }
     }.execute();
-    return ApplicationManager.getApplication().runReadAction(new Computable<PsiFile>() {
-            @Override
-            public PsiFile compute() {
-              return PsiManager.getInstance(getProject()).findFile(virtualFile[0]);
-            }
-          });
+    return ReadAction.compute(() -> PsiManager.getInstance(getProject()).findFile(virtualFile[0]));
   }
 }
index 1a9f90d086203ac4e5eaf1e9420d326657e0b650..467a0f1f88d4c5e81477fbb966788f39a17d7f27 100644 (file)
@@ -28,10 +28,6 @@ import com.intellij.psi.codeStyle.CodeStyleSettingsManager;
 import com.intellij.psi.impl.source.tree.injected.InjectedLanguageManagerImpl;
 import com.intellij.testFramework.*;
 import com.intellij.testFramework.fixtures.LightIdeaTestFixture;
-import com.intellij.util.SmartList;
-import com.intellij.util.lang.CompoundRuntimeException;
-
-import java.util.List;
 
 /**
  * @author mike
@@ -65,19 +61,15 @@ public class LightIdeaTestFixtureImpl extends BaseFixture implements LightIdeaTe
     CodeStyleSettingsManager.getInstance(project).dropTemporarySettings();
     CodeStyleSettings oldCodeStyleSettings = myOldCodeStyleSettings;
     myOldCodeStyleSettings = null;
-    List<Throwable> exceptions = new SmartList<>();
-    try {
-      UsefulTestCase.doCheckForSettingsDamage(oldCodeStyleSettings, getCurrentCodeStyleSettings(), exceptions);
 
-      LightPlatformTestCase.doTearDown(project, LightPlatformTestCase.getApplication(), true, exceptions);
-      super.tearDown();
-      InjectedLanguageManagerImpl.checkInjectorsAreDisposed(project);
-      PersistentFS.getInstance().clearIdCache();
-      PlatformTestCase.cleanupApplicationCaches(project);
-    }
-    finally {
-      CompoundRuntimeException.throwIfNotEmpty(exceptions);
-    }
+    new RunAll()
+      .append(() -> UsefulTestCase.doCheckForSettingsDamage(oldCodeStyleSettings, getCurrentCodeStyleSettings()))
+      .append(() -> LightPlatformTestCase.doTearDown(project, LightPlatformTestCase.getApplication(), true))
+      .append(super::tearDown)
+      .append(() -> InjectedLanguageManagerImpl.checkInjectorsAreDisposed(project))
+      .append(() -> PersistentFS.getInstance().clearIdCache())
+      .append(() -> PlatformTestCase.cleanupApplicationCaches(project))
+      .run();
   }
 
   @Override
index 4beb5afc9e09189fed082af435a8d95baab09df0..caf014b8d5f3f900c0e238e2e79874ec13ddc321 100644 (file)
@@ -37,6 +37,10 @@ public class CompoundRuntimeException extends RuntimeException {
     myExceptions = throwables;
   }
 
+  public List<Throwable> getExceptions() {
+    return myExceptions;
+  }
+
   @Override
   public String getMessage() {
     return processAll(new Function<Throwable, String>() {