Extracting output from Jmeter response - jmeter

Sample Request1:
id=abcd&payment=paymentinitiate&ENCID=xyz&TOKENID=1234&APPTYPE=908&Mobile=ext
Sample Response1:
{
"RESPONSECODE": "100",
"TESTID": "200",
"ERRORDESC": "Success",
"DOMAINNAME": "TEST",
"TOTALCOUNT": "4"
}
Like above i need to give 100 requests and will be getting 100 separate responses(separate debug samplers) in Jmeter. I want to extract the value for ERRORDESC and DOMAINNAME available in each response in a separate common output file.
Kindly suggest a solution for this.

You can do it by adding a JSR223 PostProcessor and using the following code:
def counter = ctx.getThreadNum() // if you run 100 requests with 100 users
//def counter = vars.getIteration() if you run 100 requests with 1 user and 100 iterations
def response = new groovy.json.JsonSlurper().parse(prev.getResponseData())
new File('response-' + counter + '.txt') << response.ERRORDESC << ',' << response.DOMAINNAME
it will generate files response-0.txt, response-1.txt etc. with the data extracted from each response
More information:
Apache Groovy - Parsing and producing JSON
Apache Groovy: What Is Groovy Used For?

Related

Capture details from http request and response in jmeter

I am setting up a jmeter test plan for http requests and I want to create a table capturing some details from http request and response. I read http request from a file using CSV Data Set Config. My request and response formats are as follows
Http Request Format: {"TYPE":"<type>", "PAYLOAD": [<Array of data>]}
Http Response Format: {"RESPONSE":[<Array of data>]}
Things I want to capture for each request, response are TYPE from HTTP Request, Array Size of RESPONSE (or Array size of PAYLOAD) and Time Taken.
The jmeter version I am using is v5.2.1. Any inputs on how can I set this up?
Edit: My HTTP request is a POST request. I am looking to capture details from Request Body.
If you don't mind using JMeter Plugins you can:
Declare the variables from the CSV file as Sample Variables
Extract the number of matches from the response using JSON Extractor configured like:
Name of created variables: responsarray
JSON Path expressions: $.RESPONSE.*
Match Nr.: -1
the variable value you need to declare in the Sample Variables will be responsearray_matchNr
The above Sample Variables can be saved into a file using Flexible File Writer
If you cannot use the plugin you still can achieve the same using JSR223 Listener and the following Groovy code:
def result = new File('result.txt')
def request = new groovy.json.JsonSlurper().parseText(sampler.getArguments().getArgument(0).getValue())
def requestType = request.TYPE
def requestArray = request.PAYLOAD.size()
def response = new groovy.json.JsonSlurper().parse(prev.getResponseData())
def responseArray = response.RESPONSE.size()
def timeTaken = prev.getTime()
result << requestType << ',' << requestArray << ',' << responseArray << ',' << timeTaken << System.getProperty('line.separator')

HTTP request based on timestamp using Jmeter

I am trying to send HTTP requests using jmeter for which I am using a HTTP sampler. The http requests have a parameter TaskID and these parameters read from a CSV file. I just wanted to make changes on how the HTTP request will be send.
The CSV file looks like this
Time TaskID
9000 42353456
9000 53463464
9000 65475787
9300 42354366
9300 23423535
9600 43545756
9600 53463467
9600 23435346
Now I want to send request based on the Time. For example in Time 9000 there are 3 TaskID. So I want to send 3 HTTP requests with those TaskIDs at a time. Similarly for the other Times as well. Any idea on how to do it?
Update:
I created a minimal working example for one possible solution.
Basically I read the csv in a JSR223 Sampler and group it with following groovy code in "read csv" sampler:
import org.apache.jmeter.services.FileServer
current_dir = FileServer.getFileServer().getBaseDir().replace("\\","/")
csv_lines = new File(current_dir + "/test.csv").readLines()
times = []
csv_lines.each { line ->
line = line.split(",")
time = line[0]
task_id = line[1]
if (vars.getObject(time)){
tasks = vars.getObject(time)
tasks.add(task_id)
vars.putObject(time, tasks)
}
else{
times.add(time)
vars.putObject(time, [task_id])
}
}
times.eachWithIndex { time, i ->
vars.put("time_" + (i+1), time)
}
Notes:
(i+1) is used because the ForEach Controller will not consider the 0th element
I used "," as csv separator and omitted the header line
the "initialize task_ids" sampler holds following code:
.
time = vars.get("time")
tasks = vars.getObject(time)
tasks.eachWithIndex {task, i ->
vars.put(time + "_" + (i+1), task)
}
I hope, this helps!

jmeter: evaluate the values of JSON values

I am trying to test my API response using JSON assertion in JMeter, but couldn't find out on how to achieve it. The API returns 2 values, and I need to check if the difference between these two value are consistent
API response:
{
"start": "12759898",
"end": "12759907"
}
I've tried like the above, but it seems to be wrong, as its a JSONPath variable.
Could anyone guide on how to evaluate these values? is it possible to achieve this?
It looks like a job for JSR223 Assertion
Add JSR223 Assertion as a child of the request which returns the above JSON
Put the following code into "Script" area:
def response = new groovy.json.JsonSlurper().parse(prev.getResponseData())
def start = response.start as long
def end = response.end as long
def delta = end - start
if (delta != 10) {
AssertionResult.setFailure(true)
AssertionResult.setFailureMessage('Expected: 10, got: ' + delta)
}
If the difference between start and end will not be equal to 10 - the request will be marked as failed.
More information:
Groovy: Parsing and producing JSON
Scripting JMeter Assertions in Groovy - A Tutorial

JMeter - Saving post data from http requst sample to the csv file

I have a Http request with Body Data which can create individual user any time when it runs for example:
{"username":"fakeuser${__RandomString(5,abcdefghijklmnofqrst1234567,userno)}","email":"fakeuser${userno}#fakedomain.com","password":"blblabla123!","passwordRepeated":"blablabla123!"}
POST Data:
{"username":"fakeuser4mf7s","email":"fakeuser4mf7s#fakedomain.com","password":"blablabla123!","passwordRepeated":"blablabla123!"}
Is there any way to grab email and password value from the Post Data and save it to the same csv file any time when specific http request sample runs.
Add JSR223 PostProcessor as a chid of the HTTP Request sampler
Put the following code into "Script" area:
import groovy.json.JsonSlurper
def request = new JsonSlurper().parseText(sampler.getArguments().getArgument(0).getValue())
def email = request.email
def password = request.password
new File('test.csv') << email + ',' + password + System.getProperty('line.separator')
Once you execute your test the JSR223 PostProcessor will add the values of email and password objects into test.csv file (normally it should reside in "bin" folder of your JMeter installation)
References:
Groovy: Parsing and Producing JSON
Groovy Goodness: Working with Files
Apache Groovy - Why and How You Should Use It

How to Duplicate file using JMeter

I am trying to duplicate a file using JMeter,
The scenario:
Loading a JSON file. For example, {"name":"John","age":"$age_place"}
Modify one property - age_place from 1 to 20
Save each modified iteration into a separate file
I have tried to do that with Simple Data Writer but it didn't work.
You have JSR223 Elements as Sampler or Pre processor which you can add powerful script,
The easiest is to replace age_place with your value, for example if saved in variable age_place:
f = new FileOutputStream("c:\\temp\\template.json", false);
p = new PrintStream(f);
this.interpreter.setOut(p);
print("{\"name\":\"John\",\"age\":\"age_place\"}".replaceAll("age_place", vars.get("age_place")));
f.close();
If you need to generate 20 files with different age you can do it using any of JSR223 Test Elements. Example Groovy code would look like:
def json = new groovy.json.JsonSlurper().parseText("{\"name\":\"John\",\"age\":\"\"}")
def builder = new groovy.json.JsonBuilder(json)
1.upto(20, {
builder.content.age= "${it}"
def writer = new File('file' + "${it}" + ".json").newWriter()
writer << builder.toPrettyString()
writer.close()
})
Once you execute your test it will create the following files in the "bin" folder of your JMeter installation:
file1.json - with the age of 1
file2.json - with the age of 2
...
file20.json - with the age of 20
References:
Groovy For Loop Examples
Groovy: Parsing and producing JSON
Apache Groovy - Why and How You Should Use It

Resources