how to Bypass the Sampler based on previous response value in jmeter? - 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

Related

Is it possible to remove empty query string parameters in jMeter?

I want to test an endpoint using jmeter, that has a copule of query string parameters, one of which is optional, loading the values from a CSV file. The problem is, can I avoid sending the query string parameter if I don't have a value for it?
It is but it will require some Groovy coding
Add JSR223 PreProcessor as a child of the request which query string you want to modify (or according to JMeter Scoping Rules if you want to apply the approach to more than one request)
Put the following code into "Script" area:
def newData = new org.apache.jmeter.config.Arguments()
0.upto(sampler.getArguments().size() - 1, { idx ->
def arg = sampler.getArguments().getArgument(idx)
if (!arg.getValue().equals('')) {
newData.addArgument(arg)
}
})
sampler.setArguments(newData)
That's it, the PreProcessor will be executed before the HTTP Request sampler and will remove all arguments which don't have their respective values

JMETER : While condition is failing with syntax error

I have a scenario where in I need to wait for the response text .I need to send the same request till i get the required response text. I included my http samples in while loop with a counter. Now I am not able get the correct while condition.
Tried with below conditions.
${__javaScript(("${recordTypeLabel1}"!="asdf" && ${counter} < 5),)}
${__jexl3("${recordTypeLabel1}" != "asdf",)}
Both are failing. How to handle this?
Pleasae help.
Threadgroup
Once only controller Login
loop controller
HTTP req
HTTP req
While loop {
Counter
HTTP request
HTTP Request
JSON extractor
}
HTTP req
Once only Controller Logout
The correct syntax for the __jexl3() function would be:
${__jexl3("${recordTypeLabel1}" != "asdf" && ${__jm__While Controller__idx} < 5,)}
Don't use __javascript() function as it is some form of a performance anti-pattern, stick to __jexl3() or __groovy() functions if you need to script some extra logic
Also you don't need to introduce a Counter, since JMeter 5.0 you have a special pre-defined variable called ${__jm__While Controller__idx} which holds zero-based iteration number of the While Controller. (If you change the While Controller's label to something else - make sure to amend the variable accordingly)
Exit when loop number exceeds the threshold
Exit when variable value becomes expected:

Jmeter values mapping

How to achieve a kind of mapping between string and numeric values that can be used for comparison in assertion? Example:
MAP "DELIVERED"=0
"PENDING"=1
"WAITING"=2
sampler1 - extracted numeric_value=0
sampler2 - assert string value="DELIVERED" is equal to its numeric value
Please check the below test plan:-
I have used variable name from regular expression of 1st sampler in the switch controller like ${regVar}..Then used the second request 3 times i.e. 0,1,2 and used response assertion with the desired value like "DELIVERED"=0 for first sampler under switch i.e "0" then in second "PENDING"=1 i.e "1"..so on.
With this, based on the regEx value from 1st http sample, only one http request will be send for 2nd sampler and that request have it own assertion. I have tried with both positive and negative cases. Please change the assertion value based on your requirements.
Please check if it helps.
Be aware of JSR223 Assertion which allows you to use arbitrary Groovy code to define pass/fail criteria.
You can access the numeric_value using vars shorthand for JMeterVariables class like:
def numericValue = vars.get('numeric_value')
Example code:
def myMap = ['0':'DELIVERED', '1':'PENDING', '2':'WAITING']
def numericValue = vars.get('numeric_value')
log.info('Numeric value is: ' + numericValue)
log.info('Status is: ' + myMap.get(numericValue))
Demo:
More information: Scripting JMeter Assertions in Groovy - A Tutorial
Thanks Dmitri, implemented solution based on your suggestion and it suites fine.

In JMeter, How do i loop until a result is found

I have a request in Jmeter that I need to loop until I find the result I am looking for. I have read a few bits about a while controller but found them unhelpful as they seem to glance over vital information or are using an older version of Jmeter
I'm currently using Jmeter 5.0, and I have attempted to implement a while controller but failed as I think I do not understand how to properly handle the response, or even grab it, and then use it as a comparison to assert if the item exists.
I get a response from the HTTP request call response that looks a little somthing like this:
{"data":{"getIDs":{"Page": 1,"PageSize": 25,"PageCount": 1,"isFirstPage": true,"batches":[{"id":"b601a257-13fe-4de3-b779-a5922e89765a"},{"id":"b601a257-13fe-4de3-b779-a5922e89765b"},{"id":"b601a257-13fe-4de3-b779-a5922e89765c"}]}}
I need to recall the endpoint until I have found the ID I am looking for or cancel after 10 attempts
So after a bit of fumbling around I, I figured on my own answer that seems to work well. But I would suggest looking at other sources before taking mine as gospel.
The basic structure looks as follows:
Within a thread I set the variables then create the while loop as the next step. Within the While loop I created a counter then added the request I wanted to loop after. To make the loop work for me, I have three items sat under the request.
A Response Assertion: this check for a 200 status as the call should never fail
A Constant Timer: There is a delay between polls of the end point
A JSR223 Assertion: groovy code used ensure the while loop logic is handled
User Defined Variables:
Here i have setup two variables:
DONE: Done is a string value I alter if my JSR223 Assertion finds the values I'm looking for in the HTTP request
MyValue (this is dynamically driven in my actual test, for demo purpose, I’m just declaring a value to look for i.e. 12345)
While Controller:
I still feel i may not understand this correctly, however after some googling I came across the following code that works for me despite some errors in the JMeter console:
${__javaScript(("${DONE}" != "yep" && ${Counter} < 10),)}
This code is saying that the while loop will continue until either of these two conditions are met:
DONE, the variable created earlier, is equal to the value yep
Counter is less than 10 (Counter is declared beneath the while loop)
Counter:
this was a simple configuration step that just worked once I understood it needed to be within the while loop, i configured the following:
Starting value = 1
Increment = 1
Exported Variable Name = Counter
Ticked 'Track Counter independently for each user'
Ticked 'Reset counter on each thread group iteration'
(Exported Variable Name: you can call this whatever you want, I’ve named it counter for the purpose of this demo)
JSR223 Assertion:
This is a simple script assertion that just uses a Boolean and a couple of if statements to assert the state of the test.
import org.apache.commons.lang3.StringUtils;
def done = vars.get("DONE");
String response = prev.getResponseDataAsString(); //retrieves the http request response as text
String MyValue = vars.get("MyValue");
def counter = vars.get("Counter");
//Find Substring within response string and stor result as boolean
String container = response;
String content = MyValue;
boolean containerContainsContent = StringUtils.containsIgnoreCase(container, content);
//Check if the true condition is met and change the value so the loop exits
if (containerContainsContent == true){
log.info("------------------------Got Here");
vars.put("DONE", "yep");
}
//Force test to fail after 10 loops
if (Counter.toString() == "10"){
assert 1 == 2
}

How to change child sample result to successful in 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.

Resources