diff options
author | George Fraser <george@fivetran.com> | 2018-09-15 17:05:59 -0700 |
---|---|---|
committer | George Fraser <george@fivetran.com> | 2018-09-15 17:05:59 -0700 |
commit | 2f20929eaa41bb0af83340b935e9ccd0361e51a3 (patch) | |
tree | 1b4ce1a0d700e9f7da61069c60bcffb85912c4dd /src/test | |
parent | 5703dc4cce4c58b34a302cadfc1ed836c1e3e165 (diff) | |
parent | 525d4e00cb66ca250b8a5640c7fa16652840ecd6 (diff) | |
download | java-language-server-2f20929eaa41bb0af83340b935e9ccd0361e51a3.zip |
Merge branch 'presentation_compiler'
Diffstat (limited to 'src/test')
73 files changed, 1394 insertions, 1758 deletions
diff --git a/src/test/java/org/javacs/ArtifactTest.java b/src/test/java/org/javacs/ArtifactTest.java index 02dbf60..e5c9297 100644 --- a/src/test/java/org/javacs/ArtifactTest.java +++ b/src/test/java/org/javacs/ArtifactTest.java @@ -13,8 +13,7 @@ public class ArtifactTest { @Test public void parseLong() { - assertThat( - Artifact.parse("foo:bar:jar:1:compile"), equalTo(new Artifact("foo", "bar", "1"))); + assertThat(Artifact.parse("foo:bar:jar:1:compile"), equalTo(new Artifact("foo", "bar", "1"))); } @Test(expected = IllegalArgumentException.class) diff --git a/src/test/java/org/javacs/ClassPathIndexTest.java b/src/test/java/org/javacs/ClassPathIndexTest.java deleted file mode 100644 index 99a3d4a..0000000 --- a/src/test/java/org/javacs/ClassPathIndexTest.java +++ /dev/null @@ -1,73 +0,0 @@ -package org.javacs; - -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import com.google.common.reflect.ClassPath; -import java.io.IOException; -import java.net.URL; -import java.net.URLClassLoader; -import java.nio.file.Paths; -import java.util.Collections; -import java.util.Optional; -import org.junit.Test; - -public class ClassPathIndexTest { - - @Test - public void createEmptyLoader() throws ClassNotFoundException { - ClassLoader emptyClassLoader = ClassPathIndex.parentClassLoader(); - - assertThat(emptyClassLoader.loadClass("java.util.ArrayList"), not(nullValue())); - - try { - Class<?> found = emptyClassLoader.loadClass("com.google.common.collect.Lists"); - - fail("Found " + found); - } catch (ClassNotFoundException e) { - // OK - } - } - - @Test - public void java8Platform() throws IOException { - String javaHome = - Paths.get("./src/test/test-platforms/jdk8-home").toAbsolutePath().toString(); - URL[] resources = ClassPathIndex.java8Platform(javaHome); - assertThat( - "found example.jar", - resources, - hasItemInArray(hasToString(containsString("rt.jar")))); - ClassPath classPath = ClassPath.from(new URLClassLoader(resources, null)); - assertThat( - classPath.getTopLevelClasses(), - hasItem(hasProperty("simpleName", equalTo("HelloWorld")))); - } - - @Test - public void java9Platform() throws IOException { - String javaHome = - Paths.get("./src/test/test-platforms/jdk9-home").toAbsolutePath().toString(); - URL[] resources = ClassPathIndex.java9Platform(javaHome); - assertThat( - "found java.compiler.jmod", - resources, - hasItemInArray(hasToString(containsString("java.compiler.jmod")))); - ClassPath classPath = ClassPath.from(new URLClassLoader(resources, null)); - assertThat( - classPath.getTopLevelClasses(), - hasItem(hasProperty("simpleName", equalTo("JavaCompiler")))); - } - - @Test - public void topLevelClasses() { - ClassPathIndex index = new ClassPathIndex(Collections.emptySet()); - Optional<ClassPath.ClassInfo> arrayList = - index.topLevelClasses() - .filter(c -> c.getName().equals("java.util.ArrayList")) - .findFirst(); - assertTrue("java.util.ArrayList is on the classpath", arrayList.isPresent()); - } -} diff --git a/src/test/java/org/javacs/ClassesTest.java b/src/test/java/org/javacs/ClassesTest.java new file mode 100644 index 0000000..323dea4 --- /dev/null +++ b/src/test/java/org/javacs/ClassesTest.java @@ -0,0 +1,70 @@ +package org.javacs; + +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; + +import com.google.common.reflect.ClassPath; +import java.net.URI; +import java.nio.file.FileSystems; +import java.nio.file.Files; +import java.util.Collections; +import org.junit.Test; + +public class ClassesTest { + + @Test + public void list() { + var jdk = Classes.jdkTopLevelClasses(); + assertThat(jdk.classes(), hasItem("java.util.List")); + assertThat(jdk.load("java.util.List"), not(nullValue())); + + var empty = Classes.classPathTopLevelClasses(Collections.emptySet()); + assertThat(empty.classes(), not(hasItem("java.util.List"))); + } + + @Test + public void arrayList() { + var jdk = Classes.jdkTopLevelClasses(); + assertThat(jdk.classes(), hasItem("java.util.ArrayList")); + assertThat(jdk.load("java.util.ArrayList"), not(nullValue())); + } + + @Test + public void platformClassPath() throws Exception { + var fs = FileSystems.getFileSystem(URI.create("jrt:/")); + var path = fs.getPath("/"); + Files.walk(path).forEach(p -> System.out.println(p)); + } + + @Test + public void loadMain() throws Exception { + var classes = ClassPath.from(this.getClass().getClassLoader()); + var found = classes.getTopLevelClasses("org.javacs"); + assertThat(found, hasItem(hasToString("org.javacs.Main"))); + + var main = found.stream().filter(c -> c.getName().equals("org.javacs.Main")).findFirst(); + assertTrue(main.isPresent()); + + var load = main.get().load(); + assertNotNull(load); + } + + void ancestors(ClassLoader classLoader) { + while (classLoader != null) { + System.out.println(classLoader.toString()); + classLoader = classLoader.getParent(); + } + } + + @Test + public void printAncestors() throws Exception { + System.out.println("This:"); + ancestors(this.getClass().getClassLoader()); + System.out.println("List:"); + ancestors(java.util.List.class.getClassLoader()); + System.out.println("System:"); + ancestors(ClassLoader.getSystemClassLoader()); + System.out.println("Platform:"); + ancestors(ClassLoader.getPlatformClassLoader()); + } +} diff --git a/src/test/java/org/javacs/CodeActionsTest.java b/src/test/java/org/javacs/CodeActionsTest.java deleted file mode 100644 index d2bbc61..0000000 --- a/src/test/java/org/javacs/CodeActionsTest.java +++ /dev/null @@ -1,105 +0,0 @@ -package org.javacs; - -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.hasItem; -import static org.junit.Assert.assertThat; - -import java.io.*; -import java.net.URI; -import java.nio.file.Files; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.stream.Collectors; -import java.util.stream.Stream; -import org.eclipse.lsp4j.*; -import org.junit.Before; -import org.junit.Test; - -public class CodeActionsTest { - - private static List<Diagnostic> diagnostics = new ArrayList<>(); - - @Before - public void before() { - diagnostics.clear(); - } - - private static final JavaLanguageServer server = - LanguageServerFixture.getJavaLanguageServer( - LanguageServerFixture.DEFAULT_WORKSPACE_ROOT, diagnostics::add); - - @Test - public void addImport() { - List<String> titles = - commands("/org/javacs/example/MissingImport.java", 5, 14) - .stream() - .map(c -> c.getTitle()) - .collect(Collectors.toList()); - - assertThat(titles, hasItem("Import java.util.ArrayList")); - } - - @Test - public void missingImport() { - String message = - "cannot find symbol\n" - + " symbol: class ArrayList\n" - + " location: class org.javacs.MissingImport"; - - assertThat( - CodeActions.cannotFindSymbolClassName(message), equalTo(Optional.of("ArrayList"))); - } - - private List<? extends Command> commands(String file, int row, int column) { - URI uri = FindResource.uri(file); - TextDocumentIdentifier document = new TextDocumentIdentifier(uri.toString()); - - try { - InputStream in = Files.newInputStream(new File(uri).toPath()); - String content = - new BufferedReader(new InputStreamReader(in)) - .lines() - .collect(Collectors.joining("\n")); - TextDocumentItem open = new TextDocumentItem(); - - open.setText(content); - open.setUri(uri.toString()); - open.setLanguageId("java"); - - server.getTextDocumentService().didOpen(new DidOpenTextDocumentParams(open, content)); - server.getTextDocumentService() - .didSave(new DidSaveTextDocumentParams(document, content)); - - return diagnostics - .stream() - .filter(diagnostic -> includes(diagnostic.getRange(), row - 1, column - 1)) - .flatMap(diagnostic -> codeActionsAt(document, diagnostic)) - .collect(Collectors.toList()); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - private boolean includes(Range range, int line, int character) { - boolean startCondition = - range.getStart().getLine() < line - || (range.getStart().getLine() == line - && range.getStart().getCharacter() <= character); - boolean endCondition = - line < range.getEnd().getLine() - || (line == range.getEnd().getLine() - && character <= range.getEnd().getCharacter()); - - return startCondition && endCondition; - } - - private Stream<? extends Command> codeActionsAt( - TextDocumentIdentifier documentId, Diagnostic diagnostic) { - CodeActionParams params = - new CodeActionParams( - documentId, diagnostic.getRange(), new CodeActionContext(diagnostics)); - - return server.getTextDocumentService().codeAction(params).join().stream(); - } -} diff --git a/src/test/java/org/javacs/CodeLensTest.java b/src/test/java/org/javacs/CodeLensTest.java new file mode 100644 index 0000000..cfc3714 --- /dev/null +++ b/src/test/java/org/javacs/CodeLensTest.java @@ -0,0 +1,27 @@ +package org.javacs; + +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; + +import java.util.concurrent.ExecutionException; +import org.eclipse.lsp4j.CodeLensParams; +import org.eclipse.lsp4j.TextDocumentIdentifier; +import org.junit.Test; + +public class CodeLensTest { + + private static final JavaLanguageServer server = LanguageServerFixture.getJavaLanguageServer(); + + @Test + public void codeLens() { + var file = "/org/javacs/example/HasTest.java"; + var uri = FindResource.uri(file); + var params = new CodeLensParams(new TextDocumentIdentifier(uri.toString())); + try { + var lenses = server.getTextDocumentService().codeLens(params).get(); + assertThat(lenses, not(empty())); + } catch (InterruptedException | ExecutionException e) { + throw new RuntimeException(e); + } + } +} diff --git a/src/test/java/org/javacs/CompilerProfiling.java b/src/test/java/org/javacs/CompilerProfiling.java deleted file mode 100644 index 01308ea..0000000 --- a/src/test/java/org/javacs/CompilerProfiling.java +++ /dev/null @@ -1,43 +0,0 @@ -package org.javacs; - -import java.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; -import java.nio.file.Paths; -import java.time.Duration; -import java.util.Collections; -import java.util.Optional; -import java.util.logging.Logger; -import javax.tools.DiagnosticCollector; -import javax.tools.JavaFileObject; -import org.junit.Ignore; -import org.junit.Test; - -@Ignore -public class CompilerProfiling { - private static final Logger LOG = Logger.getLogger("main"); - - @Test - public void parsingSpeed() throws IOException, URISyntaxException { - URI file = FindResource.uri("/org/javacs/example/LargeFile.java"); - - for (int i = 0; i < 10; i++) { - Duration duration = compileLargeFile(file); - - LOG.info(duration.toString()); - } - } - - private Duration compileLargeFile(URI file) { - long start = System.nanoTime(); - JavacHolder compiler = - JavacHolder.create( - Collections.singleton(Paths.get("src/test/test-project/workspace/src")), - Collections.emptySet()); - DiagnosticCollector<JavaFileObject> result = - compiler.compileBatch(Collections.singletonMap(file, Optional.empty())); - long finish = System.nanoTime(); - - return Duration.ofNanos(finish - start); - } -} diff --git a/src/test/java/org/javacs/CompletionsBase.java b/src/test/java/org/javacs/CompletionsBase.java index d68bcb6..929e808 100644 --- a/src/test/java/org/javacs/CompletionsBase.java +++ b/src/test/java/org/javacs/CompletionsBase.java @@ -1,31 +1,28 @@ package org.javacs; +import com.google.gson.Gson; import java.io.IOException; -import java.net.URI; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; +import java.util.*; import java.util.concurrent.ExecutionException; import java.util.logging.Logger; import java.util.stream.Collectors; import java.util.stream.Stream; import org.eclipse.lsp4j.CompletionItem; +import org.eclipse.lsp4j.CompletionParams; import org.eclipse.lsp4j.Position; import org.eclipse.lsp4j.TextDocumentIdentifier; -import org.eclipse.lsp4j.TextDocumentPositionParams; public class CompletionsBase { protected static final Logger LOG = Logger.getLogger("main"); protected Set<String> insertTemplate(String file, int row, int column) throws IOException { - List<? extends CompletionItem> items = items(file, row, column); + var items = items(file, row, column); return items.stream().map(CompletionsBase::itemInsertTemplate).collect(Collectors.toSet()); } static String itemInsertTemplate(CompletionItem i) { - String text = i.getInsertText(); + var text = i.getInsertText(); if (text == null) text = i.getLabel(); @@ -35,19 +32,29 @@ public class CompletionsBase { } protected Set<String> insertText(String file, int row, int column) throws IOException { - List<? extends CompletionItem> items = items(file, row, column); + var items = items(file, row, column); return items.stream().map(CompletionsBase::itemInsertText).collect(Collectors.toSet()); } - protected Map<String, Integer> insertCount(String file, int row, int column) - throws IOException { - List<? extends CompletionItem> items = items(file, row, column); - Map<String, Integer> result = new HashMap<>(); + protected Set<String> detail(String file, int row, int column) throws IOException { + var items = items(file, row, column); + var result = new HashSet<String>(); + for (var i : items) { + i.setData(new Gson().toJsonTree(i.getData())); + var resolved = resolve(i); + result.add(resolved.getDetail()); + } + return result; + } - for (CompletionItem each : items) { - String key = itemInsertText(each); - int count = result.getOrDefault(key, 0) + 1; + protected Map<String, Integer> insertCount(String file, int row, int column) throws IOException { + var items = items(file, row, column); + var result = new HashMap<String, Integer>(); + + for (var each : items) { + var key = itemInsertText(each); + var count = result.getOrDefault(key, 0) + 1; result.put(key, count); } @@ -56,7 +63,7 @@ public class CompletionsBase { } static String itemInsertText(CompletionItem i) { - String text = i.getInsertText(); + var text = i.getInsertText(); if (text == null) text = i.getLabel(); @@ -68,28 +75,24 @@ public class CompletionsBase { } protected Set<String> documentation(String file, int row, int column) throws IOException { - List<? extends CompletionItem> items = items(file, row, column); + var items = items(file, row, column); return items.stream() .flatMap( i -> { if (i.getDocumentation() != null) - return Stream.of(i.getDocumentation().trim()); + return Stream.of(i.getDocumentation().getRight().getValue().trim()); else return Stream.empty(); }) .collect(Collectors.toSet()); } - protected static final JavaLanguageServer server = - LanguageServerFixture.getJavaLanguageServer(); + protected static final JavaLanguageServer server = LanguageServerFixture.getJavaLanguageServer(); protected List<? extends CompletionItem> items(String file, int row, int column) { - URI uri = FindResource.uri(file); - TextDocumentPositionParams position = - new TextDocumentPositionParams( - new TextDocumentIdentifier(uri.toString()), - uri.toString(), - new Position(row - 1, column - 1)); + var uri = FindResource.uri(file); + var position = + new CompletionParams(new TextDocumentIdentifier(uri.toString()), new Position(row - 1, column - 1)); try { return server.getTextDocumentService().completion(position).get().getRight().getItems(); @@ -97,4 +100,12 @@ public class CompletionsBase { throw new RuntimeException(e); } } + + protected CompletionItem resolve(CompletionItem item) { + try { + return server.getTextDocumentService().resolveCompletionItem(item).get(); + } catch (InterruptedException | ExecutionException e) { + throw new RuntimeException(e); + } + } } diff --git a/src/test/java/org/javacs/CompletionsScopesTest.java b/src/test/java/org/javacs/CompletionsScopesTest.java index 4f43498..50b4759 100644 --- a/src/test/java/org/javacs/CompletionsScopesTest.java +++ b/src/test/java/org/javacs/CompletionsScopesTest.java @@ -5,223 +5,239 @@ import static org.hamcrest.Matchers.not; import static org.junit.Assert.assertThat; import java.io.IOException; -import java.util.Set; +import org.junit.Ignore; import org.junit.Test; public class CompletionsScopesTest extends CompletionsBase { @Test public void staticSub() throws IOException { - String file = "/org/javacs/example/AutocompleteScopes.java"; + var file = "/org/javacs/example/AutocompleteScopes.java"; // Static method - Set<String> suggestions = insertText(file, 15, 14); + var suggestions = insertText(file, 15, 14); // Locals - assertThat(suggestions, hasItems("localVariables", "arguments")); + assertThat(suggestions, hasItems("testLocalVariables", "testArguments")); // Static methods in enclosing scopes assertThat(suggestions, hasItems("testStatic")); - assertThat(suggestions, hasItems("outerStaticMethod")); + assertThat(suggestions, hasItems("testOuterStaticMethod")); // Virtual methods in enclosing scopes assertThat(suggestions, not(hasItems("testInner"))); assertThat(suggestions, hasItems("test")); - assertThat(suggestions, not(hasItems("outerMethods"))); + // TODO this is not accessible + // assertThat(suggestions, not(hasItems("testOuterMethods"))); // Inherited static methods - assertThat(suggestions, hasItems("inheritedStaticMethod")); + assertThat(suggestions, hasItems("testInheritedStaticMethod")); // Inherited virtual methods - assertThat(suggestions, hasItems("inheritedMethods")); + assertThat(suggestions, hasItems("testInheritedMethods")); // this/super in enclosing scopes - assertThat(suggestions, hasItems("this", "super")); + assertThat(suggestions, hasItems("this")); } @Test public void staticSubThisSuper() throws IOException { - String file = "/org/javacs/example/AutocompleteScopes.java"; + var file = "/org/javacs/example/AutocompleteScopes.java"; // StaticSub.this, StaticSub.super - assertThat(insertText(file, 37, 23), hasItems("this", "super")); + assertThat(insertText(file, 37, 23), hasItems("this")); // AutocompleteScopes.this, AutocompleteScopes.super - assertThat(insertText(file, 39, 32), not(hasItems("this", "super"))); + // TODO this is not accessible + // assertThat(insertText(file, 39, 32), not(hasItems("this"))); // Super.this, Super.super - assertThat(insertText(file, 41, 19), not(hasItems("this", "super"))); + // TODO this is not accessible + // assertThat(insertText(file, 41, 19), not(hasItems("this"))); } @Test public void staticSubInner() throws IOException { - String file = "/org/javacs/example/AutocompleteScopes.java"; + var file = "/org/javacs/example/AutocompleteScopes.java"; // Static method - Set<String> suggestions = insertText(file, 45, 22); + var suggestions = insertText(file, 45, 22); // Locals - assertThat(suggestions, hasItems("localVariables", "arguments")); + assertThat(suggestions, hasItems("testLocalVariables", "testArguments")); // Static methods in enclosing scopes assertThat(suggestions, hasItems("testStatic")); - assertThat(suggestions, hasItems("outerStaticMethod")); + assertThat(suggestions, hasItems("testOuterStaticMethod")); // Virtual methods in enclosing scopes assertThat(suggestions, hasItems("testInner")); assertThat(suggestions, hasItems("test")); - assertThat(suggestions, not(hasItems("outerMethods"))); + // TODO this is not accessible + // assertThat(suggestions, not(hasItems("testOuterMethods"))); // Inherited static methods - assertThat(suggestions, hasItems("inheritedStaticMethod")); + assertThat(suggestions, hasItems("testInheritedStaticMethod")); // Inherited virtual methods - assertThat(suggestions, hasItems("inheritedMethods")); + assertThat(suggestions, hasItems("testInheritedMethods")); // this/super in enclosing scopes - assertThat(suggestions, hasItems("this", "super")); + assertThat(suggestions, hasItems("this")); } @Test public void staticSubInnerThisSuper() throws IOException { - String file = "/org/javacs/example/AutocompleteScopes.java"; + var file = "/org/javacs/example/AutocompleteScopes.java"; // StaticSub.this, StaticSub.super - assertThat(insertText(file, 67, 31), hasItems("this", "super")); + assertThat(insertText(file, 67, 31), hasItems("this")); // AutocompleteScopes.this, AutocompleteScopes.super - assertThat(insertText(file, 69, 40), not(hasItems("this", "super"))); + // TODO this is not accessible + // assertThat(insertText(file, 69, 40), not(hasItems("this"))); // Super.this, Super.super - assertThat(insertText(file, 71, 27), not(hasItems("this", "super"))); + // TODO this is not accessible + // assertThat(insertText(file, 71, 27), not(hasItems("this"))); } @Test public void staticSubStaticMethod() throws IOException { - String file = "/org/javacs/example/AutocompleteScopes.java"; + var file = "/org/javacs/example/AutocompleteScopes.java"; // Static method - Set<String> suggestions = insertText(file, 78, 14); + var suggestions = insertText(file, 78, 14); // Locals - assertThat(suggestions, hasItems("localVariables", "arguments")); + assertThat(suggestions, hasItems("testLocalVariables", "testArguments")); // Static methods in enclosing scopes assertThat(suggestions, hasItems("testStatic")); - assertThat(suggestions, hasItems("outerStaticMethod")); + assertThat(suggestions, hasItems("testOuterStaticMethod")); // Virtual methods in enclosing scopes assertThat(suggestions, not(hasItems("testInner"))); assertThat(suggestions, not(hasItems("test"))); - assertThat(suggestions, not(hasItems("outerMethods"))); + assertThat(suggestions, not(hasItems("testOuterMethods"))); // Inherited static methods - assertThat(suggestions, hasItems("inheritedStaticMethod")); + assertThat(suggestions, hasItems("testInheritedStaticMethod")); // Inherited virtual methods - assertThat(suggestions, not(hasItems("inheritedMethods"))); + assertThat(suggestions, not(hasItems("testInheritedMethods"))); // this/super in enclosing scopes - assertThat(suggestions, not(hasItems("this", "super"))); + // TODO this is not accessible + // assertThat(suggestions, not(hasItems("this"))); } + // TODO this is not accessible + @Ignore @Test public void staticSubStaticMethodThisSuper() throws IOException { - String file = "/org/javacs/example/AutocompleteScopes.java"; + var file = "/org/javacs/example/AutocompleteScopes.java"; // StaticSub.this, StaticSub.super - assertThat(insertText(file, 100, 23), not(hasItems("this", "super"))); + assertThat(insertText(file, 100, 23), not(hasItems("this"))); // AutocompleteScopes.this, AutocompleteScopes.super - assertThat(insertText(file, 102, 32), not(hasItems("this", "super"))); + assertThat(insertText(file, 102, 32), not(hasItems("this"))); // Super.this, Super.super - assertThat(insertText(file, 104, 19), not(hasItems("this", "super"))); + assertThat(insertText(file, 104, 19), not(hasItems("this"))); } @Test public void staticSubStaticMethodInner() throws IOException { - String file = "/org/javacs/example/AutocompleteScopes.java"; + var file = "/org/javacs/example/AutocompleteScopes.java"; // Static method - Set<String> suggestions = insertText(file, 108, 22); + var suggestions = insertText(file, 108, 22); // Locals - assertThat(suggestions, hasItems("localVariables", "arguments")); + assertThat(suggestions, hasItems("testLocalVariables", "testArguments")); // Static methods in enclosing scopes assertThat(suggestions, hasItems("testStatic")); - assertThat(suggestions, hasItems("outerStaticMethod")); + assertThat(suggestions, hasItems("testOuterStaticMethod")); // Virtual methods in enclosing scopes assertThat(suggestions, hasItems("testInner")); - assertThat(suggestions, not(hasItems("test"))); - assertThat(suggestions, not(hasItems("outerMethods"))); + // TODO this is not accessible + // assertThat(suggestions, not(hasItems("test"))); + // TODO this is not accessible + // assertThat(suggestions, not(hasItems("testOuterMethods"))); // Inherited static methods - assertThat(suggestions, hasItems("inheritedStaticMethod")); + assertThat(suggestions, hasItems("testInheritedStaticMethod")); // Inherited virtual methods - assertThat(suggestions, not(hasItems("inheritedMethods"))); + // TODO this is not accessible + // assertThat(suggestions, not(hasItems("testInheritedMethods"))); // this/super in enclosing scopes - assertThat(suggestions, hasItems("this", "super")); + assertThat(suggestions, hasItems("this")); } + // TODO this is not accessible + @Ignore @Test public void staticSubStaticMethodInnerThisSuper() throws IOException { - String file = "/org/javacs/example/AutocompleteScopes.java"; + var file = "/org/javacs/example/AutocompleteScopes.java"; // StaticSub.this, StaticSub.super - assertThat(insertText(file, 130, 31), not(hasItems("this", "super"))); + assertThat(insertText(file, 130, 31), not(hasItems("this"))); // AutocompleteScopes.this, AutocompleteScopes.super - assertThat(insertText(file, 132, 40), not(hasItems("this", "super"))); + assertThat(insertText(file, 132, 40), not(hasItems("this"))); // Super.this, Super.super - assertThat(insertText(file, 134, 27), not(hasItems("this", "super"))); + assertThat(insertText(file, 134, 27), not(hasItems("this"))); } @Test public void sub() throws IOException { - String file = "/org/javacs/example/AutocompleteScopes.java"; + var file = "/org/javacs/example/AutocompleteScopes.java"; // Static method - Set<String> suggestions = insertText(file, 143, 14); + var suggestions = insertText(file, 143, 14); // Locals - assertThat(suggestions, hasItems("localVariables", "arguments")); + assertThat(suggestions, hasItems("testLocalVariables", "testArguments")); // Static methods in enclosing scopes assertThat(suggestions, not(hasItems("testStatic"))); - assertThat(suggestions, hasItems("outerStaticMethod")); + assertThat(suggestions, hasItems("testOuterStaticMethod")); // Virtual methods in enclosing scopes assertThat(suggestions, not(hasItems("testInner"))); assertThat(suggestions, hasItems("test")); - assertThat(suggestions, hasItems("outerMethods")); + assertThat(suggestions, hasItems("testOuterMethods")); // Inherited static methods - assertThat(suggestions, hasItems("inheritedStaticMethod")); + assertThat(suggestions, hasItems("testInheritedStaticMethod")); // Inherited virtual methods - assertThat(suggestions, hasItems("inheritedMethods")); + assertThat(suggestions, hasItems("testInheritedMethods")); // this/super in enclosing scopes - assertThat(suggestions, hasItems("this", "super")); + assertThat(suggestions, hasItems("this")); } @Test public void subThisSuper() throws IOException { - String file = "/org/javacs/example/AutocompleteScopes.java"; + var file = "/org/javacs/example/AutocompleteScopes.java"; // sub.this, sub.super - assertThat(insertText(file, 158, 17), hasItems("this", "super")); + assertThat(insertText(file, 158, 17), hasItems("this")); // AutocompleteScopes.this, AutocompleteScopes.super - assertThat(insertText(file, 160, 32), hasItems("this", "super")); + assertThat(insertText(file, 160, 32), hasItems("this")); // Super.this, Super.super - assertThat(insertText(file, 162, 19), not(hasItems("this", "super"))); + // TODO this is not accessible + // assertThat(insertText(file, 162, 19), not(hasItems("this"))); } @Test public void subInner() throws IOException { - String file = "/org/javacs/example/AutocompleteScopes.java"; + var file = "/org/javacs/example/AutocompleteScopes.java"; // Static method - Set<String> suggestions = insertText(file, 166, 22); + var suggestions = insertText(file, 166, 22); // Locals - assertThat(suggestions, hasItems("localVariables", "arguments")); + assertThat(suggestions, hasItems("testLocalVariables", "testArguments")); // Static methods in enclosing scopes assertThat(suggestions, not(hasItems("testStatic"))); - assertThat(suggestions, hasItems("outerStaticMethod")); + assertThat(suggestions, hasItems("testOuterStaticMethod")); // Virtual methods in enclosing scopes assertThat(suggestions, hasItems("testInner")); assertThat(suggestions, hasItems("test")); - assertThat(suggestions, hasItems("outerMethods")); + assertThat(suggestions, hasItems("testOuterMethods")); // Inherited static methods - assertThat(suggestions, hasItems("inheritedStaticMethod")); + assertThat(suggestions, hasItems("testInheritedStaticMethod")); // Inherited virtual methods - assertThat(suggestions, hasItems("inheritedMethods")); + assertThat(suggestions, hasItems("testInheritedMethods")); // this/super in enclosing scopes - assertThat(suggestions, hasItems("this", "super")); + assertThat(suggestions, hasItems("this")); } @Test public void subInnerThisSuper() throws IOException { - String file = "/org/javacs/example/AutocompleteScopes.java"; + var file = "/org/javacs/example/AutocompleteScopes.java"; // sub.this, sub.super - assertThat(insertText(file, 181, 25), hasItems("this", "super")); + assertThat(insertText(file, 181, 25), hasItems("this")); // AutocompleteScopes.this, AutocompleteScopes.super - assertThat(insertText(file, 183, 40), hasItems("this", "super")); + assertThat(insertText(file, 183, 40), hasItems("this")); // Super.this, Super.super - assertThat(insertText(file, 185, 27), not(hasItems("this", "super"))); + // TODO this is not accessible + // assertThat(insertText(file, 185, 27), not(hasItems("this"))); } } diff --git a/src/test/java/org/javacs/CompletionsTest.java b/src/test/java/org/javacs/CompletionsTest.java index ce1455d..46d7eb0 100644 --- a/src/test/java/org/javacs/CompletionsTest.java +++ b/src/test/java/org/javacs/CompletionsTest.java @@ -5,9 +5,6 @@ import static org.junit.Assert.*; import com.google.common.collect.Lists; import java.io.IOException; -import java.util.List; -import java.util.Map; -import java.util.Set; import java.util.stream.Collectors; import org.eclipse.lsp4j.CompletionItem; import org.junit.Ignore; @@ -17,222 +14,219 @@ public class CompletionsTest extends CompletionsBase { @Test public void staticMember() throws IOException { - String file = "/org/javacs/example/AutocompleteStaticMember.java"; + var file = "/org/javacs/example/AutocompleteStaticMember.java"; // Static methods - Set<String> suggestions = insertText(file, 5, 34); + var suggestions = insertText(file, 5, 38); - assertThat(suggestions, hasItems("fieldStatic", "methodStatic", "class")); - assertThat(suggestions, not(hasItems("fields", "methods", "getClass"))); + assertThat(suggestions, hasItems("testFieldStatic", "testMethodStatic", "class")); + assertThat(suggestions, not(hasItems("testField", "testMethod", "getClass"))); } @Test public void staticReference() throws IOException { - String file = "/org/javacs/example/AutocompleteStaticReference.java"; + var file = "/org/javacs/example/AutocompleteStaticReference.java"; // Static methods - Set<String> suggestions = insertText(file, 7, 44); + var suggestions = insertText(file, 7, 48); - assertThat(suggestions, hasItems("methods", "methodStatic")); - assertThat(suggestions, not(hasItems("new"))); + assertThat(suggestions, hasItems("testMethod", "testMethodStatic", "new")); + assertThat(suggestions, not(hasItems("class"))); } @Test public void member() throws IOException { - String file = "/org/javacs/example/AutocompleteMember.java"; + var file = "/org/javacs/example/AutocompleteMember.java"; - // Virtual methods - Set<String> suggestions = insertText(file, 5, 14); + // Virtual testMethods + var suggestions = insertText(file, 5, 14); assertThat( "excludes static members", suggestions, not( hasItems( - "fieldStatic", - "methodStatic", - "fieldStaticPrivate", - "methodStaticPrivate", + "testFieldStatic", + "testMethodStatic", + "testFieldStaticPrivate", + "testMethodStaticPrivate", "class", "AutocompleteMember"))); assertThat( "includes non-static members", suggestions, - hasItems("fields", "methods", "fieldsPrivate", "methodsPrivate", "getClass")); - assertThat( - "excludes constructors", - suggestions, - not(hasItem(startsWith("AutocompleteMember")))); + hasItems("testFields", "testMethods", "testFieldsPrivate", "testMethodsPrivate", "getClass")); + assertThat("excludes constructors", suggestions, not(hasItem(startsWith("AutocompleteMember")))); } @Test @Ignore // This has been subsumed by Javadocs public void throwsSignature() throws IOException { - String file = "/org/javacs/example/AutocompleteMember.java"; + var file = "/org/javacs/example/AutocompleteMember.java"; // Static methods - List<? extends CompletionItem> items = items(file, 5, 14); - Set<String> suggestions = items.stream().map(i -> i.getLabel()).collect(Collectors.toSet()); - Set<String> details = items.stream().map(i -> i.getDetail()).collect(Collectors.toSet()); + var items = items(file, 5, 14); + var suggestions = items.stream().map(i -> i.getLabel()).collect(Collectors.toSet()); + var details = items.stream().map(i -> i.getDetail()).collect(Collectors.toSet()); - assertThat(suggestions, hasItems("methods")); + assertThat(suggestions, hasItems("testMethods")); assertThat(details, hasItems("String () throws Exception")); } @Test public void fieldFromInitBlock() throws IOException { - String file = "/org/javacs/example/AutocompleteMembers.java"; + var file = "/org/javacs/example/AutocompleteMembers.java"; // f - Set<String> suggestions = insertText(file, 8, 10); + var suggestions = insertText(file, 8, 10); - assertThat(suggestions, hasItems("fields", "fieldStatic", "methods", "methodStatic")); + assertThat(suggestions, hasItems("testFields", "testFieldStatic", "testMethods", "testMethodStatic")); } @Test public void thisDotFieldFromInitBlock() throws IOException { - String file = "/org/javacs/example/AutocompleteMembers.java"; + var file = "/org/javacs/example/AutocompleteMembers.java"; // this.f - Set<String> suggestions = insertText(file, 9, 15); + var suggestions = insertText(file, 9, 15); - assertThat(suggestions, hasItems("fields", "methods")); - assertThat(suggestions, not(hasItems("fieldStatic", "methodStatic"))); + assertThat(suggestions, hasItems("testFields", "testMethods")); + assertThat(suggestions, not(hasItems("testFieldStatic", "testMethodStatic"))); } @Test public void classDotFieldFromInitBlock() throws IOException { - String file = "/org/javacs/example/AutocompleteMembers.java"; + var file = "/org/javacs/example/AutocompleteMembers.java"; // AutocompleteMembers.f - Set<String> suggestions = insertText(file, 10, 30); + var suggestions = insertText(file, 10, 30); - assertThat(suggestions, hasItems("fieldStatic", "methodStatic")); - assertThat(suggestions, not(hasItems("fields", "methods"))); + assertThat(suggestions, hasItems("testFieldStatic", "testMethodStatic")); + assertThat(suggestions, not(hasItems("testFields", "testMethods"))); } @Test public void fieldFromMethod() throws IOException { - String file = "/org/javacs/example/AutocompleteMembers.java"; + var file = "/org/javacs/example/AutocompleteMembers.java"; // f - Set<String> suggestions = insertText(file, 22, 10); + var suggestions = insertText(file, 22, 10); assertThat( suggestions, - hasItems("fields", "fieldStatic", "methods", "methodStatic", "arguments")); + hasItems("testFields", "testFieldStatic", "testMethods", "testMethodStatic", "testArguments")); } @Test public void thisDotFieldFromMethod() throws IOException { - String file = "/org/javacs/example/AutocompleteMembers.java"; + var file = "/org/javacs/example/AutocompleteMembers.java"; // this.f - Set<String> suggestions = insertText(file, 23, 15); + var suggestions = insertText(file, 23, 15); - assertThat(suggestions, hasItems("fields", "methods")); - assertThat(suggestions, not(hasItems("fieldStatic", "methodStatic", "arguments"))); + assertThat(suggestions, hasItems("testFields", "testMethods")); + assertThat(suggestions, not(hasItems("testFieldStatic", "testMethodStatic", "testArguments"))); } @Test public void classDotFieldFromMethod() throws IOException { - String file = "/org/javacs/example/AutocompleteMembers.java"; + var file = "/org/javacs/example/AutocompleteMembers.java"; // AutocompleteMembers.f - Set<String> suggestions = insertText(file, 24, 30); + var suggestions = insertText(file, 24, 30); - assertThat(suggestions, hasItems("fieldStatic", "methodStatic")); - assertThat(suggestions, not(hasItems("fields", "methods", "arguments"))); + assertThat(suggestions, hasItems("testFieldStatic", "testMethodStatic")); + assertThat(suggestions, not(hasItems("testFields", "testMethods", "testArguments"))); } @Test public void thisRefMethodFromMethod() throws IOException { - String file = "/org/javacs/example/AutocompleteMembers.java"; + var file = "/org/javacs/example/AutocompleteMembers.java"; // this::m - Set<String> suggestions = insertText(file, 25, 59); + var suggestions = insertText(file, 25, 59); - assertThat(suggestions, hasItems("methods")); - assertThat(suggestions, not(hasItems("fields", "fieldStatic", "methodStatic"))); + assertThat(suggestions, hasItems("testMethods")); + assertThat(suggestions, not(hasItems("testFields", "testFieldStatic", "testMethodStatic"))); } @Test public void classRefMethodFromMethod() throws IOException { - String file = "/org/javacs/example/AutocompleteMembers.java"; + var file = "/org/javacs/example/AutocompleteMembers.java"; // AutocompleteMembers::m - Set<String> suggestions = insertText(file, 26, 74); + var suggestions = insertText(file, 26, 74); - assertThat(suggestions, hasItems("methodStatic", "methods")); - assertThat(suggestions, not(hasItems("fields", "fieldStatic"))); + assertThat(suggestions, hasItems("testMethodStatic", "testMethods")); + assertThat(suggestions, not(hasItems("testFields", "testFieldStatic"))); } @Test @Ignore // javac doesn't give us helpful info about the fact that static initializers are static public void fieldFromStaticInitBlock() throws IOException { - String file = "/org/javacs/example/AutocompleteMembers.java"; + var file = "/org/javacs/example/AutocompleteMembers.java"; // f - Set<String> suggestions = insertText(file, 16, 10); + var suggestions = insertText(file, 16, 10); - assertThat(suggestions, hasItems("fieldStatic", "methodStatic")); - assertThat(suggestions, not(hasItems("fields", "methods"))); + assertThat(suggestions, hasItems("testFieldStatic", "testMethodStatic")); + assertThat(suggestions, not(hasItems("testFields", "testMethods"))); } @Test public void classDotFieldFromStaticInitBlock() throws IOException { - String file = "/org/javacs/example/AutocompleteMembers.java"; + var file = "/org/javacs/example/AutocompleteMembers.java"; // AutocompleteMembers.f - Set<String> suggestions = insertText(file, 17, 30); + var suggestions = insertText(file, 17, 30); - assertThat(suggestions, hasItems("fieldStatic", "methodStatic")); - assertThat(suggestions, not(hasItems("fields", "methods"))); + assertThat(suggestions, hasItems("testFieldStatic", "testMethodStatic")); + assertThat(suggestions, not(hasItems("testFields", "testMethods"))); } @Test public void classRefFieldFromStaticInitBlock() throws IOException { - String file = "/org/javacs/example/AutocompleteMembers.java"; + var file = "/org/javacs/example/AutocompleteMembers.java"; // AutocompleteMembers::m - Set<String> suggestions = insertText(file, 17, 30); + var suggestions = insertText(file, 17, 30); - assertThat(suggestions, hasItems("methodStatic")); - assertThat(suggestions, not(hasItems("fields", "fieldStatic", "methods"))); + assertThat(suggestions, hasItems("testMethodStatic")); + assertThat(suggestions, not(hasItems("testFields", "testFieldStatic", "testMethods"))); } @Test public void fieldFromStaticMethod() throws IOException { - String file = "/org/javacs/example/AutocompleteMembers.java"; + var file = "/org/javacs/example/AutocompleteMembers.java"; // f - Set<String> suggestions = insertText(file, 30, 10); + var suggestions = insertText(file, 30, 10); - assertThat(suggestions, hasItems("fieldStatic", "methodStatic", "arguments")); - assertThat(suggestions, not(hasItems("fields", "methods"))); + assertThat(suggestions, hasItems("testFieldStatic", "testMethodStatic", "testArguments")); + assertThat(suggestions, not(hasItems("testFields", "testMethods"))); } @Test public void classDotFieldFromStaticMethod() throws IOException { - String file = "/org/javacs/example/AutocompleteMembers.java"; + var file = "/org/javacs/example/AutocompleteMembers.java"; // AutocompleteMembers.f - Set<String> suggestions = insertText(file, 31, 30); + var suggestions = insertText(file, 31, 30); - assertThat(suggestions, hasItems("fieldStatic", "methodStatic")); - assertThat(suggestions, not(hasItems("fields", "methods", "arguments"))); + assertThat(suggestions, hasItems("testFieldStatic", "testMethodStatic")); + assertThat(suggestions, not(hasItems("testFields", "testMethods", "testArguments"))); } @Test public void classRefFieldFromStaticMethod() throws IOException { - String file = "/org/javacs/example/AutocompleteMembers.java"; + var file = "/org/javacs/example/AutocompleteMembers.java"; // TODO // AutocompleteMembers::m - Set<String> suggestions = insertText(file, 17, 30); + var suggestions = insertText(file, 17, 30); - assertThat(suggestions, hasItems("methodStatic")); - assertThat(suggestions, not(hasItems("fields", "fieldStatic", "methods"))); + assertThat(suggestions, hasItems("testMethodStatic")); + assertThat(suggestions, not(hasItems("testFields", "testFieldStatic", "testMethods"))); } private static String sortText(CompletionItem i) { @@ -242,63 +236,63 @@ public class CompletionsTest extends CompletionsBase { @Test public void otherMethod() throws IOException { - String file = "/org/javacs/example/AutocompleteOther.java"; + var file = "/org/javacs/example/AutocompleteOther.java"; // new AutocompleteMember(). - Set<String> suggestions = insertText(file, 5, 34); + var suggestions = insertText(file, 5, 34); - assertThat(suggestions, not(hasItems("fieldStatic", "methodStatic", "class"))); - assertThat(suggestions, not(hasItems("fieldStaticPrivate", "methodStaticPrivate"))); - assertThat(suggestions, not(hasItems("fieldsPrivate", "methodsPrivate"))); - assertThat(suggestions, hasItems("fields", "methods", "getClass")); + assertThat(suggestions, not(hasItems("testFieldStatic", "testMethodStatic", "class"))); + assertThat(suggestions, not(hasItems("testFieldStaticPrivate", "testMethodStaticPrivate"))); + assertThat(suggestions, not(hasItems("testFieldsPrivate", "testMethodsPrivate"))); + assertThat(suggestions, hasItems("testFields", "testMethods", "getClass")); } @Test public void otherStatic() throws IOException { - String file = "/org/javacs/example/AutocompleteOther.java"; + var file = "/org/javacs/example/AutocompleteOther.java"; // AutocompleteMember. - Set<String> suggestions = insertText(file, 7, 28); + var suggestions = insertText(file, 7, 28); - assertThat(suggestions, hasItems("fieldStatic", "methodStatic", "class")); - assertThat(suggestions, not(hasItems("fieldStaticPrivate", "methodStaticPrivate"))); - assertThat(suggestions, not(hasItems("fieldsPrivate", "methodsPrivate"))); - assertThat(suggestions, not(hasItems("fields", "methods", "getClass"))); + assertThat(suggestions, hasItems("testFieldStatic", "testMethodStatic", "class")); + assertThat(suggestions, not(hasItems("testFieldStaticPrivate", "testMethodStaticPrivate"))); + assertThat(suggestions, not(hasItems("testFieldsPrivate", "testMethodsPrivate"))); + assertThat(suggestions, not(hasItems("testFields", "testMethods", "getClass"))); } @Test public void otherDotClassDot() throws IOException { - String file = "/org/javacs/example/AutocompleteOther.java"; + var file = "/org/javacs/example/AutocompleteOther.java"; // AutocompleteMember.class. - Set<String> suggestions = insertText(file, 8, 33); + var suggestions = insertText(file, 8, 33); assertThat(suggestions, hasItems("getName", "getClass")); - assertThat(suggestions, not(hasItems("fieldStatic", "methodStatic", "class"))); - assertThat(suggestions, not(hasItems("fieldStaticPrivate", "methodStaticPrivate"))); - assertThat(suggestions, not(hasItems("fieldsPrivate", "methodsPrivate"))); - assertThat(suggestions, not(hasItems("fields", "methods"))); + assertThat(suggestions, not(hasItems("testFieldStatic", "testMethodStatic", "class"))); + assertThat(suggestions, not(hasItems("testFieldStaticPrivate", "testMethodStaticPrivate"))); + assertThat(suggestions, not(hasItems("testFieldsPrivate", "testMethodsPrivate"))); + assertThat(suggestions, not(hasItems("testFields", "testMethods"))); } @Test public void otherClass() throws IOException { - String file = "/org/javacs/example/AutocompleteOther.java"; + var file = "/org/javacs/example/AutocompleteOther.java"; - // Name of class - Set<String> suggestions = insertText(file, 6, 10); + // Auto? + var suggestions = insertText(file, 6, 13); - // String is in root scope, List is in import java.util.* assertThat(suggestions, hasItems("AutocompleteOther", "AutocompleteMember")); } + @Ignore // We are now managing imports with FixImports @Test public void addImport() { - String file = "/org/javacs/example/AutocompleteOther.java"; + var file = "/org/javacs/example/AutocompleteOther.java"; // Name of class - List<? extends CompletionItem> items = items(file, 9, 17); + var items = items(file, 9, 17); - for (CompletionItem item : items) { + for (var item : items) { if ("ArrayList".equals(item.getLabel())) { assertThat(item.getAdditionalTextEdits(), not(nullValue())); assertThat(item.getAdditionalTextEdits(), not(empty())); @@ -310,14 +304,15 @@ public class CompletionsTest extends CompletionsBase { fail("No ArrayList in " + items); } + @Ignore // We are now managing imports with FixImports @Test public void dontImportSamePackage() { - String file = "/org/javacs/example/AutocompleteOther.java"; + var file = "/org/javacs/example/AutocompleteOther.java"; // Name of class - List<? extends CompletionItem> items = items(file, 6, 10); + var items = items(file, 6, 10); - for (CompletionItem item : items) { + for (var item : items) { if ("AutocompleteMember".equals(item.getLabel())) { assertThat(item.getAdditionalTextEdits(), either(empty()).or(nullValue())); @@ -328,14 +323,15 @@ public class CompletionsTest extends CompletionsBase { fail("No AutocompleteMember in " + items); } + @Ignore // We are now managing imports with FixImports @Test public void dontImportJavaLang() { - String file = "/org/javacs/example/AutocompleteOther.java"; + var file = "/org/javacs/example/AutocompleteOther.java"; // Name of class - List<? extends CompletionItem> items = items(file, 11, 38); + var items = items(file, 11, 38); - for (CompletionItem item : items) { + for (var item : items) { if ("ArrayIndexOutOfBoundsException".equals(item.getLabel())) { assertThat(item.getAdditionalTextEdits(), either(empty()).or(nullValue())); @@ -346,14 +342,15 @@ public class CompletionsTest extends CompletionsBase { fail("No ArrayIndexOutOfBoundsException in " + items); } + @Ignore // We are now managing imports with FixImports @Test public void dontImportSelf() { - String file = "/org/javacs/example/AutocompleteOther.java"; + var file = "/org/javacs/example/AutocompleteOther.java"; // Name of class - List<? extends CompletionItem> items = items(file, 6, 10); + var items = items(file, 6, 10); - for (CompletionItem item : items) { + for (var item : items) { if ("AutocompleteOther".equals(item.getLabel())) { assertThat(item.getAdditionalTextEdits(), either(empty()).or(nullValue())); @@ -364,14 +361,15 @@ public class CompletionsTest extends CompletionsBase { fail("No AutocompleteOther in " + items); } + @Ignore // We are now managing imports with FixImports @Test public void dontImportAlreadyImported() { - String file = "/org/javacs/example/AutocompleteOther.java"; + var file = "/org/javacs/example/AutocompleteOther.java"; // Name of class - List<? extends CompletionItem> items = items(file, 12, 14); + var items = items(file, 12, 14); - for (CompletionItem item : items) { + for (var item : items) { if ("Arrays".equals(item.getLabel())) { assertThat(item.getAdditionalTextEdits(), either(empty()).or(nullValue())); @@ -382,14 +380,15 @@ public class CompletionsTest extends CompletionsBase { fail("No Arrays in " + items); } + @Ignore // We are now managing imports with FixImports @Test public void dontImportAlreadyImportedStar() { - String file = "/org/javacs/example/AutocompleteOther.java"; + var file = "/org/javacs/example/AutocompleteOther.java"; // Name of class - List<? extends CompletionItem> items = items(file, 10, 26); + var items = items(file, 10, 26); - for (CompletionItem item : items) { + for (var item : items) { if ("ArrayBlockingQueue".equals(item.getLabel())) { assertThat(item.getAdditionalTextEdits(), either(empty()).or(nullValue())); @@ -402,67 +401,71 @@ public class CompletionsTest extends CompletionsBase { @Test public void fromClasspath() throws IOException { - String file = "/org/javacs/example/AutocompleteFromClasspath.java"; + var file = "/org/javacs/example/AutocompleteFromClasspath.java"; // Static methods - List<? extends CompletionItem> items = items(file, 8, 17); - Set<String> suggestions = items.stream().map(i -> i.getLabel()).collect(Collectors.toSet()); - Set<String> details = items.stream().map(i -> i.getDetail()).collect(Collectors.toSet()); + var items = items(file, 8, 17); + var suggestions = items.stream().map(i -> i.getLabel()).collect(Collectors.toSet()); + var details = items.stream().map(i -> i.getDetail()).collect(Collectors.toSet()); assertThat(suggestions, hasItems("add", "addAll")); } @Test public void betweenLines() throws IOException { - String file = "/org/javacs/example/AutocompleteBetweenLines.java"; + var file = "/org/javacs/example/AutocompleteBetweenLines.java"; // Static methods - Set<String> suggestions = insertText(file, 9, 18); + var suggestions = insertText(file, 9, 18); assertThat(suggestions, hasItems("add")); } @Test public void reference() throws IOException { - String file = "/org/javacs/example/AutocompleteReference.java"; + var file = "/org/javacs/example/AutocompleteReference.java"; // Static methods - Set<String> suggestions = insertTemplate(file, 7, 21); + var suggestions = insertTemplate(file, 7, 21); - assertThat(suggestions, not(hasItems("methodStatic"))); - assertThat(suggestions, hasItems("methods", "getClass")); + assertThat(suggestions, not(hasItems("testMethodStatic"))); + assertThat(suggestions, hasItems("testMethods", "getClass")); } @Test @Ignore // This has been subsumed by Javadocs public void docstring() throws IOException { - String file = "/org/javacs/example/AutocompleteDocstring.java"; + var file = "/org/javacs/example/AutocompleteDocstring.java"; + var docstrings = documentation(file, 8, 14); - Set<String> docstrings = documentation(file, 8, 14); - - assertThat(docstrings, hasItems("A methods", "A fields")); + assertThat(docstrings, hasItems("A testMethods", "A testFields")); docstrings = documentation(file, 12, 31); - assertThat(docstrings, hasItems("A fieldStatic", "A methodStatic")); + assertThat(docstrings, hasItems("A testFieldStatic", "A testMethodStatic")); } @Test public void classes() throws IOException { - String file = "/org/javacs/example/AutocompleteClasses.java"; + var file = "/org/javacs/example/AutocompleteClasses.java"; - // Static methods - Set<String> suggestions = insertText(file, 5, 10); + // Fix? + var suggestions = insertText(file, 5, 12); + + assertThat(suggestions, hasItems("FixParseErrorAfter")); - assertThat(suggestions, hasItems("FixParseErrorAfter", "SomeInnerClass")); + // Some? + suggestions = insertText(file, 6, 13); + + assertThat(suggestions, hasItems("SomeInnerClass")); } @Test public void editMethodName() throws IOException { - String file = "/org/javacs/example/AutocompleteEditMethodName.java"; + var file = "/org/javacs/example/AutocompleteEditMethodName.java"; // Static methods - Set<String> suggestions = insertText(file, 5, 21); + var suggestions = insertText(file, 5, 21); assertThat(suggestions, hasItems("getClass")); } @@ -470,12 +473,12 @@ public class CompletionsTest extends CompletionsBase { @Test @Ignore // This has been subsumed by Javadocs public void restParams() throws IOException { - String file = "/org/javacs/example/AutocompleteRest.java"; + var file = "/org/javacs/example/AutocompleteRest.java"; // Static methods - List<? extends CompletionItem> items = items(file, 5, 18); - Set<String> suggestions = items.stream().map(i -> i.getLabel()).collect(Collectors.toSet()); - Set<String> details = items.stream().map(i -> i.getDetail()).collect(Collectors.toSet()); + var items = items(file, 5, 18); + var suggestions = items.stream().map(i -> i.getLabel()).collect(Collectors.toSet()); + var details = items.stream().map(i -> i.getDetail()).collect(Collectors.toSet()); assertThat(suggestions, hasItems("restMethod")); assertThat(details, hasItems("void (String... params)")); @@ -483,225 +486,207 @@ public class CompletionsTest extends CompletionsBase { @Test public void constructor() throws IOException { - String file = "/org/javacs/example/AutocompleteConstructor.java"; + var file = "/org/javacs/example/AutocompleteConstructor.java"; // Static methods - Set<String> suggestions = insertText(file, 5, 25); + var suggestions = insertText(file, 5, 25); - assertThat(suggestions, hasItems("AutocompleteConstructor<>", "AutocompleteMember")); + assertThat(suggestions, hasItem(startsWith("AutocompleteConstructor"))); + assertThat(suggestions, hasItem(startsWith("AutocompleteMember"))); } + @Ignore // We are now managing imports with FixImports @Test public void autoImportConstructor() throws IOException { - String file = "/org/javacs/example/AutocompleteConstructor.java"; + var file = "/org/javacs/example/AutocompleteConstructor.java"; // Static methods - List<? extends CompletionItem> items = items(file, 6, 19); - List<String> suggestions = Lists.transform(items, i -> i.getInsertText()); + var items = items(file, 6, 19); + var suggestions = Lists.transform(items, i -> i.getInsertText()); assertThat(suggestions, hasItems("ArrayList<>($0)")); - for (CompletionItem each : items) { + for (var each : items) { if (each.getInsertText().equals("ArrayList<>")) assertThat( - "new ? auto-imports", - each.getAdditionalTextEdits(), - both(not(empty())).and(not(nullValue()))); + "new ? auto-imports", each.getAdditionalTextEdits(), both(not(empty())).and(not(nullValue()))); } } + @Ignore @Test public void importFromSource() throws IOException { - String file = "/org/javacs/example/AutocompletePackage.java"; - - // Static methods - Set<String> suggestions = insertText(file, 3, 12); + var file = "/org/javacs/example/AutocompletePackage.java"; + var suggestions = insertText(file, 3, 12); assertThat("Does not have own package class", suggestions, hasItems("javacs")); } @Test public void importFromClasspath() throws IOException { - String file = "/org/javacs/example/AutocompletePackage.java"; - - // Static methods - Set<String> suggestions = insertText(file, 5, 13); + var file = "/org/javacs/example/AutocompletePackage.java"; + var suggestions = insertText(file, 5, 13); assertThat("Has class from classpath", suggestions, hasItems("util")); } + // TODO top level of import + @Ignore @Test public void importFirstId() throws IOException { - String file = "/org/javacs/example/AutocompletePackage.java"; + var file = "/org/javacs/example/AutocompletePackage.java"; - // Static methods - Set<String> suggestions = insertText(file, 7, 9); + // import ? + var suggestions = insertText(file, 7, 9); assertThat("Has class from classpath", suggestions, hasItems("com", "org")); } @Test public void emptyClasspath() throws IOException { - String file = "/org/javacs/example/AutocompletePackage.java"; + var file = "/org/javacs/example/AutocompletePackage.java"; // Static methods - Set<String> suggestions = insertText(file, 6, 12); + var suggestions = insertText(file, 6, 12); - assertThat( - "Has deeply nested class", - suggestions, - not(hasItems("google.common.collect.Lists"))); + assertThat("Has deeply nested class", suggestions, not(hasItems("google.common.collect.Lists"))); } @Test public void importClass() throws IOException { - String file = "/org/javacs/example/AutocompletePackage.java"; + var file = "/org/javacs/example/AutocompletePackage.java"; // Static methods - List<? extends CompletionItem> items = items(file, 4, 25); - List<String> suggestions = Lists.transform(items, i -> i.getLabel()); + var items = items(file, 4, 25); + var suggestions = Lists.transform(items, i -> i.getLabel()); assertThat(suggestions, hasItems("OtherPackagePublic")); assertThat(suggestions, not(hasItems("OtherPackagePrivate"))); - for (CompletionItem item : items) { - if (item.getLabel().equals("OtherPackagePublic")) - assertThat( - "Don't import when completing imports", - item.getAdditionalTextEdits(), - either(empty()).or(nullValue())); - } + // Imports are now being managed by FixImports + // for (var item : items) { + // if (item.getLabel().equals("OtherPackagePublic")) + // assertThat( + // "Don't import when completing imports", + // item.getAdditionalTextEdits(), + // either(empty()).or(nullValue())); + // } } @Test public void otherPackageId() throws IOException { - String file = "/org/javacs/example/AutocompleteOtherPackage.java"; + var file = "/org/javacs/example/AutocompleteOtherPackage.java"; // Static methods - List<? extends CompletionItem> items = items(file, 5, 14); - List<String> suggestions = Lists.transform(items, i -> i.getLabel()); + var items = items(file, 5, 14); + var suggestions = Lists.transform(items, i -> i.getLabel()); assertThat(suggestions, hasItems("OtherPackagePublic")); assertThat(suggestions, not(hasItems("OtherPackagePrivate"))); - for (CompletionItem item : items) { - if (item.getLabel().equals("OtherPackagePublic")) - assertThat( - "Auto-import OtherPackagePublic", - item.getAdditionalTextEdits(), - not(empty())); - } + // for (var item : items) { + // if (item.getLabel().equals("OtherPackagePublic")) + // assertThat("Auto-import OtherPackagePublic", item.getAdditionalTextEdits(), not(empty())); + // } } @Test public void fieldFromStaticInner() throws IOException { - String file = "/org/javacs/example/AutocompleteOuter.java"; + var file = "/org/javacs/example/AutocompleteOuter.java"; // Initializer of static inner class - Set<String> suggestions = insertText(file, 12, 14); + var suggestions = insertText(file, 12, 14); - assertThat(suggestions, hasItems("methodStatic", "fieldStatic")); - assertThat(suggestions, not(hasItems("methods", "fields"))); + assertThat(suggestions, hasItems("testMethodStatic", "testFieldStatic")); + // TODO this is not visible + // assertThat(suggestions, not(hasItems("testMethods", "testFields"))); } @Test public void fieldFromInner() throws IOException { - String file = "/org/javacs/example/AutocompleteOuter.java"; + var file = "/org/javacs/example/AutocompleteOuter.java"; // Initializer of inner class - Set<String> suggestions = insertText(file, 18, 14); + var suggestions = insertText(file, 18, 14); - assertThat(suggestions, hasItems("methodStatic", "fieldStatic")); - assertThat(suggestions, hasItems("methods", "fields")); + assertThat(suggestions, hasItems("testMethodStatic", "testFieldStatic")); + assertThat(suggestions, hasItems("testMethods", "testFields")); } @Test public void classDotClassFromMethod() throws IOException { - String file = "/org/javacs/example/AutocompleteInners.java"; + var file = "/org/javacs/example/AutocompleteInners.java"; // AutocompleteInners.I - Set<String> suggestions = insertText(file, 5, 29); + var suggestions = insertText(file, 5, 29); - assertThat( - "suggests qualified inner class declaration", suggestions, hasItem("InnerClass")); + assertThat("suggests qualified inner class declaration", suggestions, hasItem("InnerClass")); assertThat("suggests qualified inner enum declaration", suggestions, hasItem("InnerEnum")); } @Test public void innerClassFromMethod() throws IOException { - String file = "/org/javacs/example/AutocompleteInners.java"; + var file = "/org/javacs/example/AutocompleteInners.java"; // I - Set<String> suggestions = insertText(file, 6, 10); + var suggestions = insertText(file, 6, 10); - assertThat( - "suggests unqualified inner class declaration", suggestions, hasItem("InnerClass")); - assertThat( - "suggests unqualified inner enum declaration", suggestions, hasItem("InnerEnum")); + assertThat("suggests unqualified inner class declaration", suggestions, hasItem("InnerClass")); + assertThat("suggests unqualified inner enum declaration", suggestions, hasItem("InnerEnum")); } @Test public void newClassDotInnerClassFromMethod() throws IOException { - String file = "/org/javacs/example/AutocompleteInners.java"; + var file = "/org/javacs/example/AutocompleteInners.java"; // new AutocompleteInners.I - Set<String> suggestions = insertText(file, 10, 33); + var suggestions = insertText(file, 10, 33); - assertThat( - "suggests qualified inner class declaration", suggestions, hasItem("InnerClass")); - assertThat( - "suggests qualified inner enum declaration", - suggestions, - not(hasItem("InnerEnum"))); + assertThat("suggests qualified inner class declaration", suggestions, hasItem("InnerClass")); + // TODO you can't actually make an inner enum + // assertThat("does not suggest enum", suggestions, not(hasItem("InnerEnum"))); } @Test public void newInnerClassFromMethod() throws IOException { - String file = "/org/javacs/example/AutocompleteInners.java"; + var file = "/org/javacs/example/AutocompleteInners.java"; - // new I - Set<String> suggestions = insertText(file, 11, 14); + // new Inner? + var suggestions = insertText(file, 11, 18); - assertThat( - "suggests unqualified inner class declaration", suggestions, hasItem("InnerClass")); - assertThat( - "suggests unqualified inner enum declaration", - suggestions, - not(hasItem("InnerEnum"))); + assertThat("suggests unqualified inner class declaration", suggestions, hasItem("InnerClass")); + // TODO you can't actually make an inner enum + // assertThat("does not suggest enum", suggestions, not(hasItem("InnerEnum"))); } @Test public void innerEnum() throws IOException { - String file = "/org/javacs/example/AutocompleteInners.java"; - - Set<String> suggestions = insertText(file, 15, 40); + var file = "/org/javacs/example/AutocompleteInners.java"; + var suggestions = insertText(file, 15, 40); assertThat("suggests enum constants", suggestions, hasItems("Foo")); } @Test public void staticStarImport() throws IOException { - String file = "/org/javacs/example/AutocompleteStaticImport.java"; - - Set<String> suggestions = insertText(file, 9, 15); + var file = "/org/javacs/example/AutocompleteStaticImport.java"; + var suggestions = insertText(file, 9, 15); assertThat("suggests star-imported static method", suggestions, hasItems("emptyList")); } @Test public void staticImport() throws IOException { - String file = "/org/javacs/example/AutocompleteStaticImport.java"; - - Set<String> suggestions = insertText(file, 10, 10); + var file = "/org/javacs/example/AutocompleteStaticImport.java"; + var suggestions = insertText(file, 10, 10); assertThat("suggests star-imported static field", suggestions, hasItems("BC")); } @Test public void staticImportSourcePath() throws IOException { - String file = "/org/javacs/example/AutocompleteStaticImport.java"; - - Set<String> suggestions = insertText(file, 11, 20); + var file = "/org/javacs/example/AutocompleteStaticImport.java"; + var suggestions = insertText(file, 11, 10); assertThat( "suggests star-imported public static field from source path", @@ -714,31 +699,40 @@ public class CompletionsTest extends CompletionsBase { } @Test - public void containsCharactersInOrder() { - assertTrue(Completions.containsCharactersInOrder("FooBar", "FooBar", false)); - assertTrue(Completions.containsCharactersInOrder("FooBar", "foobar", false)); - assertTrue(Completions.containsCharactersInOrder("FooBar", "FB", false)); - assertTrue(Completions.containsCharactersInOrder("FooBar", "fb", false)); - assertFalse(Completions.containsCharactersInOrder("FooBar", "FooBar1", false)); - assertFalse(Completions.containsCharactersInOrder("FooBar", "FB1", false)); - } - - @Test public void withinConstructor() throws IOException { - String file = "/org/javacs/example/AutocompleteContext.java"; - - Set<String> suggestions = insertText(file, 8, 38); + var file = "/org/javacs/example/AutocompleteContext.java"; + var suggestions = insertText(file, 8, 38); assertThat("suggests local variable", suggestions, hasItems("length")); } @Test + @Ignore public void onlySuggestOnce() throws IOException { - String file = "/org/javacs/example/AutocompleteOnce.java"; - - Map<String, Integer> suggestions = insertCount(file, 5, 18); + var file = "/org/javacs/example/AutocompleteOnce.java"; + var suggestions = insertCount(file, 5, 18); assertThat("suggests Signatures", suggestions, hasKey("Signatures")); assertThat("suggests Signatures only once", suggestions, hasEntry("Signatures", 1)); } + + @Test + public void overloadedOnSourcePath() throws IOException { + var file = "/org/javacs/example/OverloadedMethod.java"; + var detail = detail(file, 9, 13); + + assertThat("suggests empty method", detail, hasItem("overloaded()")); + assertThat("suggests int method", detail, hasItem("overloaded(i)")); + assertThat("suggests string method", detail, hasItem("overloaded(s)")); + } + + @Test + public void overloadedOnClassPath() throws IOException { + var file = "/org/javacs/example/OverloadedMethod.java"; + var detail = detail(file, 10, 26); + + assertThat("suggests empty method", detail, hasItem("of()")); + assertThat("suggests one-arg method", detail, hasItem("of(e1)")); + // assertThat("suggests vararg method", detail, hasItem("of(elements)")); + } } diff --git a/src/test/java/org/javacs/DocsTest.java b/src/test/java/org/javacs/DocsTest.java new file mode 100644 index 0000000..583dea0 --- /dev/null +++ b/src/test/java/org/javacs/DocsTest.java @@ -0,0 +1,34 @@ +package org.javacs; + +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; + +import java.util.Set; +import org.junit.Test; + +public class DocsTest { + @Test + public void classDoc() { + var sourcePath = Set.of(JavaCompilerServiceTest.resourcesDir()); + var docs = new Docs(sourcePath); + var tree = docs.classDoc("ClassDoc"); + assertTrue(tree.isPresent()); + assertThat(tree.get().getFirstSentence(), hasToString("A great class")); + } + + @Test + public void memberDoc() { + var sourcePath = Set.of(JavaCompilerServiceTest.resourcesDir()); + var docs = new Docs(sourcePath); + var tree = docs.memberDoc("LocalMethodDoc", "targetMethod"); + assertTrue(tree.isPresent()); + assertThat(tree.get().getFirstSentence(), hasToString("A great method")); + } + + @Test + public void platformDoc() { + var docs = new Docs(Set.of()); + var tree = docs.classDoc("java.util.List"); + assertTrue(tree.isPresent()); + } +} diff --git a/src/test/java/org/javacs/FindReferencesTest.java b/src/test/java/org/javacs/FindReferencesTest.java index 90635b2..50b8ea5 100644 --- a/src/test/java/org/javacs/FindReferencesTest.java +++ b/src/test/java/org/javacs/FindReferencesTest.java @@ -3,11 +3,13 @@ package org.javacs; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; -import java.net.URI; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.logging.Logger; -import org.eclipse.lsp4j.*; +import org.eclipse.lsp4j.Location; +import org.eclipse.lsp4j.Position; +import org.eclipse.lsp4j.ReferenceParams; +import org.eclipse.lsp4j.TextDocumentIdentifier; import org.junit.Test; public class FindReferencesTest { @@ -16,8 +18,8 @@ public class FindReferencesTest { private static final JavaLanguageServer server = LanguageServerFixture.getJavaLanguageServer(); protected List<? extends Location> items(String file, int row, int column) { - URI uri = FindResource.uri(file); - ReferenceParams params = new ReferenceParams(); + var uri = FindResource.uri(file); + var params = new ReferenceParams(); params.setTextDocument(new TextDocumentIdentifier(uri.toString())); params.setUri(uri.toString()); diff --git a/src/test/java/org/javacs/FindResource.java b/src/test/java/org/javacs/FindResource.java index 5dc8088..897f85b 100644 --- a/src/test/java/org/javacs/FindResource.java +++ b/src/test/java/org/javacs/FindResource.java @@ -1,8 +1,6 @@ package org.javacs; -import java.io.File; import java.net.URI; -import java.nio.file.Path; import java.nio.file.Paths; /** Find java sources in test-project/workspace/src */ @@ -10,14 +8,11 @@ public class FindResource { public static URI uri(String resourcePath) { if (resourcePath.startsWith("/")) resourcePath = resourcePath.substring(1); - Path path = - Paths.get("./src/test/test-project/workspace/src") - .resolve(resourcePath) - .normalize(); - File file = path.toFile(); + var path = Paths.get("./src/test/test-project/workspace/src").resolve(resourcePath).normalize(); + var file = path.toAbsolutePath().toFile(); if (!file.exists()) throw new RuntimeException(file + " does not exist"); - return file.toURI(); + return URI.create("file://" + file); } } diff --git a/src/test/java/org/javacs/GotoTest.java b/src/test/java/org/javacs/GotoTest.java index 5ff1506..6c64834 100644 --- a/src/test/java/org/javacs/GotoTest.java +++ b/src/test/java/org/javacs/GotoTest.java @@ -3,12 +3,15 @@ package org.javacs; import static org.hamcrest.Matchers.*; import static org.junit.Assert.assertThat; -import java.io.IOException; import java.net.URI; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.logging.Logger; -import org.eclipse.lsp4j.*; +import org.eclipse.lsp4j.Location; +import org.eclipse.lsp4j.Position; +import org.eclipse.lsp4j.Range; +import org.eclipse.lsp4j.TextDocumentIdentifier; +import org.eclipse.lsp4j.TextDocumentPositionParams; import org.junit.Ignore; import org.junit.Test; @@ -17,98 +20,95 @@ public class GotoTest { private static final String file = "/org/javacs/example/Goto.java"; private static final URI uri = FindResource.uri(file), other = FindResource.uri("/org/javacs/example/GotoOther.java"); - private static final String defaultConstructorFile = - "/org/javacs/example/GotoDefaultConstructor.java"; + private static final String defaultConstructorFile = "/org/javacs/example/GotoDefaultConstructor.java"; private static final URI defaultConstructorUri = FindResource.uri(defaultConstructorFile); @Test - public void localVariable() throws IOException { + public void localVariable() { List<? extends Location> suggestions = doGoto(file, 9, 8); - assertThat(suggestions, contains(location(uri, 4, 15, 4, 20))); + assertThat(suggestions, contains(location(uri, 4, 8, 4, 21))); } @Test - public void defaultConstructor() throws IOException { + public void defaultConstructor() { List<? extends Location> suggestions = doGoto(defaultConstructorFile, 4, 45); - assertThat(suggestions, contains(location(defaultConstructorUri, 2, 13, 2, 35))); + assertThat(suggestions, contains(location(defaultConstructorUri, 2, 0, 6, 1))); } @Test - public void constructor() throws IOException { + public void constructor() { List<? extends Location> suggestions = doGoto(file, 10, 20); - assertThat(suggestions, contains(location(uri, 43, 11, 43, 15))); + assertThat(suggestions, contains(location(uri, 2, 0, 47, 1))); } @Test - public void className() throws IOException { + public void className() { List<? extends Location> suggestions = doGoto(file, 15, 8); - assertThat(suggestions, contains(location(uri, 2, 13, 2, 17))); + assertThat(suggestions, contains(location(uri, 2, 0, 47, 1))); } @Test - public void staticField() throws IOException { + public void staticField() { List<? extends Location> suggestions = doGoto(file, 12, 21); - assertThat(suggestions, contains(location(uri, 35, 25, 35, 36))); + assertThat(suggestions, contains(location(uri, 35, 4, 35, 37))); } @Test - public void field() throws IOException { + public void field() { List<? extends Location> suggestions = doGoto(file, 13, 21); - assertThat(suggestions, contains(location(uri, 36, 18, 36, 23))); + assertThat(suggestions, contains(location(uri, 36, 4, 36, 24))); } @Test - public void staticMethod() throws IOException { + public void staticMethod() { List<? extends Location> suggestions = doGoto(file, 15, 13); - assertThat(suggestions, contains(location(uri, 37, 25, 37, 37))); + assertThat(suggestions, contains(location(uri, 37, 4, 39, 5))); } @Test - public void method() throws IOException { + public void method() { List<? extends Location> suggestions = doGoto(file, 16, 13); - assertThat(suggestions, contains(location(uri, 40, 18, 40, 24))); + assertThat(suggestions, contains(location(uri, 40, 4, 42, 5))); } @Test - public void staticMethodReference() throws IOException { + public void staticMethodReference() { List<? extends Location> suggestions = doGoto(file, 18, 26); - assertThat(suggestions, contains(location(uri, 37, 25, 37, 37))); + assertThat(suggestions, contains(location(uri, 37, 4, 39, 5))); } @Test - public void methodReference() throws IOException { + public void methodReference() { List<? extends Location> suggestions = doGoto(file, 19, 26); - assertThat(suggestions, contains(location(uri, 40, 18, 40, 24))); + assertThat(suggestions, contains(location(uri, 40, 4, 42, 5))); } @Test - public void otherStaticMethod() throws IOException { + public void otherStaticMethod() { List<? extends Location> suggestions = doGoto(file, 28, 24); assertThat(suggestions, contains(hasProperty("uri", equalTo(other.toString())))); } @Test - public void otherMethod() throws IOException { + public void otherMethod() { List<? extends Location> suggestions = doGoto(file, 29, 17); assertThat(suggestions, contains(hasProperty("uri", equalTo(other.toString())))); } @Test - public void otherCompiledFile() throws IOException { - server.compile(other); - + public void otherCompiledFile() { List<? extends Location> suggestions = doGoto(file, 28, 24); assertThat(suggestions, contains(hasProperty("uri", equalTo(other.toString())))); @@ -116,14 +116,14 @@ public class GotoTest { @Test @Ignore // TODO - public void typeParam() throws IOException { + public void typeParam() { List<? extends Location> suggestions = doGoto(file, 45, 11); assertThat(suggestions, contains(location(uri, 2, 18, 2, 23))); } @Test - public void gotoEnum() throws IOException { + public void gotoEnum() { String file = "/org/javacs/example/GotoEnum.java"; assertThat(doGoto(file, 5, 30), not(empty())); @@ -132,22 +132,18 @@ public class GotoTest { private Location location(URI uri, int startRow, int startColumn, int endRow, int endColumn) { Position start = new Position(); - start.setLine(startRow); start.setCharacter(startColumn); Position end = new Position(); - - end.setLine(startRow); + end.setLine(endRow); end.setCharacter(endColumn); Range range = new Range(); - range.setStart(start); range.setEnd(end); Location location = new Location(); - location.setUri(uri.toString()); location.setRange(range); @@ -156,7 +152,7 @@ public class GotoTest { private static final JavaLanguageServer server = LanguageServerFixture.getJavaLanguageServer(); - private List<? extends Location> doGoto(String file, int row, int column) throws IOException { + private List<? extends Location> doGoto(String file, int row, int column) { TextDocumentIdentifier document = new TextDocumentIdentifier(); document.setUri(FindResource.uri(file).toString()); diff --git a/src/test/java/org/javacs/IncrementalFileManagerTest.java b/src/test/java/org/javacs/IncrementalFileManagerTest.java deleted file mode 100644 index 310ccd3..0000000 --- a/src/test/java/org/javacs/IncrementalFileManagerTest.java +++ /dev/null @@ -1,98 +0,0 @@ -package org.javacs; - -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.assertThat; - -import com.google.common.collect.ImmutableList; -import com.sun.tools.javac.api.JavacTool; -import com.sun.tools.javac.file.JavacFileManager; -import java.io.File; -import java.io.IOException; -import java.nio.charset.Charset; -import java.nio.file.Paths; -import javax.tools.StandardLocation; -import org.javacs.pubapi.PubApi; -import org.junit.Before; -import org.junit.Test; - -public class IncrementalFileManagerTest { - private JavacFileManager delegate = - JavacTool.create().getStandardFileManager(__ -> {}, null, Charset.defaultCharset()); - private IncrementalFileManager test = new IncrementalFileManager(delegate); - private File sourcePath = Paths.get("./src/test/test-project/workspace/src").toFile(); - private File classPath = Paths.get("./src/test/test-project/workspace/target/classes").toFile(); - - @Before - public void setPaths() throws IOException { - delegate.setLocation(StandardLocation.SOURCE_PATH, ImmutableList.of(sourcePath)); - delegate.setLocation(StandardLocation.CLASS_PATH, ImmutableList.of(classPath)); - } - - @Test - public void sourceFileSignature() { - PubApi sig = test.sourceSignature("com.example.Signatures").get(); - - assertThat( - sig.types.get("com.example.Signatures").pubApi.methods.keySet(), - hasItems("void voidMethod()", "java.lang.String stringMethod()")); - assertThat( - sig.types.get("com.example.Signatures").pubApi.methods.keySet(), - not(hasItems("void privateMethod()"))); - assertThat( - sig.types.get("com.example.Signatures").pubApi.types.keySet(), - hasItems( - "com.example.Signatures$RegularInnerClass", - "com.example.Signatures$StaticInnerClass")); - } - - @Test - public void classFileSignature() { - PubApi sig = test.classSignature("com.example.Signatures").get(); - - assertThat( - sig.types.get("com.example.Signatures").pubApi.methods.keySet(), - hasItems("void voidMethod()", "java.lang.String stringMethod()")); - assertThat( - sig.types.get("com.example.Signatures").pubApi.methods.keySet(), - not(hasItems("void privateMethod()"))); - assertThat( - sig.types.get("com.example.Signatures").pubApi.types.keySet(), - hasItems( - "com.example.Signatures$RegularInnerClass", - "com.example.Signatures$StaticInnerClass")); - } - - @Test - public void simpleSignatureEquals() { - PubApi classSig = test.classSignature("com.example.Signatures").get(), - sourceSig = test.sourceSignature("com.example.Signatures").get(); - - assertThat(classSig, equalTo(sourceSig)); - } - - @Test - public void packagePrivateSourceSignature() { - PubApi sig = test.sourceSignature("com.example.PackagePrivate").get(); - - assertThat( - sig.types.get("com.example.PackagePrivate").pubApi.methods.keySet(), - hasItem("void packagePrivateMethod()")); - } - - @Test - public void packagePrivateClassSignature() { - PubApi sig = test.classSignature("com.example.PackagePrivate").get(); - - assertThat( - sig.types.get("com.example.PackagePrivate").pubApi.methods.keySet(), - hasItem("void packagePrivateMethod()")); - } - - @Test - public void packagePrivateEquals() { - PubApi classSig = test.classSignature("com.example.PackagePrivate").get(), - sourceSig = test.sourceSignature("com.example.PackagePrivate").get(); - - assertThat(classSig, equalTo(sourceSig)); - } -} diff --git a/src/test/java/org/javacs/InferBazelConfigTest.java b/src/test/java/org/javacs/InferBazelConfigTest.java index 76dd478..d3e04fc 100644 --- a/src/test/java/org/javacs/InferBazelConfigTest.java +++ b/src/test/java/org/javacs/InferBazelConfigTest.java @@ -7,7 +7,6 @@ import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; -import java.util.Collections; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -16,23 +15,12 @@ public class InferBazelConfigTest { private Path bazelWorkspace = Paths.get("src/test/test-project/bazel-workspace"), bazelTemp = Paths.get("src/test/test-project/bazel-temp"); - private InferConfig bazel = - new InferConfig( - bazelWorkspace, - Collections.emptyList(), - Collections.emptyList(), - Paths.get("nowhere"), - Paths.get("nowhere")); + private InferConfig bazel = new InferConfig(bazelWorkspace, Paths.get("nowhere")); private Path bazelBin = bazelWorkspace.resolve("bazel-bin"), - bazelBinTarget = - bazelTemp - .resolve("xyz/execroot/test/bazel-out/local-fastbuild/bin") - .toAbsolutePath(), + bazelBinTarget = bazelTemp.resolve("xyz/execroot/test/bazel-out/local-fastbuild/bin").toAbsolutePath(), bazelGenfiles = bazelWorkspace.resolve("bazel-genfiles"), bazelGenfilesTarget = - bazelTemp - .resolve("xyz/execroot/test/bazel-out/local-fastbuild/genfiles") - .toAbsolutePath(); + bazelTemp.resolve("xyz/execroot/test/bazel-out/local-fastbuild/genfiles").toAbsolutePath(); @Before public void createBazelBinLink() throws IOException { @@ -60,9 +48,7 @@ public class InferBazelConfigTest { @Test public void bazelWorkspaceClassPath() { - assertThat( - bazel.workspaceClassPath(), - hasItem(bazelBinTarget.resolve("module/_javac/main/libmain_classes"))); + assertThat(bazel.workspaceClassPath(), hasItem(bazelBinTarget.resolve("module/_javac/main/libmain_classes"))); } @Test diff --git a/src/test/java/org/javacs/InferConfigTest.java b/src/test/java/org/javacs/InferConfigTest.java index 67026f7..2a951cc 100644 --- a/src/test/java/org/javacs/InferConfigTest.java +++ b/src/test/java/org/javacs/InferConfigTest.java @@ -3,116 +3,42 @@ package org.javacs; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; -import com.google.common.collect.ImmutableList; import java.nio.file.Path; import java.nio.file.Paths; -import java.util.Collections; -import java.util.List; import org.junit.Test; public class InferConfigTest { private Path workspaceRoot = Paths.get("src/test/test-project/workspace"); private Path mavenHome = Paths.get("src/test/test-project/home/.m2"); - private Path gradleHome = Paths.get("src/test/test-project/home/.gradle"); private Artifact externalArtifact = new Artifact("com.external", "external-library", "1.2"); - private List<Artifact> externalDependencies = ImmutableList.of(externalArtifact); - private InferConfig both = - new InferConfig( - workspaceRoot, - externalDependencies, - Collections.emptyList(), - mavenHome, - gradleHome); - private InferConfig gradle = - new InferConfig( - workspaceRoot, - externalDependencies, - Collections.emptyList(), - Paths.get("nowhere"), - gradleHome); - private InferConfig onlyPomXml = - new InferConfig( - Paths.get("src/test/test-project/only-pom-xml"), - Collections.emptyList(), - Collections.emptyList(), - mavenHome, - Paths.get("nowhere")); - private Path libraryJar = Paths.get("lib/library.jar"); - private InferConfig settingsClassPath = - new InferConfig( - workspaceRoot, - Collections.emptyList(), - ImmutableList.of(libraryJar), - mavenHome, - gradleHome); + private InferConfig infer = new InferConfig(workspaceRoot, mavenHome); @Test public void mavenClassPath() { + var found = infer.findMavenJar(externalArtifact, false); + assertTrue(found.isPresent()); assertThat( - both.buildClassPath(), - contains( - mavenHome.resolve( - "repository/com/external/external-library/1.2/external-library-1.2.jar"))); - // v1.1 should be ignored - } - - @Test - public void gradleClasspath() { - assertThat( - gradle.buildClassPath(), - contains( - gradleHome.resolve( - "caches/modules-2/files-2.1/com.external/external-library/1.2/xxx/external-library-1.2.jar"))); + found.get(), + equalTo(mavenHome.resolve("repository/com/external/external-library/1.2/external-library-1.2.jar"))); // v1.1 should be ignored } @Test public void mavenDocPath() { + var found = infer.findMavenJar(externalArtifact, true); + assertTrue(found.isPresent()); assertThat( - both.buildDocPath(), - contains( + found.get(), + equalTo( mavenHome.resolve( "repository/com/external/external-library/1.2/external-library-1.2-sources.jar"))); // v1.1 should be ignored } @Test - public void gradleDocPath() { - assertThat( - gradle.buildDocPath(), - contains( - gradleHome.resolve( - "caches/modules-2/files-2.1/com.external/external-library/1.2/yyy/external-library-1.2-sources.jar"))); - // v1.1 should be ignored - } - - @Test public void dependencyList() { assertThat( InferConfig.dependencyList(Paths.get("pom.xml")), - hasItem(new Artifact("com.sun", "tools", "1.8"))); - } - - @Test - public void onlyPomXmlClassPath() { - assertThat( - onlyPomXml.buildClassPath(), - contains( - mavenHome.resolve( - "repository/com/external/external-library/1.2/external-library-1.2.jar"))); - } - - @Test - public void onlyPomXmlDocPath() { - assertThat( - onlyPomXml.buildDocPath(), - contains( - mavenHome.resolve( - "repository/com/external/external-library/1.2/external-library-1.2-sources.jar"))); - } - - @Test - public void settingsClassPath() { - assertThat(settingsClassPath.buildClassPath(), contains(workspaceRoot.resolve(libraryJar))); + hasItem(new Artifact("org.hamcrest", "hamcrest-all", "1.3"))); } } diff --git a/src/test/java/org/javacs/JavaCompilerServiceTest.java b/src/test/java/org/javacs/JavaCompilerServiceTest.java new file mode 100644 index 0000000..f6ed81f --- /dev/null +++ b/src/test/java/org/javacs/JavaCompilerServiceTest.java @@ -0,0 +1,284 @@ +package org.javacs; + +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.URI; +import java.net.URISyntaxException; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.logging.Logger; +import java.util.stream.Collectors; +import javax.lang.model.element.Element; +import javax.tools.Diagnostic; +import javax.tools.JavaFileObject; +import org.junit.Test; + +public class JavaCompilerServiceTest { + private static final Logger LOG = Logger.getLogger("main"); + + private JavaCompilerService compiler = + new JavaCompilerService( + Collections.singleton(resourcesDir()), Collections.emptySet(), Collections.emptySet()); + + static Path resourcesDir() { + try { + return Paths.get(JavaCompilerServiceTest.class.getResource("/HelloWorld.java").toURI()).getParent(); + } catch (URISyntaxException e) { + throw new RuntimeException(e); + } + } + + private String contents(String resourceFile) { + try (var in = JavaCompilerServiceTest.class.getResourceAsStream(resourceFile)) { + return new BufferedReader(new InputStreamReader(in)).lines().collect(Collectors.joining("\n")); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + private URI resourceUri(String resourceFile) { + try { + return JavaCompilerServiceTest.class.getResource(resourceFile).toURI(); + } catch (URISyntaxException e) { + throw new RuntimeException(e); + } + } + + @Test + public void element() { + var found = compiler.element(URI.create("/HelloWorld.java"), contents("/HelloWorld.java"), 3, 24); + + assertThat(found.getSimpleName(), hasToString(containsString("println"))); + } + + @Test + public void elementWithError() { + var found = compiler.element(URI.create("/CompleteMembers.java"), contents("/CompleteMembers.java"), 3, 12); + + assertThat(found, notNullValue()); + } + + private List<String> completionNames(List<Completion> found) { + var result = new ArrayList<String>(); + for (var c : found) { + if (c.element != null) result.add(c.element.getSimpleName().toString()); + else if (c.packagePart != null) result.add(c.packagePart.name); + else if (c.keyword != null) result.add(c.keyword); + else if (c.notImportedClass != null) result.add(Parser.lastName(c.notImportedClass)); + } + return result; + } + + private List<String> elementNames(List<Element> found) { + return found.stream().map(e -> e.getSimpleName().toString()).collect(Collectors.toList()); + } + + @Test + public void identifiers() { + var found = + compiler.scopeMembers( + URI.create("/CompleteIdentifiers.java"), contents("/CompleteIdentifiers.java"), 13, 21); + var names = elementNames(found); + assertThat(names, hasItem("completeLocal")); + assertThat(names, hasItem("completeParam")); + // assertThat(names, hasItem("super")); + // assertThat(names, hasItem("this")); + assertThat(names, hasItem("completeOtherMethod")); + assertThat(names, hasItem("completeInnerField")); + assertThat(names, hasItem("completeOuterField")); + assertThat(names, hasItem("completeOuterStatic")); + assertThat(names, hasItem("CompleteIdentifiers")); + } + + @Test + public void identifiersInMiddle() { + var found = + compiler.scopeMembers(URI.create("/CompleteInMiddle.java"), contents("/CompleteInMiddle.java"), 13, 21); + var names = elementNames(found); + assertThat(names, hasItem("completeLocal")); + assertThat(names, hasItem("completeParam")); + // assertThat(names, hasItem("super")); + // assertThat(names, hasItem("this")); + assertThat(names, hasItem("completeOtherMethod")); + assertThat(names, hasItem("completeInnerField")); + assertThat(names, hasItem("completeOuterField")); + assertThat(names, hasItem("completeOuterStatic")); + assertThat(names, hasItem("CompleteInMiddle")); + } + + @Test + public void completeIdentifiers() { + var found = + compiler.completions( + URI.create("/CompleteIdentifiers.java"), + contents("/CompleteIdentifiers.java"), + 13, + 21, + Integer.MAX_VALUE) + .items; + var names = completionNames(found); + assertThat(names, hasItem("completeLocal")); + assertThat(names, hasItem("completeParam")); + // assertThat(names, hasItem("super")); + // assertThat(names, hasItem("this")); + assertThat(names, hasItem("completeOtherMethod")); + assertThat(names, hasItem("completeInnerField")); + assertThat(names, hasItem("completeOuterField")); + assertThat(names, hasItem("completeOuterStatic")); + // assertThat(names, hasItem("CompleteIdentifiers")); + } + + @Test + public void members() { + var found = + compiler.members(URI.create("/CompleteMembers.java"), contents("/CompleteMembers.java"), 3, 14, false); + var names = completionNames(found); + assertThat(names, hasItem("subMethod")); + assertThat(names, hasItem("superMethod")); + assertThat(names, hasItem("equals")); + } + + @Test + public void completeMembers() { + var found = + compiler.completions( + URI.create("/CompleteMembers.java"), + contents("/CompleteMembers.java"), + 3, + 15, + Integer.MAX_VALUE) + .items; + var names = completionNames(found); + assertThat(names, hasItem("subMethod")); + assertThat(names, hasItem("superMethod")); + assertThat(names, hasItem("equals")); + } + + @Test + public void completeExpression() { + var found = + compiler.completions( + URI.create("/CompleteExpression.java"), + contents("/CompleteExpression.java"), + 3, + 37, + Integer.MAX_VALUE) + .items; + var names = completionNames(found); + assertThat(names, hasItem("instanceMethod")); + assertThat(names, not(hasItem("create"))); + assertThat(names, hasItem("equals")); + } + + @Test + public void completeClass() { + var found = + compiler.completions( + URI.create("/CompleteClass.java"), + contents("/CompleteClass.java"), + 3, + 23, + Integer.MAX_VALUE) + .items; + var names = completionNames(found); + assertThat(names, hasItems("staticMethod", "staticField")); + assertThat(names, hasItems("class")); + assertThat(names, not(hasItem("instanceMethod"))); + assertThat(names, not(hasItem("instanceField"))); + } + + @Test + public void completeImports() { + var found = + compiler.completions( + URI.create("/CompleteImports.java"), + contents("/CompleteImports.java"), + 1, + 18, + Integer.MAX_VALUE) + .items; + var names = completionNames(found); + assertThat(names, hasItem("List")); + assertThat(names, hasItem("concurrent")); + } + + /* + @Test + public void gotoDefinition() { + var def = + compiler.definition(URI.create("/GotoDefinition.java"), 3, 12, uri -> Files.readAllText(uri)); + assertTrue(def.isPresent()); + + var t = def.get(); + var unit = t.getCompilationUnit(); + assertThat(unit.getSourceFile().getName(), endsWith("GotoDefinition.java")); + + var trees = compiler.trees(); + var pos = trees.getSourcePositions(); + var lines = unit.getLineMap(); + long start = pos.getStartPosition(unit, t.getLeaf()); + long line = lines.getLineNumber(start); + assertThat(line, equalTo(6L)); + } + */ + + @Test + public void references() { + var refs = compiler.references(URI.create("/GotoDefinition.java"), contents("/GotoDefinition.java"), 6, 13); + boolean found = false; + for (var t : refs) { + var unit = t.getCompilationUnit(); + var name = unit.getSourceFile().getName(); + var trees = compiler.trees(); + var pos = trees.getSourcePositions(); + var lines = unit.getLineMap(); + long start = pos.getStartPosition(unit, t.getLeaf()); + long line = lines.getLineNumber(start); + if (name.endsWith("GotoDefinition.java") && line == 3) found = true; + } + + if (!found) fail(String.format("No GotoDefinition.java line 3 in %s", refs)); + } + + @Test + public void overloads() { + var found = compiler.methodInvocation(URI.create("/Overloads.java"), contents("/Overloads.java"), 3, 15).get(); + var strings = found.overloads.stream().map(Object::toString).collect(Collectors.toList()); + + assertThat(strings, hasItem(containsString("print(int)"))); + assertThat(strings, hasItem(containsString("print(java.lang.String)"))); + } + + @Test + public void lint() { + List<Diagnostic<? extends JavaFileObject>> diags = + compiler.lint(Collections.singleton(Paths.get(resourceUri("/HasError.java")))); + assertThat(diags, not(empty())); + } + + @Test + public void localDoc() { + var method = + compiler.methodInvocation(URI.create("/LocalMethodDoc.java"), contents("/LocalMethodDoc.java"), 3, 21) + .get() + .activeMethod + .get(); + var doc = compiler.methodDoc(method); + assertTrue(doc.isPresent()); + assertThat(doc.toString(), containsString("A great method")); + } + + @Test + public void fixImports() { + var qualifiedNames = + compiler.fixImports(resourceUri("/MissingImport.java"), contents("/MissingImport.java")).fixedImports; + assertThat(qualifiedNames, hasItem("java.util.List")); + } +} diff --git a/src/test/java/org/javacs/JavaCompilerTest.java b/src/test/java/org/javacs/JavaCompilerTest.java deleted file mode 100644 index 95246b1..0000000 --- a/src/test/java/org/javacs/JavaCompilerTest.java +++ /dev/null @@ -1,94 +0,0 @@ -package org.javacs; - -import com.google.common.collect.ImmutableList; -import com.sun.source.tree.CompilationUnitTree; -import com.sun.source.util.JavacTask; -import com.sun.tools.javac.api.JavacTool; -import java.io.File; -import java.io.IOException; -import java.nio.charset.Charset; -import java.nio.file.Paths; -import java.util.Collections; -import java.util.List; -import java.util.Optional; -import java.util.logging.Logger; -import javax.lang.model.element.Element; -import javax.tools.Diagnostic; -import javax.tools.DiagnosticCollector; -import javax.tools.JavaCompiler; -import javax.tools.JavaFileObject; -import javax.tools.StandardJavaFileManager; -import org.junit.Test; - -public class JavaCompilerTest { - private static final Logger LOG = Logger.getLogger("main"); - - @Test - public void javacTool() throws IOException { - JavaCompiler javaCompiler = JavacTool.create(); - StandardJavaFileManager fileManager = - javaCompiler.getStandardFileManager( - this::reportError, null, Charset.defaultCharset()); - List<String> options = - ImmutableList.of( - "-sourcepath", Paths.get("src/test/resources").toAbsolutePath().toString()); - List<String> classes = Collections.emptyList(); - File file = Paths.get("src/test/resources/org/javacs/example/Bad.java").toFile(); - Iterable<? extends JavaFileObject> compilationUnits = - fileManager.getJavaFileObjectsFromFiles(Collections.singleton(file)); - JavacTask task = - (JavacTask) - javaCompiler.getTask( - null, - fileManager, - this::reportError, - options, - classes, - compilationUnits); - - Iterable<? extends CompilationUnitTree> parsed = task.parse(); - Iterable<? extends Element> typed = task.analyze(); - - LOG.info(typed.toString()); - } - - @Test - public void javacHolder() { - JavacHolder javac = - JavacHolder.create( - Collections.singleton(Paths.get("src/test/test-project/workspace/src")), - Collections.emptySet()); - File file = - Paths.get("src/test/test-project/workspace/src/org/javacs/example/Bad.java") - .toFile(); - DiagnosticCollector<JavaFileObject> compile = - javac.compileBatch(Collections.singletonMap(file.toURI(), Optional.empty())); - } - - /* It's too hard to keep this test working - @Test - public void incremental() { - JavacHolder javac = JavacHolder.create(Collections.emptySet(), Collections.singleton(Paths.get("src/test/resources")), Paths.get("target/test-output")); - - // Compile Target to a .class file - File target = Paths.get("src/test/resources/org/javacs/example/Target.java").toFile(); - DiagnosticCollector<JavaFileObject> batch = javac.compileBatch(Collections.singletonMap(target.toURI(), Optional.empty())); - - // Incremental compilation should use Target.class, not Target.java - File dependsOnTarget = Paths.get("src/test/resources/org/javacs/example/DependsOnTarget.java").toFile(); - int[] count = {0}; - FocusedResult incremental = javac.compileFocused(dependsOnTarget.toURI(), Optional.empty(), 5, 27, true); - - assertThat(counts.get(TaskEvent.Kind.PARSE), equalTo(1)); - - // Check that we can find org.javacs.example.Target - TypeElement targetClass = incremental.task.getElements().getTypeElement("org.javacs.example.Target"); - - assertThat(targetClass, not(nullValue())); - } - */ - - private void reportError(Diagnostic<? extends JavaFileObject> error) { - LOG.severe(error.getMessage(null)); - } -} diff --git a/src/test/java/org/javacs/JavadocsTest.java b/src/test/java/org/javacs/JavadocsTest.java deleted file mode 100644 index c571fe4..0000000 --- a/src/test/java/org/javacs/JavadocsTest.java +++ /dev/null @@ -1,78 +0,0 @@ -package org.javacs; - -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; - -import com.sun.javadoc.MethodDoc; -import com.sun.javadoc.RootDoc; -import java.io.IOException; -import java.nio.file.Paths; -import java.util.Collections; -import java.util.Optional; -import org.junit.Ignore; -import org.junit.Test; - -public class JavadocsTest { - - private final Javadocs docs = - new Javadocs( - Collections.singleton(Paths.get("src/test/test-project/workspace/src")), - Collections.emptySet(), - __ -> Optional.empty()); - - @Test - public void findSrcZip() { - assertTrue("Can find src.zip", Javadocs.findSrcZip().isPresent()); - } - - @Test - public void findSystemDoc() throws IOException { - RootDoc root = docs.index("java.util.ArrayList"); - - assertThat(root.classes(), not(emptyArray())); - } - - @Test - public void findMethodDoc() { - assertTrue( - "Found method", - docs.methodDoc( - "org.javacs.docs.TrickyDocstring#example(java.lang.String,java.lang.String[],java.util.List)") - .isPresent()); - } - - @Test - public void findParameterizedDoc() { - assertTrue( - "Found method", - docs.methodDoc("org.javacs.docs.TrickyDocstring#parameterized(java.lang.Object)") - .isPresent()); - } - - @Test - @Ignore // Blocked by emptyFileManager - public void findInheritedDoc() { - Optional<MethodDoc> found = docs.methodDoc("org.javacs.docs.SubDoc#method()"); - - assertTrue("Found method", found.isPresent()); - - Optional<String> docstring = found.flatMap(Javadocs::commentText); - - assertTrue("Has inherited doc", docstring.isPresent()); - assertThat("Inherited doc is not empty", docstring.get(), not(isEmptyOrNullString())); - } - - @Test - @Ignore // Doesn't work yet - public void findInterfaceDoc() { - Optional<MethodDoc> found = docs.methodDoc("org.javacs.docs.SubDoc#interfaceMethod()"); - - assertTrue("Found method", found.isPresent()); - - Optional<String> docstring = found.flatMap(Javadocs::commentText); - - assertTrue("Has inherited doc", docstring.isPresent()); - assertThat("Inherited doc is not empty", docstring.get(), not(isEmptyOrNullString())); - } -} diff --git a/src/test/java/org/javacs/LanguageServerFixture.java b/src/test/java/org/javacs/LanguageServerFixture.java index 3058b43..94ba764 100644 --- a/src/test/java/org/javacs/LanguageServerFixture.java +++ b/src/test/java/org/javacs/LanguageServerFixture.java @@ -5,25 +5,27 @@ import java.nio.file.Paths; import java.util.concurrent.CompletableFuture; import java.util.function.Consumer; import java.util.logging.Logger; -import org.eclipse.lsp4j.*; +import org.eclipse.lsp4j.Diagnostic; +import org.eclipse.lsp4j.InitializeParams; +import org.eclipse.lsp4j.MessageActionItem; +import org.eclipse.lsp4j.MessageParams; +import org.eclipse.lsp4j.PublishDiagnosticsParams; +import org.eclipse.lsp4j.ShowMessageRequestParams; import org.eclipse.lsp4j.services.LanguageClient; class LanguageServerFixture { - public static Path DEFAULT_WORKSPACE_ROOT = - Paths.get("src/test/test-project/workspace").toAbsolutePath(); + public static Path DEFAULT_WORKSPACE_ROOT = Paths.get("src/test/test-project/workspace").toAbsolutePath(); static { Main.setRootFormat(); } static JavaLanguageServer getJavaLanguageServer() { - return getJavaLanguageServer( - DEFAULT_WORKSPACE_ROOT, diagnostic -> LOG.info(diagnostic.getMessage())); + return getJavaLanguageServer(DEFAULT_WORKSPACE_ROOT, diagnostic -> LOG.info(diagnostic.getMessage())); } - static JavaLanguageServer getJavaLanguageServer( - Path workspaceRoot, Consumer<Diagnostic> onError) { + static JavaLanguageServer getJavaLanguageServer(Path workspaceRoot, Consumer<Diagnostic> onError) { return getJavaLanguageServer( workspaceRoot, new LanguageClient() { @@ -31,8 +33,7 @@ class LanguageServerFixture { public void telemetryEvent(Object o) {} @Override - public void publishDiagnostics( - PublishDiagnosticsParams publishDiagnosticsParams) { + public void publishDiagnostics(PublishDiagnosticsParams publishDiagnosticsParams) { publishDiagnosticsParams.getDiagnostics().forEach(onError); } @@ -50,18 +51,15 @@ class LanguageServerFixture { }); } - private static JavaLanguageServer getJavaLanguageServer( - Path workspaceRoot, LanguageClient client) { - JavaLanguageServer server = new JavaLanguageServer(); - InitializeParams init = new InitializeParams(); + private static JavaLanguageServer getJavaLanguageServer(Path workspaceRoot, LanguageClient client) { + var server = new JavaLanguageServer(); + var init = new InitializeParams(); - init.setRootPath(workspaceRoot.toString()); + init.setRootUri(workspaceRoot.toUri().toString()); server.initialize(init); server.installClient(client); - server.maxItems = 100; - return server; } diff --git a/src/test/java/org/javacs/LinterTest.java b/src/test/java/org/javacs/LinterTest.java deleted file mode 100644 index ab7468a..0000000 --- a/src/test/java/org/javacs/LinterTest.java +++ /dev/null @@ -1,114 +0,0 @@ -package org.javacs; - -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.assertThat; - -import java.io.IOException; -import java.net.URI; -import java.nio.file.Paths; -import java.util.Collections; -import java.util.Optional; -import java.util.logging.Logger; -import javax.tools.Diagnostic; -import javax.tools.DiagnosticCollector; -import javax.tools.JavaFileObject; -import org.junit.Test; - -public class LinterTest { - private static final Logger LOG = Logger.getLogger("main"); - - private static final JavacHolder compiler = - JavacHolder.create( - Collections.singleton(Paths.get("src/test/test-project/workspace/src")), - Collections.emptySet()); - - @Test - public void compile() throws IOException { - URI file = FindResource.uri("/org/javacs/example/HelloWorld.java"); - DiagnosticCollector<JavaFileObject> errors = - compiler.compileBatch(Collections.singletonMap(file, Optional.empty())); - - assertThat(errors.getDiagnostics(), empty()); - } - - @Test - public void missingMethodBody() throws IOException { - URI file = FindResource.uri("/org/javacs/example/MissingMethodBody.java"); - DiagnosticCollector<JavaFileObject> compile = - compiler.compileBatch(Collections.singletonMap(file, Optional.empty())); - - assertThat(compile.getDiagnostics(), not(empty())); - } - - @Test - public void incompleteAssignment() throws IOException { - URI file = FindResource.uri("/org/javacs/example/IncompleteAssignment.java"); - DiagnosticCollector<JavaFileObject> compile = - compiler.compileBatch(Collections.singletonMap(file, Optional.empty())); - - assertThat(compile.getDiagnostics(), not(empty())); - } - - @Test - public void undefinedSymbol() throws IOException { - URI file = FindResource.uri("/org/javacs/example/UndefinedSymbol.java"); - DiagnosticCollector<JavaFileObject> compile = - compiler.compileBatch(Collections.singletonMap(file, Optional.empty())); - - assertThat(compile.getDiagnostics(), not(empty())); - - Diagnostic<? extends JavaFileObject> d = compile.getDiagnostics().get(0); - - // Error position should span entire 'foo' symbol - assertThat(d.getLineNumber(), greaterThan(0L)); - assertThat(d.getStartPosition(), greaterThan(0L)); - assertThat(d.getEndPosition(), greaterThan(d.getStartPosition() + 1)); - } - - @Test(expected = IllegalArgumentException.class) - public void notJava() { - URI file = FindResource.uri("/org/javacs/example/NotJava.java.txt"); - DiagnosticCollector<JavaFileObject> compile = - compiler.compileBatch(Collections.singletonMap(file, Optional.empty())); - } - - @Test - public void errorInDependency() { - URI file = FindResource.uri("/org/javacs/example/ErrorInDependency.java"); - DiagnosticCollector<JavaFileObject> compile = - compiler.compileBatch(Collections.singletonMap(file, Optional.empty())); - - assertThat(compile.getDiagnostics(), not(empty())); - } - - @Test - public void deprecationWarning() { - URI file = FindResource.uri("/org/javacs/example/DeprecationWarning.java"); - DiagnosticCollector<JavaFileObject> compile = - compiler.compileBatch(Collections.singletonMap(file, Optional.empty())); - - assertThat(compile.getDiagnostics(), not(empty())); - } - - @Test - public void parseError() { - URI file = URI.create("/org/javacs/example/ArrowTry.java"); - String source = - "package org.javacs.example;\n" - + "\n" - + "class Example {\n" - + " private static <In, Out> Function<In, Stream<Out>> catchClasspathErrors(Function<In, Stream<Out>> f) {\n" - + " return in -> try {\n" - + " return f.apply(in);\n" - + " } catch (Symbol.CompletionFailure failed) {\n" - + " LOG.warning(failed.getMessage());\n" - + " return Stream.empty();\n" - + " };\n" - + " }\n" - + "}"; - DiagnosticCollector<JavaFileObject> compile = - compiler.compileBatch(Collections.singletonMap(file, Optional.of(source))); - - assertThat(compile.getDiagnostics(), not(empty())); - } -} diff --git a/src/test/java/org/javacs/MainTest.java b/src/test/java/org/javacs/MainTest.java deleted file mode 100644 index 4aabeb8..0000000 --- a/src/test/java/org/javacs/MainTest.java +++ /dev/null @@ -1,29 +0,0 @@ -package org.javacs; - -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import org.junit.Test; - -public class MainTest { - @Test - public void checkJavacClassLoader() - throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, - InvocationTargetException { - assertThat(Main.checkJavacClassLoader(), not(instanceOf(ChildFirstClassLoader.class))); - - ClassLoader langTools = LangTools.createLangToolsClassLoader(); - Class<?> main = langTools.loadClass("org.javacs.Main"); - assertThat( - "Main was loaded by ChildFirstClassLoader", - main.getClassLoader(), - instanceOf(ChildFirstClassLoader.class)); - Method checkJavacClassLoader = main.getMethod("checkJavacClassLoader"); - assertThat( - "JavacTool was loaded by ChildFirstClassLoader", - checkJavacClassLoader.invoke(null), - instanceOf(ChildFirstClassLoader.class)); - } -} diff --git a/src/test/java/org/javacs/ParserFixImportsTest.java b/src/test/java/org/javacs/ParserFixImportsTest.java new file mode 100644 index 0000000..eddd105 --- /dev/null +++ b/src/test/java/org/javacs/ParserFixImportsTest.java @@ -0,0 +1,16 @@ +package org.javacs; + +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; + +import java.util.Collections; +import org.junit.Test; + +public class ParserFixImportsTest { + @Test + public void findExistingImports() { + var find = Parser.existingImports(Collections.singleton(JavaCompilerServiceTest.resourcesDir())); + assertThat(find.classes, hasItem("java.util.List")); + assertThat(find.packages, hasItem("java.util")); + } +} diff --git a/src/test/java/org/javacs/ParserTest.java b/src/test/java/org/javacs/ParserTest.java new file mode 100644 index 0000000..580ce92 --- /dev/null +++ b/src/test/java/org/javacs/ParserTest.java @@ -0,0 +1,36 @@ +package org.javacs; + +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; + +import java.nio.file.Paths; +import java.util.Set; +import org.junit.Test; + +public class ParserTest { + @Test + public void testMatchesTitleCase() { + assertTrue(Parser.matchesTitleCase("FooBar", "fb")); + assertTrue(Parser.matchesTitleCase("FooBar", "fob")); + assertTrue(Parser.matchesTitleCase("AnyPrefixFooBar", "fb")); + assertTrue(Parser.matchesTitleCase("AutocompleteBetweenLines", "ABetweenLines")); + assertTrue(Parser.matchesTitleCase("UPPERFooBar", "fb")); + assertFalse(Parser.matchesTitleCase("Foobar", "fb")); + } + + @Test + public void findAutocompleteBetweenLines() { + var rel = Paths.get("src", "org", "javacs", "example", "AutocompleteBetweenLines.java"); + var file = LanguageServerFixture.DEFAULT_WORKSPACE_ROOT.resolve(rel); + assertTrue(Parser.containsWordMatching(file, "ABetweenLines")); + } + + @Test + public void findExistingImports() { + var rel = Paths.get("src", "org", "javacs", "doimport"); + var dir = LanguageServerFixture.DEFAULT_WORKSPACE_ROOT.resolve(rel); + var existing = Parser.existingImports(Set.of(dir)); + assertThat(existing.classes, hasItems("java.util.List")); + assertThat(existing.packages, hasItems("java.util", "java.io")); + } +} diff --git a/src/test/java/org/javacs/PrunerTest.java b/src/test/java/org/javacs/PrunerTest.java new file mode 100644 index 0000000..23c825c --- /dev/null +++ b/src/test/java/org/javacs/PrunerTest.java @@ -0,0 +1,54 @@ +package org.javacs; + +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.URI; +import java.util.stream.Collectors; +import org.junit.Test; + +public class PrunerTest { + + private String contents(String resourceFile) { + try (var in = JavaCompilerServiceTest.class.getResourceAsStream(resourceFile)) { + return new BufferedReader(new InputStreamReader(in)).lines().collect(Collectors.joining("\n")); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + @Test + public void pruneMethods() { + var pruner = new Pruner(URI.create("/PruneMethods.java"), contents("/PruneMethods.java")); + pruner.prune(6, 19); + var expected = contents("/PruneMethods_erased.java"); + assertThat(pruner.contents(), equalToIgnoringWhiteSpace(expected)); + } + + @Test + public void pruneToEndOfBlock() { + var pruner = new Pruner(URI.create("/PruneToEndOfBlock.java"), contents("/PruneToEndOfBlock.java")); + pruner.prune(4, 18); + var expected = contents("/PruneToEndOfBlock_erased.java"); + assertThat(pruner.contents(), equalToIgnoringWhiteSpace(expected)); + } + + @Test + public void pruneMiddle() { + var pruner = new Pruner(URI.create("/PruneMiddle.java"), contents("/PruneMiddle.java")); + pruner.prune(4, 12); + var expected = contents("/PruneMiddle_erased.java"); + assertThat(pruner.contents(), equalToIgnoringWhiteSpace(expected)); + } + + @Test + public void pruneDot() { + var pruner = new Pruner(URI.create("/PruneDot.java"), contents("/PruneDot.java")); + pruner.prune(3, 11); + var expected = contents("/PruneDot_erased.java"); + assertThat(pruner.contents(), equalToIgnoringWhiteSpace(expected)); + } +} diff --git a/src/test/java/org/javacs/RecompileTest.java b/src/test/java/org/javacs/RecompileTest.java deleted file mode 100644 index 103e318..0000000 --- a/src/test/java/org/javacs/RecompileTest.java +++ /dev/null @@ -1,87 +0,0 @@ -package org.javacs; - -import static org.hamcrest.Matchers.empty; -import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertThat; - -import java.io.IOException; -import java.net.URI; -import java.nio.file.Paths; -import java.util.Collections; -import java.util.Optional; -import javax.tools.DiagnosticCollector; -import javax.tools.JavaFileObject; -import org.junit.Test; - -public class RecompileTest { - @Test - public void compileTwice() { - URI file = FindResource.uri("/org/javacs/example/CompileTwice.java"); - JavacHolder compiler = newCompiler(); - DiagnosticCollector<JavaFileObject> compile = - compiler.compileBatch(Collections.singletonMap(file, Optional.empty())); - - assertThat(compile.getDiagnostics(), empty()); - - // Compile again - compile = compiler.compileBatch(Collections.singletonMap(file, Optional.empty())); - - assertThat(compile.getDiagnostics(), empty()); - } - - @Test - public void fixParseError() { - URI bad = FindResource.uri("/org/javacs/example/FixParseErrorBefore.java"); - URI good = FindResource.uri("/org/javacs/example/FixParseErrorAfter.java"); - JavacHolder compiler = newCompiler(); - DiagnosticCollector<JavaFileObject> badErrors = - compiler.compileBatch(Collections.singletonMap(bad, Optional.empty())); - - assertThat(badErrors.getDiagnostics(), not(empty())); - - // Parse again - DiagnosticCollector<JavaFileObject> goodErrors = - compiler.compileBatch(Collections.singletonMap(good, Optional.empty())); - - assertThat(goodErrors.getDiagnostics(), empty()); - } - - @Test - public void fixTypeError() { - URI bad = FindResource.uri("/org/javacs/example/FixTypeErrorBefore.java"); - URI good = FindResource.uri("/org/javacs/example/FixTypeErrorAfter.java"); - JavacHolder compiler = newCompiler(); - DiagnosticCollector<JavaFileObject> badErrors = - compiler.compileBatch(Collections.singletonMap(bad, Optional.empty())); - - assertThat(badErrors.getDiagnostics(), not(empty())); - - // Parse again - DiagnosticCollector<JavaFileObject> goodErrors = - compiler.compileBatch(Collections.singletonMap(good, Optional.empty())); - - assertThat(goodErrors.getDiagnostics(), empty()); - } - - private static JavacHolder newCompiler() { - return JavacHolder.create( - Collections.singleton(Paths.get("src/test/test-project/workspace/src")), - Collections.emptySet()); - } - - @Test - public void keepTypeError() throws IOException { - URI file = FindResource.uri("/org/javacs/example/UndefinedSymbol.java"); - JavacHolder compiler = newCompiler(); - - // Compile once - DiagnosticCollector<JavaFileObject> errors = - compiler.compileBatch(Collections.singletonMap(file, Optional.empty())); - assertThat(errors.getDiagnostics(), not(empty())); - - // Compile twice - errors = compiler.compileBatch(Collections.singletonMap(file, Optional.empty())); - - assertThat(errors.getDiagnostics(), not(empty())); - } -} diff --git a/src/test/java/org/javacs/RefactorFileTest.java b/src/test/java/org/javacs/RefactorFileTest.java deleted file mode 100644 index 957ff15..0000000 --- a/src/test/java/org/javacs/RefactorFileTest.java +++ /dev/null @@ -1,223 +0,0 @@ -package org.javacs; - -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; - -import com.sun.source.tree.CompilationUnitTree; -import com.sun.source.util.JavacTask; -import java.io.IOException; -import java.io.Reader; -import java.io.StringReader; -import java.net.URI; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Optional; -import java.util.function.BiConsumer; -import java.util.logging.Logger; -import org.eclipse.lsp4j.Position; -import org.eclipse.lsp4j.TextEdit; -import org.junit.Test; - -public class RefactorFileTest { - - private static final Logger LOG = Logger.getLogger("main"); - private static final URI FAKE_FILE = - URI.create("test/imaginary-resources/org/javacs/Example.java"); - - @Test - public void addImportToEmpty() { - String before = "package org.javacs;\n" + "\n" + "public class Example { void main() { } }"; - List<TextEdit> edits = addImport(before, "org.javacs", "Foo"); - String after = applyEdits(before, edits); - - assertThat( - after, - equalTo( - "package org.javacs;\n" - + "\n" - + "import org.javacs.Foo;\n" - + "\n" - + "public class Example { void main() { } }")); - } - - @Test - public void addImportToExisting() { - String before = - "package org.javacs;\n" - + "\n" - + "import java.util.List;\n" - + "\n" - + "public class Example { void main() { } }"; - List<TextEdit> edits = addImport(before, "org.javacs", "Foo"); - String after = applyEdits(before, edits); - - assertThat( - after, - equalTo( - "package org.javacs;\n" - + "\n" - + "import java.util.List;\n" - + "import org.javacs.Foo;\n" - + "\n" - + "public class Example { void main() { } }")); - } - - @Test - public void addImportAtBeginning() { - String before = - "package org.javacs;\n" - + "\n" - + "import org.javacs.Foo;\n" - + "\n" - + "public class Example { void main() { } }"; - List<TextEdit> edits = addImport(before, "java.util", "List"); - String after = applyEdits(before, edits); - - assertThat( - after, - equalTo( - "package org.javacs;\n" - + "\n" - + "import java.util.List;\n" - + "import org.javacs.Foo;\n" - + "\n" - + "public class Example { void main() { } }")); - } - - @Test - public void importAlreadyExists() { - String before = - "package org.javacs;\n" - + "\n" - + "import java.util.List;\n" - + "\n" - + "public class Example { void main() { } }"; - List<TextEdit> edits = addImport(before, "java.util", "List"); - String after = applyEdits(before, edits); - - assertThat( - after, - equalTo( - "package org.javacs;\n" - + "\n" - + "import java.util.List;\n" - + "\n" - + "public class Example { void main() { } }")); - } - - @Test - public void noPackage() { - String before = - "import java.util.List;\n" + "\n" + "public class Example { void main() { } }"; - List<TextEdit> edits = addImport(before, "org.javacs", "Foo"); - String after = applyEdits(before, edits); - - assertThat( - after, - equalTo( - "import java.util.List;\n" - + "import org.javacs.Foo;\n" - + "\n" - + "public class Example { void main() { } }")); - } - - @Test - public void noPackageNoImports() { - String before = "public class Example { void main() { } }"; - List<TextEdit> edits = addImport(before, "org.javacs", "Foo"); - String after = applyEdits(before, edits); - - assertThat( - after, - equalTo( - "import org.javacs.Foo;\n" - + "\n" - + "public class Example { void main() { } }")); - } - - private List<TextEdit> addImport(String content, String packageName, String className) { - List<TextEdit> result = new ArrayList<>(); - JavacHolder compiler = - JavacHolder.create( - Collections.singleton(Paths.get("src/test/test-project/workspace/src")), - Collections.emptySet()); - BiConsumer<JavacTask, CompilationUnitTree> doRefactor = - (task, tree) -> { - List<TextEdit> edits = - new RefactorFile(task, tree).addImport(packageName, className); - - result.addAll(edits); - }; - - compiler.compileBatch( - Collections.singletonMap(FAKE_FILE, Optional.of(content)), doRefactor); - - return result; - } - - private String applyEdits(String before, List<TextEdit> edits) { - StringBuffer buffer = new StringBuffer(before); - - edits.stream().sorted(this::compareEdits).forEach(edit -> applyEdit(buffer, edit)); - - return buffer.toString(); - } - - private int compareEdits(TextEdit left, TextEdit right) { - int compareLines = - -Integer.compare( - left.getRange().getEnd().getLine(), right.getRange().getEnd().getLine()); - - if (compareLines != 0) return compareLines; - else - return -Integer.compare( - left.getRange().getStart().getCharacter(), - right.getRange().getEnd().getCharacter()); - } - - private void applyEdit(StringBuffer buffer, TextEdit edit) { - buffer.replace( - offset(edit.getRange().getStart(), buffer), - offset(edit.getRange().getEnd(), buffer), - edit.getNewText()); - } - - private int offset(Position pos, StringBuffer buffer) { - return (int) findOffset(buffer.toString(), pos.getLine(), pos.getCharacter()); - } - - public static long findOffset(String content, int targetLine, int targetCharacter) { - try (Reader in = new StringReader(content)) { - long offset = 0; - int line = 0; - int character = 0; - - while (line < targetLine) { - int next = in.read(); - - if (next < 0) return offset; - else { - offset++; - - if (next == '\n') line++; - } - } - - while (character < targetCharacter) { - int next = in.read(); - - if (next < 0) return offset; - else { - offset++; - character++; - } - } - - return offset; - } catch (IOException e) { - throw ShowMessageException.error(e.getMessage(), e); - } - } -} diff --git a/src/test/java/org/javacs/SearchTest.java b/src/test/java/org/javacs/SearchTest.java index b92b0e1..f99bba4 100644 --- a/src/test/java/org/javacs/SearchTest.java +++ b/src/test/java/org/javacs/SearchTest.java @@ -6,7 +6,6 @@ import static org.junit.Assert.assertThat; import com.google.common.base.Joiner; import java.io.IOException; import java.net.URI; -import java.net.URISyntaxException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Set; @@ -23,10 +22,10 @@ public class SearchTest { private static final JavaLanguageServer server = LanguageServerFixture.getJavaLanguageServer(); @BeforeClass - public static void openSource() throws URISyntaxException, IOException { - URI uri = FindResource.uri("/org/javacs/example/AutocompleteBetweenLines.java"); - String textContent = Joiner.on("\n").join(Files.readAllLines(Paths.get(uri))); - TextDocumentItem document = new TextDocumentItem(); + public static void openSource() throws IOException { + var uri = FindResource.uri("/org/javacs/example/AutocompleteBetweenLines.java"); + var textContent = Joiner.on("\n").join(Files.readAllLines(Paths.get(uri))); + var document = new TextDocumentItem(); document.setUri(uri.toString()); document.setText(textContent); @@ -34,13 +33,14 @@ public class SearchTest { server.getTextDocumentService().didOpen(new DidOpenTextDocumentParams(document, null)); } - private static Set<String> searchWorkspace(String query) { + private static Set<String> searchWorkspace(String query, int limit) { try { return server.getWorkspaceService() .symbol(new WorkspaceSymbolParams(query)) .get() .stream() .map(result -> result.getName()) + .limit(limit) .collect(Collectors.toSet()); } catch (InterruptedException | ExecutionException e) { throw new RuntimeException(e); @@ -50,8 +50,7 @@ public class SearchTest { private static Set<String> searchFile(URI uri) { try { return server.getTextDocumentService() - .documentSymbol( - new DocumentSymbolParams(new TextDocumentIdentifier(uri.toString()))) + .documentSymbol(new DocumentSymbolParams(new TextDocumentIdentifier(uri.toString()))) .get() .stream() .map(result -> result.getName()) @@ -63,29 +62,29 @@ public class SearchTest { @Test public void all() { - Set<String> all = searchWorkspace(""); + var all = searchWorkspace("", 100); assertThat(all, not(empty())); } @Test public void searchClasses() { - Set<String> all = searchWorkspace("ABetweenLines"); + var all = searchWorkspace("ABetweenLines", Integer.MAX_VALUE); assertThat(all, hasItem("AutocompleteBetweenLines")); } @Test public void searchMethods() { - Set<String> all = searchWorkspace("mStatic"); + var all = searchWorkspace("mStatic", Integer.MAX_VALUE); assertThat(all, hasItem("methodStatic")); } @Test public void symbolsInFile() { - String path = "/org/javacs/example/AutocompleteMemberFixed.java"; - Set<String> all = searchFile(FindResource.uri(path)); + var path = "/org/javacs/example/AutocompleteMemberFixed.java"; + var all = searchFile(FindResource.uri(path)); assertThat( all, @@ -102,8 +101,8 @@ public class SearchTest { @Test public void explicitConstructor() { - String path = "/org/javacs/example/ReferenceConstructor.java"; - Set<String> all = searchFile(FindResource.uri(path)); + var path = "/org/javacs/example/ReferenceConstructor.java"; + var all = searchFile(FindResource.uri(path)); assertThat("includes explicit constructor", all, hasItem("ReferenceConstructor")); } diff --git a/src/test/java/org/javacs/SignatureHelpTest.java b/src/test/java/org/javacs/SignatureHelpTest.java index ee53d91..125e6fb 100644 --- a/src/test/java/org/javacs/SignatureHelpTest.java +++ b/src/test/java/org/javacs/SignatureHelpTest.java @@ -14,14 +14,14 @@ import org.junit.Test; public class SignatureHelpTest { @Test public void signatureHelp() throws IOException { - SignatureHelp help = doHelp("/org/javacs/example/SignatureHelp.java", 7, 36); + var help = doHelp("/org/javacs/example/SignatureHelp.java", 7, 36); assertThat(help.getSignatures(), hasSize(2)); } @Test public void partlyFilledIn() throws IOException { - SignatureHelp help = doHelp("/org/javacs/example/SignatureHelp.java", 8, 39); + var help = doHelp("/org/javacs/example/SignatureHelp.java", 8, 39); assertThat(help.getSignatures(), hasSize(2)); assertThat(help.getActiveSignature(), equalTo(1)); @@ -30,7 +30,7 @@ public class SignatureHelpTest { @Test public void constructor() throws IOException { - SignatureHelp help = doHelp("/org/javacs/example/SignatureHelp.java", 9, 27); + var help = doHelp("/org/javacs/example/SignatureHelp.java", 9, 27); assertThat(help.getSignatures(), hasSize(1)); assertThat(help.getSignatures().get(0).getLabel(), startsWith("SignatureHelp")); @@ -38,26 +38,27 @@ public class SignatureHelpTest { @Test public void platformConstructor() throws IOException { - SignatureHelp help = doHelp("/org/javacs/example/SignatureHelp.java", 10, 26); + var help = doHelp("/org/javacs/example/SignatureHelp.java", 10, 26); assertThat(help.getSignatures(), not(empty())); assertThat(help.getSignatures().get(0).getLabel(), startsWith("ArrayList")); - assertThat(help.getSignatures().get(0).getDocumentation(), not(nullValue())); + // TODO + // assertThat(help.getSignatures().get(0).getDocumentation(), not(nullValue())); } private static final JavaLanguageServer server = LanguageServerFixture.getJavaLanguageServer(); private SignatureHelp doHelp(String file, int row, int column) throws IOException { - TextDocumentIdentifier document = new TextDocumentIdentifier(); + var document = new TextDocumentIdentifier(); document.setUri(FindResource.uri(file).toString()); - Position position = new Position(); + var position = new Position(); position.setLine(row - 1); position.setCharacter(column - 1); - TextDocumentPositionParams p = new TextDocumentPositionParams(); + var p = new TextDocumentPositionParams(); p.setTextDocument(document); p.setPosition(position); diff --git a/src/test/java/org/javacs/SymbolIndexTest.java b/src/test/java/org/javacs/SymbolIndexTest.java deleted file mode 100644 index 285a5cb..0000000 --- a/src/test/java/org/javacs/SymbolIndexTest.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.javacs; - -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; - -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.Collections; -import java.util.Optional; -import org.junit.Test; - -public class SymbolIndexTest { - private Path workspaceRoot = Paths.get("src/test/test-project/workspace"); - private SymbolIndex index = - new SymbolIndex(workspaceRoot, () -> Collections.emptySet(), __ -> Optional.empty()); - - @Test - public void workspaceSourcePath() { - assertThat(index.sourcePath(), contains(workspaceRoot.resolve("src").toAbsolutePath())); - } -} diff --git a/src/test/java/org/javacs/SymbolUnderCursorTest.java b/src/test/java/org/javacs/SymbolUnderCursorTest.java index 0f44f5c..e090834 100644 --- a/src/test/java/org/javacs/SymbolUnderCursorTest.java +++ b/src/test/java/org/javacs/SymbolUnderCursorTest.java @@ -1,9 +1,13 @@ package org.javacs; -import static org.junit.Assert.assertEquals; - -import java.util.Optional; -import javax.lang.model.element.Element; +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; + +import java.util.StringJoiner; +import java.util.concurrent.ExecutionException; +import org.eclipse.lsp4j.Position; +import org.eclipse.lsp4j.TextDocumentIdentifier; +import org.eclipse.lsp4j.TextDocumentPositionParams; import org.junit.Ignore; import org.junit.Test; @@ -11,85 +15,108 @@ public class SymbolUnderCursorTest { @Test public void classDeclaration() { - assertEquals( - "SymbolUnderCursor", symbolAt("/org/javacs/example/SymbolUnderCursor.java", 3, 22)); + assertThat( + symbolAt("/org/javacs/example/SymbolUnderCursor.java", 3, 22), + containsString("org.javacs.example.SymbolUnderCursor")); } @Test public void fieldDeclaration() { - assertEquals("field", symbolAt("/org/javacs/example/SymbolUnderCursor.java", 4, 22)); + assertThat(symbolAt("/org/javacs/example/SymbolUnderCursor.java", 4, 22), containsString("field")); } @Test public void methodDeclaration() { - assertEquals("method", symbolAt("/org/javacs/example/SymbolUnderCursor.java", 6, 22)); + assertThat( + symbolAt("/org/javacs/example/SymbolUnderCursor.java", 6, 22), + containsString("method(String methodParameter)")); } @Test public void methodParameterDeclaration() { - assertEquals( - "methodParameter", symbolAt("/org/javacs/example/SymbolUnderCursor.java", 6, 36)); + assertThat(symbolAt("/org/javacs/example/SymbolUnderCursor.java", 6, 36), containsString("methodParameter")); } @Test public void localVariableDeclaration() { - assertEquals( - "localVariable", symbolAt("/org/javacs/example/SymbolUnderCursor.java", 7, 22)); + assertThat(symbolAt("/org/javacs/example/SymbolUnderCursor.java", 7, 22), containsString("localVariable")); } @Test public void constructorParameterDeclaration() { - assertEquals( - "constructorParameter", - symbolAt("/org/javacs/example/SymbolUnderCursor.java", 17, 46)); + assertThat( + symbolAt("/org/javacs/example/SymbolUnderCursor.java", 17, 46), containsString("constructorParameter")); } @Test public void classIdentifier() { - assertEquals( - "SymbolUnderCursor", - symbolAt("/org/javacs/example/SymbolUnderCursor.java", 12, 23)); + assertThat( + symbolAt("/org/javacs/example/SymbolUnderCursor.java", 12, 23), + containsString("org.javacs.example.SymbolUnderCursor")); } @Test public void fieldIdentifier() { - assertEquals("field", symbolAt("/org/javacs/example/SymbolUnderCursor.java", 9, 27)); + assertThat(symbolAt("/org/javacs/example/SymbolUnderCursor.java", 9, 27), containsString("field")); } @Test public void methodIdentifier() { - assertEquals("method", symbolAt("/org/javacs/example/SymbolUnderCursor.java", 12, 12)); + assertThat( + symbolAt("/org/javacs/example/SymbolUnderCursor.java", 12, 12), + containsString("method(String methodParameter)")); } @Test public void methodSelect() { - assertEquals("method", symbolAt("/org/javacs/example/SymbolUnderCursor.java", 13, 17)); + assertThat( + symbolAt("/org/javacs/example/SymbolUnderCursor.java", 13, 17), + containsString("method(String methodParameter)")); } @Ignore // tree.sym is null @Test public void methodReference() { - assertEquals("method", symbolAt("/org/javacs/example/SymbolUnderCursor.java", 14, 46)); + assertThat(symbolAt("/org/javacs/example/SymbolUnderCursor.java", 14, 65), containsString("method")); + } + + @Test + public void annotationUse() { + var found = symbolAt("/org/javacs/example/SymbolUnderCursor.java", 21, 8); + assertThat(found, containsString("@interface Override")); + assertThat(found, not(containsString("extends none"))); } @Test public void methodParameterReference() { - assertEquals( - "methodParameter", symbolAt("/org/javacs/example/SymbolUnderCursor.java", 10, 32)); + assertThat(symbolAt("/org/javacs/example/SymbolUnderCursor.java", 10, 32), containsString("methodParameter")); } @Test public void localVariableReference() { - assertEquals( - "localVariable", symbolAt("/org/javacs/example/SymbolUnderCursor.java", 10, 16)); + assertThat(symbolAt("/org/javacs/example/SymbolUnderCursor.java", 10, 16), containsString("localVariable")); } - // Re-using the language server makes these tests go a lot faster, but it will potentially produce surprising output if things go wrong + // Re-using the language server makes these tests go a lot faster, but it will potentially produce surprising output + // if things go wrong private static final JavaLanguageServer server = LanguageServerFixture.getJavaLanguageServer(); private String symbolAt(String file, int line, int character) { - Optional<Element> symbol = server.findSymbol(FindResource.uri(file), line, character); - - return symbol.map(s -> s.getSimpleName().toString()).orElse(null); + var pos = + new TextDocumentPositionParams( + new TextDocumentIdentifier(FindResource.uri(file).toString()), + new Position(line - 1, character - 1)); + var result = new StringJoiner("\n"); + try { + server.getTextDocumentService() + .hover(pos) + .get() + .getContents() + .getLeft() + .forEach(hover -> result.add(hover.isLeft() ? hover.getLeft() : hover.getRight().getValue())); + } catch (InterruptedException | ExecutionException e) { + throw new RuntimeException(e); + } + return result.toString(); } } diff --git a/src/test/java/org/javacs/TreePrunerTest.java b/src/test/java/org/javacs/TreePrunerTest.java deleted file mode 100644 index 0aa5e18..0000000 --- a/src/test/java/org/javacs/TreePrunerTest.java +++ /dev/null @@ -1,99 +0,0 @@ -package org.javacs; - -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.equalToIgnoringWhiteSpace; -import static org.junit.Assert.assertThat; - -import com.sun.source.tree.CompilationUnitTree; -import com.sun.source.util.JavacTask; -import com.sun.tools.javac.api.JavacTool; -import java.io.IOException; -import java.net.URI; -import java.util.Collections; -import java.util.logging.Logger; -import javax.tools.JavaFileObject; -import org.junit.Test; - -public class TreePrunerTest { - private static final Logger LOG = Logger.getLogger("main"); - - private JavacTask task(String source) { - return JavacTool.create() - .getTask( - null, - null, - err -> LOG.warning(err.getMessage(null)), - Collections.emptyList(), - Collections.emptyList(), - Collections.singleton( - new StringFileObject(source, URI.create("FakePath.java")))); - } - - @Test - public void putSemicolonAfterCursor() throws IOException { - String source = - "public class Example {\n" + " void main() {\n" + " this.m\n" + " }\n" + "}\n"; - JavaFileObject after = - TreePruner.putSemicolonAfterCursor( - new StringFileObject(source, URI.create("Example.java")), 3, 11); - - assertThat( - after.getCharContent(true).toString(), - equalTo( - "public class Example {\n" - + " void main() {\n" - + " this.m;\n" - + " }\n" - + "}\n")); - } - - @Test - public void putSemicolonAtEndOfLine() throws IOException { - String source = - "public class Example {\n" - + " void main() {\n" - + " this.main\n" - + " }\n" - + "}\n"; - JavaFileObject after = - TreePruner.putSemicolonAfterCursor( - new StringFileObject(source, URI.create("Example.java")), 3, 11); - - assertThat( - after.getCharContent(true).toString(), - equalTo( - "public class Example {\n" - + " void main() {\n" - + " this.main;\n" - + " }\n" - + "}\n")); - } - - @Test - public void removeStatementsAfterCursor() throws IOException { - String source = - "public class Example {\n" - + " void main() {\n" - + " foo()\n" - + " bar()\n" - + " doh()\n" - + " }\n" - + "}\n"; - JavacTask task = task(source); - CompilationUnitTree tree = task.parse().iterator().next(); - - new TreePruner(task).removeStatementsAfterCursor(tree, 4, 6); - - assertThat( - tree.toString(), - equalToIgnoringWhiteSpace( - "\n" - + "public class Example {\n" - + " \n" - + " void main() {\n" - + " foo();\n" - + " bar();\n" - + " }\n" - + "}")); - } -} diff --git a/src/test/resources/BuildUpScope.java b/src/test/resources/BuildUpScope.java new file mode 100644 index 0000000..171d816 --- /dev/null +++ b/src/test/resources/BuildUpScope.java @@ -0,0 +1,8 @@ +class BuildUpScope { + void main() { + int a = 1; + int b = 2; + int c = 3; + } + void otherMethod() { } +}
\ No newline at end of file diff --git a/src/test/resources/ClassDoc.java b/src/test/resources/ClassDoc.java new file mode 100644 index 0000000..9106496 --- /dev/null +++ b/src/test/resources/ClassDoc.java @@ -0,0 +1,4 @@ +/** A great class */ +class ClassDoc { + +}
\ No newline at end of file diff --git a/src/test/resources/CompleteClass.java b/src/test/resources/CompleteClass.java new file mode 100644 index 0000000..5f16fb8 --- /dev/null +++ b/src/test/resources/CompleteClass.java @@ -0,0 +1,13 @@ +class CompleteClass { + void test() { + CompleteClass. + } + + static void staticMethod() { } + + void instanceMethod() { } + + static int staticField; + + int instanceField; +}
\ No newline at end of file diff --git a/src/test/resources/CompleteExpression.java b/src/test/resources/CompleteExpression.java new file mode 100644 index 0000000..9b9dd00 --- /dev/null +++ b/src/test/resources/CompleteExpression.java @@ -0,0 +1,13 @@ +class CompleteExpression { + void test() { + CompleteExpression.create(). + } + + static CompleteExpression create() { + return new CompleteExpression(); + } + + int instanceMethod() { + return 1; + } +}
\ No newline at end of file diff --git a/src/test/resources/CompleteIdentifiers.java b/src/test/resources/CompleteIdentifiers.java new file mode 100644 index 0000000..8ba5e39 --- /dev/null +++ b/src/test/resources/CompleteIdentifiers.java @@ -0,0 +1,16 @@ +class CompleteIdentifiers { + static int completeOuterStatic; + int completeOuterField; + + class CompleteInnerClass { + int completeInnerField; + + void completeOtherMethod() { + } + + void test(int completeParam) { + int completeLocal = 1; + complete + } + } +}
\ No newline at end of file diff --git a/src/test/resources/CompleteImports.java b/src/test/resources/CompleteImports.java new file mode 100644 index 0000000..1b0dc80 --- /dev/null +++ b/src/test/resources/CompleteImports.java @@ -0,0 +1 @@ +import java.util.
\ No newline at end of file diff --git a/src/test/resources/CompleteInMiddle.java b/src/test/resources/CompleteInMiddle.java new file mode 100644 index 0000000..981e71e --- /dev/null +++ b/src/test/resources/CompleteInMiddle.java @@ -0,0 +1,17 @@ +class CompleteInMiddle { + static int completeOuterStatic; + int completeOuterField; + + class CompleteInnerClass { + int completeInnerField; + + void completeOtherMethod() { + } + + void test(int completeParam) { + int completeLocal = 1; + complete + int localAfter = 2; + } + } +}
\ No newline at end of file diff --git a/src/test/resources/CompleteMembers.java b/src/test/resources/CompleteMembers.java new file mode 100644 index 0000000..168dc65 --- /dev/null +++ b/src/test/resources/CompleteMembers.java @@ -0,0 +1,17 @@ +class CompleteMembers { + void test(Sub param) { + param. + } + + class Super { + void superMethod() { + + } + } + + class Sub extends Super { + void subMethod() { + + } + } +}
\ No newline at end of file diff --git a/src/test/resources/GotoDefinition.java b/src/test/resources/GotoDefinition.java new file mode 100644 index 0000000..1f8866c --- /dev/null +++ b/src/test/resources/GotoDefinition.java @@ -0,0 +1,8 @@ +class GotoDefinition { + void test() { + goToHere(); + } + + void goToHere() { + } +}
\ No newline at end of file diff --git a/src/test/resources/HasError.java b/src/test/resources/HasError.java new file mode 100644 index 0000000..ad2fbe2 --- /dev/null +++ b/src/test/resources/HasError.java @@ -0,0 +1,5 @@ +class HasError { + void test() { + String x = 1; + } +}
\ No newline at end of file diff --git a/src/test/resources/HasImport.java b/src/test/resources/HasImport.java new file mode 100644 index 0000000..2b4f66e --- /dev/null +++ b/src/test/resources/HasImport.java @@ -0,0 +1,5 @@ +import java.util.List; + +class HasImport { + +}
\ No newline at end of file diff --git a/src/test/resources/HelloWorld.java b/src/test/resources/HelloWorld.java new file mode 100644 index 0000000..b86724f --- /dev/null +++ b/src/test/resources/HelloWorld.java @@ -0,0 +1,5 @@ +public class HelloWorld { + public static void main(String[] args) { + System.out.println("Hello world!"); + } +}
\ No newline at end of file diff --git a/src/test/resources/LocalMethodDoc.java b/src/test/resources/LocalMethodDoc.java new file mode 100644 index 0000000..a240753 --- /dev/null +++ b/src/test/resources/LocalMethodDoc.java @@ -0,0 +1,12 @@ +class LocalMethodDoc { + void testMethod() { + targetMethod(1); + } + + /** + * A great method + * @param param A great param + */ + void targetMethod(int param) { + } +}
\ No newline at end of file diff --git a/src/test/resources/MissingImport.java b/src/test/resources/MissingImport.java new file mode 100644 index 0000000..79f0d92 --- /dev/null +++ b/src/test/resources/MissingImport.java @@ -0,0 +1,5 @@ +class MissingImport { + void test() { + List<String> x = null; + } +}
\ No newline at end of file diff --git a/src/test/resources/Overloads.java b/src/test/resources/Overloads.java new file mode 100644 index 0000000..e686971 --- /dev/null +++ b/src/test/resources/Overloads.java @@ -0,0 +1,8 @@ +class Overloads { + void test() { + print() + } + + void print(int i) { } + void print(String s) { } +}
\ No newline at end of file diff --git a/src/test/resources/PruneDot.java b/src/test/resources/PruneDot.java new file mode 100644 index 0000000..2ea5e1d --- /dev/null +++ b/src/test/resources/PruneDot.java @@ -0,0 +1,5 @@ +class PruneMiddle { + void test(String a) { + a. + } +}
\ No newline at end of file diff --git a/src/test/resources/PruneDot_erased.java b/src/test/resources/PruneDot_erased.java new file mode 100644 index 0000000..2ea5e1d --- /dev/null +++ b/src/test/resources/PruneDot_erased.java @@ -0,0 +1,5 @@ +class PruneMiddle { + void test(String a) { + a. + } +}
\ No newline at end of file diff --git a/src/test/resources/PruneMethods.java b/src/test/resources/PruneMethods.java new file mode 100644 index 0000000..474cee2 --- /dev/null +++ b/src/test/resources/PruneMethods.java @@ -0,0 +1,8 @@ +class PruneMethods { + void a() { + int a = 1; + } + void b() { + int b = 2; + } +}
\ No newline at end of file diff --git a/src/test/resources/PruneMethods_erased.java b/src/test/resources/PruneMethods_erased.java new file mode 100644 index 0000000..e3d1a4b --- /dev/null +++ b/src/test/resources/PruneMethods_erased.java @@ -0,0 +1,8 @@ +class PruneMethods { + void a() { + + } + void b() { + int b = 2; + } +}
\ No newline at end of file diff --git a/src/test/resources/PruneMiddle.java b/src/test/resources/PruneMiddle.java new file mode 100644 index 0000000..1916250 --- /dev/null +++ b/src/test/resources/PruneMiddle.java @@ -0,0 +1,7 @@ +class PruneMiddle { + void test() { + var a = "foo"; + a.l + var c = 3; + } +}
\ No newline at end of file diff --git a/src/test/resources/PruneMiddle_erased.java b/src/test/resources/PruneMiddle_erased.java new file mode 100644 index 0000000..5b208b3 --- /dev/null +++ b/src/test/resources/PruneMiddle_erased.java @@ -0,0 +1,7 @@ +class PruneMiddle { + void test() { + var a = "foo"; + a.l + + } +}
\ No newline at end of file diff --git a/src/test/resources/PruneToEndOfBlock.java b/src/test/resources/PruneToEndOfBlock.java new file mode 100644 index 0000000..9174589 --- /dev/null +++ b/src/test/resources/PruneToEndOfBlock.java @@ -0,0 +1,7 @@ +class PruneToEndOfBlock { + void test() { + int a = 1; + int b = 2; + int c = 3; + } +}
\ No newline at end of file diff --git a/src/test/resources/PruneToEndOfBlock_erased.java b/src/test/resources/PruneToEndOfBlock_erased.java new file mode 100644 index 0000000..fafee1f --- /dev/null +++ b/src/test/resources/PruneToEndOfBlock_erased.java @@ -0,0 +1,7 @@ +class PruneToEndOfBlock { + void test() { + int a = 1; + int b = 2; + + } +}
\ No newline at end of file diff --git a/src/test/test-project/bazel-temp/xyz/execroot/test/bazel-out/local-fastbuild/bin/bazel-bin b/src/test/test-project/bazel-temp/xyz/execroot/test/bazel-out/local-fastbuild/bin/bazel-bin new file mode 120000 index 0000000..86b13ae --- /dev/null +++ b/src/test/test-project/bazel-temp/xyz/execroot/test/bazel-out/local-fastbuild/bin/bazel-bin @@ -0,0 +1 @@ +bazel-bin
\ No newline at end of file diff --git a/src/test/test-project/bazel-workspace/module/placeholder.txt b/src/test/test-project/bazel-workspace/module/placeholder.txt new file mode 100644 index 0000000..a0b89c4 --- /dev/null +++ b/src/test/test-project/bazel-workspace/module/placeholder.txt @@ -0,0 +1 @@ +Make sure module dir gets checked into git
\ No newline at end of file diff --git a/src/test/test-project/workspace/src/org/javacs/doimport/ImportThings.java b/src/test/test-project/workspace/src/org/javacs/doimport/ImportThings.java new file mode 100644 index 0000000..df6e96a --- /dev/null +++ b/src/test/test-project/workspace/src/org/javacs/doimport/ImportThings.java @@ -0,0 +1,8 @@ +package org.javacs.doimport; + +import java.util.List; +import java.io.*; + +class ImportThings { + +}
\ No newline at end of file diff --git a/src/test/test-project/workspace/src/org/javacs/example/AutocompleteClasses.java b/src/test/test-project/workspace/src/org/javacs/example/AutocompleteClasses.java index a92b404..bddf9f4 100644 --- a/src/test/test-project/workspace/src/org/javacs/example/AutocompleteClasses.java +++ b/src/test/test-project/workspace/src/org/javacs/example/AutocompleteClasses.java @@ -2,7 +2,8 @@ package org.javacs.example; public class AutocompleteClasses { public static void test() { - S; + Fix; + Some; } public static class SomeInnerClass { diff --git a/src/test/test-project/workspace/src/org/javacs/example/AutocompleteInners.java b/src/test/test-project/workspace/src/org/javacs/example/AutocompleteInners.java index 608e1f2..33f4566 100644 --- a/src/test/test-project/workspace/src/org/javacs/example/AutocompleteInners.java +++ b/src/test/test-project/workspace/src/org/javacs/example/AutocompleteInners.java @@ -8,7 +8,7 @@ public class AutocompleteInners { public void testReference() { new AutocompleteInners.I; - new I; + new Inner; } public void testEnum() { diff --git a/src/test/test-project/workspace/src/org/javacs/example/AutocompleteMember.java b/src/test/test-project/workspace/src/org/javacs/example/AutocompleteMember.java index 3c555e2..fc63d6f 100644 --- a/src/test/test-project/workspace/src/org/javacs/example/AutocompleteMember.java +++ b/src/test/test-project/workspace/src/org/javacs/example/AutocompleteMember.java @@ -5,21 +5,21 @@ public class AutocompleteMember { this.; } - public static String fieldStatic; - public String fields; - public static String methodStatic() { + public static String testFieldStatic; + public String testFields; + public static String testMethodStatic() { return "foo"; } - public String methods() throws Exception { + public String testMethods() throws Exception { return "foo"; } - private static String fieldStaticPrivate; - private String fieldsPrivate; - private static String methodStaticPrivate() { + private static String testFieldStaticPrivate; + private String testFieldsPrivate; + private static String testMethodStaticPrivate() { return "foo"; } - private String methodsPrivate() { + private String testMethodsPrivate() { return "foo"; } }
\ No newline at end of file diff --git a/src/test/test-project/workspace/src/org/javacs/example/AutocompleteMembers.java b/src/test/test-project/workspace/src/org/javacs/example/AutocompleteMembers.java index ddc19c8..76431bc 100644 --- a/src/test/test-project/workspace/src/org/javacs/example/AutocompleteMembers.java +++ b/src/test/test-project/workspace/src/org/javacs/example/AutocompleteMembers.java @@ -1,34 +1,34 @@ package org.javacs.example; public class AutocompleteMembers { - private String fields; - private static String fieldStatic; + private String testFields; + private static String testFieldStatic; { - s; // fields, fieldStatic, methods, methodStatic - this.s; // fields, methods - AutocompleteMembers.s; // fieldStatic, methodStatic - this::s; // methods - AutocompleteMembers::s; // methods, methodStatic + t; // testFields, testFieldStatic, testMethods, testMethodStatic + this.t; // testFields, testMethods + AutocompleteMembers.t; // testFieldStatic, testMethodStatic + this::t; // testMethods + AutocompleteMembers::t; // testMethods, testMethodStatic } static { - s; // fieldStatic - AutocompleteMembers.s; // fieldStatic - AutocompleteMembers::s; // methods, methodStatic + t; // testFieldStatic + AutocompleteMembers.t; // testFieldStatic + AutocompleteMembers::t; // testMethods, testMethodStatic } - private void methods(String arguments) { - s; // fields, fieldStatic, methods, methodStatic, arguments - this.s; // fields, methods - AutocompleteMembers.s; // fieldStatic, methodStatic - java.util.function.Supplier<String> test = this::s; // methods - java.util.function.Supplier<String> test = AutocompleteMembers::s; // methods, methodStatic + private void testMethods(String testArguments) { + t; // testFields, testFieldStatic, testMethods, testMethodStatic, testArguments + this.t; // testFields, testMethods + AutocompleteMembers.t; // testFieldStatic, testMethodStatic + java.util.function.Supplier<String> test = this::t; // testMethods + java.util.function.Supplier<String> test = AutocompleteMembers::t; // testMethods, testMethodStatic } - private static void methodStatic(String arguments) { - s; // fieldStatic, arguments - AutocompleteMembers.s; // fieldStatic - AutocompleteMembers::s; // methods, methodStatic + private static void testMethodStatic(String testArguments) { + t; // testFieldStatic, testArguments + AutocompleteMembers.t; // testFieldStatic + AutocompleteMembers::t; // testMethods, testMethodStatic } }
\ No newline at end of file diff --git a/src/test/test-project/workspace/src/org/javacs/example/AutocompleteOther.java b/src/test/test-project/workspace/src/org/javacs/example/AutocompleteOther.java index 8491f72..7a4b2a6 100644 --- a/src/test/test-project/workspace/src/org/javacs/example/AutocompleteOther.java +++ b/src/test/test-project/workspace/src/org/javacs/example/AutocompleteOther.java @@ -3,7 +3,7 @@ package org.javacs.example; import java.util.Arrays; import java.util.concurrent public class AutocompleteOther { public void test() { new AutocompleteMember().; - A; + Auto; AutocompleteMember.; AutocompleteOther.class.; ArrayLis; diff --git a/src/test/test-project/workspace/src/org/javacs/example/AutocompleteOuter.java b/src/test/test-project/workspace/src/org/javacs/example/AutocompleteOuter.java index c7a4c0d..408b8a7 100644 --- a/src/test/test-project/workspace/src/org/javacs/example/AutocompleteOuter.java +++ b/src/test/test-project/workspace/src/org/javacs/example/AutocompleteOuter.java @@ -1,21 +1,21 @@ package org.javacs.example; public class AutocompleteOuter { - public String fields; - public static String fieldStatic; + public String testFields; + public static String testFieldStatic; - public String methods() { } - public static String methodStatic() { } + public String testMethods() { } + public static String testMethodStatic() { } static class StaticInner { { - s + t } } class Inner { { - s + t } } }
\ No newline at end of file diff --git a/src/test/test-project/workspace/src/org/javacs/example/AutocompleteReference.java b/src/test/test-project/workspace/src/org/javacs/example/AutocompleteReference.java index 2ba5ca4..979fd6c 100644 --- a/src/test/test-project/workspace/src/org/javacs/example/AutocompleteReference.java +++ b/src/test/test-project/workspace/src/org/javacs/example/AutocompleteReference.java @@ -11,12 +11,12 @@ public class AutocompleteReference { System.out.println(message.get()); } - private static String fieldStatic; - private String fields; - private static String methodStatic() { + private static String testFieldStatic; + private String testFields; + private static String testMethodStatic() { return "foo"; } - private String methods() { + private String testMethods() { return "foo"; } }
\ No newline at end of file diff --git a/src/test/test-project/workspace/src/org/javacs/example/AutocompleteScopes.java b/src/test/test-project/workspace/src/org/javacs/example/AutocompleteScopes.java index 2a2fa58..0e371d0 100644 --- a/src/test/test-project/workspace/src/org/javacs/example/AutocompleteScopes.java +++ b/src/test/test-project/workspace/src/org/javacs/example/AutocompleteScopes.java @@ -1,188 +1,188 @@ package org.javacs.example; public class AutocompleteScopes { - static void outerStaticMethod() { } - void outerMethods() { } + static void testOuterStaticMethod() { } + void testOuterMethods() { } static class Super { - static void inheritedStaticMethod() { } - void inheritedMethods() { } + static void testInheritedStaticMethod() { } + void testInheritedMethods() { } } static class StaticSub extends Super { - void test(String arguments) { - int localVariables; - s; + void test(String testArguments) { + int testLocalVariables; + t; // Locals - // YES: localVariables, arguments + // YES: testLocalVariables, testArguments // // Static methods in enclosing scopes // YES: testStatic - // YES: outerStaticMethod + // YES: testOuterStaticMethod // // Virtual methods in enclosing scopes // NO: testInner // YES: test - // NO: outerMethods + // NO: testOuterMethods // // Inherited static methods - // YES: inheritedStaticMethod + // YES: testInheritedStaticMethod // // Inherited virtual methods - // YES: inheritedMethods + // YES: testInheritedMethods // // this/super in enclosing scopes // YES: this, super // YES: StaticSub.this, StaticSub.super - StaticSub.s; + StaticSub.; // NO: AutocompleteScopes.this, AutocompleteScopes.super - AutocompleteScopes.s; + AutocompleteScopes.; // NO: Super.this, Super.super - Super.s; + Super.; new Object() { void testInner() { - s; + t; // Locals - // YES: localVariables, arguments + // YES: testLocalVariables, testArguments // // Static methods in enclosing scopes // YES: testStatic - // YES: outerStaticMethod + // YES: testOuterStaticMethod // // Virtual methods in enclosing scopes // YES: testInner // YES: test - // NO: outerMethods + // NO: testOuterMethods // // Inherited static methods - // YES: inheritedStaticMethod + // YES: testInheritedStaticMethod // // Inherited virtual methods - // YES: inheritedMethods + // YES: testInheritedMethods // // this/super in enclosing scopes // YES: this, super // YES: StaticSub.this, StaticSub.super - StaticSub.s; + StaticSub.; // NO: AutocompleteScopes.this, AutocompleteScopes.super - AutocompleteScopes.s; + AutocompleteScopes.; // NO: Super.this, Super.super - Super.s; + Super.; } }; } - static void testStatic(String arguments) { - int localVariables; - s; + static void testStatic(String testArguments) { + int testLocalVariables; + t; // Locals - // YES: localVariables, arguments + // YES: testLocalVariables, testArguments // // Static methods in enclosing scopes // YES: testStatic - // YES: outerStaticMethod + // YES: testOuterStaticMethod // // Virtual methods in enclosing scopes // NO: testInner // NO: test - // NO: outerMethods + // NO: testOuterMethods // // Inherited static methods - // YES: inheritedStaticMethod + // YES: testInheritedStaticMethod // // Inherited virtual methods - // NO: inheritedMethods + // NO: testInheritedMethods // // this/super in enclosing scopes // NO: this, super // NO: StaticSub.this, StaticSub.super - StaticSub.s; + StaticSub.; // NO: AutocompleteScopes.this, AutocompleteScopes.super - AutocompleteScopes.s; + AutocompleteScopes.; // NO: Super.this, Super.super - Super.s; + Super.; new Object() { void testInner() { - s; + t; // Locals - // YES: localVariables, arguments + // YES: testLocalVariables, testArguments // // Static methods in enclosing scopes // YES: testStatic - // YES: outerStaticMethod + // YES: testOuterStaticMethod // // Virtual methods in enclosing scopes // YES: testInner // NO: test - // NO: outerMethods + // NO: testOuterMethods // // Inherited static methods - // YES: inheritedStaticMethod + // YES: testInheritedStaticMethod // // Inherited virtual methods - // NO: inheritedMethods + // NO: testInheritedMethods // // this/super in enclosing scopes // YES: this, super // NO: StaticSub.this, StaticSub.super - StaticSub.s; + StaticSub.; // NO: AutocompleteScopes.this, AutocompleteScopes.super - AutocompleteScopes.s; + AutocompleteScopes.; // NO: Super.this, Super.super - Super.s; + Super.; } }; } } class Sub extends Super { - void test(String arguments) { - int localVariables; - s; + void test(String testArguments) { + int testLocalVariables; + t; // Locals - // YES: localVariables, arguments + // YES: testLocalVariables, testArguments // // Methods in enclosing scopes // NO: testInner // YES: test - // YES: outerMethods, outerStaticMethod + // YES: testOuterMethods, testOuterStaticMethod // // Inherited methods - // YES: inheritedMethods, inheritedStaticMethod + // YES: testInheritedMethods, testInheritedStaticMethod // // this/super in enclosing scopes // YES: this, super // YES: Sub.this, Sub.super - Sub.s; + Sub.; // YES: AutocompleteScopes.this, AutocompleteScopes.super - AutocompleteScopes.s; + AutocompleteScopes.; // NO: Super.this, Super.super - Super.s; + Super.; new Object() { void testInner() { - s; + t; // Locals - // YES: localVariables, arguments + // YES: testLocalVariables, testArguments // // Methods in enclosing scopes // YES: testInner // YES: test - // YES: outerMethods, outerStaticMethod + // YES: testOuterMethods, testOuterStaticMethod // // Inherited methods - // YES: inheritedMethods, inheritedStaticMethod + // YES: testInheritedMethods, testInheritedStaticMethod // // this/super in enclosing scopes // YES: this, super // YES: Sub.this, Sub.super - Sub.s; + Sub.; // YES: AutocompleteScopes.this, AutocompleteScopes.super - AutocompleteScopes.s; + AutocompleteScopes.; // NO: Super.this, Super.super - Super.s; + Super.; } }; } diff --git a/src/test/test-project/workspace/src/org/javacs/example/AutocompleteStaticImport.java b/src/test/test-project/workspace/src/org/javacs/example/AutocompleteStaticImport.java index 4f382e4..e6670a5 100644 --- a/src/test/test-project/workspace/src/org/javacs/example/AutocompleteStaticImport.java +++ b/src/test/test-project/workspace/src/org/javacs/example/AutocompleteStaticImport.java @@ -8,6 +8,6 @@ class AutocompleteStaticImport { void test() { emptyL; B; - staticFinal; + p; } }
\ No newline at end of file diff --git a/src/test/test-project/workspace/src/org/javacs/example/AutocompleteStaticMember.java b/src/test/test-project/workspace/src/org/javacs/example/AutocompleteStaticMember.java index 93191c1..b77f15d 100644 --- a/src/test/test-project/workspace/src/org/javacs/example/AutocompleteStaticMember.java +++ b/src/test/test-project/workspace/src/org/javacs/example/AutocompleteStaticMember.java @@ -2,15 +2,15 @@ package org.javacs.example; public class AutocompleteStaticMember { public static void test() { - AutocompleteStaticMember. + AutocompleteStaticMember.test } - private static String fieldStatic; - private String field; - private static String methodStatic() { + private static String testFieldStatic; + private String testField; + private static String testMethodStatic() { return "foo"; } - private String method() { + private String testMethod() { return "foo"; } }
\ No newline at end of file diff --git a/src/test/test-project/workspace/src/org/javacs/example/AutocompleteStaticReference.java b/src/test/test-project/workspace/src/org/javacs/example/AutocompleteStaticReference.java index 1a9a0fc..2a280c1 100644 --- a/src/test/test-project/workspace/src/org/javacs/example/AutocompleteStaticReference.java +++ b/src/test/test-project/workspace/src/org/javacs/example/AutocompleteStaticReference.java @@ -4,19 +4,19 @@ import java.util.function.Supplier; public class AutocompleteStaticReference { public static void test() { - print(AutocompleteStaticReference::) + print(AutocompleteStaticReference::test) } private void print(Supplier<String> message) { System.out.println(message.get()); } - private static String fieldStatic; - private String field; - private static String methodStatic() { + private static String testFieldStatic; + private String testField; + private static String testMethodStatic() { return "foo"; } - private String methods() { + private String testMethod() { return "foo"; } }
\ No newline at end of file diff --git a/src/test/test-project/workspace/src/org/javacs/example/Goto.java b/src/test/test-project/workspace/src/org/javacs/example/Goto.java index 2dd774f..3f4cb2f 100644 --- a/src/test/test-project/workspace/src/org/javacs/example/Goto.java +++ b/src/test/test-project/workspace/src/org/javacs/example/Goto.java @@ -1,7 +1,7 @@ package org.javacs.example; public class Goto<Param> { - public static void test() { + public void test() { Object local; Runnable reference; GotoOther other; diff --git a/src/test/test-project/workspace/src/org/javacs/example/HasTest.java b/src/test/test-project/workspace/src/org/javacs/example/HasTest.java new file mode 100644 index 0000000..2bdd656 --- /dev/null +++ b/src/test/test-project/workspace/src/org/javacs/example/HasTest.java @@ -0,0 +1,10 @@ +package org.javacs.example; + +import org.junit.Test; + +public class HasTest { + @Test + public void testMethod() { + + } +}
\ No newline at end of file diff --git a/src/test/test-project/workspace/src/org/javacs/example/OverloadedMethod.java b/src/test/test-project/workspace/src/org/javacs/example/OverloadedMethod.java new file mode 100644 index 0000000..a57edc4 --- /dev/null +++ b/src/test/test-project/workspace/src/org/javacs/example/OverloadedMethod.java @@ -0,0 +1,12 @@ +package org.javacs.example; + +class OverloadedMethod { + void overloaded() { } + void overloaded(int i) { } + void overloaded(String s) { } + + void testCompletion() { + over; + java.util.List.of; + } +}
\ No newline at end of file diff --git a/src/test/test-project/workspace/src/org/javacs/example/SymbolUnderCursor.java b/src/test/test-project/workspace/src/org/javacs/example/SymbolUnderCursor.java index 8ec75ec..26da058 100644 --- a/src/test/test-project/workspace/src/org/javacs/example/SymbolUnderCursor.java +++ b/src/test/test-project/workspace/src/org/javacs/example/SymbolUnderCursor.java @@ -11,10 +11,15 @@ public class SymbolUnderCursor { method(SymbolUnderCursor.class.getName()); this.method("foo"); - Function<String, String> m = this::method; + java.util.function.Function<String, String> m = this::method; } public SymbolUnderCursor(String constructorParameter) { } + + @Override + public void overrideMethod() { + + } }
\ No newline at end of file |