diff --git a/org.eclipse.wildwebdeveloper.tests/src/org/eclipse/wildwebdeveloper/tests/TestAngular.java b/org.eclipse.wildwebdeveloper.tests/src/org/eclipse/wildwebdeveloper/tests/TestAngular.java index a8f5da8c89..718ad4fd1f 100644 --- a/org.eclipse.wildwebdeveloper.tests/src/org/eclipse/wildwebdeveloper/tests/TestAngular.java +++ b/org.eclipse.wildwebdeveloper.tests/src/org/eclipse/wildwebdeveloper/tests/TestAngular.java @@ -84,22 +84,18 @@ void testAngularTs() throws Exception { .openEditor(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(), appComponentFile); DisplayHelper.sleep(4000); // Give time for LS to initialize enough before making edit and sending a // didChange - assertTrue(new DisplayHelper() { - @Override - protected boolean condition() { - try { - return Arrays - .stream(appComponentFile.findMarkers("org.eclipse.lsp4e.diagnostic", true, - IResource.DEPTH_ZERO)) - .anyMatch(marker -> marker.getAttribute(IMarker.LINE_NUMBER, -1) == 5 - && marker.getAttribute(IMarker.MESSAGE, "").contains("not exist")); - } catch (CoreException e) { - e.printStackTrace(); - return false; - } + assertTrue(DisplayHelper.waitForCondition(editor.getSite().getShell().getDisplay(), 30000, () -> { + try { + return Arrays + .stream(appComponentFile.findMarkers("org.eclipse.lsp4e.diagnostic", true, + IResource.DEPTH_ZERO)) + .anyMatch(marker -> marker.getAttribute(IMarker.LINE_NUMBER, -1) == 5 + && marker.getAttribute(IMarker.MESSAGE, "").contains("not exist")); + } catch (CoreException e) { + e.printStackTrace(); + return false; } - }.waitForCondition(editor.getSite().getShell().getDisplay(), 30000), - "Diagnostic not published in standalone component file"); + }), "Diagnostic not published in standalone component file"); editor.close(false); } @@ -118,21 +114,17 @@ void testAngularHtml() throws Exception { // then make an edit IDocument document = editor.getDocumentProvider().getDocument(editor.getEditorInput()); document.set(document.get() + "\n"); - assertTrue(new DisplayHelper() { - @Override - protected boolean condition() { - IMarker[] markers; - try { - markers = appComponentHTML.findMarkers("org.eclipse.lsp4e.diagnostic", true, IResource.DEPTH_ZERO); - return Arrays.stream(markers) - .anyMatch(marker -> marker.getAttribute(IMarker.MESSAGE, "").contains("not exist")); - } catch (CoreException e) { - e.printStackTrace(); - return false; - } + assertTrue(DisplayHelper.waitForCondition(editor.getSite().getShell().getDisplay(), 30000, () -> { + IMarker[] markers; + try { + markers = appComponentHTML.findMarkers("org.eclipse.lsp4e.diagnostic", true, IResource.DEPTH_ZERO); + return Arrays.stream(markers) + .anyMatch(marker -> marker.getAttribute(IMarker.MESSAGE, "").contains("not exist")); + } catch (CoreException e) { + e.printStackTrace(); + return false; } - }.waitForCondition(editor.getSite().getShell().getDisplay(), 30000), - "No error found on erroneous HTML component file"); + }), "No error found on erroneous HTML component file"); // test completion LSContentAssistProcessor contentAssistProcessor = new LSContentAssistProcessor(); ICompletionProposal[] proposals = contentAssistProcessor.computeCompletionProposals(Utils.getViewer(editor), diff --git a/org.eclipse.wildwebdeveloper.tests/src/org/eclipse/wildwebdeveloper/tests/TestDebug.java b/org.eclipse.wildwebdeveloper.tests/src/org/eclipse/wildwebdeveloper/tests/TestDebug.java index a0677267d8..3cb38337c2 100644 --- a/org.eclipse.wildwebdeveloper.tests/src/org/eclipse/wildwebdeveloper/tests/TestDebug.java +++ b/org.eclipse.wildwebdeveloper.tests/src/org/eclipse/wildwebdeveloper/tests/TestDebug.java @@ -65,244 +65,222 @@ @ExtendWith(AllCleanRule.class) public class TestDebug { - protected ILaunchManager launchManager; + protected ILaunchManager launchManager; - @BeforeEach - public void setUpLaunch() throws DebugException { - this.launchManager = DebugPlugin.getDefault().getLaunchManager(); - removeAllLaunches(); - ScopedPreferenceStore prefs = new ScopedPreferenceStore(InstanceScope.INSTANCE, "org.eclipse.debug.ui"); - prefs.setValue("org.eclipse.debug.ui.switch_perspective_on_suspend", MessageDialogWithToggle.ALWAYS); - } + @BeforeEach + public void setUpLaunch() throws DebugException { + this.launchManager = DebugPlugin.getDefault().getLaunchManager(); + removeAllLaunches(); + ScopedPreferenceStore prefs = new ScopedPreferenceStore(InstanceScope.INSTANCE, "org.eclipse.debug.ui"); + prefs.setValue("org.eclipse.debug.ui.switch_perspective_on_suspend", MessageDialogWithToggle.ALWAYS); + } - private void removeAllLaunches() throws DebugException { - for (ILaunch launch : this.launchManager.getLaunches()) { - try { - launch.terminate(); - } catch (DebugException e) { - e.printStackTrace(); - } - for (IDebugTarget debugTarget : launch.getDebugTargets()) { - try { - debugTarget.terminate(); - } catch (DebugException e) { - e.printStackTrace(); - } - launch.removeDebugTarget(debugTarget); - } - for (IProcess process : launch.getProcesses()) { - process.terminate(); - } - // workaround that some debugger process don't terminate as expected - // LSP4E fixes it in later versions: https://github.com/eclipse/lsp4e/pull/122 - ProcessHandle.current().descendants() - .filter(process -> process.info().commandLine() - .filter(command -> command.contains("node") && command.contains("debug")).isPresent()) - .forEach(ProcessHandle::destroyForcibly); - launchManager.removeLaunch(launch); - } - } + private void removeAllLaunches() throws DebugException { + for (ILaunch launch : this.launchManager.getLaunches()) { + try { + launch.terminate(); + } catch (DebugException e) { + e.printStackTrace(); + } + for (IDebugTarget debugTarget : launch.getDebugTargets()) { + try { + debugTarget.terminate(); + } catch (DebugException e) { + e.printStackTrace(); + } + launch.removeDebugTarget(debugTarget); + } + for (IProcess process : launch.getProcesses()) { + process.terminate(); + } + // workaround that some debugger process don't terminate as expected + // LSP4E fixes it in later versions: https://github.com/eclipse/lsp4e/pull/122 + ProcessHandle.current().descendants() + .filter(process -> process.info().commandLine() + .filter(command -> command.contains("node") && command.contains("debug")).isPresent()) + .forEach(ProcessHandle::destroyForcibly); + launchManager.removeLaunch(launch); + } + } - @AfterEach - public void tearDownLaunch() throws DebugException { - removeAllLaunches(); - } + @AfterEach + public void tearDownLaunch() throws DebugException { + removeAllLaunches(); + } - @Test - public void testRunExpandEnv() throws Exception { - File f = File.createTempFile("testEnv", ".js"); - f.deleteOnExit(); - Files.write(f.toPath(), "console.log(process.env.ECLIPSE_HOME);".getBytes()); - ILaunchConfigurationWorkingCopy launchConfig = launchManager - .getLaunchConfigurationType(NodeRunDAPDebugDelegate.ID) - .newInstance(ResourcesPlugin.getWorkspace().getRoot(), f.getName()); - launchConfig.setAttribute(LaunchConstants.PROGRAM, f.getAbsolutePath()); - launchConfig.setAttribute(LaunchManager.ATTR_ENVIRONMENT_VARIABLES, Map.of("ECLIPSE_HOME", "${eclipse_home}")); - launchConfig.setAttribute(DebugPlugin.ATTR_CAPTURE_OUTPUT, true); - ILaunch launch = launchConfig.launch(ILaunchManager.RUN_MODE, new NullProgressMonitor()); - while (!launch.isTerminated()) { - DisplayHelper.sleep(Display.getDefault(), 50); - } - // ensure last UI events are processed and console is visible and populated. - assertFalse( - DisplayHelper.waitForCondition(Display.getDefault(), 1000, - () -> Arrays.stream(ConsolePlugin.getDefault().getConsoleManager().getConsoles()) // - .filter(IOConsole.class::isInstance) // - .map(IOConsole.class::cast) // - .map(IOConsole::getDocument) // - .map(IDocument::get) // - .anyMatch(content -> content.contains("${eclipse_home}"))), - "env variable is not replaced in subprocess"); - } + @Test + public void testRunExpandEnv() throws Exception { + File f = File.createTempFile("testEnv", ".js"); + f.deleteOnExit(); + Files.write(f.toPath(), "console.log(process.env.ECLIPSE_HOME);".getBytes()); + ILaunchConfigurationWorkingCopy launchConfig = launchManager + .getLaunchConfigurationType(NodeRunDAPDebugDelegate.ID) + .newInstance(ResourcesPlugin.getWorkspace().getRoot(), f.getName()); + launchConfig.setAttribute(LaunchConstants.PROGRAM, f.getAbsolutePath()); + launchConfig.setAttribute(LaunchManager.ATTR_ENVIRONMENT_VARIABLES, Map.of("ECLIPSE_HOME", "${eclipse_home}")); + launchConfig.setAttribute(DebugPlugin.ATTR_CAPTURE_OUTPUT, true); + ILaunch launch = launchConfig.launch(ILaunchManager.RUN_MODE, new NullProgressMonitor()); + while (!launch.isTerminated()) { + DisplayHelper.sleep(Display.getDefault(), 50); + } + // ensure last UI events are processed and console is visible and populated. + assertFalse( + DisplayHelper.waitForCondition(Display.getDefault(), 1000, + () -> Arrays.stream(ConsolePlugin.getDefault().getConsoleManager().getConsoles()) // + .filter(IOConsole.class::isInstance) // + .map(IOConsole.class::cast) // + .map(IOConsole::getDocument) // + .map(IDocument::get) // + .anyMatch(content -> content.contains("${eclipse_home}"))), + "env variable is not replaced in subprocess"); + } - @Test - public void testRunExpandDebugVars() throws Exception { - IProject project = Utils.provisionTestProject("helloWorldJS"); - IFile f = project.getFile("hello.js"); - ILaunchConfigurationWorkingCopy launchConfig = launchManager - .getLaunchConfigurationType(NodeRunDAPDebugDelegate.ID) - .newInstance(ResourcesPlugin.getWorkspace().getRoot(), f.getName()); - launchConfig.setAttribute(LaunchConstants.PROGRAM, "${workspace_loc:" + f.getFullPath() + '}'); - launchConfig.setAttribute(DebugPlugin.ATTR_CAPTURE_OUTPUT, true); - ILaunch launch = launchConfig.launch(ILaunchManager.RUN_MODE, new NullProgressMonitor()); - while (!launch.isTerminated()) { - DisplayHelper.sleep(Display.getDefault(), 50); - } - // ensure last UI events are processed and console is visible and populated. - assertTrue(DisplayHelper.waitForCondition(Display.getDefault(), 1000, - () -> Arrays.stream(ConsolePlugin.getDefault().getConsoleManager().getConsoles()) // - .filter(IOConsole.class::isInstance) // - .map(IOConsole.class::cast) // - .map(IOConsole::getDocument) // - .map(IDocument::get) // - .anyMatch(content -> content.contains("Hello"))), - "Missing log output"); - } + @Test + public void testRunExpandDebugVars() throws Exception { + IProject project = Utils.provisionTestProject("helloWorldJS"); + IFile f = project.getFile("hello.js"); + ILaunchConfigurationWorkingCopy launchConfig = launchManager + .getLaunchConfigurationType(NodeRunDAPDebugDelegate.ID) + .newInstance(ResourcesPlugin.getWorkspace().getRoot(), f.getName()); + launchConfig.setAttribute(LaunchConstants.PROGRAM, "${workspace_loc:" + f.getFullPath() + '}'); + launchConfig.setAttribute(DebugPlugin.ATTR_CAPTURE_OUTPUT, true); + ILaunch launch = launchConfig.launch(ILaunchManager.RUN_MODE, new NullProgressMonitor()); + while (!launch.isTerminated()) { + DisplayHelper.sleep(Display.getDefault(), 50); + } + // ensure last UI events are processed and console is visible and populated. + assertTrue(DisplayHelper.waitForCondition(Display.getDefault(), 1000, + () -> Arrays.stream(ConsolePlugin.getDefault().getConsoleManager().getConsoles()) // + .filter(IOConsole.class::isInstance) // + .map(IOConsole.class::cast) // + .map(IOConsole::getDocument) // + .map(IDocument::get) // + .anyMatch(content -> content.contains("Hello"))), + "Missing log output"); + } - @Test - public void testFindThreadsAndHitsBreakpoint() throws Exception { - IProject project = Utils.provisionTestProject("helloWorldJS"); - IFile jsFile = project.getFile("hello.js"); - ITextEditor editor = (ITextEditor) IDE - .openEditor(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(), jsFile); - IDocument doc = editor.getDocumentProvider().getDocument(editor.getEditorInput()); - TextSelection selection = new TextSelection(doc, doc.getLineOffset(1) + 1, 0); - IToggleBreakpointsTarget toggleBreakpointsTarget = DebugUITools.getToggleBreakpointsTargetManager() - .getToggleBreakpointsTarget(editor, selection); - toggleBreakpointsTarget.toggleLineBreakpoints(editor, selection); - Set before = new HashSet<>(Arrays.asList(launchManager.getDebugTargets())); - DisplayHelper.sleep(1000); - new NodeRunDebugLaunchShortcut().launch(editor, ILaunchManager.DEBUG_MODE); - assertTrue(new DisplayHelper() { - @Override - public boolean condition() { - return launchManager.getDebugTargets().length > before.size(); - } - }.waitForCondition(Display.getDefault(), 30000), "New Debug Target not created"); - assertTrue(new DisplayHelper() { - @Override - public boolean condition() { - try { - return debugTargetWithThreads(before) != null; - } catch (DebugException e) { - e.printStackTrace(); - return false; - } - } - }.waitForCondition(Display.getDefault(), 30000), "Debug Target shows no threads"); - IDebugTarget target = debugTargetWithThreads(before); - assertTrue(new DisplayHelper() { - @Override - public boolean condition() { - try { - return Arrays.stream(target.getThreads()).anyMatch(ISuspendResume::isSuspended); - } catch (DebugException e) { - e.printStackTrace(); - return false; - } - } - }.waitForCondition(Display.getDefault(), 3000), "No thread is suspended"); - IThread suspendedThread = Arrays.stream(target.getThreads()).filter(ISuspendResume::isSuspended).findFirst() - .get(); - assertTrue(new DisplayHelper() { - @Override - protected boolean condition() { - try { - return suspendedThread.getStackFrames().length > 0 - && suspendedThread.getStackFrames()[0].getVariables().length > 0; - } catch (Exception ex) { - // ignore - return false; - } - } - }.waitForCondition(Display.getDefault(), 3000), "Suspended Thread doesn't show variables"); - IVariable localVariable = suspendedThread.getStackFrames()[0].getVariables()[0]; - assertEquals("Local", localVariable.getName()); - IVariable nVariable = Arrays.stream(localVariable.getValue().getVariables()).filter(var -> { - try { - return "n".equals(var.getName()); - } catch (DebugException e) { - return false; - } - }).findAny().get(); - assertEquals("1605", nVariable.getValue().getValueString()); - } + @Test + public void testFindThreadsAndHitsBreakpoint() throws Exception { + IProject project = Utils.provisionTestProject("helloWorldJS"); + IFile jsFile = project.getFile("hello.js"); + ITextEditor editor = (ITextEditor) IDE + .openEditor(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(), jsFile); + IDocument doc = editor.getDocumentProvider().getDocument(editor.getEditorInput()); + TextSelection selection = new TextSelection(doc, doc.getLineOffset(1) + 1, 0); + IToggleBreakpointsTarget toggleBreakpointsTarget = DebugUITools.getToggleBreakpointsTargetManager() + .getToggleBreakpointsTarget(editor, selection); + toggleBreakpointsTarget.toggleLineBreakpoints(editor, selection); + Set before = new HashSet<>(Arrays.asList(launchManager.getDebugTargets())); + DisplayHelper.sleep(1000); + new NodeRunDebugLaunchShortcut().launch(editor, ILaunchManager.DEBUG_MODE); + assertTrue(DisplayHelper.waitForCondition(Display.getDefault(), 30000, + () -> launchManager.getDebugTargets().length > before.size()), "New Debug Target not created"); + assertTrue(DisplayHelper.waitForCondition(Display.getDefault(), 30000, () -> { + try { + return debugTargetWithThreads(before) != null; + } catch (DebugException e) { + e.printStackTrace(); + return false; + } + }), "Debug Target shows no threads"); + IDebugTarget target = debugTargetWithThreads(before); + assertTrue(DisplayHelper.waitForCondition(Display.getDefault(), 3000, () -> { + try { + return Arrays.stream(target.getThreads()).anyMatch(ISuspendResume::isSuspended); + } catch (DebugException e) { + e.printStackTrace(); + return false; + } + }), "No thread is suspended"); + IThread suspendedThread = Arrays.stream(target.getThreads()).filter(ISuspendResume::isSuspended).findFirst() + .get(); + assertTrue(DisplayHelper.waitForCondition(Display.getDefault(), 3000, () -> { + try { + return suspendedThread.getStackFrames().length > 0 + && suspendedThread.getStackFrames()[0].getVariables().length > 0; + } catch (Exception ex) { + // ignore + return false; + } + }), "Suspended Thread doesn't show variables"); + IVariable localVariable = suspendedThread.getStackFrames()[0].getVariables()[0]; + assertEquals("Local", localVariable.getName()); + IVariable nVariable = Arrays.stream(localVariable.getValue().getVariables()).filter(var -> { + try { + return "n".equals(var.getName()); + } catch (DebugException e) { + return false; + } + }).findAny().get(); + assertEquals("1605", nVariable.getValue().getValueString()); + } - private IDebugTarget debugTargetWithThreads(Collection toExclude) throws DebugException { - Set current = new HashSet<>(Arrays.asList(launchManager.getDebugTargets())); - current.removeAll(toExclude); - for (IDebugTarget target : current) { - if (target.getThreads().length > 0) { - return target; - } - } - return null; - } + private IDebugTarget debugTargetWithThreads(Collection toExclude) throws DebugException { + Set current = new HashSet<>(Arrays.asList(launchManager.getDebugTargets())); + current.removeAll(toExclude); + for (IDebugTarget target : current) { + if (target.getThreads().length > 0) { + return target; + } + } + return null; + } - @Test - public void testFindThreadsAndHitsBreakpointTypeScript() throws Exception { - IProject project = Utils.provisionTestProject("HelloWorldTS"); - IFile tsFile = project.getFile("index.ts"); - ITextEditor editor = (ITextEditor) IDE - .openEditor(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(), tsFile); - IDocument doc = editor.getDocumentProvider().getDocument(editor.getEditorInput()); - TextSelection selection = new TextSelection(doc, doc.getLineOffset(2) + 1, 0); - IToggleBreakpointsTarget toggleBreakpointsTarget = DebugUITools.getToggleBreakpointsTargetManager() - .getToggleBreakpointsTarget(editor, selection); - toggleBreakpointsTarget.toggleLineBreakpoints(editor, selection); - Set before = new HashSet<>(Arrays.asList(launchManager.getDebugTargets())); - DisplayHelper.sleep(1000); - new NodeRunDebugLaunchShortcut().launch(editor, ILaunchManager.DEBUG_MODE); - assertTrue(new DisplayHelper() { - @Override - public boolean condition() { - try { - return debugTargetWithThreads(before) != null; - } catch (DebugException e) { - e.printStackTrace(); - return false; - } - } - }.waitForCondition(Display.getDefault(), 30000), "Debug Target shows no threads"); - IDebugTarget target = debugTargetWithThreads(before); - assertTrue(new DisplayHelper() { - @Override - public boolean condition() { - try { - return Arrays.stream(target.getThreads()).anyMatch(ISuspendResume::isSuspended); - } catch (DebugException e) { - e.printStackTrace(); - return false; - } - } - }.waitForCondition(Display.getDefault(), 3000), "No thread is suspended"); - IThread suspendedThread = Arrays.stream(target.getThreads()).filter(ISuspendResume::isSuspended).findFirst() - .get(); - assertTrue(new DisplayHelper() { - @Override - protected boolean condition() { - try { - return suspendedThread.getStackFrames().length > 0 - && suspendedThread.getStackFrames()[0].getVariables().length > 0; - } catch (Exception ex) { - // ignore - return false; - } - } - }.waitForCondition(Display.getDefault(), 3000), "Suspended Thread doesn't show variables"); - IVariable closureVar = null; - for (IVariable variable : suspendedThread.getStackFrames()[0].getVariables()) { - if ("Closure".equals(variable.getName())) { - closureVar = variable; - } - } - IVariable userVariable = null; - for (IVariable variable : closureVar.getValue().getVariables()) { - if ("user".equals(variable.getName())) { - userVariable = variable; - } - } - assertEquals("'Eclipse User'", userVariable.getValue().getValueString()); - } + @Test + public void testFindThreadsAndHitsBreakpointTypeScript() throws Exception { + IProject project = Utils.provisionTestProject("HelloWorldTS"); + IFile tsFile = project.getFile("index.ts"); + ITextEditor editor = (ITextEditor) IDE + .openEditor(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(), tsFile); + IDocument doc = editor.getDocumentProvider().getDocument(editor.getEditorInput()); + TextSelection selection = new TextSelection(doc, doc.getLineOffset(2) + 1, 0); + IToggleBreakpointsTarget toggleBreakpointsTarget = DebugUITools.getToggleBreakpointsTargetManager() + .getToggleBreakpointsTarget(editor, selection); + toggleBreakpointsTarget.toggleLineBreakpoints(editor, selection); + Set before = new HashSet<>(Arrays.asList(launchManager.getDebugTargets())); + DisplayHelper.sleep(1000); + new NodeRunDebugLaunchShortcut().launch(editor, ILaunchManager.DEBUG_MODE); + assertTrue(DisplayHelper.waitForCondition(Display.getDefault(), 30000, () -> { + try { + return debugTargetWithThreads(before) != null; + } catch (DebugException e) { + e.printStackTrace(); + return false; + } + }), "Debug Target shows no threads"); + IDebugTarget target = debugTargetWithThreads(before); + assertTrue(DisplayHelper.waitForCondition(Display.getDefault(), 3000, () -> { + try { + return Arrays.stream(target.getThreads()).anyMatch(ISuspendResume::isSuspended); + } catch (DebugException e) { + e.printStackTrace(); + return false; + } + }), "No thread is suspended"); + IThread suspendedThread = Arrays.stream(target.getThreads()).filter(ISuspendResume::isSuspended).findFirst() + .get(); + assertTrue(DisplayHelper.waitForCondition(Display.getDefault(), 3000, () -> { + try { + return suspendedThread.getStackFrames().length > 0 + && suspendedThread.getStackFrames()[0].getVariables().length > 0; + } catch (Exception ex) { + // ignore + return false; + } + }), "Suspended Thread doesn't show variables"); + IVariable closureVar = null; + for (IVariable variable : suspendedThread.getStackFrames()[0].getVariables()) { + if ("Closure".equals(variable.getName())) { + closureVar = variable; + } + } + IVariable userVariable = null; + for (IVariable variable : closureVar.getValue().getVariables()) { + if ("user".equals(variable.getName())) { + userVariable = variable; + } + } + assertEquals("'Eclipse User'", userVariable.getValue().getValueString()); + } } diff --git a/org.eclipse.wildwebdeveloper.tests/src/org/eclipse/wildwebdeveloper/tests/TestESLint.java b/org.eclipse.wildwebdeveloper.tests/src/org/eclipse/wildwebdeveloper/tests/TestESLint.java index ec1c48f0b3..b2c1ffbf78 100644 --- a/org.eclipse.wildwebdeveloper.tests/src/org/eclipse/wildwebdeveloper/tests/TestESLint.java +++ b/org.eclipse.wildwebdeveloper.tests/src/org/eclipse/wildwebdeveloper/tests/TestESLint.java @@ -132,30 +132,24 @@ void testESLintDiagnosticsInTSX() throws Exception { private void assertESLintIndentMarkerExists(IFile file) throws PartInitException { IDE.openEditor(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(), file); - assertTrue(new DisplayHelper() { - @Override - protected boolean condition() { - try { - return file.findMarkers("org.eclipse.lsp4e.diagnostic", true, IResource.DEPTH_ZERO).length != 0; - } catch (CoreException e) { - e.printStackTrace(); - return false; - } + assertTrue(DisplayHelper.waitForCondition(PlatformUI.getWorkbench().getDisplay(), 10000, () -> { + try { + return file.findMarkers("org.eclipse.lsp4e.diagnostic", true, IResource.DEPTH_ZERO).length != 0; + } catch (CoreException e) { + e.printStackTrace(); + return false; } - }.waitForCondition(PlatformUI.getWorkbench().getDisplay(), 10000), "Diagnostic not published"); - - assertTrue(new DisplayHelper() { - @Override - protected boolean condition() { - try { - return Arrays.asList(file.findMarkers("org.eclipse.lsp4e.diagnostic", true, IResource.DEPTH_ZERO)) - .stream().filter(Objects::nonNull) - .anyMatch(m -> m.getAttribute(IMarker.MESSAGE, null).toLowerCase().contains("indentation")); - } catch (CoreException e) { - e.printStackTrace(); - return false; - } + }), "Diagnostic not published"); + + assertTrue(DisplayHelper.waitForCondition(PlatformUI.getWorkbench().getDisplay(), 5000, () -> { + try { + return Arrays.asList(file.findMarkers("org.eclipse.lsp4e.diagnostic", true, IResource.DEPTH_ZERO)) + .stream().filter(Objects::nonNull) + .anyMatch(m -> m.getAttribute(IMarker.MESSAGE, null).toLowerCase().contains("indentation")); + } catch (CoreException e) { + e.printStackTrace(); + return false; } - }.waitForCondition(PlatformUI.getWorkbench().getDisplay(), 5000), "Diagnostic content is incorrect"); + }), "Diagnostic content is incorrect"); } } diff --git a/org.eclipse.wildwebdeveloper.tests/src/org/eclipse/wildwebdeveloper/tests/TestHTML.java b/org.eclipse.wildwebdeveloper.tests/src/org/eclipse/wildwebdeveloper/tests/TestHTML.java index 6898507246..638af28e7f 100644 --- a/org.eclipse.wildwebdeveloper.tests/src/org/eclipse/wildwebdeveloper/tests/TestHTML.java +++ b/org.eclipse.wildwebdeveloper.tests/src/org/eclipse/wildwebdeveloper/tests/TestHTML.java @@ -35,96 +35,81 @@ @ExtendWith(AllCleanRule.class) public class TestHTML { - @Test - public void testHTMLFile() throws Exception { - final IProject project = ResourcesPlugin.getWorkspace().getRoot() - .getProject("testHTMLFile" + System.currentTimeMillis()); - project.create(null); - project.open(null); - final IFile file = project.getFile("blah.html"); - file.create(new ByteArrayInputStream("FAIL".getBytes()), true, null); - ITextEditor editor = (ITextEditor) IDE - .openEditor(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(), file); - editor.getDocumentProvider().getDocument(editor.getEditorInput()).set("<"); - assertTrue(new DisplayHelper() { - @Override - protected boolean condition() { - try { - return file.findMarkers("org.eclipse.lsp4e.diagnostic", true, IResource.DEPTH_ZERO).length != 0; - } catch (CoreException e) { - return false; - } - } - }.waitForCondition(PlatformUI.getWorkbench().getDisplay(), 5000), "Diagnostic not published"); - } + @Test + public void testHTMLFile() throws Exception { + final IProject project = ResourcesPlugin.getWorkspace().getRoot() + .getProject("testHTMLFile" + System.currentTimeMillis()); + project.create(null); + project.open(null); + final IFile file = project.getFile("blah.html"); + file.create(new ByteArrayInputStream("FAIL".getBytes()), true, null); + ITextEditor editor = (ITextEditor) IDE + .openEditor(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(), file); + editor.getDocumentProvider().getDocument(editor.getEditorInput()).set("<"); + assertTrue(DisplayHelper.waitForCondition(PlatformUI.getWorkbench().getDisplay(), 5000, () -> { + try { + return file.findMarkers("org.eclipse.lsp4e.diagnostic", true, IResource.DEPTH_ZERO).length != 0; + } catch (CoreException e) { + return false; + } + }), "Diagnostic not published"); + } - @Test - public void testFormat() throws Exception { - final IProject project = ResourcesPlugin.getWorkspace().getRoot() - .getProject("testHTMLFile" + System.currentTimeMillis()); - project.create(null); - project.open(null); - final IFile file = project.getFile("blah.html"); - file.create(new ByteArrayInputStream("".getBytes()), true, null); - ITextEditor editor = (ITextEditor) IDE - .openEditor(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(), file); - editor.setFocus(); - editor.getSelectionProvider().setSelection(new TextSelection(0, 0)); - IHandlerService handlerService = PlatformUI.getWorkbench().getService(IHandlerService.class); + @Test + public void testFormat() throws Exception { + final IProject project = ResourcesPlugin.getWorkspace().getRoot() + .getProject("testHTMLFile" + System.currentTimeMillis()); + project.create(null); + project.open(null); + final IFile file = project.getFile("blah.html"); + file.create(new ByteArrayInputStream("".getBytes()), true, null); + ITextEditor editor = (ITextEditor) IDE + .openEditor(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(), file); + editor.setFocus(); + editor.getSelectionProvider().setSelection(new TextSelection(0, 0)); + IHandlerService handlerService = PlatformUI.getWorkbench().getService(IHandlerService.class); // assertTrue(PlatformUI.getWorkbench().getService(ICommandService.class).getCommand("org.eclipse.lsp4e.format") // .isEnabled()); - new DisplayHelper() { - @Override - protected boolean condition() { - try { - return PlatformUI.getWorkbench().getService(ICommandService.class) - .getCommand("org.eclipse.lsp4e.format").isEnabled(); - } catch (Exception e) { - return false; - } - } - }.waitForCondition(editor.getSite().getShell().getDisplay(), 3000); + DisplayHelper.waitForCondition(editor.getSite().getShell().getDisplay(), 3000, () -> { + try { + return PlatformUI.getWorkbench().getService(ICommandService.class) + .getCommand("org.eclipse.lsp4e.format").isEnabled(); + } catch (Exception e) { + return false; + } + }); // AtomicReference ex = new AtomicReference<>(); - new DisplayHelper() { - @Override - protected boolean condition() { - try { - handlerService.executeCommand("org.eclipse.lsp4e.format", null); - return true; - } catch (Exception e) { - return false; - } - } - }.waitForCondition(editor.getSite().getShell().getDisplay(), 3000); + DisplayHelper.waitForCondition(editor.getSite().getShell().getDisplay(), 3000, () -> { + try { + handlerService.executeCommand("org.eclipse.lsp4e.format", null); + return true; + } catch (Exception e) { + return false; + } + }); // if (ex.get() != null) { // throw ex.get(); // } - new DisplayHelper() { - @Override - protected boolean condition() { - return editor.getDocumentProvider().getDocument(editor.getEditorInput()).getNumberOfLines() > 1; - } - }.waitForCondition(editor.getSite().getShell().getDisplay(), 3000); - } + DisplayHelper.waitForCondition(editor.getSite().getShell().getDisplay(), 3000, + () -> editor.getDocumentProvider().getDocument(editor.getEditorInput()).getNumberOfLines() > 1); + } - @Test - public void autoCloseTags() throws Exception { - final IProject project = ResourcesPlugin.getWorkspace().getRoot() - .getProject("testHTMLFile" + System.currentTimeMillis()); - project.create(null); - project.open(null); - final IFile file = project.getFile("autoCloseTags.html"); - file.create(new ByteArrayInputStream(""); - assertTrue(new DisplayHelper() { - @Override - protected boolean condition() { - return "".equals(document.get()); - } - }.waitForCondition(PlatformUI.getWorkbench().getDisplay(), 5000), "Autoclose not done"); - } + @Test + public void autoCloseTags() throws Exception { + final IProject project = ResourcesPlugin.getWorkspace().getRoot() + .getProject("testHTMLFile" + System.currentTimeMillis()); + project.create(null); + project.open(null); + final IFile file = project.getFile("autoCloseTags.html"); + file.create(new ByteArrayInputStream(""); + assertTrue( + DisplayHelper.waitForCondition(PlatformUI.getWorkbench().getDisplay(), 5000, + () -> "".equals(document.get())), + "Autoclose not done"); + } } diff --git a/org.eclipse.wildwebdeveloper.tests/src/org/eclipse/wildwebdeveloper/tests/TestJSON.java b/org.eclipse.wildwebdeveloper.tests/src/org/eclipse/wildwebdeveloper/tests/TestJSON.java index 539a2d812f..ad1ba7d2fc 100644 --- a/org.eclipse.wildwebdeveloper.tests/src/org/eclipse/wildwebdeveloper/tests/TestJSON.java +++ b/org.eclipse.wildwebdeveloper.tests/src/org/eclipse/wildwebdeveloper/tests/TestJSON.java @@ -34,27 +34,24 @@ @ExtendWith(AllCleanRule.class) public class TestJSON { - @Test - public void testFormatEnabled() throws IOException, PartInitException, CoreException { - File file = File.createTempFile("test", ".json"); - IWorkbenchPage activePage = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); - IEditorPart editor = IDE.openEditorOnFileStore(activePage, EFS.getStore(file.toURI())); - ICommandService service = activePage.getWorkbenchWindow().getService(ICommandService.class); - Command formatCommand = service.getCommand("org.eclipse.lsp4e.format"); - assertNotNull(formatCommand, "Format command not found"); - assertTrue(formatCommand.isDefined(), "Format command not defined"); + @Test + public void testFormatEnabled() throws IOException, PartInitException, CoreException { + File file = File.createTempFile("test", ".json"); + IWorkbenchPage activePage = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); + IEditorPart editor = IDE.openEditorOnFileStore(activePage, EFS.getStore(file.toURI())); + ICommandService service = activePage.getWorkbenchWindow().getService(ICommandService.class); + Command formatCommand = service.getCommand("org.eclipse.lsp4e.format"); + assertNotNull(formatCommand, "Format command not found"); + assertTrue(formatCommand.isDefined(), "Format command not defined"); // assertTrue(formatCommand.isEnabled(), "Format command not enabled"); - new DisplayHelper() { - @Override - protected boolean condition() { - try { - return formatCommand.isEnabled(); - } catch (Exception e) { - return false; - } - } - }.waitForCondition(editor.getSite().getShell().getDisplay(), 3000); - assertTrue(formatCommand.isHandled(), "Format command not handled"); - } + DisplayHelper.waitForCondition(editor.getSite().getShell().getDisplay(), 3000, () -> { + try { + return formatCommand.isEnabled(); + } catch (Exception e) { + return false; + } + }); + assertTrue(formatCommand.isHandled(), "Format command not handled"); + } } diff --git a/org.eclipse.wildwebdeveloper.tests/src/org/eclipse/wildwebdeveloper/tests/TestJsTs.java b/org.eclipse.wildwebdeveloper.tests/src/org/eclipse/wildwebdeveloper/tests/TestJsTs.java index 038a6a4ab8..aa970b9531 100644 --- a/org.eclipse.wildwebdeveloper.tests/src/org/eclipse/wildwebdeveloper/tests/TestJsTs.java +++ b/org.eclipse.wildwebdeveloper.tests/src/org/eclipse/wildwebdeveloper/tests/TestJsTs.java @@ -54,224 +54,216 @@ @ExtendWith(AllCleanRule.class) public class TestJsTs { - private static final String WIZARD_CLASSNAME_TEMPLATE = "org.eclipse.ltk.internal.ui.refactoring.Refactoring"; - private static final String WIZARD_RENAME = "Rename"; - private static final String WIZARD_REFACTORING = "Refactoring"; - private static final String BUTTON_OK = "OK"; - private static final String BUTTON_CANCEL = "Cancel"; - private static final String BUTTON_CONTINUE = "Con&tinue"; - private static final String BUTTON_BACK = "< &Back"; + private static final String WIZARD_CLASSNAME_TEMPLATE = "org.eclipse.ltk.internal.ui.refactoring.Refactoring"; + private static final String WIZARD_RENAME = "Rename"; + private static final String WIZARD_REFACTORING = "Refactoring"; + private static final String BUTTON_OK = "OK"; + private static final String BUTTON_CANCEL = "Cancel"; + private static final String BUTTON_CONTINUE = "Con&tinue"; + private static final String BUTTON_BACK = "< &Back"; - private IProject project; + private IProject project; - @BeforeEach - public void setUpProject() throws CoreException { - this.project = ResourcesPlugin.getWorkspace().getRoot().getProject(getClass().getName() + System.nanoTime()); - project.create(null); - project.open(null); - } + @BeforeEach + public void setUpProject() throws CoreException { + this.project = ResourcesPlugin.getWorkspace().getRoot().getProject(getClass().getName() + System.nanoTime()); + project.create(null); + project.open(null); + } - @Test - @Timeout(value = 60, unit = TimeUnit.SECONDS) - public void testRefactoringRenameInTypeaScript() throws Exception { - final IFile file = project.getFile("TestJsTs.ts"); - String content = "function testVar(test) {\n if (\"truetrue\" == \"true\" + test ) {\n" - + " return true;\n }\n return false;\n}\n" - + "print(\"Testing var with true argument == \" + testVar(true));\n" - + "print(\"Testing var with false argument == \" + testVar(false));\n"; - final String oldName = "testVar"; - final String newName = "newName"; - internalTestRename(file, content, oldName, newName); - } + @Test + @Timeout(value = 60, unit = TimeUnit.SECONDS) + public void testRefactoringRenameInTypeaScript() throws Exception { + final IFile file = project.getFile("TestJsTs.ts"); + String content = "function testVar(test) {\n if (\"truetrue\" == \"true\" + test ) {\n" + + " return true;\n }\n return false;\n}\n" + + "print(\"Testing var with true argument == \" + testVar(true));\n" + + "print(\"Testing var with false argument == \" + testVar(false));\n"; + final String oldName = "testVar"; + final String newName = "newName"; + internalTestRename(file, content, oldName, newName); + } - @Test - @Timeout(value = 60, unit = TimeUnit.SECONDS) - public void testRefactoringRenameInJavaScript() throws Exception { - final IFile file = project.getFile("TestJsTs.js"); - String content = "function testVar(test) {\n if (\"truetrue\" == \"true\" + test ) {\n" - + " return true;\n }\n return false;\n}\n" - + "print(\"Testing var with true argument == \" + testVar(true));\n" - + "print(\"Testing var with false argument == \" + testVar(false));\n"; - final String oldName = "testVar"; - final String newName = "newName"; - internalTestRename(file, content, oldName, newName); - } + @Test + @Timeout(value = 60, unit = TimeUnit.SECONDS) + public void testRefactoringRenameInJavaScript() throws Exception { + final IFile file = project.getFile("TestJsTs.js"); + String content = "function testVar(test) {\n if (\"truetrue\" == \"true\" + test ) {\n" + + " return true;\n }\n return false;\n}\n" + + "print(\"Testing var with true argument == \" + testVar(true));\n" + + "print(\"Testing var with false argument == \" + testVar(false));\n"; + final String oldName = "testVar"; + final String newName = "newName"; + internalTestRename(file, content, oldName, newName); + } - private void internalTestRename(IFile file, String content, String oldName, String newName) throws Exception { - String newContent = content.replaceAll(oldName, newName); + private void internalTestRename(IFile file, String content, String oldName, String newName) throws Exception { + String newContent = content.replaceAll(oldName, newName); - int offset = content.indexOf(oldName); - file.create(new ByteArrayInputStream(content.getBytes()), true, null); - AbstractTextEditor editor = (AbstractTextEditor) IDE.openEditor( - PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(), file, - "org.eclipse.ui.genericeditor.GenericEditor"); - editor.getSelectionProvider().setSelection(new TextSelection(offset, 0)); - editor.setFocus(); - DisplayHelper.sleep(5000); // Give time for LS to initialize enough before making edit and sending a - // didChange + int offset = content.indexOf(oldName); + file.create(new ByteArrayInputStream(content.getBytes()), true, null); + AbstractTextEditor editor = (AbstractTextEditor) IDE.openEditor( + PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(), file, + "org.eclipse.ui.genericeditor.GenericEditor"); + editor.getSelectionProvider().setSelection(new TextSelection(offset, 0)); + editor.setFocus(); + DisplayHelper.sleep(5000); // Give time for LS to initialize enough before making edit and sending a + // didChange - IDocument document = editor.getDocumentProvider().getDocument(editor.getEditorInput()); + IDocument document = editor.getDocumentProvider().getDocument(editor.getEditorInput()); - ICommandService commandService = PlatformUI.getWorkbench().getService(ICommandService.class); - IHandlerService handlerService = PlatformUI.getWorkbench().getService(IHandlerService.class); - Command command = commandService.getCommand(IWorkbenchCommandConstants.FILE_RENAME); - assertTrue(command.isEnabled() && command.isHandled()); - Event e = new Event(); - e.widget = editor.getAdapter(Control.class); - Shell ideShell = editor.getSite().getShell(); - Display display = ideShell.getDisplay(); - e.display = display; - AtomicBoolean renameDialogOkPressed = new AtomicBoolean(); - AtomicBoolean renameDialogContinuePressed = new AtomicBoolean(); - AtomicBoolean renameDialogCancelPressed = new AtomicBoolean(); - AtomicBoolean errorDialogOkPressed = new AtomicBoolean(); - AtomicBoolean newTextIsSet = new AtomicBoolean(); + ICommandService commandService = PlatformUI.getWorkbench().getService(ICommandService.class); + IHandlerService handlerService = PlatformUI.getWorkbench().getService(IHandlerService.class); + Command command = commandService.getCommand(IWorkbenchCommandConstants.FILE_RENAME); + assertTrue(command.isEnabled() && command.isHandled()); + Event e = new Event(); + e.widget = editor.getAdapter(Control.class); + Shell ideShell = editor.getSite().getShell(); + Display display = ideShell.getDisplay(); + e.display = display; + AtomicBoolean renameDialogOkPressed = new AtomicBoolean(); + AtomicBoolean renameDialogContinuePressed = new AtomicBoolean(); + AtomicBoolean renameDialogCancelPressed = new AtomicBoolean(); + AtomicBoolean errorDialogOkPressed = new AtomicBoolean(); + AtomicBoolean newTextIsSet = new AtomicBoolean(); - Listener pressOKonRenameDialogPaint = event -> { - if (event.widget instanceof Composite c) { - Shell shell = c.getShell(); - if (shell != ideShell) { - if (shell.getData().getClass().getName().startsWith(WIZARD_CLASSNAME_TEMPLATE)) { - if (!newTextIsSet.get()) { - newTextIsSet.set(setNewText(c, newName)); - System.out.println("testRefactoringRename(): New name is set: " + newName); - } - Set buttons = getButtons(c); - if (WIZARD_RENAME.equals(shell.getText())) { - if (!renameDialogOkPressed.get()) { - if (buttons.contains(BUTTON_OK)) { - System.out.println( - "testRefactoringRename(): WIZARD_RENAME Emulating pressOK when BUTTON_OK"); - event.widget.getDisplay().asyncExec(() -> pressOk(shell)); - renameDialogOkPressed.set(true); - } - } else if (!renameDialogContinuePressed.get()) { - if (buttons.contains(BUTTON_CONTINUE)) { - System.out.println( - "testRefactoringRename(): WIZARD_RENAME Emulating pressOK when BUTTON_CONTINUE"); - event.widget.getDisplay().asyncExec(() -> pressOk(shell)); - renameDialogContinuePressed.set(true); - } else if (!renameDialogCancelPressed.get() && buttons.contains(BUTTON_CANCEL) - && buttons.contains(BUTTON_BACK)) { - System.out.println( - "testRefactoringRename(): WIZARD_RENAME Emulating pressCancel when BUTTON_CANCEL & BUTTON_BACK"); - event.widget.getDisplay().asyncExec(() -> pressCancel(shell)); - renameDialogCancelPressed.set(true); - } - } - } else if (WIZARD_REFACTORING.equals(shell.getText())) { - if (!errorDialogOkPressed.get()) { - if (buttons.contains(BUTTON_OK)) { - System.out.println( - "testRefactoringRename(): WIZARD_REFACTORING Emulating pressOK when BUTTON_OK"); - event.widget.getDisplay().asyncExec(() -> pressOk(shell)); - errorDialogOkPressed.set(true); - } - } - } - } else if (shell.getData().getClass().getName() - .startsWith("org.eclipse.jface.dialogs.MessageDialog")) { - // Most probably it's "The Rename request is not valid at the given position" - // -like error - Set buttons = getButtons(c); - if (!errorDialogOkPressed.get()) { - if (buttons.contains(BUTTON_OK)) { - System.out.println( - "testRefactoringRename(): MESSAGE_DIALOG Emulating pressOK when BUTTON_OK"); - event.widget.getDisplay().asyncExec(() -> pressOk(shell)); - errorDialogOkPressed.set(true); - } else if (buttons.contains(BUTTON_CANCEL)) { - System.out.println( - "testRefactoringRename(): MESSAGE_DIALOG Emulating pressCancel when BUTTON_CANCEL"); - event.widget.getDisplay().asyncExec(() -> pressCancel(shell)); - errorDialogOkPressed.set(true); // Report as OK pressed just to say the dialog is closed - } - } - } - } - } - }; + Listener pressOKonRenameDialogPaint = event -> { + if (event.widget instanceof Composite c) { + Shell shell = c.getShell(); + if (shell != ideShell) { + if (shell.getData().getClass().getName().startsWith(WIZARD_CLASSNAME_TEMPLATE)) { + if (!newTextIsSet.get()) { + newTextIsSet.set(setNewText(c, newName)); + System.out.println("testRefactoringRename(): New name is set: " + newName); + } + Set buttons = getButtons(c); + if (WIZARD_RENAME.equals(shell.getText())) { + if (!renameDialogOkPressed.get()) { + if (buttons.contains(BUTTON_OK)) { + System.out.println( + "testRefactoringRename(): WIZARD_RENAME Emulating pressOK when BUTTON_OK"); + event.widget.getDisplay().asyncExec(() -> pressOk(shell)); + renameDialogOkPressed.set(true); + } + } else if (!renameDialogContinuePressed.get()) { + if (buttons.contains(BUTTON_CONTINUE)) { + System.out.println( + "testRefactoringRename(): WIZARD_RENAME Emulating pressOK when BUTTON_CONTINUE"); + event.widget.getDisplay().asyncExec(() -> pressOk(shell)); + renameDialogContinuePressed.set(true); + } else if (!renameDialogCancelPressed.get() && buttons.contains(BUTTON_CANCEL) + && buttons.contains(BUTTON_BACK)) { + System.out.println( + "testRefactoringRename(): WIZARD_RENAME Emulating pressCancel when BUTTON_CANCEL & BUTTON_BACK"); + event.widget.getDisplay().asyncExec(() -> pressCancel(shell)); + renameDialogCancelPressed.set(true); + } + } + } else if (WIZARD_REFACTORING.equals(shell.getText())) { + if (!errorDialogOkPressed.get()) { + if (buttons.contains(BUTTON_OK)) { + System.out.println( + "testRefactoringRename(): WIZARD_REFACTORING Emulating pressOK when BUTTON_OK"); + event.widget.getDisplay().asyncExec(() -> pressOk(shell)); + errorDialogOkPressed.set(true); + } + } + } + } else if (shell.getData().getClass().getName() + .startsWith("org.eclipse.jface.dialogs.MessageDialog")) { + // Most probably it's "The Rename request is not valid at the given position" + // -like error + Set buttons = getButtons(c); + if (!errorDialogOkPressed.get()) { + if (buttons.contains(BUTTON_OK)) { + System.out.println( + "testRefactoringRename(): MESSAGE_DIALOG Emulating pressOK when BUTTON_OK"); + event.widget.getDisplay().asyncExec(() -> pressOk(shell)); + errorDialogOkPressed.set(true); + } else if (buttons.contains(BUTTON_CANCEL)) { + System.out.println( + "testRefactoringRename(): MESSAGE_DIALOG Emulating pressCancel when BUTTON_CANCEL"); + event.widget.getDisplay().asyncExec(() -> pressCancel(shell)); + errorDialogOkPressed.set(true); // Report as OK pressed just to say the dialog is closed + } + } + } + } + } + }; - try { - display.addFilter(SWT.Paint, pressOKonRenameDialogPaint); - ExecutionEvent executionEvent = handlerService.createExecutionEvent(command, e); - System.out.println("testRefactoringRename(): Executing command: " + IWorkbenchCommandConstants.FILE_RENAME); - command.executeWithChecks(executionEvent); - assertTrue(new DisplayHelper() { - @Override - protected boolean condition() { - return renameDialogOkPressed.get(); - } - }.waitForCondition(display, 2000), "Rename dialog not shown"); - System.out.println("testRefactoringRename(): Rename dialog is shown"); - assertTrue(new DisplayHelper() { - @Override - protected boolean condition() { - return newContent.equals(document.get()); - } - }.waitForCondition(display, 5000), "document not modified, rename not applied"); - System.out.println("testRefactoringRename(): Executed command: " + IWorkbenchCommandConstants.FILE_RENAME); - } finally { - ideShell.getDisplay().removeFilter(SWT.Paint, pressOKonRenameDialogPaint); - } - } + try { + display.addFilter(SWT.Paint, pressOKonRenameDialogPaint); + ExecutionEvent executionEvent = handlerService.createExecutionEvent(command, e); + System.out.println("testRefactoringRename(): Executing command: " + IWorkbenchCommandConstants.FILE_RENAME); + command.executeWithChecks(executionEvent); + assertTrue(DisplayHelper.waitForCondition(display, 2000, () -> renameDialogOkPressed.get()), + "Rename dialog not shown"); + System.out.println("testRefactoringRename(): Rename dialog is shown"); + assertTrue(DisplayHelper.waitForCondition(display, 5000, () -> newContent.equals(document.get())), + "document not modified, rename not applied"); + System.out.println("testRefactoringRename(): Executed command: " + IWorkbenchCommandConstants.FILE_RENAME); + } finally { + ideShell.getDisplay().removeFilter(SWT.Paint, pressOKonRenameDialogPaint); + } + } - static private Set getButtons(Widget w) { - Set result = new HashSet<>(); - if (w instanceof Button button) { - result.add(button.getText()); - } else if (w instanceof Composite composite) { - for (Control child : composite.getChildren()) { - result.addAll(getButtons(child)); - } - } - return result; - } + static private Set getButtons(Widget w) { + Set result = new HashSet<>(); + if (w instanceof Button button) { + result.add(button.getText()); + } else if (w instanceof Composite composite) { + for (Control child : composite.getChildren()) { + result.addAll(getButtons(child)); + } + } + return result; + } - static private boolean setNewText(Widget w, String newText) { - Set textWidgets = getTextWidgets(w); - if (!textWidgets.isEmpty()) { - textWidgets.forEach(t -> t.setText(newText)); - return true; - } - return false; - } + static private boolean setNewText(Widget w, String newText) { + Set textWidgets = getTextWidgets(w); + if (!textWidgets.isEmpty()) { + textWidgets.forEach(t -> t.setText(newText)); + return true; + } + return false; + } - static private Set getTextWidgets(Widget w) { - Set result = new HashSet<>(); - if (w instanceof Text text) { - result.add(text); - } else if (w instanceof Composite composite) { - for (Control child : composite.getChildren()) { - result.addAll(getTextWidgets(child)); - } - } - return result; - } + static private Set getTextWidgets(Widget w) { + Set result = new HashSet<>(); + if (w instanceof Text text) { + result.add(text); + } else if (w instanceof Composite composite) { + for (Control child : composite.getChildren()) { + result.addAll(getTextWidgets(child)); + } + } + return result; + } - static private void pressOk(Shell dialogShell) { - try { - Dialog dialog = (Dialog) dialogShell.getData(); - Method okPressedMethod = Dialog.class.getDeclaredMethod("okPressed"); - okPressedMethod.setAccessible(true); - okPressedMethod.invoke(dialog); - System.out.println("testRefactoringRename(): pressOK is executed"); - } catch (Exception ex) { - ex.printStackTrace(); - throw new Error(ex); - } - } + static private void pressOk(Shell dialogShell) { + try { + Dialog dialog = (Dialog) dialogShell.getData(); + Method okPressedMethod = Dialog.class.getDeclaredMethod("okPressed"); + okPressedMethod.setAccessible(true); + okPressedMethod.invoke(dialog); + System.out.println("testRefactoringRename(): pressOK is executed"); + } catch (Exception ex) { + ex.printStackTrace(); + throw new Error(ex); + } + } - static private void pressCancel(Shell dialogShell) { - try { - Dialog dialog = (Dialog) dialogShell.getData(); - Method cancelPressedMethod = Dialog.class.getDeclaredMethod("cancelPressed"); - cancelPressedMethod.setAccessible(true); - cancelPressedMethod.invoke(dialog); - System.out.println("testRefactoringRename(): pressCancel is executed"); - } catch (Exception ex) { - ex.printStackTrace(); - throw new Error(ex); - } - } + static private void pressCancel(Shell dialogShell) { + try { + Dialog dialog = (Dialog) dialogShell.getData(); + Method cancelPressedMethod = Dialog.class.getDeclaredMethod("cancelPressed"); + cancelPressedMethod.setAccessible(true); + cancelPressedMethod.invoke(dialog); + System.out.println("testRefactoringRename(): pressCancel is executed"); + } catch (Exception ex) { + ex.printStackTrace(); + throw new Error(ex); + } + } } diff --git a/org.eclipse.wildwebdeveloper.tests/src/org/eclipse/wildwebdeveloper/tests/TestLanguageServers.java b/org.eclipse.wildwebdeveloper.tests/src/org/eclipse/wildwebdeveloper/tests/TestLanguageServers.java index 3ee0b564c5..09bf45b98a 100644 --- a/org.eclipse.wildwebdeveloper.tests/src/org/eclipse/wildwebdeveloper/tests/TestLanguageServers.java +++ b/org.eclipse.wildwebdeveloper.tests/src/org/eclipse/wildwebdeveloper/tests/TestLanguageServers.java @@ -67,16 +67,13 @@ public void testCSSFile() throws Exception { ITextEditor editor = (ITextEditor) IDE .openEditor(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(), file); editor.getDocumentProvider().getDocument(editor.getEditorInput()).set("FAIL"); - assertTrue(new DisplayHelper() { - @Override - protected boolean condition() { - try { - return file.findMarkers("org.eclipse.lsp4e.diagnostic", true, IResource.DEPTH_ZERO).length != 0; - } catch (CoreException e) { - return false; - } + assertTrue(DisplayHelper.waitForCondition(PlatformUI.getWorkbench().getDisplay(), 5000, () -> { + try { + return file.findMarkers("org.eclipse.lsp4e.diagnostic", true, IResource.DEPTH_ZERO).length != 0; + } catch (CoreException e) { + return false; } - }.waitForCondition(PlatformUI.getWorkbench().getDisplay(), 5000), "Diagnostic not published"); + }), "Diagnostic not published"); } @Test @@ -86,16 +83,13 @@ public void testHTMLFile() throws Exception { ITextEditor editor = (ITextEditor) IDE .openEditor(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(), file); editor.getDocumentProvider().getDocument(editor.getEditorInput()).set("<"); - assertTrue(new DisplayHelper() { - @Override - protected boolean condition() { - try { - return file.findMarkers("org.eclipse.lsp4e.diagnostic", true, IResource.DEPTH_ZERO).length != 0; - } catch (CoreException e) { - return false; - } + assertTrue(DisplayHelper.waitForCondition(PlatformUI.getWorkbench().getDisplay(), 5000, () -> { + try { + return file.findMarkers("org.eclipse.lsp4e.diagnostic", true, IResource.DEPTH_ZERO).length != 0; + } catch (CoreException e) { + return false; } - }.waitForCondition(PlatformUI.getWorkbench().getDisplay(), 5000), "Diagnostic not published"); + }), "Diagnostic not published"); } @Test @@ -105,16 +99,13 @@ public void testYAMLFile() throws Exception { ITextEditor editor = (ITextEditor) IDE .openEditor(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(), file); editor.getDocumentProvider().getDocument(editor.getEditorInput()).set("hello: '"); - assertTrue(new DisplayHelper() { - @Override - protected boolean condition() { - try { - return file.findMarkers("org.eclipse.lsp4e.diagnostic", true, IResource.DEPTH_ZERO).length != 0; - } catch (CoreException e) { - return false; - } + assertTrue(DisplayHelper.waitForCondition(PlatformUI.getWorkbench().getDisplay(), 5000, () -> { + try { + return file.findMarkers("org.eclipse.lsp4e.diagnostic", true, IResource.DEPTH_ZERO).length != 0; + } catch (CoreException e) { + return false; } - }.waitForCondition(PlatformUI.getWorkbench().getDisplay(), 5000), "Diagnostic not published"); + }), "Diagnostic not published"); } @Test @@ -124,16 +115,13 @@ public void testJSONFile() throws Exception { ITextEditor editor = (ITextEditor) IDE .openEditor(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(), file); editor.getDocumentProvider().getDocument(editor.getEditorInput()).set("ERROR"); - assertTrue(new DisplayHelper() { - @Override - protected boolean condition() { - try { - return file.findMarkers("org.eclipse.lsp4e.diagnostic", true, IResource.DEPTH_ZERO).length != 0; - } catch (CoreException e) { - return false; - } + assertTrue(DisplayHelper.waitForCondition(PlatformUI.getWorkbench().getDisplay(), 5000, () -> { + try { + return file.findMarkers("org.eclipse.lsp4e.diagnostic", true, IResource.DEPTH_ZERO).length != 0; + } catch (CoreException e) { + return false; } - }.waitForCondition(PlatformUI.getWorkbench().getDisplay(), 5000), "Diagnostic not published"); + }), "Diagnostic not published"); } @Test @@ -145,16 +133,13 @@ public void testJSFile() throws Exception { DisplayHelper.sleep(2000); // Give time for LS to initialize enough before making edit and sending a // didChange editor.getDocumentProvider().getDocument(editor.getEditorInput()).set("a<"); - assertTrue(new DisplayHelper() { - @Override - protected boolean condition() { - try { - return file.findMarkers("org.eclipse.lsp4e.diagnostic", true, IResource.DEPTH_ZERO).length != 0; - } catch (CoreException e) { - return false; - } + assertTrue(DisplayHelper.waitForCondition(PlatformUI.getWorkbench().getDisplay(), 5000, () -> { + try { + return file.findMarkers("org.eclipse.lsp4e.diagnostic", true, IResource.DEPTH_ZERO).length != 0; + } catch (CoreException e) { + return false; } - }.waitForCondition(PlatformUI.getWorkbench().getDisplay(), 5000), "Diagnostic not published"); + }), "Diagnostic not published"); } @Test @@ -164,16 +149,13 @@ public void testTSFile() throws Exception { ITextEditor editor = (ITextEditor) IDE .openEditor(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(), file); editor.getDocumentProvider().getDocument(editor.getEditorInput()).set("FAIL"); - assertTrue(new DisplayHelper() { - @Override - protected boolean condition() { - try { - return file.findMarkers("org.eclipse.lsp4e.diagnostic", true, IResource.DEPTH_ZERO).length != 0; - } catch (CoreException e) { - return false; - } + assertTrue(DisplayHelper.waitForCondition(PlatformUI.getWorkbench().getDisplay(), 15000, () -> { + try { + return file.findMarkers("org.eclipse.lsp4e.diagnostic", true, IResource.DEPTH_ZERO).length != 0; + } catch (CoreException e) { + return false; } - }.waitForCondition(PlatformUI.getWorkbench().getDisplay(), 15000), "Diagnostic not published"); + }), "Diagnostic not published"); } @Test @@ -183,16 +165,13 @@ public void testJSXFile() throws Exception { ITextEditor editor = (ITextEditor) IDE .openEditor(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(), file); editor.getDocumentProvider().getDocument(editor.getEditorInput()).set("a<"); - assertTrue(new DisplayHelper() { - @Override - protected boolean condition() { - try { - return file.findMarkers("org.eclipse.lsp4e.diagnostic", true, IResource.DEPTH_ZERO).length != 0; - } catch (CoreException e) { - return false; - } + assertTrue(DisplayHelper.waitForCondition(PlatformUI.getWorkbench().getDisplay(), 5000, () -> { + try { + return file.findMarkers("org.eclipse.lsp4e.diagnostic", true, IResource.DEPTH_ZERO).length != 0; + } catch (CoreException e) { + return false; } - }.waitForCondition(PlatformUI.getWorkbench().getDisplay(), 5000), "Diagnostic not published"); + }), "Diagnostic not published"); } @Test @@ -203,34 +182,28 @@ public void testTSXFile() throws Exception { .openEditor(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(), file); editor.getDocumentProvider().getDocument(editor.getEditorInput()).set("FAIL"); - assertTrue(new DisplayHelper() { - @Override - protected boolean condition() { - try { - return file.findMarkers("org.eclipse.lsp4e.diagnostic", true, IResource.DEPTH_ZERO).length != 0; - } catch (CoreException e) { - return false; - } + assertTrue(DisplayHelper.waitForCondition(PlatformUI.getWorkbench().getDisplay(), 15000, () -> { + try { + return file.findMarkers("org.eclipse.lsp4e.diagnostic", true, IResource.DEPTH_ZERO).length != 0; + } catch (CoreException e) { + return false; } - }.waitForCondition(PlatformUI.getWorkbench().getDisplay(), 15000), "Diagnostic not published"); + }), "Diagnostic not published"); editor.getDocumentProvider().getDocument(editor.getEditorInput()).set("const x = <>;export default x;"); - assertTrue(new DisplayHelper() { - @Override - protected boolean condition() { - try { - IMarker[] markers = file.findMarkers("org.eclipse.lsp4e.diagnostic", true, IResource.DEPTH_ZERO); - for (IMarker m : markers) { - if (((String) m.getAttribute(IMarker.MESSAGE)).contains("React")) { - return true; - } + assertTrue(DisplayHelper.waitForCondition(PlatformUI.getWorkbench().getDisplay(), 15000, () -> { + try { + IMarker[] markers = file.findMarkers("org.eclipse.lsp4e.diagnostic", true, IResource.DEPTH_ZERO); + for (IMarker m : markers) { + if (((String) m.getAttribute(IMarker.MESSAGE)).contains("React")) { + return true; } - return false; - } catch (CoreException e) { - return false; } + return false; + } catch (CoreException e) { + return false; } - }.waitForCondition(PlatformUI.getWorkbench().getDisplay(), 15000), "Diagnostic not cleared"); + }), "Diagnostic not cleared"); } @Test @@ -303,16 +276,13 @@ public void testSCSSFile() throws Exception { ITextEditor editor = (ITextEditor) IDE .openEditor(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(), file); editor.getDocumentProvider().getDocument(editor.getEditorInput()).set("FAIL"); - assertTrue(new DisplayHelper() { - @Override - protected boolean condition() { - try { - return file.findMarkers("org.eclipse.lsp4e.diagnostic", true, IResource.DEPTH_ZERO).length != 0; - } catch (CoreException e) { - return false; - } + assertTrue(DisplayHelper.waitForCondition(PlatformUI.getWorkbench().getDisplay(), 5000, () -> { + try { + return file.findMarkers("org.eclipse.lsp4e.diagnostic", true, IResource.DEPTH_ZERO).length != 0; + } catch (CoreException e) { + return false; } - }.waitForCondition(PlatformUI.getWorkbench().getDisplay(), 5000), "Diagnostic not published"); + }), "Diagnostic not published"); } @Test @@ -322,15 +292,12 @@ public void testLESSFile() throws Exception { ITextEditor editor = (ITextEditor) IDE .openEditor(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(), file); editor.getDocumentProvider().getDocument(editor.getEditorInput()).set("FAIL"); - assertTrue(new DisplayHelper() { - @Override - protected boolean condition() { - try { - return file.findMarkers("org.eclipse.lsp4e.diagnostic", true, IResource.DEPTH_ZERO).length != 0; - } catch (CoreException e) { - return false; - } + assertTrue(DisplayHelper.waitForCondition(PlatformUI.getWorkbench().getDisplay(), 5000, () -> { + try { + return file.findMarkers("org.eclipse.lsp4e.diagnostic", true, IResource.DEPTH_ZERO).length != 0; + } catch (CoreException e) { + return false; } - }.waitForCondition(PlatformUI.getWorkbench().getDisplay(), 5000), "Diagnostic not published"); + }), "Diagnostic not published"); } } diff --git a/org.eclipse.wildwebdeveloper.tests/src/org/eclipse/wildwebdeveloper/tests/TestSyntaxHighlighting.java b/org.eclipse.wildwebdeveloper.tests/src/org/eclipse/wildwebdeveloper/tests/TestSyntaxHighlighting.java index 9e02a4bae3..4138f738c3 100644 --- a/org.eclipse.wildwebdeveloper.tests/src/org/eclipse/wildwebdeveloper/tests/TestSyntaxHighlighting.java +++ b/org.eclipse.wildwebdeveloper.tests/src/org/eclipse/wildwebdeveloper/tests/TestSyntaxHighlighting.java @@ -35,30 +35,27 @@ @ExtendWith(AllCleanRule.class) public class TestSyntaxHighlighting { - private IProject project; - - @BeforeEach - public void initializeHostProject() throws CoreException { - project = ResourcesPlugin.getWorkspace().getRoot().getProject("blah"); - project.create(null); - project.open(null); - } - - @Test - public void testJSXHighlighting() throws CoreException { - IFile file = project.getFile("test.jsx"); - file.create(new ByteArrayInputStream("var n = 4;\n".getBytes()), true, null); - ITextEditor editor = (ITextEditor) IDE - .openEditor(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(), file); - StyledText widget = (StyledText) editor.getAdapter(Control.class); - Color defaultTextColor = widget.getForeground(); - assertTrue(new DisplayHelper() { - @Override - protected boolean condition() { - return Arrays.stream(widget.getStyleRanges()) - .anyMatch(range -> range.foreground != null && !defaultTextColor.equals(range.foreground)); - } - }.waitForCondition(widget.getDisplay(), 5000), "Missing syntax highlighting"); - } + private IProject project; + + @BeforeEach + public void initializeHostProject() throws CoreException { + project = ResourcesPlugin.getWorkspace().getRoot().getProject("blah"); + project.create(null); + project.open(null); + } + + @Test + public void testJSXHighlighting() throws CoreException { + IFile file = project.getFile("test.jsx"); + file.create(new ByteArrayInputStream("var n = 4;\n".getBytes()), true, null); + ITextEditor editor = (ITextEditor) IDE + .openEditor(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(), file); + StyledText widget = (StyledText) editor.getAdapter(Control.class); + Color defaultTextColor = widget.getForeground(); + assertTrue( + DisplayHelper.waitForCondition(widget.getDisplay(), 5000, () -> Arrays.stream(widget.getStyleRanges()) + .anyMatch(range -> range.foreground != null && !defaultTextColor.equals(range.foreground))), + "Missing syntax highlighting"); + } } diff --git a/org.eclipse.wildwebdeveloper.tests/src/org/eclipse/wildwebdeveloper/tests/TestVue.java b/org.eclipse.wildwebdeveloper.tests/src/org/eclipse/wildwebdeveloper/tests/TestVue.java index 1346c394db..1148510d6b 100644 --- a/org.eclipse.wildwebdeveloper.tests/src/org/eclipse/wildwebdeveloper/tests/TestVue.java +++ b/org.eclipse.wildwebdeveloper.tests/src/org/eclipse/wildwebdeveloper/tests/TestVue.java @@ -90,30 +90,22 @@ void testVueApp() throws Exception { LanguageServerWrapper lsWrapper = LanguageServiceAccessor.getLSWrapper(project, LanguageServersRegistry.getInstance().getDefinition("org.eclipse.wildwebdeveloper.vue")); - assertTrue(new DisplayHelper() { - @Override - protected boolean condition() { - try { - return Arrays - .stream(appComponentFile.findMarkers("org.eclipse.lsp4e.diagnostic", true, - IResource.DEPTH_ZERO)) - .anyMatch(marker -> marker.getAttribute(IMarker.MESSAGE, "").contains("never read")); - } catch (CoreException e) { - e.printStackTrace(); - return false; - } + assertTrue(DisplayHelper.waitForCondition(editor.getSite().getShell().getDisplay(), 30000, () -> { + try { + return Arrays + .stream(appComponentFile.findMarkers("org.eclipse.lsp4e.diagnostic", true, + IResource.DEPTH_ZERO)) + .anyMatch(marker -> marker.getAttribute(IMarker.MESSAGE, "").contains("never read")); + } catch (CoreException e) { + e.printStackTrace(); + return false; } - }.waitForCondition(editor.getSite().getShell().getDisplay(), 30000), + }), "Diagnostic not published in standalone component file"); IDocument document = editor.getDocumentProvider().getDocument(editor.getEditorInput()); - assertTrue(new DisplayHelper() { - - @Override - protected boolean condition() { - return lsWrapper.isActive() && lsWrapper.isConnectedTo(LSPEclipseUtils.toUri(document)) - && lsWrapper.canOperate(project) && lsWrapper.canOperate(document); - } - }.waitForCondition(editor.getSite().getShell().getDisplay(), 30000)); + assertTrue(DisplayHelper.waitForCondition(editor.getSite().getShell().getDisplay(), 30000, + () -> lsWrapper.isActive() && lsWrapper.isConnectedTo(LSPEclipseUtils.toUri(document)) + && lsWrapper.canOperate(project) && lsWrapper.canOperate(document))); LSContentAssistProcessor contentAssistProcessor = new LSContentAssistProcessor(); ICompletionProposal[] proposals = contentAssistProcessor.computeCompletionProposals(Utils.getViewer(editor), document.get().indexOf(" }}")); @@ -142,30 +134,22 @@ void testVueTemplate() throws Exception { String tagName = "only-start"; String tag = '<' + tagName + '>'; document.set(document.get().replace(tag, tag + "<")); - assertTrue(new DisplayHelper() { - @Override - protected boolean condition() { - IMarker[] markers; - try { - markers = appComponentHTML.findMarkers("org.eclipse.lsp4e.diagnostic", true, IResource.DEPTH_ZERO); - return Arrays.stream(markers).anyMatch( - marker -> marker.getAttribute(IMarker.MESSAGE, "").contains("Element is missing end tag.")); - } catch (CoreException e) { - e.printStackTrace(); - return false; - } + assertTrue(DisplayHelper.waitForCondition(editor.getSite().getShell().getDisplay(), 30000, () -> { + IMarker[] markers; + try { + markers = appComponentHTML.findMarkers("org.eclipse.lsp4e.diagnostic", true, IResource.DEPTH_ZERO); + return Arrays.stream(markers).anyMatch( + marker -> marker.getAttribute(IMarker.MESSAGE, "").contains("Element is missing end tag.")); + } catch (CoreException e) { + e.printStackTrace(); + return false; } - }.waitForCondition(editor.getSite().getShell().getDisplay(), 30000), + }), "No error found on erroneous HTML component file"); - assertTrue(new DisplayHelper() { - - @Override - protected boolean condition() { - return lsWrapper.isActive() && lsWrapper.isConnectedTo(LSPEclipseUtils.toUri(document)) - && lsWrapper.canOperate(project) && lsWrapper.canOperate(document); - } - }.waitForCondition(editor.getSite().getShell().getDisplay(), 30000)); + assertTrue(DisplayHelper.waitForCondition(editor.getSite().getShell().getDisplay(), 30000, + () -> lsWrapper.isActive() && lsWrapper.isConnectedTo(LSPEclipseUtils.toUri(document)) + && lsWrapper.canOperate(project) && lsWrapper.canOperate(document))); LSContentAssistProcessor contentAssistProcessor = new LSContentAssistProcessor(); diff --git a/org.eclipse.wildwebdeveloper.tests/src/org/eclipse/wildwebdeveloper/tests/TestXML.java b/org.eclipse.wildwebdeveloper.tests/src/org/eclipse/wildwebdeveloper/tests/TestXML.java index 88664eda2d..fabd93550e 100644 --- a/org.eclipse.wildwebdeveloper.tests/src/org/eclipse/wildwebdeveloper/tests/TestXML.java +++ b/org.eclipse.wildwebdeveloper.tests/src/org/eclipse/wildwebdeveloper/tests/TestXML.java @@ -62,233 +62,219 @@ @ExtendWith(AllCleanRule.class) public class TestXML { - private IProject project; - private ICompletionProposal[] proposals; + private IProject project; + private ICompletionProposal[] proposals; - @BeforeEach - public void setUpProject() throws CoreException { - this.project = ResourcesPlugin.getWorkspace().getRoot().getProject(getClass().getName() + System.nanoTime()); - project.create(null); - project.open(null); - } + @BeforeEach + public void setUpProject() throws CoreException { + this.project = ResourcesPlugin.getWorkspace().getRoot().getProject(getClass().getName() + System.nanoTime()); + project.create(null); + project.open(null); + } - @Test - public void testXMLFile() throws Exception { - final IFile file = project.getFile("blah.xml"); - file.create(new ByteArrayInputStream("FAIL".getBytes()), true, null); - ITextEditor editor = (ITextEditor) IDE - .openEditor(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(), file); - editor.getDocumentProvider().getDocument(editor.getEditorInput()).set(" { + try { + return file.findMarkers("org.eclipse.lsp4e.diagnostic", true, IResource.DEPTH_ZERO).length != 0; + } catch (CoreException e) { + return false; + } + }), "Diagnostic not published"); + } - @Test - public void testXSLFile() throws Exception { - final IFile file = project.getFile("blah.xsl"); - file.create(new ByteArrayInputStream("FAIL".getBytes()), true, null); - ITextEditor editor = (ITextEditor) IDE - .openEditor(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(), file); - editor.getDocumentProvider().getDocument(editor.getEditorInput()).set("FAIL"); - assertTrue(new DisplayHelper() { - @Override - protected boolean condition() { - try { - return file.findMarkers("org.eclipse.lsp4e.diagnostic", true, IResource.DEPTH_ZERO).length != 0; - } catch (CoreException e) { - return false; - } - } - }.waitForCondition(PlatformUI.getWorkbench().getDisplay(), 5000), "Diagnostic not published"); - } + @Test + public void testXSLFile() throws Exception { + final IFile file = project.getFile("blah.xsl"); + file.create(new ByteArrayInputStream("FAIL".getBytes()), true, null); + ITextEditor editor = (ITextEditor) IDE + .openEditor(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(), file); + editor.getDocumentProvider().getDocument(editor.getEditorInput()).set("FAIL"); + assertTrue(DisplayHelper.waitForCondition(PlatformUI.getWorkbench().getDisplay(), 5000, () -> { + try { + return file.findMarkers("org.eclipse.lsp4e.diagnostic", true, IResource.DEPTH_ZERO).length != 0; + } catch (CoreException e) { + return false; + } + }), "Diagnostic not published"); + } - @Test - public void testXSDFile() throws Exception { - final IFile file = project.getFile("blah.xsd"); - file.create(new ByteArrayInputStream("FAIL".getBytes()), true, null); - ITextEditor editor = (ITextEditor) IDE - .openEditor(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(), file); - editor.getDocumentProvider().getDocument(editor.getEditorInput()).set("a<"); - assertTrue(new DisplayHelper() { - @Override - protected boolean condition() { - try { - return file.findMarkers("org.eclipse.lsp4e.diagnostic", true, IResource.DEPTH_ZERO).length != 0; - } catch (CoreException e) { - return false; - } - } - }.waitForCondition(PlatformUI.getWorkbench().getDisplay(), 5000), "Diagnostic not published"); - } + @Test + public void testXSDFile() throws Exception { + final IFile file = project.getFile("blah.xsd"); + file.create(new ByteArrayInputStream("FAIL".getBytes()), true, null); + ITextEditor editor = (ITextEditor) IDE + .openEditor(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(), file); + editor.getDocumentProvider().getDocument(editor.getEditorInput()).set("a<"); + assertTrue(DisplayHelper.waitForCondition(PlatformUI.getWorkbench().getDisplay(), 5000, () -> { + try { + return file.findMarkers("org.eclipse.lsp4e.diagnostic", true, IResource.DEPTH_ZERO).length != 0; + } catch (CoreException e) { + return false; + } + }), "Diagnostic not published"); + } - @Test - public void testDTDFile() throws Exception { - final IFile file = project.getFile("blah.dtd"); - file.create(new ByteArrayInputStream("FAIL".getBytes()), true, null); - ITextEditor editor = (ITextEditor) IDE - .openEditor(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(), file); - editor.getDocumentProvider().getDocument(editor.getEditorInput()).set(""); - assertTrue(new DisplayHelper() { - @Override - protected boolean condition() { - try { - return file.findMarkers("org.eclipse.lsp4e.diagnostic", true, IResource.DEPTH_ZERO).length != 0; - } catch (CoreException e) { - return false; - } - } - }.waitForCondition(PlatformUI.getWorkbench().getDisplay(), 5000), "Diagnostic not published"); - } + @Test + public void testDTDFile() throws Exception { + final IFile file = project.getFile("blah.dtd"); + file.create(new ByteArrayInputStream("FAIL".getBytes()), true, null); + ITextEditor editor = (ITextEditor) IDE + .openEditor(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(), file); + editor.getDocumentProvider().getDocument(editor.getEditorInput()).set(""); + assertTrue(DisplayHelper.waitForCondition(PlatformUI.getWorkbench().getDisplay(), 5000, () -> { + try { + return file.findMarkers("org.eclipse.lsp4e.diagnostic", true, IResource.DEPTH_ZERO).length != 0; + } catch (CoreException e) { + return false; + } + }), "Diagnostic not published"); + } - @Test - public void testComplexXML() throws Exception { - final IFile file = project.getFile("blah.xml"); - String content = "\n" + " |\n" + ""; - int offset = content.indexOf('|'); - content = content.replace("|", ""); - file.create(new ByteArrayInputStream(content.getBytes()), true, null); - AbstractTextEditor editor = (AbstractTextEditor) IDE.openEditor( - PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(), file, - "org.eclipse.ui.genericeditor.GenericEditor"); - editor.getSelectionProvider().setSelection(new TextSelection(offset, 0)); - LSContentAssistProcessor processor = new LSContentAssistProcessor(); - proposals = processor.computeCompletionProposals(Utils.getViewer(editor), offset); - DisplayHelper.sleep(editor.getSite().getShell().getDisplay(), 2000); - assertTrue(proposals.length > 1); - } + @Test + public void testComplexXML() throws Exception { + final IFile file = project.getFile("blah.xml"); + String content = "\n" + " |\n" + ""; + int offset = content.indexOf('|'); + content = content.replace("|", ""); + file.create(new ByteArrayInputStream(content.getBytes()), true, null); + AbstractTextEditor editor = (AbstractTextEditor) IDE.openEditor( + PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(), file, + "org.eclipse.ui.genericeditor.GenericEditor"); + editor.getSelectionProvider().setSelection(new TextSelection(offset, 0)); + LSContentAssistProcessor processor = new LSContentAssistProcessor(); + proposals = processor.computeCompletionProposals(Utils.getViewer(editor), offset); + DisplayHelper.sleep(editor.getSite().getShell().getDisplay(), 2000); + assertTrue(proposals.length > 1); + } - @Test - public void autoCloseTags() throws Exception { - final IFile file = project.getFile("autoCloseTags.xml"); - file.create(new ByteArrayInputStream(""); - assertTrue(new DisplayHelper() { - @Override - protected boolean condition() { - return "".equals(document.get()); - } - }.waitForCondition(PlatformUI.getWorkbench().getDisplay(), 5000), "Autoclose not done"); - } + @Test + public void autoCloseTags() throws Exception { + final IFile file = project.getFile("autoCloseTags.xml"); + file.create(new ByteArrayInputStream(""); + assertTrue( + DisplayHelper.waitForCondition(PlatformUI.getWorkbench().getDisplay(), 5000, + () -> "".equals(document.get())), + "Autoclose not done"); + } - /** - * Tests the creation of the system catalog with schemas that have been - * contributed. This tests as well the use of jar-URLs to allow relative - * includes within schemas (Issue #1078) - */ - @Test - public void testXMLCatalog() throws Exception { - // Create bundle with a catalog contribution - Path bundlePath = Files.createTempFile("xmlCatalogTest", "bundle.jar"); - bundlePath.toFile().deleteOnExit(); + /** + * Tests the creation of the system catalog with schemas that have been + * contributed. This tests as well the use of jar-URLs to allow relative + * includes within schemas (Issue #1078) + */ + @Test + public void testXMLCatalog() throws Exception { + // Create bundle with a catalog contribution + Path bundlePath = Files.createTempFile("xmlCatalogTest", "bundle.jar"); + bundlePath.toFile().deleteOnExit(); - try (FileOutputStream bundleOutput = new FileOutputStream(bundlePath.toFile()); - JarOutputStream bundleJarOut = new JarOutputStream(bundleOutput)) { + try (FileOutputStream bundleOutput = new FileOutputStream(bundlePath.toFile()); + JarOutputStream bundleJarOut = new JarOutputStream(bundleOutput)) { - // Manifest - bundleJarOut.putNextEntry(new JarEntry("META-INF/MANIFEST.MF")); - PrintWriter fileOut = new PrintWriter(bundleJarOut, true, StandardCharsets.UTF_8); - fileOut.println("Manifest-Version: 1.0"); - fileOut.println("Bundle-ManifestVersion: 2"); - fileOut.println("Bundle-Name: XML-Catalog-Test"); - fileOut.println("Bundle-SymbolicName: org.eclipse.wildwebdeveloper.test.xmlcatalog;singleton:=true"); - fileOut.println("Bundle-Version: 0.0.1"); - fileOut.println("Require-Bundle: org.eclipse.wst.xml.core"); + // Manifest + bundleJarOut.putNextEntry(new JarEntry("META-INF/MANIFEST.MF")); + PrintWriter fileOut = new PrintWriter(bundleJarOut, true, StandardCharsets.UTF_8); + fileOut.println("Manifest-Version: 1.0"); + fileOut.println("Bundle-ManifestVersion: 2"); + fileOut.println("Bundle-Name: XML-Catalog-Test"); + fileOut.println("Bundle-SymbolicName: org.eclipse.wildwebdeveloper.test.xmlcatalog;singleton:=true"); + fileOut.println("Bundle-Version: 0.0.1"); + fileOut.println("Require-Bundle: org.eclipse.wst.xml.core"); - // plugin.xml - bundleJarOut.putNextEntry(new JarEntry("plugin.xml")); - fileOut = new PrintWriter(bundleJarOut, true, StandardCharsets.UTF_8); - fileOut.println(""); - fileOut.println(""); - fileOut.println(""); - fileOut.println(""); - fileOut.println(""); - fileOut.println(""); - fileOut.println(""); - fileOut.println(""); - fileOut.println(""); + // plugin.xml + bundleJarOut.putNextEntry(new JarEntry("plugin.xml")); + fileOut = new PrintWriter(bundleJarOut, true, StandardCharsets.UTF_8); + fileOut.println(""); + fileOut.println(""); + fileOut.println(""); + fileOut.println(""); + fileOut.println(""); + fileOut.println(""); + fileOut.println(""); + fileOut.println(""); + fileOut.println(""); - // Schema in Jar - bundleJarOut.putNextEntry(new JarEntry("org/eclipse/wildwebdeveloper/test/schema.xsd")); - fileOut = new PrintWriter(bundleJarOut, true, StandardCharsets.UTF_8); - fileOut.println(""); - fileOut.println( - ""); - fileOut.println(""); - fileOut.println(""); - fileOut.println(""); - fileOut.println(""); - fileOut.println(""); - fileOut.println(""); - fileOut.println(""); - fileOut.println(""); - fileOut.println(""); + // Schema in Jar + bundleJarOut.putNextEntry(new JarEntry("org/eclipse/wildwebdeveloper/test/schema.xsd")); + fileOut = new PrintWriter(bundleJarOut, true, StandardCharsets.UTF_8); + fileOut.println(""); + fileOut.println( + ""); + fileOut.println(""); + fileOut.println(""); + fileOut.println(""); + fileOut.println(""); + fileOut.println(""); + fileOut.println(""); + fileOut.println(""); + fileOut.println(""); + fileOut.println(""); - bundleJarOut.closeEntry(); - } + bundleJarOut.closeEntry(); + } - // Install and start bundle - Plugin plugin = org.eclipse.wildwebdeveloper.xml.internal.Activator.getDefault(); - BundleContext bundleContext = plugin.getBundle().getBundleContext(); - URL bundleUrl = bundlePath.toUri().toURL(); - Bundle catalogBundle = bundleContext.installBundle(bundleUrl.toExternalForm(), bundleUrl.openStream()); - catalogBundle.start(); + // Install and start bundle + Plugin plugin = org.eclipse.wildwebdeveloper.xml.internal.Activator.getDefault(); + BundleContext bundleContext = plugin.getBundle().getBundleContext(); + URL bundleUrl = bundlePath.toUri().toURL(); + Bundle catalogBundle = bundleContext.installBundle(bundleUrl.toExternalForm(), bundleUrl.openStream()); + catalogBundle.start(); - // Open preferences dialog to trigger the refresh of the system catalog - PreferenceDialog dialog = PreferencesUtil.createPreferenceDialogOn( - PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), - "org.eclipse.wildwebdeveloper.xml.internal.ui.preferences.XMLCatalogPreferencePage", null, null); - dialog.getShell().open(); - dialog.getShell().close(); + // Open preferences dialog to trigger the refresh of the system catalog + PreferenceDialog dialog = PreferencesUtil.createPreferenceDialogOn( + PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), + "org.eclipse.wildwebdeveloper.xml.internal.ui.preferences.XMLCatalogPreferencePage", null, null); + dialog.getShell().open(); + dialog.getShell().close(); - // Find system.catalog in well known location from plugin - File systemCatalog = plugin.getStateLocation().append("system-catalog.xml").toFile(); - // Parse system-catalog to check it - Document systemCatalogDom = DocumentBuilderFactory.newDefaultInstance().newDocumentBuilder() - .parse(systemCatalog); + // Find system.catalog in well known location from plugin + File systemCatalog = plugin.getStateLocation().append("system-catalog.xml").toFile(); + // Parse system-catalog to check it + Document systemCatalogDom = DocumentBuilderFactory.newDefaultInstance().newDocumentBuilder() + .parse(systemCatalog); - // root - Node catalogNode = systemCatalogDom.getLastChild(); - assertEquals(Node.ELEMENT_NODE, catalogNode.getNodeType()); - assertEquals("catalog", catalogNode.getNodeName()); + // root + Node catalogNode = systemCatalogDom.getLastChild(); + assertEquals(Node.ELEMENT_NODE, catalogNode.getNodeType()); + assertEquals("catalog", catalogNode.getNodeName()); - // find URI-entries - NodeList catalogEntries = catalogNode.getChildNodes(); - List uriNodes = IntStream.range(0, catalogEntries.getLength()).mapToObj(catalogEntries::item) - .filter(n -> n.getNodeType() == Node.ELEMENT_NODE).filter(n -> "uri".equals(n.getNodeName())) - .collect(Collectors.toList()); - assertFalse(uriNodes.isEmpty(), "uri-nodes expected"); + // find URI-entries + NodeList catalogEntries = catalogNode.getChildNodes(); + List uriNodes = IntStream.range(0, catalogEntries.getLength()).mapToObj(catalogEntries::item) + .filter(n -> n.getNodeType() == Node.ELEMENT_NODE).filter(n -> "uri".equals(n.getNodeName())) + .collect(Collectors.toList()); + assertFalse(uriNodes.isEmpty(), "uri-nodes expected"); - // find expected entry - List expectedNodes = uriNodes.stream().filter(n -> "http://eclipse.org/wildwebdeveloper/test" - .equals(n.getAttributes().getNamedItem("name").getNodeValue())).collect(Collectors.toList()); - assertEquals(1, expectedNodes.size(), "one uri-node with the used name expected"); - Node uriNode = expectedNodes.get(0); + // find expected entry + List expectedNodes = uriNodes.stream().filter(n -> "http://eclipse.org/wildwebdeveloper/test" + .equals(n.getAttributes().getNamedItem("name").getNodeValue())).collect(Collectors.toList()); + assertEquals(1, expectedNodes.size(), "one uri-node with the used name expected"); + Node uriNode = expectedNodes.get(0); - // value of uri - assertNotNull(uriNode.getAttributes().getNamedItem("uri"), "uri-attribute expected"); - String uri = uriNode.getAttributes().getNamedItem("uri").getNodeValue(); - assertNotNull(uri, "value fro uri expected"); - // use of jar-uri - file is not cached in local filesystem. This enables - // relative includes in schemas - assertTrue(uri.startsWith("jar:file:/"), "jar-uri expected: " + uri); - assertTrue(uri.endsWith("/org/eclipse/wildwebdeveloper/test/schema.xsd"), - "relative path of schema in uri expected: " + uri); + // value of uri + assertNotNull(uriNode.getAttributes().getNamedItem("uri"), "uri-attribute expected"); + String uri = uriNode.getAttributes().getNamedItem("uri").getNodeValue(); + assertNotNull(uri, "value fro uri expected"); + // use of jar-uri - file is not cached in local filesystem. This enables + // relative includes in schemas + assertTrue(uri.startsWith("jar:file:/"), "jar-uri expected: " + uri); + assertTrue(uri.endsWith("/org/eclipse/wildwebdeveloper/test/schema.xsd"), + "relative path of schema in uri expected: " + uri); - // Uninstall bundle once again - catalogBundle.uninstall(); - } + // Uninstall bundle once again + catalogBundle.uninstall(); + } } diff --git a/org.eclipse.wildwebdeveloper.tests/src/org/eclipse/wildwebdeveloper/tests/TestYaml.java b/org.eclipse.wildwebdeveloper.tests/src/org/eclipse/wildwebdeveloper/tests/TestYaml.java index 2d0047b9b0..b778cc64fe 100644 --- a/org.eclipse.wildwebdeveloper.tests/src/org/eclipse/wildwebdeveloper/tests/TestYaml.java +++ b/org.eclipse.wildwebdeveloper.tests/src/org/eclipse/wildwebdeveloper/tests/TestYaml.java @@ -37,62 +37,59 @@ @ExtendWith(AllCleanRule.class) public class TestYaml { - @Test - public void testFalseDetectionAsKubernetes() throws Exception { - IProject p = ResourcesPlugin.getWorkspace().getRoot().getProject("p"); - p.create(new NullProgressMonitor()); - p.open(new NullProgressMonitor()); - IFile file = p.getFile("blah.yaml"); - file.create(new ByteArrayInputStream(new byte[0]), true, new NullProgressMonitor()); - IWorkbenchPage activePage = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); - ITextEditor editor = (ITextEditor) IDE.openEditor(activePage, file, true); - IDocument document = editor.getDocumentProvider().getDocument(editor.getEditorInput()); - document.set("name: a\ndescrition: b"); - boolean markerFound = new DisplayHelper() { - @Override - protected boolean condition() { - try { - return file.findMarkers(IMarker.PROBLEM, true, IResource.DEPTH_ZERO).length > 0; - } catch (CoreException e) { - return false; - } - } - }.waitForCondition(activePage.getWorkbenchWindow().getShell().getDisplay(), 3000); - assertFalse(markerFound, Arrays.stream(file.findMarkers(IMarker.PROBLEM, true, IResource.DEPTH_ZERO)) - .map(Object::toString).collect(Collectors.joining("\n"))); - } + @Test + public void testFalseDetectionAsKubernetes() throws Exception { + IProject p = ResourcesPlugin.getWorkspace().getRoot().getProject("p"); + p.create(new NullProgressMonitor()); + p.open(new NullProgressMonitor()); + IFile file = p.getFile("blah.yaml"); + file.create(new ByteArrayInputStream(new byte[0]), true, new NullProgressMonitor()); + IWorkbenchPage activePage = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); + ITextEditor editor = (ITextEditor) IDE.openEditor(activePage, file, true); + IDocument document = editor.getDocumentProvider().getDocument(editor.getEditorInput()); + document.set("name: a\ndescrition: b"); + boolean markerFound = DisplayHelper.waitForCondition(activePage.getWorkbenchWindow().getShell().getDisplay(), + 3000, () -> { + try { + return file.findMarkers(IMarker.PROBLEM, true, IResource.DEPTH_ZERO).length > 0; + } catch (CoreException e) { + return false; + } + }); + assertFalse(markerFound, Arrays.stream(file.findMarkers(IMarker.PROBLEM, true, IResource.DEPTH_ZERO)) + .map(Object::toString).collect(Collectors.joining("\n"))); + } - private void testErrorFile(String name) throws Exception { - IProject p = ResourcesPlugin.getWorkspace().getRoot().getProject("p"); - p.create(new NullProgressMonitor()); - p.open(new NullProgressMonitor()); - IFile file = p.getFile(name); - file.create(new ByteArrayInputStream(new byte[0]), true, new NullProgressMonitor()); - IWorkbenchPage activePage = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); - ITextEditor editor = (ITextEditor) IDE.openEditor(activePage, file, true); - IDocument document = editor.getDocumentProvider().getDocument(editor.getEditorInput()); - document.set("{version: 1}"); - boolean markerFound = new DisplayHelper() { - @Override - protected boolean condition() { - try { - return file.findMarkers(IMarker.PROBLEM, true, IResource.DEPTH_ZERO).length > 0; - } catch (CoreException e) { - return false; - } - } - }.waitForCondition(activePage.getWorkbenchWindow().getShell().getDisplay(), 6000); - assertTrue(markerFound, Arrays.stream(file.findMarkers(IMarker.PROBLEM, true, IResource.DEPTH_ZERO)) - .map(Object::toString).collect(Collectors.joining("\n"))); - } + private void testErrorFile(String name) throws Exception { + IProject p = ResourcesPlugin.getWorkspace().getRoot().getProject("p"); + p.create(new NullProgressMonitor()); + p.open(new NullProgressMonitor()); + IFile file = p.getFile(name); + file.create(new ByteArrayInputStream(new byte[0]), true, new NullProgressMonitor()); + IWorkbenchPage activePage = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); + ITextEditor editor = (ITextEditor) IDE.openEditor(activePage, file, true); + IDocument document = editor.getDocumentProvider().getDocument(editor.getEditorInput()); + document.set("{version: 1}"); + boolean markerFound = DisplayHelper.waitForCondition(activePage.getWorkbenchWindow().getShell().getDisplay(), + 6000, () -> { + try { + return file.findMarkers(IMarker.PROBLEM, true, IResource.DEPTH_ZERO).length > 0; + } catch (CoreException e) { + return false; + } - @Test - public void testSchemaExtensionPoint() throws Exception { - testErrorFile("dep.yml"); - } + }); + assertTrue(markerFound, Arrays.stream(file.findMarkers(IMarker.PROBLEM, true, IResource.DEPTH_ZERO)) + .map(Object::toString).collect(Collectors.joining("\n"))); + } - @Test - public void testSchemaExtensionPointUsingPlatformURL() throws Exception { - testErrorFile("depp.yml"); - } + @Test + public void testSchemaExtensionPoint() throws Exception { + testErrorFile("dep.yml"); + } + + @Test + public void testSchemaExtensionPointUsingPlatformURL() throws Exception { + testErrorFile("depp.yml"); + } }