1 // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
2 package com.intellij.java.codeInsight.completion
4 import com.intellij.codeInsight.CodeInsightSettings
5 import com.intellij.codeInsight.JavaProjectCodeInsightSettings
6 import com.intellij.codeInsight.completion.CompletionType
7 import com.intellij.codeInsight.completion.JavaPsiClassReferenceElement
8 import com.intellij.codeInsight.lookup.Lookup
9 import com.intellij.codeInsight.lookup.LookupElement
10 import com.intellij.codeInsight.lookup.LookupElementPresentation
11 import com.intellij.codeInsight.lookup.LookupManager
12 import com.intellij.codeInsight.lookup.impl.LookupImpl
13 import com.intellij.lang.java.JavaLanguage
14 import com.intellij.openapi.actionSystem.IdeActions
15 import com.intellij.psi.PsiClass
16 import com.intellij.psi.PsiDocumentManager
17 import com.intellij.psi.PsiMethod
18 import com.intellij.psi.PsiTypeParameter
19 import com.intellij.psi.codeStyle.CodeStyleSettingsManager
20 import com.intellij.psi.codeStyle.CommonCodeStyleSettings
21 import com.intellij.psi.codeStyle.JavaCodeStyleSettings
22 import com.intellij.testFramework.LightProjectDescriptor
23 import com.intellij.testFramework.NeedsIndex
24 import com.intellij.testFramework.PlatformTestUtil
25 import com.intellij.util.ui.UIUtil
26 import com.siyeh.ig.style.UnqualifiedFieldAccessInspection
27 import groovy.transform.CompileStatic
28 import org.jetbrains.annotations.NotNull
31 class NormalCompletionTest extends NormalCompletionTestCase {
35 protected LightProjectDescriptor getProjectDescriptor() {
39 void testSimple() throws Exception {
40 configureByFile("Simple.java")
41 assertStringItems("_local1", "_local2", "_field", "_baseField", "_method", "_baseMethod")
44 void testCastToPrimitive1() throws Exception {
45 configureByFile("CastToPrimitive1.java")
47 for (final LookupElement item : myItems) {
48 if (item.getLookupString().equals("int")) return
53 void testCastToPrimitive2() throws Exception {
54 configureByFile("CastToPrimitive2.java")
56 for (final LookupElement item : myItems) {
57 if (item.getLookupString().equals("int")) return
62 void testCastToPrimitive3() throws Exception {
63 configureByFile("CastToPrimitive3.java")
65 for (final LookupElement item : myItems) {
66 if (item.getLookupString().equals("int")) return
71 void testWriteInInvokeLater() throws Exception {
72 configureByFile("WriteInInvokeLater.java")
75 void testQualifiedNew1() throws Exception {
77 assertStringItems "IInner", "Inner"
80 void testQualifiedNew2() throws Exception {
82 assertStringItems "AnInner", "Inner"
85 void testKeywordsInName() throws Exception {
89 @NeedsIndex.ForStandardLibrary
90 void testSimpleVariable() throws Exception { doTest('\n') }
92 void testTypeParameterItemPresentation() {
94 LookupElementPresentation presentation = renderElement(myItems[0])
95 assert "Param" == presentation.itemText
96 assert presentation.tailText == " type parameter of Foo"
97 assert !presentation.typeText
98 assert !presentation.icon
99 assert !presentation.itemTextBold
101 presentation = renderElement(myItems[1])
102 assert "Param2" == presentation.itemText
103 assert presentation.tailText == " type parameter of goo"
106 void testDisplayDefaultValueInAnnotationMethods() {
108 LookupElementPresentation presentation = renderElement(myItems[0])
109 assert "myInt" == presentation.itemText
110 assert presentation.tailText == " default 42"
111 assert presentation.tailFragments[0].grayed
112 assert !presentation.typeText
113 assert !presentation.itemTextBold
115 presentation = renderElement(myItems[1])
116 assert "myString" == presentation.itemText
117 assert presentation.tailText == ' default "unknown"'
120 @NeedsIndex.ForStandardLibrary
121 void testMethodItemPresentation() {
123 LookupElementPresentation presentation = renderElement(myItems[0])
124 assert "equals" == presentation.itemText
125 assert "(Object anObject)" == presentation.tailText
126 assert "boolean" == presentation.typeText
128 assert !presentation.tailFragments.any { it.grayed }
129 assert presentation.itemTextBold
132 void testFieldItemPresentationGenerics() {
134 LookupElementPresentation presentation = renderElement(myItems[0])
135 assert "target" == presentation.itemText
136 assert !presentation.tailText
137 assert "String" == presentation.typeText
140 @NeedsIndex.ForStandardLibrary
141 void testMethodItemPresentationGenerics() {
143 LookupElementPresentation presentation = renderElement(myItems[1])
144 assert "add" == presentation.itemText
145 assert "(int index, String element)" == presentation.tailText
146 assert "void" == presentation.typeText
148 presentation = renderElement(myItems[0])
149 assert "(String e)" == presentation.tailText
150 assert "boolean" == presentation.typeText
152 assert !presentation.tailFragments.any { it.grayed }
153 assert presentation.itemTextBold
156 void testPreferLongerNamesOption() throws Exception {
157 configureByFile("PreferLongerNamesOption.java")
159 assertEquals(3, myItems.length)
160 assertEquals("abcdEfghIjk", myItems[0].getLookupString())
161 assertEquals("efghIjk", myItems[1].getLookupString())
162 assertEquals("ijk", myItems[2].getLookupString())
164 LookupManager.getInstance(getProject()).hideActiveLookup()
166 JavaCodeStyleSettings.getInstance(getProject()).PREFER_LONGER_NAMES = false
167 configureByFile("PreferLongerNamesOption.java")
169 assertEquals(3, myItems.length)
170 assertEquals("ijk", myItems[0].getLookupString())
171 assertEquals("efghIjk", myItems[1].getLookupString())
172 assertEquals("abcdEfghIjk", myItems[2].getLookupString())
175 void testSCR7208() throws Exception {
176 configureByFile("SCR7208.java")
179 @NeedsIndex.ForStandardLibrary
180 void testProtectedFromSuper() throws Exception {
181 configureByFile("ProtectedFromSuper.java")
183 assertTrue("Exception not found", Arrays.binarySearch(myItems, "xxx") > 0)
186 @NeedsIndex.ForStandardLibrary
187 void testBeforeInitialization() throws Exception {
188 configureByFile("BeforeInitialization.java")
189 assertNotNull(myItems)
190 assertTrue(myItems.length > 0)
193 @NeedsIndex.ForStandardLibrary
194 void testProtectedFromSuper2() throws Exception {
196 configureByFile("ProtectedFromSuper.java")
198 assertTrue("Exception not found", Arrays.binarySearch(myItems, "xxx") > 0)
201 void testClassLiteralInArrayAnnoInitializer() throws Throwable { doTest() }
203 void testClassLiteralInArrayAnnoInitializer2() throws Throwable { doTest() }
205 void testReferenceParameters() throws Exception {
206 configureByFile("ReferenceParameters.java")
207 assertNotNull(myItems)
208 myFixture.assertPreferredCompletionItems 0, 'AAAA', 'AAAB'
212 protected void tearDown() throws Exception {
213 CodeInsightSettings.instance.AUTOCOMPLETE_ON_CODE_COMPLETION = true
214 CodeInsightSettings.instance.setCompletionCaseSensitive(CodeInsightSettings.FIRST_LETTER)
215 CodeInsightSettings.getInstance().AUTOINSERT_PAIR_BRACKET = true
219 void testConstructorName1() throws Exception {
220 CodeInsightSettings.getInstance().AUTOCOMPLETE_ON_CODE_COMPLETION = false
222 assert 'ABCDE' in myFixture.lookupElementStrings
225 void testConstructorName2() throws Exception {
226 CodeInsightSettings.getInstance().AUTOCOMPLETE_ON_CODE_COMPLETION = false
228 assert 'ABCDE' in myFixture.lookupElementStrings
231 @NeedsIndex.ForStandardLibrary
232 void testObjectsInThrowsBlock() throws Exception {
233 configureByFile("InThrowsCompletion.java")
234 assert "C" == myFixture.lookupElementStrings[0]
235 assert "B" in myFixture.lookupElementStrings
238 void testAnnoParameterValue() throws Exception {
240 def strings = myFixture.lookupElementStrings
241 assert 'AssertionError' in strings
242 assert !('enum' in strings)
243 assert !('final' in strings)
244 assert !('equals' in strings)
245 assert !('new' in strings)
246 assert !('null' in strings)
247 assert !('public' in strings)
248 assert !('super' in strings)
249 assert !('null' in strings)
252 void testAfterInstanceof() throws Exception {
253 configureByFile("AfterInstanceof.java")
254 assert "A" in myFixture.lookupElementStrings
257 void testAfterCast1() throws Exception {
258 configureByFile("AfterCast1.java")
260 assertNotNull(myItems)
261 assertEquals(2, myItems.length)
264 void testAfterCast2() throws Exception {
265 configureByFile("AfterCast2.java")
266 checkResultByFile("AfterCast2-result.java")
269 void testMethodCallForTwoLevelSelection() throws Exception {
270 configureByFile("MethodLookup.java")
271 assertEquals(2, myItems.length)
274 void testMethodCallBeforeAnotherStatementWithParen() throws Exception {
275 configureByFile("MethodLookup2.java")
276 checkResultByFile("MethodLookup2_After.java")
279 void testMethodCallBeforeAnotherStatementWithParen2() throws Exception {
280 codeStyleSettings.METHOD_PARAMETERS_LPAREN_ON_NEXT_LINE = true
281 configureByFile("MethodLookup2.java")
282 checkResultByFile("MethodLookup2_After2.java")
285 void testSwitchEnumLabel() throws Exception {
286 configureByFile("SwitchEnumLabel.java")
287 assertEquals(3, myItems.length)
290 void testSwitchCaseWithEnumConstant() { doTest() }
292 void testSecondSwitchCaseWithEnumConstant() { doTest() }
294 @NeedsIndex.ForStandardLibrary
295 void testInsideSwitchCaseWithEnumConstant() {
297 myFixture.assertPreferredCompletionItems 0, 'compareTo', 'equals'
300 void testMethodInAnnotation() throws Exception {
301 configureByFile("Annotation.java")
302 checkResultByFile("Annotation_after.java")
305 void testMethodInAnnotation2() throws Exception {
306 configureByFile("Annotation2.java")
307 checkResultByFile("Annotation2_after.java")
310 void testMethodInAnnotation3() throws Exception {
311 configureByFile("Annotation3.java")
312 checkResultByFile("Annotation3_after.java")
315 void testMethodInAnnotation5() throws Exception {
316 configureByFile("Annotation5.java")
317 checkResultByFile("Annotation5_after.java")
320 void testMethodInAnnotation7() throws Exception {
321 configureByFile("Annotation7.java")
322 selectItem(myItems[0])
323 checkResultByFile("Annotation7_after.java")
326 void testEnumInAnnotation() throws Exception {
327 configureByFile("Annotation4.java")
328 checkResultByFile("Annotation4_after.java")
331 void testSecondAttribute() throws Exception {
332 configureByFile("Annotation6.java")
333 checkResultByFile("Annotation6_after.java")
336 void testIDEADEV6408() throws Exception {
337 configureByFile("IDEADEV6408.java")
338 assertFirstStringItems "boolean", "byte"
341 void testMethodWithLeftParTailType() throws Exception {
342 configureByFile("MethodWithLeftParTailType.java")
344 checkResultByFile("MethodWithLeftParTailType_after.java")
346 configureByFile("MethodWithLeftParTailType2.java")
348 checkResultByFile("MethodWithLeftParTailType2_after.java")
351 void testSuperErasure() throws Exception {
352 configureByFile("SuperErasure.java")
353 checkResultByFile("SuperErasure_after.java")
356 void testMethodWithLeftParTailTypeNoPairBrace() throws Exception {
357 CodeInsightSettings.getInstance().AUTOINSERT_PAIR_BRACKET = false
361 void testMethodWithLeftParTailTypeNoPairBrace2() throws Exception {
362 CodeInsightSettings.getInstance().AUTOINSERT_PAIR_BRACKET = false
364 //no tail type should work the normal way
365 configureByFile("MethodWithLeftParTailTypeNoPairBrace.java")
366 selectItem(myItems[0])
367 checkResultByFile("MethodWithLeftParTailTypeNoPairBrace_after2.java")
370 void testMethodNoPairBrace() throws Exception {
371 CodeInsightSettings.getInstance().AUTOINSERT_PAIR_BRACKET = false
375 void testExcessSpaceInTypeCast() throws Throwable {
377 selectItem(myItems[0])
381 void testFieldType() { doTest() }
383 void testFieldOfLocalClass() {
385 assert renderElement(myItems[0]).itemText == 'field'
390 void testPackageInAnnoParam() throws Throwable {
394 void testAnonymousTypeParameter() throws Throwable { doTest() }
396 @NeedsIndex.ForStandardLibrary
397 void testClassLiteralInAnnoParam() throws Throwable {
401 @NeedsIndex.ForStandardLibrary
402 void testNoForceBraces() {
403 codeStyleSettings.IF_BRACE_FORCE = CommonCodeStyleSettings.FORCE_BRACES_ALWAYS
407 void testExcludeStringBuffer() throws Throwable {
408 JavaProjectCodeInsightSettings.setExcludedNames(project, myFixture.testRootDisposable, StringBuffer.name)
410 assert !('StringBuffer' in myFixture.lookupElementStrings)
414 void testExcludeInstanceInnerClasses() throws Throwable {
415 JavaProjectCodeInsightSettings.setExcludedNames(project, myFixture.testRootDisposable, "foo")
416 myFixture.addClass 'package foo; public class Outer { public class Inner {} }'
417 myFixture.addClass 'package bar; public class Inner {}'
419 assert 'bar.Inner' == ((JavaPsiClassReferenceElement)myFixture.lookupElements[0]).qualifiedName
420 assert myFixture.lookupElementStrings == ['Inner']
424 void testExcludedInstanceInnerClassCreation() throws Throwable {
425 JavaProjectCodeInsightSettings.setExcludedNames(project, myFixture.testRootDisposable, "foo")
426 myFixture.addClass 'package foo; public class Outer { public class Inner {} }'
427 myFixture.addClass 'package bar; public class Inner {}'
429 assert 'foo.Outer.Inner' == ((JavaPsiClassReferenceElement)myFixture.lookupElements[0]).qualifiedName
430 assert myFixture.lookupElementStrings == ['Inner']
434 void testExcludedInstanceInnerClassQualifiedReference() throws Throwable {
435 JavaProjectCodeInsightSettings.setExcludedNames(project, myFixture.testRootDisposable, "foo")
436 myFixture.addClass 'package foo; public class Outer { public class Inner {} }'
437 myFixture.addClass 'package bar; public class Inner {}'
439 assert 'foo.Outer.Inner' == ((JavaPsiClassReferenceElement)myFixture.lookupElements[0]).qualifiedName
440 assert myFixture.lookupElementStrings == ['Inner']
444 void testStaticMethodOfExcludedClass() {
445 JavaProjectCodeInsightSettings.setExcludedNames(project, myFixture.testRootDisposable, "foo")
446 myFixture.addClass 'package foo; public class Outer { public static void method() {} }'
448 assert myFixture.lookupElementStrings == ['method']
452 void testExcludeWildcards() {
453 JavaProjectCodeInsightSettings.setExcludedNames(project, myFixture.testRootDisposable, "foo.Outer.*1*")
454 myFixture.addClass '''
457 public static void method1() {}
458 public static void method2() {}
459 public static void method12() {}
460 public static void method42() {}
462 myFixture.configureByText 'a.java', 'class C {{ foo.Outer.m<caret> }}'
463 myFixture.completeBasic()
464 assert myFixture.lookupElementStrings == ['method2', 'method42']
467 @NeedsIndex.SmartMode(reason = "JavaGenerateMemberCompletionContributor.fillCompletionVariants works in smart mode only (for int hashCode lookup preventing autocompletion and additional \n)")
468 void testAtUnderClass() throws Throwable {
472 void testLocalClassName() throws Throwable { doTest() }
474 void testAssigningFieldForTheFirstTime() throws Throwable { doTest() }
476 void testClassTypeParameters() throws Throwable {
478 assert 'K' in myFixture.lookupElementStrings
481 void testClassTypeParametersGenericBounds() throws Throwable {
483 assert 'K' in myFixture.lookupElementStrings
486 @NeedsIndex.ForStandardLibrary
487 void testLocalClassTwice() throws Throwable {
489 assertOrderedEquals myFixture.lookupElementStrings, 'Zoooz', 'Zooooo', 'ZipOutputStream'
492 @NeedsIndex.ForStandardLibrary
493 void testLocalTopLevelConflict() throws Throwable {
495 assertOrderedEquals myFixture.lookupElementStrings, 'Zoooz', 'Zooooo', 'ZipOutputStream'
498 @NeedsIndex.ForStandardLibrary
499 void testFinalBeforeMethodCall() throws Throwable {
501 assertStringItems 'final', 'finalize'
504 void testMethodCallAfterFinally() { doTest() }
506 void testPrivateInAnonymous() throws Throwable { doTest() }
508 void testStaticMethodFromOuterClass() {
510 assertStringItems 'foo', 'A.foo', 'for'
511 assert renderElement(myItems[1]).itemText == 'A.foo'
512 selectItem(myItems[1])
516 void testInstanceMethodFromOuterClass() {
518 assertStringItems 'foo', 'A.this.foo', 'for'
519 assert renderElement(myItems[1]).itemText == 'A.this.foo'
520 selectItem(myItems[1])
524 void testMethodParenthesesSpaces() throws Throwable {
525 codeStyleSettings.SPACE_BEFORE_METHOD_CALL_PARENTHESES = true
526 codeStyleSettings.SPACE_WITHIN_METHOD_CALL_PARENTHESES = true
530 void testMethodParenthesesSpacesArgs() throws Throwable {
531 codeStyleSettings.SPACE_BEFORE_METHOD_CALL_PARENTHESES = true
532 codeStyleSettings.SPACE_WITHIN_METHOD_CALL_PARENTHESES = true
536 void testAtUnderClassNoModifiers() throws Throwable {
540 void testBreakInIfCondition() throws Throwable { doTest() }
542 void testAccessStaticViaInstance() throws Throwable { doTest() }
544 void testIfConditionLt() {
546 myFixture.assertPreferredCompletionItems 0, 'getAnnotationsAreaOffset'
549 @NeedsIndex.ForStandardLibrary(reason = "On emptly indices 'foo' is the only item, so is not filtered out in JavaCompletionProcessor.dispreferStaticAfterInstance")
550 void testAccessStaticViaInstanceSecond() throws Throwable {
552 assert !('foo' in myFixture.lookupElementStrings)
553 myFixture.complete(CompletionType.BASIC, 2)
554 myFixture.assertPreferredCompletionItems 0, 'foo'
559 void testAccessInstanceFromStaticSecond() throws Throwable {
561 myFixture.complete(CompletionType.BASIC, 2)
565 void testBreakLabel() {
566 myFixture.configureByText("a.java", """
568 foo: while (true) break <caret>
571 assert myFixture.lookupElementStrings == ['foo']
574 void testContinueLabel() {
575 myFixture.configureByText("a.java", """
577 foo: while (true) continue <caret>
580 assert myFixture.lookupElementStrings == ['foo']
583 void testContinueLabelTail() {
584 myFixture.configureByText("a.java", """
586 foo: while (true) con<caret>
589 myFixture.checkResult("""
591 foo: while (true) continue <caret>
595 @NeedsIndex.SmartMode(reason = "For now ConstructorInsertHandler.createOverrideRunnable doesn't work in dumb mode")
596 void testAnonymousProcess() {
597 myFixture.addClass 'package java.lang; public class Process {}'
598 myFixture.addClass '''
600 public class Process {}
601 interface Pred <A> { boolean predicate(A elem); }
602 public class ListUtils {
603 public static <A> List<A> filter(List<A> list, Pred<A> pred) {}
611 void testNoThisInComment() throws Throwable { doAntiTest() }
613 void testIncNull() throws Throwable {
615 checkResultByFile(getTestName(false) + ".java")
616 assert !('null' in myFixture.lookupElementStrings)
619 void testLastExpressionInFor() throws Throwable { doTest() }
621 void testOnlyKeywordsInsideSwitch() throws Throwable {
622 configureByFile(getTestName(false) + ".java")
623 assertStringItems("case", "default")
626 @NeedsIndex.ForStandardLibrary
627 void testBooleanLiterals() throws Throwable {
631 void testDoubleBooleanInParameter() throws Throwable {
633 assertFirstStringItems("boolean", "byte")
636 void testDoubleConstant() throws Throwable {
638 assertStringItems("Intf.XFOO", "XFOO")
641 void testNotOnlyKeywordsInsideSwitch() throws Throwable {
645 @NeedsIndex.ForStandardLibrary
646 void testChainedCallOnNextLine() throws Throwable {
647 configureByFile(getTestName(false) + ".java")
648 selectItem(myItems[0])
652 void testFinishWithDot() throws Throwable {
653 configureByFile(getTestName(false) + ".java")
658 void testEnclosingThis() throws Throwable { doTest() }
661 void testSeamlessConstant() throws Throwable {
662 configureByFile(getTestName(false) + ".java")
663 selectItem(myItems[0])
667 void testDefaultAnnoParam() throws Throwable { doTest() }
669 void testSpaceAfterLookupString() throws Throwable {
670 configureByFile(getTestName(false) + ".java")
672 assertNull(getLookup())
676 @NeedsIndex.ForStandardLibrary
677 void testNoSpaceInParensWithoutParams() throws Throwable {
678 codeStyleSettings.SPACE_WITHIN_METHOD_CALL_PARENTHESES = true
683 codeStyleSettings.SPACE_WITHIN_METHOD_CALL_PARENTHESES = false
687 @NeedsIndex.ForStandardLibrary
688 void testTwoSpacesInParensWithParams() throws Throwable {
689 codeStyleSettings.SPACE_WITHIN_METHOD_CALL_PARENTHESES = true
693 @NeedsIndex.ForStandardLibrary
694 void testQualifierAsPackage() throws Throwable {
695 configureByFile(getTestName(false) + ".java")
696 selectItem(myItems[0])
700 @NeedsIndex.ForStandardLibrary
701 void testQualifierAsPackage2() throws Throwable {
705 @NeedsIndex.ForStandardLibrary
706 void testQualifierAsPackage3() throws Throwable {
710 @NeedsIndex.ForStandardLibrary
711 void testPreselectEditorSelection() {
713 assert lookup.currentItem != myFixture.lookupElements[0]
714 assert 'finalize' == lookup.currentItem.lookupString
717 void testNoMethodsInNonStaticImports() {
719 assertStringItems("*")
722 @NeedsIndex.ForStandardLibrary
723 void testMembersInStaticImports() { doTest('\n') }
725 @NeedsIndex.ForStandardLibrary
726 void testPackageNamedVariableBeforeAssignment() throws Throwable {
730 void testInnerEnumConstant() throws Throwable { doTest('\n') }
732 void testNoExpectedReturnTypeDuplication() {
734 assert myFixture.lookupElementStrings == ['boolean', 'byte']
736 void testNoExpectedVoidReturnTypeDuplication() {
738 assert myFixture.lookupElementStrings == ['void']
741 void testNoExpectedArrayTypeDuplication() {
743 assert myFixture.lookupElementStrings == ['char']
746 void testShadowedTypeParameter() {
748 assert myFixture.lookupElementStrings == ['MyParam']
751 @NeedsIndex.ForStandardLibrary
752 void testMethodReturnType() { doTest('\n') }
754 void testMethodReturnTypeNoSpace() throws Throwable {
755 configureByFile(getTestName(false) + ".java")
756 selectItem(myItems[0])
760 void testEnumWithoutConstants() throws Throwable {
764 @NeedsIndex.ForStandardLibrary
765 void testDoWhileMethodCall() throws Throwable {
769 void testSecondTypeParameterExtends() throws Throwable {
773 @NeedsIndex.ForStandardLibrary
774 void testGetterWithExistingNonEmptyParameterList() throws Throwable {
778 void testNothingAfterNumericLiteral() throws Throwable { doAntiTest() }
780 void testNothingAfterTypeParameterQualifier() { doAntiTest() }
782 void testExcludeVariableBeingDeclared() { doAntiTest() }
784 void testExcludeVariableBeingDeclared2() { doAntiTest() }
786 void testSpacesAroundEq() throws Throwable { doTest('=') }
788 void _testClassBeforeCast() throws Throwable { doTest '\n' }
790 void testNoAllClassesOnQualifiedReference() throws Throwable {
794 void testFinishClassNameWithDot() throws Throwable {
798 @NeedsIndex.ForStandardLibrary
799 void testFinishClassNameWithLParen() throws Throwable {
803 void testSelectNoParameterSignature() throws Throwable {
804 configureByFile(getTestName(false) + ".java")
805 final int parametersCount = ((PsiMethod)getLookup().getCurrentItem().getObject()).getParameterList().getParametersCount()
806 assertEquals(0, parametersCount)
811 @NeedsIndex.ForStandardLibrary
812 void testCompletionInsideClassLiteral() throws Throwable {
813 configureByFile(getTestName(false) + ".java")
818 void testFieldNegation() throws Throwable { doTest('!') }
820 void testDefaultInSwitch() throws Throwable { doTest() }
822 void testBreakInSwitch() throws Throwable { doTest() }
824 void testSuperInConstructor() throws Throwable {
828 @NeedsIndex.ForStandardLibrary
829 void testSuperInConstructorWithParams() throws Throwable {
833 void testSuperInMethod() throws Throwable {
837 void testSecondMethodParameterName() throws Throwable {
841 void testAnnotationAsUsualObject() throws Throwable {
845 void testAnnotationAsUsualObjectFromJavadoc() throws Throwable {
849 void testAnnotationAsUsualObjectInsideClass() throws Throwable {
853 void testAnnotationOnNothingParens() throws Throwable {
857 void testMultiResolveQualifier() throws Throwable {
861 void testSecondMethodParameter() throws Throwable { doTest() }
863 void testReturnInCase() throws Throwable { doTest() }
865 void testUnboxedConstantsInCase() throws Throwable { doTest() }
867 void testAnnotationWithoutValueMethod() throws Throwable {
868 configureByFile(getTestName(false) + ".java")
869 assertStringItems("bar", "foo")
872 void testAddExplicitValueInAnnotation() throws Throwable {
873 configureByTestName()
874 assertStringItems("bar", "goo")
875 selectItem(myItems[0])
879 void testUnnecessaryMethodMerging() throws Throwable {
880 configureByFile(getTestName(false) + ".java")
881 assertStringItems("fofoo", "fofoo")
884 @NeedsIndex.ForStandardLibrary
885 void testMethodMergingMinimalTail() { doTest() }
887 void testAnnotationQualifiedName() throws Throwable {
891 @NeedsIndex.SmartMode(reason = "For now ConstructorInsertHandler.createOverrideRunnable doesn't work in dumb mode")
892 void testClassNameAnonymous() throws Throwable {
896 @NeedsIndex.SmartMode(reason = "For now ConstructorInsertHandler.createOverrideRunnable doesn't work in dumb mode")
897 void testClassNameWithInner() throws Throwable {
899 assertStringItems 'Zzoo', 'Zzoo.Impl'
904 void testClassNameWithInner2() throws Throwable { doTest('\n') }
906 void testClassNameWithInstanceInner() throws Throwable { doTest('\n') }
908 @NeedsIndex.ForStandardLibrary
909 void testDoubleFalse() throws Throwable {
910 configureByFile(getTestName(false) + ".java")
911 assertFirstStringItems("false", "fefefef", "float", "finalize")
914 void testSameNamedVariableInNestedClasses() throws Throwable {
916 myFixture.assertPreferredCompletionItems 0, "ffid", "Beda.this.ffid"
917 selectItem(myItems[1])
921 void testHonorUnderscoreInPrefix() throws Throwable {
925 @NeedsIndex.ForStandardLibrary
926 void testNoSemicolonAfterExistingParenthesesEspeciallyIfItsACast() throws Throwable { doTest() }
928 void testReturningTypeVariable() throws Throwable { doTest() }
930 void testReturningTypeVariable2() throws Throwable { doTest() }
932 void testReturningTypeVariable3() throws Throwable { doTest() }
934 @NeedsIndex.ForStandardLibrary
935 void testImportInGenericType() throws Throwable {
937 myFixture.complete(CompletionType.BASIC, 2)
942 void testCaseTailType() throws Throwable { doTest() }
944 def doPrimitiveTypeTest() {
946 checkResultByFile(getTestName(false) + ".java")
947 assertTrue 'boolean' in myFixture.lookupElementStrings
950 void testFinalInForLoop() throws Throwable {
952 assertStringItems 'final'
955 @NeedsIndex.ForStandardLibrary
956 void testFinalInForLoop2() throws Throwable {
958 myFixture.assertPreferredCompletionItems 0, 'finalize', 'final'
961 void testOnlyClassesInExtends() throws Throwable {
963 assertStringItems 'Inner'
966 void testNoThisClassInExtends() throws Throwable {
968 assertStringItems 'Fooxxxx2'
971 void testPrimitiveTypesInForLoop() throws Throwable { doPrimitiveTypeTest() }
973 void testPrimitiveTypesInForLoop2() throws Throwable { doPrimitiveTypeTest() }
975 void testPrimitiveTypesInForLoop3() throws Throwable { doPrimitiveTypeTest() }
977 void testPrimitiveTypesInForLoop4() throws Throwable { doPrimitiveTypeTest() }
979 void testPrimitiveTypesInForLoop5() throws Throwable { doPrimitiveTypeTest() }
981 void testPrimitiveTypesInForLoop6() throws Throwable { doPrimitiveTypeTest() }
983 void testPrimitiveTypesInForLoopSpace() throws Throwable {
986 checkResultByFile(getTestName(false) + "_after.java")
989 void testSuggestInaccessibleOnSecondInvocation() throws Throwable {
991 assertStringItems("_bar", "_goo")
993 assertStringItems("_bar", "_goo", "_foo")
994 getLookup().setCurrentItem(getLookup().getItems().get(2))
995 selectItem(lookup.items[2], Lookup.NORMAL_SELECT_CHAR)
999 void testNoCommonPrefixInsideIdentifier() throws Throwable {
1000 final String path = getTestName(false) + ".java"
1001 configureByFile(path)
1002 checkResultByFile(path)
1003 assertStringItems("fai1", "fai2")
1007 void testProtectedInaccessibleOnSecondInvocation() throws Throwable {
1008 myFixture.configureByFile(getTestName(false) + ".java")
1009 myFixture.complete(CompletionType.BASIC, 2)
1010 myFixture.type('\n')
1014 void testPropertyReferencePrefix() throws Throwable {
1015 myFixture.addFileToProject("test.properties", "foo.bar=Foo! Bar!").getVirtualFile()
1019 @NeedsIndex.ForStandardLibrary
1020 void testSecondAnonymousClassParameter() { doTest() }
1022 void testSpaceAfterReturn() throws Throwable {
1028 void testIntersectionTypeMembers() throws Throwable {
1030 assertStringItems "fooa", "foob"
1033 void testNoReturnInTernary() throws Throwable { doTest() }
1035 void testWildcardsInLookup() throws Exception {
1037 assertNotNull(getLookup())
1042 void testSmartEnterWrapsConstructorCall() throws Throwable { doTest(Lookup.COMPLETE_STATEMENT_SELECT_CHAR as String) }
1044 void testSmartEnterNoNewLine() { doTest(Lookup.COMPLETE_STATEMENT_SELECT_CHAR as String) }
1046 void testSmartEnterWithNewLine() { doTest(Lookup.COMPLETE_STATEMENT_SELECT_CHAR as String) }
1048 @NeedsIndex.SmartMode(reason = "MethodCallFixer.apply needs smart mode to count number of parameters")
1049 void testSmartEnterGuessArgumentCount() throws Throwable { doTest(Lookup.COMPLETE_STATEMENT_SELECT_CHAR as String) }
1051 void testSmartEnterInsideArrayBrackets() { doTest(Lookup.COMPLETE_STATEMENT_SELECT_CHAR as String) }
1053 void testTabReplacesMethodNameWithLocalVariableName() throws Throwable { doTest('\t') }
1055 void testMethodParameterAnnotationClass() throws Throwable { doTest() }
1058 void testInnerAnnotation() {
1060 assert myFixture.lookupElementStrings == ['Dependency']
1065 void testPrimitiveCastOverwrite() throws Throwable { doTest() }
1067 void testClassReferenceInFor() throws Throwable { doTest ' ' }
1069 void testClassReferenceInFor2() throws Throwable { doTest ' ' }
1071 void testClassReferenceInFor3() throws Throwable {
1072 CodeInsightSettings.instance.setCompletionCaseSensitive(CodeInsightSettings.NONE)
1076 void testEnumConstantFromEnumMember() throws Throwable { doTest() }
1078 void testPrimitiveMethodParameter() throws Throwable { doTest() }
1080 void testNewExpectedClassParens() throws Throwable { doTest('\n') }
1082 void testQualifyInnerMembers() throws Throwable { doTest('\n') }
1084 void testDeepInner() throws Throwable {
1086 assert myFixture.lookupElementStrings == ['ClassInner1', 'ClassInner1.ClassInner2']
1087 selectItem(lookup.items[1])
1091 void testSuggestExpectedTypeMembers() throws Throwable { doTest('\n') }
1093 void testSuggestExpectedTypeMembersInCall() throws Throwable { doTest('\n') }
1095 void testSuggestExpectedTypeMembersInAnno() throws Throwable { doTest('\n') }
1097 void testExpectedTypesDotSelectsItem() throws Throwable { doTest('.') }
1100 void testExpectedTypeMembersVersusStaticImports() throws Throwable {
1102 assertStringItems('XFOO', 'XFOX')
1106 void testSuggestExpectedTypeMembersNonImported() throws Throwable {
1107 myFixture.addClass("package foo; public class Super { public static final Super FOO = null; }")
1108 myFixture.addClass("package foo; public class Usage { public static void foo(Super s) {} }")
1113 void testStaticallyImportedInner() throws Throwable {
1115 assertStringItems('AIOInner', 'ArrayIndexOutOfBoundsException')
1118 void testClassNameInIfBeforeIdentifier() throws Throwable {
1119 myFixture.addClass("public class ABCDEFFFFF {}")
1123 void testClassNameWithInnersTab() throws Throwable { doTest('\t') }
1125 void testClassNameWithGenericsTab() throws Throwable { doTest('\t') }
1127 void testLiveTemplatePrefixTab() throws Throwable { doTest('\t') }
1129 void testOnlyAnnotationsAfterAt() throws Throwable { doTest() }
1131 @NeedsIndex.ForStandardLibrary
1132 void testOnlyAnnotationsAfterAt2() throws Throwable { doTest('\n') }
1134 void testAnnotationBeforeIdentifier() { doTest('\n') }
1136 void testAnnotationBeforeQualifiedReference() { doTest('\n') }
1138 void testAnnotationBeforeIdentifierFinishWithSpace() { doTest(' ') }
1140 @NeedsIndex.ForStandardLibrary
1141 void testOnlyExceptionsInCatch1() throws Exception { doTest('\n') }
1143 @NeedsIndex.ForStandardLibrary
1144 void testOnlyExceptionsInCatch2() throws Exception { doTest('\n') }
1146 @NeedsIndex.ForStandardLibrary
1147 void testOnlyExceptionsInCatch3() throws Exception { doTest('\n') }
1149 @NeedsIndex.ForStandardLibrary
1150 void testOnlyExceptionsInCatch4() throws Exception { doTest('\n') }
1152 void testCommaAfterVariable() throws Throwable { doTest(',') }
1154 void testClassAngleBracket() throws Throwable { doTest('<') }
1156 void testNoArgsMethodSpace() throws Throwable { doTest(' ') }
1158 void testClassSquareBracket() throws Throwable { doTest('[') }
1160 void testPrimitiveSquareBracket() throws Throwable { doTest('[') }
1162 void testVariableSquareBracket() throws Throwable { doTest('[') }
1164 void testMethodSquareBracket() throws Throwable { doTest('[') }
1166 void testMethodParameterTypeDot() throws Throwable { doAntiTest() }
1168 @NeedsIndex.ForStandardLibrary
1169 void testNewGenericClass() throws Throwable { doTest('\n') }
1171 void testNewGenericInterface() throws Throwable { doTest() }
1173 void testEnumPrivateFinal() throws Throwable { doTest() }
1175 void testNoFieldsInImplements() throws Throwable { doTest() }
1177 void testSwitchConstantsFromReferencedClass() throws Throwable { doTest('\n') }
1179 void testSwitchValueFinishWithColon() throws Throwable { doTest(':') }
1181 void testUnfinishedMethodTypeParameter() throws Throwable {
1183 assertStringItems("MyParameter", "MySecondParameter")
1186 void testUnfinishedMethodTypeParameter2() throws Throwable {
1188 assertStringItems("MyParameter", "MySecondParameter")
1192 void testSuperProtectedMethod() throws Throwable {
1193 myFixture.addClass """package foo;
1195 protected void foo() { }
1200 @NeedsIndex.ForStandardLibrary
1201 void testOuterSuperMethodCall() {
1203 assert 'Class2.super.put' == renderElement(myItems[0]).itemText
1207 void testTopLevelClassesFromPackaged() throws Throwable {
1208 myFixture.addClass "public class Fooooo {}"
1209 final text = "package foo; class Bar { Fooo<caret> }"
1210 def file = myFixture.addFileToProject("foo/Bar.java", text)
1211 myFixture.configureFromExistingVirtualFile file.virtualFile
1212 assertEmpty myFixture.completeBasic()
1213 myFixture.checkResult text
1216 void testRightShift() throws Throwable {
1218 assertStringItems("myField1", "myField2")
1221 @NeedsIndex.ForStandardLibrary
1222 void testAfterCommonPrefix() throws Throwable {
1225 assertFirstStringItems("equals", "equalsIgnoreCase")
1227 assertFirstStringItems("equals", "equalsIgnoreCase")
1232 @NeedsIndex.ForStandardLibrary
1233 void testClassNameInsideIdentifierInIf() throws Throwable {
1235 myFixture.complete(CompletionType.BASIC, 2)
1240 void testKeywordSmartEnter() {
1242 myFixture.assertPreferredCompletionItems 0, 'null', 'nullity'
1243 myFixture.performEditorAction(IdeActions.ACTION_CHOOSE_LOOKUP_ITEM_COMPLETE_STATEMENT)
1246 void testSynchronizedArgumentSmartEnter() { doTest(Lookup.COMPLETE_STATEMENT_SELECT_CHAR as String) }
1249 void testImportStringValue() throws Throwable {
1250 myFixture.addClass("package foo; public class StringValue {}")
1251 myFixture.addClass("package java.lang; class StringValue {}")
1253 myFixture.complete(CompletionType.BASIC, 2)
1258 void testPrimitiveArrayWithRBrace() throws Throwable { doTest '[' }
1261 void testSuggestMembersOfStaticallyImportedClasses() throws Exception {
1262 myFixture.addClass("""package foo;
1264 public static void foo() {}
1265 public static void bar() {}
1272 void testSuggestMembersOfStaticallyImportedClassesUnqualifiedOnly() throws Exception {
1273 myFixture.addClass("""package foo;
1275 public static void foo() {}
1276 public static void bar() {}
1281 assertOneElement(myFixture.getLookupElements())
1287 void testSuggestMembersOfStaticallyImportedClassesConflictWithLocalMethod() throws Exception {
1288 myFixture.addClass("""package foo;
1290 public static void foo() {}
1291 public static void bar() {}
1295 myFixture.assertPreferredCompletionItems 0, 'bar', 'bar'
1296 assert renderElement(myFixture.lookupElements[1]).itemText == 'Foo.bar'
1297 myFixture.lookup.currentItem = myFixture.lookupElements[1]
1303 void testSuggestMembersOfStaticallyImportedClassesConflictWithLocalField() throws Exception {
1304 myFixture.addClass("""package foo;
1306 public static int foo = 1;
1307 public static int bar = 2;
1311 myFixture.assertPreferredCompletionItems 0, 'bar', 'Foo.bar'
1312 myFixture.lookup.currentItem = myFixture.lookupElements[1]
1317 void testInstanceMagicMethod() throws Exception { doTest() }
1319 void testNoDotOverwrite() throws Exception { doTest('.') }
1321 void testNoModifierListOverwrite() { doTest('\t') }
1323 void testStaticInnerExtendingOuter() throws Exception { doTest() }
1325 void testPrimitiveClass() throws Exception { doTest() }
1327 void testPrimitiveArrayClass() throws Exception { doTest() }
1329 void testPrimitiveArrayOnlyClass() throws Exception { doAntiTest() }
1331 void testPrimitiveArrayInAnno() throws Exception { doTest() }
1333 void testNewClassAngleBracket() throws Exception { doTest('<') }
1335 void testNewClassAngleBracketExpected() throws Exception { doTest('<') }
1337 void testNewClassSquareBracket() throws Exception { doTest('[') }
1339 void testMethodColon() throws Exception { doTest(':') }
1341 void testVariableColon() throws Exception { doTest(':') }
1343 void testFinishByClosingParenthesis() throws Exception { doTest(')') }
1345 void testNoMethodsInParameterType() {
1347 assertFirstStringItems "final", "float"
1351 void testNonImportedClassInAnnotation() {
1352 myFixture.addClass("package foo; public class XInternalTimerServiceController {}")
1353 myFixture.configureByText "a.java", """
1354 class XInternalError {}
1356 @interface Anno { Class value(); }
1358 @Anno(XInternal<caret>)
1360 myFixture.complete(CompletionType.BASIC, 2)
1361 assertFirstStringItems "XInternalError", "XInternalTimerServiceController"
1365 void testNonImportedAnnotationClass() {
1366 myFixture.addClass("package foo; public @interface XAnotherAnno {}")
1369 assertFirstStringItems "XAnno", "XAnotherAnno"
1372 @NeedsIndex.ForStandardLibrary
1373 void testMetaAnnotation() {
1374 myFixture.configureByText "a.java", "@<caret> @interface Anno {}"
1375 myFixture.complete(CompletionType.BASIC)
1376 assert myFixture.lookup.items.find { it.lookupString == 'Retention' }
1379 void testAnnotationClassFromWithinAnnotation() { doTest() }
1382 void testStaticallyImportedFieldsTwice() {
1383 myFixture.addClass("""
1385 public static final int aZOO;
1388 myFixture.configureByText("a.java", """
1394 assertOneElement myFixture.completeBasic()
1397 void testStaticallyImportedFieldsTwiceSwitch() { doTest() }
1399 void testStatementKeywords() {
1400 myFixture.configureByText("a.java", """
1405 myFixture.completeBasic()
1406 final def strings = myFixture.lookupElementStrings
1407 assertTrue 'if' in strings
1408 assertTrue 'while' in strings
1409 assertTrue 'do' in strings
1410 assertTrue 'new' in strings
1411 assertTrue 'try' in strings
1413 strings.remove 'new'
1414 assertFalse 'new' in strings
1417 void testExpressionKeywords() {
1418 myFixture.configureByText("a.java", """
1423 myFixture.completeBasic()
1424 final def strings = myFixture.lookupElementStrings
1425 assertTrue 'new' in strings
1428 void testImportAsterisk() {
1429 myFixture.configureByText "a.java", "import java.lang.<caret>"
1430 myFixture.completeBasic()
1432 myFixture.checkResult "import java.lang.*;<caret>"
1435 void testDontPreselectCaseInsensitivePrefixMatch() {
1436 CodeInsightSettings.instance.setCompletionCaseSensitive(CodeInsightSettings.NONE)
1437 myFixture.configureByText "a.java", "import java.io.*; class Foo {{ int fileSize; fil<caret>x }}"
1438 myFixture.completeBasic()
1439 assert lookup.currentItem.lookupString == 'fileSize'
1442 assert lookup.items[0].lookupString == 'File'
1443 assert lookup.items[1].lookupString == 'fileSize'
1444 assert lookup.currentItem == lookup.items[1]
1447 @NeedsIndex.ForStandardLibrary
1448 void testNoGenericsWhenChoosingWithParen() { doTest('Ma(') }
1450 @NeedsIndex.ForStandardLibrary
1451 void testNoClosingWhenChoosingWithParenBeforeIdentifier() { doTest '(' }
1453 void testPackageInMemberType() { doTest() }
1454 void testPackageInMemberTypeGeneric() { doTest() }
1456 @NeedsIndex.ForStandardLibrary
1457 void testConstantInAnno() { doTest('\n') }
1459 @NeedsIndex.SmartMode(reason = "Smart mode needed for EncodingReferenceInjector to provide EncodingReference with variants")
1460 void testCharsetName() {
1461 myFixture.addClass("package java.nio.charset; public class Charset { public static Charset forName(String s) {} }")
1462 configureByTestName()
1463 assert myFixture.lookupElementStrings.contains('UTF-8')
1467 void testInnerClassInExtendsGenerics() {
1468 def text = "package bar; class Foo extends List<Inne<caret>> { public static class Inner {} }"
1469 myFixture.configureFromExistingVirtualFile(myFixture.addClass(text).containingFile.virtualFile)
1470 myFixture.completeBasic()
1471 myFixture.type('\n')
1472 myFixture.checkResult(text.replace('Inne<caret>', 'Foo.Inner<caret>'))
1475 @NeedsIndex.ForStandardLibrary
1476 void testClassNameDot() { doTest('.') }
1479 void testClassNameDotBeforeCall() {
1480 myFixture.addClass("package foo; public class FileInputStreamSmth {}")
1481 myFixture.configureByFile(getTestName(false) + ".java")
1482 PsiDocumentManager.getInstance(project).commitAllDocuments()
1484 PsiDocumentManager.getInstance(project).commitAllDocuments()
1485 myFixture.complete(CompletionType.BASIC, 2)
1491 void testNoReturnAfterDot() {
1493 assert !('return' in myFixture.lookupElementStrings)
1496 @NeedsIndex.ForStandardLibrary
1497 void testDuplicateExpectedTypeInTypeArgumentList() {
1499 def items = myFixture.lookupElements.findAll { it.lookupString == 'String' }
1500 assert items.size() == 1
1501 assert renderElement(items[0]).tailText == ' (java.lang)'
1504 void testDuplicateInnerClass() {
1506 def items = myFixture.lookupElements.findAll { it.lookupString == 'Inner' }
1507 assert items.size() == 1
1510 void testSameSignature() {
1512 myFixture.assertPreferredCompletionItems(0, 's', 's, file', 's, file, a')
1513 lookup.setCurrentItem(lookup.items[2])
1514 myFixture.type('\n')
1518 @NeedsIndex.ForStandardLibrary
1519 void testNoParenthesesAroundCallQualifier() { doTest() }
1522 void testAllAssertClassesMethods() {
1523 myFixture.addClass 'package foo; public class Assert { public static boolean foo() {} }'
1524 myFixture.addClass 'package bar; public class Assert { public static boolean bar() {} }'
1526 assert myFixture.lookupElementStrings == ['Assert.bar', 'Assert.foo']
1532 void testCastVisually() {
1534 def p = renderElement(myFixture.lookupElements[0])
1535 assert p.itemText == 'getValue'
1536 assert p.itemTextBold
1537 assert p.typeText == 'Foo'
1540 @NeedsIndex.ForStandardLibrary
1541 void testSuggestEmptySet() {
1543 assert 'emptySet' == myFixture.lookupElementStrings[0]
1548 @NeedsIndex.ForStandardLibrary
1549 void testSuggestAllTypeArguments() {
1551 assert 'String, List<String>' == lookup.items[0].lookupString
1552 assert 'String, List<String>' == renderElement(lookup.items[0]).itemText
1557 void testNoFinalInAnonymousConstructor() { doTest() }
1559 @NeedsIndex.ForStandardLibrary
1560 void testListArrayListCast() { doTest('\n') }
1562 void testInterfaceImplementationNoCast() { doTest() }
1565 void testStaticallyImportedMethodsBeforeExpression() { doTest() }
1568 void testInnerChainedReturnType() { doTest() }
1570 private CommonCodeStyleSettings getCodeStyleSettings() {
1571 return CodeStyleSettingsManager.getSettings(getProject()).getCommonSettings(JavaLanguage.INSTANCE)
1574 void testCompatibleInterfacesCast() {
1576 assert myFixture.lookupElementStrings.containsAll(['foo', 'bar'])
1579 void testDontAutoInsertMiddleMatch() {
1582 assert lookup.items.size() == 1
1585 @NeedsIndex.SmartMode(reason = "JavaGenerateMemberCompletionContributor.fillCompletionVariants works in smart mode only (for method implementations)")
1586 void testImplementViaCompletion() {
1588 myFixture.assertPreferredCompletionItems 0, 'private', 'protected', 'public', 'public void run'
1589 def item = lookup.items[3]
1591 def p = renderElement(item)
1592 assert p.itemText == 'public void run'
1593 assert p.tailText == '(String t, int myInt) {...}'
1594 assert p.typeText == 'Foo'
1596 lookup.currentItem = item
1597 myFixture.type('\n')
1601 @NeedsIndex.SmartMode(reason = "JavaGenerateMemberCompletionContributor.fillCompletionVariants works in smart mode only (for implementing methods)")
1602 void testImplementViaCompletionWithGenerics() {
1604 myFixture.assertPreferredCompletionItems 0, 'public void methodWithGenerics', 'public void methodWithTypeParam'
1605 assert renderElement(lookup.items[0]).tailText == '(List k) {...}'
1606 assert renderElement(lookup.items[1]).tailText == '(K k) {...}'
1609 @NeedsIndex.SmartMode(reason = "JavaGenerateMemberCompletionContributor.fillCompletionVariants provides dialog option in smart mode only")
1610 void testImplementViaOverrideCompletion() {
1612 myFixture.assertPreferredCompletionItems 0, 'Override/Implement methods...', 'Override', 'public void run'
1613 lookup.currentItem = lookup.items[2]
1614 myFixture.type('\n')
1618 @NeedsIndex.SmartMode(reason = "JavaGenerateMemberCompletionContributor.fillCompletionVariants provides dialog option in smart mode only")
1619 void testSuggestToOverrideMethodsWhenTypingOverrideAnnotation() {
1621 myFixture.assertPreferredCompletionItems 0, 'Override/Implement methods...', 'Override'
1622 myFixture.type('\n')
1626 @NeedsIndex.SmartMode(reason = "JavaGenerateMemberCompletionContributor.fillCompletionVariants provides dialog option in smart mode only")
1627 void testSuggestToOverrideMethodsWhenTypingOverrideAnnotationBeforeMethod() {
1629 myFixture.assertPreferredCompletionItems 0, 'Override/Implement methods...', 'Override'
1630 myFixture.type('\n')
1634 @NeedsIndex.SmartMode(reason = "JavaGenerateMemberCompletionContributor.fillCompletionVariants works in smart mode only (for implementing methods)")
1635 void testStrikeOutDeprecatedSuperMethods() {
1637 myFixture.assertPreferredCompletionItems 0, 'void foo1', 'void foo2'
1638 assert !renderElement(lookup.items[0]).strikeout
1639 assert renderElement(lookup.items[1]).strikeout
1642 @NeedsIndex.SmartMode(reason = "JavaGenerateMemberCompletionContributor.fillCompletionVariants works in smart mode only (for equals() and hashCode())")
1643 void testInvokeGenerateEqualsHashCodeOnOverrideCompletion() { doTest() }
1644 @NeedsIndex.SmartMode(reason = "JavaGenerateMemberCompletionContributor.fillCompletionVariants works in smart mode only (for 'toString()')")
1645 void testInvokeGenerateToStringOnOverrideCompletion() { doTest() }
1647 @NeedsIndex.SmartMode(reason = "JavaGenerateMemberCompletionContributor.fillCompletionVariants works in smart mode only (for getters and setters)")
1648 void testAccessorViaCompletion() {
1651 def getter = myFixture.lookupElements.find { it.lookupString == 'public int getField' }
1652 def setter = myFixture.lookupElements.find { it.lookupString == 'public void setField' }
1653 assert getter : myFixture.lookupElementStrings
1654 assert setter : myFixture.lookupElementStrings
1656 def p = renderElement(getter)
1657 assert p.itemText == getter.lookupString
1658 assert p.tailText == '() {...}'
1661 p = renderElement(setter)
1662 assert p.itemText == setter.lookupString
1663 assert p.tailText == '(int field) {...}'
1666 lookup.currentItem = getter
1667 myFixture.type('\n')
1671 @NeedsIndex.SmartMode(reason = "JavaGenerateMemberCompletionContributor.fillCompletionVariants works in smart mode only (for getters and setters)")
1672 void testNoSetterForFinalField() {
1674 myFixture.assertPreferredCompletionItems 0, 'public', 'public int getFinalField'
1675 assert !myFixture.lookupElements.find { it.lookupString == 'public void setFinalField' }
1676 assert !myFixture.lookupElements.find { it.lookupString == 'public int getCONSTANT' }
1679 void testBraceOnNextLine() {
1680 codeStyleSettings.BRACE_STYLE = CommonCodeStyleSettings.NEXT_LINE
1684 void testDoForceBraces() {
1685 codeStyleSettings.DOWHILE_BRACE_FORCE = CommonCodeStyleSettings.FORCE_BRACES_ALWAYS
1689 void testMulticaretSingleItemInsertion() {
1693 @NeedsIndex.ForStandardLibrary
1694 void testMulticaretMethodWithParen() {
1698 @NeedsIndex.ForStandardLibrary
1699 void testMulticaretTyping() {
1708 @NeedsIndex.ForStandardLibrary
1709 void testMulticaretCompletionFromNonPrimaryCaret() {
1711 myFixture.assertPreferredCompletionItems(0, "arraycopy")
1714 void testMulticaretCompletionFromNonPrimaryCaretWithTab() {
1719 void "test complete lowercase class name"() {
1720 myFixture.addClass("package foo; public class myClass {}")
1721 myFixture.configureByText "a.java", """
1722 class Foo extends my<caret>
1724 myFixture.complete(CompletionType.BASIC, 2)
1725 myFixture.checkResult '''import foo.myClass;
1727 class Foo extends myClass
1731 void testNoClassesWithDollar() {
1732 myFixture.addClass('package some; public class $WithDollarNonImported {}')
1733 myFixture.addClass('package imported; public class $WithDollarImported {}')
1737 @NeedsIndex.ForStandardLibrary
1738 void "test don't show static inner class after instance qualifier"() {
1739 myFixture.configureByText "a.java", """
1741 static class Inner {}
1749 myFixture.completeBasic()
1750 assert !('Inner' in myFixture.lookupElementStrings)
1753 @NeedsIndex.ForStandardLibrary
1754 void "test show static member after instance qualifier when nothing matches"() {
1755 myFixture.configureByText "a.java", "class Foo{{ \"\".<caret> }}"
1756 myFixture.completeBasic()
1757 assert !('valueOf' in myFixture.lookupElementStrings)
1758 ((LookupImpl)myFixture.lookup).hide()
1759 myFixture.type 'val'
1760 myFixture.completeBasic()
1761 assert ('valueOf' in myFixture.lookupElementStrings)
1764 void testNoMathTargetMethods() { doAntiTest() }
1767 void testNoLowercaseClasses() {
1768 myFixture.addClass("package foo; public class abcdefgXxx {}")
1770 myFixture.complete(CompletionType.BASIC, 2)
1771 assertStringItems('abcdefgXxx')
1775 void testProtectedFieldInAnotherPackage() {
1776 myFixture.addClass("package foo; public class Super { protected String myString; }")
1781 void testUnimportedStaticInnerClass() {
1782 myFixture.addClass("package foo; public class Super { public static class Inner {} }")
1786 void testNoJavaLangPackagesInImport() { doAntiTest() }
1789 void testNoStaticDuplicatesFromExpectedMemberFactories() {
1791 myFixture.complete(CompletionType.BASIC, 2)
1792 myFixture.assertPreferredCompletionItems(0, "xcreateZoo", "xcreateElephant")
1795 void testNoInaccessibleCompiledElements() {
1797 myFixture.complete(CompletionType.BASIC, 2)
1798 checkResultByFile(getTestName(false) + ".java")
1799 assertEmpty(myItems)
1800 assertNull(getLookup())
1803 @NeedsIndex.SmartMode(reason = "JavaGenerateMemberCompletionContributor.fillCompletionVariants works in smart mode only (for getters)")
1804 void "test code cleanup during completion generation"() {
1805 myFixture.configureByText "a.java", "class Foo {int i; ge<caret>}"
1806 myFixture.enableInspections(new UnqualifiedFieldAccessInspection())
1807 myFixture.complete(CompletionType.BASIC)
1808 UIUtil.dispatchAllInvocationEvents()
1809 myFixture.checkResult '''class Foo {int i;
1817 void testIndentingForSwitchCase() { doTest() }
1819 void testShowMostSpecificOverride() {
1821 assert 'B' == renderElement(myFixture.lookup.items[0]).typeText
1824 @NeedsIndex.ForStandardLibrary
1825 void testShowMostSpecificOverrideOnlyFromClass() {
1827 assert 'Door' == renderElement(myFixture.lookup.items[0]).typeText
1830 void testNoOverrideWithMiddleMatchedName() {
1832 assert !('public void removeTemporaryEditorNode' in myFixture.lookupElementStrings)
1835 void testShowVarInitializers() {
1837 myFixture.assertPreferredCompletionItems 0, 'FIELD1', 'FIELD2', 'FIELD3', 'FIELD4'
1838 def items = myFixture.lookup.items
1839 assert items.collect { renderElement(it).tailText } == ['( "x")', '("y") {...}', null, ' ( = 42)']
1840 assert renderElement(items[3]).tailFragments[0].italic
1844 void testShowNonImportedVarInitializers() {
1846 myFixture.assertPreferredCompletionItems 1, 'Field', 'FIELD1', 'FIELD2', 'FIELD3', 'FIELD4'
1847 def fieldItems = myFixture.lookup.items[1..4]
1848 assert fieldItems.collect { renderElement(it).tailText } == ['( "x") in E', '("y") {...} in E', null, ' ( = 42) in E']
1849 assert renderElement(fieldItems[3]).tailFragments[0].italic
1850 assert !renderElement(fieldItems[3]).tailFragments[1].italic
1853 @NeedsIndex.ForStandardLibrary
1854 void testSuggestInterfaceArrayWhenObjectIsExpected() {
1856 assert renderElement(myFixture.lookup.items[0]).tailText.contains('{...}')
1857 assert renderElement(myFixture.lookup.items[1]).tailText.contains('[]')
1860 @NeedsIndex.ForStandardLibrary
1861 void testSuggestInterfaceArrayWhenObjectArrayIsExpected() {
1863 assert renderElement(myFixture.lookup.items[0]).tailText.contains('{...}')
1864 assert renderElement(myFixture.lookup.items[1]).tailText.contains('[]')
1867 void testDispreferPrimitiveTypesInCallArgs() throws Throwable {
1868 CodeInsightSettings.instance.setCompletionCaseSensitive(CodeInsightSettings.NONE)
1870 myFixture.assertPreferredCompletionItems 0, "dx", "doo", "Doo", "double"
1873 @NeedsIndex.ForStandardLibrary
1874 void testCopyConstructor() { doTest('\n') }
1876 @NeedsIndex.ForStandardLibrary
1877 void testGetClassType() {
1879 assert 'Class<? extends Number>' == renderElement(myFixture.lookupElements[0]).typeText
1883 void testNonImportedClassAfterNew() {
1884 def uClass = myFixture.addClass('package foo; public class U {}')
1885 myFixture.configureByText('a.java', 'class X {{ new U<caret>x }}')
1886 myFixture.completeBasic()
1887 assert myFixture.lookupElements[0].object == uClass
1890 void testSuggestClassNamesForLambdaParameterTypes() { doTest('\n') }
1892 void testOnlyExtendsSuperInWildcard() {
1893 CodeInsightSettings.instance.setCompletionCaseSensitive(CodeInsightSettings.NONE)
1896 assert myFixture.lookupElementStrings == ['extends', 'super']
1897 LookupManager.getInstance(project).hideActiveLookup()
1900 assert !myFixture.completeBasic()
1901 myFixture.type('\b')
1902 checkResultByFile(getTestName(false) + ".java")
1906 void testChainInLambdaBinary() {
1907 codeStyleSettings.ALIGN_MULTILINE_BINARY_OPERATION = true
1908 myFixture.addClass("package pkg; public class PathUtil { public static String toSystemDependentName() {} }")
1912 @NeedsIndex.ForStandardLibrary
1913 void testPairAngleBracketDisabled() {
1914 CodeInsightSettings.instance.AUTOINSERT_PAIR_BRACKET = false
1918 void testDuplicateGenericMethodSuggestionWhenInheritingFromRawType() {
1920 assert myFixture.lookupElementStrings == ['indexOf']
1923 @NeedsIndex.ForStandardLibrary
1924 void testDuplicateEnumValueOf() {
1926 assert myFixture.lookupElements.collect { renderElement((LookupElement)it).itemText } == ['Bar.valueOf', 'Foo.valueOf', 'Enum.valueOf']
1929 void testTypeArgumentInCast() {
1931 myFixture.assertPreferredCompletionItems 0, 'String'
1934 void testNoCallsInPackageStatement() { doAntiTest() }
1937 void testTypeParameterShadowingClass() {
1939 myFixture.assertPreferredCompletionItems 0, 'Tttt', 'Tttt'
1940 assert myFixture.lookupElements[0].object instanceof PsiTypeParameter
1941 assert !(myFixture.lookupElements[1].object instanceof PsiTypeParameter)
1942 selectItem(myFixture.lookupElements[1])
1946 void testLowercaseDoesNotMatchUnderscore() {
1948 assert myFixture.lookupElementStrings == ['web']
1951 void testLocalClassPresentation() {
1952 def cls = myFixture.addFileToProject('foo/Bar.java', """package foo;
1957 myFixture.configureFromExistingVirtualFile(cls.containingFile.virtualFile)
1958 def item = myFixture.completeBasic()[0]
1959 assert renderElement(item).tailText.contains('local class')
1962 void testNoDuplicateInCast() {
1964 assert myFixture.lookupElementStrings == null
1967 void testNoNonAnnotationMethods() { doAntiTest() }
1969 @NeedsIndex.ForStandardLibrary
1970 void testPreferBigDecimalToJavaUtilInner() {
1972 myFixture.assertPreferredCompletionItems 0, 'BigDecimal', 'BigDecimalLayoutForm'
1975 @NeedsIndex.ForStandardLibrary
1976 void testOnlyExceptionsInMultiCatch1() { doTest('\n') }
1978 @NeedsIndex.ForStandardLibrary
1979 void testOnlyExceptionsInMultiCatch2() { doTest('\n') }
1981 @NeedsIndex.ForStandardLibrary
1982 void testOnlyResourcesInResourceList1() { doTest('\n') }
1984 @NeedsIndex.ForStandardLibrary
1985 void testOnlyResourcesInResourceList2() { doTest('\n') }
1987 @NeedsIndex.ForStandardLibrary
1988 void testOnlyResourcesInResourceList3() { doTest('\n') }
1990 @NeedsIndex.ForStandardLibrary
1991 void testOnlyResourcesInResourceList4() { doTest('\n') }
1993 void testOnlyResourcesInResourceList5() { doTest('\n') }
1995 @NeedsIndex.ForStandardLibrary
1996 void testMethodReferenceNoStatic() { doTest('\n') }
1998 void testMethodReferenceCallContext() { doTest('\n') }
2001 void testDestroyingCompletedClassDeclaration() { doTest('\n') }
2003 @NeedsIndex.ForStandardLibrary
2004 void testResourceParentInResourceList() {
2005 configureByTestName()
2006 assert 'MyOuterResource' == myFixture.lookupElementStrings[0]
2007 assert 'MyClass' in myFixture.lookupElementStrings
2008 myFixture.type('C\n')
2009 checkResultByFile(getTestName(false) + "_after.java")
2012 void testAfterTryWithResources() {
2013 configureByTestName()
2014 def strings = myFixture.lookupElementStrings
2015 assert strings.containsAll(['final', 'finally', 'int', 'Util'])
2018 void testNewObjectHashMapWithSmartEnter() {
2019 configureByTestName()
2020 myFixture.performEditorAction(IdeActions.ACTION_CHOOSE_LOOKUP_ITEM_COMPLETE_STATEMENT)
2021 checkResultByFile(getTestName(false) + "_after.java")
2025 void testCompletingClassWithSameNameAsPackage() {
2026 myFixture.addClass("package Apple; public class Apple {}")
2030 void testSuggestGetInstanceMethodName() { doTest() }
2032 @NeedsIndex.Full(reason = "AllClassesSearchExecutor.processClassNames from JavaNoVariantsDelegator.suggestNonImportedClasses uses stub indices to provide completion, so matching Scratch class is ignored, ant so is its inner class")
2033 void testTabOnNewInnerClass() {
2034 configureByTestName()
2035 lookup.currentItem = myFixture.lookupElements.find { it.lookupString.contains('Inner') }
2036 myFixture.type('\t')
2041 void testRemoveUnusedImportOfSameName() {
2042 myFixture.addClass("package foo; public class List {}")
2043 configureByTestName()
2044 lookup.currentItem = myFixture.lookupElements.find { it.object instanceof PsiClass && ((PsiClass)it.object).qualifiedName == 'java.util.List' }
2045 myFixture.type('\n')
2049 void "test no duplication after new with expected type parameter"() {
2050 myFixture.configureByText 'a.java', 'class Foo<T> { T t = new <caret> }'
2052 assert myFixture.lookupElements.findAll { it.allLookupStrings.contains('T') }.size() < 2
2055 void "test no duplication for inner class on second invocation"() {
2056 myFixture.configureByText 'a.java', '''
2063 myFixture.complete(CompletionType.BASIC, 2)
2064 assert myFixture.lookupElements.size() == 1
2067 void "test smart enter wraps type arguments"() {
2068 myFixture.configureByText 'a.java', 'class Foo<T> { F<caret>List<String> }'
2069 myFixture.completeBasic()
2070 myFixture.type(Lookup.COMPLETE_STATEMENT_SELECT_CHAR)
2071 myFixture.checkResult 'class Foo<T> { Foo<List<String>><caret> }'
2074 void testNoSuggestionsAfterEnumConstant() { doAntiTest() }
2076 void testPutCaretInsideParensInFixedPlusVarargOverloads() { doTest('\n') }
2078 void testSuggestCurrentClassInSecondSuperGenericParameter() { doTest('\n') }
2081 void "test after new editing prefix back and forth when sometimes there are expected type suggestions and sometimes not"() {
2082 myFixture.addClass("class Super {}")
2083 myFixture.addClass("class Sub extends Super {}")
2084 myFixture.addClass("package foo; public class SubOther {}")
2085 myFixture.configureByText('a.java', "class C { Super s = new SubO<caret>x }")
2087 myFixture.completeBasic()
2088 myFixture.assertPreferredCompletionItems 0, 'SubOther'
2089 myFixture.type('\b')
2090 myFixture.assertPreferredCompletionItems 0, 'Sub'
2092 myFixture.assertPreferredCompletionItems 0, 'SubOther'
2095 void "test correct typos"() {
2096 myFixture.configureByText("a.java", "class MyClass { MyCals<caret> }")
2097 myFixture.completeBasic()
2098 myFixture.type('\n')
2099 myFixture.checkResult("class MyClass { MyClass<caret> }")
2102 void testRemoveParenthesesWhenReplacingEmptyCallWithConstant() {
2106 void testNoCallsAfterAnnotationInCodeBlock() { doTest() }
2108 void testExtendsAfterEnum() {
2109 myFixture.configureByText("a.java", "enum X ex<caret>") // should not complete
2110 myFixture.completeBasic()
2111 myFixture.checkResult("enum X ex")
2115 void testAddImportWhenCompletingInnerAfterNew() {
2116 myFixture.addClass("package p; public class Outer { public static class Inner {} }")
2117 configureByTestName()
2118 selectItem(myItems.find { it.lookupString.contains('Inner') })
2122 void "test completing qualified class name"() {
2123 myFixture.configureByText("a.java", "class C implements java.util.Li<caret>")
2124 myFixture.completeBasic()
2125 myFixture.assertPreferredCompletionItems(0, 'List')
2126 myFixture.type('\n')
2127 myFixture.checkResult("class C implements java.util.List<caret>")
2130 @NeedsIndex.ForStandardLibrary
2131 void "test suggest Object methods when super is unresolved"() {
2132 def checkGetClassPresent = { String text ->
2133 myFixture.configureByText("a.java", text)
2134 myFixture.completeBasic()
2135 myFixture.assertPreferredCompletionItems 0, 'getClass'
2137 checkGetClassPresent("class C extends Unresolved {{ getCl<caret>x }}")
2138 checkGetClassPresent("class C implements Unresolved {{ getCl<caret>x }}")
2139 checkGetClassPresent("class C extends Unresolved implements Runnable {{ getCl<caret>x }}")
2140 checkGetClassPresent("class C extends Unresolved1 implements Unresolved2 {{ getCl<caret>x }}")
2143 void testSuggestInverseOfDefaultAnnoParamValueForBoolean() {
2144 configureByTestName()
2145 myFixture.assertPreferredCompletionItems(0, 'smth = true', 'value = false')
2147 def smthDefault = myItems.find { it.lookupString == 'smth = false' }
2148 def presentation = renderElement(smthDefault)
2149 assert presentation.tailText == ' (default)'
2150 assert presentation.tailFragments[0].grayed
2152 myFixture.type('\n')
2156 void testCaseColonAfterStringConstant() { doTest() }
2158 void testOneElementArray() {
2159 configureByTestName()
2160 myFixture.assertPreferredCompletionItems 0, 'aaa', 'aaa[0]'
2161 selectItem(myItems[1])
2165 void testSuggestChainsOfExpectedType() {
2167 myFixture.assertPreferredCompletionItems 0, 'bar', 'bar().getGoo'
2168 selectItem(myItems[1])
2172 void testTopLevelPublicClass() { doTest() }
2173 void testTopLevelPublicClassIdentifierExists() { doTest() }
2174 void testTopLevelPublicClassBraceExists() { doTest() }
2176 void testPerformanceWithManyNonMatchingDeclarations() {
2177 def importedNumbers = 0..<10
2178 for (i in (importedNumbers)) {
2179 myFixture.addClass("class Foo$i {\n" +
2180 (0..100).collect { "static int FOO$it = 3;\n" }.join("") +
2183 String text = importedNumbers.collect { "import static Foo${it}.*;\n" }.join("") +
2185 (0..100).collect { "String method$it() {}\n" } +
2187 "int localVariable = 2;\n" +
2188 "localV<caret>x }" +
2190 myFixture.configureByText("a.java", text)
2191 PlatformTestUtil.startPerformanceTest(name, 300, {
2192 assert myFixture.completeBasic().length == 1
2194 lookup?.hideLookup(true)
2195 myFixture.type("\bV")
2196 psiManager.dropPsiCaches()
2201 void "test performance with many matching statically-imported declarations"() {
2202 def fieldCount = 7000
2204 myFixture.addClass("interface Constants {" +
2205 (0..<fieldCount).collect { "String field$it = \"x\";\n" } +
2207 myFixture.configureByText("a.java", "import static Constants.*; class C { { field<caret>x } }")
2208 PlatformTestUtil.startPerformanceTest(name, 10_000, {
2209 assert myFixture.completeBasic().length > 100
2211 lookup?.hideLookup(true)
2212 myFixture.type("\bd")
2213 psiManager.dropPsiCaches()