How to increment a variable while each time test plan is executed in Jmeter - 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

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'},)}

Loop controller inside While controller in JMeter

I have a while controller that stops after running for 5 seconds.
This while controller works fine when inside it, there is one sampler or one HTTP request.
Now I want to have a loop controller inside this while controller. But now, the while controller doesn't stop after 5 seconds, and the script runs for the number specified in loop controller.
Is there any way my loop controller stop working when the while controller trigers in 5 seconds?
Here's the schematic of my test plan. I want that "search" request stops after 5 seconds (the condition inside while controller), no matter the specified number in loop controller.
PS. The code inside JSR223 Sampler1 calculates the maximum time:
max = ${__timeShift(,,PT5S,,)};
vars.putObject("max", max);
And this is the logic inside While Controller:
${__groovy( now = ${__time()}; max = vars.get("max") as long; now <= max,)}
Why would you need the Loop Controller if While Controller generates loops itself?
Don't inline JMeter Functions or Variables into JSR223 Test Elements or __groovy() function otherwise you might get unexpected behaviour.
If you want to limit While Controller's number of loops to some specific maximum value just include it into your condition clause.
In the JSR223 Sampler:
max = System.currentTimeMillis() + 5000L
In the While Controller:
${__groovy( now = System.currentTimeMillis(); max = vars.getObject("max"); now <= max && (vars.get('__jm__While Controller__idx') as int) < 10,)}
More information: Using the While Controller in JMeter

Increment time value for 2 fields for every Thread and loop in jmeter

I have to Schedule a Meeting, In the particular post request body data I have to give from and to time. Every time the From & To time hours be different and time should not overlap.
For this requirement I tried the below code using JSR223 Sampler, But the issue I'm facing here is that only one time gets incremented and for every thread and loop .The value is same and it is not incrementing. Every Thread the time value should be incremented. Please let me know how I achieve it , as below code is returning same value for each Thread
def now = new Date()
log.info('Before: ' + now.format('HH:mm'))
use(groovy.time.TimeCategory) {
def nowPlus60Mins = now + 60.minutes
def nowPlus15Mins = nowPlus60Mins + 15.minutes
log.info('After: ' + nowPlus60Mins.format('HH:mm'))
log.info('End: ' + nowPlus15Mins.format('HH:mm'))
vars.put("AfterTime",nowPlus60Mins.format('HH:mm'));
vars.put("EndTime",nowPlus15Mins.format('HH:mm'));
if you want to affect all thread you must use JMeter properties, represented in script as props:
props.put("AfterTime",nowPlus60Mins.format('HH:mm'));
props.put("EndTime",nowPlus15Mins.format('HH:mm'));
To get the property value outside JSR223 Sampler using __P function as ${__P(AfterTime,)}
In JSR223 get property with props.get("EndTime")
If you run more than 1 iteration in 1 minute - it's absolutely expected that you will get the same generated offsets because given your SimpleDateFormat setting the value will update every minute.
Also you don't need any scripting, you can achieve the same using __timeShift() function directly in your request body:
plus 60 minutes: ${__timeShift(HH:mm,,PT60M,,)}
plus 15 minutes: ${__timeShift(HH:mm,,PT15M,,)}
More information: Creating Dates in JMeter Using the TimeShift Function

How to get the number of thread groups in test plan

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

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