How to change child sample result to successful in jmeter? - jmeter

I've made login process with the help of jmeter. In of of request samplers I'm expecting to get response code "401". I've added BeanShell Assertion
if (ResponseCode.equals("401") == true) {
SampleResult.setResponseOK();
SampleResult.setSuccessful(true);
}
And my Results Tree is looking like this now.
My question is - what i need to add to BeanShell in order to make child of the second sample green (passed) as well as it's parent sample?

The easiest way is using Response Assertion configured like:
If you are still looking for Beanshell solution - you need to process all sub-results along with the main result so you should amend your code like:
import org.apache.jmeter.samplers.SampleResult;
//process main sample
if (SampleResult.getResponseCode().equals("401")) {
SampleResult.setResponseCodeOK();
SampleResult.setSuccessful(true);
}
//process all subsamples
for (SampleResult subResult : SampleResult.getSubResults()){
if (subResult.getResponseCode().equals("401")){
subResult.setResponseCodeOK();
subResult.setSuccessful(true);
}
}
See How to Use BeanShell: JMeter's Favorite Built-in Component article for more information on using Beanshell in JMeter test scripts.

Related

Best way to validate entire Json response in JMeter

I would like to know best way to verify entire Json response in Jmeter. Can somebody help. Thanks.
The easiest way is use JSR223 Assertion and JsonSlurper class like:
Put the anticipated JSON into expected JMeter Variable using i.e. User Defined Variables test element like:
Add JSR223 Assertion as a child of the request you want to validate
Put the following code into "Script" area:
def expected = new groovy.json.JsonSlurper().parseText(vars.get('expected'))
def actual = new groovy.json.JsonSlurper().parse(prev.getResponseData())
if (expected != actual) {
AssertionResult.setFailure(true)
AssertionResult.setFailureMessage('Mismatch between expected and actual JSON')
}
If there will be any difference between expected and actual JSON - the sampler will be marked as failed

Jmeter assertion result listener as variable

My JMeter test plan looks like this:
HTTP Request
- Assertion
HTTP Request
- Assertion
HTTP Request
- Assertion
Assertion Result Listener
I'd like to define all assertion results from the listener as a variable and use that variable in a POST call to JIRA, so the description contains an overview of all assertions and failure and pass of each assertion.
Assertion Result Listener
I know I can save the assertion results to a file and upload that, but I need the assertion results as text in the JIRA. Any ideas how I can do that?
edit: this is for a functional test suite.
Add JSR223 Listener to your Thread Group
Put the following code into "Script" area
def result = vars.get('result')
StringBuilder builder = new StringBuilder()
if (result != null) {
builder.append(result).append(System.getProperty('line.separator'))
}
prev.getAssertionResults().each { assertionResult ->
builder.append(prev.getSampleLabel()).append(System.getProperty('line.separator'))
if (assertionResult.isFailure()) {
builder.append('\t').append(assertionResult.getFailureMessage()).append(System.getProperty('line.separator'))
}
}
vars.put('result', builder.toString())
props.put('result', builder.toString())
Add tearDown Thread Group to your Test Plan
Refer the generated string holding the assertion results using __P() function as ${__P(result,)}
Demo:
See Apache Groovy - Why and How You Should Use It article for more information on Groovy scripting in JMeter.

how to Bypass the Sampler based on previous response value in jmeter?

I have caught up in a situation, where in i need to verify the response of the Previous Sampler for one of the value and if the Value for that is [], then i need to trigger the below request or else then switch to another Sampler.
Flow:
Check Response of Sampler for One of the attribute
IF(attribute value==[])
Execute the Sampler under IF Conditions.
ELSE
New Sampler
Sample Response:
{"id":8,"merchant_id":"39","title":"Shirts-XtraLarge","subtitle":null,"price":110,"description":null,"images":"image_thumbs":[[]],"options":[],"options_available":[],"custom_options":[]}
I need to check if the attribute custom_options is empty or not! If Empty do some actions and if not empty do some other action !
Need if condition to simulate this!
Help is useful!
A nice to have feature in JMeter would be Else statement, but until then you will have to use 2 If Controllers
If Controller allows the user to control whether the test elements below it (its children) are run or not.
Assuming you hold your attribute value using regex/json/css/other post processor extractor add two condition, first is positive and under it the Sampler:
${__groovy("${attributeValue}" == "[]")}
Second is negative and under it add the New Sampler
${__groovy("${attributeValue}" != "[]")}
__groovy is encourage to use over default Javascript
Checking this and using __jexl3 or __groovy function in Condition is advised for performances
Go for Switch Controller
Add JSR223 PostProcessor as a child of the request which returns your JSON
Put the following code into "Script" area:
def size = com.jayway.jsonpath.JsonPath.read(prev.getResponseDataAsString(), '$..custom_options')[0].size()
if (size == 0) {
vars.put('size', 'empty')
} else {
vars.put('size', 'notempty')
}
Add Switch Controller to your Test Plan and use ${size} as "Switch Value"
Add Simple Controller as a child of the Switch Controller and give empty name to it. Put request(s) related to empty "custom_options" under that empty Simple Controller
Add another Simple Controller as a child of the Switch Controller and give notempty name to it. Put request(s) related to not empty "custom_options" under that notempty Simple Controller.
More information: Selection Statements in JMeter Made Easy

How to conditionally extract data with the if controller after sampling?

I am extracting the HTML response code from a samplier. I would like to use the if controller to conditionally extract more information if the right response code is returned.
So teh Get Message Response Extractor would save the response code to the variable: GetMessageResponse.
Then the If Controller would check if GetMessageResponse is 200:
If this is true then extract more information like this:
However I am not getting anything in ResponseText, what am I doing wrong?
You can do it in one shot if you switch to the JSR223 PostProcessor, the relevant Groovy code would be:
import com.jayway.jsonpath.JsonPath
if (prev.getResponseCode() == '200') {
def responseText = JsonPath.read(prev.getResponseDataAsString(),'$.MessageObj.Text').get(0)
vars.put('ResponseText', responseText)
}
else {
vars.put('ResponseText','Response code is: ' + prev.getResponseCode())
}
References:
Jayway JsonPath
Groovy: Parsing and producing JSON
Apache Groovy - Why and How You Should Use It
In JMeter what you do is extract whatever the response and set Default Value field to something that will be filled when response will not contain extraction, for example for JSON Extractor:
What you show will not work because you put Extractors in IfController, as there is no Sampler, nothing will happen due to scoping rules.
Also when you'll need for another thing to use If Controller, no need to extract response code, just use:
${JMeterThread.last_sample_ok}

read count of same response messages in thread group

I have thread group with single sampler.I have a scenario with 10 users to run for 1 hour duration. in view results tree showing different response data in every sampler's response data.can it possible to count how many times samplers get same response data.
{"success":false,"code":"104","message":"xx","status":412,"MessageType":"120","ResponseCode":"100","rilreplyDetails":"121"}
{"success":false,"code":"104","message":"yyy","status":412,"MessageType":"120","ResponseCode":"100","rilreplyDetails":"121"}
can I get a count of how many samplers get"xx" response,and how many for "yyy"?
One solution would be to define two variables in the Test Plan section, i.e: counter_xx and counter_yyy.
Then on the sampler request add one Regular Expression Extractor to extract the message value and finally use If Controller to specify which counter to increment.
The below image shows the structure for above solution.
Finally, you would be able to access the variable values by using ${counter_xx} or ${counter_yyy}.
The easiest would be doing this outside of JMeter, i.e. configure it to save response data by adding the next 2 lines to user.properties file:
jmeter.save.saveservice.output_format=xml
jmeter.save.saveservice.response_data=true
JMeter restart will be required to pick the properties up. Once your test is done inspect the resulting .jtl result file using your favorite XML editor.
See Configuring JMeter for more information on the approach.
Another option is using JSR223 Listener and the script like:
import org.apache.jmeter.engine.util.CompoundVariable
import org.apache.jmeter.functions.IterationCounter
def xxcounter = props.get("xxcounter")
if (xxcounter == null) {
xxcounter = new IterationCounter();
List<CompoundVariable> params = new ArrayList<>();
params.add(new CompoundVariable("false"));
xxcounter.setParameters(params);
}
def yycounter = props.get('yycounter')
if (yycounter == null) {
yycounter = new IterationCounter();
List<CompoundVariable> params = new ArrayList<>();
params.add(new CompoundVariable("false"));
yycounter.setParameters(params);
}
if (prev.getResponseDataAsString().contains('xx')) {
log.info('XX count: ' + xxcounter.execute(prev, sampler))
props.put('xxcounter', xxcounter)
}
if (prev.getResponseDataAsString().contains('yyy')) {
log.info('YYY count: ' + yycounter.execute(prev, sampler))
props.put('yycounter', yycounter)
}
The listener will scan current sampler response data and increment either this or that counter printing the current value to jmeter.log file.
Demo:
More information on Groovy scripting in JMeter: Apache Groovy - Why and How You Should Use It

Resources