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

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.

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

Iterating over each row and accessing every column in HTTP Sampler in JMeter

I have explored and tried solution mentioned on Google or StackOverflow but could not solve my problem.
I am trying to iterate over each row of CSV and use every column of a row in "HTTP Sampler"
This is what I have tried till now.
My Test plan structure
This is my CSV file
This is my CSV Data Set Config
I am reading entire CSV and storing values in JMeter properties variable using Bean Shell Sampler.
This is the code in Bean Shell Sampler
import java.text.*;
import java.io.*;
String filename = "load_test_date.csv";
ArrayList strList = new ArrayList();
try{
log.info("starting bean shell");
File file = new File(filename);
if(!file.exists()){
throw new Exception ("ERROR: file " + filename + " not found");
}
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
String line = null;
log.info("while loop starting");
headerLine = br.readLine();
while((line = br.readLine())!=null){
log.info(line);
String[] variables = line.split(",");
props.put("header_1",variables[0]);
props.put("header_2",variables[1]);
props.put("header_3",variables[2]);
props.put("header_4",variables[3]);
props.put("header_5",variables[4]);
}
}catch(Exception ex){
log.error(ex.getMessage());
}
Now I want to iterate over props variable and fetch each column. I tried using While controller and ForEach Controller, but it is not giving me desired output.
while controller
While loop is executing twice (instead of three times for three rows in csv file) and always using last row values
I used ForEach controller too but could not produce desired outcome
First of all, forget about Beanshell, since JMeter 3.1 you should be using JSR223 Test Elements and Groovy language for scripting.
Second, if I correctly got your point and you want to iterate all the values, i.e. from 1 to 15, you need different approach, for example read the whole file into memory, split each line by comma and create a JMeter Variable for each "cell" value, example Groovy code would be something like:
SampleResult.setIgnore()
def lines = new File('load_test_date.csv').readLines()
def counter = 1
1.upto(lines.size() - 1, { index ->
def line = lines.get(index)
line.split(',').each { column ->
vars.put('value_' + counter, column)
counter++
}
})
if you execute the script and look into Debug Sampler output you will see the following JMeter Variables
In order to iterate the generated variables you can use ForEach Controller configured like:
And use ${value} in the HTTP Request sampler to access the next "cell" value on each iteration:

How to get multiple values from a CSV file inside of one test iteration

I need to dynamically generate an XML or JSON in an iteration where the XML or JSON has a variable number of elements -- e.g., it could be books. The values of the books come from the CSV file.
I created a CSV Data Config that point to the CSV file with a variable called csvBook.
Next, in a BeanShell Sampler, I call
StringBuffer sb = new StringBuffer("<Order><Books>");
Random rv = new Random();
int size = rv.nextInt(100);
for (int i = 0; i < size; i++) {
sb.append("<Book Name=" + vars.get("csvBook") + "/>");
}
sb.append("</Books></Order>");
The problem is I don't know how to get new values from the CSV file as I run through the loop inside one iteration. The vars.get("csvBook") returns the same value in the same iteration.
Is there a command to tell JMeter to get the next CSV value (next row) (again, inside one iteration)?
Thanks in advance.
Consider switching to JSR223 Sampler and Groovy language as:
Groovy has built-in support for JSON
Groovy has built-in support for XML
Groovy performance is much better than Beanshell
The relevant Groovy code would be something like:
import groovy.xml.StreamingMarkupBuilder
def csvFile = new File('/path/to/csv/file')
def payload = {
order {
books {
csvFile.readLines().each {line ->
book (name:line)
}
}
}
}
def xmlFile = new File('/path/to/xml/file')
def writer = xmlFile.newWriter()
def builder = new StreamingMarkupBuilder()
def writable = builder.bind payload
writable.writeTo(writer)

In Jmeter bean shell preprocess is there any way to read the lines of CSV data file and put into an array

In Jmeter bean shell preprocess is there any way to read the lines of CSV data file and put into an array
csv file contains
data1
date2
date2
i want put all three values in to array and send to Http request in jmeter for for each controller
Thanks in Advance
If you want the Beanshell
BufferedReader reader = new BufferedReader(new FileReader("path.to.your.file.csv"));
int counter = 1;
for(String line; (line = reader.readLine()) != null; ) {
vars.put("date" + counter, line);
counter++;
}
However I don't see any value added by Beanshell here, it is recommended to avoid scripting and use JMeter components where possible. If you need to send values from CSV file consecutively I would recommend using one of the following test elements instead:
CSV Data Set Config
CSVRead or StringFromFile functions

How to add multiple values to a parameter in jMeter

How can I add multiple values (these values are extracted with regex extractor) to a parameter.
I have the following test:
Using the regex extractor I get the following:
Now I'm using a BeanShell PreProcessor that contains the following code:
int count = Integer.parseInt(vars.get("articleID_matchNr"));
for(int i=1;i<=count;i++) { //regex counts are 1 based
sampler.addArgument("articleIds", "[" + vars.get("articleID_" + i) + "]");
}
Using this will generate the following request:
This will add multiple parameters with the same name (articleIds) which will cause an error when I'm running the test. The correct form of the parameter should be:
articleIds=["148437", "148720"]
The number of articleIds is different from a user to another.
That's totally expected as you're adding an argument per match. You need to amend your code as follows to get desired behavior:
StringBuilder sb = new StringBuilder();
sb.append("[");
int count = Integer.parseInt(vars.get("articleID_matchNr"));
for (int i = 1; i <= count; i++) {
sb.append("\"");
sb.append(vars.get("articleID_" + i));
if (i < count) {
sb.append("\", ");
}
}
sb.append("\"]");
sampler.addArgument("articleIds", sb.toString());
See How to use BeanShell guide for more details and kind of JMeter Beanshell scripting cookbook.

Resources