Here is my simple Jmeter test plan.
User Parameters look like this:
I'm simply calling one endpoint, reading the response body and according to found IDs with the help of Regex Extractor I'm calling another endpoint. ForEach loop helps make sure for all the found IDs same endpoint is called with ID as parameter in the Path.
What I'm trying to achieve with Another HTTP Request inside ForEach loop is to read the response, and if body contains Monday, increment User Parameter Monday by 1, same for Tuesday and for every other User Parameter. Ideally at the end of the test suite, I should get something like this:
Monday - 5
Tuesday - 3
Wednesday - null or zero
Thursday - null or zero
Friday - 1
Saturday - 12
Sunday - 8
According to my BeanShell script I hope I'm following all the right paths:
import org.apache.commons.lang.StringUtils;
String response = new String(data);
int Mondays = 0;
int Tuesdays = 0;
int Wednesdays = 0;
int Thursdays = 0;
int Fridays = 0;
int Saturdays = 0;
int Sundays = 0;
if(response.contains("'DayOfWeek':'Monday'")){
Mondays++;
vars.put("Monday", Mondays.toString);
};
if(response.contains("'DayOfWeek':'Tuesday'")){
Tuesdays++;
vars.put("Tuesday", Tuesdays.toString);
};
if(response.contains("'DayOfWeek':'Wednesday'")){
Wednesdays++;
vars.put("Wednesday", Wednesdays.toString);
};
if(response.contains("'DayOfWeek':'Thursday'")){
Thursdays++;
vars.put("Thursday", Thursdays.toString);
};
if(response.contains("'DayOfWeek':'Friday'")){
Fridays++;
vars.put("Friday", Fridays.toString);
};
if(response.contains("'DayOfWeek':'Saturday'")){
Saturdays++;
vars.put("Saturday", Saturdays.toString);
};
if(response.contains("'DayOfWeek':'Sunday'")){
Sundays++;
vars.put("Sunday", Sundays.toString);
};
My small problem here is that User Parameters variables never get updated and always at the end of the run equals to 0. What am I doing wrong in this situation? Has anyone faced this task before?
Be aware that starting from JMeter version 3.1 it is recommended to use Groovy for any form of scripting to consider migrating to JSR223 PostProcessor
Looking into repeating 'DayOfWeek':'xxx' pattern it seems you don't need to create 7 branches for each weekday, you can extract the current value using Regular Expressions and set or get and increment the relevant JMeter Variable
Example code would be something like:
def day = (prev.getResponseDataAsString() =~ "'DayOfWeek':'(\\w+)'")[0].get(1)
def value = (vars.get(day) ?: '0') as int
value++
vars.put(day, value as String)
See Apache Groovy - Why and How You Should Use It article for more information on using Groovy scripting in JMeter tests
Related
I want to test a Get Request with list of values. I dont want to use CSV ,
so i started using Beanshell Preprocessor and has those values in Array. Then used for loop to use those values and send to Get Request in HTTP Request. Every this was Successful except sending values to Get request. It is reading all values and sending the last read value to Get request.
Question : I want my request to run for each value when code reads the data one by one.
var TtValuedetails;
int i;
n=22;
String[] ttvalue = {"34324324224","fdadsfadsf","dfdsfdsfds","dafadsfa",
"45435435","dfadsfads"
};
for(int i=0;i<n;i++)
{
if(i==0)
{
TtValuedetails=ttvalue[i];
if(ttvalue[0]=="34324324224")
{
vars.put("TtValuedetails",TtValuedetails);
log.info(TtValuedetails);
log.info("first value is executed" );
Org.Apache.......startRequest();
}
}
} ;
We cannot help you without seeing the full code and knowing what you're trying to achieve but one thing is obvious: you should not be using Beanshell, since JMeter 3.1 it's recommended to use Groovy for scripting.
Current problem with your code is:
ttvalue array contains 6 elements
n=22
the line TtValuedetails=ttvalue[i]; will cause failure on 7th iteration of the loop due to IndexOutOfBoundsException
If you want to send a request for each value of the ttvalue array the easiest is converting it into separate JMeter Variables like:
ttvalue_1=34324324224
ttvalue_2=fdadsfadsf
etc.
and using ForEach Controller for iterating the values.
Example Groovy code for storing the values into JMeter Variables:
String[] ttvalue = ["34324324224", "fdadsfadsf", "dfdsfdsfds", "dafadsfa",
"45435435", "dfadsfads"];
for (int i = 1; i <= ttvalue.size(); i++) {
vars.put("ttvalue_" + i, ttvalue[i - 1]);
}
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
}
I have written a regular expression (regexpname) in my thread which returns a number Ex: 10 and when I try to use the regular expression in the BeanShell postprocessor by adding __intSum function to add a number to the regular expression out put Ex: to add 4 to the regular expression out put i.e., 10 and store the result to a variable Ex: Total, using the following function:
{__intSum(4,${regexpname},Total}
upon trying to run my test, it stops immediately with the message
"Jmeter: Uncaught exception: java.lang.NumberFormatException: For
input string: "${regexpname}".....".
Please let me know how to fix the issue:
Here is the code I have put in beanshell postprocessor:
import java.text.SimpleDateFormat;
SimpleDateFormat sdf = new SimpleDateFormat("m/dd/yyyy"); // change it according to your Date format
Date originalDate = sdf.parse(vars.get("SigDate"));
Calendar cal = Calendar.getInstance();
cal.setTime(originalDate);
${__intSum(4,${regexpname},Total)};
cal.add(Calendar.DAY_OF_YEAR, Total); // change it if you need to add something else
Date newDate = cal.getTime();
vars.put("newDepdate", sdf.format(newDate));
log.info("Original date: " + vars.get("SigDate"));
log.info("New date: " + vars.get("newDepdate"));
Don't inline JMeter Functions and/or variables into scripts as they can resolve into something which will cause script failure or inconsistent behaviour. Either use "Parameters" section or go for code-based equivalents
Don't use Beanshell test elements, it is recommended to switch to JSR223 Test Elements and Groovy language for any form of scripting since JMeter 3.1
Your date format looks flaky as m stands for "minutes in hour", if you need "month in year" - go for capital M
Actually you don't even need any scripting here as there is __timeShift() function since JMeter 3.2 which can do what you need, the relevant syntax would be something like:
Use int Total = Integer.parseInt(vars.get("regexpname"))+4; instead of ${__intSum(4,${regexpname},Total)}; in your beanshell pre processor
I have defined regexpname as 10 in test plan so its adding 14 days and storing new date in newDepdate.
For more information on beanshell please follow this link
Please let me know if it helps..
I have scenario where I need to capture dynamic Order-value IDs from response and among those values, I need to select maximum value and pass it to the next request.
How can we achieve this with the help of Jmeter tool?
Assuming you have the following JMeter Variables from the PostProcessor:
foo_1=1
foo_2=5
foo_3=10
foo_matchNr=3
You can get the maximum value as follows:
Add JSR223 PostProcessor as a child of the request, make sure it goes after the PostProcessor which returns your Order-ID values
Put the following code into "Script" area:
List values = new ArrayList()
for (int i=1; i <= (vars.get('foo_matchNr') as int); i++) {
values.add((vars.get('foo_' + i) as int))
}
vars.put('foo_max', Collections.max(values) as String)
Assuming everything goes well you should be able to access the maximum value as ${foo_max} where required.
See Apache Groovy - Why and How You Should Use It article for more information on Groovy scripting in JMeter tests
I am trying to pick up a variable from Debug Sampler and replace the characters of the variables with some Randomly generated number. I have added a BeanShell Sampler for writing the custom code. Below is the piece of code:
String myvariable = vars.get("Corr_ContextN");
chars1 = new ArrayList();
chars2 = new ArrayList();
for(int i =0; i<myvariable.length(); i++) {
chars1.add(myvariable.charAt(i)); }
String value = chars1.toString();
Random randomnumber = new Random();
for (int idx=1; idx < 15; ++idx) {
chars2.add(randomnumber.nextInt(100)); }
String Newvalue1 = chars2.toString();
vars.put("NewVariable", Newvalue1 );
By the above way I get a New variable in the Debug Sampler (NewVariable) with a list of random numbers. But I want to replace the existing variable "Corr_ContextN" with this NewVariable created. In other words the existing variable should be replaced by some dynamically generated number/variable.
Please help me out.
Just change the last line to be:
vars.put("Corr_ContextN", Newvalue1 );
P.S. Consider using JSR223 Sampler instead of Beanshell. You can even reuse the same code which will perform much better being compiled by Groovy engine.
P.P.S. Be informed that much easier would be using __Random function which is capable of storing randomly generated numbers into JMeter Variables as well as returning them in place where the function is called. Check out How to Use JMeter Functions post series to learn about functions in JMeter.