How write BeanShellPostProcessor script for comparing two values - jmeter

I want compare two values and pick which one is equal to second variable.
I have written code like below in BeanShellPostProcessor
HitID = vars.get("AddPrpc139");
b=139
if(HitID.equals(b))
{
log.info("......value=");
}else
{
log.info("......value=");
}
But i am getting below error
2018-11-27 14:48:53,504 ERROR o.a.j.u.BeanShellInterpreter: Error invoking bsh method: eval In file: inline evaluation of: `` HitID = vars.get("AddPrpc139"); b=139 if(HitID.equals(b)) { log.info("......val . . . '' Encountered "if" at line 4, column 1.
2018-11-27 14:48:53,504 WARN o.a.j.e.BeanShellPostProcessor: Problem in BeanShell script: org.apache.jorphan.util.JMeterException: Error invoking bsh method: eval In file: inline evaluation of: `` HitID = vars.get("AddPrpc139"); b=139 if(HitID.equals(b)) { log.info("......val . . . '' Encountered "if" at line 4, column 1.

Java/Beanshell expect ; at end of the line. Also b can be inlined
HitID = vars.get("AddPrpc139");
if("139".equals(HitIDb))
{
Also consider moving to JSR223 PostProcessor

You need to follow Java syntax rules, to wit you need to add a semicolon after b=139 line.
You should also surround this 139 with quotation marks otherwise JMeter will be comparing a String with an Integer and you will always get into else branch even if the values will be the same
Amended code:
HitID = vars.get("AddPrpc139");
b = "139";
if (HitID.equals(b)) {
log.info("Values are equal, expected: " + b + ", got: " + HitID);
} else {
log.info("Values are NOT equal, expected: " + b + ", got: " + HitID);
}'
Demo:
Be aware that according to JMeter Best Practices you should be using JSR223 PostProcessor with Groovy language starting from JMeter 3.1. Groovy is more modern language, it is compatible with latest Java features and it has much better performance. Check out Apache Groovy - Why and How You Should Use It article for more details.

Related

Getting error in accessing Jmeter variables (variable_MarchNr) in yaml in beanshell script

I am trying to bulk edit one entity called issues, I call GetIssues API and via json extractor, get all issueId's in variable "issueIds"
json extractor to extract issueIds
Now I want to pass these Ids in other api bulk edit issues, If I directly use these array in next API, I get below error:
{"details":"Unexpected token $ in JSON at position 19","metadata":{}}
So I used to below code in Beanshell Post processor:
var mylist;
props.put("mylist", new ArrayList());
log.info("Detected " + vars.get("issueIds_matchNr") + " issueIds");
for (int i=1; i<= Integer.parseInt(vars.get("issueIds_matchNr")); i++) {
log.info("IDs # " + i + ": " + vars.get("issueIds_" + i));
props.get("mylist").add('"' + vars.get("issueIds_" + i) + '"' );
}
log.info(props.get("mylist").toString());
var issueIdList;
vars.put("issueIdList", props.get("mylist").toString());
log.info(vars.get("issueIdList"));
In my next api call if I pass issueIdList variable, then this works fine in jmeter.
sample variable values in debug sampler are like:
issueIdList=["555bcfc2", "33974d2c", "e58db1d6"]
issueIds_1=555bcfc2
issueIds_2=33974d2c
issueIds_3=e58db1d6
issueIds_matchNr=3
Problem I am facing if I convert my jmx2yaml and tried to run this file with
bzt issues.yml
then while executing above shell script, these issueIds_matchNr, issueIds_3 are not detected, I get below error;
2022-05-29 08:26:10,785 INFO o.a.j.e.J.JSR223PostProcessor: Detected null issueIds
2022-05-29 08:26:10,795 ERROR o.a.j.e.JSR223PostProcessor: Problem in JSR223 script, JSR223PostProcessor
javax.script.ScriptException: Sourced file: eval stream : Method Invocation Integer.parseInt : at Line: 4 : in file: eval stream : Integer .parseInt ( vars .get ( "issueIds_matchNr" ) )
Target exception: java.lang.NumberFormatException: null
in eval stream at line number 4
at bsh.engine.BshScriptEngine.evalSource(BshScriptEngine.java:87) ~[bsh-2.0b6.jar:2.0b6 2016-02-05 05:16:19]
My Yaml script is:
- extract-jsonpath:
issueIds:
default: NotFound
jsonpath: $..id
follow-redirects: true
jsr223:
- compile-cache: true
execute: after
language: beanshell
parameters: issueIds
script-file: script.bsh
label: Get Issue Id's
method: GET
url: https://${BASE_URL1}/${PROJECT_ID}/issues?limit=5&sortBy=-displayId&filter%5Bvalid%5D=true
You're missing one important bit: setting the Match Nr in your Taurus YAML
The correct definition of the JSON Extractor would be something like:
extract-jsonpath:
issueIds:
jsonpath: $..id
match-no: -1 #this is what you need to add
Also be informed that starting from JMeter 3.1 it's recommended to use Groovy as the scripting language so consider migrating, it will be as simple as removing the first line from your script.bsh

Jmeter BeanShellSampler error: Error invoking bsh method: eval import org.apache.commons.io.FileUtils

I use BeanShell code loading 100s of sql files in jmeter:
import org.apache.commons.io.FileUtils;
File folder = new File("D:\\sql99");
File[] sqlFiles = folder.listFiles();
for (int i = 0; i < sqlFiles.length; i++) {
File sqlFile = sqlFiles[i];
if (sqlFile.isFile()) {
vars.put("query_" + i,sqlFile.getName(),
FileUtils.readFileToString(sqlFiles[i]));
}
}
but get error info :
17:42:03,301 ERROR o.a.j.u.BeanShellInterpreter: Error invoking bsh method: eval Sourced file: inline evaluation of: ``import org.apache.commons.io.FileUtils; File folder = new File("D:\sql99"); Fi . . . '' : Error in method invocation: Method put( java.lang.String, java.lang.String, java.lang.String ) not found in class'org.apache.jmeter.threads.JMeterVariables'
I want to get each sql execute time in jmeter results tree. How to fix code?
Thanks!
You're trying to call JMeterVariables.put() function which accepts 2 Strings as the parameters passing 3 Strings
The correct syntax is vars.put("variable-name", "variable-value"); so you need to decide how to amend this line:
vars.put("query_" + i, sqlFile.getName(), FileUtils.readFileToString(sqlFiles[i]));
so it would contain only 2 parameters instead of 3.
Also since JMeter 3.1 it's recommended to use JSR223 Test Elements and Groovy language for scripting mainly for performance reasons so it might be a good option for switching (the same code will work in Groovy without changes assuming you fix the issue with vars.put() function call)

Error on accessing Output Variable in beanshell preprocessor in Jmeter

I am unable to print 'Output Variable' value of foreach Controller in Beanshell Pre/Post-processor in Jmeter.
log.info("inside hash"+ ${current_file} ); //current_file is the Output variable name defined in foreach controller and has the value of current file path.
File file=new File(${current_file});
byte[] content = FileUtils.readFileToByteArray(file);
Whenever I execute the tests, I get this error:
2021-12-15 19:58:25,208 ERROR o.a.j.u.BeanShellInterpreter: Error invoking bsh method: eval In file: inline evaluation of: ``import org.apache.commons.io.FileUtils; import org.apache.jmeter.services.FileSe . . . '' Encountered "( "inside hash" + C :" at line 4, column 9.
Can anyone help me fix this error?
Don't inline JMeter functions or variables in form of ${current_file}, use vars shorthand for JMeterVariables class instance instead
Something like:
String current_file = vars.get("current_file");
log.info("inside hash"+ current_file );
File file=new File(current_file);
Don't use Beanshell, since JMeter 3.1 it's recommended to use JSR223 Test Elements and Groovy language for scripting, there is a chance that your code will just start working after switching to Groovy or at least you will get more informative errors.

Beanshell Assertion

Could you help me with this Beanshell Assertion code:
I need to add 3 AND conditions & in the 3rd AND condition I need to add OR condition as well and I have tried the following code and I am getting the error
"BeanShellInterpreter: Error invoking bsh method: eval Sourced file: inline evaluation of: ``String Response1 = prev.getResponseDataAsString(); String Response2 = prev.getRe . . . '' : Operator: '"||"' inappropriate for objects
"
Please click on the link to view the code I tried:
Your or condition should be between boolean expressions. So end your line with
&& (Response3.contains("Value4") || Response3.contains("Value5"))
Notice also that the convention for Java variables is starting with a lowerCase character as response3

jmeter internal functions failing BeanSHellInterpreter

I cannot seem to get past the BeanShellInterpreter whenever I try and use __FileToString built-in function in a BeanShell PreProcessor script. The FileContents variable does get populated, but the script fails and I cannot work with it. Here is the code and the error messages...
try {
Integer count=vars.get("SessionId").length()-5;
vars.put("vAuth", vars.get("v_username") + vars.get("SessionId").substring(count) + ":" );
log.info("Writing a info message");
${__FileToString(C:/tmp/DeltaConnectDemoTool_3_2_0S1_5515/bin/request.txt,,FileContents)};
log.info("Writing a second info message");
}
catch (Throwable ex ) {
log.error("Failed to do this or that", ex);
}
The Error is
2016/11/17 15:52:18 ERROR - jmeter.util.BeanShellInterpreter: Error invoking bsh method: eval In file: inline evaluation of: ``try { Integer count=vars.get("SessionId").length()-5; vars.put("vAuth", vars.get . . . '' Encountered ":" at line 5, column 8.
2016/11/17 15:52:18 WARN - jmeter.modifiers.BeanShellPreProcessor: Problem in BeanShell script org.apache.jorphan.util.JMeterException: Error invoking bsh method: eval In file: inline evaluation of: ``try { Integer count=vars.get("SessionId").length()-5; vars.put("vAuth", vars.get . . . '' Encountered ":" at line 5, column 8.
try putting the string path to file in double quotes, like:
${__FileToString("C:/tmp/DeltaConnectDemoTool_3_2_0S1_5515/bin/request.txt",,FileContents)};
That's why inlining functions or variables into the script body is not recommended. You have 2 alternative options:
Use the function in the "Parameters" section. If the functions returns some value you will be able to refer in later in the Beanshell code as Parameters or bsh.args[0] like:
Implement the function in the Beanshell code. In your case it can be FileUtils.readFileToString() function:
String FileContent = org.apache.commons.io.FileUtils.readFileToString(new File("request.txt"));
vars.put("FileContent", FileContent);
See How to Use BeanShell: JMeter's Favorite Built-in Component for some extra information on scripting in JMeter

Resources