Extracting corresponding values in JSR223 post processor in JMeter Randomly - jmeter

Hi All / Dimitri T Could you please post your valuable thoughts on extracting corresponding Values (For example ItemID1 and ItemSlot1) in one block of code randomly. I was able to write below Jsr223 postprocessor code and it is working fine. But when there are Blank spaces in ItemSlot id, then they are not fetching. From below code , i am passing ${rannum} under "Match No" in required regular expression.
Note: There will be more than 100 corresponding values. In some cases, we won't have ItemSlot1.i.e Blank/null values are appearing from server response. Hence, my script is not picking corresponding values.
Application Server Response:
"viewSaleListingLink": "https://Example.com/cars/item/search/-/listing/ItemID1/100011142",
"saleCountry": "",
"saleNote": "",
"bidLiveUrl": "https://Example.com/cars//registration?p_p_id=RegistrationPortlet_WAR_PWRWeb&p_p_lifecycle=1&p_p_state=normal&ItemSlot1=103009468",
JSR223PostProcessor Code
import java.math.MathContext;
import java.math.RoundingMode;
// Read occurance values from pervious response
def Max = Integer.parseInt( vars.get("ItemID1_matchNr"));
int min=1;
int rannum = min + (int) (Math.random() * ((Max - min) + 1));
log.info("Values id ="+rannum);
vars.put("rannum",rannum.toString());
enter image description here

If you need to extract a random match/pair of matches from the response using Regular Expression Extractor - it's sufficient just to provide 0 as the "Match No" and it will automatically fetch the random match group so you won't have to write any code:
Also be aware that Post-Processors are executed in the order they appear (upside down) so:
If your JSR223 PostProcessor is above the Regular Expression Extractor - ItemID1_matchNr will be undefined
If your JSR223 PostProcessor is below the Regular Expression Extractor - your rannum variable won't have any value
Also your response seems to be JSON so it makes sense switching to JSON JMESPath Extractor which is more powerful and convenient

Related

Count the number of occurences of a string in response data

I want to search a string from a response in jmeter and count the number of occurences based on which i want to use a if controller to run the next requests. I am stuck with the code for counting the occurences
You can do it in at least 2 ways:
Using Regular Expression Extractor:
Add Regular Expression Extractor as a child of the request.
Configure it as follows:
Reference Name: anything meaningful, i.e. count
Regular Expression: string you want to count, i.e. JMeter
Template: $1$
Match No: -1
The number of matches will be stored in ${count_matchNr} JMeter Variable
Using Beanshell PostProcessor
Add Beanshell PostProcessor as a child of the request
Put the following code into the PostProcessor's "Script" area
import org.apache.commons.lang.StringUtils;
String response = new String(data);
int count = StringUtils.countMatches(response, "JMeter");
log.info("Found " + count + " \"JMeter\" words at the " + prev.getUrlAsString() + " URL");
vars.put("count", String.valueOf(count));
You'll be able to refer the matches count as ${count} JMeter Variable
References:
JMeter Regular Expressions
How to Use BeanShell: JMeter's Favorite Built-in Component

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:

Extracting a value from jmeter response and exporting it to a csv file

I need to know how can I extract a value from response in jmeter and export it to a csv file.
Suppose my response is like this:
<ns3:UpdateConsumerResponse
xmlns:ns3="http://Pandora.NextGenCRM.Integrations.UpdateConsumerResponse"
xmlns:ns0="http://tempuri.org/"
xmlns:ns1="http://schemas.datacontract.org/2004/07/Pandora.Xrm.DataModel.Request"
xmlns:ns2="http://schemas.datacontract.org/2004/07/Pandora.Xrm.DataModel.Response">
<MasterConsumerID>
CRM-CONID-000000519344
</MasterConsumerID>
</ns3:UpdateConsumerResponse>
I need to extract the master consumer value and export it to an csv file.
First of all you have to add an regular expression extractor as a child of this request
and then mention below inputs
1.Reference Name: MasterConsumer (or any variable)
2.Regular expression: abc(.*?)d (suppose your value is like abcCRM-CONID-000000519344d
then provided reg ex will work, now replace abc with your left
boundary and d with right boundary which you can get from your response. if still you need more help then
please provide this value along with more text from both side )
3.Template: $1$
4.Match No:1
5.Default Value: null
now you have your value stored in MasterConsumer variable (apply debug sampler to verify). Just you need to write into csv file, so add beanshell post processor as a child of same request and write below code for printing data into csv file
MasterConsumer =vars.get("MasterConsumer");
f = new FileOutputStream("Path"-Output.csv",true);
p=new PrintStream(f);
this.interpreter.setOut(p);
p.println(MasterConsumer);
f.close();
Add XPath Extractor as a child of the request, which returns above value
Configure it as follows:
Check Use Namespaces box
Reference Name: anything meaningful, i.e. ID
XPath query: /ns3:UpdateConsumerResponse/MasterConsumerID/text()
Add Beanshell PostProcessor after the XPath Extractor
Add the following code into the PostProcessor's "Script" area:
import org.apache.commons.io.FileUtils;
String file = "path_to_your_file.csv";
String ID = vars.get("ID");
String newline = System.getProperty("line.separator");
FileUtils.writeStringToFile(new File(file),ID + newline, true);

Retrieving certain values from a variable jMeter beanshell script

Currently developing a script in jMeter, I need to retrieve x amount of values from a response then push those values into another HTTP request, here is the tricky part the response is a table which always changes (e.g. rows increase or decrease each time the test is run) so far I've created a Regex extractor which retrieves anything between the table now I need to create a beanshell post processor which retrieves the certain values from the variable retrieved by the Regex extractor and applies them to the HTTP request. I'm not to sure if this is the best way to do this so I am open to suggestions on doing this another way.
You need Beanshell PreProcessor applied to 2nd request, not PostProcessor applied to 1st request
I don't think that using Regular Expressions is a very good idea to parse HTML, I would suggest going for CSS/JQuery Extractor or XPath Extractor instead
Once you have required values in form of
var_1=foo
var_2=bar
var_MatchNr=2
You will be able to add these values to the 2nd HTTP Request like:
import java.util.Iterator;
import java.util.Map;
Iterator iter = vars.getIterator();
int counter = 1;
while (iter.hasNext())
{
Map.Entry e = (Map.Entry)iter.next();
if (e.getValue() != null)
{
if (e.getKey().toString().startsWith("var_") && e.getValue().toString().length() >0)
{
sampler.addArgument("param" + counter, e.getValue().toString());
counter++;
}
}
}

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

Resources