Jmeter: Typed variable declaration : Method Invocation Double.parseDouble - jmeter

Hey I'm doing some beanshell scripting for API testing in jmeter. I've written quite a few jmeter scripts with beanshell and it works fine when using Integer.parseInt() method invocation, but I have a value with decimal places where my SQL returns a value of 20.00000 and my Json path extractor gets 20.0 so my test fails when comparing it. Because of this problem I decided to compare this values as double variables instead of Strings but I'm getting the error bellow when using Double.parseDouble on BeanShell.
2016/08/17 12:48:45 ERROR - jmeter.util.BeanShellInterpreter: Error invoking bsh method: eval Sourced file: inline evaluation of: print("Width Assertion..."); int Total_Printers_SQL = Integer.parseInt(vars.get . . . '' : Typed variable declaration : Method Invocation Double.parseDouble
2016/08/17 12:48:45 WARN - jmeter.assertions.BeanShellAssertion: org.apache.jorphan.util.JMeterException: Error invoking bsh method: eval Sourced file: inline evaluation of: print("Width Assertion..."); int Total_Printers_SQL = Integer.parseInt(vars.get . . . '' : Typed variable declaration : Method Invocation Double.parseDouble
Even with the errors displayed the value of the double variable is printed on Jmeter prompt as you can see below.
If anyone's a beanshell expert and could help me identify the error, that'd be awesome. Thanks!

If the number you get is not a valid Double (1.2s for example, or just null), you will get such exception. The cure is either checking that the value is double by RegEx, or simply trying to parse, and catching exception (note that Beanhell does not pass exceptions properly, so you will have to check for any exception, so it's better to limit it to that one line):
double x = 0.0; // default value
String value = vars.get("myVar");
try
{
x = Double.parseDouble(value);
}
catch(Exception e)
{
log.info("Cannot parse " + value + " as double");
}

Related

Jmeter beanshell post Processor double values update

Into a Beanshell PostProcessor
I have to increase a variable ( latitude_new) declared previously
I wrote following code
Please, could you help me to solve it?
I accept also other solutions belong JMeter World
Thank you so much
double example = Double.parseDouble(vars.get("latitude"));
double increment = 0.001;
double sum = example+increment;
vars.put("latitude_new",sum);
Into log viewer I get following error :
2023-01-16 10:07:26,757 ERROR o.a.j.u.BeanShellInterpreter: Error
invoking bsh method: eval Sourced file: inline evaluation of: ``
double example = Double.parseDouble(vars.get("latitude")); double
increment . . . '' :
Error in method invocation:
Method put( java.lang.String, double ) not found in
class'org.apache.jmeter.threads.JMeterVariables' 2023-01-16
10:07:26,758 WARN o.a.j.e.BeanShellPostProcessor: Problem in BeanShell
script: org.apache.jorphan.util.JMeterException:
Error invoking bsh method:
eval Sourced file: inline evaluation of: `` double example =
Double.parseDouble(vars.get("latitude")); double increment . . . '' :
Error in method invocation:
Method put( java.lang.String, double ) not found in
class'org.apache.jmeter.threads.JMeterVariables'your text
You cannot use vars.put() function providing a Double as an argument, the options are in:
Either convert the Double to the String first
Or consider using vars.putObject() function which takes an Object hence you can store literally anything there
Also be informed that starting from JMeter 3.1 it's recommended to use JSR223 Test Elements and Groovy language for scripting because Groovy performance is much better comparing to user scripting engines so consider migrating.

Pass a variable in bean-shell assertion Jmeter

I try to pass 2 variables to the BeanShell script of Jmeter but it fails with the error. However, if I pass a hardcoded string value, it works.
Beanshell assertion to compare variable AdID1 and MAdID1
String addrress1="${AdID1}";
String memberAddress1="${MAdID1}";
Failure1 = !addrress1.equals(memberAddress1);
if (Failure1) {
FailureMessage = "Variables are not equal. Expected \"" + addrress1 + "\" , actual:\"" + memberAddress1 + "\"";
}
if(addrress1.equals(memberAddress1)) {
log.info("Matched");
Error:BeanShellAssertion: org.apache.jorphan.util.JMeterException:
Error invoking bsh method
Don't inline JMeter Functions or Variables into scripts.
Try to use the JMeter variables in your scripts like this:
String addrress1= vars.get("AdID1");
String memberAddress1= vars.get("MAdID1");
It is advised to use JSR223 Test Elements and Groovy Language rather using BeanShell.
It is recommended to avoid scripting and use built-in JMeter Test Elements or Functions or Plugins and avoid scripting where possible so I would suggest going for Response Assertion.
The relevant configuration would be:
With regards to your script - it appears it's missing closing }.

JMeter Bean Shell PostProcessor with embedded special characters

I am extracting a variable from the HTTPReponse body which contains a string containing special characters. When I try to access the variablein the script, I am getting the following error. Is there a way to access these vars while preserving the special characters?
jmeter.util.BeanShellInterpreter: Error invoking bsh method: eval In file: inline evaluation of: `` token += "" + auQV8OGH47fz50YFm9rS/dQjTcUuGi55ryzC7S3YInNcaciCVR3/frSHwv8CE/mJD . . . '' Encountered "oSQ" at line 1, column 269.
Most probably you are accessing JMeter Variable in your script body as ${variable_name_here} which is not very recommended.
Beanshell should handle JMeter Variables without any issues given you access them via vars shorthand (or through "Parameters" section)
Given you have a JMeter Variable ${foo} the correct ways of accessing its value will be:
Using vars shorthand:
String foo = vars.get("foo");
Using "Parameters" section (assumes you have ${foo} there)
String foo = Parameters;
String foo = bsh.args[0];
Demo:
Other troubleshooting techniques:
You can add debug() command to the beginning of your script so debugging output will be printed into JMeter console window
You can put your Beanshell code inside the try block like:
try {
//your code here
}
catch (Throwable ex) {
log.error("Beanshell failure", ex);
throw ex;
}
See How to Use BeanShell: JMeter's Favorite Built-in Component article for more information on using Beanshell scripting in JMeter tests

JMeter BeanShell Assertion: Getting error when convert String to Long

Have a need to change the value from String to Long in BeanShell Assertion to do verification.
First Apporach
long balance_after_credit = Long.parseLong(String.valueOf("${balance_after_credit_from_db}"));
Second Approach
long balance_after_credit = Long.parseLong(vars.get("balance_after_credit_from_db"));
For instance, consider am getting a value as '743432545' for the variable balance_after_credit_from_db.
Error
org.apache.jorphan.util.JMeterException: Error invoking bsh method: eval Sourced file: inline evaluation of: ``long token_balance_after_credit = Long.parseLong(vars.get("token_balance_after_c . . . '' : Typed variable declaration : Method Invocation Long.parseLong
Weird thing is sometimes, I didn't get errors and the script is getting passed.
Can anyone please point out where am doing a mistake. TIA.
Inlining JMeter variables into code-based scripts is not something recommended so go for 2nd approach.
How do you know that exactly String is being returned from the database all the time? It easily can be any other object type, in fact any of described in the Mapping SQL and Java Types article. The way more safe approach will be something like:
if (vars.getObject("balance_after_credit_from_db") instanceof String) {
long balance_after_credit = Long.parseLong(vars.get("balance_after_credit_from_db"));
}
else {
log.error("Unexpected \balance_after_credit_from_db\" variable type");
log.error("Expected: String, Actual: " + vars.getObject("balance_after_credit_from_db").getClass().getName());
throw new Exception("Unexpected variable type");
}
So in case of non-String JDBC query result you will be able to see the relevant message in jmeter.log file
See Debugging JDBC Sampler Results in JMeter article for more information on working with the entities coming from databases in JMeter tests
The second option
long balance_after_credit = Long.parseLong(vars.get("balance_after_credit_from_db"));
should work, provided you have a valid numeric variable value. For instance try to run something like this:
vars.put("x", "743432545");
long balance_after_credit = Long.parseLong(vars.get("x"));
It won't return any exception.
The problem is when the variable is not defined, has empty or non-numeric value. Then Long.parseLong will throw a NumberFormatException, which you shold catch and make use of (treat it as assertion failure):
String rawValue = vars.get("balance_after_credit_from_db");
long balance_after_credit = Long.MAX_VALUE; // initialize with some unrealistic value
try {
balance_after_credit = Long.parseLong(rawValue);
}
catch(NumberFormatException e) {
Failure = true;
FailureMessage = "Variable does not contain a valid long. It was " + rawValue + " instead";
}

Parsing error on trying to retrieve value of a variable extracted using JSON path extractor in Jmeter

I have to assert JSON response of an API.
So extracted value of a field (state) using JSON path extractor and save it in variable (Optinurl)
"state":"opted_in"
In the Debug Sampler, i see the value of Optinurl as
Optinurl=
[
: "opted_in"
]
Optinurl_1=opted_in
Optinurl_matchNr=1
When i try to retrieve value of variable Optinurl in Beanshell assertion as below,
String optinValue = ${Optinurl}
i get
ERROR - jmeter.util.BeanShellInterpreter: Error invoking bsh method: eval Sourced file: inline evaluation of: String optinValue = '["opted_in"]';'' Token Parsing Error: Lexical error at line 1, column 23. Encountered: "\"" (34), after : "\'["
2016/03/07 14:40:15 WARN - jmeter.assertions.BeanShellAssertion: org.apache.jorphan.util.JMeterException: Error invoking bsh method: eval Sourced file: inline evaluation of:String optinValue = '["opted_in"]';'' Token Parsing Error: Lexical error at line 1, column 23. Encountered: "\"" (34), after : "\'["
Thanks for your help in advance !
There is a JSON Path Assertion available via JMeter Plugins project, I believe you can do what you need via it.
The correct ways of initializing a JMeter Variable in Beanshell are:
String optinValue = "${Optinurl}";
or
String optinValue = vars.get("Optinurl");
The error you're getting is not connected with your Optinurl variable initialization. Looking into
Lexical error at line 1, column 23.
It appears you have some syntax error in the very first script line. So the options are:
Double check your code, make sure that parentheses, quotation marks, etc. are matching, statements are ending with semicolon, quotation marks in strings are escaped, etc.
Adding debug(); line as the first line of your script produces comprehensive debug output to STDOUT
Surrounding your code into try/catch block allows to having more informative error stracktraces
See How to Use BeanShell: JMeter's Favorite Built-in Component guide for more detailed information on using Beanshell in your JMeter tests.
I think you want to store [ : "opted_in" ] into a string variable so use this:
String optionValue= vars.get("Optinurl");
into your beanshell assertion
and if you want only opted_in to store in to a variable then use
String optionValue= vars.get("Optinurl_1");
Thanks Dmitri, Kaushlendra for replying.
I updated my script as below and it is working fine in GUI/command line. Since vars.get("Optinurl") returns ["opted_in"], so had to remove quotes and square brackets before comparing Strings.
String optinValue = vars.get("Optinurl"). replace("[","").replace("]","").replace("\"","");
String expectedState = "${EXPECTED_STATE}";
log.info(optinValue);
log.info(expectedState);
if(!optinValue.equals(expectedState)){
Failure = true;
FailureMessage = "Values of state field for Campaign id " + "${CAMPAIGN_ID}" + " dont match ";
}
I could not use String optinValue = vars.get("Optinurl_1") because it fails when i run tests from command line (works fine in GUI mode though)

Resources