jmeter check different response for same request - json

I have this kind of request
{
"ID":"112345"
"SERVICE":"56AA77"
}
The API response could be positive or negative with different element.
positive response:
{
"RESPONSE":"OK"
"TEXT":"DONE"
}
negative response:
{
"RESPONSE":"KO"
"DESCRIPTION":"NOT FOUND"
"ERROR_CODE":"100"
}
how can I tested with JMeter using only one HTTP Request Sampler and only one CSV file ?
Actually I'm using two csv files:
positive:
TEST_ID,TEST_DESC,ID,SERVICE,RESPONSE,TEXT
negative:
TEST_ID,TEST_DESC,ID,SERVICE,RESPONSE,DESCRIPTION,ERROR_CODE
is it possible to use only one file ?
like this:
TEST_ID,TEST_DESC,ID,SERVICE,RESPONSE,TEXT,DESCRIPTION,ERROR_CODE
how Jmeter can handle this?
UPDATE:
I've two JSON Assertion objects
is it possible to create BeanShell groovy to call one of those based on the ResponseCode ?
if (prev.getResponseCode().equals("200") == true) {
checkResponsePositive
}
else
{
checkResponseNegative
}
could someone help me with the right syntax?

Add JSR223 Assertion as a child of the HTTP Request sampler
Put the following code into "Script" area:
def response = new groovy.json.JsonSlurper().parse(prev.getResponseData())
if (vars.get('RESPONSE').equals('OK')) {
if (!vars.get('TEXT').equals(response.TEXT)) {
AssertionResult.setFailure(true)
AssertionResult.setFailureMessage('TEXT field mismatch')
}
} else {
if (!vars.get('DESCRIPTION').equals(response.DESCRIPTION)) {
AssertionResult.setFailure(true)
AssertionResult.setFailureMessage('DESCRIPTION field mismatch')
}
if (!vars.get('ERROR_CODE').equals(response.ERROR_CODE)) {
AssertionResult.setFailure(true)
AssertionResult.setFailureMessage('ERROR_CODE field mismatch')
}
}
The above code will have 2 branches:
when RESPONSE JMeter Variable is OK it will validate TEXT
when RESPONSE JMeter Variable is KO it will validate DESCRIPTION and ERROR_CODE from the response against the relevant JMeter Variables.
More information:
Groovy: Parsing and producing JSON
Scripting JMeter Assertions in Groovy - A Tutorial

Yes it is possible. So, I am assuming you have used sample variables and used them in regular extractor or any extractor or may be using coding. Now, if you used it then it can check the sampler response and write whatever values it may find. For positive they may not find anything, so may write "XXX_NOTFOUND" or null depends on the data extraction approach and code.
In the below, I have used dummy sampler for positive request and put all the regular extractor below it.
Once you check the csv report generated via view result tree, you can see that variables which are found has been reported and others as "xxxxx_NotFound". This "xxxxx_NotFound" is the value I have provided in the regular expression extractor. In short, for a particular request, you can use multiple extractor and write the output in a single csv. If values found then it will write else it will write what you have given in the default.

Related

How to use csv to provide different values for json assertion for different inputs in Jmeter?

I am relatively new to API Testing.
Currently I have a setup where I am having different request jsons and for each request json there is different repsonse json assertion configuration provided with the appropriate values in Jmeter.
Since my json structure will be same and only the input values will be different, I am thinking to generalize the input values using csv and keep only one request configuration.
But would I be able to provide different values(like jsonpath and expected value) to one response json assertion configuration using csv? Because the jsonpath and expected value both will depend upon the input provided and it can have major difference as per the case.
If yes, then how to do it please let me know.
Also if I can achieve my use case using other free API Testing Tool like Postman then also let me know.
You can normally parameterize any JMeter Test Element using CSV Data Set Config
For example you have the following response:
{ "name":"John" }
And the following CSV file:
$.name,John
$.name,Jane
Add CSV Data Set Config to your Test Plan and configure it like:
Add JSON Assertion as a child of the request which returns the above JSON and configure it like:
That's it, each virtual user and/or iteration will pick up the next line from the CSV file and the ${jsonPath} and ${name} placeholders will be replaced with their respective values:
as you can see, the first request passed because name matched John and the second failed because the assertion expected name to be Jane and got John

Jmeter parse and Assert Array of Json objects

In Jmeter when trying to extract data from Json object everything is ok and works great but, when i have array of Json objects can't extract it.
Result is:
[{"id":1,"name":"test"},{"id":2,"name":"test2"}]
it is my project JSON Extractor and JSR233 Assertion.
Inside Groovy script i'm making log.info but it doesn't captures variable value which is described inside JSON Extraxtor.
String id = vars.get("id");
log.info ("The example answer is " + id);
if (id == ""){
AssertionResult.setFailureMessage("The id is null");
AssertionResult.setFailure(true);
}
Please note that if Json response looks like this {"id":1,"name":"test"}
everything works correctly.
Change your JSON Path Expression to look like: $..id. .. is a deep scan operator so it will return all id attributes values.
Change Match No to -1
It will result in the following variables:
id_1=1
id_2=2
id_matchNr=2
I have no idea what exactly you need to assert, hopefully you will be able to amend your Groovy script yourself.
Also be aware that there is JSON Assertion test element available since JMeter 4.0 so you won't need to have separate extractor and assertion elements.

how to check null /empty or value based on response from previous Sampler in Jmeter?

I have extracted the value from Json response for one of the Key. It has two possible values as either
Key=[] or
Key=[{"combination":[{"code":"size","value":"Small"}]},{"combination":
[{"code":"size","value":"Medium"}]}]
I need to check whether Key is [] or it has some values. Could you please help me what is wrong with below implementation:
if ("${Key}"=="[]") {
vars.put('size', 'empty')
} else {
vars.put('size', 'notempty')
}
My Switch controller is not navigating to Else Part based on above implementation . Help is useful!
Don't ever inline JMeter Functions or Variables into script body as they may resolve into something which will cause compilation failure or unexpected behaviour. Either use "Parameters" section like:
or use vars.get('Key') statement instead.
Don't compare string literals using ==, go for .equals() method instead
See Apache Groovy - Why and How You Should Use It article for more information on using Groovy scripting in JMeter tests
If you have an already extracted value Key and you are using an if controller with the default JavaScript you can do the following in the condition field:
"${Key}".length > 0
The "${Key}" is evaluating to your JavaScript object which is an array. You can check the length of the array to see if there are objects in it.

Regex to get a field of Json

I have a JSON text which is returned by an API. I need to grab the value of "id" field so I can use it in a test (I am doing a corrolate test in JMeter).
I can try and find the "id": text however I cannot get the Z3G2D93 part.
Regex:
/"id":"(.+?)"/g
JSON :
{
"req":{
"dat":{
"bt":"",
"ot":"07-Apr 08:21",
"typ":"PickUp",
"tot":"3480",
"ast":"",
"an":"Test Test",
"id":"Z3G2D93"
}
}
}
Configure Regular Expression Extractor as follows:
Reference Name: anything meaningful, i.e. id
Regular Expression: "id":"(.+?)"
Template: $1$
By the way, you can test your Regular Expressions in JMeter right in View Results Tree listener using RegExp Tester mode like:
See How to debug your Apache JMeter script article for more information on how to get to the bottom of JMeter script failure.
By the way, it might be easier to deal with JSON responses using JSON Path Extractor available via JMeter Plugins

Verify whole json response in jmeter by value or sort Json

I'm not using JMeter too often, and I've run into very specific issue.
My REST response is always "the same", but nodes are not in the same order due to various reasons. As well, I can't put here whole response due to sensitive data, but let's use these dummy one:
First time response might be:
{
"properties":{
"prop1":false,
"prop2":false,
"prop3":165,
"prop4":"Audi",
"prop5":true,
"prop6":true,
"prop7":false,
"prop8":"1",
"prop9":"2.0",
"prop10":0
}
}
Then other time it might be like this:
{
"properties":{
"prop2":false,
"prop1":false,
"prop10":0,
"prop3":165,
"prop7":false,
"prop5":true,
"prop6":true,
"prop8":"1",
"prop9":"2.0",
"prop4":"Audi"
}
}
As you can see, the content it self is the same, but order of nodes it's not. I have 160+ nodes and thousand of possible response orders.
Is there an easy way to compare two JSON responses comparing matching key - values, or at least to sort the response, and then compare it with sorted one in assertion patterns?
I'm not using any plugins, just basic Apache JMeter.
Thanks
I've checked using Jython, you need to download the Jython Library and save to your jmeter lib directory.
I've checked 2 JSONs with Sampler1 and Sampler2, on Sampler1 I've add a BeanShell PostProcessor with this code:
vars.put("jsonSampler1",prev.getResponseDataAsString());
On Sampler2 I've add a BSF Assertion, specifying jython as the language and with the following code:
import json
jsonSampler1 = vars.get("jsonSampler1")
jsonSampler2 = prev.getResponseDataAsString()
objectSampler1 = json.loads(jsonSampler1)
objectSampler2 = json.loads(jsonSampler2)
if ( objectSampler1 != objectSampler2 ):
AssertionResult.setFailure(True)
AssertionResult.setFailureMessage("JSON data didn't match")
Yoy can find the whole jmx in this GistHub
You will most probably have to do this with a JSR223 Assertion and Groovy.
http://jmeter.apache.org/usermanual/component_reference.html#JSR223_Assertion
http://docs.groovy-lang.org/latest/html/api/groovy/json/JsonSlurper.html
Note that if you know Python, you might look at using Jython + JSR223.
I would just set up 10 jp#gc - JSON Path Assertions. Documentation for figuring out JSON Path format is here and you can test how it would work here.
For your example you would the assertion (Add > Assertion > jp#gc - JSON Path Assertions), then to test the prop 1 put:
$.properties.prop1
in the JSON Path field, click the Validate Against Expected Value checkbox, and put
false
in the expected value field. Repeat those steps for the other 9 changing the last part of the path to each key and the value you expected back in the expected value field.
This extractor is jmeter add on found here.