How to Handle Dynamic Requests in JMeter - Which may/may not occur with each run - jmeter

In Web Application :
There is Single Page having Different Sections/Partitions
Each section Retrieves the Data with the Help of Filter Query.
If there is no matching Result, Section will Send below Request only :
Request 1: domain/search/jobs/csuser__search2_1413357426.1559
If the Query returns any matching Result, Section will Send below Two Requests:
Request 1: domain/search/jobs/csuser__search2_1413357426.1559
Request 2: domain/search/jobs/csuser__search2_1413357426.1559/results_preview
How can I manage Request 2, which may or may not occur with each run.
Currently I am manually Recording entire Network calls, Removing unnecessary ones & running it for 'N' Loop Count. How can I make sure while test is runing if any section has matching results Request 2 Should also be taken care which I might not have benn recorded on my first execution.

You can use combination of Beanshell PostProcessor and If Controller to work it around as follows:
Add a Beanshell PostProcessor as a child of the Query request
Put the following code into the PostProcessor's "Script" area:
int length = prev.getSubResults().length;
if (length > 1) {
String path = prev.getSubResults()[length - 1].getURL().getPath();
if (path.contains("results_preview")) {
vars.put("resultPresent", "true");
}
} else {
vars.put("resultPresent", "false");
}
Add an If Controller after the request
Depending on your scenario put on of the following conditions to If Controller's "Condition" input
${resultPresent}==true - children will be executed if the query returns results
${resultPresent}==false - children will be executed if the query doesn't return anything matching
Beanshell code does the following:
check how many requests were executed
if there were more than 1 requests, path of the last request is extracted
if path contains "results_preview" variable resultPresent is being set with the value of "true"
if there was only 1 request then resultPresent variable is false
References:
How to use BeanShell: JMeter's favorite built-in component
JMeter “if controller” with parameters
SampleResult class JavaDoc

As Dimitri said. The processor should run after (post) request 1. The if controller will then act on the results of the processor. Section two is only run when the condition is not "false".

Related

In jmeter, can we use few parameters with in what we declared in the HTTP request parameter section

In my case i have created one HTTP Request with all the possible parameter as below -
My .csv file is looking as below -
For some test case i need to send details in one or two parameter only, not for all. Now how can i do that in the same HTTP request without creating a new one?
Theoretically you can just send empty parameter values, just make sure that you have a blank value in the CSV file, i.e.:
param1,param2
foo,bar
baz,
,qux
Alternatively if you want to completely remove the parameters with empty values from the request you can add a JSR223 PreProcessor as a child of the HTTP Request sampler and 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)
This way JMeter will remove the parameters which don't have their respective values from the request:
In the above example sampler stands for HTTPSamplerProxy, see the JavaDoc for all available functions decriptions
More information on Groovy scripting in JMeter: Apache Groovy - Why and How You Should Use It

Looping in Jmeter

Looping test occurrence based on the data count retrieved from the JDBC request and also as input data for the HTTP request
I have test scenario where i need to use the DB output as the input criteria for the HTTP request. Based on the DB output count( from the first request) i need to loop the HTTP request and it data accordingly
I tried the logical Loop Count by passing the count variable from run time as ${TEST_ID_#}, still its not working.
I tried the logical Loop Count by passing the count variable from run time as ${TEST_ID_#}, still its not working.
Debug Sampler Output
You can extract the counter using Post Processor [either Regular Expression Extractor or JSON Extractor etc.]
Once you have extracted that count, now place a Loop controller as a parent of HTTP request.
For example. I am using User Defined Variable for loop Count:
Any reason for using ${TEST_ID_#} variable? If your Debug Sampler screenshot is full and correct you should be using ${KEY_ID_#} instead.
Also it might be a better idea to use ForEach Controller instead of the Loop Controller, the relevant configuration would be something like:
References:
How to Use ForEach Controller in JMeter
Using Regular Expressions in JMeter

JMeter check if status is 200

In my test plan I have 2 endpoints bid and win. And if bid endpoint return status 200 (it can also return 204, but I need only 200 so I can't use ${JMeterThread.last_sample_ok}) I need to run win endpoint.
I did:
create defined variable STATUS_OK
Create regular expressions extractor under bid request to get response code :
Add If controller and insert win request under that controller :
But if controller condition not working, Jmeter never run win request.
Any idea why it's not working? or maybe have I can debug it? I would be grateful for any help!!!
Updated including test plan structure:
bid requests - is CSV Data set config wit random jsons for each bid request (did like mentioned here)
thread - it's a thread with 200 users and 1 loop
bid - post request, for body I'm using one of json files ${__FileToString(/home/user/Downloads/jmeter/jsons/${__eval(${JSON_FILE})}.txt,,)}.
Also bid request include currency, bidid etc. it's Json
extractors, I'm using that data to generate correct win URL for
each bid.
if bid made - if controller discussed here
win - get request, where URL queries are different depends on bid response (using Json extractors). Url looks like:
win?auctionId=${AUCTIONID}&bidId=${BIDID}&impId=${IMPRESSIONID}&seatId=${SEAT}&price=${__javaScript((Math.random()* (4 - 1)+1).toFixed(4);)}&cur=${CUR}&adId=${ADID}
For If Controller You should use __groovy or __jexl3 function instead
Interpret Condition as Variable Expression? If this is selected, then the condition must be an expression that evaluates to "true" (case is ignored). For example, ${FOUND} or ${__jexl3(${VAR} > 100)}. Unlike the JavaScript case, the condition is only checked to see if it matches "true" (case is ignored).
Checking this and using __jexl3 or __groovy function in Condition is advised for performances
In your case use
${__groovy(vars.get("BID_STATUS") == vars.get("STATUS_OK") )}
Or
${__jexl3("${BID_STATUS}" == "${STATUS_OK}")}
You need to surround JMeter Variables references with quotation marks like:
"${BID_STATUS}" == "${STATUS_OK}"
Alternatively (better) you can get rid of this Regular Expression Extractor and switch If Controller's condition to use __groovy() function like:
${__groovy(prev.getResponseCode().equals(vars.get('STATUS_OK')),)}
More information: Apache Groovy - Why and How You Should Use It

Compare extracted variable across threads in JMeter

My goal is to POST to some URL from every thread in my thread group, which will create an asset somewhere. If all goes right, the first request will create the asset, then subsequent requests will see that the asset is already created (or in the process of being created), and will reuse that same asset.
The test plan:
Create N threads
HTTP Request - POST to some URL
Regular Expression Extractor - extract part of the response (the assetId generated by the POST request)
Verify that every thread extracted the same string from the response
My question:
What I don't have a clue how to do is the last step - verify that the value extracted from each thread is the same. How can this be done in JMeter?
To achieve your requirement, we need to share the value among all the threads.
Properties:
We can use properties to share a value. Lets assume a prop 'shared' is created with default value as blank "". Add the below code in the beanshell assertion. If it is blank, then a thread will add the value extracted from the RegEx. All other threads will just compare the value and if it does not match, it will fail it.
if(props.get("shared")==""){
props.put("shared") = "extracted";
}else{
if(!props.get("shared").equals("extracted")){
Failure = true;
}
}
Bsh.shared:
We can use the bsh.shared shared namespace to share the value among the threads and compare if the all the threads have the same value.
1.setup threadgroup will contain beanshell code like this to create a hashset.
import java.util.*;
if (bsh.shared.hashSet == void){
bsh.shared.hashSet=new HashSet();
}
bsh.shared.hashSet.clear();
2.The regular thread group will contain the code for extracting the value. Once the value is extracted, add it to the hashset which stores only the unique values. Any duplicate values are simply ignored.
bsh.shared.hashSet.add("value extracted");
3.teardown threadgroup will group will check the hashset for the size. If the size is more than 1, then it failed.
log.info(String.valueOf(bsh.shared.hashSet.size()));
I guess you can use Response Assertion.
The test plan:
Create N threads
HTTP Request - POST to some URL
Verify that every request has the same string in the response with Response Assertion
When you place this assertion on the Test plan level it applies to all the threads.

Manipulating the request body of HTTP thread based on the data extracted from the previous HTTP response

I want to manipulate the request body of HTTP thread based on the data extracted (using 'Regular Expression Extractor') from the previous HTTP response.
Here is the scenario:-
I have extracted the statusFlag and statusId from 'HTTP request 1' as:
Ref name: status
Reg. Exp: "statusFlag":"(\w+)","statusId":"(\w+)"
So, first I want to check that the value of statusFlag is 'New' or not.
If it is New then I have to proceed and feed statusId in next HTTP request or else display statusFlag mismatch.
Need help. Got stuck badly.
I believe Response Assertion is what you're looking for. Add it after the Regular Expression Extractor and configure it as follows:
Apply to: JMeter Variable -> statusFlag (or your reference name)
Pattern Matching Rules: Equals
Add New as a "Pattern to Test"
The assertion will check whether "statusFlag" is "New" and if not - it will fail the sampler and report the expected and the actual value.
Optionally you can add If Controller after the Response Assertion, use ${JMeterThread.last_sample_ok} as a condition and place 2nd request as a child of the If Controller - it will be executed only if "statusFlag" is new.
See How to Use JMeter Assertions in Three Easy Steps guide for more information on conditionally setting pass or fail criteria to requests in your JMeter test.
That's how your Jmeter project should look like.
Regular Expression Extractor stores extracted value in ct variable that can be accessed in If Controller as "${ct}" == "yourvalue" and, if true, can be also sent as a part of Request 2 body using the same ${ct} reference.
Jmeter project structure

Resources