How to add assertion on response message in jsr223 postprocessor using java code.
I tried using AssertionResult.setFailure(true); but it is not working
Use JSR223 Assertion instead JSR223 PostProcessor
JSR223 Assertion allows JSR223 script code to be used to check the status of the previous sample.
You are missing calling setFailureMessage
AssertionResult.setFailureMessage("Your reason for failure");
The script can check various aspects of the SampleResult. If an error is detected, the script should use AssertionResult.setFailureMessage("message") and AssertionResult.setFailure(true).
Something like:
def expectedMessage = 'some expected message'
def actualMessage = prev.getResponseMessage()
if (expectedMessage != actualMessage) {
AssertionResult.setFailure(true)
}
Should do the trick for you, in the above example prev stands for previous SampleResult
Demo:
More information: Scripting JMeter Assertions in Groovy - A Tutorial
Also get used to look at jmeter.log file, it might be the case your script fails somewhere somehow
Related
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
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
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.
I'm new to JMeter BeanShell PreProcessor function.
For a test I'm trying to print sample URL address.
From the tutorial I have the follownig code:
org.apache.jmeter.samplers.SampleResult;
String currentURL = SampleResult.getUrlAsString();
print(currentURL)
But I get error "Attempt to resolve method: getUrlAsString() on undefined variable", how to define this variable first?
This means the SampleResult does not exist.
You need to use prev as per this doc:
http://jmeter.apache.org/usermanual/component_reference.html#BeanShell_PreProcessor
Which references this javadoc:
http://jmeter.apache.org/api/org/apache/jmeter/samplers/SampleResult.html#getUrlAsString--
Be aware that since JMeter 3.1 it is recommended to use JSR223 Test Elements and Groovy language for any form of scripting in JMeter tests. So consider migrating to Groovy as soon as possible.
If you are using a PreProcessor it means that you don't have any SampleResult as sampler has not been yet executed. So you need to use sampler shorthand which is resolved into HTTPSamplerProxy like:
sampler.getUrl() as String
Demo:
More information: Apache Groovy - Why and How You Should Use It
I have Http Sampler body as follows,
{"Uname":"admin","Signature":"${Sign}","LoginTime":"${LogTime}","Action":"Do_Action"}
I have to get the value of "Action" from the above body, and that value nned to be sent to Pre-processor which will be useful to do further action.
Help me out of this...!!
Thanks!
I would recommend switching to JSR223 PreProcessor and Groovy language as:
Groovy has built-in JSON support
Groovy performs much better than Beanshell
Example Groovy code to extract "Action" from the request body and store it into ${action} JMeter Variable will look like:
def body = new groovy.json.JsonSlurper().parseText(sampler.getArguments().getArgument(0).getValue())
vars.put('action', body.Action)
See Groovy is the New Black article for more details.