Search in sources :

Example 16 with Assert.assertNotNull

use of org.junit.Assert.assertNotNull in project eclipse.jdt.ls by eclipse.

the class CodeActionResolveHandlerTest method testAssignAllParamsToFields.

@Test
public void testAssignAllParamsToFields() throws Exception {
    when(preferenceManager.getClientPreferences().isResolveCodeActionSupported()).thenReturn(true);
    StringBuilder buf = new StringBuilder();
    buf.append("public class App {\n");
    buf.append("    private String s;\n");
    buf.append("\n");
    buf.append("    public App(String s, String s3, String s2) {\n");
    buf.append("    }\n");
    buf.append("}\n");
    ICompilationUnit unit = defaultPackage.createCompilationUnit("App.java", buf.toString(), false, null);
    CodeActionParams params = new CodeActionParams();
    params.setTextDocument(new TextDocumentIdentifier(JDTUtils.toURI(unit)));
    Range range = CodeActionUtil.getRange(unit, "s3");
    params.setRange(range);
    CodeActionContext context = new CodeActionContext(Collections.emptyList(), Collections.singletonList(JavaCodeActionKind.QUICK_ASSIST));
    params.setContext(context);
    List<Either<Command, CodeAction>> codeActions = server.codeAction(params).join();
    Assert.assertNotNull(codeActions);
    Assert.assertFalse("No quickassist actions were found", codeActions.isEmpty());
    Optional<Either<Command, CodeAction>> assignAllToNewFieldsResponse = codeActions.stream().filter(codeAction -> {
        return "Assign all parameters to new fields".equals(codeAction.getRight().getTitle());
    }).findFirst();
    Assert.assertTrue("Should return the quick assist 'Assign all parameters to new fields'", assignAllToNewFieldsResponse.isPresent());
    CodeAction unresolvedCodeAction = assignAllToNewFieldsResponse.get().getRight();
    CodeAction resolvedCodeAction = server.resolveCodeAction(unresolvedCodeAction).join();
    Assert.assertNotNull("Should resolve the edit property in the resolveCodeAction request", resolvedCodeAction.getEdit());
    String actual = AbstractQuickFixTest.evaluateWorkspaceEdit(resolvedCodeAction.getEdit());
    buf = new StringBuilder();
    buf.append("public class App {\n");
    buf.append("    private String s;\n");
    buf.append("    private String s4;\n");
    buf.append("    private String s3;\n");
    buf.append("    private String s2;\n");
    buf.append("\n");
    buf.append("    public App(String s, String s3, String s2) {\n");
    buf.append("        s4 = s;\n");
    buf.append("        this.s3 = s3;\n");
    buf.append("        this.s2 = s2;\n");
    buf.append("    }\n");
    buf.append("}\n");
    Assert.assertEquals(buf.toString(), actual);
}
Also used : CodeActionParams(org.eclipse.lsp4j.CodeActionParams) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) Arrays(java.util.Arrays) Mock(org.mockito.Mock) JavaCodeActionKind(org.eclipse.jdt.ls.core.internal.JavaCodeActionKind) RunWith(org.junit.runner.RunWith) Diagnostic(org.eclipse.lsp4j.Diagnostic) Range(org.eclipse.lsp4j.Range) TextDocumentIdentifier(org.eclipse.lsp4j.TextDocumentIdentifier) CodeActionContext(org.eclipse.lsp4j.CodeActionContext) IPackageFragment(org.eclipse.jdt.core.IPackageFragment) CodeActionParams(org.eclipse.lsp4j.CodeActionParams) IProject(org.eclipse.core.resources.IProject) Either(org.eclipse.lsp4j.jsonrpc.messages.Either) Position(org.eclipse.lsp4j.Position) LanguageServerWorkingCopyOwner(org.eclipse.jdt.ls.core.internal.LanguageServerWorkingCopyOwner) JavaClientConnection(org.eclipse.jdt.ls.core.internal.JavaClientConnection) IPackageFragmentRoot(org.eclipse.jdt.core.IPackageFragmentRoot) Before(org.junit.Before) CodeAction(org.eclipse.lsp4j.CodeAction) JDTUtils(org.eclipse.jdt.ls.core.internal.JDTUtils) DiagnosticSeverity(org.eclipse.lsp4j.DiagnosticSeverity) IJavaProject(org.eclipse.jdt.core.IJavaProject) WorkspaceHelper(org.eclipse.jdt.ls.core.internal.WorkspaceHelper) Assert.assertNotNull(org.junit.Assert.assertNotNull) JavaCore(org.eclipse.jdt.core.JavaCore) JavaLanguageServerPlugin(org.eclipse.jdt.ls.core.internal.JavaLanguageServerPlugin) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) Mockito.when(org.mockito.Mockito.when) IType(org.eclipse.jdt.core.IType) List(java.util.List) MockitoJUnitRunner(org.mockito.runners.MockitoJUnitRunner) Command(org.eclipse.lsp4j.Command) CodeActionUtil(org.eclipse.jdt.ls.core.internal.CodeActionUtil) Assert.assertFalse(org.junit.Assert.assertFalse) CodeActionKind(org.eclipse.lsp4j.CodeActionKind) Optional(java.util.Optional) TestOptions(org.eclipse.jdt.ls.core.internal.correction.TestOptions) IProblem(org.eclipse.jdt.core.compiler.IProblem) Assert(org.junit.Assert) Collections(java.util.Collections) Assert.assertEquals(org.junit.Assert.assertEquals) AbstractQuickFixTest(org.eclipse.jdt.ls.core.internal.correction.AbstractQuickFixTest) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) TextDocumentIdentifier(org.eclipse.lsp4j.TextDocumentIdentifier) CodeActionContext(org.eclipse.lsp4j.CodeActionContext) CodeAction(org.eclipse.lsp4j.CodeAction) Either(org.eclipse.lsp4j.jsonrpc.messages.Either) Range(org.eclipse.lsp4j.Range) Test(org.junit.Test) AbstractQuickFixTest(org.eclipse.jdt.ls.core.internal.correction.AbstractQuickFixTest)

Example 17 with Assert.assertNotNull

use of org.junit.Assert.assertNotNull in project eclipse.jdt.ls by eclipse.

the class CodeActionResolveHandlerTest method testResolveCodeAction_SourceActions.

@Test
public void testResolveCodeAction_SourceActions() throws Exception {
    when(preferenceManager.getClientPreferences().isResolveCodeActionSupported()).thenReturn(true);
    StringBuilder buf = new StringBuilder();
    buf.append("public class E {\n");
    buf.append("    private void hello() {\n");
    buf.append("    }\n");
    buf.append("}\n");
    ICompilationUnit unit = defaultPackage.createCompilationUnit("E.java", buf.toString(), false, null);
    CodeActionParams params = new CodeActionParams();
    params.setTextDocument(new TextDocumentIdentifier(JDTUtils.toURI(unit)));
    final Range range = CodeActionUtil.getRange(unit, "hello");
    params.setRange(range);
    CodeActionContext context = new CodeActionContext(Collections.emptyList(), Collections.singletonList(CodeActionKind.Source));
    params.setContext(context);
    List<Either<Command, CodeAction>> codeActions = server.codeAction(params).join();
    Assert.assertNotNull(codeActions);
    Assert.assertFalse("No source actions were found", codeActions.isEmpty());
    for (Either<Command, CodeAction> codeAction : codeActions) {
        Assert.assertNull("Should defer the edit property to the resolveCodeAction request", codeAction.getRight().getEdit());
    }
    Optional<Either<Command, CodeAction>> generateConstructorResponse = codeActions.stream().filter(codeAction -> {
        return "Generate Constructors".equals(codeAction.getRight().getTitle());
    }).findFirst();
    Assert.assertTrue("Should return the quick assist 'Convert to lambda expression'", generateConstructorResponse.isPresent());
    CodeAction unresolvedCodeAction = generateConstructorResponse.get().getRight();
    Assert.assertNotNull("Should preserve the data property for the unresolved code action", unresolvedCodeAction.getData());
    CodeAction resolvedCodeAction = server.resolveCodeAction(unresolvedCodeAction).join();
    Assert.assertNotNull("Should resolve the edit property in the resolveCodeAction request", resolvedCodeAction.getEdit());
    String actual = AbstractQuickFixTest.evaluateWorkspaceEdit(resolvedCodeAction.getEdit());
    buf = new StringBuilder();
    buf.append("public class E {\n");
    buf.append("    private void hello() {\n");
    buf.append("    }\n");
    buf.append("\n");
    buf.append("    /**\n");
    buf.append("     * \n");
    buf.append("     */\n");
    buf.append("    public E() {\n");
    buf.append("    }\n");
    buf.append("}\n");
    Assert.assertEquals(buf.toString(), actual);
}
Also used : CodeActionParams(org.eclipse.lsp4j.CodeActionParams) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) Arrays(java.util.Arrays) Mock(org.mockito.Mock) JavaCodeActionKind(org.eclipse.jdt.ls.core.internal.JavaCodeActionKind) RunWith(org.junit.runner.RunWith) Diagnostic(org.eclipse.lsp4j.Diagnostic) Range(org.eclipse.lsp4j.Range) TextDocumentIdentifier(org.eclipse.lsp4j.TextDocumentIdentifier) CodeActionContext(org.eclipse.lsp4j.CodeActionContext) IPackageFragment(org.eclipse.jdt.core.IPackageFragment) CodeActionParams(org.eclipse.lsp4j.CodeActionParams) IProject(org.eclipse.core.resources.IProject) Either(org.eclipse.lsp4j.jsonrpc.messages.Either) Position(org.eclipse.lsp4j.Position) LanguageServerWorkingCopyOwner(org.eclipse.jdt.ls.core.internal.LanguageServerWorkingCopyOwner) JavaClientConnection(org.eclipse.jdt.ls.core.internal.JavaClientConnection) IPackageFragmentRoot(org.eclipse.jdt.core.IPackageFragmentRoot) Before(org.junit.Before) CodeAction(org.eclipse.lsp4j.CodeAction) JDTUtils(org.eclipse.jdt.ls.core.internal.JDTUtils) DiagnosticSeverity(org.eclipse.lsp4j.DiagnosticSeverity) IJavaProject(org.eclipse.jdt.core.IJavaProject) WorkspaceHelper(org.eclipse.jdt.ls.core.internal.WorkspaceHelper) Assert.assertNotNull(org.junit.Assert.assertNotNull) JavaCore(org.eclipse.jdt.core.JavaCore) JavaLanguageServerPlugin(org.eclipse.jdt.ls.core.internal.JavaLanguageServerPlugin) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) Mockito.when(org.mockito.Mockito.when) IType(org.eclipse.jdt.core.IType) List(java.util.List) MockitoJUnitRunner(org.mockito.runners.MockitoJUnitRunner) Command(org.eclipse.lsp4j.Command) CodeActionUtil(org.eclipse.jdt.ls.core.internal.CodeActionUtil) Assert.assertFalse(org.junit.Assert.assertFalse) CodeActionKind(org.eclipse.lsp4j.CodeActionKind) Optional(java.util.Optional) TestOptions(org.eclipse.jdt.ls.core.internal.correction.TestOptions) IProblem(org.eclipse.jdt.core.compiler.IProblem) Assert(org.junit.Assert) Collections(java.util.Collections) Assert.assertEquals(org.junit.Assert.assertEquals) AbstractQuickFixTest(org.eclipse.jdt.ls.core.internal.correction.AbstractQuickFixTest) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) TextDocumentIdentifier(org.eclipse.lsp4j.TextDocumentIdentifier) CodeAction(org.eclipse.lsp4j.CodeAction) Range(org.eclipse.lsp4j.Range) CodeActionContext(org.eclipse.lsp4j.CodeActionContext) Command(org.eclipse.lsp4j.Command) Either(org.eclipse.lsp4j.jsonrpc.messages.Either) Test(org.junit.Test) AbstractQuickFixTest(org.eclipse.jdt.ls.core.internal.correction.AbstractQuickFixTest)

Example 18 with Assert.assertNotNull

use of org.junit.Assert.assertNotNull in project eclipse.jdt.ls by eclipse.

the class CodeActionHandlerTest method testCodeAction_allKindsOfActions.

@Test
public void testCodeAction_allKindsOfActions() throws Exception {
    ICompilationUnit unit = getWorkingCopy("src/java/Foo.java", "public class Foo {\n" + "	void foo() {\n" + "		String bar = \"astring\";" + "	}\n" + "}\n");
    CodeActionParams params = new CodeActionParams();
    params.setTextDocument(new TextDocumentIdentifier(JDTUtils.toURI(unit)));
    final Range range = CodeActionUtil.getRange(unit, "bar");
    params.setRange(range);
    CodeActionContext context = new CodeActionContext(Arrays.asList(getDiagnostic(Integer.toString(IProblem.LocalVariableIsNeverUsed), range)));
    params.setContext(context);
    List<Either<Command, CodeAction>> codeActions = getCodeActions(params);
    Assert.assertNotNull(codeActions);
    Assert.assertFalse("No code actions were found", codeActions.isEmpty());
    boolean hasQuickFix = codeActions.stream().anyMatch(codeAction -> codeAction.getRight().getKind().startsWith(CodeActionKind.QuickFix));
    assertTrue("No quickfix actions were found", hasQuickFix);
    boolean hasRefactor = codeActions.stream().anyMatch(codeAction -> codeAction.getRight().getKind().startsWith(CodeActionKind.Refactor));
    assertTrue("No refactor actions were found", hasRefactor);
    boolean hasSource = codeActions.stream().anyMatch(codeAction -> codeAction.getRight().getKind().startsWith(CodeActionKind.Source));
    assertTrue("No source actions were found", hasSource);
    List<String> baseKinds = codeActions.stream().map(codeAction -> getBaseKind(codeAction.getRight().getKind())).collect(Collectors.toList());
    assertTrue("quickfix actions should be ahead of refactor actions", baseKinds.lastIndexOf(CodeActionKind.QuickFix) < baseKinds.indexOf(CodeActionKind.Refactor));
    assertTrue("refactor actions should be ahead of source actions", baseKinds.lastIndexOf(CodeActionKind.Refactor) < baseKinds.indexOf(CodeActionKind.Source));
}
Also used : CodeActionParams(org.eclipse.lsp4j.CodeActionParams) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) AbstractSourceTestCase(org.eclipse.jdt.ls.core.internal.codemanipulation.AbstractSourceTestCase) Arrays(java.util.Arrays) ProjectUtils(org.eclipse.jdt.ls.core.internal.ProjectUtils) TextDocumentIdentifier(org.eclipse.lsp4j.TextDocumentIdentifier) DefaultCodeFormatterConstants(org.eclipse.jdt.core.formatter.DefaultCodeFormatterConstants) IPackageFragment(org.eclipse.jdt.core.IPackageFragment) ClientPreferences(org.eclipse.jdt.ls.core.internal.preferences.ClientPreferences) Map(java.util.Map) Either(org.eclipse.lsp4j.jsonrpc.messages.Either) URI(java.net.URI) CodeAction(org.eclipse.lsp4j.CodeAction) JDTUtils(org.eclipse.jdt.ls.core.internal.JDTUtils) DiagnosticSeverity(org.eclipse.lsp4j.DiagnosticSeverity) IJavaProject(org.eclipse.jdt.core.IJavaProject) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) List(java.util.List) Command(org.eclipse.lsp4j.Command) CodeActionUtil(org.eclipse.jdt.ls.core.internal.CodeActionUtil) Optional(java.util.Optional) IProblem(org.eclipse.jdt.core.compiler.IProblem) AbstractQuickFixTest(org.eclipse.jdt.ls.core.internal.correction.AbstractQuickFixTest) JavaModelException(org.eclipse.jdt.core.JavaModelException) Mock(org.mockito.Mock) JavaCodeActionKind(org.eclipse.jdt.ls.core.internal.JavaCodeActionKind) RunWith(org.junit.runner.RunWith) CorrectionMessages(org.eclipse.jdt.ls.core.internal.corrections.CorrectionMessages) Diagnostic(org.eclipse.lsp4j.Diagnostic) Range(org.eclipse.lsp4j.Range) CodeActionContext(org.eclipse.lsp4j.CodeActionContext) ArrayList(java.util.ArrayList) CodeActionParams(org.eclipse.lsp4j.CodeActionParams) Position(org.eclipse.lsp4j.Position) LanguageServerWorkingCopyOwner(org.eclipse.jdt.ls.core.internal.LanguageServerWorkingCopyOwner) JavaClientConnection(org.eclipse.jdt.ls.core.internal.JavaClientConnection) IPackageFragmentRoot(org.eclipse.jdt.core.IPackageFragmentRoot) Before(org.junit.Before) WorkspaceHelper(org.eclipse.jdt.ls.core.internal.WorkspaceHelper) Assert.assertNotNull(org.junit.Assert.assertNotNull) JavaCore(org.eclipse.jdt.core.JavaCore) JavaLanguageServerPlugin(org.eclipse.jdt.ls.core.internal.JavaLanguageServerPlugin) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) Mockito.when(org.mockito.Mockito.when) PreferenceManager(org.eclipse.jdt.ls.core.internal.preferences.PreferenceManager) Mockito(org.mockito.Mockito) MockitoJUnitRunner(org.mockito.runners.MockitoJUnitRunner) WorkspaceEdit(org.eclipse.lsp4j.WorkspaceEdit) Ignore(org.junit.Ignore) NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) CodeActionKind(org.eclipse.lsp4j.CodeActionKind) Assert(org.junit.Assert) Collections(java.util.Collections) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) TextDocumentIdentifier(org.eclipse.lsp4j.TextDocumentIdentifier) CodeActionContext(org.eclipse.lsp4j.CodeActionContext) Either(org.eclipse.lsp4j.jsonrpc.messages.Either) Range(org.eclipse.lsp4j.Range) AbstractQuickFixTest(org.eclipse.jdt.ls.core.internal.correction.AbstractQuickFixTest) Test(org.junit.Test)

Example 19 with Assert.assertNotNull

use of org.junit.Assert.assertNotNull in project eclipse.jdt.ls by eclipse.

the class CodeActionHandlerTest method testCodeAction_customFileFormattingOptions.

@Test
public void testCodeAction_customFileFormattingOptions() throws Exception {
    when(clientPreferences.isWorkspaceConfigurationSupported()).thenReturn(true);
    when(connection.configuration(Mockito.any())).thenReturn(Arrays.asList(4, true));
    server.setClientConnection(connection);
    JavaLanguageServerPlugin.getInstance().setProtocol(server);
    IJavaProject javaProject = ProjectUtils.getJavaProject(project);
    Map<String, String> projectOptions = javaProject.getOptions(false);
    // Indent using Tabs
    projectOptions.put(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR, JavaCore.TAB);
    projectOptions.put(DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE, "4");
    javaProject.setOptions(projectOptions);
    IPackageFragmentRoot sourceFolder = javaProject.getPackageFragmentRoot(project.getFolder("src"));
    IPackageFragment pack1 = sourceFolder.createPackageFragment("test1", false, null);
    StringBuilder builder = new StringBuilder();
    builder.append("package test1;\n");
    builder.append("interface I {\n");
    builder.append("	void method();\n");
    builder.append("}\n");
    builder.append("public class E {\n");
    builder.append("	void bar(I i) {\n");
    builder.append("	}\n");
    builder.append("	void foo() {\n");
    builder.append("		bar(() /*[*//*]*/-> {\n");
    builder.append("		});\n");
    builder.append("	}\n");
    builder.append("}\n");
    ICompilationUnit cu = pack1.createCompilationUnit("E.java", builder.toString(), false, null);
    CodeActionParams params = new CodeActionParams();
    params.setTextDocument(new TextDocumentIdentifier(JDTUtils.toURI(cu)));
    final Range range = CodeActionUtil.getRange(cu, "/*[*//*]*/");
    params.setRange(range);
    params.setContext(new CodeActionContext(Collections.emptyList(), Arrays.asList(CodeActionKind.Refactor)));
    List<Either<Command, CodeAction>> codeActions = getCodeActions(params);
    Assert.assertNotNull(codeActions);
    Optional<Either<Command, CodeAction>> found = codeActions.stream().filter((codeAction) -> {
        return codeAction.isRight() && Objects.equals("Convert to anonymous class creation", codeAction.getRight().getTitle());
    }).findAny();
    Assert.assertTrue(found.isPresent());
    Either<Command, CodeAction> codeAction = found.get();
    Command c = codeAction.isLeft() ? codeAction.getLeft() : codeAction.getRight().getCommand();
    Assert.assertEquals(CodeActionHandler.COMMAND_ID_APPLY_EDIT, c.getCommand());
    Assert.assertNotNull(c.getArguments());
    Assert.assertTrue(c.getArguments().get(0) instanceof WorkspaceEdit);
    WorkspaceEdit edit = (WorkspaceEdit) c.getArguments().get(0);
    String actual = AbstractQuickFixTest.evaluateWorkspaceEdit(edit);
    builder = new StringBuilder();
    builder.append("package test1;\n");
    builder.append("interface I {\n");
    builder.append("	void method();\n");
    builder.append("}\n");
    builder.append("public class E {\n");
    builder.append("	void bar(I i) {\n");
    builder.append("	}\n");
    builder.append("	void foo() {\n");
    builder.append("		bar(new I() {\n");
    builder.append("            @Override\n");
    builder.append("            public void method() {\n");
    builder.append("            }\n");
    builder.append("        });\n");
    builder.append("	}\n");
    builder.append("}\n");
    AbstractSourceTestCase.compareSource(builder.toString(), actual);
}
Also used : CodeActionParams(org.eclipse.lsp4j.CodeActionParams) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) AbstractSourceTestCase(org.eclipse.jdt.ls.core.internal.codemanipulation.AbstractSourceTestCase) Arrays(java.util.Arrays) ProjectUtils(org.eclipse.jdt.ls.core.internal.ProjectUtils) TextDocumentIdentifier(org.eclipse.lsp4j.TextDocumentIdentifier) DefaultCodeFormatterConstants(org.eclipse.jdt.core.formatter.DefaultCodeFormatterConstants) IPackageFragment(org.eclipse.jdt.core.IPackageFragment) ClientPreferences(org.eclipse.jdt.ls.core.internal.preferences.ClientPreferences) Map(java.util.Map) Either(org.eclipse.lsp4j.jsonrpc.messages.Either) URI(java.net.URI) CodeAction(org.eclipse.lsp4j.CodeAction) JDTUtils(org.eclipse.jdt.ls.core.internal.JDTUtils) DiagnosticSeverity(org.eclipse.lsp4j.DiagnosticSeverity) IJavaProject(org.eclipse.jdt.core.IJavaProject) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) List(java.util.List) Command(org.eclipse.lsp4j.Command) CodeActionUtil(org.eclipse.jdt.ls.core.internal.CodeActionUtil) Optional(java.util.Optional) IProblem(org.eclipse.jdt.core.compiler.IProblem) AbstractQuickFixTest(org.eclipse.jdt.ls.core.internal.correction.AbstractQuickFixTest) JavaModelException(org.eclipse.jdt.core.JavaModelException) Mock(org.mockito.Mock) JavaCodeActionKind(org.eclipse.jdt.ls.core.internal.JavaCodeActionKind) RunWith(org.junit.runner.RunWith) CorrectionMessages(org.eclipse.jdt.ls.core.internal.corrections.CorrectionMessages) Diagnostic(org.eclipse.lsp4j.Diagnostic) Range(org.eclipse.lsp4j.Range) CodeActionContext(org.eclipse.lsp4j.CodeActionContext) ArrayList(java.util.ArrayList) CodeActionParams(org.eclipse.lsp4j.CodeActionParams) Position(org.eclipse.lsp4j.Position) LanguageServerWorkingCopyOwner(org.eclipse.jdt.ls.core.internal.LanguageServerWorkingCopyOwner) JavaClientConnection(org.eclipse.jdt.ls.core.internal.JavaClientConnection) IPackageFragmentRoot(org.eclipse.jdt.core.IPackageFragmentRoot) Before(org.junit.Before) WorkspaceHelper(org.eclipse.jdt.ls.core.internal.WorkspaceHelper) Assert.assertNotNull(org.junit.Assert.assertNotNull) JavaCore(org.eclipse.jdt.core.JavaCore) JavaLanguageServerPlugin(org.eclipse.jdt.ls.core.internal.JavaLanguageServerPlugin) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) Mockito.when(org.mockito.Mockito.when) PreferenceManager(org.eclipse.jdt.ls.core.internal.preferences.PreferenceManager) Mockito(org.mockito.Mockito) MockitoJUnitRunner(org.mockito.runners.MockitoJUnitRunner) WorkspaceEdit(org.eclipse.lsp4j.WorkspaceEdit) Ignore(org.junit.Ignore) NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) CodeActionKind(org.eclipse.lsp4j.CodeActionKind) Assert(org.junit.Assert) Collections(java.util.Collections) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) IPackageFragment(org.eclipse.jdt.core.IPackageFragment) TextDocumentIdentifier(org.eclipse.lsp4j.TextDocumentIdentifier) CodeAction(org.eclipse.lsp4j.CodeAction) WorkspaceEdit(org.eclipse.lsp4j.WorkspaceEdit) Range(org.eclipse.lsp4j.Range) IPackageFragmentRoot(org.eclipse.jdt.core.IPackageFragmentRoot) IJavaProject(org.eclipse.jdt.core.IJavaProject) CodeActionContext(org.eclipse.lsp4j.CodeActionContext) Command(org.eclipse.lsp4j.Command) Either(org.eclipse.lsp4j.jsonrpc.messages.Either) AbstractQuickFixTest(org.eclipse.jdt.ls.core.internal.correction.AbstractQuickFixTest) Test(org.junit.Test)

Example 20 with Assert.assertNotNull

use of org.junit.Assert.assertNotNull in project graal by oracle.

the class MultiThreadedLanguageTest method testAccessTruffleContextFromExclusivePolyglotThread.

@Test
public void testAccessTruffleContextFromExclusivePolyglotThread() throws Throwable {
    // don't allow multi-threading in this test as every context
    // is used exclusively by one thread.
    MultiThreadedLanguage.isThreadAccessAllowed = (req) -> {
        return req.singleThreaded;
    };
    final int iterations = 10;
    final int innerIterations = 10;
    AtomicReference<Throwable> lastError = new AtomicReference<>();
    UncaughtExceptionHandler uncaughtHandler = (run, e) -> lastError.set(e);
    Context polyglotContext = Context.newBuilder().allowCreateThread(true).build();
    ConcurrentHashMap<LanguageContext, String> seenContexts = new ConcurrentHashMap<>();
    eval(polyglotContext, new Function<Env, Object>() {

        @SuppressWarnings("hiding")
        public Object apply(Env env) {
            List<Thread> threads = new ArrayList<>();
            List<TruffleContext> contexts = new ArrayList<>();
            for (int i = 0; i < iterations; i++) {
                TruffleContext context = env.newContextBuilder().build();
                Thread thread = env.createThread(() -> {
                    assertUniqueContext();
                    List<Thread> innerThreads = new ArrayList<>();
                    List<TruffleContext> innerContexts = new ArrayList<>();
                    for (int j = 0; j < innerIterations; j++) {
                        TruffleContext innerContext = env.newContextBuilder().build();
                        Thread innerThread = env.createThread(() -> {
                            assertUniqueContext();
                        }, innerContext);
                        innerThread.setUncaughtExceptionHandler(uncaughtHandler);
                        innerThread.start();
                        innerThreads.add(innerThread);
                        innerContexts.add(innerContext);
                    }
                    for (Thread innerThread : innerThreads) {
                        try {
                            innerThread.join();
                        } catch (InterruptedException e) {
                        }
                    }
                    for (TruffleContext innerContext : innerContexts) {
                        innerContext.close();
                    }
                }, context);
                thread.setUncaughtExceptionHandler(uncaughtHandler);
                thread.start();
                threads.add(thread);
                contexts.add(context);
            }
            for (Thread thread : threads) {
                try {
                    thread.join();
                } catch (InterruptedException e) {
                }
            }
            for (TruffleContext context : contexts) {
                context.close();
            }
            return null;
        }

        private LanguageContext assertUniqueContext() {
            LanguageContext languageContext = MultiThreadedLanguage.getContext();
            Assert.assertNotNull(languageContext);
            Assert.assertFalse(seenContexts.containsKey(languageContext));
            seenContexts.put(languageContext, "");
            return languageContext;
        }
    });
    Assert.assertEquals(221, initializeCount.get());
    Assert.assertEquals(initializeCount.get() - 1, disposeCount.get());
    Assert.assertEquals(0, initializeMultiThreadingCount.get());
    // Test that the same context is available in threads when created with Env.getContext()
    MultiThreadedLanguage.isThreadAccessAllowed = (req) -> {
        return true;
    };
    eval(polyglotContext, new Function<Env, Object>() {

        @SuppressWarnings("hiding")
        public Object apply(Env env) {
            List<Thread> threads = new ArrayList<>();
            LanguageContext languageContext = MultiThreadedLanguage.getContext();
            for (int i = 0; i < iterations; i++) {
                Thread thread = env.createThread(() -> {
                    LanguageContext threadContext = MultiThreadedLanguage.getContext();
                    assertSame(languageContext, threadContext);
                    List<Thread> innerThreads = new ArrayList<>();
                    List<TruffleContext> innerContexts = new ArrayList<>();
                    for (int j = 0; j < innerIterations; j++) {
                        Thread innerThread = env.createThread(() -> {
                            LanguageContext innerThreadContext = MultiThreadedLanguage.getContext();
                            assertSame(languageContext, innerThreadContext);
                        }, env.getContext());
                        innerThread.setUncaughtExceptionHandler(uncaughtHandler);
                        innerThread.start();
                        innerThreads.add(innerThread);
                    }
                    for (Thread innerThread : innerThreads) {
                        try {
                            innerThread.join();
                        } catch (InterruptedException e) {
                        }
                    }
                    for (TruffleContext innerContext : innerContexts) {
                        innerContext.close();
                    }
                }, env.getContext());
                thread.setUncaughtExceptionHandler(uncaughtHandler);
                thread.start();
                threads.add(thread);
            }
            for (Thread thread : threads) {
                try {
                    thread.join();
                } catch (InterruptedException e) {
                }
            }
            return null;
        }
    });
    if (lastError.get() != null) {
        throw lastError.get();
    }
    polyglotContext.close();
    Assert.assertEquals(331, initializeCount.get());
    Assert.assertEquals(initializeCount.get(), disposeCount.get());
    Assert.assertEquals(1, initializeMultiThreadingCount.get());
}
Also used : ThreadRequest(com.oracle.truffle.api.test.polyglot.MultiThreadedLanguage.ThreadRequest) UncaughtExceptionHandler(java.lang.Thread.UncaughtExceptionHandler) PolyglotException(org.graalvm.polyglot.PolyglotException) Env(com.oracle.truffle.api.TruffleLanguage.Env) TimeoutException(java.util.concurrent.TimeoutException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) ArrayList(java.util.ArrayList) Assert.assertSame(org.junit.Assert.assertSame) HashSet(java.util.HashSet) Future(java.util.concurrent.Future) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Map(java.util.Map) After(org.junit.After) Assert.fail(org.junit.Assert.fail) ExecutorService(java.util.concurrent.ExecutorService) Before(org.junit.Before) Assert.assertNotNull(org.junit.Assert.assertNotNull) Semaphore(java.util.concurrent.Semaphore) Value(org.graalvm.polyglot.Value) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Assert.assertTrue(org.junit.Assert.assertTrue) Set(java.util.Set) Test(org.junit.Test) Executors(java.util.concurrent.Executors) TruffleContext(com.oracle.truffle.api.TruffleContext) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) Assert.assertNull(org.junit.Assert.assertNull) Engine(org.graalvm.polyglot.Engine) Entry(java.util.Map.Entry) Context(org.graalvm.polyglot.Context) Assert(org.junit.Assert) Collections(java.util.Collections) Assert.assertEquals(org.junit.Assert.assertEquals) LanguageContext(com.oracle.truffle.api.test.polyglot.MultiThreadedLanguage.LanguageContext) TruffleContext(com.oracle.truffle.api.TruffleContext) Context(org.graalvm.polyglot.Context) LanguageContext(com.oracle.truffle.api.test.polyglot.MultiThreadedLanguage.LanguageContext) TruffleContext(com.oracle.truffle.api.TruffleContext) AtomicReference(java.util.concurrent.atomic.AtomicReference) LanguageContext(com.oracle.truffle.api.test.polyglot.MultiThreadedLanguage.LanguageContext) Env(com.oracle.truffle.api.TruffleLanguage.Env) ArrayList(java.util.ArrayList) List(java.util.List) UncaughtExceptionHandler(java.lang.Thread.UncaughtExceptionHandler) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Test(org.junit.Test)

Aggregations

List (java.util.List)38 Assert (org.junit.Assert)38 Assert.assertNotNull (org.junit.Assert.assertNotNull)38 Test (org.junit.Test)38 Assert.assertEquals (org.junit.Assert.assertEquals)36 IdmIdentityDto (eu.bcvsolutions.idm.core.api.dto.IdmIdentityDto)28 Autowired (org.springframework.beans.factory.annotation.Autowired)28 AbstractIntegrationTest (eu.bcvsolutions.idm.test.api.AbstractIntegrationTest)26 IdmRoleDto (eu.bcvsolutions.idm.core.api.dto.IdmRoleDto)25 IdmIdentityContractDto (eu.bcvsolutions.idm.core.api.dto.IdmIdentityContractDto)24 FormService (eu.bcvsolutions.idm.core.eav.api.service.FormService)24 Before (org.junit.Before)24 IdmIdentityRoleDto (eu.bcvsolutions.idm.core.api.dto.IdmIdentityRoleDto)23 IdmFormAttributeDto (eu.bcvsolutions.idm.core.eav.api.dto.IdmFormAttributeDto)23 Assert.assertTrue (org.junit.Assert.assertTrue)23 IdmFormDefinitionDto (eu.bcvsolutions.idm.core.eav.api.dto.IdmFormDefinitionDto)22 LocalDate (java.time.LocalDate)22 Assert.assertNull (org.junit.Assert.assertNull)22 Lists (com.google.common.collect.Lists)21 IdmIdentityRoleService (eu.bcvsolutions.idm.core.api.service.IdmIdentityRoleService)20