I am writing below code in JSR223 Post processor
def my_number = vars.get("Initial_file_count").toInteger(); //convert to int type
def new_number = 3;
def add = my_number + new_number;
vars.put("MY_NUMBER", add.toString());
log.info(my_number);
Your code is more or less fine apart from the last line which needs to be changed to something like:
log.info('My Number: ' + add);
because log.info() function expects only Strings as arguments so you either need to use string concatenation or toString() method of the provided object.
Demo:
More information: Top 8 JMeter Java Classes You Should Be Using with Groovy
Related
I just want to know how to pass an array from a JSR223 sampler to another JSR223 sampler. Note that the two JSR223 are just in the same thread. I had been searching and I cannot find the exact solution. I'm just a newbie in Jmeter, just searching for java codes etc. So here is the code:
import groovy.json.JsonSlurper;
String response = prev.getResponseDataAsString();
def jsonSlurper = new JsonSlurper();
def json = jsonSlurper.parseText(response);
int size = json.records.size;
vars.put("intDashboardMeetingsCount", size);
def strMeetingsArray = new String[size];
if (size > 0) {
for (int i=0;i<size;i++) {
strMeetingsArray[i] = json.records.get(i).id;
}
}
I already got the number of records in intDashboardMeetingsCount, and I just need to know how will I able to get the data of strMeetingsArray[]
Thanks in advance!
Just use vars shorthand, it stands for JMeterVariables class instance so you should be able to use vars.putObject() function in order to add your strMeetingsArray to JMeter Variables and vars.getObject() to retrieve it.
So in 1st JSR223 Sampler:
vars.putObject('somevar', strMeetingsArray)
in 2nd JSR223 Sampler:
def strMeetingsArray = vars.getObject('somevar')
More information: The Groovy Templates Cheat Sheet for JMeter
you can use variables (vars) for a single thread. When you do a multi-thread test, you can use the properties (props).
Sample Variable Used Javascript Code:
vars.put("myString","mysamplestring");
var getString= vars.get("myString");
var array = ['bilal','demir'];
vars.putObject("myArray",array);
var getArray = vars.getObject("myArray");
log.info( "*getString : {} *getArray :{} *firstItem: {} *length : {}" , getString, getArray, getArray.length, getArray[0]);
//output: *getString : mysamplestring *getArray :{0=bilal, 1=demir} *firstItem: bilal *length : 2
Sample Properties Used Javascript Code:
var array = ['bilal','demir'];
props.put("myArray",array);
var getArray = props.get("myArray");
log.info( "getArray :{} length : {}" , getArray, getArray.length);
//output: getArray :{0=bilal, 1=demir} length : 2
For groovy change define variable code var to def
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)
jmeter ForEach controller can be used to iterate over variables with same prefix like,
myVar_1
myVar_2
myVar_3
But in my case input variable is array of strings, [ "val1", "val2", "val3" ] How to iterate over an array and send separate request for each value?
You won't be able to feed this JSON Array to the ForEach Controller, but you can convert it into a form which can be understood by the ForEach Controller
Add a JSR223 Sampler after the variable holding this JSON Array is defined
Put the following code into the "Script" area:
def json = new groovy.json.JsonSlurper().parseText(vars.get("yourInputVariable"))
def counter = 1
json.each {
vars.put("myVar_" + counter, it)
counter++
}
Replace yourInputVariable with the actual name of the variable holding the JSON Array
Add ForEach Controller under the JSR223 Sampler and perform "normal" configuration as you would do it for myVar_1, myVar_2,... - it will work fine as JSR223 Sampler creates the relevant variables basing on the data from the JSON Array.
See Parsing and producing JSON - Groovy and Groovy Is the New Black articles for more information.
Same way as you use for same prefixed variables.
For variable myVar
myVar = ["val1", "val2", "val3"];
//Following variables are automatically created
myVar_1 = "val1";
myVar_2 = "val2";
myVar_3 = "val3";
ForEach controller will be used on myVar_1, myVar_2, myVar_3
Use Debug Sampler to ensure.
jmeter version : 3.1 r1770033
I tried Dmitri's answer, but basically got stuck with the groovy script as it works only for a simple array of strings. I, however, needed a more complex array of JSON objects.
Then I switched the scripting language to ecmascript and based on the original script wrote a good old JS like this:
var jsonObject = JSON.parse(vars.get("ReportSources"));
for(var index = 0; index < jsonObject.length; index++) {
vars.put("rs_" + (index + 1), JSON.stringify(jsonObject[index]));
}
It worked for me.
I am using JMeter, I made a connection oracle and executing a query.
For example select employee_id from employee
Result is EMP100
Now I want to increase the result by 1
(e.g. EMP100 to EMP101)
and need capture new emp_is i,e EMP101 in a variable and use this variable in an another XML request.
Given you have this EMP100 in some JMeter Variable like ${foo} you can add a Beanshell PostProcessor and use the code like:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
String foo = vars.get("foo");
log.info("Original foo variable value: " + foo);
Pattern p = Pattern.compile("(\\d+)", Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
Matcher m = p.matcher(foo);
if (m.find()) {
String postfix = m.group(1);
int oldNumber = Integer.parseInt(postfix);
oldNumber++;
String newNumber = String.valueOf(oldNumber);
foo = foo.replace(postfix, newNumber);
vars.put("foo", foo);
}
log.info("New foo variable value: " + vars.get("foo"));
Demo:
After that you should be able to use the same ${foo} variable in your XML payload or wherever else.
See How to Use BeanShell: JMeter's Favorite Built-in Component article for more information on enhancing your JMeter tests with scripting.
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