Json request validation in Jmeter - json

As my json request contains all mandatory parameters in request body, I want to validate all parameters using Jmeter.
Do let me know if it is possible to validate all request parameters presents in json body using jmeter or jmeter plugins

Normally people are interested in validating responses, not the requests therefore I am not aware of any suitable Test Elements either bundled or available via Plugins. For responses validation you have JSON Path Assertion
If for some reason you need to validate the request and fail the sampler if the validation fails you can use JSR223 Post Processor. Example code:
def request = sampler.getArguments().getArgument(0).getValue()
def json = new groovy.json.JsonSlurper().parseText(request)
// do any checks you need, for example
if (!json.keySet().contains("somekey")) {
log.info("Key \"somekey\" was not found in the request")
prev.setSuccessful(false)
}
References:
JsonSlurper
Parsing and producing JSON
Groovy Is the New Black

Related

JMeter Json Extractor for Multiple Http Requests

I have setup a ForEach Controller to execute multiple HTTP requests but I would like to then extract JSON values from the response bodies from each of the HTTP requests.
When I try to add a JSON Extractor PostProcessor to the HTTP Request, I am only able to get a json value from the last HTTP Request. Is it possible to get values from all of the HTTP requests?
You're getting the values from each HTTP Request, you just overwrite the previous value when the next iteration of the ForEach Controller starts, you can double check yourself by adding Debug Sampler after the HTTP Request sampler under the ForEach Controller
Just add ${__jm__ForEach Controller__idx} pre-defined variable as a prefix or postfix for the name of the created variable in JSON Extractor so on each iteration it will create a separate JMeter Variable holding the current value extracted from the response.
Example configuration:
Demo:
JSON extractor is ok but something that you can try and is more flexible i add beanshell post processor and choose your language, then you can extract the JSON from HTTP requests.
You can choose java as language and use following code to extract the JSON as string
String jsonString = prev.getResponseDataAsString();

Jmeter - Extract JSON field value of a SENT request

I am trying to obtain data from sent JSON and use it further in another request.
My sent JSON also has dynamic variables like ${data} so the trick is that it has to execute first in order to be able to extract.
Let's say I have the following SENT JSON:
{
"field_one": ${data1},
"field_three": [more data],
"field_two": ${data2}
}
Question is: How can I extract "field_one" and "field_two" values from the sent request?
Thanks
You don't need to extract them, they are ${data1} and ${data2} so you can re-use these JMeter Variables anywhere in the script.
If I don't understand something obvious or you need to copy the values to another JMeter Variables, you can extract them as follows:
Add JSR223 PostProcessor as a child of the request which sends above JSON
Put the following code into "Script" area:
def requestBody = new groovy.json.JsonSlurper().parseText(sampler.getArguments().getArgument(0).getValue())
vars.put('field_one', requestBody.field_one)
vars.put('field_two', requestBody.field_two)
That's it, now you should have ${field_one} and ${field_two} JMeter Variables holding the values you're looking for.
In the above example sampler stands for HTTPSamplerProxy and vars for JMeterVariables, check out Top 8 JMeter Java Classes You Should Be Using with Groovy for details on the above and other JMeter API shorthands available for JSR223 Test Elements.
More informaion:
JsonSlurper
Apache Groovy: Parsing and producing JSON

JMETER store request JSON Element as variable

Trying to figure out how I can access elements of a post request body (JSON) and store it as a variable. One of my tests creates a user using ${__UUID}#gmail.com - and I'd like to then check that my response includes this same information.
I'm guessing I could probably create the UUID before the request and store it as a variable, and then check against that, but wondering if there is anything similar to JSON Path Extractor for request elements.
There is a JSR223 PreProcessor you can use to fulfil your requirement.
Assuming you have JSON Payload like:
{
"user": "${__UUID}#gmail.com"
}
Add JSR223 PostProcessor and put the following code into "Script" area:
def user = com.jayway.jsonpath.JsonPath.read(sampler.getArguments().getArgument(0).getValue(), '$..user').get(0).toString()
log.info('Random user email:' + user)
vars.put('user', user)
The above code will:
Extract from the request everything which matches $..user JSON Path expression
Print it to jmeter.log file
Store the value into a JMeter Variable so you will be able to refer it as ${user} where required.
More information:
Apache Groovy - Why and How You Should Use It
Groovy - Parsing and Producing JSON

Jmeter - Fetch the Session ID from the Response and pass it next request.Request & Responses are in JSON

Scenario :-
Im performing Load testing using API's
HTTP Request 1
I logged in using http://cabhound.com:1000/v2/driver/login and I got the below response
{"statusCode":200,"statusMessage":"Success","errorMessage":"","responseData":{"id":0,"userName":"PQeurentraps5S#tarento.com","firstName":"Partner","lastName":"Tarento","phoneNumber":"2641148625","email":"tamvrentrapnsr#tarento.com","password":"","addressOne":"","addressTwo":"","city":"","state":"","zipCode":"","loginCount":156,"welcome":"","smsOptIn":false,"promoCode":"","userNotification":"","errorMessage":"","message":"","sessionId":"6063tnerLt3013951671120oDse18492930#2","osType":"","osVersion":"","deviceType":"","deviceId":"","latitude":"","longitude":"","timeZone":"","appVersion":"","company":"Tarento","licenceNumber":"","vehicleType":"","vehicleFeature":null,"subscriptionType":"unlimited","driverWorkingCity":"Bangalore","vehicleNumber":"","locationUpdateTime":20,"rate":0,"reliable":0,"distance":0.0,"eta":0,"latitudeLongitude":"","status":"ON","payment":{"paymentType":"","cardNumber":"","cvnNumber":"","expDate":""},"vehicleTypeList":["Sedan","Limousine","SUV/Wagon","Minivan","Other"],"vehicleFeatureList":["Navigation System","Eco Friendly","Handicap accessible","Accepts credit cards"],"driverId":582,"currentLocation":null,"companyCode":"tarento","acceptanceRate":0,"like":0,"profileIndicator":0,"payWithCabHound":false,"smsSupport":false,"paymentInfo":false,"geoInfo":"","active":true}}
Please see the session id in the above response,which I want to use in next http request data
HTTP Request 2
http://cabhound.com:1000/v2/driver/dutyStatus
Below is the data which I need to post,here I want to use session id of HTTP Request 1
{"status":"ON","sessionId":"1311tnerLt9013956793297oDse462783#2","longitude":"77.686700","userName":"erpkrentrapJps#tarento.com","latitude":"12.934487"}
How to pass the session id of HTTP Request 1 (response) to HTTP Request 2 Post Data
Help me in this which I have strucked
I would recommend using JSON Path Extractor available through JMeter Plugin (you'll need Extras with Libs Set.
Regex are headache to develop, especially for JSON data which can be multiline. Beanshell has known performance issues, so using a plugin is the best option.
Relevant JSON Path query for your sessionId will look as:
$.responseData.sessionId
See Parsing JSON section of Using the XPath Extractor in JMeter guide for more details and XPath to JSON Path mapping
I can see 2 solutions for above problem,
Use Regular expression extractor to extract the value (I haven't used it with json response but I think it will work)
Use Beanshell preprocessor or postprocessor in which you can get response and find required sessionID using substr or json parsers or use simple java code. Extract the required value and use it in next request.

Using Rest assured to validate saved JSON response

I have a question regarding REST Assured. - https://code.google.com/p/rest-assured/wiki/Usage
I understand that I can use REST assured to make HTTP calls(.get .put etc.) and validate the response using when() etc. I would like to validate JSON responses that I have already saved in the database, instead of Calling the web service realtime and validating it's response.
Can I use REST-assured to Load a JSON response as a String and validate it?
Yes you can use Rest Assured's JsonPath project independently of Rest Assured (see getting started page). Once you have it in classpath you can do something like this:
JsonPath jsonPath = new JsonPath(<your json as string>);
String title = jsonPath.getString("x.y.title");