Jmeter - Fetch values from jar file to be used as separate parameters - jmeter

Based on the thread: How can i use jar file into loop counter - Jmeter, i managed to fetch the whole JSON, and used in the body.
Now i need altered version to use only specific parameter, rather then whole body.
my script is like:
my call is like
My jar data is like:
public String Australia()
{
String a = {"
+ "\"name\": \"Sydney\","
+ "\"password\": \"test1\""
+ "}";
return a;
}
public String Canada()
{
String a = {"
+ "\"name\": \"Toronto\","
+ "\"password\": \"test2\""
+ "}";
return a;
}
What is the easiest way to fetch specific parameter, and loop logic still to be kept?

If the strings in the .jar file where your PabBDetailsIncluded class lives are valid JSON you could use JsonSlurper class to fetch desired attributes values like:
For the name:
${__groovy(new groovy.json.JsonSlurper().parseText(new com.example.PabBDetailsIncluded().Canada()).name,)}
For the password:
${__groovy(new groovy.json.JsonSlurper().parseText(new com.example.PabBDetailsIncluded().Canada()).password,)}
Demo:
More information:
Apache Groovy - Parsing and producing JSON
Apache Groovy - Why and How You Should Use It

Related

Unable to add strings in JSR223 postprocessor

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

Process of Array of Strings in Beanshell preprocessor in Jmeter

I have a Jmeter (version 4.0) test script where I am using json extractor to fetch an array of strings from the response json using $..Names and storing it in a variable groupOfNames. The various names are stored like groupOfNames_1, groupOfNames_2, groupOfNames_ALL.
I need to make POST call next with body as
{
"name1", "name2", "name3" (--actual values--)
}
How can i achieve this using bean shell preprocessor? groupOfNames_ALL gives me all value but like this.... name1, name2, name3 (without quotes surrounding individual names). Please help. Thanks.
I heard Groovy is the New Black so you can add quotation marks around each of names as simply as:
vars.put('groupOfNames_ALL',vars.get('groupOfNames_ALL').split(',').collect {"\"$it\"" }.join(', '))
Demo:
Also as a gentle reminder: JMeter users are encouraged to use JSR223 Test Elements for any form of scripting since JMeter 3.1
Put the below code in your BeanShell PreProcessor:
int matchNr = Integer.parseInt(vars.get("groupOfNames_matchNr"));
for(int i = 1; i <= matchNr; i++){
String Names = vars.get("groupOfNames_" + i);
if(i == matchNr){
vars.put("AllNames", vars.get("AllNames") + "\"" + Names + "\"");
}
else if(i == 1){
vars.put("AllNames","\"" + Names + "\", ");
}
else{
vars.put("AllNames", vars.get("AllNames") + "\"" + Names + "\", ");
}
Then use the variable ${AllNames} in your post as below:
{
${AllNames}
}

JMeter-For each implementation

I have an API which takes multiple IDs as a parameter:
http://pqa-volpqa.unknown.com:8080/items/batch/?Ids=00000017072571,00000017072588,00000017072595,00000019786230,00000019987460,00000019988238,00000019988283,00000019990170,00000020015206,00000020015213
Now these IDs are mention in a CSV file like below:
00000017072571
00000017072588
00000017072595
00000019786230
~~
~~
~~
00000020015213
How can I implement this?
If they are as a single string in CSV file you can just use __StringFromFile() or __FileToString() function to read them directly into request parameter
If they are each one a separate line it is still possible with __groovy() function like:
${__groovy(def line = new File('/path/to/your/file.csv').getText().replaceAll(System.getProperty('line.separator')\,'\,'),)}
See Apache JMeter Functions - An Introduction to learn more about JMeter Functions concept.
You can add a Loop controller with Loop count = number of IDs you want to add. Then add a Counter inside the loop controller with the below configurations:
Start: 1
Increment: 1
Reference Name: Counter
Check the boxes for Track counter independently for each user and Reset counter on each thread group iteration
Add a CSV Data Set Config after the counter with the below configurations:
Filename : The full name to your file // if the csv file is not in the same folder with your jmx file you should enter the full path to your CSV file.
Variable Names : id
Finally, add a BeanShell Sampler after the csv data set config with the below code in the code area:
String id = vars.get("id");
int Counter = Integer.parseInt(vars.get("Counter"));
if (Counter == 1){
vars.put("IDs", id);
}
else{
vars.put("IDs", vars.get("IDs") + "," + id);
}
All of the above should be before your API, now you can use your API as below:
http://pqa-volpqa.unknown.com:8080/items/batch/?Ids=${IDs}

Execute query get result increment it by 1 and pass this as a variable in a xml payload

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.

Looping through JSON response + in JMETER

I am using Jmeter for performance testing and stuck at following point:
I am getting a JSON response from Webapi as follows:
PersonInfoList:
Person
[0]
{
id: 1
name: Steve
}
[1]
Person
{
id: 2
name: Mark
}
I need to get the ids based on the count of this JSON array and create a comma separated string as ("Expected value" = 1,2)
I know how to read a particular element using JSON Post processor or Regex processor but am unable to loop through the array and create a string as explained so that I can use this value in my next sampler request.
Please help me out with this: I am using Jmeter 3.0 and if this could be achieved without using external third party libs that would be great. Sorry for the JSON syntax above
Actually similar functionality comes with JSON Path PostProcessor which appeared in JMeter 3.0. In order to get all the values in a single variable configure JSON Path PostProcessor as follows:
Variable Names: anything meaningful, i.e. id
JSON Path Expressions: $..id or whatever you use to extract the ids
Match Numbers: -1
Compute concatenation var (suffix _ALL): check
As a result you'll get id_ALL variable which will contain all JSON Path expression matches (comma-separated)
More "universal" answer which will be applicable for any other extractor types and in fact will allow to concatenate any arbitrary JMeter Variables is using scripting (besides if you need this "expected value and parentheses)
In order to concatenate all variables which names start with "id" into a single string add Beanshell PostProcessor somewhere after JSON Path PostProcessor and put the following code into "Script" area
StringBuilder result = new StringBuilder();
result.append("(\"Expected value\" = ");
Iterator iterator = vars.getIterator();
while (iterator.hasNext()) {
Map.Entry e = (Map.Entry) iterator.next();
if (e.getKey().matches("id_(\\d+)")) {
result.append(e.getValue());
result.append(",");
}
}
result.append(")");
vars.put("expected_value", result.toString());
Above code will store the resulting string into ${expected value} JMeter Variable. See How to Use BeanShell: JMeter's Favorite Built-in Component article for more information regarding bypassing JMeter limitations using scripting and using JMeter and Java API from Beanshell test elements.
Demo:

Resources