Clean up copied code. Remove comments and unused code.

This commit is contained in:
Nikolay Krasko
2016-03-29 15:38:21 +03:00
parent 9fd5568425
commit fdf7a3325d
18 changed files with 373 additions and 2098 deletions
@@ -1,35 +0,0 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.test.testFramework;
/**
* Base class of block, annotated with exception. Inheritors of this
* class specifies concrete Exception classes
*/
public abstract class AbstractExceptionCase<T extends Throwable> {
public abstract Class<T> 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.";
}
}
@@ -23,10 +23,6 @@ import javax.swing.SwingUtilities
class EdtTestUtil {
companion object {
@TestOnly @JvmStatic fun runInEdtAndWait(runnable: ThrowableRunnable<Throwable>) {
runInEdtAndWait { runnable.run() }
}
@TestOnly @JvmStatic fun runInEdtAndWait(runnable: Runnable) {
runInEdtAndWait { runnable.run() }
}
@@ -1,5 +1,5 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -19,7 +19,8 @@ package org.jetbrains.kotlin.test.testFramework;
import com.intellij.core.CoreASTFactory;
import com.intellij.lang.*;
import com.intellij.lang.impl.PsiBuilderFactoryImpl;
import com.intellij.mock.*;
import com.intellij.mock.MockFileDocumentManagerImpl;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.PathManager;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.EditorFactory;
@@ -51,6 +52,7 @@ import com.intellij.psi.impl.source.text.BlockSupportImpl;
import com.intellij.psi.impl.source.text.DiffLog;
import com.intellij.psi.util.CachedValuesManager;
import com.intellij.testFramework.LightVirtualFile;
import com.intellij.testFramework.TestDataFile;
import com.intellij.util.CachedValuesManagerImpl;
import com.intellij.util.Function;
import com.intellij.util.messages.MessageBus;
@@ -59,18 +61,17 @@ import junit.framework.TestCase;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.kotlin.test.testFramework.mock.*;
import org.picocontainer.ComponentAdapter;
import org.picocontainer.MutablePicoContainer;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.Set;
@SuppressWarnings("ALL")
public abstract class KtParsingTestCase extends KtPlatformLiteFixture {
public static final Key<Document> HARD_REF_TO_DOCUMENT_KEY = Key.create("HARD_REF_TO_DOCUMENT_KEY");
protected String myFilePrefix;
protected String myFilePrefix = "";
protected String myFileExt;
protected final String myFullDataPath;
protected PsiFile myFile;
@@ -85,74 +86,62 @@ public abstract class KtParsingTestCase extends KtPlatformLiteFixture {
}
protected KtParsingTestCase(@NonNls @NotNull String dataPath, @NotNull String fileExt, boolean lowercaseFirstLetter, @NotNull ParserDefinition... definitions) {
this.myFilePrefix = "";
this.myDefinitions = definitions;
this.myFullDataPath = this.getTestDataPath() + "/" + dataPath;
this.myFileExt = fileExt;
this.myLowercaseFirstLetter = lowercaseFirstLetter;
myDefinitions = definitions;
myFullDataPath = getTestDataPath() + "/" + dataPath;
myFileExt = fileExt;
myLowercaseFirstLetter = lowercaseFirstLetter;
}
@Override
protected void setUp() throws Exception {
super.setUp();
this.initApplication();
//ComponentAdapter component = getApplication().getPicoContainer().getComponentAdapter(ProgressManager.class.getName());
//if(component == null) {
// getApplication().getPicoContainer().registerComponent(new AbstractComponentAdapter(ProgressManager.class.getName(), Object.class) {
// public Object getComponentInstance(PicoContainer container) throws PicoInitializationException, PicoIntrospectionException {
// return new ProgressManagerImpl();
// }
//
// public void verify(PicoContainer container) throws PicoIntrospectionException {
// }
// });
//}
initApplication();
ComponentAdapter component = getApplication().getPicoContainer().getComponentAdapter(ProgressManager.class.getName());
Extensions.registerAreaClass("IDEA_PROJECT", (String)null);
this.myProject = new MockProjectEx(this.getTestRootDisposable());
this.myPsiManager = new MockPsiManager(this.myProject);
this.myFileFactory = new PsiFileFactoryImpl(this.myPsiManager);
Extensions.registerAreaClass("IDEA_PROJECT", null);
myProject = new MockProjectEx(getTestRootDisposable());
myPsiManager = new MockPsiManager(myProject);
myFileFactory = new PsiFileFactoryImpl(myPsiManager);
MutablePicoContainer appContainer = getApplication().getPicoContainer();
registerComponentInstance(appContainer, MessageBus.class, MessageBusFactory.newMessageBus(getApplication()));
registerComponentInstance(appContainer, SchemesManagerFactory.class, new MockSchemesManagerFactory());
final MockEditorFactory editorFactory = new MockEditorFactory();
registerComponentInstance(appContainer, EditorFactory.class, editorFactory);
registerComponentInstance(appContainer, FileDocumentManager.class, new MockFileDocumentManagerImpl(new Function<CharSequence, Document>() {
@Override
public Document fun(CharSequence charSequence) {
return editorFactory.createDocument(charSequence);
}
}, HARD_REF_TO_DOCUMENT_KEY));
registerComponentInstance(appContainer, PsiDocumentManager.class, new MockPsiDocumentManager());
this.registerApplicationService(PsiBuilderFactory.class, new PsiBuilderFactoryImpl());
this.registerApplicationService(DefaultASTFactory.class, new CoreASTFactory());
this.registerApplicationService(ReferenceProvidersRegistry.class, new ReferenceProvidersRegistryImpl());
registerApplicationService(PsiBuilderFactory.class, new PsiBuilderFactoryImpl());
registerApplicationService(DefaultASTFactory.class, new CoreASTFactory());
registerApplicationService(ReferenceProvidersRegistry.class, new ReferenceProvidersRegistryImpl());
registerApplicationService(ProgressManager.class, new CoreProgressManager());
this.myProject.registerService(CachedValuesManager.class, new CachedValuesManagerImpl(this.myProject, new PsiCachedValuesFactory(this.myPsiManager)));
this.myProject.registerService(PsiManager.class, this.myPsiManager);
//this.myProject.registerService(StartupManager.class, new StartupManagerImpl(this.myProject));
myProject.registerService(CachedValuesManager.class, new CachedValuesManagerImpl(myProject, new PsiCachedValuesFactory(myPsiManager)));
myProject.registerService(PsiManager.class, myPsiManager);
this.registerExtensionPoint(FileTypeFactory.FILE_TYPE_FACTORY_EP, FileTypeFactory.class);
ParserDefinition[] pomModel = this.myDefinitions;
int var5 = pomModel.length;
for(int var6 = 0; var6 < var5; ++var6) {
ParserDefinition definition = pomModel[var6];
this.addExplicitExtension(LanguageParserDefinitions.INSTANCE, definition.getFileNodeType().getLanguage(), definition);
for (ParserDefinition definition : myDefinitions) {
addExplicitExtension(LanguageParserDefinitions.INSTANCE, definition.getFileNodeType().getLanguage(), definition);
}
if (myDefinitions.length > 0) {
configureFromParserDefinition(myDefinitions[0], myFileExt);
}
if(this.myDefinitions.length > 0) {
this.configureFromParserDefinition(this.myDefinitions[0], this.myFileExt);
}
PomModelImpl var8 = new PomModelImpl(this.myProject);
this.myProject.registerService(PomModel.class, var8);
new TreeAspect(var8);
// That's for reparse routines
final PomModelImpl pomModel = new PomModelImpl(myProject);
myProject.registerService(PomModel.class, pomModel);
new TreeAspect(pomModel);
}
public void configureFromParserDefinition(ParserDefinition definition, String extension) {
this.myLanguage = definition.getFileNodeType().getLanguage();
this.myFileExt = extension;
this.addExplicitExtension(LanguageParserDefinitions.INSTANCE, this.myLanguage, definition);
myLanguage = definition.getFileNodeType().getLanguage();
myFileExt = extension;
addExplicitExtension(LanguageParserDefinitions.INSTANCE, this.myLanguage, definition);
registerComponentInstance(
getApplication().getPicoContainer(), FileTypeManager.class,
new KtMockFileTypeManager(new KtMockLanguageFileType(myLanguage, myFileExt)));
@@ -160,16 +149,19 @@ public abstract class KtParsingTestCase extends KtPlatformLiteFixture {
protected <T> void addExplicitExtension(final LanguageExtension<T> instance, final Language language, final T object) {
instance.addExplicitExtension(language, object);
Disposer.register(this.myProject, new com.intellij.openapi.Disposable() {
Disposer.register(myProject, new Disposable() {
@Override
public void dispose() {
instance.removeExplicitExtension(language, object);
}
});
}
@Override
protected <T> void registerExtensionPoint(final ExtensionPointName<T> extensionPointName, Class<T> aClass) {
super.registerExtensionPoint(extensionPointName, aClass);
Disposer.register(this.myProject, new com.intellij.openapi.Disposable() {
Disposer.register(myProject, new Disposable() {
@Override
public void dispose() {
Extensions.getRootArea().unregisterExtensionPoint(extensionPointName.getName());
}
@@ -178,36 +170,37 @@ public abstract class KtParsingTestCase extends KtPlatformLiteFixture {
protected <T> void registerApplicationService(final Class<T> aClass, T object) {
getApplication().registerService(aClass, object);
Disposer.register(this.myProject, new com.intellij.openapi.Disposable() {
Disposer.register(myProject, new Disposable() {
@Override
public void dispose() {
KtPlatformLiteFixture.getApplication().getPicoContainer().unregisterComponent(aClass.getName());
getApplication().getPicoContainer().unregisterComponent(aClass.getName());
}
});
}
public MockProjectEx getProject() {
return this.myProject;
return myProject;
}
public MockPsiManager getPsiManager() {
return this.myPsiManager;
return myPsiManager;
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
this.myFile = null;
this.myProject = null;
this.myPsiManager = null;
myFile = null;
myProject = null;
myPsiManager = null;
}
protected String getTestDataPath() {
return PathManager.getHomePath();
//return PathManagerEx.getTestDataPath();
}
@NotNull
public final String getTestName() {
return this.getTestName(this.myLowercaseFirstLetter);
return getTestName(myLowercaseFirstLetter);
}
protected boolean includeRanges() {
@@ -223,88 +216,91 @@ public abstract class KtParsingTestCase extends KtPlatformLiteFixture {
}
protected void doTest(boolean checkResult) {
String name = this.getTestName();
String name = getTestName();
try {
String e = this.loadFile(name + "." + this.myFileExt);
this.myFile = this.createPsiFile(name, e);
ensureParsed(this.myFile);
assertEquals("light virtual file text mismatch", e, ((LightVirtualFile)this.myFile.getVirtualFile()).getContent().toString());
assertEquals("virtual file text mismatch", e, LoadTextUtil.loadText(this.myFile.getVirtualFile()));
assertEquals("doc text mismatch", e, this.myFile.getViewProvider().getDocument().getText());
assertEquals("psi text mismatch", e, this.myFile.getText());
ensureCorrectReparse(this.myFile);
if(checkResult) {
this.checkResult(name, this.myFile);
} else {
toParseTreeText(this.myFile, this.skipSpaces(), this.includeRanges());
String text = loadFile(name + "." + myFileExt);
myFile = createPsiFile(name, text);
ensureParsed(myFile);
assertEquals("light virtual file text mismatch", text, ((LightVirtualFile)myFile.getVirtualFile()).getContent().toString());
assertEquals("virtual file text mismatch", text, LoadTextUtil.loadText(myFile.getVirtualFile()));
assertEquals("doc text mismatch", text, myFile.getViewProvider().getDocument().getText());
assertEquals("psi text mismatch", text, myFile.getText());
ensureCorrectReparse(myFile);
if (checkResult){
checkResult(name, myFile);
}
} catch (IOException var4) {
throw new RuntimeException(var4);
else{
toParseTreeText(myFile, skipSpaces(), includeRanges());
}
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
protected void doTest(String suffix) throws IOException {
String name = this.getTestName();
String text = this.loadFile(name + "." + this.myFileExt);
this.myFile = this.createPsiFile(name, text);
ensureParsed(this.myFile);
assertEquals(text, this.myFile.getText());
this.checkResult(name + suffix, this.myFile);
String name = getTestName();
String text = loadFile(name + "." + myFileExt);
myFile = createPsiFile(name, text);
ensureParsed(myFile);
assertEquals(text, myFile.getText());
checkResult(name + suffix, myFile);
}
protected void doCodeTest(String code) throws IOException {
String name = this.getTestName();
this.myFile = this.createPsiFile("a", code);
ensureParsed(this.myFile);
assertEquals(code, this.myFile.getText());
this.checkResult(this.myFilePrefix + name, this.myFile);
String name = getTestName();
myFile = createPsiFile("a", code);
ensureParsed(myFile);
assertEquals(code, myFile.getText());
checkResult(myFilePrefix + name, myFile);
}
protected PsiFile createPsiFile(String name, String text) {
return this.createFile(name + "." + this.myFileExt, text);
return createFile(name + "." + myFileExt, text);
}
protected PsiFile createFile(@NonNls String name, String text) {
LightVirtualFile virtualFile = new LightVirtualFile(name, this.myLanguage, text);
LightVirtualFile virtualFile = new LightVirtualFile(name, myLanguage, text);
virtualFile.setCharset(CharsetToolkit.UTF8_CHARSET);
return this.createFile(virtualFile);
return createFile(virtualFile);
}
protected PsiFile createFile(LightVirtualFile virtualFile) {
return this.myFileFactory.trySetupPsiForFile(virtualFile, this.myLanguage, true, false);
return myFileFactory.trySetupPsiForFile(virtualFile, myLanguage, true, false);
}
protected void checkResult(@NonNls String targetDataName, PsiFile file) throws IOException {
doCheckResult(this.myFullDataPath, file, this.checkAllPsiRoots(), targetDataName, this.skipSpaces(), this.includeRanges());
protected void checkResult(@NonNls @TestDataFile String targetDataName, final PsiFile file) throws IOException {
doCheckResult(myFullDataPath, file, checkAllPsiRoots(), targetDataName, skipSpaces(), includeRanges());
}
public static void doCheckResult(String testDataDir, PsiFile file, boolean checkAllPsiRoots, String targetDataName, boolean skipSpaces, boolean printRanges) throws IOException {
public static void doCheckResult(String testDataDir,
PsiFile file,
boolean checkAllPsiRoots,
String targetDataName,
boolean skipSpaces,
boolean printRanges) throws IOException {
FileViewProvider provider = file.getViewProvider();
Set languages = provider.getLanguages();
if(checkAllPsiRoots && languages.size() != 1) {
Iterator var8 = languages.iterator();
Set<Language> languages = provider.getLanguages();
while(var8.hasNext()) {
Language language = (Language)var8.next();
PsiFile root = provider.getPsi(language);
String expectedName = targetDataName + "." + language.getID() + ".txt";
doCheckResult(testDataDir, expectedName, toParseTreeText(root, skipSpaces, printRanges).trim());
}
} else {
if (!checkAllPsiRoots || languages.size() == 1) {
doCheckResult(testDataDir, targetDataName + ".txt", toParseTreeText(file, skipSpaces, printRanges).trim());
return;
}
for (Language language : languages) {
PsiFile root = provider.getPsi(language);
String expectedName = targetDataName + "." + language.getID() + ".txt";
doCheckResult(testDataDir, expectedName, toParseTreeText(root, skipSpaces, printRanges).trim());
}
}
protected void checkResult(String actual) throws IOException {
String name = this.getTestName();
doCheckResult(this.myFullDataPath, this.myFilePrefix + name + ".txt", actual);
String name = getTestName();
doCheckResult(myFullDataPath, myFilePrefix + name + ".txt", actual);
}
protected void checkResult(@NonNls String targetDataName, String actual) throws IOException {
doCheckResult(this.myFullDataPath, targetDataName, actual);
protected void checkResult(@TestDataFile @NonNls String targetDataName, String actual) throws IOException {
doCheckResult(myFullDataPath, targetDataName, actual);
}
public static void doCheckResult(String fullPath, String targetDataName, String actual) throws IOException {
@@ -312,20 +308,21 @@ public abstract class KtParsingTestCase extends KtPlatformLiteFixture {
KtUsefulTestCase.assertSameLinesWithFile(expectedFileName, actual);
}
protected static String toParseTreeText(PsiElement file, boolean skipSpaces, boolean printRanges) {
protected static String toParseTreeText(PsiElement file, boolean skipSpaces, boolean printRanges) {
return DebugUtil.psiToString(file, skipSpaces, printRanges);
}
protected String loadFile(@NonNls String name) throws IOException {
return loadFileDefault(this.myFullDataPath, name);
protected String loadFile(@NonNls @TestDataFile String name) throws IOException {
return loadFileDefault(myFullDataPath, name);
}
public static String loadFileDefault(String dir, String name) throws IOException {
return FileUtil.loadFile(new File(dir, name), "UTF-8", true).trim();
return FileUtil.loadFile(new File(dir, name), CharsetToolkit.UTF8, true).trim();
}
public static void ensureParsed(PsiFile file) {
file.accept(new PsiElementVisitor() {
@Override
public void visitElement(PsiElement element) {
element.acceptChildren(this);
}
@@ -337,6 +334,7 @@ public abstract class KtParsingTestCase extends KtPlatformLiteFixture {
String fileText = file.getText();
DiffLog diffLog = (new BlockSupportImpl(file.getProject())).reparseRange(file, TextRange.allOf(fileText), fileText, new EmptyProgressIndicator(), fileText);
diffLog.performActualPsiChange(file);
TestCase.assertEquals(psiToStringDefault, DebugUtil.psiToString(file, false, false));
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -19,7 +19,6 @@ package org.jetbrains.kotlin.test.testFramework;
import com.intellij.core.CoreEncodingProjectManager;
import com.intellij.mock.MockApplicationEx;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.ComponentManager;
import com.intellij.openapi.extensions.ExtensionPoint;
import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.openapi.extensions.Extensions;
@@ -28,76 +27,63 @@ import com.intellij.openapi.fileTypes.FileTypeManager;
import com.intellij.openapi.fileTypes.FileTypeRegistry;
import com.intellij.openapi.util.Getter;
import com.intellij.openapi.vfs.encoding.EncodingManager;
import org.jetbrains.annotations.NotNull;
import org.picocontainer.MutablePicoContainer;
@SuppressWarnings("ALL")
import java.lang.reflect.Modifier;
public abstract class KtPlatformLiteFixture extends KtUsefulTestCase {
protected MockProjectEx myProject;
public KtPlatformLiteFixture() {
}
@Override
protected void setUp() throws Exception {
super.setUp();
Extensions.cleanRootArea(this.getTestRootDisposable());
Extensions.cleanRootArea(getTestRootDisposable());
}
public static MockApplicationEx getApplication() {
return (MockApplicationEx) ApplicationManager.getApplication();
return (MockApplicationEx)ApplicationManager.getApplication();
}
public void initApplication() {
MockApplicationEx instance = new MockApplicationEx(this.getTestRootDisposable());
ApplicationManager.setApplication(instance, new Getter() {
public FileTypeRegistry get() {
return FileTypeManager.getInstance();
}
}, this.getTestRootDisposable());
MockApplicationEx instance = new MockApplicationEx(getTestRootDisposable());
ApplicationManager.setApplication(instance,
new Getter<FileTypeRegistry>() {
@Override
public FileTypeRegistry get() {
return FileTypeManager.getInstance();
}
},
getTestRootDisposable());
getApplication().registerService(EncodingManager.class, CoreEncodingProjectManager.class);
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
clearFields(this);
this.myProject = null;
}
protected <T> void registerExtension(ExtensionPointName<T> extensionPointName, @NotNull T t) {
this.registerExtension(Extensions.getRootArea(), extensionPointName, t);
}
public <T> void registerExtension(ExtensionsArea area, ExtensionPointName<T> name, T t) {
this.registerExtensionPoint(area, name, (Class<? extends T>) t.getClass());
KtPlatformTestUtil.registerExtension(area, name, t, this.myTestRootDisposable);
myProject = null;
}
protected <T> void registerExtensionPoint(ExtensionPointName<T> extensionPointName, Class<T> aClass) {
this.registerExtensionPoint(Extensions.getRootArea(), extensionPointName, aClass);
registerExtensionPoint(Extensions.getRootArea(), extensionPointName, aClass);
}
protected <T> void registerExtensionPoint(ExtensionsArea area, ExtensionPointName<T> extensionPointName, Class<? extends T> aClass) {
private static <T> void registerExtensionPoint(
ExtensionsArea area, ExtensionPointName<T> extensionPointName,
Class<? extends T> aClass
) {
String name = extensionPointName.getName();
if(!area.hasExtensionPoint(name)) {
ExtensionPoint.Kind kind = !aClass.isInterface() && (aClass.getModifiers() & 1024) == 0 ? ExtensionPoint.Kind.BEAN_CLASS : ExtensionPoint.Kind.INTERFACE;
if (!area.hasExtensionPoint(name)) {
ExtensionPoint.Kind kind = aClass.isInterface() || (aClass.getModifiers() & Modifier.ABSTRACT) != 0 ? ExtensionPoint.Kind.INTERFACE : ExtensionPoint.Kind.BEAN_CLASS;
area.registerExtensionPoint(name, aClass.getName(), kind);
}
}
protected void registerComponentImplementation(MutablePicoContainer container, Class<?> key, Class<?> implementation) {
container.unregisterComponent(key);
container.registerComponentImplementation(key, implementation);
}
public static <T> T registerComponentInstance(MutablePicoContainer container, Class<T> key, T implementation) {
Object old = container.getComponentInstance(key);
container.unregisterComponent(key);
container.registerComponentInstance(key, implementation);
return (T) old;
}
public static <T> T registerComponentInstance(ComponentManager container, Class<T> key, T implementation) {
return registerComponentInstance((MutablePicoContainer)container.getPicoContainer(), key, implementation);
//noinspection unchecked
return (T)old;
}
}
@@ -16,55 +16,14 @@
package org.jetbrains.kotlin.test.testFramework;
import com.intellij.execution.ExecutionException;
import com.intellij.execution.configurations.GeneralCommandLine;
import com.intellij.execution.process.ProcessOutput;
import com.intellij.execution.util.ExecUtil;
import com.intellij.ide.DataManager;
import com.intellij.ide.util.treeView.AbstractTreeNode;
import com.intellij.ide.util.treeView.AbstractTreeStructure;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.PathManager;
import com.intellij.openapi.extensions.ExtensionPoint;
import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.extensions.ExtensionsArea;
import com.intellij.openapi.ui.Queryable;
import com.intellij.openapi.util.*;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileFilter;
import com.intellij.util.Alarm;
import com.intellij.util.ArrayUtil;
import com.intellij.util.ReflectionUtil;
import com.intellij.util.ThrowableRunnable;
import com.intellij.util.ui.UIUtil;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jetbrains.annotations.*;
import org.junit.Assert;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;
import java.awt.*;
import java.io.*;
import java.nio.charset.Charset;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
@SuppressWarnings("ALL")
// Based on com.intellij.testFramework.PlatformTestUtil
public class KtPlatformTestUtil {
public static final boolean COVERAGE_ENABLED_BUILD = "true".equals(System.getProperty("idea.coverage.enabled.build"));
private static final boolean SKIP_HEADLESS = GraphicsEnvironment.isHeadless();
private static final boolean SKIP_SLOW = Boolean.getBoolean("skip.slow.tests.locally");
@NotNull
public static String getTestName(@NotNull String name, boolean lowercaseFirstLetter) {
name = StringUtil.trimStart(name, "test");
@@ -92,30 +51,15 @@ public class KtPlatformTestUtil {
return uppercaseChars >= 3;
}
public static <T> void registerExtension(@NotNull ExtensionPointName<T> name, @NotNull T t, @NotNull Disposable parentDisposable) {
registerExtension(Extensions.getRootArea(), name, t, parentDisposable);
}
public static <T> void registerExtension(@NotNull ExtensionsArea area, @NotNull ExtensionPointName<T> name, @NotNull final T t, @NotNull Disposable parentDisposable) {
final ExtensionPoint<T> extensionPoint = area.getExtensionPoint(name.getName());
extensionPoint.registerExtension(t);
Disposer.register(parentDisposable, new Disposable() {
@Override
public void dispose() {
extensionPoint.unregisterExtension(t);
}
});
}
@Nullable
protected static String toString(@Nullable Object node, @Nullable Queryable.PrintInfo printInfo) {
if (node instanceof AbstractTreeNode) {
if (printInfo != null) {
return ((AbstractTreeNode)node).toTestString(printInfo);
return ((AbstractTreeNode) node).toTestString(printInfo);
}
else {
@SuppressWarnings({"deprecation", "UnnecessaryLocalVariable"})
final String presentation = ((AbstractTreeNode)node).getTestPresentation();
@SuppressWarnings({"deprecation", "UnnecessaryLocalVariable"}) String presentation =
((AbstractTreeNode) node).getTestPresentation();
return presentation;
}
}
@@ -124,782 +68,4 @@ public class KtPlatformTestUtil {
}
return node.toString();
}
public static String print(JTree tree, boolean withSelection) {
return print(tree, tree.getModel().getRoot(), withSelection, null, null);
}
public static String print(JTree tree, Object root, @Nullable Queryable.PrintInfo printInfo, boolean withSelection) {
return print(tree, root, withSelection, printInfo, null);
}
public static String print(JTree tree, boolean withSelection, @Nullable Condition<String> 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<String> nodePrintCondition) {
StringBuilder buffer = new StringBuilder();
final Collection<String> strings = printAsList(tree, root, withSelection, printInfo, nodePrintCondition);
for (String string : strings) {
buffer.append(string).append("\n");
}
return buffer.toString();
}
public static Collection<String> printAsList(JTree tree, boolean withSelection, @Nullable Condition<String> nodePrintCondition) {
return printAsList(tree, tree.getModel().getRoot(), withSelection, null, nodePrintCondition);
}
private static Collection<String> printAsList(JTree tree, Object root,
boolean withSelection,
@Nullable Queryable.PrintInfo printInfo,
Condition<String> nodePrintCondition) {
Collection<String> strings = new ArrayList<String>();
printImpl(tree, root, strings, 0, withSelection, printInfo, nodePrintCondition);
return strings;
}
private static void printImpl(JTree tree,
Object root,
Collection<String> strings,
int level,
boolean withSelection,
@Nullable Queryable.PrintInfo printInfo,
@Nullable Condition<String> 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<String> actualNodesPresentation = printAsList(tree, checkSelected, null);
final java.util.List<String> 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<Object>(Arrays.asList(children));
@SuppressWarnings({"UnnecessaryLocalVariable", "unchecked"}) Comparator<Object> 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<String, VirtualFile> buildNameToFileMap(VirtualFile[] files, @Nullable VirtualFileFilter filter) {
com.intellij.util.containers.HashMap<String, VirtualFile> map = new com.intellij.util.containers.HashMap<String, VirtualFile>();
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<String, VirtualFile> mapAfter = buildNameToFileMap(childrenAfter, fileFilter);
// com.intellij.util.containers.HashMap<String, VirtualFile> mapBefore = buildNameToFileMap(childrenBefore, fileFilter);
//
// Set<String> keySetAfter = mapAfter.keySet();
// Set<String> 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<String> vfsPaths = new ArrayList<String>();
for (VirtualFile file : vfs) {
vfsPaths.add(file.getPath());
}
java.util.List<String> ioPaths = new ArrayList<String>();
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<String> 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<AbstractTreeNode> createComparator(final Queryable.PrintInfo printInfo) {
return new Comparator<AbstractTreeNode>() {
@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> 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);
}
}
}
File diff suppressed because it is too large Load Diff
@@ -20,17 +20,8 @@ import com.intellij.mock.MockProject
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.project.Project
import com.intellij.util.messages.Topic
interface ProjectEx : Project {
interface ProjectSaved {
fun saved(project: Project)
companion object {
val TOPIC = Topic.create("SaveProjectTopic", ProjectSaved::class.java, Topic.BroadcastDirection.NONE)
}
}
fun init()
fun setProjectName(name: String)
@@ -27,8 +27,8 @@ public class TestRunnerUtil {
}
@TestOnly
public static boolean isJUnit4TestClass(final Class aClass) {
final int modifiers = aClass.getModifiers();
public static boolean isJUnit4TestClass(Class aClass) {
int modifiers = aClass.getModifiers();
if ((modifiers & Modifier.ABSTRACT) != 0) return false;
if ((modifiers & Modifier.PUBLIC) == 0) return false;
if (aClass.getAnnotation(RunWith.class) != null) return true;
@@ -37,30 +37,4 @@ public class TestRunnerUtil {
}
return false;
}
//public static void replaceIdeEventQueueSafely() {
// if (Toolkit.getDefaultToolkit().getSystemEventQueue() instanceof IdeEventQueue) {
// return;
// }
// if (SwingUtilities.isEventDispatchThread()) {
// throw new RuntimeException("must not call under EDT");
// }
// AWTAutoShutdown.getInstance().notifyThreadBusy(Thread.currentThread());
// UIUtil.pump();
// // in JDK 1.6 java.awt.EventQueue.push() causes slow painful death of current EDT
// // so we have to wait through its agony to termination
// try {
// SwingUtilities.invokeAndWait(new Runnable() {
// @Override
// public void run() {
// IdeEventQueue.getInstance();
// }
// });
// SwingUtilities.invokeAndWait(EmptyRunnable.getInstance());
// SwingUtilities.invokeAndWait(EmptyRunnable.getInstance());
// }
// catch (Exception e) {
// throw new RuntimeException(e);
// }
//}
}
@@ -17,45 +17,34 @@
package org.jetbrains.kotlin.test.testFramework;
import com.intellij.openapi.application.AccessToken;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.WriteAction;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.PathUtil;
import com.intellij.util.text.StringTokenizer;
import org.jetbrains.annotations.NotNull;
import org.junit.Assert;
import java.io.File;
import java.io.IOException;
public class VfsTestUtil {
public static final Key<String> TEST_DATA_FILE_PATH = Key.create("TEST_DATA_FILE_PATH");
private VfsTestUtil() {
}
public static VirtualFile createFile(final VirtualFile root, final String relativePath) {
public static VirtualFile createFile(VirtualFile root, String relativePath) {
return createFile(root, relativePath, "");
}
public static VirtualFile createFile(final VirtualFile root, final String relativePath, final String text) {
public static VirtualFile createFile(VirtualFile root, String relativePath, String text) {
return createFileOrDir(root, relativePath, text, false);
}
public static VirtualFile createDir(final VirtualFile root, final String relativePath) {
return createFileOrDir(root, relativePath, "", true);
}
private static VirtualFile createFileOrDir(final VirtualFile root,
final String relativePath,
final String text,
final boolean dir) {
private static VirtualFile createFileOrDir(
VirtualFile root,
String relativePath,
String text,
boolean dir) {
try {
AccessToken token = WriteAction.start();
try {
@@ -63,7 +52,7 @@ public class VfsTestUtil {
Assert.assertNotNull(parent);
StringTokenizer parents = new StringTokenizer(PathUtil.getParentPath(relativePath), "/");
while (parents.hasMoreTokens()) {
final String name = parents.nextToken();
String name = parents.nextToken();
VirtualFile child = parent.findChild(name);
if (child == null || !child.isValid()) {
child = parent.createChildDirectory(VfsTestUtil.class, name);
@@ -94,24 +83,6 @@ public class VfsTestUtil {
}
}
public static void deleteFile(@NotNull VirtualFile file) {
UtilKt.deleteFile(file);
}
public static void clearContent(@NotNull final VirtualFile file) {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
try {
VfsUtil.saveText(file, "");
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
});
}
@SuppressWarnings("UnusedDeclaration")
public static void overwriteTestData(String filePath, String actual) {
try {
@@ -121,31 +92,4 @@ public class VfsTestUtil {
throw new AssertionError(e);
}
}
@NotNull
public static VirtualFile findFileByCaseSensitivePath(@NotNull String absolutePath) {
String vfsPath = FileUtil.toSystemIndependentName(absolutePath);
VirtualFile vFile = LocalFileSystem.getInstance().findFileByPath(vfsPath);
Assert.assertNotNull("file " + absolutePath + " not found", vFile);
String realVfsPath = vFile.getPath();
if (!SystemInfo.isFileSystemCaseSensitive && !vfsPath.equals(realVfsPath) &&
vfsPath.equalsIgnoreCase(realVfsPath)) {
Assert.fail("Please correct case-sensitivity of path to prevent test failure on case-sensitive file systems:\n" +
" path " + vfsPath + "\n" +
"real path " + realVfsPath);
}
return vFile;
}
public static void assertFilePathEndsWithCaseSensitivePath(@NotNull VirtualFile file, @NotNull String suffixPath) {
String vfsSuffixPath = FileUtil.toSystemIndependentName(suffixPath);
String vfsPath = file.getPath();
if (!SystemInfo.isFileSystemCaseSensitive && !vfsPath.endsWith(vfsSuffixPath) &&
StringUtil.endsWithIgnoreCase(vfsPath, vfsSuffixPath)) {
String realSuffixPath = vfsPath.substring(vfsPath.length() - vfsSuffixPath.length());
Assert.fail("Please correct case-sensitivity of path to prevent test failure on case-sensitive file systems:\n" +
" path " + suffixPath + "\n" +
"real path " + realSuffixPath);
}
}
}
@@ -16,9 +16,7 @@
package org.jetbrains.kotlin.test.testFramework.mock;
import com.intellij.mock.*;
import com.intellij.openapi.fileTypes.*;
import com.intellij.openapi.fileTypes.MockLanguageFileType;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.ArrayUtil;
@@ -26,7 +24,6 @@ import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.test.testFramework.mock.KtMockLanguageFileType;
import java.util.Collections;
import java.util.List;
@@ -49,14 +46,6 @@ public class KtMockFileTypeManager extends FileTypeManager {
public void setIgnoredFilesList(@NotNull String list) {
}
public void save() {
}
@NotNull
public String getExtension(@NotNull String fileName) {
return "";
}
@Override
public void registerFileType(@NotNull FileType type, @NotNull List<FileNameMatcher> defaultAssociations) {
}
@@ -135,7 +124,7 @@ public class KtMockFileTypeManager extends FileTypeManager {
@Override
@NotNull
public FileType getStdFileType(@NotNull @NonNls final String fileTypeName) {
public FileType getStdFileType(@NotNull @NonNls String fileTypeName) {
if ("ARCHIVE".equals(fileTypeName) || "CLASS".equals(fileTypeName)) return UnknownFileType.INSTANCE;
if ("PLAIN_TEXT".equals(fileTypeName)) return PlainTextFileType.INSTANCE;
if ("JAVA".equals(fileTypeName)) return loadFileTypeSafe("com.intellij.ide.highlighter.JavaFileType", fileTypeName);
@@ -150,7 +139,7 @@ public class KtMockFileTypeManager extends FileTypeManager {
return new KtMockLanguageFileType(PlainTextLanguage.INSTANCE, fileTypeName.toLowerCase());
}
private static FileType loadFileTypeSafe(final String className, String fileTypeName) {
private static FileType loadFileTypeSafe(String className, String fileTypeName) {
try {
return (FileType)Class.forName(className).getField("INSTANCE").get(null);
}
@@ -18,7 +18,7 @@ package org.jetbrains.kotlin.test.testFramework.mock;
import com.intellij.lang.Language;
import com.intellij.openapi.fileTypes.LanguageFileType;
import com.sun.istack.internal.NotNull;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
@@ -30,16 +30,19 @@ public class KtMockLanguageFileType extends LanguageFileType {
this.myExtension = extension;
}
@Override
@NotNull
public String getName() {
return this.getLanguage().getID();
}
@Override
@NotNull
public String getDescription() {
return "";
}
@Override
@NotNull
public String getDefaultExtension() {
String var10000 = this.myExtension;
@@ -50,11 +53,12 @@ public class KtMockLanguageFileType extends LanguageFileType {
}
}
@Override
public Icon getIcon() {
return null;
}
public boolean equals(Object obj) {
return !(obj instanceof LanguageFileType)?false:this.getLanguage().equals(((LanguageFileType)obj).getLanguage());
return obj instanceof LanguageFileType && this.getLanguage().equals(((LanguageFileType) obj).getLanguage());
}
}
@@ -40,7 +40,7 @@ public class MockEditorEventMulticaster implements EditorEventMulticaster {
}
@Override
public void addEditorMouseListener(@NotNull final EditorMouseListener listener, @NotNull final Disposable parentDisposable) {
public void addEditorMouseListener(@NotNull EditorMouseListener listener, @NotNull Disposable parentDisposable) {
}
@Override
@@ -29,10 +29,6 @@ import com.intellij.util.text.CharArrayCharSequence;
import org.jetbrains.annotations.NotNull;
public class MockEditorFactory extends EditorFactory {
public Document createDocument(String text) {
return new DocumentImpl(text);
}
@Override
public Editor createEditor(@NotNull Document document) {
return null;
@@ -54,7 +50,7 @@ public class MockEditorFactory extends EditorFactory {
}
@Override
public Editor createEditor(@NotNull final Document document, final Project project, @NotNull final FileType fileType, final boolean isViewer) {
public Editor createEditor(@NotNull Document document, Project project, @NotNull FileType fileType, boolean isViewer) {
return null;
}
@@ -57,7 +57,7 @@ public class MockPsiDocumentManager extends PsiDocumentManager {
}
@Override
public void performForCommittedDocument(@NotNull final Document document, @NotNull final Runnable action) {
public void performForCommittedDocument(@NotNull Document document, @NotNull Runnable action) {
action.run();
}
@@ -43,6 +43,7 @@ public class MockPsiManager extends PsiManagerEx {
myProject = project;
}
@SuppressWarnings("unused")
public void addPsiDirectory(VirtualFile file, PsiDirectory psiDirectory) {
myDirectories.put(file, psiDirectory);
}
@@ -175,11 +176,11 @@ public class MockPsiManager extends PsiManagerEx {
}
@Override
public void beforeChildRemoval(@NotNull final PsiTreeChangeEventImpl event) {
public void beforeChildRemoval(@NotNull PsiTreeChangeEventImpl event) {
}
@Override
public void beforeChildReplacement(@NotNull final PsiTreeChangeEventImpl event) {
public void beforeChildReplacement(@NotNull PsiTreeChangeEventImpl event) {
}
@Override
@@ -28,6 +28,7 @@ public class MockSchemesManagerFactory extends SchemesManagerFactory {
@NotNull SchemeProcessor<E> processor,
@NotNull RoamingType roamingType,
@Nullable String presentableName) {
//noinspection unchecked
return EMPTY;
}
}
@@ -1,53 +0,0 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.test.testFramework.mock;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiManager;
import com.intellij.psi.impl.PsiTreeChangeEventImpl;
import com.intellij.psi.impl.file.impl.FileManager;
import org.jetbrains.annotations.NotNull;
public abstract class PsiManagerEx extends PsiManager {
public abstract boolean isBatchFilesProcessingMode();
public abstract boolean isAssertOnFileLoading(@NotNull VirtualFile file);
/**
* @param runnable to be run before <b>physical</b> PSI change
*/
public abstract void registerRunnableToRunOnChange(@NotNull Runnable runnable);
/**
* @param runnable to be run before <b>physical</b> or <b>non-physical</b> 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);
}
@@ -21,17 +21,6 @@ import com.intellij.openapi.components.ComponentManager
import com.intellij.openapi.vfs.VirtualFile
import org.picocontainer.MutablePicoContainer
fun <T> ComponentManager.registerServiceInstance(interfaceClass: Class<T>, 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 <T> runWriteAction(action: () -> T): T {
return ApplicationManager.getApplication().runWriteAction<T>(action)
}