From 4f7257ab669723626b968580cc82d5347e60210c Mon Sep 17 00:00:00 2001 From: Nikolay Krasko Date: Tue, 22 Mar 2016 16:48:06 +0300 Subject: [PATCH] Remove dependency to idea.jar in compiler tets to continue running them with JDK 1.6 --- .idea/compiler.xml | 2 - .idea/modules.xml | 1 - .../intellij/testFramework/TestDataFile.java | 29 + .../intellij/testFramework/TestDataPath.java | 33 + compiler/tests/compiler-tests.iml | 40 +- .../kotlin/cli/WrongBytecodeVersionTest.kt | 4 +- .../kotlin/codegen/CodegenTestCase.java | 4 +- .../kotlin/codegen/CustomBytecodeTextTest.kt | 4 +- .../jetbrains/kotlin/codegen/StdlibTest.java | 2 +- .../codegen/flags/AbstractWriteFlagsTest.java | 4 +- .../kotlin/integration/AntTaskJsTest.java | 6 +- .../KotlinIntegrationTestBase.java | 33 +- .../DeserializedScopeValidationVisitor.kt | 14 +- .../jvm/compiler/ExpectedLoadErrorsUtil.java | 4 +- .../MultiModuleJavaAnalysisCustomTest.kt | 4 +- .../kotlin/parsing/AbstractParsingTest.java | 8 +- .../AbstractDescriptorRendererTest.kt | 4 +- ...ctionDescriptorInExpressionRendererTest.kt | 4 +- .../repl/AbstractReplInterpreterTest.kt | 4 +- .../serialization/jvm/BitEncodingTest.java | 4 +- .../serialization/jvm/JvmNameResolverTest.kt | 9 +- .../KotlinTestWithEnvironmentManagement.java | 4 +- .../kotlin/test/TestCaseWithTmpdir.java | 4 +- .../testFramework/AbstractExceptionCase.java | 35 + .../kotlin/test/testFramework/EdtTestUtil.kt | 53 + .../test/testFramework/KtParsingTestCase.java | 342 +++++ .../testFramework/KtPlatformLiteFixture.java | 103 ++ .../testFramework/KtPlatformTestUtil.java | 905 ++++++++++++++ .../test/testFramework/KtUsefulTestCase.java | 1113 +++++++++++++++++ .../kotlin/test/testFramework/MockProjects.kt | 45 + .../test/testFramework/TestRunnerUtil.java | 66 + .../test/testFramework/VfsTestUtil.java | 151 +++ .../mock/KtMockFileTypeManager.java | 178 +++ .../mock/KtMockLanguageFileType.java | 60 + .../mock/MockEditorEventMulticaster.java | 94 ++ .../testFramework/mock/MockEditorFactory.java | 122 ++ .../testFramework/mock/MockFileManager.java | 107 ++ .../mock/MockPsiDocumentManager.java | 146 +++ .../testFramework/mock/MockPsiManager.java | 188 +++ .../mock/MockSchemesManagerFactory.java | 33 + .../test/testFramework/mock/PsiManagerEx.java | 53 + .../kotlin/test/testFramework/util.kt | 37 + idea/idea.iml | 2 +- ...tAndroidSyntheticPropertyDescriptorTest.kt | 3 +- .../resolve/android/test/CompilerTestUtils.kt | 4 +- temp-jdk8/temp-jdk8.iml | 11 - update_dependencies.xml | 9 + 47 files changed, 4016 insertions(+), 69 deletions(-) create mode 100644 compiler/tests/com/intellij/testFramework/TestDataFile.java create mode 100644 compiler/tests/com/intellij/testFramework/TestDataPath.java create mode 100644 compiler/tests/org/jetbrains/kotlin/test/testFramework/AbstractExceptionCase.java create mode 100644 compiler/tests/org/jetbrains/kotlin/test/testFramework/EdtTestUtil.kt create mode 100644 compiler/tests/org/jetbrains/kotlin/test/testFramework/KtParsingTestCase.java create mode 100644 compiler/tests/org/jetbrains/kotlin/test/testFramework/KtPlatformLiteFixture.java create mode 100644 compiler/tests/org/jetbrains/kotlin/test/testFramework/KtPlatformTestUtil.java create mode 100644 compiler/tests/org/jetbrains/kotlin/test/testFramework/KtUsefulTestCase.java create mode 100644 compiler/tests/org/jetbrains/kotlin/test/testFramework/MockProjects.kt create mode 100644 compiler/tests/org/jetbrains/kotlin/test/testFramework/TestRunnerUtil.java create mode 100644 compiler/tests/org/jetbrains/kotlin/test/testFramework/VfsTestUtil.java create mode 100644 compiler/tests/org/jetbrains/kotlin/test/testFramework/mock/KtMockFileTypeManager.java create mode 100644 compiler/tests/org/jetbrains/kotlin/test/testFramework/mock/KtMockLanguageFileType.java create mode 100644 compiler/tests/org/jetbrains/kotlin/test/testFramework/mock/MockEditorEventMulticaster.java create mode 100644 compiler/tests/org/jetbrains/kotlin/test/testFramework/mock/MockEditorFactory.java create mode 100644 compiler/tests/org/jetbrains/kotlin/test/testFramework/mock/MockFileManager.java create mode 100644 compiler/tests/org/jetbrains/kotlin/test/testFramework/mock/MockPsiDocumentManager.java create mode 100644 compiler/tests/org/jetbrains/kotlin/test/testFramework/mock/MockPsiManager.java create mode 100644 compiler/tests/org/jetbrains/kotlin/test/testFramework/mock/MockSchemesManagerFactory.java create mode 100644 compiler/tests/org/jetbrains/kotlin/test/testFramework/mock/PsiManagerEx.java create mode 100644 compiler/tests/org/jetbrains/kotlin/test/testFramework/util.kt delete mode 100644 temp-jdk8/temp-jdk8.iml diff --git a/.idea/compiler.xml b/.idea/compiler.xml index 83f969e6f0f..0aca5a0eed1 100644 --- a/.idea/compiler.xml +++ b/.idea/compiler.xml @@ -24,7 +24,6 @@ - @@ -37,7 +36,6 @@ - \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml index 07f3873960b..d7791229684 100644 --- a/.idea/modules.xml +++ b/.idea/modules.xml @@ -66,7 +66,6 @@ - diff --git a/compiler/tests/com/intellij/testFramework/TestDataFile.java b/compiler/tests/com/intellij/testFramework/TestDataFile.java new file mode 100644 index 00000000000..75b4a8c1750 --- /dev/null +++ b/compiler/tests/com/intellij/testFramework/TestDataFile.java @@ -0,0 +1,29 @@ +/* + * Copyright 2000-2010 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.intellij.testFramework; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Marks the annotated parameter as referencing a file in the testdata directory. + */ +@Retention(RetentionPolicy.SOURCE) +@Target({ElementType.PARAMETER}) +public @interface TestDataFile { +} diff --git a/compiler/tests/com/intellij/testFramework/TestDataPath.java b/compiler/tests/com/intellij/testFramework/TestDataPath.java new file mode 100644 index 00000000000..48e95c3502d --- /dev/null +++ b/compiler/tests/com/intellij/testFramework/TestDataPath.java @@ -0,0 +1,33 @@ +/* + * 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 com.intellij.testFramework; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Specifies the path to testdata for the current test case class. + * May use the variable $CONTENT_ROOT to specify the module content root or + * $PROJECT_ROOT to use the project base directory. + */ +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.TYPE}) +public @interface TestDataPath { + String value(); +} diff --git a/compiler/tests/compiler-tests.iml b/compiler/tests/compiler-tests.iml index 9e9b2270c48..4d99af81393 100644 --- a/compiler/tests/compiler-tests.iml +++ b/compiler/tests/compiler-tests.iml @@ -13,14 +13,12 @@ - - @@ -29,5 +27,43 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/compiler/tests/org/jetbrains/kotlin/cli/WrongBytecodeVersionTest.kt b/compiler/tests/org/jetbrains/kotlin/cli/WrongBytecodeVersionTest.kt index 5db023704be..a63d007c8e9 100644 --- a/compiler/tests/org/jetbrains/kotlin/cli/WrongBytecodeVersionTest.kt +++ b/compiler/tests/org/jetbrains/kotlin/cli/WrongBytecodeVersionTest.kt @@ -17,7 +17,6 @@ package org.jetbrains.kotlin.cli import com.intellij.ide.highlighter.JavaClassFileType -import com.intellij.testFramework.UsefulTestCase import org.jetbrains.kotlin.cli.common.ExitCode import org.jetbrains.kotlin.cli.jvm.K2JVMCompiler import org.jetbrains.kotlin.jvm.compiler.LoadDescriptorUtil @@ -25,10 +24,11 @@ import org.jetbrains.kotlin.load.java.JvmAnnotationNames import org.jetbrains.kotlin.load.java.JvmBytecodeBinaryVersion import org.jetbrains.kotlin.test.ConfigurationKind import org.jetbrains.kotlin.test.KotlinTestUtils +import org.jetbrains.kotlin.test.testFramework.KtUsefulTestCase import org.jetbrains.org.objectweb.asm.* import java.io.File -class WrongBytecodeVersionTest : UsefulTestCase() { +class WrongBytecodeVersionTest : KtUsefulTestCase() { private val incompatibleVersion = JvmBytecodeBinaryVersion(42, 0, 0).toArray() private fun doTest(relativeDirectory: String) { diff --git a/compiler/tests/org/jetbrains/kotlin/codegen/CodegenTestCase.java b/compiler/tests/org/jetbrains/kotlin/codegen/CodegenTestCase.java index 36f04fae24b..6b5a0ade72a 100644 --- a/compiler/tests/org/jetbrains/kotlin/codegen/CodegenTestCase.java +++ b/compiler/tests/org/jetbrains/kotlin/codegen/CodegenTestCase.java @@ -22,7 +22,6 @@ import com.google.common.collect.Lists; import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.io.FileUtil; import com.intellij.testFramework.TestDataFile; -import com.intellij.testFramework.UsefulTestCase; import kotlin.collections.ArraysKt; import kotlin.io.FilesKt; import kotlin.text.Charsets; @@ -45,6 +44,7 @@ import org.jetbrains.kotlin.test.ConfigurationKind; import org.jetbrains.kotlin.test.InTextDirectivesUtils; import org.jetbrains.kotlin.test.KotlinTestUtils; import org.jetbrains.kotlin.test.TestJdkKind; +import org.jetbrains.kotlin.test.testFramework.KtUsefulTestCase; import org.jetbrains.kotlin.utils.ExceptionUtilsKt; import org.jetbrains.org.objectweb.asm.ClassReader; import org.jetbrains.org.objectweb.asm.tree.ClassNode; @@ -75,7 +75,7 @@ import static org.jetbrains.kotlin.codegen.CodegenTestUtil.*; import static org.jetbrains.kotlin.test.KotlinTestUtils.compilerConfigurationForTests; import static org.jetbrains.kotlin.test.KotlinTestUtils.getAnnotationsJar; -public abstract class CodegenTestCase extends UsefulTestCase { +public abstract class CodegenTestCase extends KtUsefulTestCase { private static final String DEFAULT_TEST_FILE_NAME = "a_test"; protected KotlinCoreEnvironment myEnvironment; diff --git a/compiler/tests/org/jetbrains/kotlin/codegen/CustomBytecodeTextTest.kt b/compiler/tests/org/jetbrains/kotlin/codegen/CustomBytecodeTextTest.kt index d8a7774ad0d..01d83152e1c 100644 --- a/compiler/tests/org/jetbrains/kotlin/codegen/CustomBytecodeTextTest.kt +++ b/compiler/tests/org/jetbrains/kotlin/codegen/CustomBytecodeTextTest.kt @@ -16,8 +16,8 @@ package org.jetbrains.kotlin.codegen -import com.intellij.testFramework.UsefulTestCase import org.jetbrains.kotlin.test.ConfigurationKind +import org.jetbrains.kotlin.test.testFramework.KtUsefulTestCase class CustomBytecodeTextTest : AbstractBytecodeTextTest() { fun testEnumMapping() { @@ -39,7 +39,7 @@ class CustomBytecodeTextTest : AbstractBytecodeTextTest() { val text = generateToText() val getstatics = text.lines().filter { it.contains("GETSTATIC MyEnum.") }.map { it.trim() } - UsefulTestCase.assertOrderedEquals("actual bytecode:\n" + text, listOf( + KtUsefulTestCase.assertOrderedEquals("actual bytecode:\n" + text, listOf( "GETSTATIC MyEnum.${'$'}VALUES : [LMyEnum;", "GETSTATIC MyEnum.ENTRY4 : LMyEnum;", "GETSTATIC MyEnum.ENTRY3 : LMyEnum;", diff --git a/compiler/tests/org/jetbrains/kotlin/codegen/StdlibTest.java b/compiler/tests/org/jetbrains/kotlin/codegen/StdlibTest.java index 601ea5202d3..dc9ebad9adf 100644 --- a/compiler/tests/org/jetbrains/kotlin/codegen/StdlibTest.java +++ b/compiler/tests/org/jetbrains/kotlin/codegen/StdlibTest.java @@ -16,7 +16,6 @@ package org.jetbrains.kotlin.codegen; -import com.intellij.testFramework.TestRunnerUtil; import junit.framework.*; import junit.textui.TestRunner; import org.jetbrains.annotations.NotNull; @@ -42,6 +41,7 @@ import org.jetbrains.kotlin.test.ConfigurationKind; import org.jetbrains.kotlin.test.KotlinTestUtils; import org.jetbrains.kotlin.test.KotlinTestWithEnvironment; import org.jetbrains.kotlin.test.TestJdkKind; +import org.jetbrains.kotlin.test.testFramework.TestRunnerUtil; import java.io.File; import java.lang.reflect.Modifier; diff --git a/compiler/tests/org/jetbrains/kotlin/codegen/flags/AbstractWriteFlagsTest.java b/compiler/tests/org/jetbrains/kotlin/codegen/flags/AbstractWriteFlagsTest.java index 9d6445a1ec8..65c70d085c5 100644 --- a/compiler/tests/org/jetbrains/kotlin/codegen/flags/AbstractWriteFlagsTest.java +++ b/compiler/tests/org/jetbrains/kotlin/codegen/flags/AbstractWriteFlagsTest.java @@ -17,7 +17,6 @@ package org.jetbrains.kotlin.codegen.flags; import com.intellij.openapi.util.io.FileUtil; -import com.intellij.testFramework.UsefulTestCase; import org.jetbrains.annotations.NotNull; import org.jetbrains.kotlin.backend.common.output.OutputFile; import org.jetbrains.kotlin.backend.common.output.OutputFileCollection; @@ -26,6 +25,7 @@ import org.jetbrains.kotlin.codegen.GenerationUtils; import org.jetbrains.kotlin.psi.KtFile; import org.jetbrains.kotlin.test.ConfigurationKind; import org.jetbrains.kotlin.test.KotlinTestUtils; +import org.jetbrains.kotlin.test.testFramework.KtUsefulTestCase; import org.jetbrains.org.objectweb.asm.*; import java.io.File; @@ -53,7 +53,7 @@ import static org.jetbrains.kotlin.test.InTextDirectivesUtils.findStringWithPref * TESTED_OBJECTS: Test, prop$delegate * FLAGS: ACC_STATIC, ACC_FINAL, ACC_PRIVATE */ -public abstract class AbstractWriteFlagsTest extends UsefulTestCase { +public abstract class AbstractWriteFlagsTest extends KtUsefulTestCase { private KotlinCoreEnvironment jetCoreEnvironment; diff --git a/compiler/tests/org/jetbrains/kotlin/integration/AntTaskJsTest.java b/compiler/tests/org/jetbrains/kotlin/integration/AntTaskJsTest.java index 4b36b901c82..2652972b806 100644 --- a/compiler/tests/org/jetbrains/kotlin/integration/AntTaskJsTest.java +++ b/compiler/tests/org/jetbrains/kotlin/integration/AntTaskJsTest.java @@ -21,8 +21,8 @@ import com.intellij.util.Function; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import org.jetbrains.kotlin.js.test.rhino.RhinoFunctionResultChecker; -import org.jetbrains.kotlin.js.test.rhino.RhinoUtils; +//import org.jetbrains.kotlin.js.test.rhino.RhinoFunctionResultChecker; +//import org.jetbrains.kotlin.js.test.rhino.RhinoUtils; import org.jetbrains.kotlin.test.KotlinTestUtils; import java.io.File; @@ -61,7 +61,7 @@ public class AntTaskJsTest extends AbstractAntTaskTest { } }); - RhinoUtils.runRhinoTest(filePaths, new RhinoFunctionResultChecker("out", "foo", "box", "OK")); + //RhinoUtils.runRhinoTest(filePaths, new RhinoFunctionResultChecker("out", "foo", "box", "OK")); } private void doJsAntTestForPostfixPrefix(@Nullable String prefix, @Nullable String postfix) throws Exception { diff --git a/compiler/tests/org/jetbrains/kotlin/integration/KotlinIntegrationTestBase.java b/compiler/tests/org/jetbrains/kotlin/integration/KotlinIntegrationTestBase.java index 81229cd8ead..d341fcec0c7 100644 --- a/compiler/tests/org/jetbrains/kotlin/integration/KotlinIntegrationTestBase.java +++ b/compiler/tests/org/jetbrains/kotlin/integration/KotlinIntegrationTestBase.java @@ -17,10 +17,13 @@ package org.jetbrains.kotlin.integration; import com.intellij.execution.ExecutionException; -import com.intellij.execution.OutputListener; import com.intellij.execution.configurations.GeneralCommandLine; import com.intellij.execution.process.OSProcessHandler; +import com.intellij.execution.process.ProcessAdapter; +import com.intellij.execution.process.ProcessEvent; +import com.intellij.execution.process.ProcessOutputTypes; import com.intellij.openapi.application.PathManager; +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; @@ -141,4 +144,30 @@ public abstract class KotlinIntegrationTestBase extends TestCaseWithTmpdir { protected static File getKotlinProjectHome() { return new File(PathManager.getHomePath()).getParentFile(); } -} + + private static class OutputListener extends ProcessAdapter { + private final StringBuilder out; + private final StringBuilder err; + + public OutputListener(@NotNull StringBuilder out, @NotNull StringBuilder err) { + this.out = out; + this.err = err; + } + + @Override + public void onTextAvailable(ProcessEvent event, Key outputType) { + if (outputType == ProcessOutputTypes.STDERR) { + err.append(event.getText()); + } + else if (outputType == ProcessOutputTypes.SYSTEM) { + // skip + } + else { + out.append(event.getText()); + } + } + + @Override + public void processTerminated(ProcessEvent event) {} + } +} \ No newline at end of file diff --git a/compiler/tests/org/jetbrains/kotlin/jvm/compiler/DeserializedScopeValidationVisitor.kt b/compiler/tests/org/jetbrains/kotlin/jvm/compiler/DeserializedScopeValidationVisitor.kt index b9d8913d923..dd39f4e0a91 100644 --- a/compiler/tests/org/jetbrains/kotlin/jvm/compiler/DeserializedScopeValidationVisitor.kt +++ b/compiler/tests/org/jetbrains/kotlin/jvm/compiler/DeserializedScopeValidationVisitor.kt @@ -16,16 +16,16 @@ package org.jetbrains.kotlin.jvm.compiler +import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor +import org.jetbrains.kotlin.descriptors.ClassDescriptor +import org.jetbrains.kotlin.descriptors.DeclarationDescriptor +import org.jetbrains.kotlin.descriptors.PackageViewDescriptor +import org.jetbrains.kotlin.resolve.MemberComparator import org.jetbrains.kotlin.resolve.scopes.MemberScope import org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedMemberScope -import org.jetbrains.kotlin.descriptors.DeclarationDescriptor -import com.intellij.testFramework.UsefulTestCase -import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor +import org.jetbrains.kotlin.test.testFramework.KtUsefulTestCase import org.jetbrains.kotlin.test.util.DescriptorValidator import org.jetbrains.kotlin.test.util.DescriptorValidator.ValidationVisitor -import org.jetbrains.kotlin.descriptors.PackageViewDescriptor -import org.jetbrains.kotlin.descriptors.ClassDescriptor -import org.jetbrains.kotlin.resolve.MemberComparator class DeserializedScopeValidationVisitor : ValidationVisitor() { override fun validateScope(scopeOwner: DeclarationDescriptor, scope: MemberScope, collector: DescriptorValidator.DiagnosticCollector) { @@ -45,7 +45,7 @@ private fun validateDeserializedScope(scopeOwner: DeclarationDescriptor, scope: } private fun checkSorted(descriptors: Collection, declaration: DeclarationDescriptor) { - UsefulTestCase.assertOrderedEquals( + KtUsefulTestCase.assertOrderedEquals( "Members of $declaration should be sorted by serialization.", descriptors, descriptors.sortedWith(MemberComparator.INSTANCE) diff --git a/compiler/tests/org/jetbrains/kotlin/jvm/compiler/ExpectedLoadErrorsUtil.java b/compiler/tests/org/jetbrains/kotlin/jvm/compiler/ExpectedLoadErrorsUtil.java index c0b212a7336..4fbeff62965 100644 --- a/compiler/tests/org/jetbrains/kotlin/jvm/compiler/ExpectedLoadErrorsUtil.java +++ b/compiler/tests/org/jetbrains/kotlin/jvm/compiler/ExpectedLoadErrorsUtil.java @@ -30,8 +30,8 @@ import org.jetbrains.kotlin.resolve.scopes.MemberScope; import java.util.*; -import static com.intellij.testFramework.UsefulTestCase.assertNotNull; -import static com.intellij.testFramework.UsefulTestCase.assertSameElements; +import static org.jetbrains.kotlin.test.testFramework.KtUsefulTestCase.assertNotNull; +import static org.jetbrains.kotlin.test.testFramework.KtUsefulTestCase.assertSameElements; public class ExpectedLoadErrorsUtil { public static final String ANNOTATION_CLASS_NAME = "org.jetbrains.kotlin.jvm.compiler.annotation.ExpectLoadError"; diff --git a/compiler/tests/org/jetbrains/kotlin/jvm/compiler/MultiModuleJavaAnalysisCustomTest.kt b/compiler/tests/org/jetbrains/kotlin/jvm/compiler/MultiModuleJavaAnalysisCustomTest.kt index 1225135e534..1287282d9be 100644 --- a/compiler/tests/org/jetbrains/kotlin/jvm/compiler/MultiModuleJavaAnalysisCustomTest.kt +++ b/compiler/tests/org/jetbrains/kotlin/jvm/compiler/MultiModuleJavaAnalysisCustomTest.kt @@ -19,7 +19,6 @@ package org.jetbrains.kotlin.jvm.compiler import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.search.DelegatingGlobalSearchScope import com.intellij.psi.search.GlobalSearchScope -import com.intellij.testFramework.UsefulTestCase import org.jetbrains.kotlin.analyzer.ModuleContent import org.jetbrains.kotlin.analyzer.ModuleInfo import org.jetbrains.kotlin.analyzer.ResolverForProject @@ -39,13 +38,14 @@ import org.jetbrains.kotlin.resolve.jvm.JvmAnalyzerFacade import org.jetbrains.kotlin.resolve.jvm.JvmPlatformParameters import org.jetbrains.kotlin.test.ConfigurationKind import org.jetbrains.kotlin.test.KotlinTestUtils +import org.jetbrains.kotlin.test.testFramework.KtUsefulTestCase import org.jetbrains.kotlin.test.TestJdkKind import org.jetbrains.kotlin.types.ErrorUtils import org.junit.Assert import java.io.File import java.util.* -class MultiModuleJavaAnalysisCustomTest : UsefulTestCase() { +class MultiModuleJavaAnalysisCustomTest : KtUsefulTestCase() { private class TestModule( val _name: String, val kotlinFiles: List, val javaFilesScope: GlobalSearchScope, diff --git a/compiler/tests/org/jetbrains/kotlin/parsing/AbstractParsingTest.java b/compiler/tests/org/jetbrains/kotlin/parsing/AbstractParsingTest.java index 95dca09bc3d..a3238eece26 100644 --- a/compiler/tests/org/jetbrains/kotlin/parsing/AbstractParsingTest.java +++ b/compiler/tests/org/jetbrains/kotlin/parsing/AbstractParsingTest.java @@ -25,23 +25,19 @@ import com.intellij.psi.PsiErrorElement; import com.intellij.psi.PsiFile; import com.intellij.psi.tree.IElementType; import com.intellij.psi.util.PsiTreeUtil; -import com.intellij.testFramework.ParsingTestCase; import com.intellij.util.PathUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.kotlin.KtNodeTypes; import org.jetbrains.kotlin.psi.*; import org.jetbrains.kotlin.script.KotlinScriptDefinitionProvider; import org.jetbrains.kotlin.test.KotlinTestUtils; +import org.jetbrains.kotlin.test.testFramework.KtParsingTestCase; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.lang.reflect.Modifier; -public abstract class AbstractParsingTest extends ParsingTestCase { - static { - System.setProperty("idea.platform.prefix", "Idea"); - } - +public abstract class AbstractParsingTest extends KtParsingTestCase { @Override protected void setUp() throws Exception { super.setUp(); diff --git a/compiler/tests/org/jetbrains/kotlin/renderer/AbstractDescriptorRendererTest.kt b/compiler/tests/org/jetbrains/kotlin/renderer/AbstractDescriptorRendererTest.kt index 3289b8916f5..a033b494a5d 100644 --- a/compiler/tests/org/jetbrains/kotlin/renderer/AbstractDescriptorRendererTest.kt +++ b/compiler/tests/org/jetbrains/kotlin/renderer/AbstractDescriptorRendererTest.kt @@ -18,7 +18,6 @@ package org.jetbrains.kotlin.renderer import com.intellij.openapi.editor.impl.DocumentImpl import com.intellij.openapi.util.io.FileUtil -import com.intellij.testFramework.UsefulTestCase import org.jetbrains.kotlin.cli.jvm.compiler.CliLightClassGenerationSupport import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment import org.jetbrains.kotlin.cli.jvm.config.getModuleName @@ -39,6 +38,7 @@ import org.jetbrains.kotlin.resolve.lazy.declarations.FileBasedDeclarationProvid import org.jetbrains.kotlin.test.ConfigurationKind import org.jetbrains.kotlin.test.KotlinTestUtils import org.jetbrains.kotlin.test.KotlinTestWithEnvironment +import org.jetbrains.kotlin.test.testFramework.KtUsefulTestCase import java.io.File import java.util.* @@ -147,7 +147,7 @@ abstract class AbstractDescriptorRendererTest : KotlinTestWithEnvironment() { val renderedDescriptors = descriptors.map { renderer.render(it) }.joinToString(separator = "\n") val document = DocumentImpl(psiFile.text) - UsefulTestCase.assertSameLines(KotlinTestUtils.getLastCommentedLines(document), renderedDescriptors.toString()) + KtUsefulTestCase.assertSameLines(KotlinTestUtils.getLastCommentedLines(document), renderedDescriptors.toString()) } override fun createEnvironment(): KotlinCoreEnvironment { diff --git a/compiler/tests/org/jetbrains/kotlin/renderer/AbstractFunctionDescriptorInExpressionRendererTest.kt b/compiler/tests/org/jetbrains/kotlin/renderer/AbstractFunctionDescriptorInExpressionRendererTest.kt index bd446778371..cb39eaf02db 100644 --- a/compiler/tests/org/jetbrains/kotlin/renderer/AbstractFunctionDescriptorInExpressionRendererTest.kt +++ b/compiler/tests/org/jetbrains/kotlin/renderer/AbstractFunctionDescriptorInExpressionRendererTest.kt @@ -18,7 +18,6 @@ package org.jetbrains.kotlin.renderer import com.intellij.openapi.editor.impl.DocumentImpl import com.intellij.openapi.util.io.FileUtil -import com.intellij.testFramework.UsefulTestCase import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.descriptors.impl.FunctionExpressionDescriptor @@ -31,6 +30,7 @@ import org.jetbrains.kotlin.resolve.lazy.JvmResolveUtil import org.jetbrains.kotlin.test.ConfigurationKind import org.jetbrains.kotlin.test.KotlinTestUtils import org.jetbrains.kotlin.test.KotlinTestWithEnvironment +import org.jetbrains.kotlin.test.testFramework.KtUsefulTestCase import org.jetbrains.kotlin.utils.addIfNotNull import java.io.File @@ -61,7 +61,7 @@ abstract class AbstractFunctionDescriptorInExpressionRendererTest : KotlinTestWi val renderedDescriptors = descriptors.map { renderer.render(it) }.joinToString(separator = "\n") val document = DocumentImpl(file.text) - UsefulTestCase.assertSameLines(KotlinTestUtils.getLastCommentedLines(document), renderedDescriptors.toString()) + KtUsefulTestCase.assertSameLines(KotlinTestUtils.getLastCommentedLines(document), renderedDescriptors.toString()) } override fun createEnvironment(): KotlinCoreEnvironment { diff --git a/compiler/tests/org/jetbrains/kotlin/repl/AbstractReplInterpreterTest.kt b/compiler/tests/org/jetbrains/kotlin/repl/AbstractReplInterpreterTest.kt index 90df17bf50d..243e33a2e93 100644 --- a/compiler/tests/org/jetbrains/kotlin/repl/AbstractReplInterpreterTest.kt +++ b/compiler/tests/org/jetbrains/kotlin/repl/AbstractReplInterpreterTest.kt @@ -17,11 +17,11 @@ package org.jetbrains.kotlin.repl import com.intellij.openapi.util.text.StringUtil -import com.intellij.testFramework.UsefulTestCase import org.jetbrains.kotlin.cli.jvm.repl.ReplInterpreter import org.jetbrains.kotlin.test.ConfigurationKind import org.jetbrains.kotlin.test.KotlinTestUtils import org.jetbrains.kotlin.test.TestJdkKind +import org.jetbrains.kotlin.test.testFramework.KtUsefulTestCase import org.junit.Assert import java.io.File import java.io.PrintWriter @@ -37,7 +37,7 @@ private val TRAILING_NEWLINE_REGEX = Regex("\n$") private val INCOMPLETE_LINE_MESSAGE = "incomplete line" -abstract class AbstractReplInterpreterTest : UsefulTestCase() { +abstract class AbstractReplInterpreterTest : KtUsefulTestCase() { init { System.setProperty("java.awt.headless", "true") } diff --git a/compiler/tests/org/jetbrains/kotlin/serialization/jvm/BitEncodingTest.java b/compiler/tests/org/jetbrains/kotlin/serialization/jvm/BitEncodingTest.java index 57328247f11..509fc454803 100644 --- a/compiler/tests/org/jetbrains/kotlin/serialization/jvm/BitEncodingTest.java +++ b/compiler/tests/org/jetbrains/kotlin/serialization/jvm/BitEncodingTest.java @@ -16,8 +16,8 @@ package org.jetbrains.kotlin.serialization.jvm; -import com.intellij.testFramework.UsefulTestCase; import org.jetbrains.annotations.NotNull; +import org.jetbrains.kotlin.test.testFramework.KtUsefulTestCase; import java.util.Random; @@ -25,7 +25,7 @@ import static org.jetbrains.kotlin.serialization.jvm.BitEncoding.decodeBytes; import static org.jetbrains.kotlin.serialization.jvm.BitEncoding.encodeBytes; import static org.junit.Assert.assertArrayEquals; -public class BitEncodingTest extends UsefulTestCase { +public class BitEncodingTest extends KtUsefulTestCase { private static final int[] BIG_LENGTHS = new int[] {1000, 32000, 33000, 65000, 65534, 65535, 65536, 65537, 100000, 131074, 239017, 314159, 1000000}; diff --git a/compiler/tests/org/jetbrains/kotlin/serialization/jvm/JvmNameResolverTest.kt b/compiler/tests/org/jetbrains/kotlin/serialization/jvm/JvmNameResolverTest.kt index a96f0b13d51..9e4074674fb 100644 --- a/compiler/tests/org/jetbrains/kotlin/serialization/jvm/JvmNameResolverTest.kt +++ b/compiler/tests/org/jetbrains/kotlin/serialization/jvm/JvmNameResolverTest.kt @@ -16,18 +16,15 @@ package org.jetbrains.kotlin.serialization.jvm -import com.intellij.testFramework.UsefulTestCase -import com.intellij.testFramework.UsefulTestCase.assertEquals import org.jetbrains.kotlin.load.kotlin.JvmNameResolver import org.jetbrains.kotlin.name.ClassId import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.serialization.jvm.JvmProtoBuf.StringTableTypes.Record -import org.jetbrains.kotlin.serialization.jvm.JvmProtoBuf.StringTableTypes.Record.Operation.DESC_TO_CLASS_ID -import org.jetbrains.kotlin.serialization.jvm.JvmProtoBuf.StringTableTypes.Record.Operation.INTERNAL_TO_CLASS_ID -import org.jetbrains.kotlin.serialization.jvm.JvmProtoBuf.StringTableTypes.Record.Operation.NONE +import org.jetbrains.kotlin.serialization.jvm.JvmProtoBuf.StringTableTypes.Record.Operation.* +import org.jetbrains.kotlin.test.testFramework.KtUsefulTestCase import java.util.* -class JvmNameResolverTest : UsefulTestCase() { +class JvmNameResolverTest : KtUsefulTestCase() { private class Context { val types = JvmProtoBuf.StringTableTypes.newBuilder() val strings = ArrayList() diff --git a/compiler/tests/org/jetbrains/kotlin/test/KotlinTestWithEnvironmentManagement.java b/compiler/tests/org/jetbrains/kotlin/test/KotlinTestWithEnvironmentManagement.java index 2888dc6334e..c74c0a5aa6c 100644 --- a/compiler/tests/org/jetbrains/kotlin/test/KotlinTestWithEnvironmentManagement.java +++ b/compiler/tests/org/jetbrains/kotlin/test/KotlinTestWithEnvironmentManagement.java @@ -16,12 +16,12 @@ package org.jetbrains.kotlin.test; -import com.intellij.testFramework.UsefulTestCase; import org.jetbrains.annotations.NotNull; import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment; +import org.jetbrains.kotlin.test.testFramework.KtUsefulTestCase; import org.jetbrains.kotlin.types.DelegatingFlexibleType; -public abstract class KotlinTestWithEnvironmentManagement extends UsefulTestCase { +public abstract class KotlinTestWithEnvironmentManagement extends KtUsefulTestCase { static { System.setProperty("java.awt.headless", "true"); DelegatingFlexibleType.RUN_SLOW_ASSERTIONS = true; diff --git a/compiler/tests/org/jetbrains/kotlin/test/TestCaseWithTmpdir.java b/compiler/tests/org/jetbrains/kotlin/test/TestCaseWithTmpdir.java index e01c3f98072..a1577c0df97 100644 --- a/compiler/tests/org/jetbrains/kotlin/test/TestCaseWithTmpdir.java +++ b/compiler/tests/org/jetbrains/kotlin/test/TestCaseWithTmpdir.java @@ -16,11 +16,11 @@ package org.jetbrains.kotlin.test; -import com.intellij.testFramework.UsefulTestCase; +import org.jetbrains.kotlin.test.testFramework.KtUsefulTestCase; import java.io.File; -public abstract class TestCaseWithTmpdir extends UsefulTestCase { +public abstract class TestCaseWithTmpdir extends KtUsefulTestCase { protected File tmpdir; @Override diff --git a/compiler/tests/org/jetbrains/kotlin/test/testFramework/AbstractExceptionCase.java b/compiler/tests/org/jetbrains/kotlin/test/testFramework/AbstractExceptionCase.java new file mode 100644 index 00000000000..ca806ad6eca --- /dev/null +++ b/compiler/tests/org/jetbrains/kotlin/test/testFramework/AbstractExceptionCase.java @@ -0,0 +1,35 @@ +/* + * 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 new file mode 100644 index 00000000000..e9452a6caf5 --- /dev/null +++ b/compiler/tests/org/jetbrains/kotlin/test/testFramework/EdtTestUtil.kt @@ -0,0 +1,53 @@ +/* + * 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 + +import com.intellij.util.ThrowableRunnable +import org.jetbrains.annotations.TestOnly +import java.lang.reflect.InvocationTargetException +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() } + } + } +} + + +// Test only because in production you must use Application.invokeAndWait(Runnable, ModalityState). +// The problem is - Application logs errors, but not throws. But in tests must be thrown. +// In any case name "runInEdtAndWait" is better than "invokeAndWait". +@TestOnly +fun runInEdtAndWait(runnable: () -> Unit) { + if (SwingUtilities.isEventDispatchThread()) { + runnable() + } + else { + try { + SwingUtilities.invokeAndWait(runnable) + } + catch (e: InvocationTargetException) { + throw e.cause ?: e + } + } +} \ No newline at end of file diff --git a/compiler/tests/org/jetbrains/kotlin/test/testFramework/KtParsingTestCase.java b/compiler/tests/org/jetbrains/kotlin/test/testFramework/KtParsingTestCase.java new file mode 100644 index 00000000000..2ac52fd9029 --- /dev/null +++ b/compiler/tests/org/jetbrains/kotlin/test/testFramework/KtParsingTestCase.java @@ -0,0 +1,342 @@ +/* + * 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; + +import com.intellij.core.CoreASTFactory; +import com.intellij.lang.*; +import com.intellij.lang.impl.PsiBuilderFactoryImpl; +import com.intellij.mock.*; +import com.intellij.openapi.application.PathManager; +import com.intellij.openapi.editor.Document; +import com.intellij.openapi.editor.EditorFactory; +import com.intellij.openapi.extensions.ExtensionPointName; +import com.intellij.openapi.extensions.Extensions; +import com.intellij.openapi.fileEditor.FileDocumentManager; +import com.intellij.openapi.fileEditor.impl.LoadTextUtil; +import com.intellij.openapi.fileTypes.FileTypeFactory; +import com.intellij.openapi.fileTypes.FileTypeManager; +import com.intellij.openapi.options.SchemesManagerFactory; +import com.intellij.openapi.progress.EmptyProgressIndicator; +import com.intellij.openapi.progress.ProgressManager; +import com.intellij.openapi.progress.impl.CoreProgressManager; +import com.intellij.openapi.util.Disposer; +import com.intellij.openapi.util.Key; +import com.intellij.openapi.util.TextRange; +import com.intellij.openapi.util.io.FileUtil; +import com.intellij.openapi.vfs.CharsetToolkit; +import com.intellij.pom.PomModel; +import com.intellij.pom.core.impl.PomModelImpl; +import com.intellij.pom.tree.TreeAspect; +import com.intellij.psi.*; +import com.intellij.psi.impl.DebugUtil; +import com.intellij.psi.impl.PsiCachedValuesFactory; +import com.intellij.psi.impl.PsiFileFactoryImpl; +import com.intellij.psi.impl.source.resolve.reference.ReferenceProvidersRegistry; +import com.intellij.psi.impl.source.resolve.reference.ReferenceProvidersRegistryImpl; +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.util.CachedValuesManagerImpl; +import com.intellij.util.Function; +import com.intellij.util.messages.MessageBus; +import com.intellij.util.messages.MessageBusFactory; +import junit.framework.TestCase; +import org.jetbrains.annotations.NonNls; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.kotlin.test.testFramework.mock.*; +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 myFileExt; + protected final String myFullDataPath; + protected PsiFile myFile; + private MockPsiManager myPsiManager; + private PsiFileFactoryImpl myFileFactory; + protected Language myLanguage; + private final ParserDefinition[] myDefinitions; + private final boolean myLowercaseFirstLetter; + + protected KtParsingTestCase(@NonNls @NotNull String dataPath, @NotNull String fileExt, @NotNull ParserDefinition... definitions) { + this(dataPath, fileExt, false, definitions); + } + + 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; + } + + 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 { + // } + // }); + //} + + Extensions.registerAreaClass("IDEA_PROJECT", (String)null); + this.myProject = new MockProjectEx(this.getTestRootDisposable()); + this.myPsiManager = new MockPsiManager(this.myProject); + this.myFileFactory = new PsiFileFactoryImpl(this.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() { + 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(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)); + 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); + } + + 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); + } + + public void configureFromParserDefinition(ParserDefinition definition, String extension) { + this.myLanguage = definition.getFileNodeType().getLanguage(); + this.myFileExt = extension; + this.addExplicitExtension(LanguageParserDefinitions.INSTANCE, this.myLanguage, definition); + registerComponentInstance( + getApplication().getPicoContainer(), FileTypeManager.class, + new KtMockFileTypeManager(new KtMockLanguageFileType(myLanguage, myFileExt))); + } + + 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() { + public void dispose() { + instance.removeExplicitExtension(language, object); + } + }); + } + + protected void registerExtensionPoint(final ExtensionPointName extensionPointName, Class aClass) { + super.registerExtensionPoint(extensionPointName, aClass); + Disposer.register(this.myProject, new com.intellij.openapi.Disposable() { + public void dispose() { + Extensions.getRootArea().unregisterExtensionPoint(extensionPointName.getName()); + } + }); + } + + protected void registerApplicationService(final Class aClass, T object) { + getApplication().registerService(aClass, object); + Disposer.register(this.myProject, new com.intellij.openapi.Disposable() { + public void dispose() { + KtPlatformLiteFixture.getApplication().getPicoContainer().unregisterComponent(aClass.getName()); + } + }); + } + + public MockProjectEx getProject() { + return this.myProject; + } + + public MockPsiManager getPsiManager() { + return this.myPsiManager; + } + + protected void tearDown() throws Exception { + super.tearDown(); + this.myFile = null; + this.myProject = null; + this.myPsiManager = null; + } + + protected String getTestDataPath() { + return PathManager.getHomePath(); + //return PathManagerEx.getTestDataPath(); + } + + @NotNull + public final String getTestName() { + return this.getTestName(this.myLowercaseFirstLetter); + } + + protected boolean includeRanges() { + return false; + } + + protected boolean skipSpaces() { + return false; + } + + protected boolean checkAllPsiRoots() { + return true; + } + + protected void doTest(boolean checkResult) { + String name = this.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()); + } + + } catch (IOException var4) { + throw new RuntimeException(var4); + } + } + + 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); + } + + 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); + } + + protected PsiFile createPsiFile(String name, String text) { + return this.createFile(name + "." + this.myFileExt, text); + } + + protected PsiFile createFile(@NonNls String name, String text) { + LightVirtualFile virtualFile = new LightVirtualFile(name, this.myLanguage, text); + virtualFile.setCharset(CharsetToolkit.UTF8_CHARSET); + return this.createFile(virtualFile); + } + + protected PsiFile createFile(LightVirtualFile virtualFile) { + return this.myFileFactory.trySetupPsiForFile(virtualFile, this.myLanguage, true, false); + } + + protected void checkResult(@NonNls String targetDataName, PsiFile file) throws IOException { + doCheckResult(this.myFullDataPath, file, this.checkAllPsiRoots(), targetDataName, this.skipSpaces(), this.includeRanges()); + } + + 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(); + + 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 { + doCheckResult(testDataDir, targetDataName + ".txt", toParseTreeText(file, skipSpaces, printRanges).trim()); + } + } + + protected void checkResult(String actual) throws IOException { + String name = this.getTestName(); + doCheckResult(this.myFullDataPath, this.myFilePrefix + name + ".txt", actual); + } + + protected void checkResult(@NonNls String targetDataName, String actual) throws IOException { + doCheckResult(this.myFullDataPath, targetDataName, actual); + } + + public static void doCheckResult(String fullPath, String targetDataName, String actual) throws IOException { + String expectedFileName = fullPath + File.separatorChar + targetDataName; + KtUsefulTestCase.assertSameLinesWithFile(expectedFileName, actual); + } + + 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); + } + + public static String loadFileDefault(String dir, String name) throws IOException { + return FileUtil.loadFile(new File(dir, name), "UTF-8", true).trim(); + } + + public static void ensureParsed(PsiFile file) { + file.accept(new PsiElementVisitor() { + public void visitElement(PsiElement element) { + element.acceptChildren(this); + } + }); + } + + public static void ensureCorrectReparse(@NotNull PsiFile file) { + String psiToStringDefault = DebugUtil.psiToString(file, false, false); + 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 new file mode 100644 index 00000000000..a3aaaed9e93 --- /dev/null +++ b/compiler/tests/org/jetbrains/kotlin/test/testFramework/KtPlatformLiteFixture.java @@ -0,0 +1,103 @@ +/* + * 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; + +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; +import com.intellij.openapi.extensions.ExtensionsArea; +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") +public abstract class KtPlatformLiteFixture extends KtUsefulTestCase { + protected MockProjectEx myProject; + + public KtPlatformLiteFixture() { + } + + protected void setUp() throws Exception { + super.setUp(); + Extensions.cleanRootArea(this.getTestRootDisposable()); + } + + public static MockApplicationEx 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()); + getApplication().registerService(EncodingManager.class, CoreEncodingProjectManager.class); + } + + 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); + } + + protected void registerExtensionPoint(ExtensionPointName extensionPointName, Class aClass) { + this.registerExtensionPoint(Extensions.getRootArea(), extensionPointName, aClass); + } + + protected 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; + 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); + } +} diff --git a/compiler/tests/org/jetbrains/kotlin/test/testFramework/KtPlatformTestUtil.java b/compiler/tests/org/jetbrains/kotlin/test/testFramework/KtPlatformTestUtil.java new file mode 100644 index 00000000000..955a9e0172b --- /dev/null +++ b/compiler/tests/org/jetbrains/kotlin/test/testFramework/KtPlatformTestUtil.java @@ -0,0 +1,905 @@ +/* + * 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; + +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 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") +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"); + return StringUtil.isEmpty(name) ? "" : lowercaseFirstLetter(name, lowercaseFirstLetter); + } + + @NotNull + public static String lowercaseFirstLetter(@NotNull String name, boolean lowercaseFirstLetter) { + if (lowercaseFirstLetter && !isAllUppercaseName(name)) { + name = Character.toLowerCase(name.charAt(0)) + name.substring(1); + } + return name; + } + + public static boolean isAllUppercaseName(@NotNull String name) { + int uppercaseChars = 0; + for (int i = 0; i < name.length(); i++) { + if (Character.isLowerCase(name.charAt(i))) { + return false; + } + if (Character.isUpperCase(name.charAt(i))) { + uppercaseChars++; + } + } + 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); + } + else { + @SuppressWarnings({"deprecation", "UnnecessaryLocalVariable"}) + final String presentation = ((AbstractTreeNode)node).getTestPresentation(); + return presentation; + } + } + if (node == null) { + return "NULL"; + } + 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 new file mode 100644 index 00000000000..c72557703bd --- /dev/null +++ b/compiler/tests/org/jetbrains/kotlin/test/testFramework/KtUsefulTestCase.java @@ -0,0 +1,1113 @@ +/* + * 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; + +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.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.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.util.*; +import java.util.List; +import java.util.concurrent.DelayQueue; +import java.util.concurrent.Delayed; +import java.util.concurrent.TimeUnit; + +@SuppressWarnings("ALL") +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() { + } + + public String toString() { + String testName = KtUsefulTestCase.this.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 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() { + } + + protected boolean shouldContainTempFiles() { + return true; + } + + 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()); + } + + protected void tearDown() throws Exception { + boolean var13 = false; + + try { + var13 = true; + Disposer.dispose(this.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()) { + 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)) { + FileUtil.delete(file); + } + } + } + } else { + FileUtil.delete(new File(this.myTempDir)); + } + } + + UIUtil.removeLeakingAppleListeners(); + 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(); + } + + 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; + } + } + + 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); + } + + 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) { + 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"); + componentKeyStrokeMap.clear(); + Map containerMap = (Map)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; + } + + protected void runTest() throws Throwable { + final Throwable[] throwables = new Throwable[1]; + Runnable runnable = new Runnable() { + 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; + } + + } + }; + this.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 { + EdtTestUtil.runInEdtAndWait(runnable); + } + + protected 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 { + 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; + } + } + } + + if(exception != null) { + throw exception; + } + } + + 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)})); + } + + 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; + } + + @NonNls + public static String toString(Iterable collection) { + 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); + } + } + + 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) { + Assert.assertNotNull(actual); + Assert.assertNotNull(expected); + assertOrderedEquals(errorMsg, actual, (Collection)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); + } + + 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); + } + + } + + 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); + } + + public static void assertSameElements(Collection collection, T... expected) { + assertSameElements((Collection)collection, (Collection)Arrays.asList(expected)); + } + + public static void assertSameElements(Collection collection, Collection expected) { + assertSameElements((String)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))) { + Assert.assertEquals(message, toString(expected, "\n"), toString(collection, "\n")); + 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); + } + + public static String toString(Collection collection, String separator) { + List list = ContainerUtil.map2List(collection, new Function() { + public String fun(Object o) { + return String.valueOf(o); + } + }); + 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) { + builder.append(separator); + } + + builder.append(o); + } + + 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; + } + + 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; + } + + 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) { + 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); + } + + public static String getTestName(String name, boolean lowercaseFirstLetter) { + return name == null? "": KtPlatformTestUtil.getTestName(name, lowercaseFirstLetter); + } + + /** @deprecated */ + public static String lowercaseFirstLetter(String name, boolean lowercaseFirstLetter) { + return KtPlatformTestUtil.lowercaseFirstLetter(name, lowercaseFirstLetter); + } + + /** @deprecated */ + 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); + } + + 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) { + 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); + } + } + + public static void clearFields(Object test) throws IllegalAccessException { + for(Class aClass = test.getClass(); aClass != null; aClass = aClass.getSuperclass()) { + 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); + } + } + } + + } + } + + 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; + } + } + } + + return false; + } + + protected String getHomePath() { + return PathManager.getHomePath().replace(File.separatorChar, '/'); + } + + 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; + } +} diff --git a/compiler/tests/org/jetbrains/kotlin/test/testFramework/MockProjects.kt b/compiler/tests/org/jetbrains/kotlin/test/testFramework/MockProjects.kt new file mode 100644 index 00000000000..73536c50fa2 --- /dev/null +++ b/compiler/tests/org/jetbrains/kotlin/test/testFramework/MockProjects.kt @@ -0,0 +1,45 @@ +/* + * 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 + +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) +} + +class MockProjectEx(parentDisposable: Disposable) : MockProject(if (ApplicationManager.getApplication() != null) ApplicationManager.getApplication().picoContainer else null, parentDisposable), ProjectEx { + override fun setProjectName(name: String) { + } + + override fun init() { + } +} \ No newline at end of file diff --git a/compiler/tests/org/jetbrains/kotlin/test/testFramework/TestRunnerUtil.java b/compiler/tests/org/jetbrains/kotlin/test/testFramework/TestRunnerUtil.java new file mode 100644 index 00000000000..17b1221e548 --- /dev/null +++ b/compiler/tests/org/jetbrains/kotlin/test/testFramework/TestRunnerUtil.java @@ -0,0 +1,66 @@ +/* + * 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; + +import org.jetbrains.annotations.TestOnly; +import org.junit.Test; +import org.junit.runner.RunWith; + +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; + +public class TestRunnerUtil { + private TestRunnerUtil() { + } + + @TestOnly + public static boolean isJUnit4TestClass(final Class aClass) { + final 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; + for (Method method : aClass.getMethods()) { + if (method.getAnnotation(Test.class) != null) return true; + } + 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 new file mode 100644 index 00000000000..9bc014d52d6 --- /dev/null +++ b/compiler/tests/org/jetbrains/kotlin/test/testFramework/VfsTestUtil.java @@ -0,0 +1,151 @@ +/* + * 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; + +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) { + return createFile(root, relativePath, ""); + } + + public static VirtualFile createFile(final VirtualFile root, final String relativePath, final 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) { + try { + AccessToken token = WriteAction.start(); + try { + VirtualFile parent = root; + Assert.assertNotNull(parent); + StringTokenizer parents = new StringTokenizer(PathUtil.getParentPath(relativePath), "/"); + while (parents.hasMoreTokens()) { + final String name = parents.nextToken(); + VirtualFile child = parent.findChild(name); + if (child == null || !child.isValid()) { + child = parent.createChildDirectory(VfsTestUtil.class, name); + } + parent = child; + } + + VirtualFile file; + parent.getChildren();//need this to ensure that fileCreated event is fired + if (dir) { + file = parent.createChildDirectory(VfsTestUtil.class, PathUtil.getFileName(relativePath)); + } + else { + file = parent.findFileByRelativePath(relativePath); + if (file == null) { + file = parent.createChildData(VfsTestUtil.class, PathUtil.getFileName(relativePath)); + } + VfsUtil.saveText(file, text); + } + return file; + } + finally { + token.finish(); + } + } + catch (IOException e) { + throw new RuntimeException(e); + } + } + + 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 { + FileUtil.writeToFile(new File(filePath), actual); + } + catch (IOException e) { + 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 new file mode 100644 index 00000000000..6a23abe1eb5 --- /dev/null +++ b/compiler/tests/org/jetbrains/kotlin/test/testFramework/mock/KtMockFileTypeManager.java @@ -0,0 +1,178 @@ +/* + * 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.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; +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; +import java.util.Locale; + +public class KtMockFileTypeManager extends FileTypeManager { + private final FileType fileType; + + public KtMockFileTypeManager(FileType fileType) { + this.fileType = fileType; + } + + @Override + @NotNull + public String getIgnoredFilesList() { + throw new IncorrectOperationException(); + } + + @Override + 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) { + } + + @Override + @NotNull + public FileType getFileTypeByFileName(@NotNull String fileName) { + return fileType; + } + + @Override + @NotNull + public FileType getFileTypeByFile(@NotNull VirtualFile file) { + return fileType; + } + + @Override + @NotNull + public FileType getFileTypeByExtension(@NotNull String extension) { + return fileType; + } + + @Override + @NotNull + public FileType[] getRegisteredFileTypes() { + return FileType.EMPTY_ARRAY; + } + + @Override + public boolean isFileIgnored(@NotNull String name) { + return false; + } + + @Override + public boolean isFileIgnored(@NotNull VirtualFile file) { + return false; + } + + @Override + @NotNull + public String[] getAssociatedExtensions(@NotNull FileType type) { + return ArrayUtil.EMPTY_STRING_ARRAY; + } + + @Override + public void addFileTypeListener(@NotNull FileTypeListener listener) { + } + + @Override + public void removeFileTypeListener(@NotNull FileTypeListener listener) { + } + + @Override + public FileType getKnownFileTypeOrAssociate(@NotNull VirtualFile file) { + return file.getFileType(); + } + + @Override + public FileType getKnownFileTypeOrAssociate(@NotNull VirtualFile file, @NotNull Project project) { + return getKnownFileTypeOrAssociate(file); + } + + @Override + @NotNull + public List getAssociations(@NotNull FileType type) { + return Collections.emptyList(); + } + + @Override + public void associate(@NotNull FileType type, @NotNull FileNameMatcher matcher) { + } + + @Override + public void removeAssociation(@NotNull FileType type, @NotNull FileNameMatcher matcher) { + } + + @Override + @NotNull + public FileType getStdFileType(@NotNull @NonNls final 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); + if ("XML".equals(fileTypeName)) return loadFileTypeSafe("com.intellij.ide.highlighter.XmlFileType", fileTypeName); + if ("DTD".equals(fileTypeName)) return loadFileTypeSafe("com.intellij.ide.highlighter.DTDFileType", fileTypeName); + if ("JSP".equals(fileTypeName)) return loadFileTypeSafe("com.intellij.ide.highlighter.NewJspFileType", fileTypeName); + if ("JSPX".equals(fileTypeName)) return loadFileTypeSafe("com.intellij.ide.highlighter.JspxFileType", fileTypeName); + if ("HTML".equals(fileTypeName)) return loadFileTypeSafe("com.intellij.ide.highlighter.HtmlFileType", fileTypeName); + if ("XHTML".equals(fileTypeName)) return loadFileTypeSafe("com.intellij.ide.highlighter.XHtmlFileType", fileTypeName); + if ("JavaScript".equals(fileTypeName)) return loadFileTypeSafe("com.intellij.lang.javascript.JavaScriptFileType", fileTypeName); + if ("Properties".equals(fileTypeName)) return loadFileTypeSafe("com.intellij.lang.properties.PropertiesFileType", fileTypeName); + return new KtMockLanguageFileType(PlainTextLanguage.INSTANCE, fileTypeName.toLowerCase()); + } + + private static FileType loadFileTypeSafe(final String className, String fileTypeName) { + try { + return (FileType)Class.forName(className).getField("INSTANCE").get(null); + } + catch (Exception ignored) { + return new KtMockLanguageFileType(PlainTextLanguage.INSTANCE, fileTypeName.toLowerCase(Locale.ENGLISH)); + } + } + + @Override + public boolean isFileOfType(@NotNull VirtualFile file, @NotNull FileType type) { + return false; + } + + @NotNull + @Override + public FileType detectFileTypeFromContent(@NotNull VirtualFile file) { + return UnknownFileType.INSTANCE; + } + + @Nullable + @Override + public FileType findFileTypeByName(@NotNull String fileTypeName) { + return null; + } +} \ No newline at end of file diff --git a/compiler/tests/org/jetbrains/kotlin/test/testFramework/mock/KtMockLanguageFileType.java b/compiler/tests/org/jetbrains/kotlin/test/testFramework/mock/KtMockLanguageFileType.java new file mode 100644 index 00000000000..42efbad4322 --- /dev/null +++ b/compiler/tests/org/jetbrains/kotlin/test/testFramework/mock/KtMockLanguageFileType.java @@ -0,0 +1,60 @@ +/* + * 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.lang.Language; +import com.intellij.openapi.fileTypes.LanguageFileType; +import com.sun.istack.internal.NotNull; + +import javax.swing.*; + +public class KtMockLanguageFileType extends LanguageFileType { + private final String myExtension; + + public KtMockLanguageFileType(@NotNull Language language, String extension) { + super(language); + this.myExtension = extension; + } + + @NotNull + public String getName() { + return this.getLanguage().getID(); + } + + @NotNull + public String getDescription() { + return ""; + } + + @NotNull + public String getDefaultExtension() { + String var10000 = this.myExtension; + if(this.myExtension == null) { + throw new IllegalStateException(String.format("@NotNull method %s.%s must not return null", new Object[]{"com/intellij/mock/KtMockLanguageFileType", "getDefaultExtension"})); + } else { + return var10000; + } + } + + public Icon getIcon() { + return null; + } + + public boolean equals(Object obj) { + return !(obj instanceof LanguageFileType)?false: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 new file mode 100644 index 00000000000..1e05181c7be --- /dev/null +++ b/compiler/tests/org/jetbrains/kotlin/test/testFramework/mock/MockEditorEventMulticaster.java @@ -0,0 +1,94 @@ +/* + * 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.Disposable; +import com.intellij.openapi.editor.event.*; +import org.jetbrains.annotations.NotNull; + +public class MockEditorEventMulticaster implements EditorEventMulticaster { + public MockEditorEventMulticaster() { + } + + @Override + public void addDocumentListener(@NotNull DocumentListener listener) { + } + + @Override + public void addDocumentListener(@NotNull DocumentListener listener, @NotNull Disposable parentDisposable) { + } + + @Override + public void removeDocumentListener(@NotNull DocumentListener listener) { + } + + @Override + public void addEditorMouseListener(@NotNull EditorMouseListener listener) { + } + + @Override + public void addEditorMouseListener(@NotNull final EditorMouseListener listener, @NotNull final Disposable parentDisposable) { + } + + @Override + public void removeEditorMouseListener(@NotNull EditorMouseListener listener) { + } + + @Override + public void addEditorMouseMotionListener(@NotNull EditorMouseMotionListener listener) { + } + + @Override + public void addEditorMouseMotionListener(@NotNull EditorMouseMotionListener listener, @NotNull Disposable parentDisposable) { + } + + @Override + public void removeEditorMouseMotionListener(@NotNull EditorMouseMotionListener listener) { + } + + @Override + public void addCaretListener(@NotNull CaretListener listener) { + } + + @Override + public void addCaretListener(@NotNull CaretListener listener, @NotNull Disposable parentDisposable) { + } + + @Override + public void removeCaretListener(@NotNull CaretListener listener) { + } + + @Override + public void addSelectionListener(@NotNull SelectionListener listener) { + } + + @Override + public void addSelectionListener(@NotNull SelectionListener listener, @NotNull Disposable parentDisposable) { + } + + @Override + public void removeSelectionListener(@NotNull SelectionListener listener) { + } + + @Override + public void addVisibleAreaListener(@NotNull VisibleAreaListener listener) { + } + + @Override + public void removeVisibleAreaListener(@NotNull VisibleAreaListener listener) { + } + +} diff --git a/compiler/tests/org/jetbrains/kotlin/test/testFramework/mock/MockEditorFactory.java b/compiler/tests/org/jetbrains/kotlin/test/testFramework/mock/MockEditorFactory.java new file mode 100644 index 00000000000..5abec62a846 --- /dev/null +++ b/compiler/tests/org/jetbrains/kotlin/test/testFramework/mock/MockEditorFactory.java @@ -0,0 +1,122 @@ +/* + * 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.Disposable; +import com.intellij.openapi.editor.Document; +import com.intellij.openapi.editor.Editor; +import com.intellij.openapi.editor.EditorFactory; +import com.intellij.openapi.editor.event.EditorEventMulticaster; +import com.intellij.openapi.editor.event.EditorFactoryListener; +import com.intellij.openapi.editor.impl.DocumentImpl; +import com.intellij.openapi.fileTypes.FileType; +import com.intellij.openapi.project.Project; +import com.intellij.openapi.vfs.VirtualFile; +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; + } + + @Override + public Editor createViewer(@NotNull Document document) { + return null; + } + + @Override + public Editor createEditor(@NotNull Document document, Project project) { + return null; + } + + @Override + public Editor createEditor(@NotNull Document document, Project project, @NotNull VirtualFile file, boolean isViewer) { + return null; + } + + @Override + public Editor createEditor(@NotNull final Document document, final Project project, @NotNull final FileType fileType, final boolean isViewer) { + return null; + } + + @Override + public Editor createViewer(@NotNull Document document, Project project) { + return null; + } + + @Override + public void releaseEditor(@NotNull Editor editor) { + } + + @Override + @NotNull + public Editor[] getEditors(@NotNull Document document, Project project) { + return Editor.EMPTY_ARRAY; + } + + @Override + @NotNull + public Editor[] getEditors(@NotNull Document document) { + return getEditors(document, null); + } + + @Override + @NotNull + public Editor[] getAllEditors() { + return Editor.EMPTY_ARRAY; + } + + @Override + public void addEditorFactoryListener(@NotNull EditorFactoryListener listener) { + } + + @Override + public void addEditorFactoryListener(@NotNull EditorFactoryListener listener, @NotNull Disposable parentDisposable) { + } + + @Override + public void removeEditorFactoryListener(@NotNull EditorFactoryListener listener) { + } + + @Override + @NotNull + public EditorEventMulticaster getEventMulticaster() { + return new MockEditorEventMulticaster(); + } + + @Override + @NotNull + public Document createDocument(@NotNull CharSequence text) { + return new DocumentImpl(text); + } + + @Override + @NotNull + public Document createDocument(@NotNull char[] text) { + return createDocument(new CharArrayCharSequence(text)); + } + + @Override + public void refreshAllEditors() { + } + +} diff --git a/compiler/tests/org/jetbrains/kotlin/test/testFramework/mock/MockFileManager.java b/compiler/tests/org/jetbrains/kotlin/test/testFramework/mock/MockFileManager.java new file mode 100644 index 00000000000..787a49df7d1 --- /dev/null +++ b/compiler/tests/org/jetbrains/kotlin/test/testFramework/mock/MockFileManager.java @@ -0,0 +1,107 @@ +/* + * 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.FileViewProvider; +import com.intellij.psi.PsiDirectory; +import com.intellij.psi.PsiFile; +import com.intellij.psi.SingleRootFileViewProvider; +import com.intellij.psi.impl.PsiManagerEx; +import com.intellij.psi.impl.file.impl.FileManager; +import com.intellij.util.containers.WeakFactoryMap; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.List; + +public class MockFileManager implements FileManager { + private final PsiManagerEx myManager; + // in mock tests it's LightVirtualFile, they're only alive when they're referenced, + // and there can not be several instances representing the same file + private final WeakFactoryMap myViewProviders = new WeakFactoryMap() { + @Override + protected FileViewProvider create(VirtualFile key) { + return new SingleRootFileViewProvider(myManager, key); + } + }; + + @Override + @NotNull + public FileViewProvider createFileViewProvider(@NotNull VirtualFile file, boolean eventSystemEnabled) { + return new SingleRootFileViewProvider(myManager, file, eventSystemEnabled); + } + + public MockFileManager(PsiManagerEx manager) { + myManager = manager; + } + + @Override + public void dispose() { + throw new UnsupportedOperationException("Method dispose is not yet implemented in " + getClass().getName()); + } + + @Override + @Nullable + public PsiFile findFile(@NotNull VirtualFile vFile) { + return getCachedPsiFile(vFile); + } + + @Override + @Nullable + public PsiDirectory findDirectory(@NotNull VirtualFile vFile) { + throw new UnsupportedOperationException("Method findDirectory is not yet implemented in " + getClass().getName()); + } + + @Override + public void reloadFromDisk(@NotNull PsiFile file) //Q: move to PsiFile(Impl)? + { + throw new UnsupportedOperationException("Method reloadFromDisk is not yet implemented in " + getClass().getName()); + } + + @Override + @Nullable + public PsiFile getCachedPsiFile(@NotNull VirtualFile vFile) { + FileViewProvider provider = findCachedViewProvider(vFile); + return provider.getPsi(provider.getBaseLanguage()); + } + + @Override + public void cleanupForNextTest() { + myViewProviders.clear(); + } + + @Override + public FileViewProvider findViewProvider(@NotNull VirtualFile file) { + throw new UnsupportedOperationException("Method findViewProvider is not yet implemented in " + getClass().getName()); + } + + @Override + public FileViewProvider findCachedViewProvider(@NotNull VirtualFile file) { + return myViewProviders.get(file); + } + + @Override + public void setViewProvider(@NotNull VirtualFile virtualFile, FileViewProvider fileViewProvider) { + myViewProviders.put(virtualFile, fileViewProvider); + } + + @Override + @NotNull + public List getAllCachedFiles() { + throw new UnsupportedOperationException("Method getAllCachedFiles is not yet implemented in " + getClass().getName()); + } +} diff --git a/compiler/tests/org/jetbrains/kotlin/test/testFramework/mock/MockPsiDocumentManager.java b/compiler/tests/org/jetbrains/kotlin/test/testFramework/mock/MockPsiDocumentManager.java new file mode 100644 index 00000000000..48bfeeb2813 --- /dev/null +++ b/compiler/tests/org/jetbrains/kotlin/test/testFramework/mock/MockPsiDocumentManager.java @@ -0,0 +1,146 @@ +/* + * 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.editor.Document; +import com.intellij.openapi.fileEditor.FileDocumentManager; +import com.intellij.openapi.util.Computable; +import com.intellij.openapi.vfs.VirtualFile; +import com.intellij.psi.PsiDocumentManager; +import com.intellij.psi.PsiFile; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.Collection; + +public class MockPsiDocumentManager extends PsiDocumentManager { + @Override + @Nullable + public PsiFile getPsiFile(@NotNull Document document) { + throw new UnsupportedOperationException("Method getPsiFile is not yet implemented in " + getClass().getName()); + } + + @Override + @Nullable + public PsiFile getCachedPsiFile(@NotNull Document document) { + throw new UnsupportedOperationException("Method getCachedPsiFile is not yet implemented in " + getClass().getName()); + } + + @Override + @Nullable + public Document getDocument(@NotNull PsiFile file) { + return null; + } + + @Override + @Nullable + public Document getCachedDocument(@NotNull PsiFile file) { + VirtualFile vFile = file.getViewProvider().getVirtualFile(); + return FileDocumentManager.getInstance().getCachedDocument(vFile); + } + + @Override + public void commitAllDocuments() { + } + + @Override + public void performForCommittedDocument(@NotNull final Document document, @NotNull final Runnable action) { + action.run(); + } + + @Override + public void commitDocument(@NotNull Document document) { + } + + @NotNull + @Override + public CharSequence getLastCommittedText(@NotNull Document document) { + return document.getImmutableCharSequence(); + } + + @Override + public long getLastCommittedStamp(@NotNull Document document) { + return document.getModificationStamp(); + } + + @Nullable + @Override + public Document getLastCommittedDocument(@NotNull PsiFile file) { + return null; + } + + @Override + @NotNull + public Document[] getUncommittedDocuments() { + throw new UnsupportedOperationException("Method getUncommittedDocuments is not yet implemented in " + getClass().getName()); + } + + @Override + public boolean isUncommited(@NotNull Document document) { + throw new UnsupportedOperationException("Method isUncommited is not yet implemented in " + getClass().getName()); + } + + @Override + public boolean isCommitted(@NotNull Document document) { + throw new UnsupportedOperationException(); + } + + @Override + public boolean hasUncommitedDocuments() { + throw new UnsupportedOperationException("Method hasUncommitedDocuments is not yet implemented in " + getClass().getName()); + } + + @Override + public void commitAndRunReadAction(@NotNull Runnable runnable) { + throw new UnsupportedOperationException("Method commitAndRunReadAction is not yet implemented in " + getClass().getName()); + } + + @Override + public T commitAndRunReadAction(@NotNull Computable computation) { + throw new UnsupportedOperationException("Method commitAndRunReadAction is not yet implemented in " + getClass().getName()); + } + + @Override + public void addListener(@NotNull Listener listener) { + throw new UnsupportedOperationException("Method addListener is not yet implemented in " + getClass().getName()); + } + + @Override + public void removeListener(@NotNull Listener listener) { + throw new UnsupportedOperationException("Method removeListener is not yet implemented in " + getClass().getName()); + } + + @Override + public boolean isDocumentBlockedByPsi(@NotNull Document doc) { + throw new UnsupportedOperationException("Method isDocumentBlockedByPsi is not yet implemented in " + getClass().getName()); + } + + @Override + public void doPostponedOperationsAndUnblockDocument(@NotNull Document doc) { + throw new UnsupportedOperationException( + "Method doPostponedOperationsAndUnblockDocument is not yet implemented in " + getClass().getName()); + } + + @Override + public boolean performWhenAllCommitted(@NotNull Runnable action) { + throw new UnsupportedOperationException(); + } + + @Override + public void reparseFiles(@NotNull Collection files, boolean includeOpenFiles) { + throw new UnsupportedOperationException(); + } +} diff --git a/compiler/tests/org/jetbrains/kotlin/test/testFramework/mock/MockPsiManager.java b/compiler/tests/org/jetbrains/kotlin/test/testFramework/mock/MockPsiManager.java new file mode 100644 index 00000000000..8d0c382a14b --- /dev/null +++ b/compiler/tests/org/jetbrains/kotlin/test/testFramework/mock/MockPsiManager.java @@ -0,0 +1,188 @@ +/* + * 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.Disposable; +import com.intellij.openapi.project.Project; +import com.intellij.openapi.util.Comparing; +import com.intellij.openapi.util.Key; +import com.intellij.openapi.vfs.VirtualFile; +import com.intellij.psi.*; +import com.intellij.psi.impl.PsiManagerEx; +import com.intellij.psi.impl.PsiModificationTrackerImpl; +import com.intellij.psi.impl.PsiTreeChangeEventImpl; +import com.intellij.psi.impl.file.impl.FileManager; +import com.intellij.psi.util.PsiModificationTracker; +import gnu.trove.THashMap; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.Map; + +public class MockPsiManager extends PsiManagerEx { + private final Project myProject; + private final Map myDirectories = new THashMap(); + private MockFileManager myMockFileManager; + private PsiModificationTrackerImpl myPsiModificationTracker; + + public MockPsiManager(@NotNull Project project) { + myProject = project; + } + + public void addPsiDirectory(VirtualFile file, PsiDirectory psiDirectory) { + myDirectories.put(file, psiDirectory); + } + + @Override + @NotNull + public Project getProject() { + return myProject; + } + + @Override + public PsiFile findFile(@NotNull VirtualFile file) { + return null; + } + + @Override + @Nullable + public + FileViewProvider findViewProvider(@NotNull VirtualFile file) { + return null; + } + + @Override + public PsiDirectory findDirectory(@NotNull VirtualFile file) { + return myDirectories.get(file); + } + + @Override + public boolean areElementsEquivalent(PsiElement element1, PsiElement element2) { + return Comparing.equal(element1, element2); + } + + @Override + public void reloadFromDisk(@NotNull PsiFile file) { + } + + @Override + public void addPsiTreeChangeListener(@NotNull PsiTreeChangeListener listener) { + } + + @Override + public void addPsiTreeChangeListener(@NotNull PsiTreeChangeListener listener, @NotNull Disposable parentDisposable) { + } + + @Override + public void removePsiTreeChangeListener(@NotNull PsiTreeChangeListener listener) { + } + + @Override + @NotNull + public PsiModificationTracker getModificationTracker() { + if (myPsiModificationTracker == null) { + myPsiModificationTracker = new PsiModificationTrackerImpl(myProject); + } + return myPsiModificationTracker; + } + + @Override + public void startBatchFilesProcessingMode() { + } + + @Override + public void finishBatchFilesProcessingMode() { + } + + @Override + public T getUserData(@NotNull Key key) { + return null; + } + + @Override + public void putUserData(@NotNull Key key, T value) { + } + + @Override + public boolean isDisposed() { + return false; + } + + @Override + public void dropResolveCaches() { + getFileManager().cleanupForNextTest(); + } + + @Override + public boolean isInProject(@NotNull PsiElement element) { + return false; + } + + @Override + public boolean isBatchFilesProcessingMode() { + return false; + } + + @Override + public boolean isAssertOnFileLoading(@NotNull VirtualFile file) { + return false; + } + + @Override + public void beforeChange(boolean isPhysical) { + throw new UnsupportedOperationException(); + } + + @Override + public void afterChange(boolean isPhysical) { + throw new UnsupportedOperationException(); + } + + @Override + public void registerRunnableToRunOnChange(@NotNull Runnable runnable) { + } + + @Override + public void registerRunnableToRunOnAnyChange(@NotNull Runnable runnable) { + } + + @Override + public void registerRunnableToRunAfterAnyChange(@NotNull Runnable runnable) { + throw new UnsupportedOperationException("Method registerRunnableToRunAfterAnyChange is not yet implemented in " + getClass().getName()); + } + + @Override + @NotNull + public FileManager getFileManager() { + if (myMockFileManager == null) { + myMockFileManager = new MockFileManager(this); + } + return myMockFileManager; + } + + @Override + public void beforeChildRemoval(@NotNull final PsiTreeChangeEventImpl event) { + } + + @Override + public void beforeChildReplacement(@NotNull final PsiTreeChangeEventImpl event) { + } + + @Override + public void beforeChildAddition(@NotNull PsiTreeChangeEventImpl event) { + } +} diff --git a/compiler/tests/org/jetbrains/kotlin/test/testFramework/mock/MockSchemesManagerFactory.java b/compiler/tests/org/jetbrains/kotlin/test/testFramework/mock/MockSchemesManagerFactory.java new file mode 100644 index 00000000000..80cd84785de --- /dev/null +++ b/compiler/tests/org/jetbrains/kotlin/test/testFramework/mock/MockSchemesManagerFactory.java @@ -0,0 +1,33 @@ +/* + * 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.components.RoamingType; +import com.intellij.openapi.options.*; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +public class MockSchemesManagerFactory extends SchemesManagerFactory { + private static final SchemesManager EMPTY = new EmptySchemesManager(); + + @Override + protected SchemesManager create(@NotNull String directoryName, + @NotNull SchemeProcessor processor, + @NotNull RoamingType roamingType, + @Nullable String presentableName) { + 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 new file mode 100644 index 00000000000..0779e012987 --- /dev/null +++ b/compiler/tests/org/jetbrains/kotlin/test/testFramework/mock/PsiManagerEx.java @@ -0,0 +1,53 @@ +/* + * 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 new file mode 100644 index 00000000000..b041779047b --- /dev/null +++ b/compiler/tests/org/jetbrains/kotlin/test/testFramework/util.kt @@ -0,0 +1,37 @@ +/* + * 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 + +import com.intellij.openapi.application.ApplicationManager +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 diff --git a/idea/idea.iml b/idea/idea.iml index 9ea7099080f..dc148164c2f 100644 --- a/idea/idea.iml +++ b/idea/idea.iml @@ -20,7 +20,6 @@ - @@ -50,6 +49,7 @@ + \ No newline at end of file diff --git a/plugins/plugins-tests/tests/org/jetbrains/kotlin/lang/resolve/android/test/AbstractAndroidSyntheticPropertyDescriptorTest.kt b/plugins/plugins-tests/tests/org/jetbrains/kotlin/lang/resolve/android/test/AbstractAndroidSyntheticPropertyDescriptorTest.kt index bd601559046..26202d53e1a 100644 --- a/plugins/plugins-tests/tests/org/jetbrains/kotlin/lang/resolve/android/test/AbstractAndroidSyntheticPropertyDescriptorTest.kt +++ b/plugins/plugins-tests/tests/org/jetbrains/kotlin/lang/resolve/android/test/AbstractAndroidSyntheticPropertyDescriptorTest.kt @@ -28,9 +28,10 @@ import org.jetbrains.kotlin.storage.LockBasedStorageManager import org.jetbrains.kotlin.test.ConfigurationKind import org.jetbrains.kotlin.test.KotlinTestUtils import org.jetbrains.kotlin.test.TestJdkKind +import org.jetbrains.kotlin.test.testFramework.KtUsefulTestCase import java.io.File -abstract class AbstractAndroidSyntheticPropertyDescriptorTest : UsefulTestCase() { +abstract class AbstractAndroidSyntheticPropertyDescriptorTest : KtUsefulTestCase() { fun doTest(path: String) { val config = KotlinTestUtils.compilerConfigurationForTests(ConfigurationKind.ALL, TestJdkKind.ANDROID_API) diff --git a/plugins/plugins-tests/tests/org/jetbrains/kotlin/lang/resolve/android/test/CompilerTestUtils.kt b/plugins/plugins-tests/tests/org/jetbrains/kotlin/lang/resolve/android/test/CompilerTestUtils.kt index 71f107e4a64..d1649ee2973 100644 --- a/plugins/plugins-tests/tests/org/jetbrains/kotlin/lang/resolve/android/test/CompilerTestUtils.kt +++ b/plugins/plugins-tests/tests/org/jetbrains/kotlin/lang/resolve/android/test/CompilerTestUtils.kt @@ -16,7 +16,6 @@ package org.jetbrains.kotlin.lang.resolve.android.test -import com.intellij.testFramework.UsefulTestCase import com.intellij.testFramework.registerServiceInstance import org.jetbrains.kotlin.android.synthetic.AndroidConfigurationKeys import org.jetbrains.kotlin.android.synthetic.AndroidExtensionPropertiesComponentContainerContributor @@ -33,9 +32,10 @@ import org.jetbrains.kotlin.codegen.extensions.ExpressionCodegenExtension import org.jetbrains.kotlin.config.CompilerConfiguration import org.jetbrains.kotlin.extensions.StorageComponentContainerContributor import org.jetbrains.kotlin.resolve.jvm.extensions.PackageFragmentProviderExtension +import org.jetbrains.kotlin.test.testFramework.KtUsefulTestCase import java.io.File -fun UsefulTestCase.createAndroidTestEnvironment(configuration: CompilerConfiguration, resDirectories: List): KotlinCoreEnvironment { +fun KtUsefulTestCase.createAndroidTestEnvironment(configuration: CompilerConfiguration, resDirectories: List): KotlinCoreEnvironment { configuration.put(AndroidConfigurationKeys.VARIANT, resDirectories) configuration.put(AndroidConfigurationKeys.PACKAGE, "test") diff --git a/temp-jdk8/temp-jdk8.iml b/temp-jdk8/temp-jdk8.iml deleted file mode 100644 index 37cc8040633..00000000000 --- a/temp-jdk8/temp-jdk8.iml +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/update_dependencies.xml b/update_dependencies.xml index db081740ba6..16a8e026589 100644 --- a/update_dependencies.xml +++ b/update_dependencies.xml @@ -747,6 +747,15 @@ + + + + + + + + +