Is it possible to remove empty query string parameters in jMeter? - 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

Related

Read data from CSV and create Json Array in Jmeter

I have One POST request and below is the My Body Payload .
{
"ABC": "ITBK1",
"Code": "AH01001187",
"ScheduleDate": "2021-09-02T22:59:00Z",
"FilterType": 2,
"FilterData": [
"LoadTest92","LoadTest93"
]
}
I'm passing the ContractorId to filterData as below.
{
"ABC": "ITBK1",
"Code": "AH01001187",
"ScheduleDate": "${startTo}",
"FilterType": 2,
"FilterData": ["${contractorId}"]
}
but it taking one id at a time for this Json. How can i send multiple data for this FilterData jsonArray from csv please help on this.
First of all don't post code (including CSV file content) as image
As per CSV Data Set Config documentation:
By default, the file is only opened once, and each thread will use a different line from the file. However the order in which lines are passed to threads depends on the order in which they execute, which may vary between iterations. Lines are read at the start of each test iteration. The file name and mode are resolved in the first iteration.
So it means that you need to go to the next iteration in order to read the next line.
If you want to send all the values from column J as the "FilterData" you could do something like:
Add JSR223 PreProcessor as a child of the request you want to parameterize
Put the following code into "Script" area:
def lines = new File('/path/to/your/file.csv').readLines()
def payload = []
lines.each { line ->
def contractor = line.split(',')[9]
payload.add(contractor as String)
}
vars.put('payload', new groovy.json.JsonBuilder(payload).toPrettyString())
That's it, use ${payload} instead of your ["${contractorId}"] variable in the HTTP request.
More information:
JsonBuilder
JMeterVariables
Apache Groovy - Why and How You Should Use It

Remove an HTTP Request PATH Variable if null

I have this script in JMeter, PUT method,
how can i remove a path variable if the value from the input data is blank?
I know i can remove this if the parameter were in the Parameter tab of the HTTP request using the remove Arguments, the thing is I have a value in the body data so I have to put the URL parameters in the path that's why remove arguments is not working anymore.
code:
if ("${thisfromCSV}" == "") {
sampler.getArguments().removeArgument("thisParameter");
}
this works if the parameter is located at the Parameters tab of the HTTP Request
Add JSR223 PreProcessor as a child of the HTTP Request you would like to modify
Put the following code into "Script" area:
def url = new URL("http://example.com" + sampler.getPath())
def params = url.query.split('&').collectEntries({ param ->
param.split('=').collect {
URLDecoder.decode(it, 'UTF-8')
}
})
if (vars.get('thisfromCSV') == '') {
params.remove('thisParameter')
}
def query = params.collect { k, v -> "$k=$v" }.join('&')
sampler.setPath(url.path + '?' + query)
That's it, the code will remove thisParameter from the Sampler's URL query string in case of thisfromCSV variable is empty.
See Apache Groovy - Why and How You Should Use It for more information on using Groovy scripting in JMeter tests.

Looping through JSON response + in JMETER

I am using Jmeter for performance testing and stuck at following point:
I am getting a JSON response from Webapi as follows:
PersonInfoList:
Person
[0]
{
id: 1
name: Steve
}
[1]
Person
{
id: 2
name: Mark
}
I need to get the ids based on the count of this JSON array and create a comma separated string as ("Expected value" = 1,2)
I know how to read a particular element using JSON Post processor or Regex processor but am unable to loop through the array and create a string as explained so that I can use this value in my next sampler request.
Please help me out with this: I am using Jmeter 3.0 and if this could be achieved without using external third party libs that would be great. Sorry for the JSON syntax above
Actually similar functionality comes with JSON Path PostProcessor which appeared in JMeter 3.0. In order to get all the values in a single variable configure JSON Path PostProcessor as follows:
Variable Names: anything meaningful, i.e. id
JSON Path Expressions: $..id or whatever you use to extract the ids
Match Numbers: -1
Compute concatenation var (suffix _ALL): check
As a result you'll get id_ALL variable which will contain all JSON Path expression matches (comma-separated)
More "universal" answer which will be applicable for any other extractor types and in fact will allow to concatenate any arbitrary JMeter Variables is using scripting (besides if you need this "expected value and parentheses)
In order to concatenate all variables which names start with "id" into a single string add Beanshell PostProcessor somewhere after JSON Path PostProcessor and put the following code into "Script" area
StringBuilder result = new StringBuilder();
result.append("(\"Expected value\" = ");
Iterator iterator = vars.getIterator();
while (iterator.hasNext()) {
Map.Entry e = (Map.Entry) iterator.next();
if (e.getKey().matches("id_(\\d+)")) {
result.append(e.getValue());
result.append(",");
}
}
result.append(")");
vars.put("expected_value", result.toString());
Above code will store the resulting string into ${expected value} JMeter Variable. See How to Use BeanShell: JMeter's Favorite Built-in Component article for more information regarding bypassing JMeter limitations using scripting and using JMeter and Java API from Beanshell test elements.
Demo:

How to post the exact number of values which are retrieved from post processor?

I'm landing into a page where some Customers listed out. I'm retriving all the Customer Ids by Regular Expression Extractor Post-Processor.
Now, in a subsequent request I need to pass those Ids. It's being passed as a 'Body Data' by the following format:
[19327,15947,14421,18813,20942]
Let say, there are 5 Customer Ids retrived, then I can use the variables for each record as follows:
Passing Variables: [${CustomerId_1},${CustomerId_2},${CustomerId_3},${CustomerId_5}]
Posting Variable Values: [19327,15947,14421,18813,20942]
But let say, there are only 3 Customer Ids retrived, and if I pass the variables as above then the sampler will fail because currently it just retrived 3 Customer Id records.
Passing Variables: [${CustomerId_1},${CustomerId_2},${CustomerId_3},${CustomerId_5}]
Posting Variable Values: [19327,15947,14421,${CustomerId_4},${CustomerId_5}]
How to deal with this issue, plz. do help.
Thanks in advance
Add Beanshell PreProcessor as a child of your 2nd request
Put the following code into the Pre-Processor's "Script" area
int customers = Integer.parseInt(vars.get("CustomerId_matchNr"));
StringBuilder requestBuilder = new StringBuilder();
requestBuilder.append("[");
for (int i = 1; i <= customers; i++) {
requestBuilder.append(vars.get("CustomerId_" + i));
if (i != customers) {
requestBuilder.append(",");
}
}
requestBuilder.append("]");
sampler.getArguments().getArgument(0).setValue(requestBuilder.toString());
The above code will build required request line depending on number of matches and automatically set request body.
Referenced classes:
vars - shorthand to JMeterVariables
sampler - provides access to the parent sampler, in case of HTTP Request it will be HTTPSamplerProxy
StringBuilder - comes with Java SDK
See How to Use BeanShell: JMeter's Favorite Built-in Component guide for more information on Beanshell scripting, explanation of pre-defined variables and some useful examples.
refName_matchNr will return the number of matches. So in your case CustomerId_matchNr will give you number of customerIDs.
Use a beanshell pre-processor to run a loop and construct the BodyData string and save it to a new variable, use that variable in your subsequent sampler.

Jmeter extract data using BeanShell PreProcessor and add parameters

Having the following request:
From this I extract using the Regular Expression Extractor the following string:
%5B1172%2C63%2C61%2C66%2C69%2C68%5D
I decode this using the urldecode function: ${__urldecode(${Groups_g2})}
Decoded: [1172,63,61,66,69,68]
On the following request I want to extract the values using the BeanShell PreProcessor to obtain a list of parameters like this one:
I know that I have to use sampler.addArgument but i can't figure how to extract data from the list and add the values as parameters.
Try the following:
Put ${__urldecode(${Groups_g2})} into Beanshell PreProcessor's Parameters input field
Enter the following code into Script area
String params = Parameters.substring(1, Parameters.length() - 1); // remove square brackets
int counter = 1;
for (String param : params.split(",")) {
sampler.addArgument("parameter" + counter, param);
counter++;
}
I have no idea what parameter names need to look like, hopefully above information will be helpful.
HTTP Request with no parameters:
Beanshell PreProcessor
Parameters in View Results Tree Listener
For more information on Beanshell scripting in Apache JMeter check out How to use BeanShell: JMeter's favorite built-in component guide.

Resources