Unable to pass value from beanshell preprocessor to sampler? - jmeter

I am trying to set value in beanshell inside "CANCEL ORDER" sampler and then use in sampler request body.
Trying
vars.put("orders",Arrays.toString(orderList.toArray()));
and accessing in json request body using ${orders} and its not passing value.
{
"orderIds": ${orders},
"tonce": "${tonce}"
}
POST data:
{
"orderIds": ${orders},

Your "not passing value" doesn't tell anything to us, if your Beanshell script doesn't work as expected first of all you need to check jmeter.log file for any suspicious entries, if your script fails somehow you will be able to see the error message in the log.
It worth checking your orderList variable value using Debug Sampler or printing it to the aforementioned jmeter.log file using log.info() shorthand
Since JMeter 3.1 it's recommended to use JSR223 Test Elements and Groovy language for scripting as:
Groovy has built-in JSON support
Groovy performs much better comparing to Beanshell

Related

Code in JMeter JSR223 Sampler comments is executed

Please tell me why the code in comments (both /*something*/ and //something) is executed using JSR223 Sampler & BeanShell sampler?
For example, I have:
and in the next JSR223 Sampler I have:
and the result is:
and the question is: why this code: "/${__setProperty(checkProperty, 50)};/" is executed regardless of that it is in comment and it is in wrong condition?
JMeter Functions are being executed in the place where they're found, no matter where it is, in Sampler label, comments section, sampler body, etc.
Actually inlining JMeter Functions and/or Variables into JSR223 scripts is not the best idea as
it might conflict with Groovy's string interpolation syntax
the function or variable might resolve into something causing script compilation failure or logic error
and last but not the least Groovy will cache the first occurrence and use it for subsequent iterations
So if you need to set a property - use props.put() function like
props.put('foo', 'bar')
And finally I'm not sure that using props.clear() is a good idea because there are some pre-defined JMeter properties (you can check yourself using Debug Sampler and View Results Tree listener combination) and it might result into unexpected behaviour if a test element will be relying on that property existence and/or value

I want to fail Beanshell sampler when my script is not conditions not satisfied

I am using Beanshell sampler with java code to compare the two files line by line. I want to fail the Beanshell sampler if comparison failed at any line. I see always my beanshell sampler is sucess in view results treee even the comparison failed or passed. So any one please give me a idea how to fail the sampler.
Note: I used Beanshell Assertion as well but its not worked.
View Results Tree Image
Beanshell Sampler with Beanshell Assertion
boolean differenceInFile = false;
SampleResult.setSuccessful(differenceInFile);
IsSuccess=differenceInFile;
line #2 and line #3 is what you need in your bean shell sampler to pass / fail depending on your file comparasion
Sample JMX File
It will show you as an xml, try to download it
There is SampleResult pre-defined variable which you can use for setting the sampler passed or failed, define response code, response message, response body, etc.
So something like:
if (there_are_differences) {
SampleResult.setSuccessful(false)
SampleResult.setResponseCode("500")
SampleResult.setResponseMessage("Files are different")
}
In the assertion you have AssertionResult for the same.
Also be aware that you should be using JSR223 Test Elements and Groovy language for scripting since JMeter 3.1 so it might be a good option for migration.
More information on JMeter API shorthands available for the JSR223 Test Elements - Top 8 JMeter Java Classes You Should Be Using with Groovy

How to correctly extract .pem key from request response with JSON extrator

I am using a jmeter JSON extractor for a JSON that looks like this
{"type":"rpc","tid":7,"action":"SecurityManager","method":"getAuthenticationKey","result":"-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAydpVbheWPx4ZMbxJ8yCm\ndcP2EaRZD2R4PUmuFhdDdvpxT\/so00\/22orFQMgw8hrgEZ07ISzarOlclchm7DtF\nzxUzjGon1d5OJ2\/61niT+bAyuykn7y63\/BEtGS3KsR9ez3Ds+JR04Tca\/ajUYAIo\nrtAdCuvQuWkk4ZmZWywa7n899KOndL8S3G0R9Bex5XwfXJoE2BC6Ww75gwkzANFX\nIqkTYeepIMai3B8H31VIW2aJXURbjgN4yrk4sOy5a5JqnPEeCPKJR3nCrZDZGG06\ncoq0swW8oegNI9SFsiIqpDQ6Fi4WqqH5EMNu6FrkF3HAqwwyGljnogGNdnkwajiu\nCQIDAQAB\n-----END PUBLIC KEY-----\n"}
I am trying to use that value (for example just show it)
log.info("${key}")
, but I get the error
o.a.j.p.j.s.JSR223Sampler: Problem in JSR223 script JSR223 Sampler, message: javax.script.ScriptException: org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
Script26.groovy: 8: expecting anything but ''\n''; got it anyway # line 8, column 39.
log.info("-----BEGIN PUBLIC KEY-----
Is there something i am not doing right ?
You should never use ${} in Groovy script in JMeter.
Instead do this:
log.info("Got key:{}", vars["key"]);
Provided your variable is named key
And this is how you would configure JSON Extractor:
Given you use JSR223 Test Elements already you don't need the JSON Extractor, the PEM key can be extracted and printed in one shot via JSR223 PostProcessor
Add JSR223 PostProcessor as a child of the request which returns the above JSON
Put the following code into "Script" area:
vars.put('key', new groovy.json.JsonSlurper().parse(prev.getResponseData()).result)
log.info(vars.get('key'))
Enjoy the printed variable in Log Viewer window
Of course you will be able to access it as ${key} in the other Test Elements
References:
Groovy: Parsing and Producing JSON
Apache Groovy - Why and How You Should Use It
Going forward please avoid using JMeter functions and/or variables in Groovy scripts as they conflict with Groovy GString Templates, may be resolved into something which cause compilation or runtime failure and non-compatible with Groovy caching of compiled scripts feature negatively impacting JMeter performance.

jmeter prev.getResponseDataAsString getting wrong return

I have a looping process that will extract some values from a web service (working) and loop through to pull all the information for each value (working).
I need to capture the whole return into a variable so I can modify it and post it back up later.
Screenshot:
When the "Baseline for ..." get kicks in, I get the proper response
But the "Get response" BeanShell PreProcessor is picking up old responses
Screenshot:
Given where my "Get response" object is, I would assume the:
vars.put("ResponceData", prev.getResponseDataAsString());
...would grab the response from "Baseline for ${ID} of site ${callSite}". Please help!
You are using wrong test element. Beanshell PreProcessor is being executed before request therefore it acts properly and returns response from the previous request instead of current one. You need to change it to the Beanshell PostProcessor and your code will start working as you expect.
It is recommended to avoid scripting where possible, if you need to save response data into a JMeter Variable you can do it using i.e. Regular Expression Extractor. According How to Extract Data From Files With JMeter article the relevant configuration will be something like:
Reference Name: ResponceData
Regular Expression: (?s)(^.*)
Template: $1$
If you face a JMeter limitation which cannot be worked around without using scripting make sure you are using the most performing scripting language, since JMeter 3.1 it is recommended to use JSR223 Test Elements and Groovy language

Print response json in jmeter using beanshell

I want print my json response in jmeter. I used beanshell but it shows error. Below is the line to print json object extracted in "data":
log.info("========"+${data});
Don't ever inline JMeter Functions or Variables into scripts, they may resolve into something which will cause compilation/interpretation failure, use code-based equivalents instead or pass functions/variables via "Parameters" section.
Exhibit A: using vars shorthand
log.info("========" + vars.get("data"));
Exhibit B: using "Parameters" section
Using Beanshell isn't the best scripting option, consider migrating to JSR223 Elements and Groovy language as Beanshell has known performance problems. Moreover, Groovy has built-in JSON support See Apache Groovy - Why and How You Should Use It for details.
And finally your ${data} variable might not be defined (i.e. your extractor fails), in this case you will get interpretation failure on attempt to refer it as ${data}, double check its value using Debug Sampler and View Results Tree listener combination.

Resources