How to get the number of thread groups in test plan - jmeter

I have a small script that has it's own properties and a single Thread Group. Sometimes I need to merge this test script into a bigger test plan that has more than a single Thread Group. I need a way to say if there's only 1 thread group then apply these user defined variables. Any ideas? I'm thinking I would add an If Controller but I can't seem to find what condition I would put.

You can instead add If condition about your TestPlan,
For example if your small script is 1.jmx check
${jexl3( "1.jmx" == "${__TestPlanName}")}
Also you can add a variable in Test plan as amILong with true value and check if it exists.

Actually you can get the number of Thread Groups in the Test Plan, but it will require some scripting assuming using JMeter API.
Add JSR223 Sampler somewhere to your Test Plan
Make sure groovy language is selected in "Language" dropdown
Put the following code into "Script" area:
import org.apache.jmeter.engine.StandardJMeterEngine
import org.apache.jmeter.threads.ThreadGroup
import org.apache.jorphan.collections.HashTree
import org.apache.jorphan.collections.SearchByClass
import java.lang.reflect.Field
def engine = ctx.getEngine()
def test = engine.getClass().getDeclaredField("test")
test.setAccessible(true)
def testPlanTree = (HashTree) test.get(engine)
def threadGroupSearch = new SearchByClass<>(ThreadGroup.class)
testPlanTree.traverse(threadGroupSearch)
def threadGroups = threadGroupSearch.getSearchResults().size()
log.info('Detected ' + threadGroups + ' Thread Groups in the Test Plan')
if (threadGroups == 1) {
props.put('foo', 'bar')
}
else {
props.put('foo', 'baz')
}
If there is only one Thread Group in the Test Plan the above code will create foo JMeter Property with the value of bar, in the other case(s) the property value will be baz. You will be able to refer the property via __P() function as ${__P(foo,)} where required, i.e. in the If Controller.
Demo:
More information: Apache Groovy - Why and How You Should Use It

Related

How to create a counter in JMeter and save the value for the next execution?

i've been trying to save the value of a counter once the execution finishes, with the idea that the next one starts with that same value. For example: I start with a counter that has 1 as value, loop it 5 times and the execution finishes with that counter having his value in 5. Then, i want that counter to start with his value in 5, how is this doable?
You can save it into a file using a suitable JSR223 Test Element like:
new File('counter.txt').text = vars.get('your-counter-variable-name-here')
where vars stands for JMeterVariables class instance, see Top 8 JMeter Java Classes You Should Be Using with Groovy article for more information on this and other JMeter API shorthands
the same for initialization, you can use __groovy() function with the following code:
${__groovy(file = new File('counter.txt'); if (file.exists()) {return file.text} else { return '0'},)}

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

Validating User defined variables

I have several user defined variables set via properties i would like to validate.
I can use a jsr223 sampler to validate these but i dont want to duplicate all the names which are already set in the user defined variables.
Is there some programatic way to get hold of the declared user defined variables, possibly via the sampler or context variables?
There is vars shorthand for JMeterVariables class instance which holds all the JMeter Variables (including the ones you set via User Defined Variables class).
Check out Top 8 JMeter Java Classes You Should Be Using with Groovy article for more information on vars and other JMeter API shorthands available for the JSR223 Test Elements.
However this way you will get all the JMeter Variables including pre-defined ones
If you want to validate only the variables you have defined in the User Defined Variables configuration element you can play a little trick with the Reflection:
import org.apache.jmeter.config.Arguments
import org.apache.jorphan.collections.SearchByClass
def engine = engine = ctx.getEngine()
def test = engine.getClass().getDeclaredField('test')
test.setAccessible(true)
def testPlanTree = test.get(engine)
SearchByClass<Arguments> udvSearch = new SearchByClass<>(Arguments.class)
testPlanTree.traverse(udvSearch)
Collection<Arguments> udv = udvSearch.getSearchResults()
udv.each { arguments ->
0.upto(arguments.size() - 1, { rowNum ->
def arg = arguments.getArgument(rowNum)
log.info('Variable name = ' + arg.getName() + ', variable value = ' + arg.getValue())
})
}

How to increment a variable while each time test plan is executed in Jmeter

I have a scenario to run a test plan multiple times in a day, during the first execution of my UDV sequence should be "xxxx-1". Subsequent execution within the day the UDV sequence should get incremented like "xxxx-2", "xxxx-3", etc. I tried by putting a Bean Shell Post processor with an if condition.
Need to run daily, run the test every four hour interval and reset the counter back to 1 at 5th execution.
The only way to store the variable between Test Plan executions is to write it into a file or a database table.
To do it with the file:
Add setUp Thread Group to your Test Plan
Add JSR223 Sampler to the setUp Thread Group and put the following code into "Script" area
def file = new File('number')
if (!file.exists() || !file.canRead()) {
number = '1'
}
else {
number = file.text
}
props.put('number', number as String)
Add tearDown Thread Group to your Test Plan
Add a JSR223 Sampler to the tearDown Thread Group and put the following code into "Script" area:
def number = props.get('number') as int
number++
new File('number').text = number
You can refer the generated value using __P() function as xxx-${__P(number,)} where required.
More information: Apache Groovy - Why and How You Should Use It

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

Resources