diff --git a/compiler/tests/org/jetbrains/kotlin/test/testFramework/AbstractExceptionCase.java b/compiler/tests/org/jetbrains/kotlin/test/testFramework/AbstractExceptionCase.java deleted file mode 100644 index ca806ad6eca..00000000000 --- a/compiler/tests/org/jetbrains/kotlin/test/testFramework/AbstractExceptionCase.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright 2010-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 org.jetbrains.kotlin.test.testFramework; - -/** - * Base class of block, annotated with exception. Inheritors of this - * class specifies concrete Exception classes - */ -public abstract class AbstractExceptionCase { - - public abstract Class getExpectedExceptionClass(); - - /** - * Suspicious code must be in implementation of this closure - * @throws T - */ - public abstract void tryClosure() throws T; - - public String getAssertionErrorMessage() { - return getExpectedExceptionClass().getName() + " must be thrown."; - } -} diff --git a/compiler/tests/org/jetbrains/kotlin/test/testFramework/EdtTestUtil.kt b/compiler/tests/org/jetbrains/kotlin/test/testFramework/EdtTestUtil.kt index e9452a6caf5..7e43d3a86d1 100644 --- a/compiler/tests/org/jetbrains/kotlin/test/testFramework/EdtTestUtil.kt +++ b/compiler/tests/org/jetbrains/kotlin/test/testFramework/EdtTestUtil.kt @@ -23,10 +23,6 @@ import javax.swing.SwingUtilities class EdtTestUtil { companion object { - @TestOnly @JvmStatic fun runInEdtAndWait(runnable: ThrowableRunnable) { - runInEdtAndWait { runnable.run() } - } - @TestOnly @JvmStatic fun runInEdtAndWait(runnable: Runnable) { runInEdtAndWait { runnable.run() } } diff --git a/compiler/tests/org/jetbrains/kotlin/test/testFramework/KtParsingTestCase.java b/compiler/tests/org/jetbrains/kotlin/test/testFramework/KtParsingTestCase.java index 2ac52fd9029..a7f88ccc3e3 100644 --- a/compiler/tests/org/jetbrains/kotlin/test/testFramework/KtParsingTestCase.java +++ b/compiler/tests/org/jetbrains/kotlin/test/testFramework/KtParsingTestCase.java @@ -1,5 +1,5 @@ /* - * Copyright 2010-2016 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. @@ -19,7 +19,8 @@ package org.jetbrains.kotlin.test.testFramework; import com.intellij.core.CoreASTFactory; import com.intellij.lang.*; import com.intellij.lang.impl.PsiBuilderFactoryImpl; -import com.intellij.mock.*; +import com.intellij.mock.MockFileDocumentManagerImpl; +import com.intellij.openapi.Disposable; import com.intellij.openapi.application.PathManager; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.EditorFactory; @@ -51,6 +52,7 @@ import com.intellij.psi.impl.source.text.BlockSupportImpl; import com.intellij.psi.impl.source.text.DiffLog; import com.intellij.psi.util.CachedValuesManager; import com.intellij.testFramework.LightVirtualFile; +import com.intellij.testFramework.TestDataFile; import com.intellij.util.CachedValuesManagerImpl; import com.intellij.util.Function; import com.intellij.util.messages.MessageBus; @@ -59,18 +61,17 @@ import junit.framework.TestCase; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.kotlin.test.testFramework.mock.*; +import org.picocontainer.ComponentAdapter; import org.picocontainer.MutablePicoContainer; import java.io.File; import java.io.IOException; -import java.util.Iterator; import java.util.Set; @SuppressWarnings("ALL") public abstract class KtParsingTestCase extends KtPlatformLiteFixture { public static final Key HARD_REF_TO_DOCUMENT_KEY = Key.create("HARD_REF_TO_DOCUMENT_KEY"); - - protected String myFilePrefix; + protected String myFilePrefix = ""; protected String myFileExt; protected final String myFullDataPath; protected PsiFile myFile; @@ -85,74 +86,62 @@ public abstract class KtParsingTestCase extends KtPlatformLiteFixture { } protected KtParsingTestCase(@NonNls @NotNull String dataPath, @NotNull String fileExt, boolean lowercaseFirstLetter, @NotNull ParserDefinition... definitions) { - this.myFilePrefix = ""; - this.myDefinitions = definitions; - this.myFullDataPath = this.getTestDataPath() + "/" + dataPath; - this.myFileExt = fileExt; - this.myLowercaseFirstLetter = lowercaseFirstLetter; + myDefinitions = definitions; + myFullDataPath = getTestDataPath() + "/" + dataPath; + myFileExt = fileExt; + myLowercaseFirstLetter = lowercaseFirstLetter; } + @Override protected void setUp() throws Exception { super.setUp(); - this.initApplication(); - //ComponentAdapter component = getApplication().getPicoContainer().getComponentAdapter(ProgressManager.class.getName()); - //if(component == null) { - // getApplication().getPicoContainer().registerComponent(new AbstractComponentAdapter(ProgressManager.class.getName(), Object.class) { - // public Object getComponentInstance(PicoContainer container) throws PicoInitializationException, PicoIntrospectionException { - // return new ProgressManagerImpl(); - // } - // - // public void verify(PicoContainer container) throws PicoIntrospectionException { - // } - // }); - //} + initApplication(); + ComponentAdapter component = getApplication().getPicoContainer().getComponentAdapter(ProgressManager.class.getName()); - Extensions.registerAreaClass("IDEA_PROJECT", (String)null); - this.myProject = new MockProjectEx(this.getTestRootDisposable()); - this.myPsiManager = new MockPsiManager(this.myProject); - this.myFileFactory = new PsiFileFactoryImpl(this.myPsiManager); + Extensions.registerAreaClass("IDEA_PROJECT", null); + myProject = new MockProjectEx(getTestRootDisposable()); + myPsiManager = new MockPsiManager(myProject); + myFileFactory = new PsiFileFactoryImpl(myPsiManager); MutablePicoContainer appContainer = getApplication().getPicoContainer(); registerComponentInstance(appContainer, MessageBus.class, MessageBusFactory.newMessageBus(getApplication())); registerComponentInstance(appContainer, SchemesManagerFactory.class, new MockSchemesManagerFactory()); final MockEditorFactory editorFactory = new MockEditorFactory(); registerComponentInstance(appContainer, EditorFactory.class, editorFactory); registerComponentInstance(appContainer, FileDocumentManager.class, new MockFileDocumentManagerImpl(new Function() { + @Override public Document fun(CharSequence charSequence) { return editorFactory.createDocument(charSequence); } }, HARD_REF_TO_DOCUMENT_KEY)); registerComponentInstance(appContainer, PsiDocumentManager.class, new MockPsiDocumentManager()); - this.registerApplicationService(PsiBuilderFactory.class, new PsiBuilderFactoryImpl()); - this.registerApplicationService(DefaultASTFactory.class, new CoreASTFactory()); - this.registerApplicationService(ReferenceProvidersRegistry.class, new ReferenceProvidersRegistryImpl()); + registerApplicationService(PsiBuilderFactory.class, new PsiBuilderFactoryImpl()); + registerApplicationService(DefaultASTFactory.class, new CoreASTFactory()); + registerApplicationService(ReferenceProvidersRegistry.class, new ReferenceProvidersRegistryImpl()); registerApplicationService(ProgressManager.class, new CoreProgressManager()); - this.myProject.registerService(CachedValuesManager.class, new CachedValuesManagerImpl(this.myProject, new PsiCachedValuesFactory(this.myPsiManager))); - this.myProject.registerService(PsiManager.class, this.myPsiManager); - //this.myProject.registerService(StartupManager.class, new StartupManagerImpl(this.myProject)); + myProject.registerService(CachedValuesManager.class, new CachedValuesManagerImpl(myProject, new PsiCachedValuesFactory(myPsiManager))); + myProject.registerService(PsiManager.class, myPsiManager); + this.registerExtensionPoint(FileTypeFactory.FILE_TYPE_FACTORY_EP, FileTypeFactory.class); - ParserDefinition[] pomModel = this.myDefinitions; - int var5 = pomModel.length; - for(int var6 = 0; var6 < var5; ++var6) { - ParserDefinition definition = pomModel[var6]; - this.addExplicitExtension(LanguageParserDefinitions.INSTANCE, definition.getFileNodeType().getLanguage(), definition); + for (ParserDefinition definition : myDefinitions) { + addExplicitExtension(LanguageParserDefinitions.INSTANCE, definition.getFileNodeType().getLanguage(), definition); + } + if (myDefinitions.length > 0) { + configureFromParserDefinition(myDefinitions[0], myFileExt); } - if(this.myDefinitions.length > 0) { - this.configureFromParserDefinition(this.myDefinitions[0], this.myFileExt); - } - - PomModelImpl var8 = new PomModelImpl(this.myProject); - this.myProject.registerService(PomModel.class, var8); - new TreeAspect(var8); + // That's for reparse routines + final PomModelImpl pomModel = new PomModelImpl(myProject); + myProject.registerService(PomModel.class, pomModel); + new TreeAspect(pomModel); } public void configureFromParserDefinition(ParserDefinition definition, String extension) { - this.myLanguage = definition.getFileNodeType().getLanguage(); - this.myFileExt = extension; - this.addExplicitExtension(LanguageParserDefinitions.INSTANCE, this.myLanguage, definition); + myLanguage = definition.getFileNodeType().getLanguage(); + myFileExt = extension; + addExplicitExtension(LanguageParserDefinitions.INSTANCE, this.myLanguage, definition); registerComponentInstance( getApplication().getPicoContainer(), FileTypeManager.class, new KtMockFileTypeManager(new KtMockLanguageFileType(myLanguage, myFileExt))); @@ -160,16 +149,19 @@ public abstract class KtParsingTestCase extends KtPlatformLiteFixture { protected void addExplicitExtension(final LanguageExtension instance, final Language language, final T object) { instance.addExplicitExtension(language, object); - Disposer.register(this.myProject, new com.intellij.openapi.Disposable() { + Disposer.register(myProject, new Disposable() { + @Override public void dispose() { instance.removeExplicitExtension(language, object); } }); } + @Override protected void registerExtensionPoint(final ExtensionPointName extensionPointName, Class aClass) { super.registerExtensionPoint(extensionPointName, aClass); - Disposer.register(this.myProject, new com.intellij.openapi.Disposable() { + Disposer.register(myProject, new Disposable() { + @Override public void dispose() { Extensions.getRootArea().unregisterExtensionPoint(extensionPointName.getName()); } @@ -178,36 +170,37 @@ public abstract class KtParsingTestCase extends KtPlatformLiteFixture { protected void registerApplicationService(final Class aClass, T object) { getApplication().registerService(aClass, object); - Disposer.register(this.myProject, new com.intellij.openapi.Disposable() { + Disposer.register(myProject, new Disposable() { + @Override public void dispose() { - KtPlatformLiteFixture.getApplication().getPicoContainer().unregisterComponent(aClass.getName()); + getApplication().getPicoContainer().unregisterComponent(aClass.getName()); } }); } public MockProjectEx getProject() { - return this.myProject; + return myProject; } public MockPsiManager getPsiManager() { - return this.myPsiManager; + return myPsiManager; } + @Override protected void tearDown() throws Exception { super.tearDown(); - this.myFile = null; - this.myProject = null; - this.myPsiManager = null; + myFile = null; + myProject = null; + myPsiManager = null; } protected String getTestDataPath() { return PathManager.getHomePath(); - //return PathManagerEx.getTestDataPath(); } @NotNull public final String getTestName() { - return this.getTestName(this.myLowercaseFirstLetter); + return getTestName(myLowercaseFirstLetter); } protected boolean includeRanges() { @@ -223,88 +216,91 @@ public abstract class KtParsingTestCase extends KtPlatformLiteFixture { } protected void doTest(boolean checkResult) { - String name = this.getTestName(); - + String name = getTestName(); try { - String e = this.loadFile(name + "." + this.myFileExt); - this.myFile = this.createPsiFile(name, e); - ensureParsed(this.myFile); - assertEquals("light virtual file text mismatch", e, ((LightVirtualFile)this.myFile.getVirtualFile()).getContent().toString()); - assertEquals("virtual file text mismatch", e, LoadTextUtil.loadText(this.myFile.getVirtualFile())); - assertEquals("doc text mismatch", e, this.myFile.getViewProvider().getDocument().getText()); - assertEquals("psi text mismatch", e, this.myFile.getText()); - ensureCorrectReparse(this.myFile); - if(checkResult) { - this.checkResult(name, this.myFile); - } else { - toParseTreeText(this.myFile, this.skipSpaces(), this.includeRanges()); + String text = loadFile(name + "." + myFileExt); + myFile = createPsiFile(name, text); + ensureParsed(myFile); + assertEquals("light virtual file text mismatch", text, ((LightVirtualFile)myFile.getVirtualFile()).getContent().toString()); + assertEquals("virtual file text mismatch", text, LoadTextUtil.loadText(myFile.getVirtualFile())); + assertEquals("doc text mismatch", text, myFile.getViewProvider().getDocument().getText()); + assertEquals("psi text mismatch", text, myFile.getText()); + ensureCorrectReparse(myFile); + if (checkResult){ + checkResult(name, myFile); } - - } catch (IOException var4) { - throw new RuntimeException(var4); + else{ + toParseTreeText(myFile, skipSpaces(), includeRanges()); + } + } + catch (IOException e) { + throw new RuntimeException(e); } } protected void doTest(String suffix) throws IOException { - String name = this.getTestName(); - String text = this.loadFile(name + "." + this.myFileExt); - this.myFile = this.createPsiFile(name, text); - ensureParsed(this.myFile); - assertEquals(text, this.myFile.getText()); - this.checkResult(name + suffix, this.myFile); + String name = getTestName(); + String text = loadFile(name + "." + myFileExt); + myFile = createPsiFile(name, text); + ensureParsed(myFile); + assertEquals(text, myFile.getText()); + checkResult(name + suffix, myFile); } protected void doCodeTest(String code) throws IOException { - String name = this.getTestName(); - this.myFile = this.createPsiFile("a", code); - ensureParsed(this.myFile); - assertEquals(code, this.myFile.getText()); - this.checkResult(this.myFilePrefix + name, this.myFile); + String name = getTestName(); + myFile = createPsiFile("a", code); + ensureParsed(myFile); + assertEquals(code, myFile.getText()); + checkResult(myFilePrefix + name, myFile); } protected PsiFile createPsiFile(String name, String text) { - return this.createFile(name + "." + this.myFileExt, text); + return createFile(name + "." + myFileExt, text); } protected PsiFile createFile(@NonNls String name, String text) { - LightVirtualFile virtualFile = new LightVirtualFile(name, this.myLanguage, text); + LightVirtualFile virtualFile = new LightVirtualFile(name, myLanguage, text); virtualFile.setCharset(CharsetToolkit.UTF8_CHARSET); - return this.createFile(virtualFile); + return createFile(virtualFile); } protected PsiFile createFile(LightVirtualFile virtualFile) { - return this.myFileFactory.trySetupPsiForFile(virtualFile, this.myLanguage, true, false); + return myFileFactory.trySetupPsiForFile(virtualFile, myLanguage, true, false); } - protected void checkResult(@NonNls String targetDataName, PsiFile file) throws IOException { - doCheckResult(this.myFullDataPath, file, this.checkAllPsiRoots(), targetDataName, this.skipSpaces(), this.includeRanges()); + protected void checkResult(@NonNls @TestDataFile String targetDataName, final PsiFile file) throws IOException { + doCheckResult(myFullDataPath, file, checkAllPsiRoots(), targetDataName, skipSpaces(), includeRanges()); } - public static void doCheckResult(String testDataDir, PsiFile file, boolean checkAllPsiRoots, String targetDataName, boolean skipSpaces, boolean printRanges) throws IOException { + public static void doCheckResult(String testDataDir, + PsiFile file, + boolean checkAllPsiRoots, + String targetDataName, + boolean skipSpaces, + boolean printRanges) throws IOException { FileViewProvider provider = file.getViewProvider(); - Set languages = provider.getLanguages(); - if(checkAllPsiRoots && languages.size() != 1) { - Iterator var8 = languages.iterator(); + Set languages = provider.getLanguages(); - while(var8.hasNext()) { - Language language = (Language)var8.next(); - PsiFile root = provider.getPsi(language); - String expectedName = targetDataName + "." + language.getID() + ".txt"; - doCheckResult(testDataDir, expectedName, toParseTreeText(root, skipSpaces, printRanges).trim()); - } - - } else { + if (!checkAllPsiRoots || languages.size() == 1) { doCheckResult(testDataDir, targetDataName + ".txt", toParseTreeText(file, skipSpaces, printRanges).trim()); + return; + } + + for (Language language : languages) { + PsiFile root = provider.getPsi(language); + String expectedName = targetDataName + "." + language.getID() + ".txt"; + doCheckResult(testDataDir, expectedName, toParseTreeText(root, skipSpaces, printRanges).trim()); } } protected void checkResult(String actual) throws IOException { - String name = this.getTestName(); - doCheckResult(this.myFullDataPath, this.myFilePrefix + name + ".txt", actual); + String name = getTestName(); + doCheckResult(myFullDataPath, myFilePrefix + name + ".txt", actual); } - protected void checkResult(@NonNls String targetDataName, String actual) throws IOException { - doCheckResult(this.myFullDataPath, targetDataName, actual); + protected void checkResult(@TestDataFile @NonNls String targetDataName, String actual) throws IOException { + doCheckResult(myFullDataPath, targetDataName, actual); } public static void doCheckResult(String fullPath, String targetDataName, String actual) throws IOException { @@ -312,20 +308,21 @@ public abstract class KtParsingTestCase extends KtPlatformLiteFixture { KtUsefulTestCase.assertSameLinesWithFile(expectedFileName, actual); } - protected static String toParseTreeText(PsiElement file, boolean skipSpaces, boolean printRanges) { + protected static String toParseTreeText(PsiElement file, boolean skipSpaces, boolean printRanges) { return DebugUtil.psiToString(file, skipSpaces, printRanges); } - protected String loadFile(@NonNls String name) throws IOException { - return loadFileDefault(this.myFullDataPath, name); + protected String loadFile(@NonNls @TestDataFile String name) throws IOException { + return loadFileDefault(myFullDataPath, name); } public static String loadFileDefault(String dir, String name) throws IOException { - return FileUtil.loadFile(new File(dir, name), "UTF-8", true).trim(); + return FileUtil.loadFile(new File(dir, name), CharsetToolkit.UTF8, true).trim(); } public static void ensureParsed(PsiFile file) { file.accept(new PsiElementVisitor() { + @Override public void visitElement(PsiElement element) { element.acceptChildren(this); } @@ -337,6 +334,7 @@ public abstract class KtParsingTestCase extends KtPlatformLiteFixture { String fileText = file.getText(); DiffLog diffLog = (new BlockSupportImpl(file.getProject())).reparseRange(file, TextRange.allOf(fileText), fileText, new EmptyProgressIndicator(), fileText); diffLog.performActualPsiChange(file); + TestCase.assertEquals(psiToStringDefault, DebugUtil.psiToString(file, false, false)); } } \ No newline at end of file diff --git a/compiler/tests/org/jetbrains/kotlin/test/testFramework/KtPlatformLiteFixture.java b/compiler/tests/org/jetbrains/kotlin/test/testFramework/KtPlatformLiteFixture.java index a3aaaed9e93..cab7a35be5d 100644 --- a/compiler/tests/org/jetbrains/kotlin/test/testFramework/KtPlatformLiteFixture.java +++ b/compiler/tests/org/jetbrains/kotlin/test/testFramework/KtPlatformLiteFixture.java @@ -1,5 +1,5 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. + * Copyright 2000-2014 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. @@ -19,7 +19,6 @@ package org.jetbrains.kotlin.test.testFramework; import com.intellij.core.CoreEncodingProjectManager; import com.intellij.mock.MockApplicationEx; import com.intellij.openapi.application.ApplicationManager; -import com.intellij.openapi.components.ComponentManager; import com.intellij.openapi.extensions.ExtensionPoint; import com.intellij.openapi.extensions.ExtensionPointName; import com.intellij.openapi.extensions.Extensions; @@ -28,76 +27,63 @@ import com.intellij.openapi.fileTypes.FileTypeManager; import com.intellij.openapi.fileTypes.FileTypeRegistry; import com.intellij.openapi.util.Getter; import com.intellij.openapi.vfs.encoding.EncodingManager; -import org.jetbrains.annotations.NotNull; import org.picocontainer.MutablePicoContainer; -@SuppressWarnings("ALL") +import java.lang.reflect.Modifier; + public abstract class KtPlatformLiteFixture extends KtUsefulTestCase { protected MockProjectEx myProject; - public KtPlatformLiteFixture() { - } - + @Override protected void setUp() throws Exception { super.setUp(); - Extensions.cleanRootArea(this.getTestRootDisposable()); + Extensions.cleanRootArea(getTestRootDisposable()); } public static MockApplicationEx getApplication() { - return (MockApplicationEx) ApplicationManager.getApplication(); + return (MockApplicationEx)ApplicationManager.getApplication(); } public void initApplication() { - MockApplicationEx instance = new MockApplicationEx(this.getTestRootDisposable()); - ApplicationManager.setApplication(instance, new Getter() { - public FileTypeRegistry get() { - return FileTypeManager.getInstance(); - } - }, this.getTestRootDisposable()); + MockApplicationEx instance = new MockApplicationEx(getTestRootDisposable()); + ApplicationManager.setApplication(instance, + new Getter() { + @Override + public FileTypeRegistry get() { + return FileTypeManager.getInstance(); + } + }, + getTestRootDisposable()); getApplication().registerService(EncodingManager.class, CoreEncodingProjectManager.class); } + @Override protected void tearDown() throws Exception { super.tearDown(); clearFields(this); - this.myProject = null; - } - - protected void registerExtension(ExtensionPointName extensionPointName, @NotNull T t) { - this.registerExtension(Extensions.getRootArea(), extensionPointName, t); - } - - public void registerExtension(ExtensionsArea area, ExtensionPointName name, T t) { - this.registerExtensionPoint(area, name, (Class) t.getClass()); - KtPlatformTestUtil.registerExtension(area, name, t, this.myTestRootDisposable); + myProject = null; } protected void registerExtensionPoint(ExtensionPointName extensionPointName, Class aClass) { - this.registerExtensionPoint(Extensions.getRootArea(), extensionPointName, aClass); + registerExtensionPoint(Extensions.getRootArea(), extensionPointName, aClass); } - protected void registerExtensionPoint(ExtensionsArea area, ExtensionPointName extensionPointName, Class aClass) { + private static void registerExtensionPoint( + ExtensionsArea area, ExtensionPointName extensionPointName, + Class aClass + ) { String name = extensionPointName.getName(); - if(!area.hasExtensionPoint(name)) { - ExtensionPoint.Kind kind = !aClass.isInterface() && (aClass.getModifiers() & 1024) == 0 ? ExtensionPoint.Kind.BEAN_CLASS : ExtensionPoint.Kind.INTERFACE; + if (!area.hasExtensionPoint(name)) { + ExtensionPoint.Kind kind = aClass.isInterface() || (aClass.getModifiers() & Modifier.ABSTRACT) != 0 ? ExtensionPoint.Kind.INTERFACE : ExtensionPoint.Kind.BEAN_CLASS; area.registerExtensionPoint(name, aClass.getName(), kind); } - - } - - protected void registerComponentImplementation(MutablePicoContainer container, Class key, Class implementation) { - container.unregisterComponent(key); - container.registerComponentImplementation(key, implementation); } public static T registerComponentInstance(MutablePicoContainer container, Class key, T implementation) { Object old = container.getComponentInstance(key); container.unregisterComponent(key); container.registerComponentInstance(key, implementation); - return (T) old; - } - - public static T registerComponentInstance(ComponentManager container, Class key, T implementation) { - return registerComponentInstance((MutablePicoContainer)container.getPicoContainer(), key, implementation); + //noinspection unchecked + return (T)old; } } diff --git a/compiler/tests/org/jetbrains/kotlin/test/testFramework/KtPlatformTestUtil.java b/compiler/tests/org/jetbrains/kotlin/test/testFramework/KtPlatformTestUtil.java index 955a9e0172b..eea7c47b0fb 100644 --- a/compiler/tests/org/jetbrains/kotlin/test/testFramework/KtPlatformTestUtil.java +++ b/compiler/tests/org/jetbrains/kotlin/test/testFramework/KtPlatformTestUtil.java @@ -16,55 +16,14 @@ package org.jetbrains.kotlin.test.testFramework; -import com.intellij.execution.ExecutionException; -import com.intellij.execution.configurations.GeneralCommandLine; -import com.intellij.execution.process.ProcessOutput; -import com.intellij.execution.util.ExecUtil; -import com.intellij.ide.DataManager; import com.intellij.ide.util.treeView.AbstractTreeNode; -import com.intellij.ide.util.treeView.AbstractTreeStructure; -import com.intellij.openapi.Disposable; -import com.intellij.openapi.actionSystem.*; -import com.intellij.openapi.application.ApplicationManager; -import com.intellij.openapi.application.PathManager; -import com.intellij.openapi.extensions.ExtensionPoint; -import com.intellij.openapi.extensions.ExtensionPointName; -import com.intellij.openapi.extensions.Extensions; -import com.intellij.openapi.extensions.ExtensionsArea; import com.intellij.openapi.ui.Queryable; -import com.intellij.openapi.util.*; -import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; -import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.openapi.vfs.VirtualFileFilter; -import com.intellij.util.Alarm; -import com.intellij.util.ArrayUtil; -import com.intellij.util.ReflectionUtil; -import com.intellij.util.ThrowableRunnable; -import com.intellij.util.ui.UIUtil; -import org.jdom.Element; -import org.jdom.JDOMException; -import org.jetbrains.annotations.*; -import org.junit.Assert; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.swing.*; -import javax.swing.tree.DefaultMutableTreeNode; -import javax.swing.tree.TreePath; -import java.awt.*; -import java.io.*; -import java.nio.charset.Charset; -import java.text.DecimalFormat; -import java.text.DecimalFormatSymbols; -import java.util.*; -import java.util.concurrent.atomic.AtomicBoolean; - -@SuppressWarnings("ALL") +// Based on com.intellij.testFramework.PlatformTestUtil public class KtPlatformTestUtil { - public static final boolean COVERAGE_ENABLED_BUILD = "true".equals(System.getProperty("idea.coverage.enabled.build")); - - private static final boolean SKIP_HEADLESS = GraphicsEnvironment.isHeadless(); - private static final boolean SKIP_SLOW = Boolean.getBoolean("skip.slow.tests.locally"); - @NotNull public static String getTestName(@NotNull String name, boolean lowercaseFirstLetter) { name = StringUtil.trimStart(name, "test"); @@ -92,30 +51,15 @@ public class KtPlatformTestUtil { return uppercaseChars >= 3; } - public static void registerExtension(@NotNull ExtensionPointName name, @NotNull T t, @NotNull Disposable parentDisposable) { - registerExtension(Extensions.getRootArea(), name, t, parentDisposable); - } - - public static void registerExtension(@NotNull ExtensionsArea area, @NotNull ExtensionPointName name, @NotNull final T t, @NotNull Disposable parentDisposable) { - final ExtensionPoint extensionPoint = area.getExtensionPoint(name.getName()); - extensionPoint.registerExtension(t); - Disposer.register(parentDisposable, new Disposable() { - @Override - public void dispose() { - extensionPoint.unregisterExtension(t); - } - }); - } - @Nullable protected static String toString(@Nullable Object node, @Nullable Queryable.PrintInfo printInfo) { if (node instanceof AbstractTreeNode) { if (printInfo != null) { - return ((AbstractTreeNode)node).toTestString(printInfo); + return ((AbstractTreeNode) node).toTestString(printInfo); } else { - @SuppressWarnings({"deprecation", "UnnecessaryLocalVariable"}) - final String presentation = ((AbstractTreeNode)node).getTestPresentation(); + @SuppressWarnings({"deprecation", "UnnecessaryLocalVariable"}) String presentation = + ((AbstractTreeNode) node).getTestPresentation(); return presentation; } } @@ -124,782 +68,4 @@ public class KtPlatformTestUtil { } return node.toString(); } - - public static String print(JTree tree, boolean withSelection) { - return print(tree, tree.getModel().getRoot(), withSelection, null, null); - } - - public static String print(JTree tree, Object root, @Nullable Queryable.PrintInfo printInfo, boolean withSelection) { - return print(tree, root, withSelection, printInfo, null); - } - - public static String print(JTree tree, boolean withSelection, @Nullable Condition nodePrintCondition) { - return print(tree, tree.getModel().getRoot(), withSelection, null, nodePrintCondition); - } - - public static String print(JTree tree, Object root, - boolean withSelection, - @Nullable Queryable.PrintInfo printInfo, - @Nullable Condition nodePrintCondition) { - StringBuilder buffer = new StringBuilder(); - final Collection strings = printAsList(tree, root, withSelection, printInfo, nodePrintCondition); - for (String string : strings) { - buffer.append(string).append("\n"); - } - return buffer.toString(); - } - - public static Collection printAsList(JTree tree, boolean withSelection, @Nullable Condition nodePrintCondition) { - return printAsList(tree, tree.getModel().getRoot(), withSelection, null, nodePrintCondition); - } - - private static Collection printAsList(JTree tree, Object root, - boolean withSelection, - @Nullable Queryable.PrintInfo printInfo, - Condition nodePrintCondition) { - Collection strings = new ArrayList(); - printImpl(tree, root, strings, 0, withSelection, printInfo, nodePrintCondition); - return strings; - } - - private static void printImpl(JTree tree, - Object root, - Collection strings, - int level, - boolean withSelection, - @Nullable Queryable.PrintInfo printInfo, - @Nullable Condition nodePrintCondition) { - DefaultMutableTreeNode defaultMutableTreeNode = (DefaultMutableTreeNode)root; - - final Object userObject = defaultMutableTreeNode.getUserObject(); - String nodeText; - if (userObject != null) { - nodeText = toString(userObject, printInfo); - } - else { - nodeText = "null"; - } - - if (nodePrintCondition != null && !nodePrintCondition.value(nodeText)) return; - - final StringBuilder buff = new StringBuilder(); - StringUtil.repeatSymbol(buff, ' ', level); - - final boolean expanded = tree.isExpanded(new TreePath(defaultMutableTreeNode.getPath())); - if (!defaultMutableTreeNode.isLeaf()) { - buff.append(expanded ? "-" : "+"); - } - - final boolean selected = tree.getSelectionModel().isPathSelected(new TreePath(defaultMutableTreeNode.getPath())); - if (withSelection && selected) { - buff.append("["); - } - - buff.append(nodeText); - - if (withSelection && selected) { - buff.append("]"); - } - - strings.add(buff.toString()); - - int childCount = tree.getModel().getChildCount(root); - if (expanded) { - for (int i = 0; i < childCount; i++) { - printImpl(tree, tree.getModel().getChild(root, i), strings, level + 1, withSelection, printInfo, nodePrintCondition); - } - } - } - - public static void assertTreeEqual(JTree tree, @NonNls String expected) { - assertTreeEqual(tree, expected, false); - } - - public static void assertTreeEqualIgnoringNodesOrder(JTree tree, @NonNls String expected) { - assertTreeEqualIgnoringNodesOrder(tree, expected, false); - } - - public static void assertTreeEqual(JTree tree, String expected, boolean checkSelected) { - String treeStringPresentation = print(tree, checkSelected); - Assert.assertEquals(expected, treeStringPresentation); - } - - public static void assertTreeEqualIgnoringNodesOrder(JTree tree, String expected, boolean checkSelected) { - final Collection actualNodesPresentation = printAsList(tree, checkSelected, null); - final java.util.List expectedNodes = StringUtil.split(expected, "\n"); - KtUsefulTestCase.assertSameElements(actualNodesPresentation, expectedNodes); - } - - @TestOnly - public static void waitForAlarm(final int delay) throws InterruptedException { - assert !ApplicationManager.getApplication().isWriteAccessAllowed(): "It's a bad idea to wait for an alarm under the write action. Somebody creates an alarm which requires read action and you are deadlocked."; - assert ApplicationManager.getApplication().isDispatchThread(); - - final AtomicBoolean invoked = new AtomicBoolean(); - final Alarm alarm = new Alarm(Alarm.ThreadToUse.SWING_THREAD); - alarm.addRequest(new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - alarm.addRequest(new Runnable() { - @Override - public void run() { - invoked.set(true); - } - }, delay); - } - }); - } - }, delay); - - UIUtil.dispatchAllInvocationEvents(); - - boolean sleptAlready = false; - while (!invoked.get()) { - UIUtil.dispatchAllInvocationEvents(); - //noinspection BusyWait - Thread.sleep(sleptAlready ? 10 : delay); - sleptAlready = true; - } - UIUtil.dispatchAllInvocationEvents(); - } - - //@TestOnly - //public static void dispatchAllInvocationEventsInIdeEventQueue() throws InterruptedException { - // assert SwingUtilities.isEventDispatchThread() : Thread.currentThread(); - // final EventQueue eventQueue = Toolkit.getDefaultToolkit().getSystemEventQueue(); - // while (true) { - // AWTEvent event = eventQueue.peekEvent(); - // if (event == null) break; - // AWTEvent event1 = eventQueue.getNextEvent(); - // if (event1 instanceof InvocationEvent) { - // IdeEventQueue.getInstance().dispatchEvent(event1); - // } - // } - //} - - //private static Date raidDate(Bombed bombed) { - // final Calendar instance = Calendar.getInstance(); - // instance.set(Calendar.YEAR, bombed.year()); - // instance.set(Calendar.MONTH, bombed.month()); - // instance.set(Calendar.DAY_OF_MONTH, bombed.day()); - // instance.set(Calendar.HOUR_OF_DAY, bombed.time()); - // instance.set(Calendar.MINUTE, 0); - // - // return instance.getTime(); - //} - // - //public static boolean bombExplodes(Bombed bombedAnnotation) { - // Date now = new Date(); - // return now.after(raidDate(bombedAnnotation)); - //} - - public static StringBuilder print(AbstractTreeStructure structure, - Object node, - int currentLevel, - @Nullable Comparator comparator, - int maxRowCount, - char paddingChar, - @Nullable Queryable.PrintInfo printInfo) { - StringBuilder buffer = new StringBuilder(); - doPrint(buffer, currentLevel, node, structure, comparator, maxRowCount, 0, paddingChar, printInfo); - return buffer; - } - - private static int doPrint(StringBuilder buffer, - int currentLevel, - Object node, - AbstractTreeStructure structure, - @Nullable Comparator comparator, - int maxRowCount, - int currentLine, - char paddingChar, - @Nullable Queryable.PrintInfo printInfo) { - if (currentLine >= maxRowCount && maxRowCount != -1) return currentLine; - - StringUtil.repeatSymbol(buffer, paddingChar, currentLevel); - buffer.append(toString(node, printInfo)).append("\n"); - currentLine++; - Object[] children = structure.getChildElements(node); - - if (comparator != null) { - ArrayList list = new ArrayList(Arrays.asList(children)); - @SuppressWarnings({"UnnecessaryLocalVariable", "unchecked"}) Comparator c = comparator; - Collections.sort(list, c); - children = ArrayUtil.toObjectArray(list); - } - for (Object child : children) { - currentLine = doPrint(buffer, currentLevel + 1, child, structure, comparator, maxRowCount, currentLine, paddingChar, printInfo); - } - - return currentLine; - } - - public static String print(Object[] objects) { - return print(Arrays.asList(objects)); - } - - public static String print(Collection c) { - StringBuilder result = new StringBuilder(); - for (Iterator iterator = c.iterator(); iterator.hasNext();) { - Object each = iterator.next(); - result.append(toString(each, null)); - if (iterator.hasNext()) { - result.append("\n"); - } - } - - return result.toString(); - } - - public static String print(ListModel model) { - StringBuilder result = new StringBuilder(); - for (int i = 0; i < model.getSize(); i++) { - result.append(toString(model.getElementAt(i), null)); - result.append("\n"); - } - return result.toString(); - } - - public static String print(JTree tree) { - return print(tree, false); - } - - public static void assertTreeStructureEquals(final AbstractTreeStructure treeStructure, final String expected) { - Assert.assertEquals(expected, print(treeStructure, treeStructure.getRootElement(), 0, null, -1, ' ', null).toString()); - } - - public static void invokeNamedAction(final String actionId) { - final AnAction action = ActionManager.getInstance().getAction(actionId); - Assert.assertNotNull(action); - final Presentation presentation = new Presentation(); - @SuppressWarnings("deprecation") final DataContext context = DataManager.getInstance().getDataContext(); - final AnActionEvent event = AnActionEvent.createFromAnAction(action, null, "", context); - action.update(event); - Assert.assertTrue(presentation.isEnabled()); - action.actionPerformed(event); - } - - //public static void assertTiming(final String message, final long expectedMs, final long actual) { - // if (COVERAGE_ENABLED_BUILD) return; - // - // final long expectedOnMyMachine = Math.max(1, expectedMs * Timings.MACHINE_TIMING / Timings.ETALON_TIMING); - // - // // Allow 10% more in case of test machine is busy. - // String logMessage = message; - // if (actual > expectedOnMyMachine) { - // int percentage = (int)(100.0 * (actual - expectedOnMyMachine) / expectedOnMyMachine); - // logMessage += ". Operation took " + percentage + "% longer than expected"; - // } - // logMessage += ". Expected on my machine: " + expectedOnMyMachine + "." + - // " Actual: " + actual + "." + - // " Expected on Standard machine: " + expectedMs + ";" + - // " Actual on Standard: " + actual * Timings.ETALON_TIMING / Timings.MACHINE_TIMING + ";" + - // " Timings: CPU=" + Timings.CPU_TIMING + - // ", I/O=" + Timings.IO_TIMING + "." + - // " (" + (int)(Timings.MACHINE_TIMING*1.0/Timings.ETALON_TIMING*100) + "% of the Standard)" + - // "."; - // final double acceptableChangeFactor = 1.1; - // if (actual < expectedOnMyMachine) { - // System.out.println(logMessage); - // TeamCityLogger.info(logMessage); - // } - // else if (actual < expectedOnMyMachine * acceptableChangeFactor) { - // TeamCityLogger.warning(logMessage, null); - // } - // else { - // // throw AssertionFailedError to try one more time - // throw new AssertionFailedError(logMessage); - // } - //} - - /** - * example usage: startPerformanceTest("calculating pi",100, testRunnable).cpuBound().assertTiming(); - */ - @Contract(pure = true) // to warn about not calling .assertTiming() in the end - public static TestInfo startPerformanceTest(@NonNls @NotNull String message, int expectedMs, @NotNull ThrowableRunnable test) { - return new TestInfo(test, expectedMs,message); - } - - public static boolean canRunTest(@NotNull Class testCaseClass) { - if (!SKIP_SLOW && !SKIP_HEADLESS) { - return true; - } - - for (Class clazz = testCaseClass; clazz != null; clazz = clazz.getSuperclass()) { - //if (SKIP_HEADLESS && clazz.getAnnotation(SkipInHeadlessEnvironment.class) != null) { - // System.out.println("Class '" + testCaseClass.getName() + "' is skipped because it requires working UI environment"); - // return false; - //} - //if (SKIP_SLOW && clazz.getAnnotation(SkipSlowTestLocally.class) != null) { - // System.out.println("Class '" + testCaseClass.getName() + "' is skipped because it is dog slow"); - // return false; - //} - } - - return true; - } - - public static void assertPathsEqual(@Nullable String expected, @Nullable String actual) { - if (expected != null) expected = FileUtil.toSystemIndependentName(expected); - if (actual != null) actual = FileUtil.toSystemIndependentName(actual); - Assert.assertEquals(expected, actual); - } - - @NotNull - public static String getRtJarPath() { - String home = System.getProperty("java.home"); - return SystemInfo.isAppleJvm ? FileUtil.toCanonicalPath(home + "/../Classes/classes.jar") : home + "/lib/rt.jar"; - } - - //public static void saveProject(Project project) { - // ApplicationEx application = ApplicationManagerEx.getApplicationEx(); - // boolean oldValue = application.isDoNotSave(); - // try { - // application.doNotSave(false); - // project.save(); - // } - // finally { - // application.doNotSave(oldValue); - // } - //} - - public static class TestInfo { - private final ThrowableRunnable test; // runnable to measure - private final int expectedMs; // millis the test is expected to run - private ThrowableRunnable setup; // to run before each test - private boolean usesAllCPUCores; // true if the test runs faster on multi-core - private int attempts = 4; // number of retries if performance failed - private final String message; // to print on fail - private boolean adjustForIO = true; // true if test uses IO, timings need to be re-calibrated according to this agent disk performance - private boolean adjustForCPU = true; // true if test uses CPU, timings need to be re-calibrated according to this agent CPU speed - private boolean useLegacyScaling; - - private TestInfo(@NotNull ThrowableRunnable test, int expectedMs, String message) { - this.test = test; - this.expectedMs = expectedMs; - assert expectedMs > 0 : "Expected must be > 0. Was: "+ expectedMs; - this.message = message; - } - - @Contract(pure = true) // to warn about not calling .assertTiming() in the end - public TestInfo setup(@NotNull ThrowableRunnable setup) { assert this.setup==null; this.setup = setup; return this; } - @Contract(pure = true) // to warn about not calling .assertTiming() in the end - public TestInfo usesAllCPUCores() { assert adjustForCPU : "This test configured to be io-bound, it cannot use all cores"; usesAllCPUCores = true; return this; } - @Contract(pure = true) // to warn about not calling .assertTiming() in the end - public TestInfo cpuBound() { adjustForIO = false; adjustForCPU = true; return this; } - @Contract(pure = true) // to warn about not calling .assertTiming() in the end - public TestInfo ioBound() { adjustForIO = true; adjustForCPU = false; return this; } - @Contract(pure = true) // to warn about not calling .assertTiming() in the end - public TestInfo attempts(int attempts) { this.attempts = attempts; return this; } - /** - * @deprecated Enables procedure for nonlinear scaling of results between different machines. This was historically enabled, but doesn't - * seem to be meaningful, and is known to make results worse in some cases. Consider migration off this setting, recalibrating - * expected execution time accordingly. - */ - @Contract(pure = true) // to warn about not calling .assertTiming() in the end - public TestInfo useLegacyScaling() { useLegacyScaling = true; return this; } - - //public void assertTiming() { - // assert expectedMs != 0 : "Must call .expect() before run test"; - // if (COVERAGE_ENABLED_BUILD) return; - // Timings.getStatistics(); // warm-up, measure - // - // while (true) { - // attempts--; - // long start; - // try { - // if (setup != null) setup.run(); - // start = System.currentTimeMillis(); - // test.run(); - // } - // catch (Throwable throwable) { - // throw new RuntimeException(throwable); - // } - // long finish = System.currentTimeMillis(); - // long duration = finish - start; - // - // int expectedOnMyMachine = expectedMs; - // if (adjustForCPU) { - // expectedOnMyMachine = adjust(expectedOnMyMachine, Timings.CPU_TIMING, Timings.ETALON_CPU_TIMING, useLegacyScaling); - // - // expectedOnMyMachine = usesAllCPUCores ? expectedOnMyMachine * 8 / JobSchedulerImpl.CORES_COUNT : expectedOnMyMachine; - // } - // if (adjustForIO) { - // expectedOnMyMachine = adjust(expectedOnMyMachine, Timings.IO_TIMING, Timings.ETALON_IO_TIMING, useLegacyScaling); - // } - // - // // Allow 10% more in case of test machine is busy. - // String logMessage = message; - // if (duration > expectedOnMyMachine) { - // int percentage = (int)(100.0 * (duration - expectedOnMyMachine) / expectedOnMyMachine); - // logMessage += ": " + percentage + "% longer"; - // } - // logMessage += - // ". Expected: " + formatTime(expectedOnMyMachine) + ". Actual: " + formatTime(duration) + "." + Timings.getStatistics(); - // final double acceptableChangeFactor = 1.1; - // if (duration < expectedOnMyMachine) { - // int percentage = (int)(100.0 * (expectedOnMyMachine - duration) / expectedOnMyMachine); - // logMessage = percentage + "% faster. " + logMessage; - // - // TeamCityLogger.info(logMessage); - // System.out.println("SUCCESS: " + logMessage); - // } - // else if (duration < expectedOnMyMachine * acceptableChangeFactor) { - // TeamCityLogger.warning(logMessage, null); - // System.out.println("WARNING: " + logMessage); - // } - // else { - // // try one more time - // if (attempts == 0) { - // //try { - // // Object result = Class.forName("com.intellij.util.ProfilingUtil").getMethod("captureCPUSnapshot").invoke(null); - // // System.err.println("CPU snapshot captured in '"+result+"'"); - // //} - // //catch (Exception e) { - // //} - // - // throw new AssertionFailedError(logMessage); - // } - // System.gc(); - // System.gc(); - // System.gc(); - // String s = "Another epic fail (remaining attempts: " + attempts + "): " + logMessage; - // TeamCityLogger.warning(s, null); - // System.err.println(s); - // //if (attempts == 1) { - // // try { - // // Class.forName("com.intellij.util.ProfilingUtil").getMethod("startCPUProfiling").invoke(null); - // // } - // // catch (Exception e) { - // // } - // //} - // continue; - // } - // break; - // } - //} - - private static String formatTime(long millis) { - String hint = ""; - DecimalFormat format = new DecimalFormat("#.0", DecimalFormatSymbols.getInstance(Locale.US)); - if (millis >= 60 * 1000) hint = format.format(millis / 60 / 1000.f) + "m"; - if (millis >= 1000) hint += (hint.isEmpty() ? "" : " ") + format.format(millis / 1000.f) + "s"; - String result = millis + "ms"; - if (!hint.isEmpty()) { - result = result + " (" + hint + ")"; - } - return result; - } - - private static int adjust(int expectedOnMyMachine, long thisTiming, long etalonTiming, boolean useLegacyScaling) { - if (useLegacyScaling) { - double speed = 1.0 * thisTiming / etalonTiming; - double delta = speed < 1 - ? 0.9 + Math.pow(speed - 0.7, 2) - : 0.45 + Math.pow(speed - 0.25, 2); - expectedOnMyMachine *= delta; - return expectedOnMyMachine; - } - else { - return (int)(expectedOnMyMachine * thisTiming / etalonTiming); - } - } - } - - - //public static void assertTiming(String message, long expected, @NotNull Runnable actionToMeasure) { - // assertTiming(message, expected, 4, actionToMeasure); - //} - - public static long measure(@NotNull Runnable actionToMeasure) { - long start = System.currentTimeMillis(); - actionToMeasure.run(); - long finish = System.currentTimeMillis(); - return finish - start; - } - - //public static void assertTiming(String message, long expected, int attempts, @NotNull Runnable actionToMeasure) { - // while (true) { - // attempts--; - // long duration = measure(actionToMeasure); - // try { - // assertTiming(message, expected, duration); - // break; - // } - // catch (AssertionFailedError e) { - // if (attempts == 0) throw e; - // System.gc(); - // System.gc(); - // System.gc(); - // String s = "Another epic fail (remaining attempts: " + attempts + "): " + e.getMessage(); - // TeamCityLogger.warning(s, null); - // System.err.println(s); - // } - // } - //} - - private static com.intellij.util.containers.HashMap buildNameToFileMap(VirtualFile[] files, @Nullable VirtualFileFilter filter) { - com.intellij.util.containers.HashMap map = new com.intellij.util.containers.HashMap(); - for (VirtualFile file : files) { - if (filter != null && !filter.accept(file)) continue; - map.put(file.getName(), file); - } - return map; - } - - //public static void assertDirectoriesEqual(VirtualFile dirAfter, VirtualFile dirBefore) throws IOException { - // assertDirectoriesEqual(dirAfter, dirBefore, null); - //} - - //@SuppressWarnings("UnsafeVfsRecursion") - //public static void assertDirectoriesEqual(VirtualFile dirAfter, VirtualFile dirBefore, @Nullable VirtualFileFilter fileFilter) throws IOException { - // FileDocumentManager.getInstance().saveAllDocuments(); - // - // VirtualFile[] childrenAfter = dirAfter.getChildren(); - // - // if (dirAfter.isInLocalFileSystem() && dirAfter.getFileSystem() != TempFileSystem.getInstance()) { - // File[] ioAfter = new File(dirAfter.getPath()).listFiles(); - // shallowCompare(childrenAfter, ioAfter); - // } - // - // VirtualFile[] childrenBefore = dirBefore.getChildren(); - // if (dirBefore.isInLocalFileSystem() && dirBefore.getFileSystem() != TempFileSystem.getInstance()) { - // File[] ioBefore = new File(dirBefore.getPath()).listFiles(); - // shallowCompare(childrenBefore, ioBefore); - // } - // - // com.intellij.util.containers.HashMap mapAfter = buildNameToFileMap(childrenAfter, fileFilter); - // com.intellij.util.containers.HashMap mapBefore = buildNameToFileMap(childrenBefore, fileFilter); - // - // Set keySetAfter = mapAfter.keySet(); - // Set keySetBefore = mapBefore.keySet(); - // Assert.assertEquals(dirAfter.getPath(), keySetAfter, keySetBefore); - // - // for (String name : keySetAfter) { - // VirtualFile fileAfter = mapAfter.get(name); - // VirtualFile fileBefore = mapBefore.get(name); - // if (fileAfter.isDirectory()) { - // assertDirectoriesEqual(fileAfter, fileBefore, fileFilter); - // } - // else { - // assertFilesEqual(fileAfter, fileBefore); - // } - // } - //} - - private static void shallowCompare(VirtualFile[] vfs, @Nullable File[] io) { - java.util.List vfsPaths = new ArrayList(); - for (VirtualFile file : vfs) { - vfsPaths.add(file.getPath()); - } - - java.util.List ioPaths = new ArrayList(); - if (io != null) { - for (File file : io) { - ioPaths.add(file.getPath().replace(File.separatorChar, '/')); - } - } - - Assert.assertEquals(sortAndJoin(vfsPaths), sortAndJoin(ioPaths)); - } - - private static String sortAndJoin(java.util.List strings) { - Collections.sort(strings); - StringBuilder buf = new StringBuilder(); - for (String string : strings) { - buf.append(string); - buf.append('\n'); - } - return buf.toString(); - } - - //public static void assertFilesEqual(VirtualFile fileAfter, VirtualFile fileBefore) throws IOException { - // try { - // assertJarFilesEqual(VfsUtilCore.virtualToIoFile(fileAfter), VfsUtilCore.virtualToIoFile(fileBefore)); - // } - // catch (IOException e) { - // FileDocumentManager manager = FileDocumentManager.getInstance(); - // - // Document docBefore = manager.getDocument(fileBefore); - // boolean canLoadBeforeText = !fileBefore.getFileType().isBinary() || fileBefore.getFileType() == FileTypes.UNKNOWN; - // String textB = docBefore != null - // ? docBefore.getText() - // : !canLoadBeforeText - // ? null - // : LoadTextUtil.getTextByBinaryPresentation(fileBefore.contentsToByteArray(false), fileBefore).toString(); - // - // Document docAfter = manager.getDocument(fileAfter); - // boolean canLoadAfterText = !fileBefore.getFileType().isBinary() || fileBefore.getFileType() == FileTypes.UNKNOWN; - // String textA = docAfter != null - // ? docAfter.getText() - // : !canLoadAfterText - // ? null - // : LoadTextUtil.getTextByBinaryPresentation(fileAfter.contentsToByteArray(false), fileAfter).toString(); - // - // if (textA != null && textB != null) { - // Assert.assertEquals(fileAfter.getPath(), textA, textB); - // } - // else { - // Assert.assertArrayEquals(fileAfter.getPath(), fileAfter.contentsToByteArray(), fileBefore.contentsToByteArray()); - // } - // } - //} - - //public static void assertJarFilesEqual(File file1, File file2) throws IOException { - // final File tempDirectory1; - // final File tempDirectory2; - // - // final JarFile jarFile1 = new JarFile(file1); - // try { - // final JarFile jarFile2 = new JarFile(file2); - // try { - // tempDirectory1 = PlatformTestCase.createTempDir("tmp1"); - // tempDirectory2 = PlatformTestCase.createTempDir("tmp2"); - // ZipUtil.extract(jarFile1, tempDirectory1, null); - // ZipUtil.extract(jarFile2, tempDirectory2, null); - // } - // finally { - // jarFile2.close(); - // } - // } - // finally { - // jarFile1.close(); - // } - // - // final VirtualFile dirAfter = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(tempDirectory1); - // Assert.assertNotNull(tempDirectory1.toString(), dirAfter); - // final VirtualFile dirBefore = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(tempDirectory2); - // Assert.assertNotNull(tempDirectory2.toString(), dirBefore); - // ApplicationManager.getApplication().runWriteAction(new Runnable() { - // @Override - // public void run() { - // dirAfter.refresh(false, true); - // dirBefore.refresh(false, true); - // } - // }); - // assertDirectoriesEqual(dirAfter, dirBefore); - //} - - public static void assertElementsEqual(final Element expected, final Element actual) throws IOException { - if (!JDOMUtil.areElementsEqual(expected, actual)) { - Assert.assertEquals(printElement(expected), printElement(actual)); - } - } - - public static void assertElementEquals(final String expected, final Element actual) { - try { - assertElementsEqual(JDOMUtil.loadDocument(expected).getRootElement(), actual); - } - catch (IOException e) { - throw new AssertionError(e); - } - catch (JDOMException e) { - throw new AssertionError(e); - } - } - - public static String printElement(final Element element) throws IOException { - final StringWriter writer = new StringWriter(); - JDOMUtil.writeElement(element, writer, "\n"); - return writer.getBuffer().toString(); - } - - public static String getCommunityPath() { - final String homePath = PathManager.getHomePath(); - if (new File(homePath, "community/.idea").isDirectory()) { - return homePath + File.separatorChar + "community"; - } - return homePath; - } - - public static String getPlatformTestDataPath() { - return getCommunityPath().replace(File.separatorChar, '/') + "/platform/platform-tests/testData/"; - } - - - public static Comparator createComparator(final Queryable.PrintInfo printInfo) { - return new Comparator() { - @Override - public int compare(final AbstractTreeNode o1, final AbstractTreeNode o2) { - String displayText1 = o1.toTestString(printInfo); - String displayText2 = o2.toTestString(printInfo); - return Comparing.compare(displayText1, displayText2); - } - }; - } - - @NotNull - public static T notNull(@Nullable T t) { - Assert.assertNotNull(t); - return t; - } - - @NotNull - public static String loadFileText(@NotNull String fileName) throws IOException { - return StringUtil.convertLineSeparators(FileUtil.loadFile(new File(fileName))); - } - - //public static void tryGcSoftlyReachableObjects() { - // GCUtil.tryGcSoftlyReachableObjects(); - //} - - public static void withEncoding(@NotNull String encoding, @NotNull final Runnable r) { - withEncoding(encoding, new ThrowableRunnable() { - @Override - public void run() throws Throwable { - r.run(); - } - }); - } - - public static void withEncoding(@NotNull String encoding, @NotNull ThrowableRunnable r) { - Charset oldCharset = Charset.defaultCharset(); - try { - try { - patchSystemFileEncoding(encoding); - r.run(); - } - finally { - patchSystemFileEncoding(oldCharset.name()); - } - } - catch (Throwable t) { - throw new RuntimeException(t); - } - } - - private static void patchSystemFileEncoding(String encoding) { - ReflectionUtil.resetField(Charset.class, Charset.class, "defaultCharset"); - System.setProperty("file.encoding", encoding); - } - - public static void withStdErrSuppressed(@NotNull Runnable r) { - PrintStream std = System.err; - System.setErr(new PrintStream(NULL)); - try { - r.run(); - } - finally { - System.setErr(std); - } - } - - @SuppressWarnings("IOResourceOpenedButNotSafelyClosed") - private static final OutputStream NULL = new OutputStream() { - @Override - public void write(int b) throws IOException { } - }; - - public static void assertSuccessful(@NotNull GeneralCommandLine command) { - try { - ProcessOutput output = ExecUtil.execAndGetOutput(command.withRedirectErrorStream(true)); - Assert.assertEquals(output.getStdout(), 0, output.getExitCode()); - } - catch (ExecutionException e) { - throw new RuntimeException(e); - } - } } \ No newline at end of file diff --git a/compiler/tests/org/jetbrains/kotlin/test/testFramework/KtUsefulTestCase.java b/compiler/tests/org/jetbrains/kotlin/test/testFramework/KtUsefulTestCase.java index c72557703bd..64f1dcf30ca 100644 --- a/compiler/tests/org/jetbrains/kotlin/test/testFramework/KtUsefulTestCase.java +++ b/compiler/tests/org/jetbrains/kotlin/test/testFramework/KtUsefulTestCase.java @@ -16,159 +16,106 @@ package org.jetbrains.kotlin.test.testFramework; -import com.intellij.diagnostic.PerformanceWatcher; -import com.intellij.mock.MockApplication; import com.intellij.openapi.Disposable; -import com.intellij.openapi.application.Application; -import com.intellij.openapi.application.ApplicationManager; -import com.intellij.openapi.application.PathManager; import com.intellij.openapi.application.impl.ApplicationInfoImpl; -import com.intellij.openapi.fileTypes.StdFileTypes; -import com.intellij.openapi.util.*; +import com.intellij.openapi.util.Comparing; +import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.io.FileSystemUtil; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; -import com.intellij.openapi.vfs.*; -import com.intellij.psi.codeStyle.CodeStyleSchemes; -import com.intellij.psi.codeStyle.CodeStyleSettings; -import com.intellij.psi.codeStyle.CodeStyleSettingsManager; +import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.rt.execution.junit.FileComparisonFailure; -import com.intellij.util.Consumer; import com.intellij.util.Function; import com.intellij.util.ReflectionUtil; -import com.intellij.util.ThrowableRunnable; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.hash.HashMap; import com.intellij.util.ui.UIUtil; import gnu.trove.THashSet; import junit.framework.AssertionFailedError; import junit.framework.TestCase; -import org.jdom.Element; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; import org.junit.Assert; -import javax.swing.*; -import java.awt.*; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.security.SecureRandom; +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; -@SuppressWarnings("ALL") +@SuppressWarnings("UseOfSystemOutOrSystemErr") public abstract class KtUsefulTestCase extends TestCase { - public static final boolean IS_UNDER_TEAMCITY = System.getenv("TEAMCITY_VERSION") != null; - /** @deprecated */ - @Deprecated - 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; - 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(); - protected final Disposable myTestRootDisposable = new Disposable() { - public void dispose() { - } + private static final String TEMP_DIR_MARKER = "unitTest_"; + private static final String ORIGINAL_TEMP_DIR = FileUtil.getTempDirectory(); + + 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() { + @Override + public void dispose() { } + + @Override public String toString() { - String testName = KtUsefulTestCase.this.getTestName(false); + String testName = getTestName(false); return KtUsefulTestCase.this.getClass() + (StringUtil.isEmpty(testName) ? "" : ".test" + testName); } }; - protected static String ourPathToKeep = null; - private List myPathsToKeep = new ArrayList(); - private CodeStyleSettings myOldCodeStyleSettings; + + private static final String ourPathToKeep = null; + private final List myPathsToKeep = new ArrayList(); + private String myTempDir; - protected static final Key CREATION_PLACE = Key.create("CREATION_PLACE"); - private static final Set DELETE_ON_EXIT_HOOK_DOT_FILES; - private static final Class DELETE_ON_EXIT_HOOK_CLASS; - public KtUsefulTestCase() { + static { + // Radar #5755208: Command line Java applications need a way to launch without a Dock icon. + System.setProperty("apple.awt.UIElement", "true"); } - protected boolean shouldContainTempFiles() { - return true; - } + private boolean oldDisposerDebug; + @Override protected void setUp() throws Exception { super.setUp(); - if(this.shouldContainTempFiles()) { - String testName = FileUtil.sanitizeFileName(this.getTestName(true)); - if(StringUtil.isEmptyOrSpaces(testName)) { - testName = ""; - } - testName = (new File(testName)).getName(); - this.myTempDir = FileUtil.toSystemDependentName(ORIGINAL_TEMP_DIR + "/" + "unitTest_" + testName + "_" + RNG.nextInt(1000)); - FileUtil.resetCanonicalTempPathCache(this.myTempDir); - } - - ApplicationInfoImpl.setInPerformanceTest(this.isPerformanceTest()); + String testName = FileUtil.sanitizeFileName(getTestName(true)); + if (StringUtil.isEmptyOrSpaces(testName)) testName = ""; + testName = new File(testName).getName(); // in case the test name contains file separators + myTempDir = new File(ORIGINAL_TEMP_DIR, TEMP_DIR_MARKER + testName).getPath(); + FileUtil.resetCanonicalTempPathCache(myTempDir); + boolean isPerformanceTest = isPerformanceTest(); + ApplicationInfoImpl.setInPerformanceTest(isPerformanceTest); + // turn off Disposer debugging for performance tests + oldDisposerDebug = Disposer.setDebugMode(Disposer.isDebugMode() && !isPerformanceTest); } + @Override protected void tearDown() throws Exception { - boolean var13 = false; - try { - var13 = true; - Disposer.dispose(this.myTestRootDisposable); + Disposer.dispose(myTestRootDisposable); cleanupSwingDataStructures(); cleanupDeleteOnExitHookList(); - var13 = false; - } finally { - if(var13) { - if(this.shouldContainTempFiles()) { - FileUtil.resetCanonicalTempPathCache(ORIGINAL_TEMP_DIR); - if(this.hasTmpFilesToKeep()) { - File[] files1 = (new File(this.myTempDir)).listFiles(); - if(files1 != null) { - File[] var8 = files1; - int var9 = files1.length; - - for(int var10 = 0; var10 < var9; ++var10) { - File file1 = var8[var10]; - if(!this.shouldKeepTmpFile(file1)) { - FileUtil.delete(file1); - } - } - } - } else { - FileUtil.delete(new File(this.myTempDir)); - } - } - - } } - - if(this.shouldContainTempFiles()) { + finally { + Disposer.setDebugMode(oldDisposerDebug); FileUtil.resetCanonicalTempPathCache(ORIGINAL_TEMP_DIR); - if(this.hasTmpFilesToKeep()) { - File[] files = (new File(this.myTempDir)).listFiles(); - if(files != null) { - File[] var2 = files; - int var3 = files.length; - - for(int var4 = 0; var4 < var3; ++var4) { - File file = var2[var4]; - if(!this.shouldKeepTmpFile(file)) { + if (hasTmpFilesToKeep()) { + File[] files = new File(myTempDir).listFiles(); + if (files != null) { + for (File file : files) { + if (!shouldKeepTmpFile(file)) { FileUtil.delete(file); } } } - } else { - FileUtil.delete(new File(this.myTempDir)); + } + else { + FileUtil.delete(new File(myTempDir)); } } @@ -176,438 +123,212 @@ public abstract class KtUsefulTestCase extends TestCase { super.tearDown(); } - protected void addTmpFileToKeep(File file) { - this.myPathsToKeep.add(file.getPath()); - } - private boolean hasTmpFilesToKeep() { - return ourPathToKeep != null && FileUtil.isAncestor(this.myTempDir, ourPathToKeep, false) || !this.myPathsToKeep.isEmpty(); + return !myPathsToKeep.isEmpty(); } private boolean shouldKeepTmpFile(File file) { String path = file.getPath(); - if(FileUtil.pathsEqual(path, ourPathToKeep)) { - return true; - } else { - Iterator var3 = this.myPathsToKeep.iterator(); - - String pathToKeep; - do { - if(!var3.hasNext()) { - return false; - } - - pathToKeep = (String)var3.next(); - } while(!FileUtil.pathsEqual(path, pathToKeep)); - - return true; + if (FileUtil.pathsEqual(path, ourPathToKeep)) return true; + for (String pathToKeep : myPathsToKeep) { + if (FileUtil.pathsEqual(path, pathToKeep)) return true; } + return false; } - public static void cleanupDeleteOnExitHookList() throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException { - Class i = DELETE_ON_EXIT_HOOK_CLASS; - ArrayList 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); + private static final Set DELETE_ON_EXIT_HOOK_DOT_FILES; + private static final Class DELETE_ON_EXIT_HOOK_CLASS; + static { + Class aClass; + try { + aClass = Class.forName("java.io.DeleteOnExitHook"); } + catch (Exception e) { + throw new RuntimeException(e); + } + Set files = ReflectionUtil.getStaticFieldValue(aClass, Set.class, "files"); + DELETE_ON_EXIT_HOOK_CLASS = aClass; + DELETE_ON_EXIT_HOOK_DOT_FILES = files; + } - for(int var7 = list.size() - 1; var7 >= 0; --var7) { - String path = (String)list.get(var7); - if(FileSystemUtil.getAttributes(path) == null || (new File(path)).delete()) { - Class var3 = DELETE_ON_EXIT_HOOK_CLASS; - synchronized(DELETE_ON_EXIT_HOOK_CLASS) { + 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); + } + for (int i = list.size() - 1; i >= 0; i--) { + String path = list.get(i); + if (FileSystemUtil.getAttributes(path) == null || new File(path).delete()) { + synchronized (DELETE_ON_EXIT_HOOK_CLASS) { DELETE_ON_EXIT_HOOK_DOT_FILES.remove(path); } } } - } private static void cleanupSwingDataStructures() throws Exception { - Object manager = ReflectionUtil - .getDeclaredMethod(Class.forName("javax.swing.KeyboardManager"), "getCurrentManager", new Class[0]).invoke((Object)null, new Object[0]); - Map componentKeyStrokeMap = (Map)ReflectionUtil.getField(manager.getClass(), manager, Hashtable.class, "componentKeyStrokeMap"); + Object manager = ReflectionUtil.getDeclaredMethod(Class.forName("javax.swing.KeyboardManager"), "getCurrentManager").invoke(null); + Map componentKeyStrokeMap = ReflectionUtil.getField(manager.getClass(), manager, Hashtable.class, "componentKeyStrokeMap"); componentKeyStrokeMap.clear(); - Map containerMap = (Map)ReflectionUtil.getField(manager.getClass(), manager, Hashtable.class, "containerMap"); + Map containerMap = ReflectionUtil.getField(manager.getClass(), manager, Hashtable.class, "containerMap"); containerMap.clear(); } - protected void checkForSettingsDamage(@NotNull List exceptions) { - Application app = ApplicationManager.getApplication(); - if(!this.isPerformanceTest() && app != null && !(app instanceof MockApplication)) { - CodeStyleSettings oldCodeStyleSettings = this.myOldCodeStyleSettings; - if(oldCodeStyleSettings != null) { - this.myOldCodeStyleSettings = null; - doCheckForSettingsDamage(oldCodeStyleSettings, this.getCurrentCodeStyleSettings(), exceptions); - } - } - } - - public static void doCheckForSettingsDamage(@NotNull CodeStyleSettings oldCodeStyleSettings, @NotNull CodeStyleSettings currentCodeStyleSettings, @NotNull List exceptions) { - //CodeInsightSettings settings = CodeInsightSettings.getInstance(); - // - //try { - // Element e = new Element("temp"); - // settings.writeExternal(e); - // Assert.assertEquals("Code insight settings damaged", DEFAULT_SETTINGS_EXTERNALIZED, JDOMUtil.writeElement(e, "\n")); - //} catch (AssertionError var23) { - // CodeInsightSettings clean = new CodeInsightSettings(); - // Field[] var6 = clean.getClass().getFields(); - // int var7 = var6.length; - // - // for(int var8 = 0; var8 < var7; ++var8) { - // Field field = var6[var8]; - // - // try { - // ReflectionUtil.copyFieldValue(clean, settings, field); - // } catch (Exception var22) { - // ; - // } - // } - // - // exceptions.add(var23); - //} - // - //currentCodeStyleSettings.getIndentOptions(StdFileTypes.JAVA); - // - //try { - // checkSettingsEqual(oldCodeStyleSettings, currentCodeStyleSettings, "Code style settings damaged"); - //} catch (Throwable var20) { - // exceptions.add(var20); - //} finally { - // currentCodeStyleSettings.clearCodeStyleSettings(); - //} - // - //try { - // InplaceRefactoring.checkCleared(); - //} catch (AssertionError var19) { - // exceptions.add(var19); - //} - // - //try { - // StartMarkAction.checkCleared(); - //} catch (AssertionError var18) { - // exceptions.add(var18); - //} - - } - - protected void storeSettings() { - if(!this.isPerformanceTest() && ApplicationManager.getApplication() != null) { - this.myOldCodeStyleSettings = this.getCurrentCodeStyleSettings().clone(); - this.myOldCodeStyleSettings.getIndentOptions(StdFileTypes.JAVA); - } - - } - - protected CodeStyleSettings getCurrentCodeStyleSettings() { - return CodeStyleSchemes.getInstance().getCurrentScheme() == null ? new CodeStyleSettings() : CodeStyleSettingsManager.getInstance().getCurrentSettings(); - } - - public Disposable getTestRootDisposable() { - return this.myTestRootDisposable; + @NotNull + public final Disposable getTestRootDisposable() { + return myTestRootDisposable; } + @Override protected void runTest() throws Throwable { final Throwable[] throwables = new Throwable[1]; + Runnable runnable = new Runnable() { + @Override public void run() { try { KtUsefulTestCase.super.runTest(); - } catch (InvocationTargetException var2) { - var2.fillInStackTrace(); - throwables[0] = var2.getTargetException(); - } catch (IllegalAccessException var3) { - var3.fillInStackTrace(); - throwables[0] = var3; - } catch (Throwable var4) { - throwables[0] = var4; } - + catch (InvocationTargetException e) { + e.fillInStackTrace(); + throwables[0] = e.getTargetException(); + } + catch (IllegalAccessException e) { + e.fillInStackTrace(); + throwables[0] = e; + } + catch (Throwable e) { + throwables[0] = e; + } } }; - this.invokeTestRunnable(runnable); - if(throwables[0] != null) { + + invokeTestRunnable(runnable); + + if (throwables[0] != null) { throw throwables[0]; } } - protected boolean shouldRunTest() { - return KtPlatformTestUtil.canRunTest(this.getClass()); - } - - public static void edt(@NotNull Runnable r) { - EdtTestUtil.runInEdtAndWait(r); - } - - protected void invokeTestRunnable(@NotNull Runnable runnable) throws Exception { + private static void invokeTestRunnable(@NotNull Runnable runnable) throws Exception { EdtTestUtil.runInEdtAndWait(runnable); } - protected void defaultRunBare() throws Throwable { + private void defaultRunBare() throws Throwable { Throwable exception = null; - boolean var16 = false; - - label102: { - long tearingDown; - long teardownCost; - label101: { - try { - var16 = true; - tearingDown = System.nanoTime(); - this.setUp(); - teardownCost = (System.nanoTime() - tearingDown) / 1000000L; - this.logPerClassCost(teardownCost, TOTAL_SETUP_COST_MILLIS); - this.runTest(); - var16 = false; - break label101; - } catch (Throwable var20) { - exception = var20; - var16 = false; - } finally { - if(var16) { - try { - long tearingDown1 = System.nanoTime(); - this.tearDown(); - long teardownCost1 = (System.nanoTime() - tearingDown1) / 1000000L; - this.logPerClassCost(teardownCost1, TOTAL_TEARDOWN_COST_MILLIS); - } catch (Throwable var17) { - if(exception == null) { - ; - } - } - - } - } - - try { - tearingDown = System.nanoTime(); - this.tearDown(); - teardownCost = (System.nanoTime() - tearingDown) / 1000000L; - this.logPerClassCost(teardownCost, TOTAL_TEARDOWN_COST_MILLIS); - } catch (Throwable var18) { - if(exception == null) { - exception = var18; - } - } - break label102; - } + try { + long setupStart = System.nanoTime(); + setUp(); + long setupCost = (System.nanoTime() - setupStart) / 1000000; + logPerClassCost(setupCost, TOTAL_SETUP_COST_MILLIS); + runTest(); + } + catch (Throwable running) { + exception = running; + } + finally { try { - tearingDown = System.nanoTime(); - this.tearDown(); - teardownCost = (System.nanoTime() - tearingDown) / 1000000L; - this.logPerClassCost(teardownCost, TOTAL_TEARDOWN_COST_MILLIS); - } catch (Throwable var19) { - if(exception == null) { - exception = var19; - } + long teardownStart = System.nanoTime(); + tearDown(); + long teardownCost = (System.nanoTime() - teardownStart) / 1000000; + logPerClassCost(teardownCost, TOTAL_TEARDOWN_COST_MILLIS); + } + catch (Throwable tearingDown) { + if (exception == null) exception = tearingDown; } } - - if(exception != null) { - throw exception; - } + if (exception != null) throw exception; } + /** + * Logs the setup cost grouped by test fixture class (superclass of the current test class). + * + * @param cost setup cost in milliseconds + */ private void logPerClassCost(long cost, Map costMap) { - Class superclass = this.getClass().getSuperclass(); - Long oldCost = (Long)costMap.get(superclass.getName()); - long newCost = oldCost == null?cost:oldCost.longValue() + cost; - costMap.put(superclass.getName(), Long.valueOf(newCost)); - } - - public static void logSetupTeardownCosts() { - long totalSetup = 0L; - long totalTeardown = 0L; - System.out.println("Setup costs"); - - Iterator var4; - Map.Entry entry; - for(var4 = TOTAL_SETUP_COST_MILLIS.entrySet().iterator(); var4.hasNext(); totalSetup += ((Long)entry.getValue()).longValue()) { - entry = (Map.Entry)var4.next(); - System.out.println(String.format(" %s: %d ms", new Object[]{entry.getKey(), entry.getValue()})); - } - - System.out.println("Teardown costs"); - - for(var4 = TOTAL_TEARDOWN_COST_MILLIS.entrySet().iterator(); var4.hasNext(); totalTeardown += ((Long)entry.getValue()).longValue()) { - entry = (Map.Entry)var4.next(); - System.out.println(String.format(" %s: %d ms", new Object[]{entry.getKey(), entry.getValue()})); - } - - System.out.println(String.format("Total overhead: setup %d ms, teardown %d ms", new Object[]{Long.valueOf(totalSetup), Long.valueOf(totalTeardown)})); - System.out.println(String.format("##teamcity[buildStatisticValue key=\'ideaTests.totalSetupMs\' value=\'%d\']", new Object[]{Long.valueOf(totalSetup)})); - System.out.println(String.format("##teamcity[buildStatisticValue key=\'ideaTests.totalTeardownMs\' value=\'%d\']", new Object[]{Long.valueOf(totalTeardown)})); + Class superclass = getClass().getSuperclass(); + Long oldCost = costMap.get(superclass.getName()); + long newCost = oldCost == null ? cost : oldCost + cost; + costMap.put(superclass.getName(), newCost); } + @Override public void runBare() throws Throwable { - if(this.shouldRunTest()) { - if(this.runInDispatchThread()) { - //TestRunnerUtil.replaceIdeEventQueueSafely(); - //EdtTestUtil.runInEdtAndWait(new ThrowableRunnable() { - // public void run() throws Throwable { - KtUsefulTestCase.this.defaultRunBare(); - // } - //}); - } else { - this.defaultRunBare(); - } - - } - } - - protected boolean runInDispatchThread() { - return true; + this.defaultRunBare(); } @NonNls public static String toString(Iterable collection) { - if(!collection.iterator().hasNext()) { + if (!collection.iterator().hasNext()) { return ""; - } else { - StringBuilder builder = new StringBuilder(); + } - for(Iterator var2 = collection.iterator(); var2.hasNext(); builder.append("\n")) { - Object o = var2.next(); - if(o instanceof THashSet) { - builder.append(new TreeSet((THashSet)o)); - } else { - builder.append(o); - } + StringBuilder builder = new StringBuilder(); + for (Object o : collection) { + if (o instanceof THashSet) { + builder.append(new TreeSet((THashSet)o)); } - - return builder.toString(); + else { + builder.append(o); + } + builder.append("\n"); } + return builder.toString(); } - public static void assertOrderedEquals(T[] actual, T... expected) { - assertOrderedEquals((Iterable)Arrays.asList(actual), (Object[])expected); - } - - public static void assertOrderedEquals(Iterable actual, T... expected) { - assertOrderedEquals((String)null, actual, expected); - } - - public static void assertOrderedEquals(@NotNull byte[] actual, @NotNull byte[] expected) { - assertEquals(actual.length, expected.length); - - for(int i = 0; i < actual.length; ++i) { - byte a = actual[i]; - byte e = expected[i]; - assertEquals("not equals at index: " + i, e, a); - } - - } - - public static void assertOrderedEquals(@NotNull int[] actual, @NotNull int[] expected) { - if(actual.length != expected.length) { - fail("Expected size: " + expected.length + "; actual: " + actual.length + "\nexpected: " + Arrays.toString(expected) + "\nactual : " + Arrays.toString(actual)); - } - - for(int i = 0; i < actual.length; ++i) { - int a = actual[i]; - int e = expected[i]; - assertEquals("not equals at index: " + i, e, a); - } - - } - - public static void assertOrderedEquals(String errorMsg, @NotNull Iterable actual, @NotNull T... expected) { + private static void assertOrderedEquals(String errorMsg, @NotNull Iterable actual, @NotNull T... expected) { Assert.assertNotNull(actual); Assert.assertNotNull(expected); - assertOrderedEquals(errorMsg, actual, (Collection)Arrays.asList(expected)); + assertOrderedEquals(errorMsg, actual, Arrays.asList(expected)); } - public static void assertOrderedEquals(Iterable actual, Collection expected) { - assertOrderedEquals((String)null, actual, (Collection)expected); - } - - public static void assertOrderedEquals(String erroMsg, Iterable actual, Collection expected) { - ArrayList list = new ArrayList(); - Iterator expectedString = actual.iterator(); - - while(expectedString.hasNext()) { - Object actualString = expectedString.next(); - list.add(actualString); + public static void assertOrderedEquals( + String erroMsg, + Iterable actual, + Collection expected) { + ArrayList list = new ArrayList(); + for (T t : actual) { + list.add(t); } - - if(!list.equals(new ArrayList(expected))) { - String expectedString1 = toString(expected); - String actualString1 = toString(actual); - Assert.assertEquals(erroMsg, expectedString1, actualString1); - Assert.fail("Warning! \'toString\' does not reflect the difference.\nExpected: " + expectedString1 + "\nActual: " + actualString1); + if (!list.equals(new ArrayList(expected))) { + String expectedString = toString(expected); + String actualString = toString(actual); + Assert.assertEquals(erroMsg, expectedString, actualString); + Assert.fail("Warning! 'toString' does not reflect the difference.\nExpected: " + expectedString + "\nActual: " + actualString); } - - } - - public static void assertOrderedCollection(T[] collection, @NotNull Consumer... checkers) { - Assert.assertNotNull(collection); - assertOrderedCollection((Collection)Arrays.asList(collection), checkers); } public static void assertSameElements(T[] collection, T... expected) { - assertSameElements((Collection)Arrays.asList(collection), (Object[])expected); + assertSameElements(Arrays.asList(collection), expected); } public static void assertSameElements(Collection collection, T... expected) { - assertSameElements((Collection)collection, (Collection)Arrays.asList(expected)); + assertSameElements(collection, Arrays.asList(expected)); } public static void assertSameElements(Collection collection, Collection expected) { - assertSameElements((String)null, 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))) { + 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) { - assertContainsOrdered(collection, (Collection)Arrays.asList(expected)); - } - - public static void assertContainsOrdered(Collection collection, Collection expected) { - ArrayList copy = new ArrayList(collection); - copy.retainAll(expected); - assertOrderedEquals(toString(collection), copy, (Collection)expected); - } - - public static void assertContainsElements(Collection collection, T... expected) { - assertContainsElements(collection, (Collection)Arrays.asList(expected)); - } - - public static void assertContainsElements(Collection collection, Collection expected) { - ArrayList copy = new ArrayList(collection); - copy.retainAll(expected); - assertSameElements(toString(collection), copy, expected); } public static String toString(Object[] collection, String separator) { - return toString((Collection)Arrays.asList(collection), separator); - } - - public static void assertDoesntContain(Collection collection, T... notExpected) { - assertDoesntContain(collection, (Collection)Arrays.asList(notExpected)); - } - - public static void assertDoesntContain(Collection collection, Collection notExpected) { - ArrayList expected = new ArrayList(collection); - expected.removeAll(notExpected); - assertSameElements((Collection)collection, (Collection)expected); + return toString(Arrays.asList(collection), separator); } public static String toString(Collection collection, String separator) { - List list = ContainerUtil.map2List(collection, new Function() { + List list = ContainerUtil.map2List(collection, new Function() { + @Override public String fun(Object o) { return String.valueOf(o); } @@ -615,207 +336,59 @@ public abstract class KtUsefulTestCase extends TestCase { Collections.sort(list); StringBuilder builder = new StringBuilder(); boolean flag = false; - - for(Iterator var5 = list.iterator(); var5.hasNext(); flag = true) { - String o = (String)var5.next(); - if(flag) { + for (String o : list) { + if (flag) { builder.append(separator); } - builder.append(o); + flag = true; } - return builder.toString(); } - public static void assertOrderedCollection(Collection collection, Consumer... checkers) { - Assert.assertNotNull(collection); - if(collection.size() != checkers.length) { - Assert.fail(toString(collection)); - } - - int i = 0; - - for(Iterator var3 = collection.iterator(); var3.hasNext(); ++i) { - Object actual = var3.next(); - - try { - checkers[i].consume(actual); - } catch (AssertionFailedError var6) { - System.out.println(i + ": " + actual); - throw var6; - } - } - - } - - public static void assertUnorderedCollection(T[] collection, Consumer... checkers) { - assertUnorderedCollection((Collection)Arrays.asList(collection), checkers); - } - - public static void assertUnorderedCollection(Collection collection, Consumer... checkers) { - Assert.assertNotNull(collection); - if(collection.size() != checkers.length) { - Assert.fail(toString(collection)); - } - - HashSet checkerSet = new HashSet(Arrays.asList(checkers)); - int i = 0; - Throwable lastError = null; - - for(Iterator var5 = collection.iterator(); var5.hasNext(); ++i) { - Object actual = var5.next(); - boolean flag = true; - - Throwable error; - for(Iterator var8 = checkerSet.iterator(); var8.hasNext(); lastError = error) { - Consumer condition = (Consumer)var8.next(); - error = accepts(condition, actual); - if(error == null) { - checkerSet.remove(condition); - flag = false; - break; - } - } - - if(flag) { - lastError.printStackTrace(); - Assert.fail("Incorrect element(" + i + "): " + actual); - } - } - - } - - private static Throwable accepts(Consumer condition, T actual) { - try { - condition.consume(actual); - return null; - } catch (Throwable var3) { - return var3; - } - } - @Contract("null, _ -> fail") public static T assertInstanceOf(Object o, 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)); - return (T) o; + @SuppressWarnings("unchecked") T t = (T)o; + return t; } - public static T assertOneElement(Collection collection) { - Assert.assertNotNull(collection); - Iterator iterator = collection.iterator(); - String toString = toString(collection); - Assert.assertTrue(toString, iterator.hasNext()); - Object t = iterator.next(); - Assert.assertFalse(toString, iterator.hasNext()); - return (T) t; + protected static void assertEmpty(String errorMsg, Collection collection) { + //noinspection unchecked + assertOrderedEquals(errorMsg, collection); } - public static T assertOneElement(T[] ts) { - Assert.assertNotNull(ts); - Assert.assertEquals(Arrays.asList(ts).toString(), 1L, (long)ts.length); - return ts[0]; - } - - @Contract("null, _ -> fail") - public static void assertOneOf(T value, T... values) { - boolean found = false; - Object[] var3 = values; - int var4 = values.length; - - for(int var5 = 0; var5 < var4; ++var5) { - Object v = var3[var5]; - if(value == v || value != null && value.equals(v)) { - found = true; - } - } - - Assert.assertTrue(value + " should be equal to one of " + Arrays.toString(values), found); - } - - public static void printThreadDump() { - PerformanceWatcher.dumpThreadsToConsole("Thread dump:"); - } - - public static void assertEmpty(Object[] array) { - assertOrderedEquals(array, new Object[0]); - } - - public static void assertNotEmpty(Collection collection) { - if(collection != null) { - assertTrue(!collection.isEmpty()); - } - } - - public static void assertEmpty(Collection collection) { - assertEmpty(collection.toString(), collection); - } - - public static void assertNullOrEmpty(Collection collection) { - if(collection != null) { - assertEmpty((String)null, collection); - } - } - - public static void assertEmpty(String s) { - assertTrue(s, StringUtil.isEmpty(s)); - } - - public static void assertEmpty(String errorMsg, Collection collection) { - assertOrderedEquals(errorMsg, collection, (T[])(new Object[0])); - } - - public static void assertSize(int expectedSize, Object[] array) { + protected static void assertSize(int expectedSize, Object[] array) { assertEquals(toString(Arrays.asList(array)), expectedSize, array.length); } - public static void assertSize(int expectedSize, Collection c) { - assertEquals(toString(c), expectedSize, c.size()); - } - - protected T disposeOnTearDown(T disposable) { - Disposer.register(this.myTestRootDisposable, disposable); - return disposable; - } - public static void assertSameLines(String expected, String actual) { String expectedText = StringUtil.convertLineSeparators(expected.trim()); String actualText = StringUtil.convertLineSeparators(actual.trim()); Assert.assertEquals(expectedText, actualText); } - public static void assertExists(File file) { - assertTrue("File should exist " + file, file.exists()); - } - - public static void assertDoesntExist(File file) { - assertFalse("File should not exist " + file, file.exists()); - } - protected String getTestName(boolean lowercaseFirstLetter) { - return getTestName(this.getName(), lowercaseFirstLetter); + return getTestName(getName(), lowercaseFirstLetter); } public static String getTestName(String name, boolean lowercaseFirstLetter) { - return name == null? "": KtPlatformTestUtil.getTestName(name, lowercaseFirstLetter); + return name == null ? "" : KtPlatformTestUtil.getTestName(name, lowercaseFirstLetter); } - /** @deprecated */ + /** @deprecated use {@link KtPlatformTestUtil#lowercaseFirstLetter(String, boolean)} (to be removed in IDEA 17) */ + @SuppressWarnings("unused") public static String lowercaseFirstLetter(String name, boolean lowercaseFirstLetter) { return KtPlatformTestUtil.lowercaseFirstLetter(name, lowercaseFirstLetter); } - /** @deprecated */ + /** @deprecated use {@link KtPlatformTestUtil#isAllUppercaseName(String)} (to be removed in IDEA 17) */ + @SuppressWarnings("unused") public static boolean isAllUppercaseName(String name) { return KtPlatformTestUtil.isAllUppercaseName(name); } - protected String getTestDirectoryName() { - String testName = this.getTestName(true); - return testName.replaceAll("_.*", ""); - } - public static void assertSameLinesWithFile(String filePath, String actualText) { assertSameLinesWithFile(filePath, actualText, true); } @@ -823,291 +396,46 @@ public abstract class KtUsefulTestCase extends TestCase { public static void assertSameLinesWithFile(String filePath, String actualText, boolean trimBeforeComparing) { String fileText; try { - if(OVERWRITE_TESTDATA) { - VfsTestUtil.overwriteTestData(filePath, actualText); - System.out.println("File " + filePath + " created."); - } - fileText = FileUtil.loadFile(new File(filePath), CharsetToolkit.UTF8_CHARSET); - } catch (FileNotFoundException var6) { + } + catch (FileNotFoundException e) { VfsTestUtil.overwriteTestData(filePath, actualText); throw new AssertionFailedError("No output text found. File " + filePath + " created."); - } catch (IOException var7) { - throw new RuntimeException(var7); } - - String expected = StringUtil.convertLineSeparators(trimBeforeComparing?fileText.trim():fileText); - String actual = StringUtil.convertLineSeparators(trimBeforeComparing?actualText.trim():actualText); - if(!Comparing.equal(expected, actual)) { - throw new FileComparisonFailure((String)null, expected, actual, filePath); + catch (IOException e) { + throw new RuntimeException(e); + } + String expected = StringUtil.convertLineSeparators(trimBeforeComparing ? fileText.trim() : fileText); + String actual = StringUtil.convertLineSeparators(trimBeforeComparing ? actualText.trim() : actualText); + if (!Comparing.equal(expected, actual)) { + throw new FileComparisonFailure(null, expected, actual, filePath); } } public static void clearFields(Object test) throws IllegalAccessException { - for(Class aClass = test.getClass(); aClass != null; aClass = aClass.getSuperclass()) { + Class aClass = test.getClass(); + while (aClass != null) { clearDeclaredFields(test, aClass); - } - - } - - public static void clearDeclaredFields(Object test, Class aClass) throws IllegalAccessException { - if(aClass != null) { - Field[] var2 = aClass.getDeclaredFields(); - int var3 = var2.length; - - for(int var4 = 0; var4 < var3; ++var4) { - Field field = var2[var4]; - String name = field.getDeclaringClass().getName(); - if(!name.startsWith("junit.framework.") && !name.startsWith("com.intellij.testFramework.")) { - int modifiers = field.getModifiers(); - if((modifiers & 16) == 0 && (modifiers & 8) == 0 && !field.getType().isPrimitive()) { - field.setAccessible(true); - field.set(test, (Object)null); - } - } - } - + aClass = aClass.getSuperclass(); } } - protected static void checkSettingsEqual(CodeStyleSettings expected, CodeStyleSettings settings, String message) throws Exception { - if(expected != null && settings != null) { - Element oldS = new Element("temp"); - expected.writeExternal(oldS); - Element newS = new Element("temp"); - settings.writeExternal(newS); - String newString = JDOMUtil.writeElement(newS, "\n"); - String oldString = JDOMUtil.writeElement(oldS, "\n"); - Assert.assertEquals(message, oldString, newString); - } - } - - public boolean isPerformanceTest() { - String name = this.getName(); - return name != null && name.contains("Performance") || this.getClass().getName().contains("Performance"); - } - - protected static void checkAllTimersAreDisposed(@NotNull List exceptions) { - Field firstTimerF; - Object timerQueue; - Object timer; - try { - Class text = Class.forName("javax.swing.TimerQueue"); - Method t = text.getDeclaredMethod("sharedInstance", new Class[0]); - t.setAccessible(true); - firstTimerF = ReflectionUtil.getDeclaredField(text, "firstTimer"); - timerQueue = t.invoke((Object)null, new Object[0]); - if(firstTimerF == null) { - DelayQueue delayQueue = (DelayQueue)ReflectionUtil.getField(text, timerQueue, DelayQueue.class, "queue"); - timer = delayQueue.peek(); - } else { - firstTimerF.setAccessible(true); - timer = firstTimerF.get(timerQueue); - } - } catch (Throwable var10) { - exceptions.add(var10); - return; - } - - if(timer != null) { - if(firstTimerF != null) { - ReflectionUtil.resetField(timerQueue, firstTimerF); - } - - String var11 = ""; - if(timer instanceof Delayed) { - long var12 = ((Delayed)timer).getDelay(TimeUnit.MILLISECONDS); - var11 = "(delayed for " + var12 + "ms)"; - Method getTimer = ReflectionUtil.getDeclaredMethod(timer.getClass(), "getTimer", new Class[0]); - getTimer.setAccessible(true); - - try { - timer = getTimer.invoke(timer, new Object[0]); - } catch (Exception var9) { - exceptions.add(var9); - return; - } - } - - javax.swing.Timer var13 = (javax.swing.Timer)timer; - var11 = "Timer (listeners: " + Arrays.asList(var13.getActionListeners()) + ") " + var11; - exceptions.add(new AssertionFailedError("Not disposed Timer: " + var11 + "; queue:" + timerQueue)); - } - - } - - protected void assertException(AbstractExceptionCase exceptionCase) throws Throwable { - this.assertException(exceptionCase, (String)null); - } - - protected void assertException(AbstractExceptionCase exceptionCase, @Nullable String expectedErrorMsg) throws Throwable { - assertExceptionOccurred(true, exceptionCase, expectedErrorMsg); - } - - protected void assertNoException(AbstractExceptionCase exceptionCase) throws Throwable { - assertExceptionOccurred(false, exceptionCase, (String)null); - } - - protected void assertNoThrowable(Runnable closure) { - String throwableName = null; - - try { - closure.run(); - } catch (Throwable var4) { - throwableName = var4.getClass().getName(); - } - - assertNull(throwableName); - } - - private static void assertExceptionOccurred(boolean shouldOccur, AbstractExceptionCase exceptionCase, String expectedErrorMsg) throws Throwable { - boolean wasThrown = false; - - try { - exceptionCase.tryClosure(); - } catch (Throwable var9) { - if(shouldOccur) { - wasThrown = true; - String errorMessage = exceptionCase.getAssertionErrorMessage(); - assertEquals(errorMessage, exceptionCase.getExpectedExceptionClass(), var9.getClass()); - if(expectedErrorMsg != null) { - assertEquals("Compare error messages", expectedErrorMsg, var9.getMessage()); - } - } else { - if(!exceptionCase.getExpectedExceptionClass().equals(var9.getClass())) { - throw var9; - } - - wasThrown = true; - System.out.println(""); - var9.printStackTrace(System.out); - fail("Exception isn\'t expected here. Exception message: " + var9.getMessage()); - } - } finally { - if(shouldOccur && !wasThrown) { - fail(exceptionCase.getAssertionErrorMessage()); - } - - } - - } - - protected boolean annotatedWith(@NotNull Class annotationClass) { - Class aClass = this.getClass(); - String methodName = "test" + this.getTestName(false); - - for(boolean methodChecked = false; aClass != null && aClass != Object.class; aClass = aClass.getSuperclass()) { - if(aClass.getAnnotation(annotationClass) != null) { - return true; - } - - if(!methodChecked) { - Method method = ReflectionUtil.getDeclaredMethod(aClass, methodName, new Class[0]); - if(method != null) { - if(method.getAnnotation(annotationClass) != null) { - return true; - } - - methodChecked = true; + private static void clearDeclaredFields(Object test, Class aClass) throws IllegalAccessException { + if (aClass == null) return; + for (Field field : aClass.getDeclaredFields()) { + @NonNls String name = field.getDeclaringClass().getName(); + if (!name.startsWith("junit.framework.") && !name.startsWith("com.intellij.testFramework.")) { + int modifiers = field.getModifiers(); + if ((modifiers & Modifier.FINAL) == 0 && (modifiers & Modifier.STATIC) == 0 && !field.getType().isPrimitive()) { + field.setAccessible(true); + field.set(test, null); } } } - - return false; } - protected String getHomePath() { - return PathManager.getHomePath().replace(File.separatorChar, '/'); + private boolean isPerformanceTest() { + String name = getName(); + return name != null && name.contains("Performance") || getClass().getName().contains("Performance"); } - - protected static boolean isInHeadlessEnvironment() { - return GraphicsEnvironment.isHeadless(); - } - - public static void refreshRecursively(@NotNull VirtualFile file) { - VfsUtilCore.visitChildrenRecursively(file, new VirtualFileVisitor(new VirtualFileVisitor.Option[0]) { - public boolean visitFile(@NotNull VirtualFile file) { - file.getChildren(); - return true; - } - }); - file.refresh(false, true); - } - - //@NotNull - //public static Test filteredSuite(@RegExp String regexp, @NotNull Test test) { - // final Pattern pattern = Pattern.compile(regexp); - // final TestSuite testSuite = new TestSuite(); - // (new Processor() { - // public boolean process(Test test) { - // if(test instanceof TestSuite) { - // int i = 0; - // - // for(int len = ((TestSuite)test).testCount(); i < len; ++i) { - // this.process(((TestSuite)test).testAt(i)); - // } - // } else if(pattern.matcher(test.toString()).find()) { - // testSuite.addTest(test); - // } - // - // return false; - // } - // }).process(test); - // return testSuite; - //} - - @Nullable - public static VirtualFile refreshAndFindFile(@NotNull final File file) { - return (VirtualFile)UIUtil.invokeAndWaitIfNeeded(new Computable() { - public VirtualFile compute() { - return LocalFileSystem.getInstance().refreshAndFindFileByIoFile(file); - } - }); - } - - public static void invokeAndWaitIfNeeded(@NotNull final ThrowableRunnable runnable) throws Exception { - if(SwingUtilities.isEventDispatchThread()) { - runnable.run(); - } else { - final Ref ref = Ref.create(); - SwingUtilities.invokeAndWait(new Runnable() { - public void run() { - try { - runnable.run(); - } catch (Exception var2) { - ref.set(var2); - } - - } - }); - if(!ref.isNull()) { - throw (Exception)ref.get(); - } - } - - } - - static { - System.setProperty("apple.awt.UIElement", "true"); - - try { - //CodeInsightSettings aClass = new CodeInsightSettings(); - Element files = new Element("temp"); - //aClass.writeExternal(files); - DEFAULT_SETTINGS_EXTERNALIZED = JDOMUtil.writeElement(files, "\n"); - } catch (Exception var3) { - throw new RuntimeException(var3); - } - - Class aClass1; - try { - aClass1 = Class.forName("java.io.DeleteOnExitHook"); - } catch (Exception var2) { - throw new RuntimeException(var2); - } - - Set files1 = (Set)ReflectionUtil.getStaticFieldValue(aClass1, Set.class, "files"); - DELETE_ON_EXIT_HOOK_CLASS = aClass1; - DELETE_ON_EXIT_HOOK_DOT_FILES = files1; - } -} +} \ No newline at end of file diff --git a/compiler/tests/org/jetbrains/kotlin/test/testFramework/MockProjects.kt b/compiler/tests/org/jetbrains/kotlin/test/testFramework/MockProjects.kt index 73536c50fa2..c2ceff36b11 100644 --- a/compiler/tests/org/jetbrains/kotlin/test/testFramework/MockProjects.kt +++ b/compiler/tests/org/jetbrains/kotlin/test/testFramework/MockProjects.kt @@ -20,17 +20,8 @@ import com.intellij.mock.MockProject import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.project.Project -import com.intellij.util.messages.Topic interface ProjectEx : Project { - interface ProjectSaved { - fun saved(project: Project) - - companion object { - val TOPIC = Topic.create("SaveProjectTopic", ProjectSaved::class.java, Topic.BroadcastDirection.NONE) - } - } - fun init() fun setProjectName(name: String) diff --git a/compiler/tests/org/jetbrains/kotlin/test/testFramework/TestRunnerUtil.java b/compiler/tests/org/jetbrains/kotlin/test/testFramework/TestRunnerUtil.java index 17b1221e548..d8fa3ce44a7 100644 --- a/compiler/tests/org/jetbrains/kotlin/test/testFramework/TestRunnerUtil.java +++ b/compiler/tests/org/jetbrains/kotlin/test/testFramework/TestRunnerUtil.java @@ -27,8 +27,8 @@ public class TestRunnerUtil { } @TestOnly - public static boolean isJUnit4TestClass(final Class aClass) { - final int modifiers = aClass.getModifiers(); + public static boolean isJUnit4TestClass(Class aClass) { + int modifiers = aClass.getModifiers(); if ((modifiers & Modifier.ABSTRACT) != 0) return false; if ((modifiers & Modifier.PUBLIC) == 0) return false; if (aClass.getAnnotation(RunWith.class) != null) return true; @@ -37,30 +37,4 @@ public class TestRunnerUtil { } return false; } - - //public static void replaceIdeEventQueueSafely() { - // if (Toolkit.getDefaultToolkit().getSystemEventQueue() instanceof IdeEventQueue) { - // return; - // } - // if (SwingUtilities.isEventDispatchThread()) { - // throw new RuntimeException("must not call under EDT"); - // } - // AWTAutoShutdown.getInstance().notifyThreadBusy(Thread.currentThread()); - // UIUtil.pump(); - // // in JDK 1.6 java.awt.EventQueue.push() causes slow painful death of current EDT - // // so we have to wait through its agony to termination - // try { - // SwingUtilities.invokeAndWait(new Runnable() { - // @Override - // public void run() { - // IdeEventQueue.getInstance(); - // } - // }); - // SwingUtilities.invokeAndWait(EmptyRunnable.getInstance()); - // SwingUtilities.invokeAndWait(EmptyRunnable.getInstance()); - // } - // catch (Exception e) { - // throw new RuntimeException(e); - // } - //} } diff --git a/compiler/tests/org/jetbrains/kotlin/test/testFramework/VfsTestUtil.java b/compiler/tests/org/jetbrains/kotlin/test/testFramework/VfsTestUtil.java index 9bc014d52d6..f18f6847e95 100644 --- a/compiler/tests/org/jetbrains/kotlin/test/testFramework/VfsTestUtil.java +++ b/compiler/tests/org/jetbrains/kotlin/test/testFramework/VfsTestUtil.java @@ -17,45 +17,34 @@ package org.jetbrains.kotlin.test.testFramework; import com.intellij.openapi.application.AccessToken; -import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.WriteAction; -import com.intellij.openapi.util.Key; -import com.intellij.openapi.util.SystemInfo; 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.VirtualFile; import com.intellij.util.PathUtil; import com.intellij.util.text.StringTokenizer; -import org.jetbrains.annotations.NotNull; import org.junit.Assert; import java.io.File; import java.io.IOException; public class VfsTestUtil { - public static final Key TEST_DATA_FILE_PATH = Key.create("TEST_DATA_FILE_PATH"); - private VfsTestUtil() { } - public static VirtualFile createFile(final VirtualFile root, final String relativePath) { + public static VirtualFile createFile(VirtualFile root, String relativePath) { return createFile(root, relativePath, ""); } - public static VirtualFile createFile(final VirtualFile root, final String relativePath, final String text) { + public static VirtualFile createFile(VirtualFile root, String relativePath, String text) { return createFileOrDir(root, relativePath, text, false); } - public static VirtualFile createDir(final VirtualFile root, final String relativePath) { - return createFileOrDir(root, relativePath, "", true); - } - - private static VirtualFile createFileOrDir(final VirtualFile root, - final String relativePath, - final String text, - final boolean dir) { + private static VirtualFile createFileOrDir( + VirtualFile root, + String relativePath, + String text, + boolean dir) { try { AccessToken token = WriteAction.start(); try { @@ -63,7 +52,7 @@ public class VfsTestUtil { Assert.assertNotNull(parent); StringTokenizer parents = new StringTokenizer(PathUtil.getParentPath(relativePath), "/"); while (parents.hasMoreTokens()) { - final String name = parents.nextToken(); + String name = parents.nextToken(); VirtualFile child = parent.findChild(name); if (child == null || !child.isValid()) { child = parent.createChildDirectory(VfsTestUtil.class, name); @@ -94,24 +83,6 @@ public class VfsTestUtil { } } - public static void deleteFile(@NotNull VirtualFile file) { - UtilKt.deleteFile(file); - } - - public static void clearContent(@NotNull final VirtualFile file) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - try { - VfsUtil.saveText(file, ""); - } - catch (IOException e) { - throw new RuntimeException(e); - } - } - }); - } - @SuppressWarnings("UnusedDeclaration") public static void overwriteTestData(String filePath, String actual) { try { @@ -121,31 +92,4 @@ public class VfsTestUtil { throw new AssertionError(e); } } - - @NotNull - public static VirtualFile findFileByCaseSensitivePath(@NotNull String absolutePath) { - String vfsPath = FileUtil.toSystemIndependentName(absolutePath); - VirtualFile vFile = LocalFileSystem.getInstance().findFileByPath(vfsPath); - Assert.assertNotNull("file " + absolutePath + " not found", vFile); - String realVfsPath = vFile.getPath(); - if (!SystemInfo.isFileSystemCaseSensitive && !vfsPath.equals(realVfsPath) && - vfsPath.equalsIgnoreCase(realVfsPath)) { - Assert.fail("Please correct case-sensitivity of path to prevent test failure on case-sensitive file systems:\n" + - " path " + vfsPath + "\n" + - "real path " + realVfsPath); - } - return vFile; - } - - public static void assertFilePathEndsWithCaseSensitivePath(@NotNull VirtualFile file, @NotNull String suffixPath) { - String vfsSuffixPath = FileUtil.toSystemIndependentName(suffixPath); - String vfsPath = file.getPath(); - if (!SystemInfo.isFileSystemCaseSensitive && !vfsPath.endsWith(vfsSuffixPath) && - StringUtil.endsWithIgnoreCase(vfsPath, vfsSuffixPath)) { - String realSuffixPath = vfsPath.substring(vfsPath.length() - vfsSuffixPath.length()); - Assert.fail("Please correct case-sensitivity of path to prevent test failure on case-sensitive file systems:\n" + - " path " + suffixPath + "\n" + - "real path " + realSuffixPath); - } - } } \ No newline at end of file diff --git a/compiler/tests/org/jetbrains/kotlin/test/testFramework/mock/KtMockFileTypeManager.java b/compiler/tests/org/jetbrains/kotlin/test/testFramework/mock/KtMockFileTypeManager.java index 6a23abe1eb5..a5330fdd662 100644 --- a/compiler/tests/org/jetbrains/kotlin/test/testFramework/mock/KtMockFileTypeManager.java +++ b/compiler/tests/org/jetbrains/kotlin/test/testFramework/mock/KtMockFileTypeManager.java @@ -16,9 +16,7 @@ package org.jetbrains.kotlin.test.testFramework.mock; -import com.intellij.mock.*; import com.intellij.openapi.fileTypes.*; -import com.intellij.openapi.fileTypes.MockLanguageFileType; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.ArrayUtil; @@ -26,7 +24,6 @@ import com.intellij.util.IncorrectOperationException; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import org.jetbrains.kotlin.test.testFramework.mock.KtMockLanguageFileType; import java.util.Collections; import java.util.List; @@ -49,14 +46,6 @@ public class KtMockFileTypeManager extends FileTypeManager { public void setIgnoredFilesList(@NotNull String list) { } - public void save() { - } - - @NotNull - public String getExtension(@NotNull String fileName) { - return ""; - } - @Override public void registerFileType(@NotNull FileType type, @NotNull List defaultAssociations) { } @@ -135,7 +124,7 @@ public class KtMockFileTypeManager extends FileTypeManager { @Override @NotNull - public FileType getStdFileType(@NotNull @NonNls final String fileTypeName) { + public FileType getStdFileType(@NotNull @NonNls String fileTypeName) { if ("ARCHIVE".equals(fileTypeName) || "CLASS".equals(fileTypeName)) return UnknownFileType.INSTANCE; if ("PLAIN_TEXT".equals(fileTypeName)) return PlainTextFileType.INSTANCE; if ("JAVA".equals(fileTypeName)) return loadFileTypeSafe("com.intellij.ide.highlighter.JavaFileType", fileTypeName); @@ -150,7 +139,7 @@ public class KtMockFileTypeManager extends FileTypeManager { return new KtMockLanguageFileType(PlainTextLanguage.INSTANCE, fileTypeName.toLowerCase()); } - private static FileType loadFileTypeSafe(final String className, String fileTypeName) { + private static FileType loadFileTypeSafe(String className, String fileTypeName) { try { return (FileType)Class.forName(className).getField("INSTANCE").get(null); } diff --git a/compiler/tests/org/jetbrains/kotlin/test/testFramework/mock/KtMockLanguageFileType.java b/compiler/tests/org/jetbrains/kotlin/test/testFramework/mock/KtMockLanguageFileType.java index 42efbad4322..4481046868b 100644 --- a/compiler/tests/org/jetbrains/kotlin/test/testFramework/mock/KtMockLanguageFileType.java +++ b/compiler/tests/org/jetbrains/kotlin/test/testFramework/mock/KtMockLanguageFileType.java @@ -18,7 +18,7 @@ package org.jetbrains.kotlin.test.testFramework.mock; import com.intellij.lang.Language; import com.intellij.openapi.fileTypes.LanguageFileType; -import com.sun.istack.internal.NotNull; +import org.jetbrains.annotations.NotNull; import javax.swing.*; @@ -30,16 +30,19 @@ public class KtMockLanguageFileType extends LanguageFileType { this.myExtension = extension; } + @Override @NotNull public String getName() { return this.getLanguage().getID(); } + @Override @NotNull public String getDescription() { return ""; } + @Override @NotNull public String getDefaultExtension() { String var10000 = this.myExtension; @@ -50,11 +53,12 @@ public class KtMockLanguageFileType extends LanguageFileType { } } + @Override public Icon getIcon() { return null; } public boolean equals(Object obj) { - return !(obj instanceof LanguageFileType)?false:this.getLanguage().equals(((LanguageFileType)obj).getLanguage()); + return obj instanceof LanguageFileType && this.getLanguage().equals(((LanguageFileType) obj).getLanguage()); } } \ No newline at end of file diff --git a/compiler/tests/org/jetbrains/kotlin/test/testFramework/mock/MockEditorEventMulticaster.java b/compiler/tests/org/jetbrains/kotlin/test/testFramework/mock/MockEditorEventMulticaster.java index 1e05181c7be..2f03527e5b6 100644 --- a/compiler/tests/org/jetbrains/kotlin/test/testFramework/mock/MockEditorEventMulticaster.java +++ b/compiler/tests/org/jetbrains/kotlin/test/testFramework/mock/MockEditorEventMulticaster.java @@ -40,7 +40,7 @@ public class MockEditorEventMulticaster implements EditorEventMulticaster { } @Override - public void addEditorMouseListener(@NotNull final EditorMouseListener listener, @NotNull final Disposable parentDisposable) { + public void addEditorMouseListener(@NotNull EditorMouseListener listener, @NotNull Disposable parentDisposable) { } @Override diff --git a/compiler/tests/org/jetbrains/kotlin/test/testFramework/mock/MockEditorFactory.java b/compiler/tests/org/jetbrains/kotlin/test/testFramework/mock/MockEditorFactory.java index 5abec62a846..7473ec9cd2f 100644 --- a/compiler/tests/org/jetbrains/kotlin/test/testFramework/mock/MockEditorFactory.java +++ b/compiler/tests/org/jetbrains/kotlin/test/testFramework/mock/MockEditorFactory.java @@ -29,10 +29,6 @@ import com.intellij.util.text.CharArrayCharSequence; import org.jetbrains.annotations.NotNull; public class MockEditorFactory extends EditorFactory { - public Document createDocument(String text) { - return new DocumentImpl(text); - } - @Override public Editor createEditor(@NotNull Document document) { return null; @@ -54,7 +50,7 @@ public class MockEditorFactory extends EditorFactory { } @Override - public Editor createEditor(@NotNull final Document document, final Project project, @NotNull final FileType fileType, final boolean isViewer) { + public Editor createEditor(@NotNull Document document, Project project, @NotNull FileType fileType, boolean isViewer) { return null; } diff --git a/compiler/tests/org/jetbrains/kotlin/test/testFramework/mock/MockPsiDocumentManager.java b/compiler/tests/org/jetbrains/kotlin/test/testFramework/mock/MockPsiDocumentManager.java index 48bfeeb2813..812636f983b 100644 --- a/compiler/tests/org/jetbrains/kotlin/test/testFramework/mock/MockPsiDocumentManager.java +++ b/compiler/tests/org/jetbrains/kotlin/test/testFramework/mock/MockPsiDocumentManager.java @@ -57,7 +57,7 @@ public class MockPsiDocumentManager extends PsiDocumentManager { } @Override - public void performForCommittedDocument(@NotNull final Document document, @NotNull final Runnable action) { + public void performForCommittedDocument(@NotNull Document document, @NotNull Runnable action) { action.run(); } diff --git a/compiler/tests/org/jetbrains/kotlin/test/testFramework/mock/MockPsiManager.java b/compiler/tests/org/jetbrains/kotlin/test/testFramework/mock/MockPsiManager.java index 8d0c382a14b..ec799338a6b 100644 --- a/compiler/tests/org/jetbrains/kotlin/test/testFramework/mock/MockPsiManager.java +++ b/compiler/tests/org/jetbrains/kotlin/test/testFramework/mock/MockPsiManager.java @@ -43,6 +43,7 @@ public class MockPsiManager extends PsiManagerEx { myProject = project; } + @SuppressWarnings("unused") public void addPsiDirectory(VirtualFile file, PsiDirectory psiDirectory) { myDirectories.put(file, psiDirectory); } @@ -175,11 +176,11 @@ public class MockPsiManager extends PsiManagerEx { } @Override - public void beforeChildRemoval(@NotNull final PsiTreeChangeEventImpl event) { + public void beforeChildRemoval(@NotNull PsiTreeChangeEventImpl event) { } @Override - public void beforeChildReplacement(@NotNull final PsiTreeChangeEventImpl event) { + public void beforeChildReplacement(@NotNull PsiTreeChangeEventImpl event) { } @Override diff --git a/compiler/tests/org/jetbrains/kotlin/test/testFramework/mock/MockSchemesManagerFactory.java b/compiler/tests/org/jetbrains/kotlin/test/testFramework/mock/MockSchemesManagerFactory.java index 80cd84785de..e53eebf2c98 100644 --- a/compiler/tests/org/jetbrains/kotlin/test/testFramework/mock/MockSchemesManagerFactory.java +++ b/compiler/tests/org/jetbrains/kotlin/test/testFramework/mock/MockSchemesManagerFactory.java @@ -28,6 +28,7 @@ public class MockSchemesManagerFactory extends SchemesManagerFactory { @NotNull SchemeProcessor processor, @NotNull RoamingType roamingType, @Nullable String presentableName) { + //noinspection unchecked return EMPTY; } } diff --git a/compiler/tests/org/jetbrains/kotlin/test/testFramework/mock/PsiManagerEx.java b/compiler/tests/org/jetbrains/kotlin/test/testFramework/mock/PsiManagerEx.java deleted file mode 100644 index 0779e012987..00000000000 --- a/compiler/tests/org/jetbrains/kotlin/test/testFramework/mock/PsiManagerEx.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright 2010-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 org.jetbrains.kotlin.test.testFramework.mock; - -import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.psi.PsiManager; -import com.intellij.psi.impl.PsiTreeChangeEventImpl; -import com.intellij.psi.impl.file.impl.FileManager; -import org.jetbrains.annotations.NotNull; - -public abstract class PsiManagerEx extends PsiManager { - public abstract boolean isBatchFilesProcessingMode(); - - public abstract boolean isAssertOnFileLoading(@NotNull VirtualFile file); - - /** - * @param runnable to be run before physical PSI change - */ - public abstract void registerRunnableToRunOnChange(@NotNull Runnable runnable); - - /** - * @param runnable to be run before physical or non-physical PSI change - */ - public abstract void registerRunnableToRunOnAnyChange(@NotNull Runnable runnable); - - public abstract void registerRunnableToRunAfterAnyChange(@NotNull Runnable runnable); - - @NotNull - public abstract FileManager getFileManager(); - - public abstract void beforeChildAddition(@NotNull PsiTreeChangeEventImpl event); - - public abstract void beforeChildRemoval(@NotNull PsiTreeChangeEventImpl event); - - public abstract void beforeChildReplacement(@NotNull PsiTreeChangeEventImpl event); - - public abstract void beforeChange(boolean isPhysical); - - public abstract void afterChange(boolean isPhysical); -} diff --git a/compiler/tests/org/jetbrains/kotlin/test/testFramework/util.kt b/compiler/tests/org/jetbrains/kotlin/test/testFramework/util.kt index b041779047b..fdd1ef66c62 100644 --- a/compiler/tests/org/jetbrains/kotlin/test/testFramework/util.kt +++ b/compiler/tests/org/jetbrains/kotlin/test/testFramework/util.kt @@ -21,17 +21,6 @@ import com.intellij.openapi.components.ComponentManager import com.intellij.openapi.vfs.VirtualFile import org.picocontainer.MutablePicoContainer -fun ComponentManager.registerServiceInstance(interfaceClass: Class, instance: T) { - val picoContainer = picoContainer as MutablePicoContainer - val key = interfaceClass.name - picoContainer.unregisterComponent(key) - picoContainer.registerComponentInstance(key, instance) -} - -fun deleteFile(file: VirtualFile) { - runInEdtAndWait { runWriteAction { file.delete(null) } } -} - fun runWriteAction(action: () -> T): T { return ApplicationManager.getApplication().runWriteAction(action) } \ No newline at end of file