Exclude blank values from csv file for JSON array in Jmeter - jmeter

I have jsonarray as [foodid1,foodid2,foodid3] .The values of these are reading from a csv file
csv file content
foodid1,foodid2,foodid3
10,12,14
if I don't want to pass the value to foodid2, the JSON array is being passed as [10,,14]
Instead, I wanted it to be passed as [10,14].
following is the JSON body:
customerdetails={
"regDate":${regDate},
"regNo":"${regNo}",
"firstName":"${fname}",
"lastName":"${lname}",
"dateOfBirth":"${dob}",
"bloodGroupId":0,
"mobileNo":"${mobile}",
"residenceNo":"${resdno}",
"officeNo":"${officeno}",
"email":"${email}",
"address1":"${adr1}",
"address2":"${adr2}",
"pincode":"${pin}",
"stateId":${stateid},
"city":"${city}"}
&customerhistory={
"historyId":[${food1},${food2},${food3},${food4}]}
how can I handle this situation in Jmeter
Thanks in Advance

The easiest solution would be replacing double commas with single commas on the fly using Beanshell PreProcessor
Add Beanshell PreProcessor as a child of the HTTP Request you're going to modify
Put the following code into the PreProcessor's "Script" area:
import org.apache.jmeter.config.Arguments;
import org.apache.jmeter.config.Argument;
import org.apache.jmeter.protocol.http.util.HTTPArgument;
Arguments oldArgs = sampler.getArguments();
Arguments newArgs = new Arguments();
for (int i = 0; i < oldArgs.getArgumentCount(); i++) {
Argument argument = oldArgs.getArgument(i);
String oldValue = argument.getValue();
String newValue = oldValue.replaceAll(",,", ",");
newArgs.addArgument(new HTTPArgument(argument.getName(), newValue));
}
sampler.setArguments(newArgs);
When you will run your test the PreProcessor will replace ,, with , for each parameter value.
See How to Use BeanShell: JMeter's Favorite Built-in Component article for more information about using Beanshell in JMeter tests.

Related

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:

Need to extract dynamic values from a string response in Jmeter

I need to extract the dynamic value "BSS1,DS1,HYS1,MS1,PTS1,QS1,USG1,YS1,RT10086,RT10081,RT10084,RT10082,OT10076,RT10083,UT10081,RT10085,"
from the string response "ACCOUNT_DETAIL_ACCOUNT_PRODUCT_SERVICES_EDIT_UPDATE_NameSpace.grid.setSelectedKeys(["BSS1","DS1","HYS1","MS1","PTS1","QS1","USG1","YS1","RT10086","RT10081","RT10084","RT10082","OT10076","RT10083","UT10081","RT10085"]);"
I have tried using the regular expression extractor :
Regular Expression :Keys\(\[\"(.+?)\",\"(.+?)\",\"(.+?)\",\"(.+?)\",\"(.+?)\",\"(.+?)\",\"(.+?)\",\"(.+?)\",\"(.+?)\",\"(.+?)\",\"(.+?)\",\"(.+?)\",\"(.+?)\",\"(.+?)\",\"(.+?)\",\"(.+?)\"]\)
template : $1$$2$$3$$4$$5$$6$$7$$8$$9$$10$$11$$12$$13$$14$$15$$16$
But the above regular expression works only if there are 16 values in the response. If the response contains less number of values, for example, "ACCOUNT_DETAIL_ACCOUNT_PRODUCT_SERVICES_EDIT_UPDATE_NameSpace.grid.setSelectedKeys(["BSS1","DS1"]);"
then the above regular expression doesn't work.
How can I extract the values in the response if the total count is unknown?
Also the double quotes in the response need to be omitted.
Is there any post processor using which dynamic values can be extracted?
Any help is greatly appreciated.
I believe it will be easier with some scripting.
Add Beanshell PostProcessor as a child of the request which returns aforementioned response
Put the following code into the PostProcessor's "Script" area:
String response = new String(data);
String rawKeys = response.substring(response.indexOf("[") + 1, response.indexOf("]")); // get the data inside square brackets
String keysWithoutQuotes = rawKeys.replaceAll("\"", ""); // remove quotes
String[] keyData = keysWithoutQuotes.split("\\,"); // get array of keys
for (int i = 0; i < keyData.length; i++) { // store array of keys into JMeter variables like
vars.put("Keys_" + (i +1), keyData[i]); // Keys_1=BSS1, Keys_2=DS1, etc.
}
vars.put("Keys_matchNr", String.valueOf(keyData.length)); // set Keys_matchNr variable
Where:
data is byte array containing parent sampler's response data
vars is a shorthand to JMeterVariables class which provides read/write access to JMeter Variables.
As a result you'll have variables like:
Keys_1=BSS1
Keys_2=DS1
..
Keys_matchNr=X
See How to Use BeanShell: JMeter's Favorite Built-in Component guide for additional information on Beanshell scripting in JMeter and some more examples

jmeter json path bean post processor

I have following entries that got extracted from Response using JSONPath extractor
entries = ["e-1553","e-1552","c-1052","e-1551","c-1050",
"e-1550","c-1049","e-1549","c-1051","e-1548",
"c-1048","e-1547","c-1047","e-1546","c-1045",
"e-1545","e-1544","c-1046","e-1543","e-1542",
"c-1026","e-1541","e-1540","e-1539","e-1538",
"c-1025","e-1537","e-1536","c-1024","f-1535",
"f-1534"]
I want to Iterate only over those entries that start with "e-" e.g. "e-1553,e-1552" etc. in my ForEach Controller and exclude other entries such as "c-1052, c-1050" etc.
So that I can use http://somesite.com/e-1553 etc.
How do I do that?
Given you have "entries" variable which holds that JSONArray you can get all the entries which start from "e-" as follows:
Add a Beanshell PostProcessor after the JSONPath Extractor
Put the following code into the PostProcessor's "Script" area:
JSONArray array = JSONArray.fromObject(vars.get("entries"));
int counter = 0;
for (int i=0;i < array.size();i++) {
String s = array.get(i).toString();
if (s.startsWith("e-"))
{
counter++;
vars.put("entry_" + counter, s);
}
}
It will produce variables like:
entry_1=e-1553
entry_10=e-1544
entry_11=e-1543
entry_12=e-1542
entry_13=e-1541
etc.
Then add ForEach Controller and configure it as follows:
Input variable prefix: entry
Start index for loop: 0
Output variable name: current_entry
Then in HTTP Request use ${current_entry} in the Path.
See How to use BeanShell: JMeter's favorite built-in component guide for more information on Beanshell scripting in JMeter.

how to extract value from request in Jmeter

Hi I am passing an email which is a time function like below
email = ${__time(MMddyy)}_${__time(HMS)}#yopmail.com
The value of this function changes eveytime I call the variable email.
I would like to store this value that is generated from this function into a variable and use that in other requests.
So currently I am getting two different emails in two different http requests since there is some time lag between my two http requests.
what I would like to do is .. store the email that is being sent in first http request by extracting the value from the request and pass it in the second http request.
POST data:
email=062915_160738%40yopmail.com
I know the way to extract from html response.. but is there any way to extract from request in jmeter?
If so can someone pls tell me how to achieve this?
thank you
Add a Beanshell PostProcessor as a child of the request which sends that POST request
Put the following code into the PostProcessor's "Script" area
import org.apache.jmeter.config.Argument;
import org.apache.jmeter.config.Arguments;
Arguments argz = ctx.getCurrentSampler().getArguments();
for (int i = 0; i < argz.getArgumentCount(); i++) {
Argument arg = argz.getArgument(i);
if (arg.getName().equals("email")) {
vars.put("EMAIL", arg.getValue());
break;
}
}
Refer generated value as ${EMAIL} where required.
Clarification:
above code will extract the value of email request parameter (if any) and store it to EMAIL JMeter Variable
ctx - shorthand to JMeterContext class instance
vars = shorthand to JMeterVariables class instance
Arguments and Argument - you can figure that out from JMeterContext JavaDoc
See How to use BeanShell: JMeter's favorite built-in component guide for more information on Beanshell scripting in JMeter.
Instead of the entire email, you can store the timestamp value in a variable and then use this timestamp variable to create email anywhere you want.
This way you will can have same email every where.
Add a Beanshell PostProcessor & Add following script:
import org.apache.jmeter.config.Argument;
import org.apache.jmeter.config.Arguments;
Arguments argz = ctx.getCurrentSampler().getArguments();
for (int i = 0; i < argz.getArgumentCount(); i++) {
Argument arg = argz.getArgument(i);
String req_body = arg.getValue();
vars.put("req_Json",req_body);
}
here we get the output in json format:
${req_Json}=
"email":"062915_160738%40yopmail.com",
"name":"abc xyz"
Now using jp#gc Json Path Extractor extract the value of email
Json expression = $['email']
and store the value in email_value_extacted
now use the variable ${email_value_extacted} anywhere you want to use.
finally,
${email_value_extacted} = 062915_160738%40yopmail.com
Is it HTTP Sampler? If so, just put into beanshell postprocessor:
String prevQuery = prev.getQueryString(); //your request text
System.out.println(prevQuery );
Also works for any samplers:
String prevQuery = prev.getSamplerData();
You can use Regular Expression extractor to extract the e-mail address from the request URL.
Add Regular Expression Extractor as a child of sampler which sends the post request.
In the Regular Expression Extractor select URL in Response Filed to check instead of Body.
You should be able to extract e-mail id from the request in this way.

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