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

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.

Related

Jmeter : I am using Json extractor to pass value from the Json response but I am not seeing the value in the debug sampler

I am trying to pass the values of the basketId and basketItemId from the Create Basket Json response to Jmeter variable so that I can use these values in the next requests. I set up everything according to the documentation, however I am not able to see the values in the debug sampler in the Tree - Response Data area. Any help is appreciated?
You're not seeing your values because your sampler hasn't been executed
It has not been executed because you need to provide the same number of the "Default Values" as the variables you declared. If you look at jmeter.log file you will see something like:
Mismatch between number of variables, json expressions and default values
The solution would be adding the default values like:
null;null
And assuming your Json Path expression matches something in the response you will see both values.
More information: API Testing With JMeter and the JSON Extractor

jmeter check different response for same request

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.

How to retrieve the JSON value from multiple array response data using regular expression extractor in jmeter?

{
"response":
{
"responseData":
{
"createdDate":"2016-04-23 14:39:35",
"modifiedDate":"2016-04-23 14:39:35",
"catalogID":1009
}
}
}
Here is sample JSON data for reference. I need to extract the value of catalogID=1009. How to extract the value of catalogID?? can anyone please share your idea???
What is the regular expression to retrieve the catalogID??
Use the following regular expression extractor configuration:
Reference Name: variable name of your choice, i.e. catalogID
Regular Expression: "catalogID":(\d+)
Template: $1$
Refer extracted value as ${catalogID} where required.
Few tips:
You can use View Results Tree listener in RegExp Tester mode to test your regular expressions against real response:
See How to debug your Apache JMeter script article for more details.
There is JSON Path Extractor available via JMeter Plugins which allows using JSON Path language (more handy than regular expressions when it comes to JSON), for example the relevant query to get "catalogID" will be as simple as:
$..catalogID[0]
There is also an online JSON Path Expression Tester
If you want to use regex, use
"catalogID":(.+?)
or
"catalogID":(\d+) <-- For only digits
You can also install the plugin JSONPath for jmeter and use this instead
$.response[0].responseData[0].catalogID
More info
I have found the solution for this question.
Here you want to extract the integer value means then use this requalar expression like "catalogID":(.*?),
String means "catalogID":"(.*?)",
Lets do it!

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.

Using jmeter variable in if controller

I want to use the jmeter if controller and use a jmeter variable which I get while processing the previous response.
I have two services search and register. The logic I want to use is hit the search service, if I get a good response (i.e. the search exists) no need to register. If the search is empty hit register service and check the search service again.
So I have a Simple controller. Under simple controller I have search service with BSF assertion. Next thing under simple controller is the if controller (with register service) for which I need a variable (say ${found} )
I will be creating the variable in bsf assertion as
import groovy.json.*
def slurper = new JsonSlurper()
def result = slurper.parseText(prev.getResponseDataAsString())
if (result.id != null ) {
def found = 0 // can be text logical or any other type ..
}
Question: Can I use the variable ${found} created in the bsf assertion search service as a condition for If controller ? Will it be available beyond the service. Will it be better to have it as user defined variable ?
Depending on found variable type it can be:
vars.put("found", found); - for String
vars.put("found", String.valueOf(found)); - for chars, integers, floats, doubles, booleans, etc.
vars.putObject("found", found) - for anything which cannot be cast to a String
props.put(found, found); - for any Object types. Opposite to JMeter Variables JMeter Properties have "global" scope and Variables visibility is limited to the current thread group only so if you need to pass this value to another Thread Group you need to use properties.
Be careful while setting conditions in the If Controller as in case of string literals you'll need to put both variable and value in quotation marks like:
"${found}"=="someid"
See How to use JMeter's 'IF' Controller and get Pie. guide for more details.
By the way, there is a couple of test elements available via JMeter Plugins which are designed to work with JSON data so you won't have to use BSF scripting:
JSON Path Extractor - to perform correlation on JSON data
JSON Path Assertion - to use assertions on response
yes the variable "found" can be used. But you need to add the following at the end of your code
vars.put("found",found);
Hope this will help.