Using jmeter variable in if controller - json

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.

Related

I am trying to add a username and string combined to a variable in Jmeter [duplicate]

I have a requirement to use randome url from a url list I extract from a json response.
Say I extract them in this mannser
imageUrls_1=https://blah01.com
imageUrls_2=https://blah02.com
imageUrls_3=https://blah03.com
imageUrls_4=https://blah04.com
imageURLs_matchNr=4
In a following JSSR223 sampler I was able to generate a variable called "url" with one of the url names selected randomely
("imageUrls_1","imageUrls_2",etc)
I was thinking to use them in my HTTP request to get the correcponding url as follows. ${${url}}. But soon found out its not giving me anything other than "${${url}}" :(.
JMeter Is it possible to place a varibale inside a varible name?
Basically I need to use one of the extracted urls randomely in my HTTP request.
The easiest way is going for __V() and __Random() functions combination like:
${__V(imageUrls_${__Random(1,${imageURLs_matchNr},)},)}
Demo:
More information: Here’s What to Do to Combine Multiple JMeter Variables
Use __V function
${__V(url)}
The V (variable) function returns the result of evaluating a variable name expression.

Pass the JSON extractor Ref name to another request sequentailly in Jmeter which is outside the loop

I have used While controller in Jmeter and fetching the data (i.e JSON _id values) one by one from the Response. total there are 50 Id's/per response.
E.g.
"_id: "57565556654","_id":"68676665555", "_id": "87686877545"
Http Request - When this request is submitted I am getting _id from the response.
Used JSON extractor to fetch the _id's from the Response. i.e. 50 ids. Ref Name = DeleteQuestionsID
In Debug Sampler DeleteQuestionsID_MatchNr shows DeleteQuestionsID_MatchNr =1, bcoz JSOn extarctor is running inside While loop
I need to Pass these 50 Id's one by one to Next Http request which is outside the While loop.
Http Request : `'/v1/tests/'$'{TestID}/questions/${DeleteQuestionsID}
`How to achieve this?
You can save the values into JMeter Variables by adding JSR223 PostProcessor after the JSON Extractor and using the following code:
vars.put('DeleteQuestionsID_' + vars.get('__jm__While Controller__idx'), vars.get('DeleteQuestionsID'))
It will generate 50 JMeter Variables like:
DeleteQuestionsID_0=foo
DeleteQuestionsID_1=bar
DeleteQuestionsID_2=baz
etc.
which can re-use later on where required.
vars is a shorhand for JMeterVariables class instance, it provides read/write access to all JMeter Variables in scope, check out Top 8 JMeter Java Classes You Should Be Using with Groovy for more information on this and other JMeter API shorthands available for JSR223 Test Elements.
This is why ForEach_Controller created for
ForEach controller loops through the values of a set of related variables. When you add samplers (or controllers) to a ForEach controller, every sample (or controller) is executed one or more times, where during every loop the variable has a new value. The input should consist of several variables, each extended with an underscore and a number. Each such variable must have a value. So for example when the input variable has the name inputVar, the following variables should have been defined:
inputVar_1 = wendy
inputVar_2 = charles

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.

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.

Grails, create domain object from json-string with has-many relation

I'm trying to parse a grails parameter map to a Json String, and then back to a parameter map. (For saving html form entries with constraint-violations)
Everything is fine as long as there is no hasMany relationship in the parameter-map.
I'm using
fc.parameter = params as JSON
to save the params as JSON String.
Later I'm trying to rebuild the parameter map and create a new Domain-Object with it:
new Foo(JSON.parse(fc.parameter))
Everything is fine using only 1:1 relationships (states).
[states:2, listSize:50, name:TestFilter]
But when I try to rebuild a params-map with multi-select values (states)
[states:[1,2], listSize:50, name:TestFilter]
I'm getting this IllegalStateException:
Failed to convert property value of type org.codehaus.groovy.grails.web.json.JSONArray to required type java.util.Set for property states; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [de.gotosec.approve.State] for property states[0]: no matching editors or conversion strategy found
I tried to use this, but without success:
JSON.use("deep") {
new Foo(JSON.parse(fc.parameter))
}
You can use JsonSlurper instead of the converters.JSON of grails, it maps JSON objects to Groovy Maps. I think this link also might help you.
Edit: Now, if the problem is binding the params map to your domain, you should try using bindData() method, like:
bindData(foo, params)
Note that this straightforward use is only if you're calling bindData inside a controller.
What seems to be happening in your case is that Grails is trying to bind a concrete type of List (ArrayList in the case of JsonSlurper and JSONArray in the case of converters.JSON) into a Set of properties (which is the default data structure for one-to-many associations). I would have to take a look at your code to confirm that. But, as you did substitute states: [1,2] for a method of your app, try another test to confirm this hypothesis. Change:
states:[1,2]
for
states:[1,2] as Set
If this is really the problem and not even bindData() works, take a look at this for a harder way to make it work using object marshalling and converters.JSON. I don't know if it's practical for you to use it in your project, but it sure works nicely ;)