diff --git a/java/testFramework/src/com/intellij/codeInsight/CodeInsightTestCase.java b/java/testFramework/src/com/intellij/codeInsight/CodeInsightTestCase.java index 0afd2d66a48d..5c3060027f96 100644 --- a/java/testFramework/src/com/intellij/codeInsight/CodeInsightTestCase.java +++ b/java/testFramework/src/com/intellij/codeInsight/CodeInsightTestCase.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -192,20 +192,17 @@ public abstract class CodeInsightTestCase extends PsiTestCase { final EditorInfo editorInfo = new EditorInfo(document.getText()); final String newFileText = editorInfo.getNewFileText(); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - if (!document.getText().equals(newFileText)) { - document.setText(newFileText); - } - - PsiFile file = myPsiManager.findFile(virtualFile); - if (myFile == null) myFile = file; - - if (myEditor == null) myEditor = editor; - - editorInfo.applyToEditor(editor); + ApplicationManager.getApplication().runWriteAction(() -> { + if (!document.getText().equals(newFileText)) { + document.setText(newFileText); } + + PsiFile file = myPsiManager.findFile(virtualFile); + if (myFile == null) myFile = file; + + if (myEditor == null) myEditor = editor; + + editorInfo.applyToEditor(editor); }); @@ -219,60 +216,57 @@ public abstract class CodeInsightTestCase extends PsiTestCase { final File toDirIO = createTempDirectory(); final VirtualFile toDir = getVirtualFile(toDirIO); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - try { - final ModuleRootManager rootManager = ModuleRootManager.getInstance(myModule); - final ModifiableRootModel rootModel = rootManager.getModifiableModel(); - if (clearModelBeforeConfiguring()) { - rootModel.clear(); - } - - // auxiliary files should be copied first - VirtualFile[] reversed = ArrayUtil.reverseArray(vFiles); - Map editorInfos; - if (rawProjectRoot != null) { - final File projectRoot = rawProjectRoot.getCanonicalFile(); - FileUtil.copyDir(projectRoot, toDirIO); - VirtualFile fromDir = getVirtualFile(projectRoot); - editorInfos = - copyFilesFillingEditorInfos(fromDir, toDir, ContainerUtil.map2Array(reversed, String.class, new Function() { - @Override - public String fun(final VirtualFile s) { - return s.getPath().substring(projectRoot.getPath().length()); - } - })); - - toDir.refresh(false, true); - } - else { - editorInfos = new LinkedHashMap(); - for (final VirtualFile vFile : reversed) { - VirtualFile parent = vFile.getParent(); - assert parent.isDirectory() : parent; - editorInfos.putAll(copyFilesFillingEditorInfos(parent, toDir, vFile.getName())); - } - } - - boolean sourceRootAdded = false; - if (isAddDirToContentRoot()) { - final ContentEntry contentEntry = rootModel.addContentEntry(toDir); - if (isAddDirToSource()) { - sourceRootAdded = true; - contentEntry.addSourceFolder(toDir, isAddDirToTests()); - } - } - doCommitModel(rootModel); - if (sourceRootAdded) { - sourceRootAdded(toDir); - } - - openEditorsAndActivateLast(editorInfos); + ApplicationManager.getApplication().runWriteAction(() -> { + try { + final ModuleRootManager rootManager = ModuleRootManager.getInstance(myModule); + final ModifiableRootModel rootModel = rootManager.getModifiableModel(); + if (clearModelBeforeConfiguring()) { + rootModel.clear(); } - catch (IOException e) { - LOG.error(e); + + // auxiliary files should be copied first + VirtualFile[] reversed = ArrayUtil.reverseArray(vFiles); + Map editorInfos; + if (rawProjectRoot != null) { + final File projectRoot = rawProjectRoot.getCanonicalFile(); + FileUtil.copyDir(projectRoot, toDirIO); + VirtualFile fromDir = getVirtualFile(projectRoot); + editorInfos = + copyFilesFillingEditorInfos(fromDir, toDir, ContainerUtil.map2Array(reversed, String.class, new Function() { + @Override + public String fun(final VirtualFile s) { + return s.getPath().substring(projectRoot.getPath().length()); + } + })); + + toDir.refresh(false, true); } + else { + editorInfos = new LinkedHashMap<>(); + for (final VirtualFile vFile : reversed) { + VirtualFile parent = vFile.getParent(); + assert parent.isDirectory() : parent; + editorInfos.putAll(copyFilesFillingEditorInfos(parent, toDir, vFile.getName())); + } + } + + boolean sourceRootAdded = false; + if (isAddDirToContentRoot()) { + final ContentEntry contentEntry = rootModel.addContentEntry(toDir); + if (isAddDirToSource()) { + sourceRootAdded = true; + contentEntry.addSourceFolder(toDir, isAddDirToTests()); + } + } + doCommitModel(rootModel); + if (sourceRootAdded) { + sourceRootAdded(toDir); + } + + openEditorsAndActivateLast(editorInfos); + } + catch (IOException e) { + LOG.error(e); } }); @@ -303,9 +297,9 @@ public abstract class CodeInsightTestCase extends PsiTestCase { protected Map copyFilesFillingEditorInfos(@NotNull VirtualFile fromDir, @NotNull VirtualFile toDir, @NotNull String... relativePaths) throws IOException { - Map editorInfos = new LinkedHashMap(); + Map editorInfos = new LinkedHashMap<>(); - List streamsToClose = new ArrayList(); + List streamsToClose = new ArrayList<>(); for (String relativePath : relativePaths) { relativePath = StringUtil.trimStart(relativePath, "/"); @@ -352,21 +346,18 @@ public abstract class CodeInsightTestCase extends PsiTestCase { @NotNull protected final List openEditors(@NotNull final Map editorInfos) { - return ContainerUtil.map(editorInfos.keySet(), new Function() { - @Override - public Editor fun(final VirtualFile newVFile) { - PsiFile file = myPsiManager.findFile(newVFile); - if (myFile == null) myFile = file; + return ContainerUtil.map(editorInfos.keySet(), newVFile -> { + PsiFile file = myPsiManager.findFile(newVFile); + if (myFile == null) myFile = file; - Editor editor = createEditor(newVFile); - if (myEditor == null) myEditor = editor; + Editor editor = createEditor(newVFile); + if (myEditor == null) myEditor = editor; - EditorInfo editorInfo = editorInfos.get(newVFile); - if (editorInfo != null) { - editorInfo.applyToEditor(editor); - } - return editor; + EditorInfo editorInfo = editorInfos.get(newVFile); + if (editorInfo != null) { + editorInfo.applyToEditor(editor); } + return editor; }); } diff --git a/java/testFramework/src/com/intellij/testFramework/IdeaTestCase.java b/java/testFramework/src/com/intellij/testFramework/IdeaTestCase.java index e3bc22b196f0..f3aa67a29a0f 100644 --- a/java/testFramework/src/com/intellij/testFramework/IdeaTestCase.java +++ b/java/testFramework/src/com/intellij/testFramework/IdeaTestCase.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,9 +24,9 @@ import com.intellij.openapi.vfs.pointers.VirtualFilePointerManager; import com.intellij.pom.java.LanguageLevel; import com.intellij.psi.PsiClass; import com.intellij.psi.impl.JavaPsiFacadeEx; +import org.jetbrains.annotations.NotNull; import java.util.Arrays; -import java.util.Comparator; /** * @author mike @@ -71,12 +71,7 @@ public abstract class IdeaTestCase extends PlatformTestCase { public static void initPlatformPrefix() { } - protected static void sortClassesByName(final PsiClass[] classes) { - Arrays.sort(classes, new Comparator() { - @Override - public int compare(PsiClass o1, PsiClass o2) { - return o1.getName().compareTo(o2.getName()); - } - }); + protected static void sortClassesByName(@NotNull PsiClass[] classes) { + Arrays.sort(classes, (o1, o2) -> o1.getName().compareTo(o2.getName())); } } diff --git a/java/testFramework/src/com/intellij/testFramework/ModuleTestCase.java b/java/testFramework/src/com/intellij/testFramework/ModuleTestCase.java index 604d4edec662..e3cea9296e31 100644 --- a/java/testFramework/src/com/intellij/testFramework/ModuleTestCase.java +++ b/java/testFramework/src/com/intellij/testFramework/ModuleTestCase.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -46,7 +46,7 @@ import java.util.Collection; import java.util.List; public abstract class ModuleTestCase extends IdeaTestCase { - protected final Collection myModulesToDispose = new ArrayList(); + protected final Collection myModulesToDispose = new ArrayList<>(); @Override protected void setUp() throws Exception { @@ -70,7 +70,7 @@ public abstract class ModuleTestCase extends IdeaTestCase { } catch (Throwable e) { if (errors == null) { - errors = new SmartList(); + errors = new SmartList<>(); } errors.add(e); } @@ -99,12 +99,7 @@ public abstract class ModuleTestCase extends IdeaTestCase { protected Module createModule(final String path, final ModuleType moduleType) { Module module = ApplicationManager.getApplication().runWriteAction( - new Computable() { - @Override - public Module compute() { - return ModuleManager.getInstance(myProject).newModule(path, moduleType.getId()); - } - } + (Computable)() -> ModuleManager.getInstance(myProject).newModule(path, moduleType.getId()) ); myModulesToDispose.add(module); @@ -118,12 +113,7 @@ public abstract class ModuleTestCase extends IdeaTestCase { final ModuleManager moduleManager = ModuleManager.getInstance(myProject); Module module; try { - module = ApplicationManager.getApplication().runWriteAction(new ThrowableComputable() { - @Override - public Module compute() throws Exception { - return moduleManager.loadModule(normalizedPath); - } - }); + module = ApplicationManager.getApplication().runWriteAction((ThrowableComputable)() -> moduleManager.loadModule(normalizedPath)); } catch (Exception e) { LOG.error(e); diff --git a/java/testFramework/src/com/intellij/testFramework/PsiTestCase.java b/java/testFramework/src/com/intellij/testFramework/PsiTestCase.java index 4c2abb08be74..296d1f5afa50 100644 --- a/java/testFramework/src/com/intellij/testFramework/PsiTestCase.java +++ b/java/testFramework/src/com/intellij/testFramework/PsiTestCase.java @@ -18,6 +18,7 @@ package com.intellij.testFramework; import com.intellij.openapi.application.Result; import com.intellij.openapi.application.WriteAction; import com.intellij.openapi.application.ex.PathManagerEx; +import com.intellij.openapi.editor.Document; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.fileTypes.FileTypeRegistry; @@ -30,6 +31,7 @@ import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VfsUtil; +import com.intellij.openapi.vfs.VfsUtilCore; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.*; import com.intellij.psi.impl.PsiManagerImpl; @@ -115,7 +117,7 @@ public abstract class PsiTestCase extends ModuleTestCase { protected PsiElement configureByFileWithMarker(String filePath, String marker) throws Exception{ final VirtualFile vFile = VfsTestUtil.findFileByCaseSensitivePath(filePath); - String fileText = VfsUtil.loadText(vFile); + String fileText = VfsUtilCore.loadText(vFile); fileText = StringUtil.convertLineSeparators(fileText); int offset = fileText.indexOf(marker); @@ -225,15 +227,15 @@ public abstract class PsiTestCase extends ModuleTestCase { return myFile; } - public com.intellij.openapi.editor.Document getDocument(PsiFile file) { + public Document getDocument(PsiFile file) { return PsiDocumentManager.getInstance(getProject()).getDocument(file); } - public com.intellij.openapi.editor.Document getDocument(VirtualFile file) { + public Document getDocument(VirtualFile file) { return FileDocumentManager.getInstance().getDocument(file); } - public void commitDocument(com.intellij.openapi.editor.Document document) { + public void commitDocument(Document document) { PsiDocumentManager.getInstance(getProject()).commitDocument(document); } } diff --git a/platform/testFramework/src/com/intellij/FileSetTestCase.java b/platform/testFramework/src/com/intellij/FileSetTestCase.java index d89e175a52c2..74300cabf8b3 100644 --- a/platform/testFramework/src/com/intellij/FileSetTestCase.java +++ b/platform/testFramework/src/com/intellij/FileSetTestCase.java @@ -1,11 +1,19 @@ /* - * Created by IntelliJ IDEA. - * User: user - * Date: Sep 22, 2002 - * Time: 2:45:20 PM - * To change template for new class use - * Code Style | Class Templates options (Tools | IDE Options). + * Copyright 2000-2016 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ + package com.intellij; import com.intellij.openapi.project.Project; @@ -14,6 +22,7 @@ import com.intellij.openapi.util.text.StringUtil; import com.intellij.testFramework.LightPlatformTestCase; import com.intellij.util.ArrayUtil; import junit.framework.TestSuite; +import org.jetbrains.annotations.NotNull; import java.io.File; import java.io.IOException; @@ -26,7 +35,7 @@ public abstract class FileSetTestCase extends TestSuite { protected Project myProject; private Pattern myPattern; - public FileSetTestCase(String path) { + public FileSetTestCase(@NotNull String path) { File f = new File(path); if (f.isDirectory()) { myFiles = f.listFiles(); @@ -43,6 +52,11 @@ public abstract class FileSetTestCase extends TestSuite { addAllTests(); } + protected FileSetTestCase(@NotNull File[] files) { + myFiles = files; + addAllTests(); + } + protected void setUp() { } @@ -61,11 +75,6 @@ public abstract class FileSetTestCase extends TestSuite { public abstract String transform(String testName, String[] data) throws Exception; - protected FileSetTestCase(File[] files) { - myFiles = files; - addAllTests(); - } - @Override public String getName() { return getClass().getName(); @@ -97,7 +106,7 @@ public abstract class FileSetTestCase extends TestSuite { private final File myTestFile; private final String myTestName; - public ActualTest(File testFile, String testName) { + ActualTest(File testFile, String testName) { myTestFile = testFile; myTestName = testName; } @@ -124,12 +133,11 @@ public abstract class FileSetTestCase extends TestSuite { String content = loadFile(myTestFile); assertNotNull(content); - List input = new ArrayList(); - - int separatorIndex; + List input = new ArrayList<>(); content = StringUtil.replace(content, "\r", ""); + int separatorIndex; while ((separatorIndex = content.indexOf(getDelimiter())) >= 0) { input.add(content.substring(0, separatorIndex)); content = content.substring(separatorIndex); @@ -138,25 +146,25 @@ public abstract class FileSetTestCase extends TestSuite { String result = content; - assertTrue("No data found in source file", input.size() > 0); + assertTrue("No data found in source file", !input.isEmpty()); while (StringUtil.startsWithChar(result, '-') || StringUtil.startsWithChar(result, '\n') || StringUtil.startsWithChar(result, '\r')) { result = result.substring(1); } - final String transformed; - FileSetTestCase.this.myProject = getProject(); + myProject = getProject(); String testName = myTestFile.getName(); final int dotIdx = testName.indexOf('.'); if (dotIdx >= 0) { testName = testName.substring(0, dotIdx); } - transformed = StringUtil.replace(transform(testName, ArrayUtil.toStringArray(input)), "\r", ""); + final String transformed = StringUtil.replace(transform(testName, ArrayUtil.toStringArray(input)), "\r", ""); result = StringUtil.replace(result, "\r", ""); assertEquals(result.trim(),transformed.trim()); } + @NotNull @Override protected String getTestName(final boolean lowercaseFirstLetter) { return ""; diff --git a/platform/testFramework/src/com/intellij/testFramework/LightPlatformCodeInsightTestCase.java b/platform/testFramework/src/com/intellij/testFramework/LightPlatformCodeInsightTestCase.java index 1a420a0289ec..5d058fb4ea2b 100644 --- a/platform/testFramework/src/com/intellij/testFramework/LightPlatformCodeInsightTestCase.java +++ b/platform/testFramework/src/com/intellij/testFramework/LightPlatformCodeInsightTestCase.java @@ -30,7 +30,9 @@ import com.intellij.openapi.application.ex.PathManagerEx; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.command.WriteCommandAction; import com.intellij.openapi.diagnostic.Logger; -import com.intellij.openapi.editor.*; +import com.intellij.openapi.editor.Document; +import com.intellij.openapi.editor.Editor; +import com.intellij.openapi.editor.EditorFactory; import com.intellij.openapi.editor.actionSystem.EditorActionManager; import com.intellij.openapi.editor.actionSystem.TypedAction; import com.intellij.openapi.editor.ex.util.EditorUtil; @@ -80,12 +82,9 @@ public abstract class LightPlatformCodeInsightTestCase extends LightPlatformTest @Override protected void runTest() throws Throwable { if (isRunInWriteAction()) { - WriteCommandAction.runWriteCommandAction(getProject(), new ThrowableComputable() { - @Override - public Void compute() throws Throwable { - doRunTest(); - return null; - } + WriteCommandAction.runWriteCommandAction(getProject(), (ThrowableComputable)() -> { + doRunTest(); + return null; }); } else { @@ -237,14 +236,11 @@ public abstract class LightPlatformCodeInsightTestCase extends LightPlatformTest private static void setupEditorForInjectedLanguage() { if (myEditor != null) { - final Ref editorWindowRef = new Ref(); - myEditor.getCaretModel().runForEachCaret(new CaretAction() { - @Override - public void perform(Caret caret) { - Editor editor = InjectedLanguageUtil.getEditorForInjectedLanguageNoCommit(myEditor, myFile); - if (caret == myEditor.getCaretModel().getPrimaryCaret() && editor instanceof EditorWindow) { - editorWindowRef.set((EditorWindow)editor); - } + final Ref editorWindowRef = new Ref<>(); + myEditor.getCaretModel().runForEachCaret(caret -> { + Editor editor = InjectedLanguageUtil.getEditorForInjectedLanguageNoCommit(myEditor, myFile); + if (caret == myEditor.getCaretModel().getPrimaryCaret() && editor instanceof EditorWindow) { + editorWindowRef.set((EditorWindow)editor); } }); if (!editorWindowRef.isNull()) { @@ -320,7 +316,8 @@ public abstract class LightPlatformCodeInsightTestCase extends LightPlatformTest String fileText = null; try { fileText = FileUtil.loadFile(ioFile, CharsetToolkit.UTF8_CHARSET); - } catch (IOException e) { + } + catch (IOException e) { LOG.error(e); } checkResultByText(message, StringUtil.convertLineSeparators(fileText), ignoreTrailingSpaces, getTestDataPath() + "/" + filePath); @@ -350,30 +347,27 @@ public abstract class LightPlatformCodeInsightTestCase extends LightPlatformTest protected void checkResultByText(final String message, @NotNull final String fileText, final boolean ignoreTrailingSpaces, final String filePath) { bringRealEditorBack(); PsiDocumentManager.getInstance(getProject()).commitAllDocuments(); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - final Document document = EditorFactory.getInstance().createDocument(fileText); + ApplicationManager.getApplication().runWriteAction(() -> { + final Document document = EditorFactory.getInstance().createDocument(fileText); - if (ignoreTrailingSpaces) { - ((DocumentImpl)document).stripTrailingSpaces(getProject()); - } - - EditorTestUtil.CaretAndSelectionState carets = EditorTestUtil.extractCaretAndSelectionMarkers(document); - - PostprocessReformattingAspect.getInstance(getProject()).doPostponedFormatting(); - String newFileText = document.getText(); - - PsiDocumentManager.getInstance(getProject()).commitAllDocuments(); - String fileText = myFile.getText(); - String failMessage = getMessage("Text mismatch", message); - if (filePath != null && !newFileText.equals(fileText)) { - throw new FileComparisonFailure(failMessage, newFileText, fileText, filePath); - } - assertEquals(failMessage, newFileText, fileText); - - EditorTestUtil.verifyCaretAndSelectionState(myEditor, carets, message); + if (ignoreTrailingSpaces) { + ((DocumentImpl)document).stripTrailingSpaces(getProject()); } + + EditorTestUtil.CaretAndSelectionState carets = EditorTestUtil.extractCaretAndSelectionMarkers(document); + + PostprocessReformattingAspect.getInstance(getProject()).doPostponedFormatting(); + String newFileText = document.getText(); + + PsiDocumentManager.getInstance(getProject()).commitAllDocuments(); + String fileText1 = myFile.getText(); + String failMessage = getMessage("Text mismatch", message); + if (filePath != null && !newFileText.equals(fileText1)) { + throw new FileComparisonFailure(failMessage, newFileText, fileText1, filePath); + } + assertEquals(failMessage, newFileText, fileText1); + + EditorTestUtil.verifyCaretAndSelectionState(myEditor, carets, message); }); } @@ -382,27 +376,24 @@ public abstract class LightPlatformCodeInsightTestCase extends LightPlatformTest @NotNull final String fileText, final boolean ignoreTrailingSpaces, final String filePath) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - final Document fakeDocument = EditorFactory.getInstance().createDocument(fileText); + ApplicationManager.getApplication().runWriteAction(() -> { + final Document fakeDocument = EditorFactory.getInstance().createDocument(fileText); - if (ignoreTrailingSpaces) { - ((DocumentImpl)fakeDocument).stripTrailingSpaces(getProject()); - } - - EditorTestUtil.CaretAndSelectionState carets = EditorTestUtil.extractCaretAndSelectionMarkers(fakeDocument); - - String newFileText = fakeDocument.getText(); - String fileText = editor.getDocument().getText(); - String failMessage = getMessage("Text mismatch", message); - if (filePath != null && !newFileText.equals(fileText)) { - throw new FileComparisonFailure(failMessage, newFileText, fileText, filePath); - } - assertEquals(failMessage, newFileText, fileText); - - EditorTestUtil.verifyCaretAndSelectionState(editor, carets, message); + if (ignoreTrailingSpaces) { + ((DocumentImpl)fakeDocument).stripTrailingSpaces(getProject()); } + + EditorTestUtil.CaretAndSelectionState carets = EditorTestUtil.extractCaretAndSelectionMarkers(fakeDocument); + + String newFileText = fakeDocument.getText(); + String fileText1 = editor.getDocument().getText(); + String failMessage = getMessage("Text mismatch", message); + if (filePath != null && !newFileText.equals(fileText1)) { + throw new FileComparisonFailure(failMessage, newFileText, fileText1, filePath); + } + assertEquals(failMessage, newFileText, fileText1); + + EditorTestUtil.verifyCaretAndSelectionState(editor, carets, message); }); } @@ -624,39 +615,32 @@ public abstract class LightPlatformCodeInsightTestCase extends LightPlatformTest executeAction(actionId, editor, getProject()); } public static void executeAction(@NonNls @NotNull final String actionId, @NotNull final Editor editor, Project project) { - CommandProcessor.getInstance().executeCommand(project, new Runnable() { - @Override - public void run() { - EditorTestUtil.executeAction(editor, actionId); - } + CommandProcessor.getInstance().executeCommand(project, () -> { + EditorTestUtil.executeAction(editor, actionId); }, "", null, editor.getDocument()); } @NotNull protected static DataContext getCurrentEditorDataContext() { final DataContext defaultContext = DataManager.getInstance().getDataContext(); - return new DataContext() { - @Override - @Nullable - public Object getData(@NonNls String dataId) { - if (CommonDataKeys.EDITOR.is(dataId)) { - return getEditor(); - } - if (CommonDataKeys.PROJECT.is(dataId)) { - return getProject(); - } - if (CommonDataKeys.PSI_FILE.is(dataId)) { - return getFile(); - } - if (CommonDataKeys.PSI_ELEMENT.is(dataId)) { - PsiFile file = getFile(); - if (file == null) return null; - Editor editor = getEditor(); - if (editor == null) return null; - return file.findElementAt(editor.getCaretModel().getOffset()); - } - return defaultContext.getData(dataId); + return dataId -> { + if (CommonDataKeys.EDITOR.is(dataId)) { + return getEditor(); } + if (CommonDataKeys.PROJECT.is(dataId)) { + return getProject(); + } + if (CommonDataKeys.PSI_FILE.is(dataId)) { + return getFile(); + } + if (CommonDataKeys.PSI_ELEMENT.is(dataId)) { + PsiFile file = getFile(); + if (file == null) return null; + Editor editor = getEditor(); + if (editor == null) return null; + return file.findElementAt(editor.getCaretModel().getOffset()); + } + return defaultContext.getData(dataId); }; } @@ -723,7 +707,7 @@ public abstract class LightPlatformCodeInsightTestCase extends LightPlatformTest fail("Test files not found in " + testDir.getPath()); } - final List result = new ArrayList(); + final List result = new ArrayList<>(); for (File file : files) { final String fileSuffix = fileBasedTestCase.getFileSuffix(file.getName()); if (fileSuffix != null) { @@ -745,15 +729,12 @@ public abstract class LightPlatformCodeInsightTestCase extends LightPlatformTest public void before() throws Throwable { final Throwable[] throwables = new Throwable[1]; - invokeTestRunnable(new Runnable() { - @Override - public void run() { - try { - setUp(); - } - catch (Throwable e) { - throwables[0] = e; - } + invokeTestRunnable(() -> { + try { + setUp(); + } + catch (Throwable e) { + throwables[0] = e; } }); @@ -766,15 +747,12 @@ public abstract class LightPlatformCodeInsightTestCase extends LightPlatformTest public void after() throws Throwable { final Throwable[] throwables = new Throwable[1]; - invokeTestRunnable(new Runnable() { - @Override - public void run() { - try { - tearDown(); - } - catch (Throwable e) { - throwables[0] = e; - } + invokeTestRunnable(() -> { + try { + tearDown(); + } + catch (Throwable e) { + throwables[0] = e; } }); if (throwables[0] != null) { @@ -785,15 +763,12 @@ public abstract class LightPlatformCodeInsightTestCase extends LightPlatformTest protected void runSingleTest(@NotNull final Runnable testRunnable) throws Throwable { final Throwable[] throwables = new Throwable[1]; - Runnable runnable = new Runnable() { - @Override - public void run() { - try { - testRunnable.run(); - } - catch (Throwable e) { - throwables[0] = e; - } + Runnable runnable = () -> { + try { + testRunnable.run(); + } + catch (Throwable e) { + throwables[0] = e; } }; diff --git a/platform/testFramework/src/com/intellij/testFramework/LightPlatformTestCase.java b/platform/testFramework/src/com/intellij/testFramework/LightPlatformTestCase.java index c0af55755fed..2dc2e974565c 100644 --- a/platform/testFramework/src/com/intellij/testFramework/LightPlatformTestCase.java +++ b/platform/testFramework/src/com/intellij/testFramework/LightPlatformTestCase.java @@ -172,11 +172,8 @@ public abstract class LightPlatformTestCase extends UsefulTestCase implements Da @TestOnly public static void disposeApplication() { if (ourApplication != null) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - Disposer.dispose(ourApplication); - } + ApplicationManager.getApplication().runWriteAction(() -> { + Disposer.dispose(ourApplication); }); ourApplication = null; @@ -227,15 +224,12 @@ public abstract class LightPlatformTestCase extends UsefulTestCase implements Da private static void initProject(@NotNull final LightProjectDescriptor descriptor) throws Exception { ourProjectDescriptor = descriptor; - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - if (ourProject != null) { - closeAndDeleteProject(); - } - else { - cleanPersistedVFSContent(); - } + ApplicationManager.getApplication().runWriteAction(() -> { + if (ourProject != null) { + closeAndDeleteProject(); + } + else { + cleanPersistedVFSContent(); } }); @@ -280,25 +274,22 @@ public abstract class LightPlatformTestCase extends UsefulTestCase implements Da @Override protected void setUp() throws Exception { - EdtTestUtil.runInEdtAndWait(new ThrowableRunnable() { - @Override - public void run() throws Exception { - LightPlatformTestCase.super.setUp(); - initApplication(); - ApplicationInfoImpl.setInPerformanceTest(isPerformanceTest()); + EdtTestUtil.runInEdtAndWait((ThrowableRunnable)() -> { + LightPlatformTestCase.super.setUp(); + initApplication(); + ApplicationInfoImpl.setInPerformanceTest(isPerformanceTest()); - ourApplication.setDataProvider(LightPlatformTestCase.this); - LightProjectDescriptor descriptor = new SimpleLightProjectDescriptor(getModuleType(), getProjectJDK()); - doSetup(descriptor, configureLocalInspectionTools(), getTestRootDisposable()); - InjectedLanguageManagerImpl.pushInjectors(getProject()); + ourApplication.setDataProvider(this); + LightProjectDescriptor descriptor = new SimpleLightProjectDescriptor(getModuleType(), getProjectJDK()); + doSetup(descriptor, configureLocalInspectionTools(), getTestRootDisposable()); + InjectedLanguageManagerImpl.pushInjectors(getProject()); - storeSettings(); + storeSettings(); - myThreadTracker = new ThreadTracker(); - ModuleRootManager.getInstance(ourModule).orderEntries().getAllLibrariesAndSdkClassesRoots(); - VirtualFilePointerManagerImpl filePointerManager = (VirtualFilePointerManagerImpl)VirtualFilePointerManager.getInstance(); - filePointerManager.storePointers(); - } + myThreadTracker = new ThreadTracker(); + ModuleRootManager.getInstance(ourModule).orderEntries().getAllLibrariesAndSdkClassesRoots(); + VirtualFilePointerManagerImpl filePointerManager = (VirtualFilePointerManagerImpl)VirtualFilePointerManager.getInstance(); + filePointerManager.storePointers(); }); } @@ -331,7 +322,7 @@ public abstract class LightPlatformTestCase extends UsefulTestCase implements Da clearUncommittedDocuments(getProject()); CodeInsightTestFixtureImpl.configureInspections(localInspectionTools, getProject(), - Collections.emptyList(), parentDisposable); + Collections.emptyList(), parentDisposable); assertFalse(getPsiManager().isDisposed()); Boolean passed = null; @@ -352,12 +343,7 @@ public abstract class LightPlatformTestCase extends UsefulTestCase implements Da if (manager instanceof FileDocumentManagerImpl) { Document[] unsavedDocuments = manager.getUnsavedDocuments(); manager.saveAllDocuments(); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - ((FileDocumentManagerImpl)manager).dropAllUnsavedDocuments(); - } - }); + ApplicationManager.getApplication().runWriteAction(((FileDocumentManagerImpl)manager)::dropAllUnsavedDocuments); assertEmpty("There are unsaved documents", Arrays.asList(unsavedDocuments)); } @@ -409,17 +395,14 @@ public abstract class LightPlatformTestCase extends UsefulTestCase implements Da if (key == null) { HighlightDisplayKey.register(shortName, toolWrapper.getDisplayName(), toolWrapper.getID()); } - InspectionProfileImpl.initAndDo(new Computable() { - @Override - public Object compute() { - InspectionProfileImpl impl = (InspectionProfileImpl)profile; - InspectionToolWrapper existingWrapper = impl.getInspectionTool(shortName, project); - if (existingWrapper == null || existingWrapper.isInitialized() != toolWrapper.isInitialized() || toolWrapper.isInitialized() && toolWrapper.getTool() != existingWrapper.getTool()) { - impl.addTool(project, toolWrapper, new THashMap>()); - } - impl.enableTool(shortName, project); - return null; + InspectionProfileImpl.initAndDo((Computable)() -> { + InspectionProfileImpl impl = (InspectionProfileImpl)profile; + InspectionToolWrapper existingWrapper = impl.getInspectionTool(shortName, project); + if (existingWrapper == null || existingWrapper.isInitialized() != toolWrapper.isInitialized() || toolWrapper.isInitialized() && toolWrapper.getTool() != existingWrapper.getTool()) { + impl.addTool(project, toolWrapper, new THashMap<>()); } + impl.enableTool(shortName, project); + return null; }); } @@ -432,7 +415,7 @@ public abstract class LightPlatformTestCase extends UsefulTestCase implements Da protected void tearDown() throws Exception { Project project = getProject(); CodeStyleSettingsManager.getInstance(project).dropTemporarySettings(); - List errors = new SmartList(); + List errors = new SmartList<>(); try { checkForSettingsDamage(errors); doTearDown(project, ourApplication, true, errors); @@ -521,14 +504,11 @@ public abstract class LightPlatformTestCase extends UsefulTestCase implements Da ((HintManagerImpl)HintManager.getInstance()).cleanup(); DocumentCommitThread.getInstance().clearQueue(); - EdtTestUtil.runInEdtAndWait(new Runnable() { - @Override - public void run() { - ((UndoManagerImpl)UndoManager.getGlobalInstance()).dropHistoryInTests(); - ((UndoManagerImpl)UndoManager.getInstance(project)).dropHistoryInTests(); + EdtTestUtil.runInEdtAndWait((Runnable)() -> { + ((UndoManagerImpl)UndoManager.getGlobalInstance()).dropHistoryInTests(); + ((UndoManagerImpl)UndoManager.getInstance(project)).dropHistoryInTests(); - UIUtil.dispatchAllInvocationEvents(); - } + UIUtil.dispatchAllInvocationEvents(); }); TemplateDataLanguageMappings.getInstance(project).cleanupForNextTest(); @@ -600,25 +580,22 @@ public abstract class LightPlatformTestCase extends UsefulTestCase implements Da } TestRunnerUtil.replaceIdeEventQueueSafely(); - EdtTestUtil.runInEdtAndWait(new ThrowableRunnable() { - @Override - public void run() throws Throwable { + EdtTestUtil.runInEdtAndWait((ThrowableRunnable)() -> { + try { + ourTestThread = Thread.currentThread(); + startRunAndTear(); + } + finally { + ourTestThread = null; try { - ourTestThread = Thread.currentThread(); - startRunAndTear(); + Application application = ApplicationManager.getApplication(); + if (application instanceof ApplicationEx) { + PlatformTestCase.cleanupApplicationCaches(ourProject); + } + resetAllFields(); } - finally { - ourTestThread = null; - try { - Application application = ApplicationManager.getApplication(); - if (application instanceof ApplicationEx) { - PlatformTestCase.cleanupApplicationCaches(ourProject); - } - resetAllFields(); - } - catch (Throwable e) { - e.printStackTrace(); - } + catch (Throwable e) { + e.printStackTrace(); } } }); @@ -671,7 +648,6 @@ public abstract class LightPlatformTestCase extends UsefulTestCase implements Da * @param fileName - name of the file to create. Extension is used to choose what PSI should be created like java, jsp, aj, xml etc. * @param text - file text. * @return dummy psi file. - * @throws IncorrectOperationException * */ @NotNull @@ -693,6 +669,7 @@ public abstract class LightPlatformTestCase extends UsefulTestCase implements Da * * @param lowercaseFirstLetter - whether first letter after test should be lowercased. */ + @NotNull @Override protected String getTestName(boolean lowercaseFirstLetter) { String name = getName(); @@ -712,6 +689,7 @@ public abstract class LightPlatformTestCase extends UsefulTestCase implements Da PsiDocumentManager.getInstance(getProject()).commitAllDocuments(); } + @NotNull @Override protected CodeStyleSettings getCurrentCodeStyleSettings() { if (CodeStyleSchemes.getInstance().getCurrentScheme() == null) return new CodeStyleSettings(); @@ -757,22 +735,10 @@ public abstract class LightPlatformTestCase extends UsefulTestCase implements Da } private static void registerShutdownHook() { - ShutDownTracker.getInstance().registerShutdownTask(new Runnable() { - @Override - public void run() { - ShutDownTracker.invokeAndWait(true, true, new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - closeAndDeleteProject(); - } - }); - } - }); - } - }); + ShutDownTracker.getInstance().registerShutdownTask( + () -> ShutDownTracker.invokeAndWait(true, true, + () -> ApplicationManager.getApplication().runWriteAction( + LightPlatformTestCase::closeAndDeleteProject))); } private static class SimpleLightProjectDescriptor extends LightProjectDescriptor { diff --git a/platform/testFramework/src/com/intellij/testFramework/PlatformTestCase.java b/platform/testFramework/src/com/intellij/testFramework/PlatformTestCase.java index 217cd0c46525..d8795f48c377 100644 --- a/platform/testFramework/src/com/intellij/testFramework/PlatformTestCase.java +++ b/platform/testFramework/src/com/intellij/testFramework/PlatformTestCase.java @@ -103,7 +103,7 @@ public abstract class PlatformTestCase extends UsefulTestCase implements DataPro protected ProjectManagerEx myProjectManager; protected Project myProject; protected Module myModule; - protected static final Collection myFilesToDelete = new HashSet(); + protected static final Collection myFilesToDelete = new HashSet<>(); protected boolean myAssertionsInTestDetected; protected static final Logger LOG = Logger.getInstance("#com.intellij.testFramework.PlatformTestCase"); public static Thread ourTestThread; @@ -170,6 +170,7 @@ public abstract class PlatformTestCase extends UsefulTestCase implements DataPro ((PersistentFSImpl)PersistentFS.getInstance()).cleanPersistedContents(); } + @NotNull @Override protected CodeStyleSettings getCurrentCodeStyleSettings() { if (CodeStyleSchemes.getInstance().getCurrentScheme() == null) return new CodeStyleSettings(); @@ -392,7 +393,7 @@ public abstract class PlatformTestCase extends UsefulTestCase implements DataPro return ourEternallyLivingFilesCache; } - Set survivors = new HashSet(); + Set survivors = new HashSet<>(); for (IndexableSetContributor contributor : IndexableSetContributor.EP_NAME.getExtensions()) { for (VirtualFile file : IndexableSetContributor.getRootsToIndex(contributor)) { @@ -430,7 +431,7 @@ public abstract class PlatformTestCase extends UsefulTestCase implements DataPro @Override protected void tearDown() throws Exception { - List exceptions = new SmartList(); + List exceptions = new SmartList<>(); Project project = myProject; if (project != null) { try { @@ -557,15 +558,12 @@ public abstract class PlatformTestCase extends UsefulTestCase implements DataPro exceptions.add(e); } finally { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - try { - Disposer.dispose(projectToClose); - } - catch (Throwable e) { - exceptions.add(e); - } + ApplicationManager.getApplication().runWriteAction(() -> { + try { + Disposer.dispose(projectToClose); + } + catch (Throwable e) { + exceptions.add(e); } }); } @@ -629,12 +627,9 @@ public abstract class PlatformTestCase extends UsefulTestCase implements DataPro } finally { try { - SwingUtilities.invokeAndWait(new Runnable() { - @Override - public void run() { - cleanupApplicationCaches(getProject()); - resetAllFields(); - } + SwingUtilities.invokeAndWait(() -> { + cleanupApplicationCaches(getProject()); + resetAllFields(); }); } catch (Throwable e) { @@ -644,54 +639,51 @@ public abstract class PlatformTestCase extends UsefulTestCase implements DataPro } private void runBareImpl() throws Throwable { - ThrowableRunnable runnable = new ThrowableRunnable() { - @Override - public void run() throws Throwable { - ourTestThread = Thread.currentThread(); - ourTestTime = DEFAULT_TEST_TIME; + ThrowableRunnable runnable = () -> { + ourTestThread = Thread.currentThread(); + ourTestTime = DEFAULT_TEST_TIME; + try { try { + myAssertionsInTestDetected = true; + setUp(); + myAssertionsInTestDetected = false; + } + catch (Throwable e) { try { - myAssertionsInTestDetected = true; - setUp(); - myAssertionsInTestDetected = false; + tearDown(); } - catch (Throwable e) { - try { - tearDown(); - } - catch (Throwable ignored) { - } - - throw e; + catch (Throwable ignored) { } - Throwable exception = null; - try { - myAssertionsInTestDetected = true; - runTest(); - myAssertionsInTestDetected = false; - } - catch (Throwable e) { - exception = e; - } - finally { - try { - tearDown(); - } - catch (Throwable e) { - if (exception == null) { - exception = e; - } - } - } + throw e; + } - if (exception != null) { - throw exception; - } + Throwable exception = null; + try { + myAssertionsInTestDetected = true; + runTest(); + myAssertionsInTestDetected = false; + } + catch (Throwable e) { + exception = e; } finally { - ourTestThread = null; + try { + tearDown(); + } + catch (Throwable e) { + if (exception == null) { + exception = e; + } + } } + + if (exception != null) { + throw exception; + } + } + finally { + ourTestThread = null; } }; @@ -734,21 +726,18 @@ public abstract class PlatformTestCase extends UsefulTestCase implements DataPro @Override protected void invokeTestRunnable(@NotNull final Runnable runnable) throws Exception { final Exception[] e = new Exception[1]; - Runnable runnable1 = new Runnable() { - @Override - public void run() { - try { - if (ApplicationManager.getApplication().isDispatchThread() && isRunInWriteAction()) { - ApplicationManager.getApplication().runWriteAction(runnable); - } - else { - runnable.run(); - } + Runnable runnable1 = () -> { + try { + if (ApplicationManager.getApplication().isDispatchThread() && isRunInWriteAction()) { + ApplicationManager.getApplication().runWriteAction(runnable); } - catch (Exception e1) { - e[0] = e1; + else { + runnable.run(); } } + catch (Exception e1) { + e[0] = e1; + } }; if (annotatedWith(WrapInCommand.class)) { @@ -811,13 +800,9 @@ public abstract class PlatformTestCase extends UsefulTestCase implements DataPro if (bom != null) { stream.write(bom); } - OutputStreamWriter writer = new OutputStreamWriter(stream, charset); - try { + try (OutputStreamWriter writer = new OutputStreamWriter(stream, charset)) { writer.write(content); } - finally { - writer.close(); - } } public static VirtualFile createTempFile(@NonNls @NotNull String ext, @Nullable byte[] bom, @NonNls @NotNull String content, @NotNull Charset charset) throws IOException { diff --git a/platform/testFramework/src/com/intellij/testFramework/UsefulTestCase.java b/platform/testFramework/src/com/intellij/testFramework/UsefulTestCase.java index 82b4ce285671..2f64f783002f 100644 --- a/platform/testFramework/src/com/intellij/testFramework/UsefulTestCase.java +++ b/platform/testFramework/src/com/intellij/testFramework/UsefulTestCase.java @@ -66,7 +66,6 @@ import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; -import java.security.SecureRandom; import java.util.*; import java.util.List; import java.util.concurrent.DelayQueue; @@ -84,14 +83,13 @@ public abstract class UsefulTestCase extends TestCase { public static final String IDEA_MARKER_CLASS = "com.intellij.openapi.roots.IdeaModifiableModelsProvider"; public static final String TEMP_DIR_MARKER = "unitTest_"; - protected static boolean OVERWRITE_TESTDATA = false; + protected static boolean OVERWRITE_TESTDATA; private static final String DEFAULT_SETTINGS_EXTERNALIZED; - private static final Random RNG = new SecureRandom(); private static final String ORIGINAL_TEMP_DIR = FileUtil.getTempDirectory(); - public static Map TOTAL_SETUP_COST_MILLIS = new HashMap(); - public static Map TOTAL_TEARDOWN_COST_MILLIS = new HashMap(); + private static final Map TOTAL_SETUP_COST_MILLIS = new HashMap<>(); + private static final Map TOTAL_TEARDOWN_COST_MILLIS = new HashMap<>(); @NotNull protected final Disposable myTestRootDisposable = new Disposable() { @@ -105,13 +103,13 @@ public abstract class UsefulTestCase extends TestCase { } }; - protected static String ourPathToKeep = null; - private List myPathsToKeep = new ArrayList(); + static String ourPathToKeep; + private final List myPathsToKeep = new ArrayList<>(); private CodeStyleSettings myOldCodeStyleSettings; private String myTempDir; - protected static final Key CREATION_PLACE = Key.create("CREATION_PLACE"); + static final Key CREATION_PLACE = Key.create("CREATION_PLACE"); static { // Radar #5755208: Command line Java applications need a way to launch without a Dock icon. @@ -182,7 +180,7 @@ public abstract class UsefulTestCase extends TestCase { super.tearDown(); } - protected void addTmpFileToKeep(File file) { + protected void addTmpFileToKeep(@NotNull File file) { myPathsToKeep.add(file.getPath()); } @@ -190,7 +188,7 @@ public abstract class UsefulTestCase extends TestCase { return ourPathToKeep != null && FileUtil.isAncestor(myTempDir, ourPathToKeep, false) || !myPathsToKeep.isEmpty(); } - private boolean shouldKeepTmpFile(File file) { + private boolean shouldKeepTmpFile(@NotNull File file) { String path = file.getPath(); if (FileUtil.pathsEqual(path, ourPathToKeep)) return true; for (String pathToKeep : myPathsToKeep) { @@ -214,12 +212,12 @@ public abstract class UsefulTestCase extends TestCase { DELETE_ON_EXIT_HOOK_DOT_FILES = files; } - public static void cleanupDeleteOnExitHookList() throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException { + private static void cleanupDeleteOnExitHookList() throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException { // try to reduce file set retained by java.io.DeleteOnExitHook List list; synchronized (DELETE_ON_EXIT_HOOK_CLASS) { if (DELETE_ON_EXIT_HOOK_DOT_FILES.isEmpty()) return; - list = new ArrayList(DELETE_ON_EXIT_HOOK_DOT_FILES); + list = new ArrayList<>(DELETE_ON_EXIT_HOOK_DOT_FILES); } for (int i = list.size() - 1; i >= 0; i--) { String path = list.get(i); @@ -255,7 +253,9 @@ public abstract class UsefulTestCase extends TestCase { doCheckForSettingsDamage(oldCodeStyleSettings, getCurrentCodeStyleSettings(), exceptions); } - public static void doCheckForSettingsDamage(@NotNull CodeStyleSettings oldCodeStyleSettings, @NotNull CodeStyleSettings currentCodeStyleSettings, @NotNull List exceptions) { + public static void doCheckForSettingsDamage(@NotNull CodeStyleSettings oldCodeStyleSettings, + @NotNull CodeStyleSettings currentCodeStyleSettings, + @NotNull List exceptions) { final CodeInsightSettings settings = CodeInsightSettings.getInstance(); try { Element newS = new Element("temp"); @@ -299,13 +299,14 @@ public abstract class UsefulTestCase extends TestCase { } } - protected void storeSettings() { + void storeSettings() { if (!isPerformanceTest() && ApplicationManager.getApplication() != null) { myOldCodeStyleSettings = getCurrentCodeStyleSettings().clone(); myOldCodeStyleSettings.getIndentOptions(StdFileTypes.JAVA); } } + @NotNull protected CodeStyleSettings getCurrentCodeStyleSettings() { if (CodeStyleSchemes.getInstance().getCurrentScheme() == null) return new CodeStyleSettings(); return CodeStyleSettingsManager.getInstance().getCurrentSettings(); @@ -320,23 +321,20 @@ public abstract class UsefulTestCase extends TestCase { protected void runTest() throws Throwable { final Throwable[] throwables = new Throwable[1]; - Runnable runnable = new Runnable() { - @Override - public void run() { - try { - UsefulTestCase.super.runTest(); - } - catch (InvocationTargetException e) { - e.fillInStackTrace(); - throwables[0] = e.getTargetException(); - } - catch (IllegalAccessException e) { - e.fillInStackTrace(); - throwables[0] = e; - } - catch (Throwable e) { - throwables[0] = e; - } + Runnable runnable = () -> { + try { + UsefulTestCase.super.runTest(); + } + catch (InvocationTargetException e) { + e.fillInStackTrace(); + throwables[0] = e.getTargetException(); + } + catch (IllegalAccessException e) { + e.fillInStackTrace(); + throwables[0] = e; + } + catch (Throwable e) { + throwables[0] = e; } }; @@ -391,21 +389,22 @@ public abstract class UsefulTestCase extends TestCase { * * @param cost setup cost in milliseconds */ - private void logPerClassCost(long cost, Map costMap) { + private void logPerClassCost(long cost, @NotNull Map costMap) { Class superclass = getClass().getSuperclass(); Long oldCost = costMap.get(superclass.getName()); long newCost = oldCost == null ? cost : oldCost + cost; costMap.put(superclass.getName(), newCost); } - public static void logSetupTeardownCosts() { - long totalSetup = 0, totalTeardown = 0; + static void logSetupTeardownCosts() { System.out.println("Setup costs"); + long totalSetup = 0; for (Map.Entry entry : TOTAL_SETUP_COST_MILLIS.entrySet()) { System.out.println(String.format(" %s: %d ms", entry.getKey(), entry.getValue())); totalSetup += entry.getValue(); } System.out.println("Teardown costs"); + long totalTeardown = 0; for (Map.Entry entry : TOTAL_TEARDOWN_COST_MILLIS.entrySet()) { System.out.println(String.format(" %s: %d ms", entry.getKey(), entry.getValue())); totalTeardown += entry.getValue(); @@ -421,12 +420,7 @@ public abstract class UsefulTestCase extends TestCase { if (runInDispatchThread()) { TestRunnerUtil.replaceIdeEventQueueSafely(); - EdtTestUtil.runInEdtAndWait(new ThrowableRunnable() { - @Override - public void run() throws Throwable { - defaultRunBare(); - } - }); + EdtTestUtil.runInEdtAndWait((ThrowableRunnable)this::defaultRunBare); } else { defaultRunBare(); @@ -438,7 +432,7 @@ public abstract class UsefulTestCase extends TestCase { } @NonNls - public static String toString(Iterable collection) { + public static String toString(@NotNull Iterable collection) { if (!collection.iterator().hasNext()) { return ""; } @@ -446,7 +440,7 @@ public abstract class UsefulTestCase extends TestCase { final StringBuilder builder = new StringBuilder(); for (final Object o : collection) { if (o instanceof THashSet) { - builder.append(new TreeSet((THashSet)o)); + builder.append(new TreeSet<>((THashSet)o)); } else { builder.append(o); @@ -456,11 +450,13 @@ public abstract class UsefulTestCase extends TestCase { return builder.toString(); } - public static void assertOrderedEquals(T[] actual, T... expected) { + @SafeVarargs + public static void assertOrderedEquals(@NotNull T[] actual, @NotNull T... expected) { assertOrderedEquals(Arrays.asList(actual), expected); } - public static void assertOrderedEquals(Iterable actual, T... expected) { + @SafeVarargs + public static void assertOrderedEquals(@NotNull Iterable actual, @NotNull T... expected) { assertOrderedEquals(null, actual, expected); } @@ -484,20 +480,19 @@ public abstract class UsefulTestCase extends TestCase { } } + @SafeVarargs public static void assertOrderedEquals(final String errorMsg, @NotNull Iterable actual, @NotNull T... expected) { - Assert.assertNotNull(actual); - Assert.assertNotNull(expected); assertOrderedEquals(errorMsg, actual, Arrays.asList(expected)); } - public static void assertOrderedEquals(final Iterable actual, final Collection expected) { + public static void assertOrderedEquals(@NotNull Iterable actual, @NotNull Collection expected) { assertOrderedEquals(null, actual, expected); } public static void assertOrderedEquals(final String erroMsg, - final Iterable actual, - final Collection expected) { - ArrayList list = new ArrayList(); + @NotNull Iterable actual, + @NotNull Collection expected) { + List list = new ArrayList<>(); for (T t : actual) { list.add(t); } @@ -509,67 +504,72 @@ public abstract class UsefulTestCase extends TestCase { } } - public static void assertOrderedCollection(T[] collection, @NotNull Consumer... checkers) { - Assert.assertNotNull(collection); + @SafeVarargs + public static void assertOrderedCollection(@NotNull T[] collection, @NotNull Consumer... checkers) { assertOrderedCollection(Arrays.asList(collection), checkers); } - public static void assertSameElements(T[] collection, T... expected) { + @SafeVarargs + public static void assertSameElements(@NotNull T[] collection, @NotNull T... expected) { assertSameElements(Arrays.asList(collection), expected); } - public static void assertSameElements(Collection collection, T... expected) { + @SafeVarargs + public static void assertSameElements(@NotNull Collection collection, @NotNull T... expected) { assertSameElements(collection, Arrays.asList(expected)); } - public static void assertSameElements(Collection collection, Collection expected) { + public static void assertSameElements(@NotNull Collection collection, @NotNull Collection expected) { assertSameElements(null, collection, expected); } - public static void assertSameElements(String message, Collection collection, Collection expected) { - assertNotNull(collection); - assertNotNull(expected); - if (collection.size() != expected.size() || !new HashSet(expected).equals(new HashSet(collection))) { + public static void assertSameElements(String message, @NotNull Collection collection, @NotNull Collection expected) { + if (collection.size() != expected.size() || !new HashSet<>(expected).equals(new HashSet(collection))) { Assert.assertEquals(message, toString(expected, "\n"), toString(collection, "\n")); - Assert.assertEquals(message, new HashSet(expected), new HashSet(collection)); + Assert.assertEquals(message, new HashSet<>(expected), new HashSet(collection)); } } - public static void assertContainsOrdered(Collection collection, T... expected) { + @SafeVarargs + public static void assertContainsOrdered(@NotNull Collection collection, @NotNull T... expected) { assertContainsOrdered(collection, Arrays.asList(expected)); } - public static void assertContainsOrdered(Collection collection, Collection expected) { - ArrayList copy = new ArrayList(collection); + public static void assertContainsOrdered(@NotNull Collection collection, @NotNull Collection expected) { + ArrayList copy = new ArrayList<>(collection); copy.retainAll(expected); assertOrderedEquals(toString(collection), copy, expected); } - public static void assertContainsElements(Collection collection, T... expected) { + @SafeVarargs + public static void assertContainsElements(@NotNull Collection collection, @NotNull T... expected) { assertContainsElements(collection, Arrays.asList(expected)); } - public static void assertContainsElements(Collection collection, Collection expected) { - ArrayList copy = new ArrayList(collection); + public static void assertContainsElements(@NotNull Collection collection, @NotNull Collection expected) { + ArrayList copy = new ArrayList<>(collection); copy.retainAll(expected); assertSameElements(toString(collection), copy, expected); } - public static String toString(Object[] collection, String separator) { + @NotNull + public static String toString(@NotNull Object[] collection, @NotNull String separator) { return toString(Arrays.asList(collection), separator); } - public static void assertDoesntContain(Collection collection, T... notExpected) { + @SafeVarargs + public static void assertDoesntContain(@NotNull Collection collection, @NotNull T... notExpected) { assertDoesntContain(collection, Arrays.asList(notExpected)); } - public static void assertDoesntContain(Collection collection, Collection notExpected) { - ArrayList expected = new ArrayList(collection); + public static void assertDoesntContain(@NotNull Collection collection, @NotNull Collection notExpected) { + ArrayList expected = new ArrayList<>(collection); expected.removeAll(notExpected); assertSameElements(collection, expected); } - public static String toString(Collection collection, String separator) { + @NotNull + public static String toString(@NotNull Collection collection, @NotNull String separator) { List list = ContainerUtil.map2List(collection, new Function() { @Override public String fun(final Object o) { @@ -589,8 +589,8 @@ public abstract class UsefulTestCase extends TestCase { return builder.toString(); } - public static void assertOrderedCollection(Collection collection, Consumer... checkers) { - Assert.assertNotNull(collection); + @SafeVarargs + public static void assertOrderedCollection(@NotNull Collection collection, @NotNull Consumer... checkers) { if (collection.size() != checkers.length) { Assert.fail(toString(collection)); } @@ -607,16 +607,17 @@ public abstract class UsefulTestCase extends TestCase { } } - public static void assertUnorderedCollection(T[] collection, Consumer... checkers) { + @SafeVarargs + public static void assertUnorderedCollection(@NotNull T[] collection, @NotNull Consumer... checkers) { assertUnorderedCollection(Arrays.asList(collection), checkers); } - public static void assertUnorderedCollection(Collection collection, Consumer... checkers) { - Assert.assertNotNull(collection); + @SafeVarargs + public static void assertUnorderedCollection(@NotNull Collection collection, @NotNull Consumer... checkers) { if (collection.size() != checkers.length) { Assert.fail(toString(collection)); } - Set> checkerSet = new HashSet>(Arrays.asList(checkers)); + Set> checkerSet = new HashSet<>(Arrays.asList(checkers)); int i = 0; Throwable lastError = null; for (final T actual : collection) { @@ -640,7 +641,7 @@ public abstract class UsefulTestCase extends TestCase { } } - private static Throwable accepts(final Consumer condition, final T actual) { + private static Throwable accepts(@NotNull Consumer condition, final T actual) { try { condition.consume(actual); return null; @@ -651,15 +652,14 @@ public abstract class UsefulTestCase extends TestCase { } @Contract("null, _ -> fail") - public static T assertInstanceOf(Object o, Class aClass) { + public static T assertInstanceOf(Object o, @NotNull Class aClass) { Assert.assertNotNull("Expected instance of: " + aClass.getName() + " actual: " + null, o); Assert.assertTrue("Expected instance of: " + aClass.getName() + " actual: " + o.getClass().getName(), aClass.isInstance(o)); @SuppressWarnings("unchecked") T t = (T)o; return t; } - public static T assertOneElement(Collection collection) { - Assert.assertNotNull(collection); + public static T assertOneElement(@NotNull Collection collection) { Iterator iterator = collection.iterator(); String toString = toString(collection); Assert.assertTrue(toString, iterator.hasNext()); @@ -668,14 +668,14 @@ public abstract class UsefulTestCase extends TestCase { return t; } - public static T assertOneElement(T[] ts) { - Assert.assertNotNull(ts); + public static T assertOneElement(@NotNull T[] ts) { Assert.assertEquals(Arrays.asList(ts).toString(), 1, ts.length); return ts[0]; } + @SafeVarargs @Contract("null, _ -> fail") - public static void assertOneOf(T value, T... values) { + public static void assertOneOf(T value, @NotNull T... values) { boolean found = false; for (T v : values) { if (value == v || value != null && value.equals(v)) { @@ -689,7 +689,7 @@ public abstract class UsefulTestCase extends TestCase { PerformanceWatcher.dumpThreadsToConsole("Thread dump:"); } - public static void assertEmpty(final Object[] array) { + public static void assertEmpty(@NotNull Object[] array) { assertOrderedEquals(array); } @@ -698,10 +698,11 @@ public abstract class UsefulTestCase extends TestCase { assertTrue(!collection.isEmpty()); } - public static void assertEmpty(final Collection collection) { + public static void assertEmpty(@NotNull Collection collection) { assertEmpty(collection.toString(), collection); } - public static void assertNullOrEmpty(final Collection collection) { + + public static void assertNullOrEmpty(@Nullable Collection collection) { if (collection == null) return; assertEmpty(null, collection); } @@ -711,7 +712,7 @@ public abstract class UsefulTestCase extends TestCase { } public static void assertEmpty(final String errorMsg, final Collection collection) { - assertOrderedEquals(errorMsg, collection); + assertOrderedEquals(errorMsg, collection, Collections.emptyList()); } public static void assertSize(int expectedSize, final Object[] array) { @@ -733,18 +734,20 @@ public abstract class UsefulTestCase extends TestCase { Assert.assertEquals(expectedText, actualText); } - public static void assertExists(File file){ + public static void assertExists(@NotNull File file){ assertTrue("File should exist " + file, file.exists()); } - public static void assertDoesntExist(File file){ + public static void assertDoesntExist(@NotNull File file){ assertFalse("File should not exist " + file, file.exists()); } + @NotNull protected String getTestName(boolean lowercaseFirstLetter) { return getTestName(getName(), lowercaseFirstLetter); } + @NotNull public static String getTestName(String name, boolean lowercaseFirstLetter) { return name == null ? "" : PlatformTestUtil.getTestName(name, lowercaseFirstLetter); } @@ -793,7 +796,7 @@ public abstract class UsefulTestCase extends TestCase { } } - public static void clearFields(final Object test) throws IllegalAccessException { + protected static void clearFields(@NotNull Object test) throws IllegalAccessException { Class aClass = test.getClass(); while (aClass != null) { clearDeclaredFields(test, aClass); @@ -816,7 +819,7 @@ public abstract class UsefulTestCase extends TestCase { } @SuppressWarnings("deprecation") - protected static void checkSettingsEqual(CodeStyleSettings expected, CodeStyleSettings settings, String message) throws Exception { + private static void checkSettingsEqual(CodeStyleSettings expected, CodeStyleSettings settings, String message) throws Exception { if (expected == null || settings == null) return; Element oldS = new Element("temp"); @@ -835,12 +838,9 @@ public abstract class UsefulTestCase extends TestCase { } public static void doPostponedFormatting(final Project project) { - DocumentUtil.writeInRunUndoTransparentAction(new Runnable() { - @Override - public void run() { - PsiDocumentManager.getInstance(project).commitAllDocuments(); - PostprocessReformattingAspect.getInstance(project).doPostponedFormatting(); - } + DocumentUtil.writeInRunUndoTransparentAction(() -> { + PsiDocumentManager.getInstance(project).commitAllDocuments(); + PostprocessReformattingAspect.getInstance(project).doPostponedFormatting(); }); } @@ -881,7 +881,6 @@ public abstract class UsefulTestCase extends TestCase { * * @param exceptionCase Block annotated with some exception type * @param expectedErrorMsg expected error messge - * @throws Throwable */ protected void assertException(final AbstractExceptionCase exceptionCase, @Nullable final String expectedErrorMsg) throws Throwable { @@ -892,7 +891,6 @@ public abstract class UsefulTestCase extends TestCase { * Checks that code block doesn't throw corresponding exception. * * @param exceptionCase Block annotated with some exception type - * @throws Throwable */ protected void assertNoException(final AbstractExceptionCase exceptionCase) throws Throwable { assertExceptionOccurred(false, exceptionCase, null); @@ -1005,12 +1003,7 @@ public abstract class UsefulTestCase extends TestCase { @Nullable public static VirtualFile refreshAndFindFile(@NotNull final File file) { - return UIUtil.invokeAndWaitIfNeeded(new Computable() { - @Override - public VirtualFile compute() { - return LocalFileSystem.getInstance().refreshAndFindFileByIoFile(file); - } - }); + return UIUtil.invokeAndWaitIfNeeded(() -> LocalFileSystem.getInstance().refreshAndFindFileByIoFile(file)); } public static void invokeAndWaitIfNeeded(@NotNull final ThrowableRunnable runnable) throws Exception { @@ -1019,15 +1012,12 @@ public abstract class UsefulTestCase extends TestCase { } else { final Ref ref = Ref.create(); - SwingUtilities.invokeAndWait(new Runnable() { - @Override - public void run() { - try { - runnable.run(); - } - catch (Exception e) { - ref.set(e); - } + SwingUtilities.invokeAndWait(() -> { + try { + runnable.run(); + } + catch (Exception e) { + ref.set(e); } }); if (!ref.isNull()) throw ref.get(); diff --git a/plugins/git4idea/tests/git4idea/push/GitPushOperationSingleRepoTest.kt b/plugins/git4idea/tests/git4idea/push/GitPushOperationSingleRepoTest.kt index d04c31a008bd..7cd681c02e13 100644 --- a/plugins/git4idea/tests/git4idea/push/GitPushOperationSingleRepoTest.kt +++ b/plugins/git4idea/tests/git4idea/push/GitPushOperationSingleRepoTest.kt @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -469,7 +469,7 @@ class GitPushOperationSingleRepoTest : GitPushOperationBaseTest() { getUpdatedFiles(actualResult.updatedFiles), ContainerUtil.notNullize(updatedFiles)) } - private fun getUpdatedFiles(updatedFiles: UpdatedFiles): Collection? { + private fun getUpdatedFiles(updatedFiles: UpdatedFiles): Collection { val result = ContainerUtil.newArrayList() for (group in updatedFiles.topLevelGroups) { result.addAll(getUpdatedFiles(group))