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

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

Related

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

vars.put function not writing the desired value into the jmeter parameter

Below is the code which i have been trying to address the below UseCase in JMETER.Quick help is appreciated.
Usecase:
A particular text like "History" in a page response needs to be validated and the if the text counts is more than 50 a random selection of the options within the page needs to be made.And if the text counts is less than 50 1st option needs to be selected.
I am new to Jmeter and trying to solve this usingJSR223 POST processor but somehow stuck at vars.put function where i am unable to see the desired number being populated within the V paramter.
Using a boundary extractor where match no 1 should suffice the 1st selection and 0 should suffice the random selection.
def TotalInstanceAvailable = vars.get("sCount_matchNr").toInteger()
log.info("Total Instance Available = ${TotalInstanceAvailable}");
def boundary_analyzer =50;
def DesiredNumber,V
if (TotalInstanceAvailable < boundary_analyzer)
{
log.info("I am inside the loop")
DesiredNumber = 0;
log.info("DesiredNumber= ${DesiredNumber}");
vars.put("V", DesiredNumber)
log.info("v= ${V}");
}
else{
DesiredNumber=1;
log.info("DesiredNumber=${DesiredNumber}");
vars.put("V", "DesiredNumber")
log.info("v= ${V}");
}
def sCount = vars.get("sCount")
log.info("Text matching number is ${sCount_matchNr}")
You cannot store an integer in JMeter Variables using vars.put() function, you either need to cast it to String first, to wit change this line:
vars.put("V", DesiredNumber)
to this one
vars.put("V", DesiredNumber as String)
alternatively you can use vars.putObject() function which can store literally everything however you will be able to use the value only in JSR223 Elements by calling vars.getObject()
Whenever you face a problem with your JMeter script get used to look at jmeter.log file or toggle Log Viewer window - in absolute majority of cases you will find the root cause of your problem in the log file:

Jmeter- how to pass a fixed number of values from an array at a time until iterating through all values to a http request

In my get htttp request, I get an array of ids ex: list=[1, 2, 3.....1000]
And then for my next http request, I want to pass all the values in the list 10 at a time, so it will be 100 requests total and each time, it takes 10 values from the list array. I'm using a loop controller to call the http request 100 times. but I dont know how to retrieve 10 values at a time, and then go to the next 10, next 10 until all values are used.
How should I do that?
Add a regular expression extractor to your get request as a child.
Add the following properties shown in the screenshot to extract List
Add a Beanshell sampler/ JSR223 sampler and add the following code.
The code below creates a series of variables and store series of 10 values in a variable starting from Final_0 to Final_99
import java.util.Arrays
String complete_List=vars.get("List");
String[] complete_List_Array = complete_List.split(",");
int i;
for(i=1;i<=complete_List_Array.length;i++)
{vars.put("List_"+i,complete_List_Array[i-1]);}
int j;
int loopcount=complete_List_Array.length/10;
vars.put("loopcount",Integer.toString(loopcount));
for(j=0;j
{
StringBuilder sb = new StringBuilder();
sb.append("[");
for(i=j*10+1;i<=(j+1)*10;i++)
{
sb.append(vars.get("List_" + i));
if (i < (j+1)*10)
sb.append(",");
}
sb.append("]");
vars.put("Final_"+j,sb.toString());
}
vars.put("counter","0");
Add a loop counter and mention loop count as ${loopcount} as shown below
You can add HTTP Request as a child of loop counter and to pass series of 1o value at a time use ${__V(Final_${counter})}
Add a beanshell post processor to the http request to that will increment the counter
add the following code to the beanshell sampler
int counter = Integer.parseInt(vars.get("counter")) +1;
vars.put("counter",Integer.toString(counter));
You can see in the results its passing series of 10 values at a time and loop will run for 100 times
For more info on beanshell please follow the link
Please let me know if it helps.........
Considering you have the list array available at your disposal by using any extractor.
Extract the sublist from the array and put them in properties. Then, fetch the properties where ever you want it.
In the below I am fetching the sublist from the array and putting it in jmeter properties.
Here, I am fetching the values from the properties. This is just for demonstration and you dont need this. After putting list in properties just fetch in HTTP sampler as shown in the last image.
Now, to fetch it in HTTP sampler you can use loop and counter and fetch the properties using groovy. Loop for iteration and counter for increment the variable mylist_x.
Hope this helps.

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

Resources