Getting issue while comparing one property to another in JMeter - jmeter

In my JMeter test plan, I want to set a flag in case of failure in every HTTP request. So I created a JSR223 PostProcessor in request with the following snippet:
if (!prev.isSuccessful()) {
int abc = 1
props.put('result', vars.get('abc'))
}
where result is defined as global in the thread.
In teardown I want to exit JMeter by comparing with the value of the flag . So I am doing the following:
if ((props.get('result') as int) == 1) {
System.exit(1);
}
Can anyone help me what wrong I am doing in this? Is there any other way by which I can do this.

This statement vars.get('abc') will return null because you just declare an integer called abc and not writing it to JMeter Variables.
You need to amend your code to something like:
if (!prev.isSuccessful()) {
int abc = 1
props.put('result', abc)
}
also there is no need to cast it to the integer back, it's stored as the object of the given type
if (props.get('result') == 1) {
System.exit(1);
}
More information:
Properties aka props
JMeterVariables aka vars
Top 8 JMeter Java Classes You Should Be Using with Groovy
You may also find AutoStop Listener useful

Related

Jmeter - How to put each member of the forEach loop into variable

Based on this thread - Jmeter - how to return multiple ID(s) based on the array (match JSON path with array)
I managed to get ID's, for every single member of the array.
Now I need to alternate the code and to have a variable for every single ID.
What i tried is:
vars.get('array').replace("[", "").replace("]", "").split(", ").each { country ->
def result = new groovy.json.JsonSlurper().parse(prev.getResponseData()).payload.find { entry -> entry.name == country.trim() }
vars.put("tim" + ${__counter(,)}, result.id as String);
}
But, I am only able to get a single variable.
What should I do in order to save every single result.id, into variables like:
tim1, tim2, tim3...
Don't inline JMeter Functions or Variables into Groovy scripts.
As per JMeter Documentation:
The JSR223 test elements have a feature (compilation) that can significantly increase performance. To benefit from this feature:
Use Script files instead of inlining them. This will make JMeter compile them if this feature is available on ScriptEngine and cache them.
Or Use Script Text and check Cache compiled script if available property.
When using this feature, ensure your script code does not use JMeter variables or JMeter function calls directly in script code as caching would only cache first replacement. Instead use script parameters.
So I would rather recommend amending your code as follows:
vars.get('array').replace("[", "").replace("]", "").split(", ").eachWithIndex { country, index ->
def result = new groovy.json.JsonSlurper().parse(prev.getResponseData()).payload.find { entry -> entry.name == country.trim() }
if (result != null) {
vars.put("tim" + (index + 1), result.id as String);
}
}
Demo:
More information: Apache Groovy - Why and How You Should Use It

Is it possible to remove empty query string parameters in jMeter?

I want to test an endpoint using jmeter, that has a copule of query string parameters, one of which is optional, loading the values from a CSV file. The problem is, can I avoid sending the query string parameter if I don't have a value for it?
It is but it will require some Groovy coding
Add JSR223 PreProcessor as a child of the request which query string you want to modify (or according to JMeter Scoping Rules if you want to apply the approach to more than one request)
Put the following code into "Script" area:
def newData = new org.apache.jmeter.config.Arguments()
0.upto(sampler.getArguments().size() - 1, { idx ->
def arg = sampler.getArguments().getArgument(idx)
if (!arg.getValue().equals('')) {
newData.addArgument(arg)
}
})
sampler.setArguments(newData)
That's it, the PreProcessor will be executed before the HTTP Request sampler and will remove all arguments which don't have their respective values

Jmeter: Comparison of multiple result for result response with JDBC variables

In j meter: In a bean-shell assertion or any other I want to match the content of response which I have fetched using Jason extractor suppose:
Result[1]=A, Result[2]=b, Result[3]=c
and so on Versus variables I have fetched using JDBC pre-processor which has saved as:
Result_1=, Result_2=B, Result_3=c.
I am able to match 1 variable at a time but not all at one time. so need help with bean-shell code to compare all result at once.
Add JSR223 Assertion somewhere to your test plan (normally as a child of a Sampler you would like to fail)
Put the following code into "Script" area
for (int i = 1; i <= Integer.parseInt(vars.get('ResultFromJSON_matchNr')); i++) {
if (!vars.get('ResultFromJSON' + i).equals(vars.get('ResultFromJDBC_' + i))) {
AssertionResult.setFailure(true)
AssertionResult.setFailureMessage('Variables mismatch')
}
}
Make sure you have groovy selected as the "Language" and have Cache compiled script if available box ticked
The above script assumes ResultFromJSON and ResultFromJDBC JMeter Variables reference names, amend them according to your real definitions.
More information: Scripting JMeter Assertions in Groovy - A Tutorial

read count of same response messages in thread group

I have thread group with single sampler.I have a scenario with 10 users to run for 1 hour duration. in view results tree showing different response data in every sampler's response data.can it possible to count how many times samplers get same response data.
{"success":false,"code":"104","message":"xx","status":412,"MessageType":"120","ResponseCode":"100","rilreplyDetails":"121"}
{"success":false,"code":"104","message":"yyy","status":412,"MessageType":"120","ResponseCode":"100","rilreplyDetails":"121"}
can I get a count of how many samplers get"xx" response,and how many for "yyy"?
One solution would be to define two variables in the Test Plan section, i.e: counter_xx and counter_yyy.
Then on the sampler request add one Regular Expression Extractor to extract the message value and finally use If Controller to specify which counter to increment.
The below image shows the structure for above solution.
Finally, you would be able to access the variable values by using ${counter_xx} or ${counter_yyy}.
The easiest would be doing this outside of JMeter, i.e. configure it to save response data by adding the next 2 lines to user.properties file:
jmeter.save.saveservice.output_format=xml
jmeter.save.saveservice.response_data=true
JMeter restart will be required to pick the properties up. Once your test is done inspect the resulting .jtl result file using your favorite XML editor.
See Configuring JMeter for more information on the approach.
Another option is using JSR223 Listener and the script like:
import org.apache.jmeter.engine.util.CompoundVariable
import org.apache.jmeter.functions.IterationCounter
def xxcounter = props.get("xxcounter")
if (xxcounter == null) {
xxcounter = new IterationCounter();
List<CompoundVariable> params = new ArrayList<>();
params.add(new CompoundVariable("false"));
xxcounter.setParameters(params);
}
def yycounter = props.get('yycounter')
if (yycounter == null) {
yycounter = new IterationCounter();
List<CompoundVariable> params = new ArrayList<>();
params.add(new CompoundVariable("false"));
yycounter.setParameters(params);
}
if (prev.getResponseDataAsString().contains('xx')) {
log.info('XX count: ' + xxcounter.execute(prev, sampler))
props.put('xxcounter', xxcounter)
}
if (prev.getResponseDataAsString().contains('yyy')) {
log.info('YYY count: ' + yycounter.execute(prev, sampler))
props.put('yycounter', yycounter)
}
The listener will scan current sampler response data and increment either this or that counter printing the current value to jmeter.log file.
Demo:
More information on Groovy scripting in JMeter: Apache Groovy - Why and How You Should Use It

Use properties as an input variable prefix in a logic controller (i.e. foreach)

In JMeter I am exporting a list of properties from one thread group to another.
They look like:
prop_1="value1"
prop_2="value2"
prop_3="value3"
prop_4="value4"
prop_#="4"
Now in the 2nd thread group I want to loop over them - I tried to do that with a foreach controller.
However the foreach controller expects a variable prefix and not a property prefix.
Is there any way to solve this?
One way would probably be to copy all the properties into variables in a preprocessor, but that sounds very clumsy.
Background:
My first thread group triggers several job execution of a longer duration.
The second thread group shall poll a database until each of those jobs are finished. For that it needs to know the job names that were created by the initial thread group (in my example above "value1..4").
Is there any nicer way to transfer the job names from one thread group to another than using properties?
Indeed, looking into ForEach Controller source it appears that ForEach Controller is looking only in JMeter Variables.
final JMeterVariables variables = context.getVariables();
final Object currentVariable = variables.getObject(inputVariable);
if (currentVariable != null) {
variables.putObject(getReturnVal(), currentVariable);
if (log.isDebugEnabled()) {
log.debug("ForEach resultstring isDone=" + variables.get(getReturnVal()));
}
return false;
}
However it is possible to convert JMeter Properties to JMeter Variables using Beanshell scripting.
For instance, if you need to convert all JMeter Properties starting with prop_ into JMeter Variables with the same name, add a Beanshell Sampler before your ForEach Controller and put the following code into it's "Script" area:
Enumeration e = props.propertyNames();
while (e.hasMoreElements()) {
String propertyName = e.nextElement().toString();
if (propertyName.startsWith("prop_")) {
vars.put(propertyName, props.getProperty(propertyName));
}
}
Above code will iterate all the JMeter Properties, look for the ones starting with prop_ and convert them to JMeter Variables which you can use in the ForEach Controller.
For more information on Beanshell scripting in Apache JMeter refer to How to use BeanShell: JMeter's favorite built-in component guide.

Resources