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
Related
Hi I want to store the value return by below code in JMeter webDriver Sampler . but i am getting error.
String access_token = WDS.browser.executeScript("return window.localStorage.getItem(localStorage.key(2))");
WDS.log.info("access_token : " + access_token);
OR
var access_token = WDS.browser.executeScript("return window.localStorage.getItem(localStorage.key(2))");
WDS.log.info("access_token : " + access_token);
Both above ways are not working?
In order to be able to help we need to know the details of the error "you are getting". Also it's unclear what localStorage.key(2) object stands for.
Here is an example of getting se:fkey value from https://stackoverflow.com website:
I used default language for WebDriver Sampler: javascript and the following piece of code:
WDS.sampleResult.sampleStart()
WDS.browser.get('https://stackoverflow.com')
var access_token = WDS.browser.executeScript('return window.localStorage.getItem("se:fkey")')
WDS.log.info('Got the following value from local storage: ' + access_token)
WDS.sampleResult.sampleEnd()
And it works just fine:
If you additionally need to store the value into a JMeter Variable add the following line:
WDS.vars.put('access_token', access_token)
and you will be able to access the extracted value as ${access_token} where required.
More information: The WebDriver Sampler: Your Top 10 Questions Answered
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')
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!
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.
I need to test a web service with header-item lines with reading values from csv.
<urn:Requisition_BudgetReqExportHeaderDetails_Item>
<!--Zero or more repetitions:-->
<urn:item>
<urn:CompanyCode>
<urn:UniqueName>?</urn:UniqueName>
</urn:CompanyCode>
<urn:ERPRequisitionID>?</urn:ERPRequisitionID>
<urn:HoldTillDate>?</urn:HoldTillDate>
<urn:IsServiceRequisition>?</urn:IsServiceRequisition>
<urn:Name>?</urn:Name>
</urn:item>
</urn:Requisition_BudgetReqExportHeaderDetails_Item>
I can read values from CSV file but this web service is complex and items might be 1 or more than 2.
How can I handle this web service request?
You can use JSR223 PreProcessor like:
Add JSR223 PreProcessor as a child of your request
Put the code to generate the XML payload into "Script" area, an example one would look like:
def writer = new StringWriter()
def xml = new groovy.xml.MarkupBuilder(writer)
xml.records() {
car(name:'HSV Maloo', make:'Holden', year:2006) {
country('Australia')
record(type:'speed', 'Production Pickup Truck with speed of 271kph')
}
car(name:'Royale', make:'Bugatti', year:1931) {
country('France')
record(type:'price', 'Most Valuable Car at $15 million')
}
}
sampler.addNonEncodedArgument("", writer.toString(), "")
Amend it to match your requirement
When you run your test the JSR223 PreProcessor will generate the request body and set it in the HTTP Request sampler
References:
sampler - a shorthand to HTTPSamplerProxy class, see the JavaDoc for all available methods and fields
Groovy - Creating XML - learn how to create XML data using Groovy language
Groovy is the New Black - an introduction to Groovy scripting in JMeter