diff --git a/.ratignore b/.ratignore index 1689cd38d4f..ac404b56771 100644 --- a/.ratignore +++ b/.ratignore @@ -28,6 +28,7 @@ extras/Test.jtl lib/aareadme.txt lib/opt/README.txt src/licenses/licenses/*/CC0-1.0.txt +src/licenses/licenses/autocomplete/LICENSE.md #local/** #reports/** src/launcher/src/main/resources/org/apache/jmeter/jmeter_as_ascii_art.txt diff --git a/src/bom-thirdparty/build.gradle.kts b/src/bom-thirdparty/build.gradle.kts index 85f8ca290d3..7e4b224af45 100644 --- a/src/bom-thirdparty/build.gradle.kts +++ b/src/bom-thirdparty/build.gradle.kts @@ -44,6 +44,7 @@ dependencies { api("bsf:bsf:2.4.0") api("cglib:cglib-nodep:3.3.0") api("com.fifesoft:rsyntaxtextarea:4.0.1") + api("com.fifesoft:autocomplete:4.0.0") api("com.github.ben-manes.caffeine:caffeine:3.3.0") api("com.github.weisj:darklaf-core:3.1.1") api("com.github.weisj:darklaf-extensions-rsyntaxarea:0.4.1") diff --git a/src/components/src/main/java/org/apache/jmeter/assertions/JSR223AssertionBeanInfo.java b/src/components/src/main/java/org/apache/jmeter/assertions/JSR223AssertionBeanInfo.java index 19e1e7573e3..8568f796e21 100644 --- a/src/components/src/main/java/org/apache/jmeter/assertions/JSR223AssertionBeanInfo.java +++ b/src/components/src/main/java/org/apache/jmeter/assertions/JSR223AssertionBeanInfo.java @@ -17,12 +17,13 @@ package org.apache.jmeter.assertions; +import org.apache.jmeter.gui.util.JSR223Completion; import org.apache.jmeter.util.JSR223BeanInfoSupport; public class JSR223AssertionBeanInfo extends JSR223BeanInfoSupport { public JSR223AssertionBeanInfo() { - super(JSR223Assertion.class); + super(JSR223Assertion.class, JSR223Completion.Binding.SAMPLE_RESULT, JSR223Completion.Binding.ASSERTION_RESULT); } } diff --git a/src/components/src/main/java/org/apache/jmeter/visualizers/JSR223ListenerBeanInfo.java b/src/components/src/main/java/org/apache/jmeter/visualizers/JSR223ListenerBeanInfo.java index 58aefba6aca..af6f942fde1 100644 --- a/src/components/src/main/java/org/apache/jmeter/visualizers/JSR223ListenerBeanInfo.java +++ b/src/components/src/main/java/org/apache/jmeter/visualizers/JSR223ListenerBeanInfo.java @@ -17,12 +17,13 @@ package org.apache.jmeter.visualizers; +import org.apache.jmeter.gui.util.JSR223Completion; import org.apache.jmeter.util.JSR223BeanInfoSupport; public class JSR223ListenerBeanInfo extends JSR223BeanInfoSupport { public JSR223ListenerBeanInfo() { - super(JSR223Listener.class); + super(JSR223Listener.class, JSR223Completion.Binding.SAMPLE_EVENT, JSR223Completion.Binding.LISTENER_SAMPLE_RESULT); } } diff --git a/src/components/src/test/java/org/apache/jmeter/assertions/JSR223ComponentGuiCompletionTest.java b/src/components/src/test/java/org/apache/jmeter/assertions/JSR223ComponentGuiCompletionTest.java new file mode 100644 index 00000000000..547172ed4eb --- /dev/null +++ b/src/components/src/test/java/org/apache/jmeter/assertions/JSR223ComponentGuiCompletionTest.java @@ -0,0 +1,59 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to you under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.jmeter.assertions; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeFalse; + +import java.awt.GraphicsEnvironment; + +import org.apache.jmeter.test.gui.JSR223GuiCompletionTestSupport; +import org.apache.jmeter.visualizers.JSR223Listener; +import org.junit.jupiter.api.Test; + +class JSR223ComponentGuiCompletionTest { + + @Test + void completesAssertionBindingThroughTheDisplayedTestBeanEditor() throws Exception { + assumeFalse(GraphicsEnvironment.isHeadless()); + JSR223Assertion assertion = new JSR223Assertion(); + String script = "AssertionResult.setFailureMe"; + + JSR223GuiCompletionTestSupport.Result result = JSR223GuiCompletionTestSupport.invoke( + JSR223Assertion.class, assertion, script, script.length(), "AssertionResult.setFailureMessage"); + + assertTrue(result.completionActionInstalled()); + assertTrue(result.completionAccepted()); + assertEquals("AssertionResult.setFailureMessage(message)", result.text()); + } + + @Test + void completesListenerBindingThroughTheDisplayedTestBeanEditor() throws Exception { + assumeFalse(GraphicsEnvironment.isHeadless()); + JSR223Listener listener = new JSR223Listener(); + String script = "sampleEvent.getThreadG"; + + JSR223GuiCompletionTestSupport.Result result = JSR223GuiCompletionTestSupport.invoke( + JSR223Listener.class, listener, script, script.length(), "sampleEvent.getThreadGroup"); + + assertTrue(result.completionActionInstalled()); + assertTrue(result.completionAccepted()); + assertEquals("sampleEvent.getThreadGroup()", result.text()); + } +} diff --git a/src/core/build.gradle.kts b/src/core/build.gradle.kts index c7785a39699..6708d5c60d7 100644 --- a/src/core/build.gradle.kts +++ b/src/core/build.gradle.kts @@ -35,6 +35,9 @@ dependencies { api("com.fifesoft:rsyntaxtextarea") { because("JSyntaxTextArea extends RSyntaxTextArea") } + api("com.fifesoft:autocomplete") { + because("JSR223 script editors provide code completion") + } api("net.sf.jtidy:jtidy") { because("public static Tidy XPathUtil#makeTidyParser()") } diff --git a/src/core/src/main/java/org/apache/jmeter/gui/util/JSR223Completion.java b/src/core/src/main/java/org/apache/jmeter/gui/util/JSR223Completion.java new file mode 100644 index 00000000000..f2a99398199 --- /dev/null +++ b/src/core/src/main/java/org/apache/jmeter/gui/util/JSR223Completion.java @@ -0,0 +1,391 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to you under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.jmeter.gui.util; + +import java.awt.Component; +import java.awt.Container; +import java.awt.Window; +import java.awt.event.ActionEvent; +import java.awt.event.InputEvent; +import java.awt.event.KeyEvent; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; + +import javax.swing.AbstractAction; +import javax.swing.Action; +import javax.swing.Icon; +import javax.swing.JList; +import javax.swing.KeyStroke; +import javax.swing.SwingUtilities; +import javax.swing.text.BadLocationException; +import javax.swing.text.JTextComponent; + +import org.fife.ui.autocomplete.AutoCompletion; +import org.fife.ui.autocomplete.Completion; +import org.fife.ui.autocomplete.DefaultCompletionProvider; +import org.fife.ui.autocomplete.DescWindowVisibility; +import org.fife.ui.autocomplete.FunctionCompletion; +import org.fife.ui.autocomplete.ParameterizedCompletion; +import org.fife.ui.autocomplete.VariableCompletion; + +/** + * Installs Ctrl+Space completion for the bindings exposed to JSR223 scripts. + */ +public final class JSR223Completion { + + // TestBean property for the extra bindings specific to a JSR223 element. + public static final String BINDINGS_PROPERTY = "jsr223.bindings"; + + // A binding provided by a specific JSR223 element, beyond the common bindings. + public enum Binding { + SAMPLE_RESULT("SampleResult", "SampleResult", "Sample result the script can inspect or update"), + ASSERTION_RESULT("AssertionResult", "AssertionResult", "Result of this assertion"), + SAMPLE_EVENT("sampleEvent", "SampleEvent", "Event for the sample"), + LISTENER_SAMPLE_RESULT("sampleResult", "SampleResult", "Result for the sample event"); + + private final String bindingName; + private final String bindingType; + private final String summary; + + Binding(String bindingName, String bindingType, String summary) { + this.bindingName = bindingName; + this.bindingType = bindingType; + this.summary = summary; + } + } + + private JSR223Completion() { + } + + public static AutoCompletion install(JSyntaxTextArea area) { + return install(area, new Binding[0]); + } + + public static AutoCompletion install(JSyntaxTextArea area, Binding... bindings) { + AutoCompletion completion = new AutoCompletion(createProvider(bindings)); + completion.setTriggerKey(KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, InputEvent.CTRL_DOWN_MASK)); + completion.setAutoActivationEnabled(false); + completion.setAutoCompleteSingleChoices(false); + completion.setDescWindowVisibility(DescWindowVisibility.ALWAYS); + completion.setParameterAssistanceEnabled(true); + KeyStroke parameterStart = KeyStroke.getKeyStroke('('); + Object originalParameterKey = area.getInputMap().get(parameterStart); + Action originalParameterAction = area.getActionMap().get(originalParameterKey); + completion.install(area); + installVariableParenthesisFallback(area, parameterStart, originalParameterAction); + return completion; + } + + private static void installVariableParenthesisFallback(JSyntaxTextArea area, KeyStroke parameterStart, + Action originalParameterAction) { + Object actionKey = area.getInputMap().get(parameterStart); + Action parameterAction = area.getActionMap().get(actionKey); + if (parameterAction == null) { + return; + } + area.getActionMap().put(actionKey, new AbstractAction() { + @Override + public void actionPerformed(ActionEvent event) { + Completion selected = selectedCompletion(area); + parameterAction.actionPerformed(event); + if (selected != null && !(selected instanceof ParameterizedCompletion)) { + if (originalParameterAction != null) { + originalParameterAction.actionPerformed(new ActionEvent(area, ActionEvent.ACTION_PERFORMED, "(")); + } else { + area.replaceSelection("("); + } + } + } + }); + } + + private static Completion selectedCompletion(JSyntaxTextArea area) { + Window owner = SwingUtilities.getWindowAncestor(area); + if (owner == null) { + return null; + } + for (Window popup : owner.getOwnedWindows()) { + if (popup.isVisible()) { + JList list = findCompletionList(popup); + if (list != null && list.getSelectedValue() instanceof Completion completion) { + return completion; + } + } + } + return null; + } + + private static JList findCompletionList(Container container) { + for (Component component : container.getComponents()) { + if (component instanceof JList list + && list.getModel().getSize() > 0 + && list.getModel().getElementAt(0) instanceof Completion) { + return list; + } + if (component instanceof Container child) { + JList list = findCompletionList(child); + if (list != null) { + return list; + } + } + } + return null; + } + + private static DefaultCompletionProvider createProvider(Binding... bindings) { + DefaultCompletionProvider provider = new JSR223CompletionProvider(); + provider.setParameterizedCompletionParams('(', ", ", ')'); + + variable(provider, "vars", "JMeterVariables", "Thread-local JMeter variables"); + variable(provider, "props", "java.util.Properties", "JMeter properties shared by all threads"); + variable(provider, "ctx", "JMeterContext", "Current thread context"); + variable(provider, "log", "org.slf4j.Logger", "Logger for jmeter.log"); + variable(provider, "sampler", "Sampler", "The current sampler"); + variable(provider, "prev", "SampleResult", "Previous sample result"); + variable(provider, "Label", "String", "Element name"); + variable(provider, "FileName", "String", "Script file name"); + variable(provider, "Parameters", "String", "Parameters field as one string"); + variable(provider, "args", "String[]", "Parameters split on spaces"); + variable(provider, "args.length", "int", "Number of script arguments"); + variable(provider, "OUT", "java.io.PrintStream", "System.out"); + + method(provider, "vars.get", "String", "Get variable value", "String name"); + method(provider, "vars.put", "void", "Set variable value", "String name", "String value"); + method(provider, "vars.getObject", "Object", "Get object variable", "String name"); + method(provider, "vars.putObject", "void", "Set object variable", "String name", "Object value"); + method(provider, "vars.remove", "Object", "Remove variable and return its value", "String name"); + method(provider, "vars.getIteration", "int", "Current iteration number"); + + method(provider, "props.get", "Object", "Get a value stored directly in the JMeter properties", "Object key"); + method(provider, "props.getProperty", "String", "Get a string property, checking defaults when needed", "String name"); + method(provider, "props.put", "Object", "Set property", "Object key", "Object value"); + method(provider, "props.setProperty", "Object", "Set property", "String name", "String value"); + + for (String level : new String[]{"debug", "info", "warn", "error"}) { + method(provider, "log." + level, "void", "Log at " + level.toUpperCase(Locale.ROOT) + " level", "String msg"); + } + + method(provider, "ctx.getThreadNum", "int", "Thread number within its group"); + method(provider, "ctx.getPreviousResult", "SampleResult", "Previous sample result"); + method(provider, "ctx.getCurrentSampler", "Sampler", "Current sampler"); + method(provider, "ctx.getVariables", "JMeterVariables", "Thread variables"); + method(provider, "ctx.getThreadGroup", "AbstractThreadGroup", "Owning thread group"); + + addSampleResultMethods(provider, "prev"); + for (Binding binding : bindings) { + variable(provider, binding.bindingName, binding.bindingType, binding.summary); + switch (binding) { + case SAMPLE_RESULT, LISTENER_SAMPLE_RESULT -> addSampleResultMethods(provider, binding.bindingName); + case ASSERTION_RESULT -> addAssertionResultMethods(provider, binding.bindingName); + case SAMPLE_EVENT -> addSampleEventMethods(provider, binding.bindingName); + } + } + return provider; + } + + private static final class JSR223CompletionProvider extends DefaultCompletionProvider { + @Override + public String getAlreadyEnteredText(JTextComponent component) { + try { + int caret = component.getCaretPosition(); + String text = component.getDocument().getText(0, caret); + int start = selectorStart(text, caret); + return text.substring(start); + } catch (BadLocationException e) { + throw new IllegalStateException("Unable to read text before completion caret", e); + } + } + + @Override + protected List getCompletionsImpl(JTextComponent component) { + String enteredText = getAlreadyEnteredText(component); + String prefix = normalizeSelector(enteredText); + boolean safeNavigation = enteredText.contains("?"); + List matches = new ArrayList<>(); + String suffix = textAfterCaret(component); + if (!suffix.isEmpty() && (Character.isJavaIdentifierPart(suffix.charAt(0)) || suffix.charAt(0) == '$')) { + return matches; + } + boolean existingCall = suffix.stripLeading().startsWith("("); + for (Completion completion : completions) { + String inputText = completion.getInputText(); + if (inputText.regionMatches(true, 0, prefix, 0, prefix.length()) + && !(existingCall && completion instanceof FunctionCompletion + && inputText.equalsIgnoreCase(prefix))) { + matches.add(safeNavigation ? new SafeNavigationCompletion(completion) : completion); + } + } + return matches; + } + + private static int selectorStart(String text, int caret) { + int start = caret; + while (start > 0) { + char ch = text.charAt(start - 1); + if (Character.isJavaIdentifierPart(ch) || ch == '$' || ch == '.' || ch == '?') { + start--; + } else if (Character.isWhitespace(ch)) { + int beforeWhitespace = start - 1; + int afterWhitespace = start; + while (beforeWhitespace >= 0 && Character.isWhitespace(text.charAt(beforeWhitespace))) { + beforeWhitespace--; + } + while (afterWhitespace < caret && Character.isWhitespace(text.charAt(afterWhitespace))) { + afterWhitespace++; + } + if ((beforeWhitespace >= 0 && (text.charAt(beforeWhitespace) == '.' + || text.charAt(beforeWhitespace) == '?')) + || (afterWhitespace < caret && (text.charAt(afterWhitespace) == '.' + || text.charAt(afterWhitespace) == '?'))) { + start--; + } else { + break; + } + } else { + break; + } + } + return start; + } + + private static String normalizeSelector(String selector) { + return selector.replaceAll("\\s*\\?\\s*\\.\\s*|\\s*\\.\\s*", "."); + } + + private static String textAfterCaret(JTextComponent component) { + try { + return component.getDocument().getText(component.getCaretPosition(), + component.getDocument().getLength() - component.getCaretPosition()); + } catch (BadLocationException e) { + throw new IllegalStateException("Unable to read text after completion caret", e); + } + } + } + + private static void addAssertionResultMethods(DefaultCompletionProvider provider, String result) { + method(provider, result + ".getName", "String", "Assertion name"); + method(provider, result + ".isFailure", "boolean", "Whether the assertion failed"); + method(provider, result + ".isError", "boolean", "Whether an error occurred"); + method(provider, result + ".getFailureMessage", "String", "Failure or error message"); + method(provider, result + ".setError", "void", "Set the error flag", "boolean error"); + method(provider, result + ".setFailure", "void", "Set the failure flag", "boolean failure"); + method(provider, result + ".setFailureMessage", "void", "Set the failure message", "String message"); + method(provider, result + ".setResultForFailure", "AssertionResult", "Set a failure result", "String message"); + method(provider, result + ".setResultForNull", "AssertionResult", "Set a null-result failure"); + } + + private static void addSampleEventMethods(DefaultCompletionProvider provider, String event) { + method(provider, event + ".getResult", "SampleResult", "Sample result for this event"); + method(provider, event + ".getThreadGroup", "String", "Thread group name"); + method(provider, event + ".getHostname", "String", "Host name"); + method(provider, event + ".isTransactionSampleEvent", "boolean", "Whether this is a transaction event"); + method(provider, event + ".getVarValue", "String", "Sample variable value", "int index"); + } + + private static void addSampleResultMethods(DefaultCompletionProvider provider, String result) { + method(provider, result + ".getResponseDataAsString", "String", "Response body as text"); + method(provider, result + ".setResponseData", "void", "Set response body", "String data", "String encoding"); + method(provider, result + ".getResponseCode", "String", "Response code"); + method(provider, result + ".setResponseCode", "void", "Set response code", "String code"); + method(provider, result + ".setResponseMessage", "void", "Set response message", "String msg"); + method(provider, result + ".isSuccessful", "boolean", "Success flag"); + method(provider, result + ".setSuccessful", "void", "Set success flag", "boolean ok"); + method(provider, result + ".getTime", "long", "Elapsed time in ms"); + method(provider, result + ".getSampleLabel", "String", "Label for this sample"); + method(provider, result + ".setSampleLabel", "void", "Set the label for this sample", "String label"); + } + + private static void variable(DefaultCompletionProvider provider, String name, String type, String summary) { + VariableCompletion completion = new VariableCompletion(provider, name, type); + completion.setShortDescription(summary); + completion.setSummary(summary); + provider.addCompletion(completion); + } + + private static void method(DefaultCompletionProvider provider, String name, String returnType, String summary, + String... params) { + FunctionCompletion completion = new FunctionCompletion(provider, name, returnType); + List parameters = new ArrayList<>(); + for (String parameter : params) { + int space = parameter.lastIndexOf(' '); + parameters.add(new ParameterizedCompletion.Parameter( + parameter.substring(0, space), parameter.substring(space + 1))); + } + completion.setParams(parameters); + completion.setShortDescription(summary); + completion.setSummary(summary); + provider.addCompletion(completion); + } + + private static final class SafeNavigationCompletion implements Completion { + private final Completion delegate; + private final String inputText; + + private SafeNavigationCompletion(Completion delegate) { + this.delegate = delegate; + inputText = delegate.getInputText().replaceFirst("\\.", "?."); + } + + @Override + public int compareTo(Completion other) { + return inputText.compareToIgnoreCase(other.getInputText()); + } + + @Override + public String getAlreadyEntered(JTextComponent component) { + return delegate.getAlreadyEntered(component); + } + + @Override + public Icon getIcon() { + return delegate.getIcon(); + } + + @Override + public String getInputText() { + return inputText; + } + + @Override + public org.fife.ui.autocomplete.CompletionProvider getProvider() { + return delegate.getProvider(); + } + + @Override + public int getRelevance() { + return delegate.getRelevance(); + } + + @Override + public String getReplacementText() { + String replacementText = delegate.getReplacementText(); + return inputText + replacementText.substring(delegate.getInputText().length()); + } + + @Override + public String getSummary() { + return delegate.getSummary(); + } + + @Override + public String getToolTipText() { + return delegate.getToolTipText(); + } + } +} diff --git a/src/core/src/main/java/org/apache/jmeter/testbeans/gui/GenericTestBeanCustomizer.java b/src/core/src/main/java/org/apache/jmeter/testbeans/gui/GenericTestBeanCustomizer.java index 9f25190d335..bf13c38444b 100644 --- a/src/core/src/main/java/org/apache/jmeter/testbeans/gui/GenericTestBeanCustomizer.java +++ b/src/core/src/main/java/org/apache/jmeter/testbeans/gui/GenericTestBeanCustomizer.java @@ -246,16 +246,20 @@ public GenericTestBeanCustomizer(){ if (guiType instanceof TypeEditor typeEditor) { propertyEditor = typeEditor.getInstance(descriptor); } else if (guiType instanceof Class aClass && Enum.class.isAssignableFrom(aClass)) { - @SuppressWarnings("unchecked") // we check the class type above - final Class> enumClass = (Class>) guiType; - propertyEditor = new EnumEditor(descriptor, enumClass, (ResourceBundle) descriptor.getValue(GenericTestBeanCustomizer.RESOURCE_BUNDLE)); + @SuppressWarnings("unchecked") // we check the class type above + final Class> enumClass = (Class>) guiType; + propertyEditor = new EnumEditor(descriptor, enumClass, + (ResourceBundle) descriptor.getValue(GenericTestBeanCustomizer.RESOURCE_BUNDLE)); } else { Class editorClass = descriptor.getPropertyEditorClass(); - log.debug("Property {} has editor class {}", name, editorClass); - if (editorClass != null) { + log.debug("Property {} has editor class {}", name, editorClass); try { - propertyEditor = (PropertyEditor) editorClass.getDeclaredConstructor().newInstance(); + if (editorClass == JSR223TextAreaEditor.class) { + propertyEditor = new JSR223TextAreaEditor(descriptor); + } else { + propertyEditor = (PropertyEditor) editorClass.getDeclaredConstructor().newInstance(); + } } catch (ReflectiveOperationException e) { log.error("Can't create property editor.", e); throw new Error(e.toString()); @@ -308,9 +312,10 @@ public GenericTestBeanCustomizer(){ // In case of BSF and JSR elements i want to add textAreaEditor as a listener to scriptLanguage ComboBox. String beanName = this.beanInfo.getBeanDescriptor().getName(); if (beanName.startsWith("BSF") || beanName.startsWith("JSR223")) { // $NON-NLS-1$ $NON-NLS-2$ - WrapperEditor we = (WrapperEditor) editors[scriptLanguageIndex]; - TextAreaEditor tae = (TextAreaEditor) editors[textAreaEditorIndex]; - we.addChangeListener(tae); + if (editors[scriptLanguageIndex] instanceof WrapperEditor we + && editors[textAreaEditorIndex] instanceof TextAreaEditor tae) { + we.addChangeListener(tae); + } } // Obtain message formats: diff --git a/src/core/src/main/java/org/apache/jmeter/testbeans/gui/JSR223TextAreaEditor.java b/src/core/src/main/java/org/apache/jmeter/testbeans/gui/JSR223TextAreaEditor.java new file mode 100644 index 00000000000..99c2c9e3b9d --- /dev/null +++ b/src/core/src/main/java/org/apache/jmeter/testbeans/gui/JSR223TextAreaEditor.java @@ -0,0 +1,30 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to you under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.jmeter.testbeans.gui; + +import java.beans.PropertyDescriptor; + +/** + * Text editor with code completion for JSR223 scripts. + */ +public class JSR223TextAreaEditor extends TextAreaEditor { + + public JSR223TextAreaEditor(PropertyDescriptor descriptor) { + super(descriptor, true); + } +} diff --git a/src/core/src/main/java/org/apache/jmeter/testbeans/gui/TextAreaEditor.java b/src/core/src/main/java/org/apache/jmeter/testbeans/gui/TextAreaEditor.java index c6726ca1f56..73b2990ee3c 100644 --- a/src/core/src/main/java/org/apache/jmeter/testbeans/gui/TextAreaEditor.java +++ b/src/core/src/main/java/org/apache/jmeter/testbeans/gui/TextAreaEditor.java @@ -20,21 +20,33 @@ import java.awt.Component; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; +import java.awt.event.HierarchyEvent; +import java.awt.event.HierarchyListener; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.beans.PropertyDescriptor; import java.beans.PropertyEditorSupport; import java.util.Locale; +import javax.swing.SwingUtilities; + +import org.apache.jmeter.gui.util.JSR223Completion; import org.apache.jmeter.gui.util.JSyntaxTextArea; import org.apache.jmeter.gui.util.JTextScrollPane; +import org.fife.ui.autocomplete.AutoCompletion; -public class TextAreaEditor extends PropertyEditorSupport implements FocusListener, PropertyChangeListener { +public class TextAreaEditor extends PropertyEditorSupport implements FocusListener, PropertyChangeListener, HierarchyListener { private final JSyntaxTextArea textUI; private final JTextScrollPane scroller; + private boolean completionEnabled; + + private JSR223Completion.Binding[] completionBindings = new JSR223Completion.Binding[0]; + + private AutoCompletion completion; + /** {@inheritDoc} */ @Override public void focusGained(FocusEvent e) { @@ -49,6 +61,9 @@ public void focusLost(FocusEvent e) { private final void init() {// called from ctor, so must not be overridable textUI.discardAllEdits(); textUI.addFocusListener(this); + if (completionEnabled) { + textUI.addHierarchyListener(this); + } } /** @@ -81,7 +96,20 @@ public TextAreaEditor(Object source) { * to be used for the editor. Must not be null */ public TextAreaEditor(PropertyDescriptor descriptor) { + this(descriptor, false); + } + + protected TextAreaEditor(PropertyDescriptor descriptor, boolean enableCodeCompletion) { textUI = JSyntaxTextArea.getInstance(10, 60); + if (enableCodeCompletion) { + completionEnabled = true; + Object bindings = descriptor.getValue(JSR223Completion.BINDINGS_PROPERTY); + completionBindings = bindings instanceof JSR223Completion.Binding[] bindingArray + ? bindingArray.clone() : new JSR223Completion.Binding[0]; + if (textUI.isDisplayable()) { + completion = JSR223Completion.install(textUI, completionBindings); + } + } textUI.setLanguage((String) descriptor.getValue(GenericTestBeanCustomizer.TEXT_LANGUAGE)); scroller = JTextScrollPane.getInstance(textUI, true); init(); @@ -137,4 +165,24 @@ public void propertyChange(PropertyChangeEvent evt) { textUI.setLanguage(lang); } } + + @Override + public void hierarchyChanged(HierarchyEvent event) { + if ((event.getChangeFlags() & HierarchyEvent.DISPLAYABILITY_CHANGED) == 0 || !completionEnabled) { + return; + } + if (textUI.isDisplayable()) { + if (completion == null) { + completion = JSR223Completion.install(textUI, completionBindings); + } + } else if (completion != null) { + AutoCompletion currentCompletion = completion; + SwingUtilities.invokeLater(() -> { + if (completion == currentCompletion && !textUI.isDisplayable()) { + currentCompletion.uninstall(); + completion = null; + } + }); + } + } } diff --git a/src/core/src/main/java/org/apache/jmeter/testbeans/gui/TypeEditor.java b/src/core/src/main/java/org/apache/jmeter/testbeans/gui/TypeEditor.java index 63cc74ca9b0..f283447d0db 100644 --- a/src/core/src/main/java/org/apache/jmeter/testbeans/gui/TypeEditor.java +++ b/src/core/src/main/java/org/apache/jmeter/testbeans/gui/TypeEditor.java @@ -53,6 +53,12 @@ PropertyEditor getInstance(PropertyDescriptor descriptor) { PropertyEditor getInstance(PropertyDescriptor descriptor) { return new ComboStringEditor(descriptor); } + }, + JSR223TextAreaEditor { + @Override + PropertyEditor getInstance(PropertyDescriptor descriptor) { + return new JSR223TextAreaEditor(descriptor); + } }; // Some editors may need the descriptor diff --git a/src/core/src/main/java/org/apache/jmeter/util/JSR223BeanInfoSupport.java b/src/core/src/main/java/org/apache/jmeter/util/JSR223BeanInfoSupport.java index 825b45b2356..fab4ef44380 100644 --- a/src/core/src/main/java/org/apache/jmeter/util/JSR223BeanInfoSupport.java +++ b/src/core/src/main/java/org/apache/jmeter/util/JSR223BeanInfoSupport.java @@ -17,7 +17,11 @@ package org.apache.jmeter.util; +import java.beans.IndexedPropertyDescriptor; +import java.beans.IntrospectionException; +import java.beans.PropertyDescriptor; import java.util.Arrays; +import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.ListResourceBundle; @@ -28,6 +32,7 @@ import javax.script.ScriptEngineFactory; import javax.script.ScriptEngineManager; +import org.apache.jmeter.gui.util.JSR223Completion; import org.apache.jmeter.testbeans.TestBean; /** @@ -82,8 +87,68 @@ protected Object[][] getContents() { } }; + // BeanInfoSupport calls getPropertyDescriptors() while its constructor runs. + // Do not initialize this field explicitly: that would overwrite the cache after super(). + private PropertyDescriptor[] propertyDescriptors; + + /** + * Preserve the original JVM constructor for already-compiled plugins. + * + * @param beanClass class of the TestBean + */ protected JSR223BeanInfoSupport(Class beanClass) { + this(beanClass, new JSR223Completion.Binding[0]); + } + + protected JSR223BeanInfoSupport(Class beanClass, JSR223Completion.Binding... bindings) { super(beanClass, LANGUAGE_TAGS, NAME_BUNDLE); + if (bindings.length > 0) { + property("script").setValue(JSR223Completion.BINDINGS_PROPERTY, bindings.clone()); + } + } + + @Override + public PropertyDescriptor[] getPropertyDescriptors() { + if (propertyDescriptors == null) { + // Introspector can share inherited descriptors between JSR223 element classes. + propertyDescriptors = super.getPropertyDescriptors().clone(); + for (int i = 0; i < propertyDescriptors.length; i++) { + if ("script".equals(propertyDescriptors[i].getName())) { // $NON-NLS-1$ + propertyDescriptors[i] = copyPropertyDescriptor(propertyDescriptors[i]); + } + } + } + return propertyDescriptors; + } + + private static PropertyDescriptor copyPropertyDescriptor(PropertyDescriptor descriptor) { + try { + PropertyDescriptor copy; + if (descriptor instanceof IndexedPropertyDescriptor indexedDescriptor) { + copy = new IndexedPropertyDescriptor(descriptor.getName(), descriptor.getReadMethod(), + descriptor.getWriteMethod(), indexedDescriptor.getIndexedReadMethod(), + indexedDescriptor.getIndexedWriteMethod()); + } else { + copy = new PropertyDescriptor(descriptor.getName(), descriptor.getReadMethod(), + descriptor.getWriteMethod()); + } + copy.setDisplayName(descriptor.getDisplayName()); + copy.setShortDescription(descriptor.getShortDescription()); + copy.setExpert(descriptor.isExpert()); + copy.setHidden(descriptor.isHidden()); + copy.setPreferred(descriptor.isPreferred()); + copy.setBound(descriptor.isBound()); + copy.setConstrained(descriptor.isConstrained()); + copy.setPropertyEditorClass(descriptor.getPropertyEditorClass()); + Enumeration attributeNames = descriptor.attributeNames(); + while (attributeNames.hasMoreElements()) { + String attributeName = attributeNames.nextElement(); + copy.setValue(attributeName, descriptor.getValue(attributeName)); + } + return copy; + } catch (IntrospectionException e) { + throw new IllegalStateException("Unable to copy property descriptor " + descriptor.getName(), e); + } } /** diff --git a/src/core/src/main/java/org/apache/jmeter/util/JSR223TestElement.java b/src/core/src/main/java/org/apache/jmeter/util/JSR223TestElement.java index f6fe6716ab8..eeeb46d89cd 100644 --- a/src/core/src/main/java/org/apache/jmeter/util/JSR223TestElement.java +++ b/src/core/src/main/java/org/apache/jmeter/util/JSR223TestElement.java @@ -135,6 +135,7 @@ private String getScriptLanguageWithDefault() { * @param bindings Bindings */ protected void populateBindings(Bindings bindings) { + // Keep these common bindings in sync with JSR223Completion; subclasses may add their own bindings. final String label = getName(); final String fileName = getFilename(); final String scriptParameters = getParameters(); @@ -156,7 +157,6 @@ protected void populateBindings(Bindings bindings) { // For use in debugging: bindings.put("OUT", System.out); // NOSONAR $NON-NLS-1$ (this name is fixed) - // Most subclasses will need these: Sampler sampler = jmctx.getCurrentSampler(); bindings.put("sampler", sampler); // $NON-NLS-1$ (this name is fixed) SampleResult prev = jmctx.getPreviousResult(); diff --git a/src/core/src/main/java/org/apache/jmeter/util/ScriptingBeanInfoSupport.java b/src/core/src/main/java/org/apache/jmeter/util/ScriptingBeanInfoSupport.java index 46a4fdb90af..bb06b0cc164 100644 --- a/src/core/src/main/java/org/apache/jmeter/util/ScriptingBeanInfoSupport.java +++ b/src/core/src/main/java/org/apache/jmeter/util/ScriptingBeanInfoSupport.java @@ -30,6 +30,7 @@ import org.apache.jmeter.testbeans.BeanInfoSupport; import org.apache.jmeter.testbeans.TestBean; import org.apache.jmeter.testbeans.gui.FileEditor; +import org.apache.jmeter.testbeans.gui.JSR223TextAreaEditor; import org.apache.jmeter.testbeans.gui.TextAreaEditor; /** @@ -116,7 +117,11 @@ protected ScriptingBeanInfoSupport(Class beanClass, String[] p = property("script"); // $NON-NLS-1$ p.setValue(NOT_UNDEFINED, true); p.setValue(DEFAULT, ""); // $NON-NLS-1$ - p.setPropertyEditorClass(TextAreaEditor.class); + if (JSR223TestElement.class.isAssignableFrom(beanClass)) { + p.setPropertyEditorClass(JSR223TextAreaEditor.class); + } else { + p.setPropertyEditorClass(TextAreaEditor.class); + } createPropertyGroup("scripting", // $NON-NLS-1$ new String[] { "script" }); // $NON-NLS-1$ diff --git a/src/core/src/test/java/org/apache/jmeter/gui/util/JSR223CompletionTest.java b/src/core/src/test/java/org/apache/jmeter/gui/util/JSR223CompletionTest.java new file mode 100644 index 00000000000..a7e2cd78058 --- /dev/null +++ b/src/core/src/test/java/org/apache/jmeter/gui/util/JSR223CompletionTest.java @@ -0,0 +1,466 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to you under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.jmeter.gui.util; + +import static org.junit.jupiter.api.Assertions.assertAll; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.awt.Component; +import java.awt.Container; +import java.awt.event.ActionEvent; +import java.awt.event.InputEvent; +import java.awt.event.KeyEvent; +import java.beans.IndexedPropertyDescriptor; +import java.beans.PropertyDescriptor; +import java.lang.reflect.Constructor; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; + +import javax.swing.Action; +import javax.swing.KeyStroke; + +import org.apache.jmeter.testbeans.TestBean; +import org.apache.jmeter.testbeans.gui.TestBeanGUI; +import org.apache.jmeter.testelement.property.StringProperty; +import org.apache.jmeter.util.JSR223BeanInfoSupport; +import org.apache.jmeter.util.JSR223TestElement; +import org.fife.ui.autocomplete.AutoCompletion; +import org.fife.ui.autocomplete.Completion; +import org.fife.ui.autocomplete.CompletionProvider; +import org.fife.ui.autocomplete.FunctionCompletion; +import org.fife.ui.autocomplete.VariableCompletion; +import org.junit.jupiter.api.Test; + +class JSR223CompletionTest { + + public static class SampleResultElement extends JSR223TestElement implements TestBean { + } + + public static class SampleResultElementBeanInfo extends JSR223BeanInfoSupport { + public SampleResultElementBeanInfo() { + super(SampleResultElement.class, JSR223Completion.Binding.SAMPLE_RESULT); + } + } + + public static class SampleEventElement extends JSR223TestElement implements TestBean { + } + + public static class SampleEventElementBeanInfo extends JSR223BeanInfoSupport { + public SampleEventElementBeanInfo() { + super(SampleEventElement.class, JSR223Completion.Binding.SAMPLE_EVENT); + } + } + + public static class IndexedElement extends JSR223TestElement implements TestBean { + public String[] getOptions() { + return new String[0]; + } + + public void setOptions(String[] options) { + } + + public String getOptions(int index) { + return ""; + } + + public void setOptions(int index, String option) { + } + } + + @Test + void argsQualifierReturnsOnlyItsLengthCompletion() { + assertEquals(List.of("args.length"), completionNames("args.")); + } + + @Test + void completesUnmatchedArgsNeighborWithNoCandidates() { + assertEquals(List.of(), completionNames("args.lenz")); + } + + @Test + void completesSampleResultMethodsAfterQualifier() { + assertEquals(List.of( + "SampleResult.getResponseCode", + "SampleResult.getResponseDataAsString", + "SampleResult.getSampleLabel", + "SampleResult.getTime", + "SampleResult.isSuccessful", + "SampleResult.setResponseCode", + "SampleResult.setResponseData", + "SampleResult.setResponseMessage", + "SampleResult.setSampleLabel", + "SampleResult.setSuccessful"), + completionNames("SampleResult.", JSR223Completion.Binding.SAMPLE_RESULT)); + } + + @Test + void completesSampleResultResponseCodePrefix() { + assertEquals(List.of("SampleResult.getResponseCode"), + completionNames("SampleResult.getResponseC", JSR223Completion.Binding.SAMPLE_RESULT)); + } + + @Test + void completesAssertionFailureMessagePrefix() { + assertEquals(List.of("AssertionResult.getFailureMessage"), + completionNames("AssertionResult.getFailureM", + JSR223Completion.Binding.SAMPLE_RESULT, JSR223Completion.Binding.ASSERTION_RESULT)); + } + + @Test + void completesSampleEventThreadGroupPrefix() { + assertEquals(List.of("sampleEvent.getThreadGroup"), + completionNames("sampleEvent.getThreadG", + JSR223Completion.Binding.SAMPLE_EVENT, JSR223Completion.Binding.LISTENER_SAMPLE_RESULT)); + } + + @Test + void completesListenerSampleResultResponseCodePrefix() { + assertEquals(List.of("sampleResult.getResponseCode"), + completionNames("sampleResult.getResponseC", + JSR223Completion.Binding.SAMPLE_EVENT, JSR223Completion.Binding.LISTENER_SAMPLE_RESULT)); + } + + @Test + void offersAllRuntimeBindingsToCommonScripts() { + assertEquals(List.of( + "FileName", "Label", "OUT", "Parameters", "args", "ctx", "log", "prev", "props", "sampler", "vars"), + variableNames()); + } + + @Test + void offersElementSpecificBindingsToEachScriptElement() { + assertAll("element-specific runtime bindings", + () -> assertEquals(List.of("SampleResult"), + extraBindingNames(JSR223Completion.Binding.SAMPLE_RESULT), "sampler"), + () -> assertEquals(List.of("AssertionResult", "SampleResult"), + extraBindingNames(JSR223Completion.Binding.SAMPLE_RESULT, + JSR223Completion.Binding.ASSERTION_RESULT), "assertion"), + () -> assertEquals(List.of("sampleEvent", "sampleResult"), + extraBindingNames(JSR223Completion.Binding.SAMPLE_EVENT, + JSR223Completion.Binding.LISTENER_SAMPLE_RESULT), "listener")); + } + + @Test + void varsRemoveCompletionReturnsObject() { + assertEquals(List.of("vars.remove"), completionNames("vars.rem")); + FunctionCompletion remove = completionObjects("vars.rem", "vars.rem".length()) + .stream() + .filter(FunctionCompletion.class::isInstance) + .map(FunctionCompletion.class::cast) + .filter(completion -> "vars.remove".equals(completion.getInputText())) + .findFirst() + .orElseThrow(); + + assertAll("vars.remove completion metadata", + () -> assertEquals("Object", remove.getType()), + () -> assertTrue(remove.getSummary().contains("Remove variable and return its value")), + () -> assertEquals(1, remove.getParamCount())); + } + + @Test + void documentsVariableAndMethodCompletions() { + List completions = completionObjects("", 0); + VariableCompletion vars = completions.stream() + .filter(VariableCompletion.class::isInstance) + .map(VariableCompletion.class::cast) + .filter(completion -> "vars".equals(completion.getInputText())) + .findFirst() + .orElseThrow(); + FunctionCompletion put = completions.stream() + .filter(FunctionCompletion.class::isInstance) + .map(FunctionCompletion.class::cast) + .filter(completion -> "vars.put".equals(completion.getInputText())) + .findFirst() + .orElseThrow(); + + assertAll("variable completion description", + () -> assertTrue(vars.getSummary().contains("Thread-local JMeter variables"))); + assertAll("method completion description and arguments", + () -> assertTrue(put.getSummary().contains("Set variable value")), + () -> assertEquals("name", put.getParam(0).getName()), + () -> assertEquals("value", put.getParam(1).getName())); + } + + @Test + void elementBindingMetadataIsIsolated() { + JSR223BeanInfoSupport first = new SampleResultElementBeanInfo(); + JSR223BeanInfoSupport second = new SampleEventElementBeanInfo(); + + assertAll("isolated element script bindings", + () -> assertArrayEquals( + new JSR223Completion.Binding[] {JSR223Completion.Binding.SAMPLE_RESULT}, + scriptBindings(first), "SampleResultElementBeanInfo"), + () -> assertArrayEquals( + new JSR223Completion.Binding[] {JSR223Completion.Binding.SAMPLE_EVENT}, + scriptBindings(second), "SampleEventElementBeanInfo")); + } + + @Test + void completesPartialTopLevelBindingPrefix() { + assertEquals(List.of("Label"), completionNames("Labe")); + } + + @Test + void completesAllPreviousResultMethodsAfterQualifier() { + assertEquals(List.of( + "prev.getResponseCode", + "prev.getResponseDataAsString", + "prev.getSampleLabel", + "prev.getTime", + "prev.isSuccessful", + "prev.setResponseCode", + "prev.setResponseData", + "prev.setResponseMessage", + "prev.setSampleLabel", + "prev.setSuccessful"), + completionNames("prev.")); + } + + @Test + void completesPreviousResultResponseCodeInsideExpression() { + assertEquals(List.of("prev.getResponseCode"), completionNames("def result = prev.getResponseC")); + } + + @Test + void completesSafeNavigationThreadContextPrefix() { + assertEquals(List.of("ctx?.getThreadGroup", "ctx?.getThreadNum"), completionNames("ctx?.getTh")); + Completion threadNum = completionObjects("ctx?.getTh", "ctx?.getTh".length()).stream() + .filter(completion -> "ctx?.getThreadNum".equals(completion.getInputText())) + .findFirst().orElseThrow(); + assertTrue(threadNum.getReplacementText().startsWith("ctx?.getThreadNum")); + } + + @Test + void completesSafeNavigationWithWhitespaceAroundSelector() { + assertEquals(List.of("ctx?.getThreadGroup", "ctx?.getThreadNum"), completionNames("ctx ?. getTh")); + } + + @Test + void completesNormalNavigationWithWhitespaceAroundSelector() { + assertEquals(List.of("ctx.getThreadGroup", "ctx.getThreadNum"), completionNames("ctx . getTh")); + } + + @Test + void unknownBindingMemberReturnsNoCompletions() { + assertEquals(List.of(), completionNames("vars.noSuchMember")); + } + + @Test + void assignmentExpressionReturnsOnlyTheMatchingVariableMethod() { + assertEquals(List.of("vars.getIteration"), completionNames("x=vars.getI")); + } + + @Test + void completesSafeNavigationArgsLength() { + assertEquals(List.of("args?.length"), completionNames("args?.length")); + } + + @Test + void completesSafeNavigationPreviousResultMethods() { + assertEquals(List.of("prev?.getResponseCode", "prev?.getResponseDataAsString"), + completionNames("prev?.getRes")); + } + + @Test + void returnsNoCandidatesForUnrelatedReceiver() { + assertEquals(List.of(), completionNames("other.ctx.")); + } + + @Test + void returnsNoCandidatesForIdentifierContainingBindingName() { + assertEquals(List.of(), completionNames("my$ctx.get")); + } + + @Test + void returnsNoCandidatesWhenCaretIsInsideTokenSuffix() { + assertEquals(List.of(), completionNames("args.length", 7)); + } + + @Test + void returnsNoCandidatesWhenCaretPrecedesExistingCallSuffix() { + String expression = "ctx.getThreadNum()"; + assertEquals(List.of(), completionNames(expression, "ctx.getThreadNum".length())); + } + + @Test + void returnsNoCandidatesWhenWhitespacePrecedesExistingCallSuffix() { + assertEquals(List.of(), completionNames("ctx.getThreadNum ()", "ctx.getThreadNum".length())); + } + + @Test + void completionIsInstalledOnTheRealSyntaxEditorWithoutSingleChoiceInsertion() { + JSyntaxTextArea textArea = JSyntaxTextArea.getInstance(5, 40); + AutoCompletion completion = JSR223Completion.install(textArea); + textArea.setText("vars.ge"); + textArea.setCaretPosition(textArea.getText().length()); + + assertFalse(completion.getAutoCompleteSingleChoices()); + assertEquals(List.of("vars.get", "vars.getIteration", "vars.getObject"), + completion.getCompletionProvider().getCompletions(textArea).stream() + .map(Completion::getInputText).sorted().collect(Collectors.toList())); + + completion.uninstall(); + } + + @Test + void ctrlSpaceDoesNotChangeExistingExpressionsWithTheCaretInsideThem() { + JSyntaxTextArea textArea = JSyntaxTextArea.getInstance(5, 40); + AutoCompletion completion = JSR223Completion.install(textArea); + KeyStroke trigger = KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, InputEvent.CTRL_DOWN_MASK); + Object actionKey = textArea.getInputMap().get(trigger); + Action action = textArea.getActionMap().get(actionKey); + + assertNotNull(action); + try { + assertCtrlSpaceLeavesTextUnchanged(textArea, action, "ctx.getThreadNum()", "ctx.getThreadNum".length()); + assertCtrlSpaceLeavesTextUnchanged(textArea, action, "args.length", "args.le".length()); + } finally { + completion.uninstall(); + } + } + + private static void assertCtrlSpaceLeavesTextUnchanged(JSyntaxTextArea textArea, Action action, + String text, int caret) { + textArea.setText(text); + textArea.setCaretPosition(caret); + + action.actionPerformed(new ActionEvent(textArea, ActionEvent.ACTION_PERFORMED, "completion")); + + assertEquals(text, textArea.getText()); + } + + @Test + void preservesIndexedPropertyDescriptorInformation() throws Exception { + JSR223BeanInfoSupport beanInfo = new JSR223BeanInfoSupport(IndexedElement.class) {}; + PropertyDescriptor options = Arrays.stream(beanInfo.getPropertyDescriptors()) + .filter(descriptor -> "options".equals(descriptor.getName())) + .findFirst().orElseThrow(); + assertTrue(options instanceof IndexedPropertyDescriptor); + assertEquals(String.class, ((IndexedPropertyDescriptor) options).getIndexedPropertyType()); + assertNotNull(((IndexedPropertyDescriptor) options).getIndexedReadMethod()); + assertSame(beanInfo.getPropertyDescriptors(), beanInfo.getPropertyDescriptors()); + } + + @Test + void preservesOriginalBeanInfoConstructorForBinaryCompatibility() throws ReflectiveOperationException { + Constructor constructor = + JSR223BeanInfoSupport.class.getDeclaredConstructor(Class.class); + assertTrue(Modifier.isProtected(constructor.getModifiers())); + + SampleResultElementBeanInfo beanInfo = new SampleResultElementBeanInfo(); + assertNotNull(Arrays.stream(beanInfo.getPropertyDescriptors()) + .filter(descriptor -> "script".equals(descriptor.getName())) + .findFirst().orElse(null)); + } + + @Test + void refreshesScriptWhenConfiguringAnotherElementOfTheSameType() { + TestBeanGUI gui = new TestBeanGUI(SampleResultElement.class); + SampleResultElement first = new SampleResultElement(); + first.setProperty(new StringProperty("script", "first script")); + gui.configure(first); + assertEquals("first script", findTextArea(gui).getText()); + + SampleResultElement second = new SampleResultElement(); + second.setProperty(new StringProperty("script", "second script")); + gui.configure(second); + + assertEquals("second script", findTextArea(gui).getText()); + } + + private static JSyntaxTextArea findTextArea(Container container) { + for (Component component : container.getComponents()) { + if (component instanceof JSyntaxTextArea textArea) { + return textArea; + } + if (component instanceof Container child) { + JSyntaxTextArea textArea = findTextArea(child); + if (textArea != null) { + return textArea; + } + } + } + return null; + } + + private static List completionNames(String text) { + return completionNames(text, new JSR223Completion.Binding[0]); + } + + private static List completionNames(String text, int caret) { + return completionObjects(text, caret).stream() + .map(Completion::getInputText) + .sorted() + .collect(Collectors.toList()); + } + + private static List completionNames(String text, JSR223Completion.Binding... bindings) { + List names = completionObjects(text, text.length(), bindings).stream() + .map(Completion::getInputText).collect(Collectors.toCollection(ArrayList::new)); + Collections.sort(names); + return names; + } + + private static List completionObjects(String text, int caret, JSR223Completion.Binding... bindings) { + JSyntaxTextArea textArea = JSyntaxTextArea.getInstance(5, 40); + AutoCompletion completion = JSR223Completion.install(textArea, bindings); + try { + textArea.setText(text); + textArea.setCaretPosition(caret); + CompletionProvider provider = completion.getCompletionProvider(); + return provider.getCompletions(textArea); + } finally { + completion.uninstall(); + } + } + + private static List variableNames(JSR223Completion.Binding... bindings) { + return completionObjects("", 0, bindings).stream() + .filter(VariableCompletion.class::isInstance) + .filter(completion -> !(completion instanceof FunctionCompletion)) + .map(Completion::getInputText) + .filter(name -> !"args.length".equals(name)) + .sorted() + .collect(Collectors.toList()); + } + + private static List extraBindingNames(JSR223Completion.Binding... bindings) { + List commonNames = variableNames(); + return variableNames(bindings).stream() + .filter(name -> !commonNames.contains(name)) + .collect(Collectors.toList()); + } + + private static JSR223Completion.Binding[] scriptBindings(JSR223BeanInfoSupport beanInfo) { + for (PropertyDescriptor descriptor : beanInfo.getPropertyDescriptors()) { + if ("script".equals(descriptor.getName())) { + return (JSR223Completion.Binding[]) descriptor.getValue(JSR223Completion.BINDINGS_PROPERTY); + } + } + throw new AssertionError("Missing script property"); + } +} diff --git a/src/core/src/test/java/org/apache/jmeter/testbeans/gui/JSR223ScriptEditorTest.java b/src/core/src/test/java/org/apache/jmeter/testbeans/gui/JSR223ScriptEditorTest.java new file mode 100644 index 00000000000..d8cc3d52c20 --- /dev/null +++ b/src/core/src/test/java/org/apache/jmeter/testbeans/gui/JSR223ScriptEditorTest.java @@ -0,0 +1,157 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to you under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.jmeter.testbeans.gui; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeFalse; + +import java.awt.Component; +import java.awt.Container; +import java.awt.GraphicsEnvironment; +import java.beans.PropertyEditor; +import java.beans.PropertyEditorSupport; +import java.util.HashMap; + +import javax.swing.JFrame; +import javax.swing.JPanel; +import javax.swing.SwingUtilities; +import javax.swing.UIManager; + +import org.apache.jmeter.gui.util.JSyntaxTextArea; +import org.apache.jmeter.testbeans.TestBean; +import org.apache.jmeter.util.JSR223BeanInfoSupport; +import org.apache.jmeter.util.JSR223TestElement; +import org.junit.jupiter.api.Test; + +class JSR223ScriptEditorTest { + + public static class ScriptElement extends JSR223TestElement implements TestBean { + } + + public static class ScriptElementBeanInfo extends JSR223BeanInfoSupport { + public ScriptElementBeanInfo() { + super(ScriptElement.class); + } + + void setScriptEditorClass(Class editorClass) { + property("script").setPropertyEditorClass(editorClass); + } + + Class getScriptEditorClass() { + return property("script").getPropertyEditorClass(); + } + + void setScriptGuiType(Object guiType) { + property("script").setValue(GenericTestBeanCustomizer.GUITYPE, guiType); + } + } + + public static class CustomEditor extends PropertyEditorSupport { + @Override + public boolean supportsCustomEditor() { + return true; + } + + @Override + public Component getCustomEditor() { + return new MarkerPanel(); + } + } + + private static class MarkerPanel extends JPanel { + private static final long serialVersionUID = 1L; + } + + @Test + void usesCompletionEditorByDefaultForJsr223Script() { + ScriptElementBeanInfo beanInfo = new ScriptElementBeanInfo(); + assertEquals(JSR223TextAreaEditor.class, beanInfo.getScriptEditorClass()); + + GenericTestBeanCustomizer customizer = new GenericTestBeanCustomizer(beanInfo); + customizer.setObject(new HashMap<>()); + + assertTrue(contains(customizer, JSyntaxTextArea.class)); + assertFalse(contains(customizer, MarkerPanel.class)); + } + + @Test + void usesPluginPropertyEditorInPlaceOfDefaultCompletionEditor() { + ScriptElementBeanInfo beanInfo = new ScriptElementBeanInfo(); + beanInfo.setScriptEditorClass(CustomEditor.class); + GenericTestBeanCustomizer customizer = new GenericTestBeanCustomizer(beanInfo); + customizer.setObject(new HashMap<>()); + + assertTrue(contains(customizer, MarkerPanel.class)); + } + + @Test + void preservesPluginGuiTypePriorityOverPropertyEditorClass() { + ScriptElementBeanInfo beanInfo = new ScriptElementBeanInfo(); + beanInfo.setScriptEditorClass(CustomEditor.class); + beanInfo.setScriptGuiType(TypeEditor.TextAreaEditor); + GenericTestBeanCustomizer customizer = new GenericTestBeanCustomizer(beanInfo); + customizer.setObject(new HashMap<>()); + + assertTrue(contains(customizer, JSyntaxTextArea.class)); + assertFalse(contains(customizer, MarkerPanel.class)); + } + + @Test + void uninstallCompletionWhenDisplayedEditorIsDiscarded() throws Exception { + assumeFalse(GraphicsEnvironment.isHeadless()); + long listenerCount = autoCompletionListenerCount(); + + for (int i = 0; i < 3; i++) { + JFrame frame = new JFrame("JSR223 editor lifecycle test"); + ScriptElementBeanInfo beanInfo = new ScriptElementBeanInfo(); + GenericTestBeanCustomizer customizer = new GenericTestBeanCustomizer(beanInfo); + customizer.setObject(new HashMap<>()); + frame.setContentPane(customizer); + frame.pack(); + frame.setVisible(true); + SwingUtilities.invokeAndWait(() -> { + }); + + assertEquals(listenerCount + 1, autoCompletionListenerCount()); + + frame.dispose(); + SwingUtilities.invokeAndWait(() -> { + }); + assertEquals(listenerCount, autoCompletionListenerCount()); + } + } + + private static long autoCompletionListenerCount() { + return java.util.Arrays.stream(UIManager.getPropertyChangeListeners()) + .filter(listener -> listener.getClass().getName() + .startsWith("org.fife.ui.autocomplete.AutoCompletion$")) + .count(); + } + + private static boolean contains(Container container, Class type) { + for (Component component : container.getComponents()) { + if (type.isInstance(component) + || component instanceof Container child && contains(child, type)) { + return true; + } + } + return false; + } +} diff --git a/src/core/src/testFixtures/java/org/apache/jmeter/test/gui/JSR223GuiCompletionTestSupport.java b/src/core/src/testFixtures/java/org/apache/jmeter/test/gui/JSR223GuiCompletionTestSupport.java new file mode 100644 index 00000000000..c9955796a3e --- /dev/null +++ b/src/core/src/testFixtures/java/org/apache/jmeter/test/gui/JSR223GuiCompletionTestSupport.java @@ -0,0 +1,203 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to you under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.jmeter.test.gui; + +import java.awt.Component; +import java.awt.Container; +import java.awt.Window; +import java.awt.event.ActionEvent; +import java.awt.event.InputEvent; +import java.awt.event.KeyEvent; +import java.awt.event.MouseEvent; +import java.util.concurrent.atomic.AtomicReference; + +import javax.swing.Action; +import javax.swing.JFrame; +import javax.swing.JList; +import javax.swing.KeyStroke; +import javax.swing.SwingUtilities; + +import org.apache.jmeter.gui.util.JSyntaxTextArea; +import org.apache.jmeter.testbeans.TestBean; +import org.apache.jmeter.testbeans.gui.TestBeanGUI; +import org.apache.jmeter.testelement.TestElement; +import org.fife.ui.autocomplete.Completion; + +/** + * Runs script completion through a displayed TestBeanGUI and its installed keyboard actions. + */ +public final class JSR223GuiCompletionTestSupport { + + private static final KeyStroke COMPLETION_KEY = + KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, InputEvent.CTRL_DOWN_MASK); + + private JSR223GuiCompletionTestSupport() { + } + + public static Result invoke(Class beanClass, TestElement element, String script, + int caretPosition, String completionToAccept) throws Exception { + return invoke(beanClass, element, script, caretPosition, completionToAccept, false); + } + + public static Result typeOpeningParenthesis(Class beanClass, TestElement element, + String script, int caretPosition) throws Exception { + return invoke(beanClass, element, script, caretPosition, null, true); + } + + private static Result invoke(Class beanClass, TestElement element, String script, + int caretPosition, String completionToAccept, boolean typeOpeningParenthesis) throws Exception { + AtomicReference frame = new AtomicReference<>(); + AtomicReference editor = new AtomicReference<>(); + AtomicReference triggerInstalled = new AtomicReference<>(false); + AtomicReference popupVisible = new AtomicReference<>(false); + try { + SwingUtilities.invokeAndWait(() -> { + JFrame window = new JFrame("JSR223 completion test"); + frame.set(window); + TestBeanGUI gui = new TestBeanGUI(beanClass); + gui.configure(element); + window.setContentPane(gui); + window.pack(); + window.setVisible(true); + window.toFront(); + + JSyntaxTextArea textArea = findTextArea(gui); + if (textArea == null) { + throw new AssertionError("TestBeanGUI did not create a JSyntaxTextArea"); + } + editor.set(textArea); + textArea.setText(script); + textArea.setCaretPosition(caretPosition); + textArea.requestFocusInWindow(); + + Action action = actionFor(textArea, COMPLETION_KEY); + triggerInstalled.set(action != null); + if (action != null) { + action.actionPerformed(new ActionEvent(textArea, ActionEvent.ACTION_PERFORMED, "completion")); + } + popupVisible.set(isCompletionPopupVisible(window)); + if (typeOpeningParenthesis) { + Action parenthesisAction = actionFor(textArea, KeyStroke.getKeyStroke('(')); + if (parenthesisAction == null) { + throw new AssertionError("Completion editor did not install its parenthesis action"); + } + parenthesisAction.actionPerformed(new ActionEvent(textArea, ActionEvent.ACTION_PERFORMED, "(")); + } else if (completionToAccept != null) { + acceptCompletion(window, completionToAccept); + } + }); + + AtomicReference result = new AtomicReference<>(); + SwingUtilities.invokeAndWait(() -> result.set(editor.get().getText())); + return new Result(result.get(), triggerInstalled.get(), completionToAccept != null, popupVisible.get()); + } finally { + JFrame window = frame.get(); + if (window != null) { + SwingUtilities.invokeAndWait(window::dispose); + } + } + } + + private static Action actionFor(JSyntaxTextArea textArea, KeyStroke keyStroke) { + Object actionKey = textArea.getInputMap().get(keyStroke); + return actionKey == null ? null : textArea.getActionMap().get(actionKey); + } + + private static void acceptCompletion(JFrame frame, String completionToAccept) { + Window popup = findCompletionPopup(frame); + if (popup == null) { + throw new AssertionError("Completion popup is not visible"); + } + JList list = findCompletionList((Container) popup); + if (list == null) { + throw new AssertionError("Completion popup did not expose its choices"); + } + int index = -1; + for (int i = 0; i < list.getModel().getSize(); i++) { + Object value = list.getModel().getElementAt(i); + if (value instanceof Completion completion && completionToAccept.equals(completion.getInputText())) { + index = i; + break; + } + } + if (index < 0) { + throw new AssertionError("Completion popup did not contain " + completionToAccept); + } + list.setSelectedIndex(index); + java.awt.Rectangle bounds = list.getCellBounds(index, index); + int x = bounds.x + bounds.width / 2; + int y = bounds.y + bounds.height / 2; + long now = System.currentTimeMillis(); + list.dispatchEvent(new MouseEvent(list, MouseEvent.MOUSE_CLICKED, now, 0, x, y, 2, false, + MouseEvent.BUTTON1)); + } + + private static Window findCompletionPopup(JFrame frame) { + for (Window window : frame.getOwnedWindows()) { + if (window.isVisible() + && "org.fife.ui.autocomplete.AutoCompletePopupWindow".equals(window.getClass().getName())) { + return window; + } + } + return null; + } + + private static boolean isCompletionPopupVisible(JFrame frame) { + for (Window window : frame.getOwnedWindows()) { + if (window.isVisible() + && "org.fife.ui.autocomplete.AutoCompletePopupWindow".equals(window.getClass().getName())) { + return true; + } + } + return false; + } + + private static JList findCompletionList(Container container) { + for (Component component : container.getComponents()) { + if (component instanceof JList list) { + return list; + } + if (component instanceof Container child) { + JList list = findCompletionList(child); + if (list != null) { + return list; + } + } + } + return null; + } + + private static JSyntaxTextArea findTextArea(Container container) { + for (Component component : container.getComponents()) { + if (component instanceof JSyntaxTextArea textArea) { + return textArea; + } + if (component instanceof Container child) { + JSyntaxTextArea textArea = findTextArea(child); + if (textArea != null) { + return textArea; + } + } + } + return null; + } + + public record Result(String text, boolean completionActionInstalled, boolean completionAccepted, + boolean popupVisible) { + } +} diff --git a/src/dist/src/dist/expected_release_artifacts.txt b/src/dist/src/dist/expected_release_artifacts.txt index 93e4744af9e..24f67410500 100644 --- a/src/dist/src/dist/expected_release_artifacts.txt +++ b/src/dist/src/dist/expected_release_artifacts.txt @@ -8,6 +8,7 @@ com.fasterxml.jackson.core:jackson-annotations com.fasterxml.jackson.core:jackson-core com.fasterxml.jackson.core:jackson-databind com.fasterxml.woodstox:woodstox-core +com.fifesoft:autocomplete com.fifesoft:rsyntaxtextarea com.github.ben-manes.caffeine:caffeine com.github.weisj:darklaf-compatibility diff --git a/src/licenses/build.gradle.kts b/src/licenses/build.gradle.kts index ebaed7acae5..e20424c7506 100644 --- a/src/licenses/build.gradle.kts +++ b/src/licenses/build.gradle.kts @@ -109,6 +109,11 @@ val gatherBinaryLicenses by tasks.registering(GatherLicenseTask::class) { expectedLicense = SpdxLicense.BSD_2_Clause } + overrideLicense("com.fifesoft:autocomplete") { + expectedLicense = SpdxLicense.BSD_3_Clause + licenseFiles = "autocomplete" + } + for (mig in listOf("com.miglayout:miglayout-core", "com.miglayout:miglayout-swing")) { overrideLicense(mig) { expectedLicense = SimpleLicense("BSD", uri("http://www.debian.org/misc/bsd.license")) diff --git a/src/licenses/licenses/autocomplete/LICENSE.md b/src/licenses/licenses/autocomplete/LICENSE.md new file mode 100644 index 00000000000..9933cbd7dab --- /dev/null +++ b/src/licenses/licenses/autocomplete/LICENSE.md @@ -0,0 +1,25 @@ +Copyright (c) 2021, Robert Futrell +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the distribution. +* Neither the name of the author nor the names of its contributors may + be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/src/protocol/java/src/main/java/org/apache/jmeter/protocol/java/sampler/JSR223SamplerBeanInfo.java b/src/protocol/java/src/main/java/org/apache/jmeter/protocol/java/sampler/JSR223SamplerBeanInfo.java index 9fa2095772e..a559583d4c8 100644 --- a/src/protocol/java/src/main/java/org/apache/jmeter/protocol/java/sampler/JSR223SamplerBeanInfo.java +++ b/src/protocol/java/src/main/java/org/apache/jmeter/protocol/java/sampler/JSR223SamplerBeanInfo.java @@ -17,11 +17,12 @@ package org.apache.jmeter.protocol.java.sampler; +import org.apache.jmeter.gui.util.JSR223Completion; import org.apache.jmeter.util.JSR223BeanInfoSupport; public class JSR223SamplerBeanInfo extends JSR223BeanInfoSupport { public JSR223SamplerBeanInfo() { - super(JSR223Sampler.class); + super(JSR223Sampler.class, JSR223Completion.Binding.SAMPLE_RESULT); } } diff --git a/src/protocol/java/src/test/java/org/apache/jmeter/protocol/java/sampler/JSR223SamplerGuiCompletionTest.java b/src/protocol/java/src/test/java/org/apache/jmeter/protocol/java/sampler/JSR223SamplerGuiCompletionTest.java new file mode 100644 index 00000000000..6dcbd2b2d2a --- /dev/null +++ b/src/protocol/java/src/test/java/org/apache/jmeter/protocol/java/sampler/JSR223SamplerGuiCompletionTest.java @@ -0,0 +1,128 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to you under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.jmeter.protocol.java.sampler; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeFalse; + +import java.awt.GraphicsEnvironment; + +import org.apache.jmeter.test.gui.JSR223GuiCompletionTestSupport; +import org.junit.jupiter.api.Test; + +class JSR223SamplerGuiCompletionTest { + + @Test + void completesSamplerBindingThroughTheDisplayedTestBeanEditor() throws Exception { + assumeFalse(GraphicsEnvironment.isHeadless()); + JSR223Sampler sampler = new JSR223Sampler(); + String script = "SampleResult.getResponseC"; + + JSR223GuiCompletionTestSupport.Result result = JSR223GuiCompletionTestSupport.invoke( + JSR223Sampler.class, sampler, script, script.length(), "SampleResult.getResponseCode"); + + assertTrue(result.completionActionInstalled()); + assertTrue(result.popupVisible()); + assertTrue(result.completionAccepted()); + assertEquals("SampleResult.getResponseCode()", result.text()); + } + + @Test + void insertsMethodArgumentPlaceholdersInTheInstalledEditor() throws Exception { + assumeFalse(GraphicsEnvironment.isHeadless()); + JSR223Sampler sampler = new JSR223Sampler(); + String script = "vars.pu"; + + JSR223GuiCompletionTestSupport.Result result = JSR223GuiCompletionTestSupport.invoke( + JSR223Sampler.class, sampler, script, script.length(), "vars.put"); + + assertTrue(result.completionActionInstalled()); + assertTrue(result.completionAccepted()); + assertEquals("vars.put(name, value)", result.text()); + } + + @Test + void completesThreadContextBindingThroughTheDisplayedTestBeanEditor() throws Exception { + assumeFalse(GraphicsEnvironment.isHeadless()); + JSR223Sampler sampler = new JSR223Sampler(); + String script = "ctx.getThreadN"; + + JSR223GuiCompletionTestSupport.Result result = JSR223GuiCompletionTestSupport.invoke( + JSR223Sampler.class, sampler, script, script.length(), "ctx.getThreadNum"); + + assertTrue(result.completionActionInstalled()); + assertTrue(result.completionAccepted()); + assertEquals("ctx.getThreadNum()", result.text()); + } + + @Test + void typingParenthesisAfterSelectingVariablePreservesTheTypedCharacter() throws Exception { + assumeFalse(GraphicsEnvironment.isHeadless()); + JSR223Sampler sampler = new JSR223Sampler(); + String script = "var"; + + JSR223GuiCompletionTestSupport.Result result = JSR223GuiCompletionTestSupport.typeOpeningParenthesis( + JSR223Sampler.class, sampler, script, script.length()); + + assertTrue(result.completionActionInstalled()); + assertTrue(result.popupVisible()); + assertEquals("var(", result.text()); + } + + @Test + void completionDoesNotDuplicateAnExistingCallSuffix() throws Exception { + assumeFalse(GraphicsEnvironment.isHeadless()); + JSR223Sampler sampler = new JSR223Sampler(); + String script = "ctx.getThreadNum()"; + + JSR223GuiCompletionTestSupport.Result result = JSR223GuiCompletionTestSupport.invoke( + JSR223Sampler.class, sampler, script, "ctx.getThreadNum".length(), null); + + assertTrue(result.completionActionInstalled()); + assertEquals(script, result.text()); + } + + @Test + void doesNotCompleteJMeterBindingInsideAnotherIdentifier() throws Exception { + assumeFalse(GraphicsEnvironment.isHeadless()); + JSR223Sampler sampler = new JSR223Sampler(); + String script = "def my$ctx = [id: 42]\nmy$ctx.getThreadN"; + + JSR223GuiCompletionTestSupport.Result result = JSR223GuiCompletionTestSupport.invoke( + JSR223Sampler.class, sampler, script, script.length(), null); + + assertTrue(result.completionActionInstalled()); + assertFalse(result.popupVisible()); + assertEquals(script, result.text()); + } + + @Test + void bsfEditorDoesNotInstallCompletionForCommonBindingText() throws Exception { + assumeFalse(GraphicsEnvironment.isHeadless()); + BSFSampler sampler = new BSFSampler(); + String script = "vars.pu"; + + JSR223GuiCompletionTestSupport.Result result = JSR223GuiCompletionTestSupport.invoke( + BSFSampler.class, sampler, script, script.length(), null); + + assertFalse(result.completionActionInstalled()); + assertEquals(script, result.text()); + } +} diff --git a/xdocs/changes.xml b/xdocs/changes.xml index 38335903b63..b9ed1d8d4a0 100644 --- a/xdocs/changes.xml +++ b/xdocs/changes.xml @@ -86,6 +86,7 @@ Summary
  • 63576358 Ensure writable directories when copying template files while report generation.
  • 65096675 Synchronize recent file menu across multiple JVMs. Contributed by Corneliu C (https://github.com/KingRabbid)
  • 6596Fallback to English locale when loading test plans that use string values for enum properties, so old sample plans load correctly even with non-English locales.
  • +
  • 45406860Provide Ctrl+Space code completion for JMeter bindings in JSR223 script editors.
  • HTTP Samplers and Test Script Recorder

    diff --git a/xdocs/usermanual/component_reference.xml b/xdocs/usermanual/component_reference.xml index e4b28ef878e..8dd3c9300a7 100644 --- a/xdocs/usermanual/component_reference.xml +++ b/xdocs/usermanual/component_reference.xml @@ -1223,6 +1223,10 @@ To benefit from this feature: +

    In JSR223 script editors, press Ctrl+Space to complete JMeter bindings and selected methods on those +bindings, for example vars.get. Completion is not activated automatically. On macOS, if +Ctrl+Space is assigned to switching input sources, change that system shortcut so the key press can reach +JMeter.

    Cache size is controlled by the following JMeter property (jmeter.properties): jsr223.compiled_scripts_cache_size=100 Unlike the , the interpreter is not saved between invocations.