Capture details from http request and response in jmeter - 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')

Related

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 4 | HTTP Request sampler JAVA implementation bytes sent not captured

We are using JAVA implementation for one of the requests.In the request we are uploading a file. Request doesn't work when HTTPCLIENT4 implementation is selected.The request works fine with previous Jmeter version with HTTPCLIENT3.1 implementation. We need to capture bytes sent in results. How to capture bytes sent through JAVA implementation in HTTP Request sampler
Sent bytes is basically a combination of URL + headers + body so you can calculate it yourself using JSR223 PostProcessor and code like:
def url = sampler.getUrl().toString().length()
def headers = prev.getHeadersSize()
def body = 0;
sampler.getHTTPFiles().each {file ->
body += new File(file.getPath()).length()
}
prev.setSentBytes(url + headers + body)
Where:
sampler is an instance of HTTPSamplerProxy where you can get all files which you're sending with the request
prev is an instance of HTTPSampleResult where you can get URL and Headers and also override Sent Bytes field.
See The Groovy Templates Cheat Sheet for JMeter to see what else you can do with Groovy and how.

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

Parsing the response using REST vs. SOAP API in Ruby

I am trying to parse a response that I receive using Rest API calls, but get an error when I say, something like: response.body.first[1]. I am transferring Soap API calls to rest API calls. Is response.first something that can only be used in Soap, if so what is the equivalent in Rest? Here is the code snippet that I am having trouble with:
url = ##rest_base_url.to_s + "filters/#{id.to_s}/results"
resource = RestClient::Resource.new url, #username, #password
response = resource.get
data = JSON.parse(response.body)["data"]
if response.body.first[1][:return].nil?
requirements = nil
elsif response.body.first[1][:return].is_a?(Array)
# puts "|get_requirements| req is an array".blue
requirements = []
Thank you

Resources