How to replace the characters of a variable with some random numbers in Jmeter - jmeter

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.

Related

User Beanshell processor to write code so that data driven testing performed rather than using csv

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]);
}

how to concatenate all the values of a variable in Jmeter

I am storing output of JDBC request in Jmeter Variable - "temp_num".
Now I need to concatenate all the values stored in this variable in form of 'a','b','c'......'n'. I did try aggregation withing SLQ script too, but there we have a limit on string length, that's why I would like to probably use something like string builder, but not sure how to use it.
You can convert JDBC result set into a string using JSR223 PostProcessor and the code like :
temp_num = vars.getObject("temp_num");
result = new StringBuilder();
for (Object row : temp_num) {
iter = row.entrySet().iterator();
while (iter.hasNext()) {
pair = iter.next();
result.append(pair.getValue());
result.append(",");
}
}
vars.put('result', result.toString())
However be aware that there is a limit of the number of characters in Java String so make sure not to exceed it.
More information: Debugging JDBC Sampler Results in JMeter

Jmeter - How to handle duplicate values captured in RegExpression from the same response

How to ensure/handle duplicate values are not getting captured while using regular expression?
In my scenario i need to capture multiple offers from my response. But cant use the same offers again and again within the transaction
There are multiple ways to do this. If you are using the default Regular Expression Extractor, the problem is it creates the variables (eg: offer_1, offer_2 etc), ready to go with the execution. It would've been easier if it returned a ArrayList of some sort where we can remove the duplicates. What I am about to suggest is to add those variables to a list in a JSR223(groovy) sampler/post processor then convert them back to usual jmeter variables to use in the usual jmeter script flow.
Snippet:
I created a sample script as per your description which would return multiple offers with some duplicates. Following is the state of jmeter variables before post processing.
offer_1=RUSSIA
offer_1_g=1
offer_1_g0=offer="RUSSIA"
offer_1_g1=RUSSIA
offer_2=UK
offer_2_g=1
offer_2_g0=offer="UK"
offer_2_g1=UK
offer_3=ICELAND
offer_3_g=1
offer_3_g0=offer="ICELAND"
offer_3_g1=ICELAND
offer_4=USA
offer_4_g=1
offer_4_g0=offer="USA"
offer_4_g1=USA
offer_5=UK
offer_5_g=1
offer_5_g0=offer="UK"
offer_5_g1=UK
offer_6=USA
offer_6_g=1
offer_6_g0=offer="USA"
offer_6_g1=USA
offer_7=USA
offer_7_g=1
offer_7_g0=offer="USA"
offer_7_g1=USA
offer_matchNr=7
As you can see above there are duplicates in the variables. Put the following Groovy code in a JSR223 post processor with groovy as language selected.
// Count of offers extracted by Regular Expression Extractor
def count = Integer.parseInt(vars.get("offer_matchNr"))
// An empty list which will store the offers
def offer_list = []
for (int i = 1; i <= count; i++){
def offer = vars.get("offer_" + i)
offer_list.add(offer)
}
// Removes the duplicates in the list
offer_list.unique()
// Following one liner adds new variables but with only unique offers in similar format as jmeter variable.
offer_list.eachWithIndex{ it, index -> vars.put("unique_offer_${index+1}", "${it}")}
After post processing:
unique_offer_1=RUSSIA
unique_offer_2=UK
unique_offer_3=ICELAND
unique_offer_4=USA

Jmeter Beanshell: Take multiple variables from CSV Data Set Config?

I have a Jmeter test in which I want to post an XML message to a JMS queue. This message will be formed dynamically via a BeanShell Preprocessor, which pulls data from multiple CSV Data Set Config elements.
One item of this XML message that is dynamic is the number of elements in it - it will be a random number between 1 and 10. For each Line element, I want to pull a different variable from a CSV Data Set Config element. However, I'm finding if I do something like the below, I keep getting the same variable:
for (int i = 0; i < numberOfLines; i++) {
InputXML = InputXML + "<OrderLine ItemID=\"${ItemID}\" />";
}
The above will keep using the same ${ItemID} variable for all of lines but what I want is for it to grab the next one in the CSV file.
Is there any way to accomplish this via Beanshell?
To go along with your data, if CSV looks like (first row will saved as variables)
0,1,2,3,4,5,6,7,8,9
a,b,c,d,e,f,g,h,i,j
The Beanshell will use index i to get value of column i in CSV:
String InputXML = "";
for (int i = 0; i < 10; i++) {
String a = vars.get(String.valueOf(i));
InputXML = InputXML + "<OrderLine ItemID=\"" + a + "\" />";
}
vars.put("InputXML",InputXML);
InputXML variable will hold the full value.
If you want random value until 10, you can use JMeter function ${__Random(0,10,myRandom)}.
If you want to get random line in CSV you can use the similar answer.

Need to extract dynamic values from a string response in Jmeter

I need to extract the dynamic value "BSS1,DS1,HYS1,MS1,PTS1,QS1,USG1,YS1,RT10086,RT10081,RT10084,RT10082,OT10076,RT10083,UT10081,RT10085,"
from the string response "ACCOUNT_DETAIL_ACCOUNT_PRODUCT_SERVICES_EDIT_UPDATE_NameSpace.grid.setSelectedKeys(["BSS1","DS1","HYS1","MS1","PTS1","QS1","USG1","YS1","RT10086","RT10081","RT10084","RT10082","OT10076","RT10083","UT10081","RT10085"]);"
I have tried using the regular expression extractor :
Regular Expression :Keys\(\[\"(.+?)\",\"(.+?)\",\"(.+?)\",\"(.+?)\",\"(.+?)\",\"(.+?)\",\"(.+?)\",\"(.+?)\",\"(.+?)\",\"(.+?)\",\"(.+?)\",\"(.+?)\",\"(.+?)\",\"(.+?)\",\"(.+?)\",\"(.+?)\"]\)
template : $1$$2$$3$$4$$5$$6$$7$$8$$9$$10$$11$$12$$13$$14$$15$$16$
But the above regular expression works only if there are 16 values in the response. If the response contains less number of values, for example, "ACCOUNT_DETAIL_ACCOUNT_PRODUCT_SERVICES_EDIT_UPDATE_NameSpace.grid.setSelectedKeys(["BSS1","DS1"]);"
then the above regular expression doesn't work.
How can I extract the values in the response if the total count is unknown?
Also the double quotes in the response need to be omitted.
Is there any post processor using which dynamic values can be extracted?
Any help is greatly appreciated.
I believe it will be easier with some scripting.
Add Beanshell PostProcessor as a child of the request which returns aforementioned response
Put the following code into the PostProcessor's "Script" area:
String response = new String(data);
String rawKeys = response.substring(response.indexOf("[") + 1, response.indexOf("]")); // get the data inside square brackets
String keysWithoutQuotes = rawKeys.replaceAll("\"", ""); // remove quotes
String[] keyData = keysWithoutQuotes.split("\\,"); // get array of keys
for (int i = 0; i < keyData.length; i++) { // store array of keys into JMeter variables like
vars.put("Keys_" + (i +1), keyData[i]); // Keys_1=BSS1, Keys_2=DS1, etc.
}
vars.put("Keys_matchNr", String.valueOf(keyData.length)); // set Keys_matchNr variable
Where:
data is byte array containing parent sampler's response data
vars is a shorthand to JMeterVariables class which provides read/write access to JMeter Variables.
As a result you'll have variables like:
Keys_1=BSS1
Keys_2=DS1
..
Keys_matchNr=X
See How to Use BeanShell: JMeter's Favorite Built-in Component guide for additional information on Beanshell scripting in JMeter and some more examples

Resources