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

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);

Related

Extracting corresponding values in JSR223 post processor in JMeter Randomly

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

How to remove the characters �� from the JSON response using Jmeter?

Below is the JSON Response from the Server, How to remove the characters �� from the below Response using Jmeter
Response :
{"_id":"5d56cc5c31acfd001298e863","test_id":"5d56cc593801370012bdb2bb","display_order":"1","question_type":"MULTIPLE CHOICE","isbn":"9780393630749","status":"added","question":{"_id":"5d56cc5c31acfd001298e864","questionId":"5d4262bb56c1d800122fcb48","QuestionTitle":{"key":"","value":"","valueRTF":"","valueHtml":"��������\n
I have written the groovy Script. but it is not removing the char.
def response = prev.getResponseDataAsString();
def var1= response.replaceAll("\�", "");
and I need to use this Var1 in another request.
Most probably you're seeing these question marks due to encoding problems, try setting file.encoding property to UTF-8 in system.properties file and restart JMeter, most probably you will see normal text instead of the question marks.
If for some reason the above hint is not applicable I would recommend replacing the whole valueHtml attribute value using JsonBuilder, the relevant code would be something like:
def builder = new groovy.json.JsonBuilder(new groovy.json.JsonSlurper().parse(prev.getResponseData()))
builder.content.question.QuestionTitle.valueHtml = ''
vars.put('Var1', builder.toPrettyString())
As the result you will have the same JSON structure with empty valueHtml attribute.
More information:
Groovy: Parsing and producing JSON
Apache Groovy - Why and How You Should Use It
As it is a JSON Response, add JSON Extractor Post Processor to the Parent Sampler from where the Response is expected. Extract whole JSON with following settings:
Now, use a JSR223 Sampler, with following code in script area:
String var1 = vars.get("jsonOutput");
log.info("Output: " + var1);
String replaceString=var1.replace('?','-'); // replace with whatever you want to, I am replacing it with '-'
log.info("Output: " + replaceString);
vars.put("NewString", replaceString);
Afterwards, you can use ${NewString} wherever you want.

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:

JMeter - Using response data as variable

The response I get back from a post is just a plain text guid seen here I'd like to pull this guid and use it in a variable for my following Get statement:
post response data
And I've tried a bunch of configurations in my regular expression extractor.
But it just ends up pulling Null when what I want is that guid.
Null
I'm new to jmeter - so thank you in advance for the help.
If you need the whole response use the following Regular Expression Extractor configuration:
Reference Name: response
Regular Expression: (?s)(^.*)
Template: $1$
As per How to Extract Data From Files With JMeter guide:
() = grouping
(?s) = single line modifier
^ = line start
. = wild-card character
* = repetition
So it will return the whole response.

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