-
Notifications
You must be signed in to change notification settings - Fork 5.3k
/
CodeInsightTestFixtureImpl.java
2340 lines (2063 loc) · 96.4 KB
/
CodeInsightTestFixtureImpl.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2000-2024 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.testFramework.fixtures.impl;
import com.intellij.analysis.AnalysisScope;
import com.intellij.application.options.CodeStyle;
import com.intellij.codeHighlighting.RainbowHighlighter;
import com.intellij.codeInsight.AutoPopupController;
import com.intellij.codeInsight.TargetElementUtil;
import com.intellij.codeInsight.completion.CompletionType;
import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer;
import com.intellij.codeInsight.daemon.DaemonCodeAnalyzerSettings;
import com.intellij.codeInsight.daemon.GutterMark;
import com.intellij.codeInsight.daemon.ProblemHighlightFilter;
import com.intellij.codeInsight.daemon.impl.*;
import com.intellij.codeInsight.highlighting.actions.HighlightUsagesAction;
import com.intellij.codeInsight.intention.IntentionAction;
import com.intellij.codeInsight.intention.IntentionActionDelegate;
import com.intellij.codeInsight.intention.IntentionSource;
import com.intellij.codeInsight.intention.impl.CachedIntentions;
import com.intellij.codeInsight.intention.impl.IntentionActionWithTextCaching;
import com.intellij.codeInsight.intention.impl.IntentionListStep;
import com.intellij.codeInsight.intention.impl.ShowIntentionActionsHandler;
import com.intellij.codeInsight.intention.impl.preview.IntentionPreviewDiffResult;
import com.intellij.codeInsight.intention.impl.preview.IntentionPreviewPopupUpdateProcessor;
import com.intellij.codeInsight.intention.preview.IntentionPreviewInfo;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupManager;
import com.intellij.codeInsight.lookup.impl.LookupImpl;
import com.intellij.codeInspection.InspectionProfileEntry;
import com.intellij.codeInspection.InspectionToolProvider;
import com.intellij.codeInspection.LocalInspectionTool;
import com.intellij.codeInspection.actions.CleanupInspectionIntention;
import com.intellij.codeInspection.ex.InspectionToolWrapper;
import com.intellij.facet.Facet;
import com.intellij.facet.FacetManager;
import com.intellij.find.FindManager;
import com.intellij.find.actions.SearchTarget2UsageTarget;
import com.intellij.find.findUsages.FindUsagesHandler;
import com.intellij.find.findUsages.FindUsagesManager;
import com.intellij.find.findUsages.FindUsagesOptions;
import com.intellij.find.impl.FindManagerImpl;
import com.intellij.find.usages.api.SearchTarget;
import com.intellij.find.usages.api.UsageOptions;
import com.intellij.find.usages.impl.AllSearchOptions;
import com.intellij.ide.IdeEventQueue;
import com.intellij.ide.actions.searcheverywhere.ClassSearchEverywhereContributor;
import com.intellij.ide.actions.searcheverywhere.SearchEverywhereContributor;
import com.intellij.ide.actions.searcheverywhere.SymbolSearchEverywhereContributor;
import com.intellij.ide.structureView.StructureViewBuilder;
import com.intellij.ide.structureView.newStructureView.StructureViewComponent;
import com.intellij.ide.util.scopeChooser.ScopeDescriptor;
import com.intellij.injected.editor.DocumentWindow;
import com.intellij.injected.editor.EditorWindow;
import com.intellij.injected.editor.VirtualFileWindow;
import com.intellij.lang.LanguageStructureViewBuilder;
import com.intellij.lang.annotation.HighlightSeverity;
import com.intellij.lang.injection.InjectedLanguageManager;
import com.intellij.mock.MockProgressIndicator;
import com.intellij.model.psi.PsiSymbolReference;
import com.intellij.model.psi.impl.ReferencesKt;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.actionSystem.ex.ActionUtil;
import com.intellij.openapi.actionSystem.impl.SimpleDataContext;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ReadAction;
import com.intellij.openapi.application.WriteAction;
import com.intellij.openapi.application.impl.NonBlockingReadActionImpl;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.EditorFactory;
import com.intellij.openapi.editor.Inlay;
import com.intellij.openapi.editor.colors.EditorColorsManager;
import com.intellij.openapi.editor.colors.EditorColorsScheme;
import com.intellij.openapi.editor.colors.TextAttributesKey;
import com.intellij.openapi.editor.ex.MarkupModelEx;
import com.intellij.openapi.editor.ex.util.EditorUtil;
import com.intellij.openapi.editor.impl.DocumentImpl;
import com.intellij.openapi.editor.impl.DocumentMarkupModel;
import com.intellij.openapi.editor.impl.EditorImpl;
import com.intellij.openapi.editor.markup.RangeHighlighter;
import com.intellij.openapi.editor.markup.TextAttributes;
import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.openapi.extensions.ExtensionsArea;
import com.intellij.openapi.fileEditor.*;
import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx;
import com.intellij.openapi.fileEditor.impl.EditorHistoryManager;
import com.intellij.openapi.fileEditor.impl.text.TextEditorProvider;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.FileTypeManager;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.project.DumbService;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ModuleRootManager;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.roots.impl.ProjectRootManagerComponent;
import com.intellij.openapi.roots.impl.ProjectRootManagerImpl;
import com.intellij.openapi.roots.impl.libraries.LibraryTableTracker;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.Segment;
import com.intellij.openapi.util.ThrowableComputable;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vcs.readOnlyHandler.ReadonlyStatusHandlerImpl;
import com.intellij.openapi.vfs.*;
import com.intellij.openapi.vfs.impl.VirtualFilePointerTracker;
import com.intellij.openapi.vfs.newvfs.ArchiveFileSystem;
import com.intellij.platform.testFramework.core.FileComparisonFailedError;
import com.intellij.profile.codeInspection.ProjectInspectionProfileManager;
import com.intellij.psi.*;
import com.intellij.psi.impl.PsiManagerEx;
import com.intellij.psi.impl.PsiManagerImpl;
import com.intellij.psi.impl.source.PsiFileImpl;
import com.intellij.psi.impl.source.tree.FileElement;
import com.intellij.psi.impl.source.tree.injected.InjectedLanguageEditorUtil;
import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.SearchScope;
import com.intellij.psi.stubs.StubTextInconsistencyException;
import com.intellij.psi.util.PsiUtilBase;
import com.intellij.refactoring.move.moveFilesOrDirectories.MoveFilesOrDirectoriesProcessor;
import com.intellij.refactoring.rename.*;
import com.intellij.refactoring.rename.api.RenameTarget;
import com.intellij.refactoring.rename.impl.RenameKt;
import com.intellij.testFramework.*;
import com.intellij.testFramework.fixtures.*;
import com.intellij.testFramework.utils.inlays.CaretAndInlaysInfo;
import com.intellij.testFramework.utils.inlays.InlayHintsChecker;
import com.intellij.ui.components.breadcrumbs.Crumb;
import com.intellij.ui.content.Content;
import com.intellij.usageView.UsageInfo;
import com.intellij.usageView.UsageViewContentManager;
import com.intellij.usages.*;
import com.intellij.usages.impl.UsageViewImpl;
import com.intellij.util.*;
import com.intellij.util.concurrency.AppExecutorUtil;
import com.intellij.util.concurrency.annotations.RequiresEdt;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.indexing.FileBasedIndex;
import com.intellij.util.indexing.FileBasedIndexExtension;
import com.intellij.util.indexing.FindSymbolParameters;
import com.intellij.util.io.ReadOnlyAttributeUtil;
import com.intellij.util.ui.UIUtil;
import kotlin.UninitializedPropertyAccessException;
import org.intellij.lang.annotations.Language;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
import org.jetbrains.annotations.Unmodifiable;
import org.junit.Assert;
import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.lang.ref.Reference;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static com.intellij.find.usages.impl.ImplKt.buildUsageViewQuery;
import static com.intellij.openapi.util.io.FileUtil.toSystemDependentName;
import static com.intellij.testFramework.RunAll.runAll;
import static com.intellij.testFramework.UsefulTestCase.assertOneElement;
import static com.intellij.util.ObjectUtils.coalesce;
import static org.junit.Assert.*;
/**
* @author Dmitry Avdeev
*/
@TestOnly
public class CodeInsightTestFixtureImpl extends BaseFixture implements CodeInsightTestFixture {
private static final Logger LOG = Logger.getInstance(CodeInsightTestFixtureImpl.class);
private static final Function<IntentionAction, String> INTENTION_NAME_FUN = intentionAction -> '"' + intentionAction.getText() + '"';
private static final String RAINBOW = "rainbow";
private static final String FOLD = "fold";
private final IdeaProjectTestFixture myProjectFixture;
private final TempDirTestFixture myTempDirFixture;
private PsiManagerImpl myPsiManager;
private VirtualFile myFile;
// Strong references to PSI files configured by the test (to avoid tree access assertions after PSI has been GC'ed)
@SuppressWarnings("unused") private PsiFile myPsiFile;
private PsiFile[] myAllPsiFiles;
private Editor editor;
private EditorTestFixture myEditorTestFixture;
private String myTestDataPath;
private VirtualFileFilter myVirtualFileFilter = new FileTreeAccessFilter();
private boolean myAllowDirt;
private boolean caresAboutInjection = true;
private boolean myReadEditorMarkupModel;
private VirtualFilePointerTracker myVirtualFilePointerTracker;
private LibraryTableTracker myLibraryTableTracker;
private SelectionAndCaretMarkupApplyPolicy mySelectionAndCaretMarkupApplyPolicy = SelectionAndCaretMarkupApplyPolicy.UPDATE_FILE_AND_KEEP_DOCUMENT_CLEAN;
public CodeInsightTestFixtureImpl(@NotNull IdeaProjectTestFixture projectFixture, @NotNull TempDirTestFixture tempDirTestFixture) {
myProjectFixture = projectFixture;
myTempDirFixture = tempDirTestFixture;
}
private void setFileAndEditor(@NotNull VirtualFile file, @NotNull Editor editor) {
myFile = file;
this.editor = editor;
myEditorTestFixture = new EditorTestFixture(getProject(), editor, file);
myPsiFile = ReadAction.compute(() -> PsiManager.getInstance(getProject()).findFile(myFile));
}
private void clearFileAndEditor() {
myFile = null;
editor = null;
myEditorTestFixture = null;
myPsiFile = null;
myAllPsiFiles = null;
}
private static void addGutterIconRenderer(GutterMark renderer, int offset, @NotNull Map<? super Integer, List<GutterMark>> result) {
if (renderer == null) return;
List<GutterMark> renderers = result.computeIfAbsent(offset, __ -> new SmartList<>());
renderers.add(renderer);
}
private static @Unmodifiable @NotNull List<HighlightInfo> removeDuplicatedRangesForInjected(@NotNull List<HighlightInfo> infos) {
infos = new ArrayList<>(infos);
infos.sort((o1, o2) -> {
int i = o1.startOffset - o2.startOffset;
return i != 0 ? i : o1.getSeverity().myVal - o2.getSeverity().myVal;
});
HighlightInfo prevInfo = null;
for (Iterator<? extends HighlightInfo> it = infos.iterator(); it.hasNext();) {
HighlightInfo info = it.next();
if (prevInfo != null &&
info.getSeverity() == HighlightInfoType.SYMBOL_TYPE_SEVERITY &&
info.getDescription() == null &&
info.startOffset == prevInfo.startOffset &&
info.endOffset == prevInfo.endOffset) {
it.remove();
}
prevInfo = info.type == HighlightInfoType.INJECTED_LANGUAGE_FRAGMENT ? info : null;
}
return infos;
}
@TestOnly
public static @NotNull @Unmodifiable List<HighlightInfo> instantiateAndRun(@NotNull PsiFile file,
@NotNull Editor editor,
int @NotNull [] toIgnore,
boolean canChangeDocument) {
return instantiateAndRun(file, editor, toIgnore, canChangeDocument, false);
}
@TestOnly
public static @NotNull @Unmodifiable List<HighlightInfo> instantiateAndRun(@NotNull PsiFile psiFile,
@NotNull Editor editor,
int @NotNull [] toIgnore,
boolean canChangeDocument,
boolean readEditorMarkupModel) {
SmartPsiElementPointer<PsiFile> filePointer = ReadAction.compute(() -> SmartPointerManager.createPointer(psiFile));
Project project = psiFile.getProject();
ensureIndexesUpToDate(project);
VirtualFile virtualFile = filePointer.getVirtualFile();
if (!ReadAction.compute(() -> ProblemHighlightFilter.shouldHighlightFile(Objects.requireNonNull(filePointer.getElement())))) {
boolean inSource = ReadAction.compute(() -> ProjectRootManager.getInstance(project).getFileIndex().isInSource(virtualFile));
throw new IllegalStateException("ProblemHighlightFilter.shouldHighlightFile('" + filePointer.getElement() + "') == false, so can't highlight it." +
(inSource ? "" : " Maybe it's because " + virtualFile+ " is outside source folders? (source folders: " +
ReadAction.compute(() -> Arrays.toString(ProjectRootManager.getInstance(project).getContentSourceRoots()))+")"));
}
DaemonCodeAnalyzerImpl codeAnalyzer = (DaemonCodeAnalyzerImpl)DaemonCodeAnalyzer.getInstance(project);
TextEditor textEditor = TextEditorProvider.getInstance().getTextEditor(editor);
DaemonCodeAnalyzerSettings settings = DaemonCodeAnalyzerSettings.getInstance();
ProjectInspectionProfileManager.getInstance(project); // avoid "severities changed, restart" event
Throwable exception = null;
int retries = 1000;
for (int i = 0; i < retries; i++) {
try {
settings.forceUseZeroAutoReparseDelay(true);
List<HighlightInfo> infos = new ArrayList<>();
EdtTestUtil.runInEdtAndWait(() -> {
PsiFile file = filePointer.getElement();
assertNotNull(file);
codeAnalyzer.runPasses(file, editor.getDocument(), textEditor, toIgnore, canChangeDocument, null);
IdeaTestExecutionPolicy policy = IdeaTestExecutionPolicy.current();
if (policy != null) {
policy.waitForHighlighting(project, editor);
}
IdentifierHighlighterPassFactory.waitForIdentifierHighlighting();
UIUtil.dispatchAllInvocationEvents();
Segment focusModeRange = (editor instanceof EditorImpl) ? ((EditorImpl)editor).getFocusModeRange() : null;
int startOffset = focusModeRange != null ? focusModeRange.getStartOffset() : 0;
int endOffset = focusModeRange != null ? focusModeRange.getEndOffset() : editor.getDocument().getTextLength();
DaemonCodeAnalyzerEx.processHighlights(editor.getDocument(), project, null, startOffset, endOffset,
Processors.cancelableCollectProcessor(infos));
if (readEditorMarkupModel) {
MarkupModelEx markupModel = (MarkupModelEx)editor.getMarkupModel();
DaemonCodeAnalyzerEx.processHighlights(markupModel, project, null, startOffset, endOffset,
Processors.cancelableCollectProcessor(infos));
}
});
return infos;
}
catch (ProcessCanceledException e) {
Throwable cause = e.getCause();
if (cause != null && cause != e && cause.getClass() != Throwable.class) {
// canceled because of an exception, no need to repeat the same
exception = cause;
break;
}
exception = e;
EdtTestUtil.runInEdtAndWait(() -> {
PsiDocumentManager.getInstance(project).commitAllDocuments();
UIUtil.dispatchAllInvocationEvents();
});
}
catch (Exception e) {
exception = e;
}
finally {
settings.forceUseZeroAutoReparseDelay(false);
}
}
ExceptionUtil.rethrow(exception);
throw new AssertionError("Unable to highlight after " + retries + " retries", exception);
}
public static void ensureIndexesUpToDate(@NotNull Project project) {
IndexingTestUtil.waitUntilIndexesAreReady(project);
if (!DumbService.isDumb(project)) {
ReadAction.run(() -> {
for (FileBasedIndexExtension<?,?> extension : FileBasedIndexExtension.EXTENSION_POINT_NAME.getExtensionList()) {
FileBasedIndex.getInstance().ensureUpToDate(extension.getName(), project, null);
}
});
}
}
@TestOnly
public static @NotNull @Unmodifiable List<IntentionAction> getAvailableIntentions(@NotNull Editor editor, @NotNull PsiFile file) {
IdeaTestExecutionPolicy current = IdeaTestExecutionPolicy.current();
if (current != null) {
current.waitForHighlighting(file.getProject(), editor);
}
waitForUnresolvedReferencesQuickFixesUnderCaret(file, editor);
List<IntentionAction> result = new ArrayList<>();
ApplicationManager.getApplication().invokeAndWait(() -> {
IntentionListStep intentionListStep = getIntentionListStep(editor, file);
for (Map.Entry<IntentionAction, List<IntentionAction>> entry : intentionListStep.getActionsWithSubActions().entrySet()) {
result.add(entry.getKey());
result.addAll(entry.getValue());
}
});
return result;
}
@RequiresEdt
private static @NotNull IntentionListStep getIntentionListStep(@NotNull Editor editor, @NotNull PsiFile file) {
CachedIntentions cachedIntentions = ShowIntentionActionsHandler.calcCachedIntentions(file.getProject(), editor, file);
return new IntentionListStep(null, editor, file, file.getProject(), cachedIntentions);
}
public static void waitForUnresolvedReferencesQuickFixesUnderCaret(@NotNull PsiFile file, @NotNull Editor editor) {
if (ApplicationManager.getApplication().isDispatchThread()) {
assert !ApplicationManager.getApplication().isWriteAccessAllowed(): "must not call under write action";
Future<?> future = ApplicationManager.getApplication().executeOnPooledThread(() -> {
if (!ReadAction.compute(() -> file.getProject().isDisposed() || editor.isDisposed())) {
DaemonCodeAnalyzerImpl.waitForUnresolvedReferencesQuickFixesUnderCaret(file, editor);
}
});
try {
while (!future.isDone()) {
try {
future.get(10, TimeUnit.MILLISECONDS);
}
catch (TimeoutException ignored) {
}
UIUtil.dispatchAllInvocationEvents();
}
future.get();
}
catch (InterruptedException | ExecutionException e) {
throw new RuntimeException(e);
}
}
else {
DaemonCodeAnalyzerImpl.waitForUnresolvedReferencesQuickFixesUnderCaret(file, editor);
}
}
@Override
public @NotNull String getTempDirPath() {
return myTempDirFixture.getTempDirPath();
}
@Override
public @NotNull TempDirTestFixture getTempDirFixture() {
return myTempDirFixture;
}
@Override
public @NotNull VirtualFile copyFileToProject(@NotNull String sourcePath) {
return copyFileToProject(sourcePath, sourcePath);
}
@Override
public @NotNull VirtualFile copyFileToProject(@NotNull String sourcePath, @NotNull String targetPath) {
String testDataPath = getTestDataPath();
File sourceFile = new File(testDataPath, toSystemDependentName(sourcePath));
if (!sourceFile.exists()) {
File candidate = new File(sourcePath);
if (candidate.isAbsolute()) {
sourceFile = candidate;
if (FileUtil.pathsEqual(targetPath, sourcePath)) {
Path testDataPathObj = Paths.get(testDataPath);
Path targetPathObj = Paths.get(targetPath);
if (targetPathObj.startsWith(testDataPathObj) && !targetPathObj.equals(testDataPathObj)) {
targetPath = testDataPathObj.relativize(targetPathObj).toString();
}
else {
throw new IllegalArgumentException("Cannot guess target path for '" + sourcePath + "'; please specify explicitly");
}
}
}
}
targetPath = FileUtil.toSystemIndependentName(targetPath);
VirtualFile targetFile = myTempDirFixture.getFile(targetPath);
if (!sourceFile.exists() && targetFile != null && targetPath.equals(sourcePath)) {
return targetFile;
}
assertFileEndsWithCaseSensitivePath(sourceFile);
assertTrue("Cannot find source file: " + sourceFile + "; test data path: " + testDataPath+"; sourcePath: "+sourcePath, sourceFile.exists());
assertTrue("Not a file: " + sourceFile, sourceFile.isFile());
if (targetFile == null) {
targetFile = myTempDirFixture.createFile(targetPath);
VfsTestUtil.assertFilePathEndsWithCaseSensitivePath(targetFile, sourcePath);
targetFile.putUserData(VfsTestUtil.TEST_DATA_FILE_PATH, sourceFile.getAbsolutePath());
}
copyContent(sourceFile, targetFile);
IndexingTestUtil.waitUntilIndexesAreReady(getProject());
return targetFile;
}
private static void assertFileEndsWithCaseSensitivePath(@NotNull File sourceFile) {
try {
String sourceName = sourceFile.getPath();
File realFile = sourceFile.getCanonicalFile();
String realFileName = realFile.getPath();
if (!sourceName.equals(realFileName) && sourceName.equalsIgnoreCase(realFileName)) {
fail("Please correct case-sensitivity of path to prevent test failure on case-sensitive file systems:\n" +
" path " + sourceFile.getPath() + "\n" +
"real path " + realFile.getPath());
}
}
catch (IOException e) {
throw new UncheckedIOException("sourceFile="+sourceFile, e);
}
}
private static void copyContent(@NotNull File sourceFile, @NotNull VirtualFile targetFile) {
try {
WriteAction.runAndWait(() -> {
targetFile.setBinaryContent(FileUtil.loadFileBytes(sourceFile));
// update the document now, otherwise MemoryDiskConflictResolver will do it later at unexpected moment of time
FileDocumentManager.getInstance().reloadFiles(targetFile);
});
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public @NotNull VirtualFile copyDirectoryToProject(@NotNull String sourcePath, @NotNull String targetPath) {
String testDataPath = getTestDataPath();
File fromFile = new File(testDataPath + "/" + sourcePath);
if (myTempDirFixture instanceof LightTempDirTestFixtureImpl) {
VirtualFile file = myTempDirFixture.copyAll(fromFile.getPath(), targetPath);
IndexingTestUtil.waitUntilIndexesAreReady(getProject());
return file;
}
File targetFile = new File(getTempDirPath() + "/" + targetPath);
try {
FileUtil.copyDir(fromFile, targetFile);
}
catch (IOException e) {
throw new RuntimeException(e);
}
VirtualFile file = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(targetFile);
assertNotNull(file);
file.refresh(false, true);
IndexingTestUtil.waitUntilIndexesAreReady(getProject());
IdeaTestExecutionPolicy policy = IdeaTestExecutionPolicy.current();
if (policy != null) {
PsiDirectory directory = ReadAction.compute(() -> PsiManager.getInstance(getProject()).findDirectory(file));
assertNotNull(directory);
policy.testDirectoryConfigured(directory);
}
return file;
}
@Override
public void enableInspections(InspectionProfileEntry @NotNull ... inspections) {
assertInitialized();
InspectionsKt.enableInspectionTools(getProject(), myProjectFixture.getTestRootDisposable(), inspections);
}
@SafeVarargs
@Override
public final void enableInspections(Class<? extends LocalInspectionTool> @NotNull ... inspections) {
enableInspections(Arrays.asList(inspections));
}
@Override
public void enableInspections(@NotNull Collection<Class<? extends LocalInspectionTool>> inspections) {
List<InspectionProfileEntry> tools = InspectionTestUtil.instantiateTools(inspections);
enableInspections(tools.toArray(new InspectionProfileEntry[0]));
}
@Override
public void disableInspections(InspectionProfileEntry @NotNull ... inspections) {
InspectionsKt.disableInspections(getProject(), inspections);
}
@Override
public void enableInspections(InspectionToolProvider @NotNull ... providers) {
List<Class<? extends LocalInspectionTool>> classes = Stream.of(providers)
.flatMap(p -> Stream.of(p.getInspectionClasses()))
.filter(LocalInspectionTool.class::isAssignableFrom)
.collect(Collectors.toList());
enableInspections(classes);
}
@Override
public long testHighlighting(boolean checkWarnings, boolean checkInfos, boolean checkWeakWarnings, String @NotNull ... filePaths) {
if (filePaths.length > 0) {
configureByFilesInner(filePaths);
}
return collectAndCheckHighlighting(checkWarnings, checkInfos, checkWeakWarnings);
}
@Override
public long testHighlightingAllFiles(boolean checkWarnings, boolean checkInfos, boolean checkWeakWarnings, String @NotNull ... paths) {
return collectAndCheckHighlighting(checkWarnings, checkInfos, checkWeakWarnings, Stream.of(paths).map(this::copyFileToProject));
}
@Override
public long testHighlightingAllFiles(boolean checkWarnings,
boolean checkInfos,
boolean checkWeakWarnings,
VirtualFile @NotNull ... files) {
return collectAndCheckHighlighting(checkWarnings, checkInfos, checkWeakWarnings, Stream.of(files));
}
private long collectAndCheckHighlighting(boolean checkWarnings,
boolean checkInfos,
boolean checkWeakWarnings,
@NotNull Stream<? extends VirtualFile> files) {
record FileHighlighting(PsiFile file, Editor editor, ExpectedHighlightingData data) {}
List<FileHighlighting> data = files.map(file -> {
PsiFile psiFile = myPsiManager.findFile(file);
assertNotNull(psiFile);
Document document = PsiDocumentManager.getInstance(getProject()).getDocument(psiFile);
assertNotNull(document);
ExpectedHighlightingData datum =
new ExpectedHighlightingData(document, checkWarnings, checkWeakWarnings, checkInfos, false);
datum.init();
return new FileHighlighting(psiFile, createEditor(file), datum);
}).toList();
long elapsed = 0;
for (FileHighlighting highlighting : data) {
setFileAndEditor(highlighting.file().getVirtualFile(), highlighting.editor());
elapsed += collectAndCheckHighlighting(highlighting.data());
}
return elapsed;
}
@Override
public long checkHighlighting(boolean checkWarnings, boolean checkInfos, boolean checkWeakWarnings) {
return checkHighlighting(checkWarnings, checkInfos, checkWeakWarnings, false);
}
@Override
public long checkHighlighting(boolean checkWarnings, boolean checkInfos, boolean checkWeakWarnings, boolean ignoreExtraHighlighting) {
return collectAndCheckHighlighting(checkWarnings, checkInfos, checkWeakWarnings, ignoreExtraHighlighting);
}
@Override
public long checkHighlighting() {
return checkHighlighting(true, false, true);
}
@Override
public long testHighlighting(String @NotNull ... filePaths) {
return testHighlighting(true, false, true, filePaths);
}
@Override
public long testHighlighting(boolean checkWarnings, boolean checkInfos, boolean checkWeakWarnings, @NotNull VirtualFile file) {
openFileInEditor(file);
return collectAndCheckHighlighting(checkWarnings, checkInfos, checkWeakWarnings);
}
@Override
public @NotNull HighlightTestInfo testFile(String @NotNull ... filePath) {
return new HighlightTestInfo(myProjectFixture.getTestRootDisposable(), filePath) {
@Override
public HighlightTestInfo doTest() {
configureByFiles(filePaths);
ExpectedHighlightingData data =
new ExpectedHighlightingData(editor.getDocument(), checkWarnings, checkWeakWarnings, checkInfos, false);
if (checkSymbolNames) data.checkSymbolNames();
data.init();
collectAndCheckHighlighting(data);
return this;
}
};
}
@Override
public void openFileInEditor(@NotNull VirtualFile file) {
setFileAndEditor(file, createEditor(file));
}
@Override
public void testInspection(@NotNull String testDir, @NotNull InspectionToolWrapper<?,?> toolWrapper) {
VirtualFile sourceDir = copyDirectoryToProject(new File(testDir, "src").getPath(), "");
testInspection(testDir, toolWrapper, sourceDir);
}
@Override
public void testInspection(@NotNull String testDir, @NotNull InspectionToolWrapper<?, ?> toolWrapper, @NotNull VirtualFile sourceDir) {
PsiDirectory psiDirectory = getPsiManager().findDirectory(sourceDir);
assertNotNull(psiDirectory);
AnalysisScope scope = new AnalysisScope(psiDirectory);
scope.invalidate();
GlobalInspectionContextForTests globalContext =
InspectionsKt.createGlobalContextForTool(scope, getProject(), Collections.<InspectionToolWrapper<?, ?>>singletonList(toolWrapper));
InspectionTestUtil.runTool(toolWrapper, scope, globalContext);
InspectionTestUtil.compareToolResults(globalContext, toolWrapper, false, new File(getTestDataPath(), testDir).getPath());
}
@Override
public @NotNull PsiSymbolReference findSingleReferenceAtCaret() {
PsiFile file = getFile();
assertNotNull(file);
return assertOneElement(ReferencesKt.referencesAt(file, getCaretOffset()));
}
@Override
public @Nullable PsiReference getReferenceAtCaretPosition(String @NotNull ... filePaths) {
if (filePaths.length > 0) {
configureByFilesInner(filePaths);
}
return ReadAction.compute(() -> getFile().findReferenceAt(editor.getCaretModel().getOffset()));
}
@Override
public @NotNull PsiReference getReferenceAtCaretPositionWithAssertion(String @NotNull ... filePaths) {
PsiReference reference = getReferenceAtCaretPosition(filePaths);
assertNotNull("no reference found at " + editor.getCaretModel().getLogicalPosition(), reference);
return reference;
}
@Override
public @NotNull List<IntentionAction> getAvailableIntentions(String @NotNull ... filePaths) {
if (filePaths.length > 0) {
configureByFilesInner(filePaths);
}
return getAvailableIntentions();
}
@Override
public @NotNull List<IntentionAction> getAllQuickFixes(String @NotNull ... filePaths) {
if (filePaths.length != 0) {
configureByFilesInner(filePaths);
}
return myEditorTestFixture.getAllQuickFixes();
}
@Override
public @NotNull List<IntentionAction> getAvailableIntentions() {
doHighlighting();
return getAvailableIntentions(ReadAction.compute(() -> getHostEditor()), ReadAction.compute(() -> getHostFileAtCaret()));
}
private @NotNull Editor getHostEditor() {
return InjectedLanguageEditorUtil.getTopLevelEditor(getEditor());
}
private @NotNull PsiFile getHostFileAtCaret() {
return Objects.requireNonNull(PsiUtilBase.getPsiFileInEditor(getHostEditor(), getProject()));
}
@Override
public @NotNull @Unmodifiable List<IntentionAction> filterAvailableIntentions(@NotNull String hint) {
return ContainerUtil.filter(getAvailableIntentions(), action -> action.getText().startsWith(hint));
}
@Override
public @NotNull IntentionAction findSingleIntention(@NotNull String hint) {
List<IntentionAction> list = filterAvailableIntentions(hint);
if (list.isEmpty()) {
fail("\"" + hint + "\" not in [" + StringUtil.join(getAvailableIntentions(), INTENTION_NAME_FUN, ", ") + "]");
}
else if (list.size() > 1) {
fail("Too many intentions found for \"" + hint + "\": [" + StringUtil.join(list, INTENTION_NAME_FUN, ", ") + "]");
}
return assertOneElement(list);
}
@Override
public IntentionAction getAvailableIntention(@NotNull String intentionName, String @NotNull ... filePaths) {
List<IntentionAction> intentions = getAvailableIntentions(filePaths);
IntentionAction action = CodeInsightTestUtil.findIntentionByText(intentions, intentionName);
if (action == null) {
LOG.debug(intentionName + " not found among " + StringUtil.join(intentions, IntentionAction::getText, ","));
}
return action;
}
@Override
public void checkPreviewAndLaunchAction(@NotNull IntentionAction action) {
if (skipPreview(action)) {
launchAction(action);
} else {
String text = getIntentionPreviewText(action);
assertNotNull(action.getText(), text);
launchAction(action);
NonBlockingReadActionImpl.waitForAsyncTaskCompletion();
assertEquals(action.getText(), InjectedLanguageManager.getInstance(getProject()).getTopLevelFile(getFile()).getText(), text);
}
}
private static boolean skipPreview(@NotNull IntentionAction action) {
return IntentionActionDelegate.unwrap(action) instanceof CleanupInspectionIntention;
}
@Override
public @Nullable String getIntentionPreviewText(@NotNull IntentionAction action) {
// Run in background thread to catch accidental write-actions during preview generation
try {
return ReadAction.nonBlocking(() -> IntentionPreviewPopupUpdateProcessor.getPreviewText(getProject(), action, getFile(), getEditor()))
.submit(AppExecutorUtil.getAppExecutorService()).get();
}
catch (InterruptedException | ExecutionException e) {
throw new RuntimeException(e);
}
}
@Override
public @Nullable String getIntentionPreviewText(@NotNull String hint) {
IntentionActionWithTextCaching action = findCachingAction(hint);
if (action == null) return null;
IntentionPreviewInfo info =
IntentionPreviewPopupUpdateProcessor.getPreviewInfo(getProject(), action.getAction(), getFile(), getEditor(), action.getFixOffset());
return info == IntentionPreviewInfo.EMPTY ? null : ((IntentionPreviewDiffResult)info).getNewText();
}
@Override
public void launchAction(@NotNull String hint) {
IntentionActionWithTextCaching action = findCachingAction(hint);
if (action == null) throw new IllegalArgumentException();
ShowIntentionActionsHandler.chooseActionAndInvoke(getHostFile(), getHostEditor(), action.getAction(), action.getText(),
action.getFixOffset(), IntentionSource.CONTEXT_ACTIONS);
}
private @Nullable IntentionActionWithTextCaching findCachingAction(@NotNull String hint) {
doHighlighting();
List<IntentionActionWithTextCaching> list = getIntentionListStep(getEditor(), getFile()).getValues();
return ContainerUtil.find(list, caching -> caching.getAction().getText().startsWith(hint));
}
@Override
public void checkIntentionPreviewHtml(@NotNull IntentionAction action, @NotNull @Language("HTML") String expected) {
// Run in background thread to catch accidental write-actions during preview generation
IntentionPreviewInfo info;
try {
info = ReadAction.nonBlocking(() -> IntentionPreviewPopupUpdateProcessor.getPreviewInfo(getProject(), action, getFile(), getEditor()))
.submit(AppExecutorUtil.getAppExecutorService()).get();
}
catch (InterruptedException | ExecutionException e) {
throw new RuntimeException(e);
}
assertTrue(action.getText(), info instanceof IntentionPreviewInfo.Html);
assertEquals(action.getText(), expected, ((IntentionPreviewInfo.Html)info).content().toString());
}
@Override
public void launchAction(@NotNull IntentionAction action) {
EdtTestUtil.runInEdtAndWait(() -> invokeIntention(action, getHostFileAtCaret(), getHostEditor()));
}
@Override
public void testCompletion(String @NotNull [] filesBefore, @NotNull @TestDataFile String fileAfter) {
testCompletionTyping(filesBefore, "", fileAfter);
}
@Override
public void testCompletionTyping(String @NotNull [] filesBefore, @NotNull String toType, @NotNull String fileAfter) {
assertInitialized();
configureByFiles(filesBefore);
complete(CompletionType.BASIC);
type(toType);
try {
checkResultByFile(fileAfter);
}
catch (RuntimeException e) {
//noinspection UseOfSystemOutOrSystemErr
System.out.println("LookupElementStrings = " + getLookupElementStrings());
throw e;
}
}
protected void assertInitialized() {
assertNotNull("setUp() hasn't been called", myPsiManager);
}
@Override
public void testCompletion(@NotNull String fileBefore,
@NotNull String fileAfter,
@TestDataFile String @NotNull ... additionalFiles) {
testCompletionTyping(fileBefore, "", fileAfter, additionalFiles);
}
@Override
public void testCompletionTyping(@NotNull @TestDataFile String fileBefore,
@NotNull String toType,
@NotNull @TestDataFile String fileAfter,
@TestDataFile String @NotNull ... additionalFiles) {
testCompletionTyping(ArrayUtil.reverseArray(ArrayUtil.append(additionalFiles, fileBefore)), toType, fileAfter);
}
@Override
public void testCompletionVariants(@NotNull String fileBefore, String @NotNull ... expectedItems) {
assertInitialized();
List<String> result = getCompletionVariants(fileBefore);
assertNotNull(result);
UsefulTestCase.assertSameElements(result, expectedItems);
}
@Override
public @Unmodifiable List<String> getCompletionVariants(String @NotNull ... filesBefore) {
assertInitialized();
configureByFiles(filesBefore);
LookupElement[] items = complete(CompletionType.BASIC);
assertNotNull("No lookup was shown, probably there was only one lookup element that was inserted automatically", items);
return getLookupElementStrings();
}
@Override
public @Nullable @Unmodifiable List<String> getLookupElementStrings() {
assertInitialized();
return myEditorTestFixture.getLookupElementStrings();
}
@Override
public void finishLookup(char completionChar) {
myEditorTestFixture.finishLookup(completionChar);
}
@Override
public void testRename(@NotNull String fileBefore,
@NotNull String fileAfter,
@NotNull String newName,
@TestDataFile String @NotNull ... additionalFiles) {
assertInitialized();
configureByFiles(ArrayUtil.reverseArray(ArrayUtil.append(additionalFiles, fileBefore)));
testRename(fileAfter, newName);
}
@Override
public void testRenameUsingHandler(@NotNull String fileBefore,
@NotNull String fileAfter,
@NotNull String newName,
String @NotNull ... additionalFiles) {
assertInitialized();
configureByFiles(ArrayUtil.reverseArray(ArrayUtil.append(additionalFiles, fileBefore)));
testRenameUsingHandler(fileAfter, newName);
}
@Override
public void testRenameUsingHandler(@NotNull String fileAfter, @NotNull String newName) {
renameElementAtCaretUsingHandler(newName);
checkResultByFile(fileAfter);
}
@Override
public void testRename(@NotNull String fileAfter, @NotNull String newName) {
renameElementAtCaret(newName);
checkResultByFile(fileAfter);
}
@Override
public @NotNull PsiElement getElementAtCaret() {
assertInitialized();
return myEditorTestFixture.getElementAtCaret();
}
@Override
public void renameElementAtCaret(@NotNull String newName) {
renameElement(getElementAtCaret(), newName);
}
@Override
public void renameElementAtCaretUsingHandler(@NotNull String newName) {
DataContext editorContext = EditorUtil.getEditorDataContext(editor);
DataContext context = CustomizedDataContext.withSnapshot(editorContext, sink -> {
sink.set(PsiElementRenameHandler.DEFAULT_NAME, newName);
});
RenameHandler renameHandler = RenameHandlerRegistry.getInstance().getRenameHandler(context);
assertNotNull("No handler for this context", renameHandler);
renameHandler.invoke(getProject(), editor, getFile(), context);
}
@Override
public void renameElement(@NotNull PsiElement element, @NotNull String newName) {
final boolean searchInComments = false;
final boolean searchTextOccurrences = false;
renameElement(element, newName, searchInComments, searchTextOccurrences);
}
@Override
public void renameElement(@NotNull PsiElement element,
@NotNull String newName,
boolean searchInComments,
boolean searchTextOccurrences) {
PsiElement substitution = RenamePsiElementProcessor.forElement(element).substituteElementToRename(element, editor);
if (substitution == null) return;
new RenameProcessor(getProject(), substitution, newName, searchInComments, searchTextOccurrences).run();
}
@Override
public void renameTarget(@NotNull RenameTarget renameTarget, @NotNull String newName) {
RenameKt.renameAndWait(getProject(), renameTarget, newName);
}
@Override
public <T extends PsiElement> T findElementByText(@NotNull String text, @NotNull Class<T> elementClass) {
return myEditorTestFixture.findElementByText(text, elementClass);
}
@Override
public void type(char c) {
assertInitialized();
myEditorTestFixture.type(c);
}
@Override
public void type(@NotNull String s) {
myEditorTestFixture.type(s);
}
@Override
public void performEditorAction(@NotNull String actionId, @Nullable AnActionEvent actionEvent) {
assertInitialized();
EdtTestUtil.runInEdtAndWait(() -> myEditorTestFixture.performEditorAction(actionId, actionEvent));
}
@Override
public @NotNull Presentation testAction(@NotNull AnAction action) {
AnActionEvent e = TestActionEvent.createTestEvent(action);
ActionUtil.performDumbAwareUpdate(action, e, false);
if (e.getPresentation().isEnabled()) {
ActionUtil.performActionDumbAwareWithCallbacks(action, e);
}
return e.getPresentation();