2 * Copyright 2000-2011 JetBrains s.r.o.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 package com.intellij.testFramework.fixtures.impl;
19 import com.intellij.analysis.AnalysisScope;
20 import com.intellij.codeHighlighting.HighlightDisplayLevel;
21 import com.intellij.codeInsight.TargetElementUtilBase;
22 import com.intellij.codeInsight.completion.CodeCompletionHandlerBase;
23 import com.intellij.codeInsight.completion.CompletionProgressIndicator;
24 import com.intellij.codeInsight.completion.CompletionType;
25 import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer;
26 import com.intellij.codeInsight.daemon.DaemonCodeAnalyzerSettings;
27 import com.intellij.codeInsight.daemon.HighlightDisplayKey;
28 import com.intellij.codeInsight.daemon.impl.DaemonCodeAnalyzerImpl;
29 import com.intellij.codeInsight.daemon.impl.HighlightInfo;
30 import com.intellij.codeInsight.daemon.impl.HighlightInfoType;
31 import com.intellij.codeInsight.daemon.impl.ShowIntentionsPass;
32 import com.intellij.codeInsight.folding.CodeFoldingManager;
33 import com.intellij.codeInsight.highlighting.actions.HighlightUsagesAction;
34 import com.intellij.codeInsight.intention.IntentionAction;
35 import com.intellij.codeInsight.intention.impl.ShowIntentionActionsHandler;
36 import com.intellij.codeInsight.lookup.LookupElement;
37 import com.intellij.codeInsight.lookup.LookupManager;
38 import com.intellij.codeInsight.lookup.impl.LookupImpl;
39 import com.intellij.codeInspection.*;
40 import com.intellij.codeInspection.ex.*;
41 import com.intellij.facet.Facet;
42 import com.intellij.facet.FacetManager;
43 import com.intellij.find.FindManager;
44 import com.intellij.find.findUsages.FindUsagesHandler;
45 import com.intellij.find.findUsages.FindUsagesOptions;
46 import com.intellij.find.impl.FindManagerImpl;
47 import com.intellij.ide.DataManager;
48 import com.intellij.ide.startup.StartupManagerEx;
49 import com.intellij.ide.startup.impl.StartupManagerImpl;
50 import com.intellij.ide.structureView.StructureViewBuilder;
51 import com.intellij.ide.structureView.newStructureView.StructureViewComponent;
52 import com.intellij.lang.LanguageStructureViewBuilder;
53 import com.intellij.openapi.Disposable;
54 import com.intellij.openapi.actionSystem.*;
55 import com.intellij.openapi.actionSystem.ex.ActionManagerEx;
56 import com.intellij.openapi.application.ApplicationManager;
57 import com.intellij.openapi.application.Result;
58 import com.intellij.openapi.command.CommandProcessor;
59 import com.intellij.openapi.command.WriteCommandAction;
60 import com.intellij.openapi.editor.*;
61 import com.intellij.openapi.editor.actionSystem.DocCommandGroupId;
62 import com.intellij.openapi.editor.actionSystem.EditorActionManager;
63 import com.intellij.openapi.editor.ex.EditorEx;
64 import com.intellij.openapi.editor.ex.util.EditorUtil;
65 import com.intellij.openapi.editor.impl.DocumentImpl;
66 import com.intellij.openapi.editor.impl.DocumentMarkupModel;
67 import com.intellij.openapi.editor.markup.GutterIconRenderer;
68 import com.intellij.openapi.editor.markup.RangeHighlighter;
69 import com.intellij.openapi.extensions.ExtensionPoint;
70 import com.intellij.openapi.extensions.ExtensionPointName;
71 import com.intellij.openapi.extensions.Extensions;
72 import com.intellij.openapi.extensions.ExtensionsArea;
73 import com.intellij.openapi.fileEditor.*;
74 import com.intellij.openapi.fileEditor.impl.text.TextEditorProvider;
75 import com.intellij.openapi.fileTypes.FileType;
76 import com.intellij.openapi.fileTypes.FileTypeManager;
77 import com.intellij.openapi.fileTypes.StdFileTypes;
78 import com.intellij.openapi.module.Module;
79 import com.intellij.openapi.project.DumbService;
80 import com.intellij.openapi.project.Project;
81 import com.intellij.openapi.util.*;
82 import com.intellij.openapi.util.io.FileUtil;
83 import com.intellij.openapi.util.text.StringUtil;
84 import com.intellij.openapi.vfs.LocalFileSystem;
85 import com.intellij.openapi.vfs.VfsUtil;
86 import com.intellij.openapi.vfs.VirtualFile;
87 import com.intellij.openapi.vfs.VirtualFileFilter;
88 import com.intellij.profile.codeInspection.InspectionProfileManager;
89 import com.intellij.profile.codeInspection.InspectionProjectProfileManager;
90 import com.intellij.psi.*;
91 import com.intellij.psi.codeStyle.CodeStyleSettingsManager;
92 import com.intellij.psi.impl.PsiManagerImpl;
93 import com.intellij.psi.impl.PsiModificationTrackerImpl;
94 import com.intellij.psi.impl.cache.CacheManager;
95 import com.intellij.psi.impl.cache.impl.todo.TodoIndex;
96 import com.intellij.psi.impl.source.PostprocessReformattingAspect;
97 import com.intellij.psi.impl.source.PsiFileImpl;
98 import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil;
99 import com.intellij.psi.search.GlobalSearchScope;
100 import com.intellij.psi.search.UsageSearchContext;
101 import com.intellij.psi.statistics.StatisticsManager;
102 import com.intellij.psi.statistics.impl.StatisticsManagerImpl;
103 import com.intellij.psi.stubs.StubUpdatingIndex;
104 import com.intellij.psi.util.PsiTreeUtil;
105 import com.intellij.refactoring.move.moveFilesOrDirectories.MoveFilesOrDirectoriesProcessor;
106 import com.intellij.refactoring.rename.RenameProcessor;
107 import com.intellij.refactoring.rename.RenamePsiElementProcessor;
108 import com.intellij.testFramework.*;
109 import com.intellij.testFramework.fixtures.*;
110 import com.intellij.usageView.UsageInfo;
111 import com.intellij.util.*;
112 import com.intellij.util.containers.ContainerUtil;
113 import com.intellij.util.indexing.FileBasedIndex;
114 import com.intellij.util.ui.UIUtil;
115 import gnu.trove.THashMap;
116 import junit.framework.Assert;
117 import org.jetbrains.annotations.NonNls;
118 import org.jetbrains.annotations.NotNull;
119 import org.jetbrains.annotations.Nullable;
121 import javax.swing.*;
123 import java.io.IOException;
127 * @author Dmitry Avdeev
129 @SuppressWarnings({"TestMethodWithIncorrectSignature", "JUnitTestCaseWithNoTests", "JUnitTestClassNamingConvention"})
130 public class CodeInsightTestFixtureImpl extends BaseFixture implements CodeInsightTestFixture {
132 @NonNls private static final String PROFILE = "Configurable";
134 private static final Function<IntentionAction,String> INTENTION_NAME_FUN = new Function<IntentionAction, String>() {
136 public String fun(final IntentionAction intentionAction) {
137 return "\"" + intentionAction.getText() + "\"";
141 private PsiManagerImpl myPsiManager;
142 private PsiFile myFile;
143 private Editor myEditor;
144 private String myTestDataPath;
145 private boolean myEmptyLookup;
147 private InspectionProfileEntry[] myInspections;
148 private final Map<String, InspectionProfileEntry> myAvailableTools = new THashMap<String, InspectionProfileEntry>();
149 private final Map<String, InspectionTool> myAvailableLocalTools = new THashMap<String, InspectionTool>();
151 private final TempDirTestFixture myTempDirFixture;
152 protected final IdeaProjectTestFixture myProjectFixture;
153 @NonNls private static final String XXX = "XXX";
154 private final FileTreeAccessFilter myJavaFilesFilter = new FileTreeAccessFilter();
155 private boolean myAllowDirt;
156 private final Map<String, LocalInspectionEP> myExtensions = new HashMap<String, LocalInspectionEP>();
158 public CodeInsightTestFixtureImpl(IdeaProjectTestFixture projectFixture, TempDirTestFixture tempDirTestFixture) {
159 myProjectFixture = projectFixture;
160 myTempDirFixture = tempDirTestFixture;
164 public void setTestDataPath(String dataPath) {
165 myTestDataPath = dataPath;
169 public String getTempDirPath() {
170 return myTempDirFixture.getTempDirPath();
174 public TempDirTestFixture getTempDirFixture() {
175 return myTempDirFixture;
179 public VirtualFile copyFileToProject(@NonNls final String sourceFilePath, @NonNls final String targetPath) {
180 File fromFile = new File(getTestDataPath() + "/" + sourceFilePath);
181 if (!fromFile.exists()) {
182 fromFile = new File(sourceFilePath);
185 if (myTempDirFixture instanceof LightTempDirTestFixtureImpl) {
186 VirtualFile fromVFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(fromFile);
187 if (fromVFile == null) {
188 fromVFile = myTempDirFixture.getFile(sourceFilePath);
190 assert fromVFile != null : "can't find test data file " + sourceFilePath + " (" + getTestDataPath() + ")";
191 return myTempDirFixture.copyFile(fromVFile, targetPath);
194 final File destFile = new File(getTempDirPath() + "/" + targetPath);
195 if (!destFile.exists()) {
196 if (fromFile.isDirectory()) {
197 assert destFile.mkdirs() : destFile;
200 if (!fromFile.exists()) {
201 fail("Cannot find source file: '"+sourceFilePath+"'. getTestDataPath()='"+getTestDataPath()+"'. getHomePath()='"+getHomePath()+"'.");
204 FileUtil.copy(fromFile, destFile);
206 catch (IOException e) {
207 throw new RuntimeException("Cannot copy " + fromFile + " to " + destFile, e);
212 final VirtualFile file = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(destFile);
213 assert file != null : destFile;
218 public VirtualFile copyDirectoryToProject(@NonNls final String sourceFilePath, @NonNls final String targetPath) {
219 assert getTestDataPath() != null : "test data path not specified";
220 final File fromFile = new File(getTestDataPath() + "/" + sourceFilePath);
221 if (myTempDirFixture instanceof LightTempDirTestFixtureImpl) {
222 return myTempDirFixture.copyAll(fromFile.getPath(), targetPath);
225 final File destFile = new File(getTempDirPath() + "/" + targetPath);
227 FileUtil.copyDir(fromFile, destFile);
229 catch (IOException e) {
230 throw new RuntimeException(e);
232 final VirtualFile file = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(destFile);
233 Assert.assertNotNull(file);
234 file.refresh(false, true);
240 public VirtualFile copyFileToProject(@NonNls final String sourceFilePath) {
241 return copyFileToProject(sourceFilePath, sourceFilePath);
245 public void enableInspections(InspectionProfileEntry... inspections) {
246 myInspections = inspections;
247 if (isInitialized()) {
248 configureInspections(myInspections);
252 private boolean isInitialized() {
253 return myPsiManager != null;
257 public void enableInspections(final Class<? extends LocalInspectionTool>... inspections) {
258 final ArrayList<LocalInspectionTool> tools = new ArrayList<LocalInspectionTool>();
259 for (Class clazz : inspections) {
261 LocalInspectionTool inspection = (LocalInspectionTool)clazz.getConstructor().newInstance();
262 tools.add(inspection);
264 catch (Exception e) {
265 throw new RuntimeException("Cannot instantiate " + clazz);
268 enableInspections(tools.toArray(new LocalInspectionTool[tools.size()]));
272 public void disableInspections(InspectionProfileEntry... inspections) {
273 myAvailableTools.clear();
274 myAvailableLocalTools.clear();
275 final ArrayList<InspectionProfileEntry> tools = new ArrayList<InspectionProfileEntry>(Arrays.asList(myInspections));
276 for (Iterator<InspectionProfileEntry> i = tools.iterator(); i.hasNext();) {
277 final InspectionProfileEntry tool = i.next();
278 for (InspectionProfileEntry toRemove : inspections) {
279 if (tool.getShortName().equals(toRemove.getShortName())) {
285 myInspections = tools.toArray(new InspectionProfileEntry[tools.size()]);
286 configureInspections(myInspections);
290 public void enableInspections(InspectionToolProvider... providers) {
291 final ArrayList<LocalInspectionTool> tools = new ArrayList<LocalInspectionTool>();
292 for (InspectionToolProvider provider : providers) {
293 for (Class clazz : provider.getInspectionClasses()) {
295 Object o = clazz.getConstructor().newInstance();
296 if (o instanceof LocalInspectionTool) {
297 LocalInspectionTool inspection = (LocalInspectionTool)o;
298 tools.add(inspection);
301 catch (Exception e) {
302 throw new RuntimeException("Cannot instantiate " + clazz, e);
306 myInspections = tools.toArray(new LocalInspectionTool[tools.size()]);
307 configureInspections(myInspections);
311 public long testHighlighting(final boolean checkWarnings,
312 final boolean checkInfos,
313 final boolean checkWeakWarnings,
314 final String... filePaths) {
315 final Ref<Long> duration = new Ref<Long>();
316 if (filePaths.length > 0) {
317 configureByFilesInner(filePaths);
320 collectAndCheckHighlightings(checkWarnings, checkInfos, checkWeakWarnings, duration);
322 catch (Exception e) {
323 throw new RuntimeException(e);
325 return duration.get().longValue();
329 public long testHighlightingAllFiles(final boolean checkWarnings,
330 final boolean checkInfos,
331 final boolean checkWeakWarnings,
332 @NonNls final String... filePaths) {
333 final ArrayList<VirtualFile> files = new ArrayList<VirtualFile>();
334 for (String path : filePaths) {
335 files.add(copyFileToProject(path));
337 return testHighlightingAllFiles(checkWarnings, checkInfos, checkWeakWarnings, VfsUtil.toVirtualFileArray(files));
341 public long testHighlightingAllFiles(final boolean checkWarnings,
342 final boolean checkInfos,
343 final boolean checkWeakWarnings,
344 @NonNls final VirtualFile... files) {
345 final Ref<Long> duration = new Ref<Long>();
346 collectAndCheckHighlightings(checkWarnings, checkInfos, checkWeakWarnings, duration, files);
347 return duration.get().longValue();
350 private void collectAndCheckHighlightings(final boolean checkWarnings,
351 final boolean checkInfos,
352 final boolean checkWeakWarnings,
353 final Ref<Long> duration,
354 final VirtualFile[] files) {
355 final List<Trinity<PsiFile, Editor, ExpectedHighlightingData>> datas =
356 ContainerUtil.map2List(files, new Function<VirtualFile, Trinity<PsiFile, Editor, ExpectedHighlightingData>>() {
358 public Trinity<PsiFile, Editor, ExpectedHighlightingData> fun(final VirtualFile file) {
359 final PsiFile psiFile = myPsiManager.findFile(file);
360 assertNotNull(psiFile);
361 final Document document = PsiDocumentManager.getInstance(getProject()).getDocument(psiFile);
362 assertNotNull(document);
363 ExpectedHighlightingData data = new ExpectedHighlightingData(document, checkWarnings, checkWeakWarnings, checkInfos, psiFile);
365 return Trinity.create(psiFile, createEditor(file), data);
368 for (Trinity<PsiFile, Editor, ExpectedHighlightingData> trinity : datas) {
369 myEditor = trinity.second;
370 myFile = trinity.first;
371 collectAndCheckHighlightings(trinity.third, duration);
376 public long checkHighlighting(final boolean checkWarnings, final boolean checkInfos, final boolean checkWeakWarnings) {
377 final Ref<Long> duration = new Ref<Long>();
379 collectAndCheckHighlightings(checkWarnings, checkInfos, checkWeakWarnings, duration);
381 catch (Exception e) {
382 throw new RuntimeException(e);
384 return duration.get().longValue();
388 public long checkHighlighting() {
389 return checkHighlighting(true, true, true);
393 public long testHighlighting(final String... filePaths) {
394 return testHighlighting(true, true, true, filePaths);
398 public long testHighlighting(final boolean checkWarnings,
399 final boolean checkInfos,
400 final boolean checkWeakWarnings,
401 final VirtualFile file) {
402 final Ref<Long> duration = new Ref<Long>();
403 openFileInEditor(file);
405 collectAndCheckHighlightings(checkWarnings, checkInfos, checkWeakWarnings, duration);
407 catch (Exception e) {
408 throw new RuntimeException(e);
410 return duration.get().longValue();
414 public HighlightTestInfo testFile(@NonNls @NotNull String... filePath) {
415 return new HighlightTestInfo(getTestRootDisposable(), filePath){
417 public HighlightTestInfo doTest() throws Exception {
418 configureByFiles(filePaths);
419 ExpectedHighlightingData data = new ExpectedHighlightingData(myEditor.getDocument(), checkWarnings, checkWeakWarnings, checkInfos, myFile);
420 if (checkSymbolNames) data.checkSymbolNames();
422 collectAndCheckHighlightings(data, Ref.create(0L));
428 public void openFileInEditor(@NotNull final VirtualFile file) {
429 myFile = myPsiManager.findFile(file);
430 myEditor = createEditor(file);
434 public void testInspection(String testDir, InspectionTool tool) {
435 VirtualFile sourceDir = copyDirectoryToProject(new File(testDir, "src").getPath(), "src");
436 AnalysisScope scope = new AnalysisScope(getPsiManager().findDirectory(sourceDir));
440 InspectionManagerEx inspectionManager = (InspectionManagerEx)InspectionManager.getInstance(getProject());
441 GlobalInspectionContextImpl globalContext = createGlobalContextForTool(scope, getProject(), inspectionManager, tool);
443 InspectionTestUtil.runTool(tool, scope, globalContext, inspectionManager);
444 InspectionTestUtil.compareToolResults(tool, false, new File(getTestDataPath(), testDir).getPath());
447 public static GlobalInspectionContextImpl createGlobalContextForTool(AnalysisScope scope,
448 final Project project,
449 final InspectionManagerEx inspectionManager,
450 final InspectionTool... tools) {
451 final GlobalInspectionContextImpl globalContext = new GlobalInspectionContextImpl(project, inspectionManager.getContentManager()){
453 protected List<ToolsImpl> getUsedTools() {
454 List<ToolsImpl> result = new ArrayList<ToolsImpl>();
455 for (InspectionTool tool : tools) {
456 result.add(new ToolsImpl(tool, tool.getDefaultLevel(), true));
462 public boolean isToCheckMember(PsiElement element, InspectionProfileEntry tool) {
466 globalContext.setCurrentScope(scope);
467 return globalContext;
472 public PsiReference getReferenceAtCaretPosition(final String... filePaths) {
473 if (filePaths.length > 0) {
474 configureByFilesInner(filePaths);
476 return getFile().findReferenceAt(myEditor.getCaretModel().getOffset());
481 public PsiReference getReferenceAtCaretPositionWithAssertion(final String... filePaths) {
482 final PsiReference reference = getReferenceAtCaretPosition(filePaths);
483 assert reference != null : "no reference found at " + myEditor.getCaretModel().getLogicalPosition();
489 public List<IntentionAction> getAvailableIntentions(final String... filePaths) {
490 if (filePaths.length > 0) {
491 configureByFilesInner(filePaths);
493 return getAvailableIntentions();
498 public List<IntentionAction> getAllQuickFixes(@NonNls final String... filePaths) {
499 configureByFilesInner(filePaths);
500 List<HighlightInfo> infos = doHighlighting();
501 ArrayList<IntentionAction> actions = new ArrayList<IntentionAction>();
502 for (HighlightInfo info : infos) {
503 for (Pair<HighlightInfo.IntentionActionDescriptor, TextRange> pair : info.quickFixActionRanges) {
504 actions.add(pair.getFirst().getAction());
512 public List<IntentionAction> getAvailableIntentions() {
514 return getAvailableIntentions(myEditor, myFile);
518 public List<IntentionAction> filterAvailableIntentions(@NotNull final String hint) {
519 final List<IntentionAction> availableIntentions = getAvailableIntentions();
520 return ContainerUtil.findAll(availableIntentions, new Condition<IntentionAction>() {
522 public boolean value(final IntentionAction intentionAction) {
523 return intentionAction.getText().startsWith(hint);
529 public IntentionAction findSingleIntention(@NotNull final String hint) {
530 final List<IntentionAction> list = filterAvailableIntentions(hint);
531 if (list.isEmpty()) {
532 Assert.fail("\"" + hint + "\" not in [" + StringUtil.join(getAvailableIntentions(), INTENTION_NAME_FUN, ", ") + "]");
534 else if (list.size() > 1) {
535 Assert.fail("Too many intention found for \"" + hint + "\": [" + StringUtil.join(list, INTENTION_NAME_FUN, ", ") + "]");
537 return UsefulTestCase.assertOneElement(list);
541 public IntentionAction getAvailableIntention(final String intentionName, final String... filePaths) {
542 List<IntentionAction> intentions = getAvailableIntentions(filePaths);
543 return CodeInsightTestUtil.findIntentionByText(intentions, intentionName);
547 public void launchAction(@NotNull final IntentionAction action) {
548 ShowIntentionActionsHandler.chooseActionAndInvoke(getFile(), getEditor(), action, action.getText());
552 public void testCompletion(final String[] filesBefore, final String fileAfter) {
554 configureByFiles(filesBefore);
555 complete(CompletionType.BASIC);
556 checkResultByFile(fileAfter);
559 protected void assertInitialized() {
560 Assert.assertNotNull("setUp() hasn't been called", myPsiManager);
564 public void testCompletion(String fileBefore, String fileAfter, final String... additionalFiles) {
565 testCompletion(ArrayUtil.reverseArray(ArrayUtil.append(additionalFiles, fileBefore)), fileAfter);
569 public void testCompletionVariants(final String fileBefore, final String... expectedItems) {
571 final List<String> result = getCompletionVariants(fileBefore);
572 Assert.assertNotNull(result);
573 UsefulTestCase.assertSameElements(result, expectedItems);
577 public List<String> getCompletionVariants(final String... filesBefore) {
579 configureByFiles(filesBefore);
580 final LookupElement[] items = complete(CompletionType.BASIC);
581 Assert.assertNotNull("No lookup was shown, probably there was only one lookup element that was inserted automatically", items);
582 return getLookupElementStrings();
587 public List<String> getLookupElementStrings() {
589 final LookupElement[] elements = getLookupElements();
590 if (elements == null) return null;
592 return ContainerUtil.map(elements, new Function<LookupElement, String>() {
594 public String fun(final LookupElement lookupItem) {
595 return lookupItem.getLookupString();
601 public void testRename(final String fileBefore, final String fileAfter, final String newName, final String... additionalFiles) {
603 configureByFiles(ArrayUtil.reverseArray(ArrayUtil.append(additionalFiles, fileBefore)));
604 testRename(fileAfter, newName);
608 public void testRename(final String fileAfter, final String newName) {
609 renameElementAtCaret(newName);
610 checkResultByFile(fileAfter);
615 public PsiElement getElementAtCaret() {
617 final PsiElement element = TargetElementUtilBase.findTargetElement(getCompletionEditor(),
618 TargetElementUtilBase.REFERENCED_ELEMENT_ACCEPTED |
619 TargetElementUtilBase.ELEMENT_NAME_ACCEPTED);
620 assert element != null : "element not found in file " +
622 " at caret position, offset " +
623 myEditor.getCaretModel().getOffset();
628 public void renameElementAtCaret(final String newName) {
629 renameElement(getElementAtCaret(), newName);
633 public void renameElement(final PsiElement element, final String newName) {
634 final boolean searchInComments = false;
635 final boolean searchTextOccurrences = false;
636 renameElement(element, newName, searchInComments, searchTextOccurrences);
640 public void renameElement(final PsiElement element,
641 final String newName,
642 final boolean searchInComments,
643 final boolean searchTextOccurrences) {
644 final PsiElement substitution = RenamePsiElementProcessor.forElement(element).substituteElementToRename(element, myEditor);
645 if (substitution == null) return;
646 new RenameProcessor(getProject(), substitution, newName, searchInComments, searchTextOccurrences).run();
650 public <T extends PsiElement> T findElementByText(String text, Class<T> elementClass) {
651 int pos = PsiDocumentManager.getInstance(getProject()).getDocument(getFile()).getText().indexOf(text);
652 assert pos >= 0 : "text not found in file";
653 return PsiTreeUtil.getParentOfType(getFile().findElementAt(pos), elementClass);
657 public void type(final char c) {
659 UIUtil.invokeAndWaitIfNeeded(new Runnable() {
662 final EditorActionManager actionManager = EditorActionManager.getInstance();
664 performEditorAction(IdeActions.ACTION_EDITOR_BACKSPACE);
668 if (_performEditorAction(IdeActions.ACTION_CHOOSE_LOOKUP_ITEM)) {
672 performEditorAction(IdeActions.ACTION_EDITOR_ENTER);
676 if (_performEditorAction(IdeActions.ACTION_CHOOSE_LOOKUP_ITEM_REPLACE)) {
679 if (_performEditorAction(IdeActions.ACTION_EXPAND_LIVE_TEMPLATE_BY_TAB)) {
682 if (_performEditorAction(IdeActions.ACTION_EDITOR_TAB)) {
687 CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() {
690 CommandProcessor.getInstance().setCurrentCommandGroupId(myEditor.getDocument());
691 ActionManagerEx.getInstanceEx().fireBeforeEditorTyping(c, getEditorDataContext());
692 actionManager.getTypedAction().actionPerformed(getEditor(), c, getEditorDataContext());
694 }, null, DocCommandGroupId.noneGroupId(myEditor.getDocument()));
699 private DataContext getEditorDataContext() {
700 return ((EditorEx)myEditor).getDataContext();
704 public void type(String s) {
705 for (int i = 0; i < s.length(); i++) {
711 public void performEditorAction(final String actionId) {
713 _performEditorAction(actionId);
716 private boolean _performEditorAction(String actionId) {
717 final DataContext dataContext = getEditorDataContext();
719 ActionManagerEx managerEx = ActionManagerEx.getInstanceEx();
720 AnAction action = managerEx.getAction(actionId);
721 AnActionEvent event = new AnActionEvent(null, dataContext, ActionPlaces.UNKNOWN, new Presentation(), managerEx, 0);
723 action.update(event);
725 if (!event.getPresentation().isEnabled()) {
729 managerEx.fireBeforeActionPerformed(action, dataContext, event);
731 action.actionPerformed(event);
733 managerEx.fireAfterActionPerformed(action, dataContext, event);
738 public Presentation testAction(AnAction action) {
739 DataContext context = DataManager.getInstance().getDataContext();
740 TestActionEvent e = new TestActionEvent(context, action);
741 action.beforeActionPerformedUpdate(e);
742 if (e.getPresentation().isEnabled() && e.getPresentation().isVisible()) {
743 action.actionPerformed(e);
745 return e.getPresentation();
749 public Collection<UsageInfo> testFindUsages(@NonNls final String... fileNames) {
751 configureByFiles(fileNames);
752 final PsiElement targetElement = TargetElementUtilBase
753 .findTargetElement(getEditor(), TargetElementUtilBase.ELEMENT_NAME_ACCEPTED | TargetElementUtilBase.REFERENCED_ELEMENT_ACCEPTED);
754 assert targetElement != null : "Cannot find referenced element";
755 return findUsages(targetElement);
759 public Collection<UsageInfo> findUsages(@NotNull final PsiElement targetElement) {
760 final Project project = getProject();
761 final FindUsagesHandler handler =
762 ((FindManagerImpl)FindManager.getInstance(project)).getFindUsagesManager().getFindUsagesHandler(targetElement, false);
764 final CommonProcessors.CollectProcessor<UsageInfo> processor = new CommonProcessors.CollectProcessor<UsageInfo>();
765 assert handler != null : "Cannot find handler for: " + targetElement;
766 final PsiElement[] psiElements = ArrayUtil.mergeArrays(handler.getPrimaryElements(), handler.getSecondaryElements());
767 final FindUsagesOptions options = handler.getFindUsagesOptions(null);
768 for (PsiElement psiElement : psiElements) {
769 handler.processElementUsages(psiElement, processor, options);
771 return processor.getResults();
775 public RangeHighlighter[] testHighlightUsages(final String... files) {
776 configureByFiles(files);
777 testAction(new HighlightUsagesAction());
778 final Editor editor = getEditor();
779 //final Editor editor = PlatformDataKeys.EDITOR.getData(DataManager.getInstance().getDataContext());
780 //assert editor != null;
781 //HighlightUsagesHandler.invoke(getProject(), editor, getFile());
782 return editor.getMarkupModel().getAllHighlighters();
786 public void moveFile(@NonNls final String filePath, @NonNls final String to, final String... additionalFiles) {
788 final Project project = getProject();
789 new WriteCommandAction.Simple(project) {
791 protected void run() throws Exception {
792 configureByFiles(ArrayUtil.reverseArray(ArrayUtil.append(additionalFiles, filePath)));
793 final VirtualFile file = findFileInTempDir(to);
794 assert file != null : "Directory " + to + " not found";
795 assert file.isDirectory() : to + " is not a directory";
796 final PsiDirectory directory = myPsiManager.findDirectory(file);
797 new MoveFilesOrDirectoriesProcessor(project, new PsiElement[]{myFile}, directory,
798 false, false, null, null).run();
800 }.execute().throwException();
805 public GutterIconRenderer findGutter(final String filePath) {
806 configureByFilesInner(filePath);
807 int offset = myEditor.getCaretModel().getOffset();
809 final Collection<HighlightInfo> infos = doHighlighting();
810 for (HighlightInfo info : infos) {
811 if (info.endOffset >= offset && info.startOffset <= offset) {
812 final GutterIconRenderer renderer = info.getGutterIconRenderer();
813 if (renderer != null) {
818 RangeHighlighter[] highlighters = DocumentMarkupModel.forDocument(myEditor.getDocument(), getProject(), true).getAllHighlighters();
819 for (RangeHighlighter highlighter : highlighters) {
820 if (highlighter.getEndOffset() >= offset && highlighter.getStartOffset() <= offset) {
821 GutterIconRenderer renderer = highlighter.getGutterIconRenderer();
822 if (renderer != null) {
832 public Collection<GutterIconRenderer> findAllGutters(final String filePath) {
833 final Project project = getProject();
834 final SortedMap<Integer, List<GutterIconRenderer>> result = new TreeMap<Integer, List<GutterIconRenderer>>();
835 configureByFilesInner(filePath);
837 List<HighlightInfo> infos = doHighlighting();
838 for (HighlightInfo info : infos) {
839 addGutterIconRenderer(info.getGutterIconRenderer(), info.startOffset, result);
842 RangeHighlighter[] highlighters = DocumentMarkupModel.forDocument(myEditor.getDocument(), project, true).getAllHighlighters();
843 for (final RangeHighlighter highlighter : highlighters) {
844 if (!highlighter.isValid()) continue;
845 addGutterIconRenderer(highlighter.getGutterIconRenderer(), highlighter.getStartOffset(), result);
847 return ContainerUtil.concat(result.values());
850 private static void addGutterIconRenderer(final GutterIconRenderer renderer,
852 SortedMap<Integer, List<GutterIconRenderer>> result) {
853 if (renderer == null) return;
855 List<GutterIconRenderer> renderers = result.get(offset);
856 if (renderers == null) {
857 result.put(offset, renderers = new SmartList<GutterIconRenderer>());
859 renderers.add(renderer);
864 public PsiFile addFileToProject(@NonNls final String relativePath, @NonNls final String fileText) {
866 return addFileToProject(getTempDirPath(), relativePath, fileText);
869 protected PsiFile addFileToProject(String rootPath, String relativePath, String fileText) {
871 if (myTempDirFixture instanceof LightTempDirTestFixtureImpl) {
872 final VirtualFile file = myTempDirFixture.createFile(relativePath, fileText);
873 return PsiManager.getInstance(getProject()).findFile(file);
876 return ((HeavyIdeaTestFixture)myProjectFixture).addFileToProject(rootPath, relativePath, fileText);
878 catch (IOException e) {
879 throw new RuntimeException(e);
882 ((PsiModificationTrackerImpl)PsiManager.getInstance(getProject()).getModificationTracker()).incCounter();
886 public <T> void registerExtension(final ExtensionsArea area, final ExtensionPointName<T> epName, final T extension) {
888 final ExtensionPoint<T> extensionPoint = area.getExtensionPoint(epName);
889 extensionPoint.registerExtension(extension);
890 disposeOnTearDown(new Disposable() {
892 public void dispose() {
893 extensionPoint.unregisterExtension(extension);
899 public PsiManager getPsiManager() {
904 public LookupElement[] complete(CompletionType type) {
905 return complete(type, 1);
909 public LookupElement[] complete(final CompletionType type, final int invocationCount) {
911 myEmptyLookup = false;
912 UIUtil.invokeAndWaitIfNeeded(new Runnable() {
915 CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() {
918 final CodeCompletionHandlerBase handler = new CodeCompletionHandlerBase(type) {
921 protected void completionFinished(int offset1,
923 CompletionProgressIndicator indicator,
924 LookupElement[] items,
925 boolean hasModifiers) {
926 myEmptyLookup = items.length == 0;
927 super.completionFinished(offset1, offset2, indicator, items, hasModifiers);
930 Editor editor = getCompletionEditor();
931 handler.invokeCompletion(getProject(), editor, invocationCount, false);
932 PsiDocumentManager.getInstance(getProject()).commitAllDocuments(); // to compare with file text
938 return getLookupElements();
942 protected Editor getCompletionEditor() {
943 return InjectedLanguageUtil.getEditorForInjectedLanguageNoCommit(myEditor, myFile);
948 public LookupElement[] completeBasic() {
949 return complete(CompletionType.BASIC);
954 public LookupElement[] getLookupElements() {
955 LookupImpl lookup = getLookup();
956 if (lookup == null) {
957 return myEmptyLookup ? LookupElement.EMPTY_ARRAY : null;
960 final List<LookupElement> list = lookup.getItems();
961 return list.toArray(new LookupElement[list.size()]);
966 public void checkResult(final String text) {
967 checkResult(text, false);
971 public void checkResult(final String text, final boolean stripTrailingSpaces) {
972 new WriteCommandAction(getProject()) {
974 protected void run(Result result) throws Throwable {
975 PsiDocumentManager.getInstance(getProject()).commitAllDocuments();
976 EditorUtil.fillVirtualSpaceUntilCaret(myEditor);
977 checkResult("TEXT", stripTrailingSpaces, SelectionAndCaretMarkupLoader.fromText(text, getProject()), myFile.getText());
983 public void checkResultByFile(final String expectedFile) {
984 checkResultByFile(expectedFile, false);
988 public void checkResultByFile(final String expectedFile, final boolean ignoreTrailingWhitespaces) {
990 new WriteCommandAction.Simple(getProject()) {
993 protected void run() throws Exception {
994 checkResultByFile(expectedFile, myFile, ignoreTrailingWhitespaces);
996 }.execute().throwException();
1000 public void checkResultByFile(final String filePath, final String expectedFile, final boolean ignoreTrailingWhitespaces) {
1001 assertInitialized();
1003 new WriteCommandAction.Simple(getProject()) {
1006 protected void run() throws Exception {
1007 final String path = filePath.replace(File.separatorChar, '/');
1008 final VirtualFile copy = findFileInTempDir(path);
1010 throw new IllegalArgumentException("could not find results file " + path);
1012 final PsiFile psiFile = myPsiManager.findFile(copy);
1013 assert psiFile != null;
1014 checkResultByFile(expectedFile, psiFile, ignoreTrailingWhitespaces);
1016 }.execute().throwException();
1020 public void setUp() throws Exception {
1023 myProjectFixture.setUp();
1024 myTempDirFixture.setUp();
1025 myPsiManager = (PsiManagerImpl)PsiManager.getInstance(getProject());
1026 configureInspections(myInspections == null ? LocalInspectionTool.EMPTY_ARRAY : myInspections);
1028 DaemonCodeAnalyzerImpl daemonCodeAnalyzer = (DaemonCodeAnalyzerImpl)DaemonCodeAnalyzer.getInstance(getProject());
1029 daemonCodeAnalyzer.prepareForTest();
1031 DaemonCodeAnalyzerSettings.getInstance().setImportHintEnabled(false);
1032 ensureIndexesUpToDate(getProject());
1033 ((StartupManagerImpl)StartupManagerEx.getInstanceEx(getProject())).runPostStartupActivities();
1034 LocalInspectionEP[] extensions = Extensions.getExtensions(LocalInspectionEP.LOCAL_INSPECTION);
1035 for (LocalInspectionEP extension : extensions) {
1036 myExtensions.put(extension.shortName, extension);
1041 public void tearDown() throws Exception {
1042 ((StatisticsManagerImpl)StatisticsManager.getInstance()).clearStatistics();
1044 FileEditorManager editorManager = FileEditorManager.getInstance(getProject());
1045 VirtualFile[] openFiles = editorManager.getOpenFiles();
1046 for (VirtualFile openFile : openFiles) {
1047 editorManager.closeFile(openFile);
1052 myPsiManager = null;
1053 myInspections = null;
1054 myAvailableLocalTools.clear();
1055 myAvailableTools.clear();
1057 myProjectFixture.tearDown();
1058 myTempDirFixture.tearDown();
1063 private void enableInspectionTool(InspectionProfileEntry tool) {
1064 final String shortName = tool.getShortName();
1065 final HighlightDisplayKey key = HighlightDisplayKey.find(shortName);
1067 String id = tool instanceof LocalInspectionTool ? ((LocalInspectionTool)tool).getID() : shortName;
1068 HighlightDisplayKey.register(shortName, tool.getDisplayName(), id);
1070 myAvailableTools.put(shortName, tool);
1071 InspectionTool inspectionTool;
1072 if (tool instanceof LocalInspectionTool) {
1073 LocalInspectionEP ep = myExtensions.get(tool.getShortName());
1074 inspectionTool = new LocalInspectionToolWrapper((LocalInspectionTool)tool, ep);
1077 inspectionTool = (InspectionTool)tool;
1079 myAvailableLocalTools.put(shortName, inspectionTool);
1082 private void configureInspections(final InspectionProfileEntry[] tools) {
1083 for (InspectionProfileEntry tool : tools) {
1084 enableInspectionTool(tool);
1087 final InspectionProfileImpl profile = new InspectionProfileImpl(PROFILE) {
1090 public ModifiableModel getModifiableModel() {
1097 public InspectionProfileEntry[] getInspectionTools(PsiElement element) {
1098 final Collection<InspectionTool> tools = myAvailableLocalTools.values();
1099 return tools.toArray(new InspectionTool[tools.size()]);
1103 public List<ToolsImpl> getAllEnabledInspectionTools(Project project) {
1104 List<ToolsImpl> result = new ArrayList<ToolsImpl>();
1105 for (InspectionProfileEntry entry : getInspectionTools(null)) {
1106 result.add(new ToolsImpl(entry, entry.getDefaultLevel(), true));
1112 public boolean isToolEnabled(HighlightDisplayKey key, PsiElement element) {
1113 return key != null && key.toString() != null && myAvailableTools.containsKey(key.toString());
1117 public InspectionProfileEntry getInspectionTool(@NotNull String shortName) {
1118 return myAvailableTools.get(shortName);
1122 public HighlightDisplayLevel getErrorLevel(@NotNull HighlightDisplayKey key, PsiElement element) {
1123 final InspectionProfileEntry entry = myAvailableTools.get(key.toString());
1124 return entry != null ? entry.getDefaultLevel() : HighlightDisplayLevel.WARNING;
1128 public InspectionTool getInspectionTool(@NotNull String shortName, @NotNull PsiElement element) {
1129 return myAvailableLocalTools.get(shortName);
1132 final InspectionProfileManager inspectionProfileManager = InspectionProfileManager.getInstance();
1133 inspectionProfileManager.addProfile(profile);
1134 Disposer.register(getTestRootDisposable(), new Disposable() {
1136 public void dispose() {
1137 inspectionProfileManager.deleteProfile(PROFILE);
1140 inspectionProfileManager.setRootProfile(profile.getName());
1141 InspectionProjectProfileManager.getInstance(getProject()).updateProfile(profile);
1142 InspectionProjectProfileManager.getInstance(getProject()).setProjectProfile(profile.getName());
1145 private PsiFile[] configureByFilesInner(@NonNls String... filePaths) {
1146 assertInitialized();
1149 PsiFile[] psiFiles = new PsiFile[filePaths.length];
1150 for (int i = filePaths.length - 1; i >= 0; i--) {
1151 psiFiles[i] = configureByFileInner(filePaths[i]);
1157 public PsiFile configureByFile(final String file) {
1158 configureByFilesInner(file);
1163 public PsiFile[] configureByFiles(@NonNls final String... files) {
1164 return configureByFilesInner(files);
1168 public PsiFile configureByText(final FileType fileType, @NonNls final String text) {
1169 assertInitialized();
1170 final String extension = fileType.getDefaultExtension();
1171 final FileTypeManager fileTypeManager = FileTypeManager.getInstance();
1172 if (fileTypeManager.getFileTypeByExtension(extension) != fileType) {
1173 new WriteCommandAction(getProject()) {
1175 protected void run(Result result) throws Exception {
1176 fileTypeManager.associateExtension(fileType, extension);
1180 final String fileName = "aaa." + extension;
1181 return configureByText(fileName, text);
1185 public PsiFile configureByText(final String fileName, @NonNls final String text) {
1186 assertInitialized();
1187 new WriteCommandAction(getProject()) {
1189 protected void run(Result result) throws Throwable {
1190 final VirtualFile vFile;
1191 if (myTempDirFixture instanceof LightTempDirTestFixtureImpl) {
1192 final VirtualFile root = LightPlatformTestCase.getSourceRoot();
1193 root.refresh(false, false);
1194 vFile = root.findOrCreateChildData(this, fileName);
1197 String prefix = StringUtil.getPackageName(fileName);
1198 if (prefix.length() < 3) {
1201 final File tempFile = FileUtil.createTempFile(new File(getTempDirPath()), prefix, "." + StringUtil.getShortName(fileName), true);
1202 vFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(tempFile);
1204 final Document document = FileDocumentManager.getInstance().getCachedDocument(vFile);
1205 if (document != null) {
1206 FileDocumentManager.getInstance().saveDocument(document);
1209 VfsUtil.saveText(vFile, text);
1210 configureInner(vFile, SelectionAndCaretMarkupLoader.fromFile(vFile, getProject()));
1217 public Document getDocument(final PsiFile file) {
1218 assertInitialized();
1219 return PsiDocumentManager.getInstance(getProject()).getDocument(file);
1224 * @throws IOException
1226 private PsiFile configureByFileInner(@NonNls String filePath) {
1227 assertInitialized();
1228 final VirtualFile file = copyFileToProject(filePath);
1229 return configureByFileInner(file);
1233 public PsiFile configureFromTempProjectFile(final String filePath) {
1234 final VirtualFile fileInTempDir = findFileInTempDir(filePath);
1235 if (fileInTempDir == null) {
1236 throw new IllegalArgumentException("Could not find file in temp dir: " + filePath);
1238 return configureByFileInner(fileInTempDir);
1242 public void configureFromExistingVirtualFile(VirtualFile f) {
1243 configureByFileInner(f);
1246 private PsiFile configureByFileInner(final VirtualFile copy) {
1247 return configureInner(copy, SelectionAndCaretMarkupLoader.fromFile(copy, getProject()));
1250 private PsiFile configureInner(@NotNull final VirtualFile copy, final SelectionAndCaretMarkupLoader loader) {
1251 assertInitialized();
1252 new WriteCommandAction.Simple(getProject()) {
1255 copy.setBinaryContent(loader.newFileText.getBytes(copy.getCharset()), 0, 0, null);
1257 catch (IOException e) {
1258 throw new RuntimeException(e);
1260 myFile = myPsiManager.findFile(copy);
1261 myEditor = createEditor(copy);
1262 assert myEditor != null : "Editor couldn't be created for file: " +
1264 ", use copyFileToProject(..) method for this file instead of configureByFile(..)";
1265 if (loader.caretMarker != null) {
1266 int offset = loader.caretMarker.getStartOffset();
1267 myEditor.getCaretModel().moveToOffset(offset);
1269 if (loader.selStartMarker != null && loader.selEndMarker != null) {
1270 myEditor.getSelectionModel().setSelection(loader.selStartMarker.getStartOffset(), loader.selEndMarker.getStartOffset());
1273 Module module = getModule();
1274 if (module != null) {
1275 for (Facet facet : FacetManager.getInstance(module).getAllFacets()) {
1276 module.getMessageBus().syncPublisher(FacetManager.FACETS_TOPIC).facetConfigurationChanged(facet);
1280 }.execute().throwException();
1287 public VirtualFile findFileInTempDir(final String filePath) {
1288 if (myTempDirFixture instanceof LightTempDirTestFixtureImpl) {
1289 return myTempDirFixture.getFile(filePath);
1291 String fullPath = getTempDirPath() + "/" + filePath;
1293 final VirtualFile copy = LocalFileSystem.getInstance().refreshAndFindFileByPath(fullPath.replace(File.separatorChar, '/'));
1294 assert copy != null : "file " + fullPath + " not found";
1299 private Editor createEditor(VirtualFile file) {
1300 final Project project = getProject();
1301 final FileEditorManager instance = FileEditorManager.getInstance(project);
1302 if (file.getFileType().isBinary()) {
1305 return instance.openTextEditor(new OpenFileDescriptor(project, file, 0), false);
1308 private void collectAndCheckHighlightings(boolean checkWarnings, boolean checkInfos, boolean checkWeakWarnings, Ref<Long> duration)
1310 ExpectedHighlightingData data =
1311 new ExpectedHighlightingData(myEditor.getDocument(), checkWarnings, checkWeakWarnings, checkInfos, myFile);
1313 collectAndCheckHighlightings(data, duration);
1316 private void collectAndCheckHighlightings(final ExpectedHighlightingData data, final Ref<Long> duration) {
1317 final Project project = getProject();
1318 PsiDocumentManager.getInstance(project).commitAllDocuments();
1320 ((PsiFileImpl)myFile).calcTreeElement(); //to load text
1322 //to initialize caches
1323 CacheManager.SERVICE.getInstance(project).getFilesWithWord(XXX, UsageSearchContext.IN_COMMENTS, GlobalSearchScope.allScope(project), true);
1325 List<HighlightInfo> infos;
1327 ((PsiManagerImpl)PsiManager.getInstance(project)).setAssertOnFileLoadingFilter(myJavaFilesFilter);
1329 final long start = System.currentTimeMillis();
1330 // ProfilingUtil.startCPUProfiling();
1331 infos = doHighlighting();
1332 removeDuplicatedRangesForInjected(infos);
1333 final long elapsed = System.currentTimeMillis() - start;
1334 duration.set(duration.isNull() ? elapsed : duration.get().longValue() + elapsed);
1335 // ProfilingUtil.captureCPUSnapshot("testing");
1338 ((PsiManagerImpl)PsiManager.getInstance(project)).setAssertOnFileLoadingFilter(VirtualFileFilter.NONE);
1342 data.checkResult(infos, myEditor.getDocument().getText());
1345 private static void removeDuplicatedRangesForInjected(List<HighlightInfo> infos) {
1346 Collections.sort(infos, new Comparator<HighlightInfo>() {
1348 public int compare(HighlightInfo o1, HighlightInfo o2) {
1349 final int i = o2.startOffset - o1.startOffset;
1350 return i != 0 ? i : o1.getSeverity().myVal - o2.getSeverity().myVal;
1353 HighlightInfo prevInfo = null;
1354 for (Iterator<HighlightInfo> it = infos.iterator(); it.hasNext();) {
1355 final HighlightInfo info = it.next();
1356 if (prevInfo != null &&
1357 info.getSeverity() == HighlightInfoType.SYMBOL_TYPE_SEVERITY &&
1358 info.description == null &&
1359 info.startOffset == prevInfo.startOffset &&
1360 info.endOffset == prevInfo.endOffset) {
1363 prevInfo = info.type == HighlightInfoType.INJECTED_LANGUAGE_FRAGMENT ? info : null;
1369 public List<HighlightInfo> doHighlighting() {
1370 final Project project = getProject();
1371 PsiDocumentManager.getInstance(project).commitAllDocuments();
1373 return instantiateAndRun(getFile(), getEditor(), ArrayUtil.EMPTY_INT_ARRAY, myAllowDirt);
1377 public static List<HighlightInfo> instantiateAndRun(@NotNull PsiFile file,
1378 @NotNull Editor editor,
1379 @NotNull int[] toIgnore,
1380 boolean canChangeDocument) {
1381 Project project = file.getProject();
1382 ensureIndexesUpToDate(project);
1383 DaemonCodeAnalyzerImpl codeAnalyzer = (DaemonCodeAnalyzerImpl)DaemonCodeAnalyzer.getInstance(project);
1384 TextEditor textEditor = TextEditorProvider.getInstance().getTextEditor(editor);
1385 return codeAnalyzer.runPasses(file, editor.getDocument(), textEditor, toIgnore, canChangeDocument, null);
1388 public static void ensureIndexesUpToDate(Project project) {
1389 if (!DumbService.isDumb(project)) {
1390 FileBasedIndex.getInstance().ensureUpToDate(StubUpdatingIndex.INDEX_ID, project, null);
1391 FileBasedIndex.getInstance().ensureUpToDate(TodoIndex.NAME, project, null);
1396 public String getTestDataPath() {
1397 return myTestDataPath;
1401 public Project getProject() {
1402 return myProjectFixture.getProject();
1406 public Module getModule() {
1407 return myProjectFixture.getModule();
1411 public Editor getEditor() {
1416 public int getCaretOffset() {
1417 return myEditor.getCaretModel().getOffset();
1421 public PsiFile getFile() {
1425 public static List<IntentionAction> getAvailableIntentions(@NotNull final Editor editor, @NotNull final PsiFile file) {
1426 return ApplicationManager.getApplication().runReadAction(new Computable<List<IntentionAction>>() {
1428 public List<IntentionAction> compute() {
1429 return doGetAvailableIntentions(editor, file);
1434 private static List<IntentionAction> doGetAvailableIntentions(@NotNull Editor editor, @NotNull PsiFile file) {
1435 ShowIntentionsPass.IntentionsInfo intentions = new ShowIntentionsPass.IntentionsInfo();
1436 ShowIntentionsPass.getActionsToShow(editor, file, intentions, -1);
1437 List<HighlightInfo.IntentionActionDescriptor> descriptors = new ArrayList<HighlightInfo.IntentionActionDescriptor>();
1438 descriptors.addAll(intentions.intentionsToShow);
1439 descriptors.addAll(intentions.errorFixesToShow);
1440 descriptors.addAll(intentions.inspectionFixesToShow);
1441 descriptors.addAll(intentions.guttersToShow);
1443 PsiElement element = file.findElementAt(editor.getCaretModel().getOffset());
1444 List<IntentionAction> result = new ArrayList<IntentionAction>();
1446 List<HighlightInfo> infos = DaemonCodeAnalyzerImpl.getFileLevelHighlights(file.getProject(), file);
1447 for (HighlightInfo info : infos) {
1448 for (Pair<HighlightInfo.IntentionActionDescriptor, TextRange> pair : info.quickFixActionRanges) {
1449 HighlightInfo.IntentionActionDescriptor actionInGroup = pair.first;
1450 if (actionInGroup.getAction().isAvailable(file.getProject(), editor, file)) {
1451 descriptors.add(actionInGroup);
1456 // add all intention options for simplicity
1457 for (HighlightInfo.IntentionActionDescriptor descriptor : descriptors) {
1458 result.add(descriptor.getAction());
1459 List<IntentionAction> options = descriptor.getOptions(element,editor);
1460 if (options != null) {
1461 for (IntentionAction option : options) {
1462 if (option.isAvailable(file.getProject(), editor, file)) {
1472 public void allowTreeAccessForFile(final VirtualFile file) {
1473 myJavaFilesFilter.allowTreeAccessForFile(file);
1477 public void allowTreeAccessForAllFiles() {
1478 myJavaFilesFilter.allowTreeAccessForAllFiles();
1481 static class SelectionAndCaretMarkupLoader {
1482 final String newFileText;
1483 final RangeMarker caretMarker;
1484 final RangeMarker selStartMarker;
1485 final RangeMarker selEndMarker;
1487 static SelectionAndCaretMarkupLoader fromFile(String path, Project project) throws IOException {
1488 return new SelectionAndCaretMarkupLoader(StringUtil.convertLineSeparators(FileUtil.loadFile(new File(path))),
1492 static SelectionAndCaretMarkupLoader fromFile(VirtualFile file, Project project) {
1495 text = VfsUtil.loadText(file);
1497 catch (IOException e) {
1498 throw new RuntimeException(e);
1500 return new SelectionAndCaretMarkupLoader(StringUtil.convertLineSeparators(text), project);
1503 static SelectionAndCaretMarkupLoader fromText(String text, Project project) {
1504 return new SelectionAndCaretMarkupLoader(text, project);
1507 private SelectionAndCaretMarkupLoader(String fileText, Project project) {
1508 final Document document = EditorFactory.getInstance().createDocument(fileText);
1510 int caretIndex = fileText.indexOf(CARET_MARKER);
1511 int selStartIndex = fileText.indexOf(SELECTION_START_MARKER);
1512 int selEndIndex = fileText.indexOf(SELECTION_END_MARKER);
1514 caretMarker = caretIndex >= 0 ? document.createRangeMarker(caretIndex, caretIndex) : null;
1515 selStartMarker = selStartIndex >= 0 ? document.createRangeMarker(selStartIndex, selStartIndex) : null;
1516 selEndMarker = selEndIndex >= 0 ? document.createRangeMarker(selEndIndex, selEndIndex) : null;
1518 new WriteCommandAction(project) {
1520 protected void run(Result result) throws Exception {
1521 if (caretMarker != null) {
1522 document.deleteString(caretMarker.getStartOffset(), caretMarker.getStartOffset() + CARET_MARKER.length());
1524 if (selStartMarker != null) {
1525 document.deleteString(selStartMarker.getStartOffset(), selStartMarker.getStartOffset() + SELECTION_START_MARKER.length());
1527 if (selEndMarker != null) {
1528 document.deleteString(selEndMarker.getStartOffset(), selEndMarker.getStartOffset() + SELECTION_END_MARKER.length());
1533 newFileText = document.getText();
1537 private void checkResultByFile(@NonNls String expectedFile,
1538 @NotNull PsiFile originalFile,
1539 boolean stripTrailingSpaces) throws IOException {
1540 if (!stripTrailingSpaces) {
1541 EditorUtil.fillVirtualSpaceUntilCaret(myEditor);
1543 PsiDocumentManager.getInstance(getProject()).commitAllDocuments();
1545 final String fileText = originalFile.getText();
1546 final String path = getTestDataPath() + "/" + expectedFile;
1548 /*final VirtualFile result = LocalFileSystem.getInstance().findFileByPath(path);
1549 final int caret = myEditor.getCaretModel().getOffset();
1550 final String newText = myFile == originalFile ? fileText.substring(0, caret) + "<caret>" + fileText.substring(caret) : fileText;
1551 VfsUtil.saveText(result, newText);*/
1553 checkResult(expectedFile, stripTrailingSpaces,
1554 SelectionAndCaretMarkupLoader.fromFile(path, getProject()), fileText);
1558 private void checkResult(final String expectedFile,
1559 final boolean stripTrailingSpaces,
1560 final SelectionAndCaretMarkupLoader loader,
1561 String actualText) {
1562 assertInitialized();
1563 Project project = getProject();
1565 project.getComponent(PostprocessReformattingAspect.class).doPostponedFormatting();
1566 if (stripTrailingSpaces) {
1567 actualText = stripTrailingSpaces(actualText);
1570 PsiDocumentManager.getInstance(project).commitAllDocuments();
1572 String newFileText1 = loader.newFileText;
1573 if (stripTrailingSpaces) {
1574 newFileText1 = stripTrailingSpaces(newFileText1);
1577 actualText = StringUtil.convertLineSeparators(actualText);
1579 //noinspection HardCodedStringLiteral
1580 Assert.assertEquals("Text mismatch in file " + expectedFile, newFileText1, actualText);
1582 if (loader.caretMarker != null) {
1583 final int tabSize = CodeStyleSettingsManager.getSettings(getProject()).getIndentOptions(StdFileTypes.JAVA).TAB_SIZE;
1585 int caretLine = StringUtil.offsetToLineNumber(loader.newFileText, loader.caretMarker.getStartOffset());
1586 int caretCol = EditorUtil.calcColumnNumber(null, loader.newFileText, StringUtil.lineColToOffset(loader.newFileText, caretLine, 0), loader.caretMarker.getStartOffset(), tabSize);
1588 final int actualLine = myEditor.getCaretModel().getLogicalPosition().line;
1589 final int actualCol = myEditor.getCaretModel().getLogicalPosition().column;
1590 boolean caretPositionEquals = caretLine == actualLine && caretCol == actualCol;
1591 assertTrue("Caret position in " + expectedFile + " differs. Expected " + genCaretPositionPresentation(caretLine, caretCol) +
1592 ". Actual " + genCaretPositionPresentation(actualLine, actualCol), caretPositionEquals);
1595 if (loader.selStartMarker != null && loader.selEndMarker != null) {
1596 int selStartLine = StringUtil.offsetToLineNumber(loader.newFileText, loader.selStartMarker.getStartOffset());
1597 int selStartCol = loader.selStartMarker.getStartOffset() - StringUtil.lineColToOffset(loader.newFileText, selStartLine, 0);
1599 int selEndLine = StringUtil.offsetToLineNumber(loader.newFileText, loader.selEndMarker.getEndOffset());
1600 int selEndCol = loader.selEndMarker.getEndOffset() - StringUtil.lineColToOffset(loader.newFileText, selEndLine, 0);
1602 final int selStartLineActual = StringUtil.offsetToLineNumber(loader.newFileText, myEditor.getSelectionModel().getSelectionStart());
1603 final int selStartColActual = myEditor.getSelectionModel().getSelectionStart() - StringUtil.lineColToOffset(loader.newFileText, selStartLineActual, 0);
1605 final int selEndLineActual = StringUtil.offsetToLineNumber(loader.newFileText, myEditor.getSelectionModel().getSelectionEnd());
1606 final int selEndColActual = myEditor.getSelectionModel().getSelectionEnd() - StringUtil.lineColToOffset(loader.newFileText, selEndLineActual, 0);
1608 final boolean selectionEquals = selStartCol == selStartColActual &&
1609 selStartLine == selStartLineActual &&
1610 selEndCol == selEndColActual &&
1611 selEndLine == selEndLineActual;
1612 Assert.assertTrue("selection in " +
1614 " differs. Expected " +
1615 genSelectionPresentation(selStartLine, selStartCol, selEndLine, selEndCol) +
1617 genSelectionPresentation(selStartLineActual, selStartColActual, selEndLineActual, selEndColActual),
1620 else if (myEditor != null) {
1621 Assert.assertTrue("has no selection in " + expectedFile, !myEditor.getSelectionModel().hasSelection());
1625 private static String genCaretPositionPresentation(int line, int col) {
1628 return "(" + line + ", " + col + ")";
1631 private static String genSelectionPresentation(int startLine, int startCol, int endLine, int endCol) {
1636 return "(" + startLine + ", " + startCol + ")-(" + endLine + ", " + endCol + ")";
1639 private static String stripTrailingSpaces(String actualText) {
1640 final Document document = EditorFactory.getInstance().createDocument(actualText);
1641 ((DocumentImpl)document).stripTrailingSpaces();
1642 actualText = document.getText();
1646 public void canChangeDocumentDuringHighlighting(boolean canI) {
1650 private static final String START_FOLD = "<fold\\stext=\'[^\']*\'(\\sexpand=\'[^\']*\')*>";
1651 private static final String END_FOLD = "</fold>";
1653 private class Border implements Comparable<Border> {
1654 public static final boolean LEFT = true;
1655 public static final boolean RIGHT = false;
1656 public boolean mySide;
1657 public int myOffset;
1658 public String myText;
1659 public boolean myIsExpanded;
1661 private Border(boolean side, int offset, String text, boolean isExpanded) {
1665 myIsExpanded = isExpanded;
1668 public boolean isExpanded() {
1669 return myIsExpanded;
1672 public boolean isSide() {
1676 public int getOffset() {
1680 public String getText() {
1684 public int compareTo(Border o) {
1685 return getOffset() < o.getOffset() ? 1 : -1;
1689 private String getFoldingDescription(@NotNull String content, @NotNull String initialFileName,
1690 boolean doCheckCollapseStatus) {
1691 configureByText(FileTypeManager.getInstance().getFileTypeByFileName(initialFileName), content);
1692 CodeFoldingManager.getInstance(getProject()).buildInitialFoldings(myEditor);
1694 final FoldingModel model = myEditor.getFoldingModel();
1695 final FoldRegion[] foldingRegions = model.getAllFoldRegions();
1696 final List<Border> borders = new LinkedList<Border>();
1698 for (FoldRegion region : foldingRegions) {
1699 borders.add(new Border(Border.LEFT, region.getStartOffset(), region.getPlaceholderText(), region.isExpanded()));
1700 borders.add(new Border(Border.RIGHT, region.getEndOffset(), "", region.isExpanded()));
1702 Collections.sort(borders);
1704 StringBuilder result = new StringBuilder(myEditor.getDocument().getText());
1705 for (Border border : borders) {
1706 result.insert(border.getOffset(), border.isSide() == Border.LEFT ? "<fold text=\'" + border.getText() + "\'" +
1707 (doCheckCollapseStatus ? " expand=\'" +
1708 border.isExpanded() +
1713 return result.toString();
1716 private void testFoldingRegions(final String verificationFileName, boolean doCheckCollapseStatus) {
1717 String expectedContent;
1719 expectedContent = FileUtil.loadFile(new File(verificationFileName));
1721 catch (IOException e) {
1722 throw new RuntimeException(e);
1724 Assert.assertNotNull(expectedContent);
1726 expectedContent = StringUtil.replace(expectedContent, "\r", "");
1727 final String cleanContent = expectedContent.replaceAll(START_FOLD, "").replaceAll(END_FOLD, "");
1728 final String actual = getFoldingDescription(cleanContent, verificationFileName, doCheckCollapseStatus);
1730 assertEquals(expectedContent, actual);
1733 public void testFoldingWithCollapseStatus(final String verificationFileName) {
1734 testFoldingRegions(verificationFileName, true);
1737 public void testFolding(final String verificationFileName) {
1738 testFoldingRegions(verificationFileName, false);
1742 public void assertPreferredCompletionItems(final int selected, @NonNls final String... expected) {
1743 final LookupImpl lookup = getLookup();
1744 assertNotNull(lookup);
1746 final LinkedHashMap<LookupElement,StringBuilder> relevanceStrings = lookup.getRelevanceStrings();
1748 final JList list = lookup.getList();
1749 final List<LookupElement> model = lookup.getItems();
1750 final List<String> actual = new ArrayList<String>();
1751 final int count = lookup.getPreferredItemsCount();
1752 for (int i = 0; i < count; i++) {
1753 actual.add(model.get(i).getLookupString());
1755 if (!actual.equals(Arrays.asList(expected))) {
1756 final List<String> strings = new ArrayList<String>();
1757 for (int i = 0; i < model.size(); i++) {
1758 final LookupElement item = model.get(i);
1759 strings.add(item.getLookupString() + " " + relevanceStrings.get(item));
1760 if (i == count - 1) {
1764 assertOrderedEquals(strings, expected);
1766 assertEquals(selected, list.getSelectedIndex());
1770 public void testStructureView(Consumer<StructureViewComponent> consumer) {
1771 assert myFile != null : "configure first";
1773 final VirtualFile vFile = myFile.getVirtualFile();
1774 assert vFile != null : "no virtual file for " + myFile;
1776 final FileEditor fileEditor = FileEditorManager.getInstance(getProject()).getSelectedEditor(vFile);
1777 assert fileEditor != null : "editor not opened for " + vFile;
1779 final StructureViewBuilder builder = LanguageStructureViewBuilder.INSTANCE.getStructureViewBuilder(myFile);
1780 assert builder != null : "no builder for " + myFile;
1782 StructureViewComponent component = null;
1784 component = (StructureViewComponent)builder.createStructureView(fileEditor, myProjectFixture.getProject());
1785 consumer.consume(component);
1788 if (component != null) Disposer.dispose(component);
1792 private LookupImpl getLookup() {
1793 return (LookupImpl)LookupManager.getActiveLookup(myEditor);