Increment time value for 2 fields for every Thread and loop in jmeter - 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

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

In JMeter, How do i loop until a result is found

I have a request in Jmeter that I need to loop until I find the result I am looking for. I have read a few bits about a while controller but found them unhelpful as they seem to glance over vital information or are using an older version of Jmeter
I'm currently using Jmeter 5.0, and I have attempted to implement a while controller but failed as I think I do not understand how to properly handle the response, or even grab it, and then use it as a comparison to assert if the item exists.
I get a response from the HTTP request call response that looks a little somthing like this:
{"data":{"getIDs":{"Page": 1,"PageSize": 25,"PageCount": 1,"isFirstPage": true,"batches":[{"id":"b601a257-13fe-4de3-b779-a5922e89765a"},{"id":"b601a257-13fe-4de3-b779-a5922e89765b"},{"id":"b601a257-13fe-4de3-b779-a5922e89765c"}]}}
I need to recall the endpoint until I have found the ID I am looking for or cancel after 10 attempts
So after a bit of fumbling around I, I figured on my own answer that seems to work well. But I would suggest looking at other sources before taking mine as gospel.
The basic structure looks as follows:
Within a thread I set the variables then create the while loop as the next step. Within the While loop I created a counter then added the request I wanted to loop after. To make the loop work for me, I have three items sat under the request.
A Response Assertion: this check for a 200 status as the call should never fail
A Constant Timer: There is a delay between polls of the end point
A JSR223 Assertion: groovy code used ensure the while loop logic is handled
User Defined Variables:
Here i have setup two variables:
DONE: Done is a string value I alter if my JSR223 Assertion finds the values I'm looking for in the HTTP request
MyValue (this is dynamically driven in my actual test, for demo purpose, I’m just declaring a value to look for i.e. 12345)
While Controller:
I still feel i may not understand this correctly, however after some googling I came across the following code that works for me despite some errors in the JMeter console:
${__javaScript(("${DONE}" != "yep" && ${Counter} < 10),)}
This code is saying that the while loop will continue until either of these two conditions are met:
DONE, the variable created earlier, is equal to the value yep
Counter is less than 10 (Counter is declared beneath the while loop)
Counter:
this was a simple configuration step that just worked once I understood it needed to be within the while loop, i configured the following:
Starting value = 1
Increment = 1
Exported Variable Name = Counter
Ticked 'Track Counter independently for each user'
Ticked 'Reset counter on each thread group iteration'
(Exported Variable Name: you can call this whatever you want, I’ve named it counter for the purpose of this demo)
JSR223 Assertion:
This is a simple script assertion that just uses a Boolean and a couple of if statements to assert the state of the test.
import org.apache.commons.lang3.StringUtils;
def done = vars.get("DONE");
String response = prev.getResponseDataAsString(); //retrieves the http request response as text
String MyValue = vars.get("MyValue");
def counter = vars.get("Counter");
//Find Substring within response string and stor result as boolean
String container = response;
String content = MyValue;
boolean containerContainsContent = StringUtils.containsIgnoreCase(container, content);
//Check if the true condition is met and change the value so the loop exits
if (containerContainsContent == true){
log.info("------------------------Got Here");
vars.put("DONE", "yep");
}
//Force test to fail after 10 loops
if (Counter.toString() == "10"){
assert 1 == 2
}

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