How to capture thread specific different data form drop down list in jmeter? - jmeter

My application consist the Select Title drop down list contains values as Mr, Miss, Dr & Mrs.
I want to capture the different title (Random but from above 4) for different thread. please suggest how it is possible.
This is my script i have pass the title parameter as ${randomTitle}
Value pass to database as,
Post request as,

Out of interest, is it vital to use enum there?
Try amending your code as follows:
import java.util.Random;
String[] frm_titles = {"Mr", "Miss", "Dr", "Mrs"};
Random randGenerator = new Random();
int randInt = randGenerator.nextInt(frm_titles.length);
vars.put("randomTitle",frm_titles[randInt]);
It should work this way. Enum must not be local to Beanshell interpreter, if you need to use enum structure - compile it as .jar and place it to JMeter classpath.
See How to use BeanShell: JMeter's favorite built-in component guide for more details on Beanshell scripting in Apache JMeter.

You can use Beanshell Preprocessor:
import java.util.Random;
public enum frm_titles {"Mr", "Miss", "Dr", "Mrs"};
Random randGenerator = new Random();
int randInt = randGenerator.nextInt(frm_titles.values().length);
vars.put("randomTitle",frm_titles.values()[randInt].toString());
Then, in your test plan change the post params and add ${randomTitle} instead your title param.
Check this links for more info:
http://www.beanshell.org/manual/quickstart.html
http://jmeter.apache.org/usermanual/component_reference.html#BeanShell_Sampler
http://jmeter.apache.org/usermanual/functions.html
http://testeverythingqtp.blogspot.com.es/2013/01/jmeter-bean-shell-script-create-file.html
http://jmeter-kh.blogspot.com.es/2009/07/how-to-make-beanshell-work-in-jmeter.html

I think 2 ways are possible,
you can try beanshell processor
you can try regular expression extractor and counter
first approach is best explained above, for 2nd approach you can try,
Random product selection using Jmeter

Related

Jmeter - Calling javascript using JSR223 Post processor

I capture 6 elements using a regular expression. say
Variable : UserDetails
Regular Expression : loadHeadWorkFlow\('(.+?)','(.+?)','(.+?)','(.+?)','(.+?)','(.+?)','/I
Template : $1$$2$$3$$4$$5$$6$
Now I could access these values via UserDetails_g1, UserDetails_g2.....UserDetails_g6
Next, these 6 values need to be encrypted using a javascript file. The file contains the logic.
How should my code be using JSR223 post processor?
The steps that I followed:
1.
load('Encryption.js');
var result = encrypt("${UserDetails_g1}","password");
log.info("encrypted value is "+result);
vars.put("LoginDataString",result);
var result1 = encrypt("${UserDetails_g2}","password1");
vars.put("UserId",result1);
var result2 = encrypt("${UserDetails_g3}","password2");
vars.put("RoleId",result2);
First value is encrypted correctly. But the other values aren't correct. If I add individual post processors for every variable. All the encrypted values show correctly.
Is there a way where I could use a single post processor to perform all the 6 encryptions. Thanks in advance
Regards,
Ajith
Use vars instead of ${} syntax
var result = encrypt(vars.get("UserDetails_g1"),"password");
log.info("encrypted value is "+result);
vars.put("LoginDataString",result);
var result1 = encrypt(vars.get("UserDetails_g2"),"password1");
vars.put("UserId",result1);
var result2 = encrypt(vars.get("UserDetails_g3"),"password2");
vars.put("RoleId",result2);
From JMeter perspective there is no problems, just check that your UserDetails_g2 variable has anticipated value using Debug Sampler and View Results Tree listener combination., the you might want to check this encrypt() function implementation.
Another possible reason is this JavaScript language selection itself, the Nashorn engine performance is a big question mark when it comes to the load, according to JMeter Best Practices it's recommended to use Groovy language for scripting so you might want to consider re-writing the function in Groovy

How to get the name given to transaction controller using beanshell preprocesssor in jmeter

I want to get the name given to transaction controller using BeanShell preprocessor in JMeter.
Which I want to use to connect and display in dynaTrace later using header manager.
I tried something like this using BeanShell listener
String test = sampleResult.getSampleLabel();
log.info(test);
but I want to use the preprocessor.
log.info(sampler.getName());
This is used to get the name of sampler, in the similar way I want to get the name of transaction controller.
Specifically, I want to use BeanShell preprocessor .
Can somebody help me in this?
You cannot walk further than Previous Result or Previous Sampler so I would state that it is not something you can implement easily. Looks like your test is not very well designed as normally people do not require knowing the name of the parent sampler controller.
Nevertheless you can get access to JMeter Test Plan Tree and figure out information from there. The example code will look something like:
import org.apache.jmeter.control.TransactionController;
import org.apache.jmeter.engine.StandardJMeterEngine;
import org.apache.jorphan.collections.HashTree;
import org.apache.jorphan.collections.SearchByClass;
import java.lang.reflect.Field;
import java.util.Collection;
StandardJMeterEngine engine = ctx.getEngine();
Field test = engine.getClass().getDeclaredField("test");
test.setAccessible(true);
HashTree testPlanTree = (HashTree) test.get(engine);
SearchByClass txnCtrlSearch = new SearchByClass(TransactionController.class);
testPlanTree.traverse(txnCtrlSearch);
Collection txnControllers = txnCtrlSearch.getSearchResults();
for (Object txnController : txnControllers) {
log.info(((TransactionController) txnController).getName());
}
Demo:
Some information on using JMeter API from Beanshell scripts: How to Use BeanShell: JMeter's Favorite Built-in Component

How can I navigate the JMeter test element tree from within a sampler script

From a JSR223 Sampler, I can get access to the current test element using the sampler variable.
From there, how can I navigate the tree of TestElement objects? For example, how can I get access to the parent test element (and then it’s parent, etc) or how can I get access to the TestPlan test element?
Background:
I want to dynamically create a JDBC Connection Configuration element from a JSR223 Sampler using Groovy.
From other questions (e.g., here) and web searches (e.g., here), I know how to create test plan elements from the top down (e.g., how to create a test plan and build the tree down from there). So I know how to do the new DataSourceElement() which is a TestElement but I don’t know how to add that new element to the test plan. In the sampler script I have access to the sampler (Sampler) and the ctx (JMeterContext) variables but I don’t know how to navigate the test element tree.
I tried just using sampler.addTestElement but a config element isn’t really valid under a sampler element. Still, I did try but the config element was not found when I tried to use it in a JDBC Request (error: "No pool found named: 'myDatabaseThreadPool', ensure Variable Name matches Variable Name of JDBC Connection Configuration").
I’m hoping that if I can get the TestPlan element and add the config element to that, then it would work.
FWIW, my test plan looks like this:
Test Plan
Thread Group 1 (could be a setup thread group)
JSR223 Sampler (this is where I want to create the dynamic config)
Thread Group 2 (multiple threads)
JDBC Request (uses the pool variable name specified in the dynamic config)
View Results Tree
I can go into further detail about why I want to dynamically create the JDBC Connection Configuration, but if there’s an easy answer about how to navigate the test element tree from inside my sampler script I’d like to know that anyway.
As you have mentioned you have access to JMeterContext via ctx shorthand. Hence you have access to StandardJMeterEngine class instance via ctx.getEngine(); method.
Looking into StandardJMeterEngine source you can see that test plan is being stored as HashTree structure:
private HashTree test;
So the choices are in:
change access modifier to public and recompile JMeter from sources
use Trail - Java Reflection API in order to access test value
Reference code:
import org.apache.jmeter.engine.StandardJMeterEngine;
import org.apache.jmeter.testelement.TestPlan;
import org.apache.jorphan.collections.HashTree;
import org.apache.jorphan.collections.SearchByClass;
import java.lang.reflect.Field;
import java.util.Collection;
StandardJMeterEngine engine = ctx.getEngine();
Field test = engine.getClass().getDeclaredField("test");
test.setAccessible(true);
HashTree testPlanTree = (HashTree) test.get(engine);
SearchByClass testPlans = new SearchByClass(TestPlan.class);
testPlanTree.traverse(testPlans);
Collection testPlansRes = testPlans.getSearchResults();
TestPlan testPlan = (TestPlan)testPlansRes.toArray()[0];
//do what you need with "testPlanTree" and/or "testPlan"
Check out How to Use BeanShell: JMeter's Favorite Built-in Component guide for more information using JMeter and Java API from scripting test elements.

Jmeter while controller doesn't seem to evaluate variables as numbers

I am writing a jmeter script that keeps loading data until a table reaches a specified size. I have a while loop, in which I have one HTTP Sampler to loads the data, then another HTTP Sampler with an XPath Post-processor to check the table size (they call two different APIs). The reference variable of the XPath Post Processor is currentSize and I have a user defined variable maxSize, but using ${currentSize} < ${maxSize} as the condition for the while loop creates an infinite loop.
Thinking maybe the problem is that the output of XPath is a string, I've tried doing various things in beanshell to coerce it to a number, but I'm a beanshell noob, so I haven't been successful with that either. Can anyone guide me about how to get jmeter to recognize a variable as a number? (Preferably a decimal, but if I have to round to an int, I can live with that.)
Thanks!
I think using __javascript(parseInt()) should suffice for you to check the condition.
e.g.
${__javaScript(parseInt(${time_elapsed_string}) < parseInt(${duration}))}
Assuming that you have following variables:
currentSize
maxSize
continue
where continue is set via User Defined Variables and has the value of true
You can use following Beanshell code to check if current size is equal or greater than maximum size:
import java.math.BigDecimal;
String currentSize = vars.get("currentSize");
String maxSize = vars.get("maxSize");
BigDecimal currentSizeNumber = new BigDecimal(currentSize);
BigDecimal maxSizeNumber = new BigDecimal(maxSize);
if (currentSizeNumber.compareTo(maxSizeNumber) > -1){
vars.put("continue", "false");
}
Make sure that following criteria are met:
Your While Controller has ${continue} as a condition
Beanshell Sampler, Pre / Post Processor or Assertion with the code above is added as a child of the While Controller
See How to use BeanShell guide for more details and kind of Beanshell cookbook.
Everything should work this way.
Hope this helps.

JMeter set variable to random option

I've been using JMeter and I'm aware of the __Random and __RandomString functions. I need to pick a random option and store it in a variable because it will be used as part of a parameter path for multiple calls. For example:
http://www.example.com/pets/{random option such as: cat, dog, parakeet}/
I've tried doing simple like this, where I set the variable ${query} to one, two, or three using a random controller with userdefined variables as children. This seems like it should work, however I always get ${query} set to three.
Any insight or ideas are will be well recieved. Thanks to all in advance.
You can use Beanshell Pre Processor to generate random value
String[] query = new String[]{"cat", "dog", "parakeet"};
Random random = new Random();
int i = random.nextInt(query.length);
vars.put("randomOption",query[i]);
After that in your HTTP Request
http://www.example.com/pets/${randomOption}
As an alternative to String[] query = new String[]{"cat", "dog", "parakeet"}; you can use Beanshell pre-defined Parameters stanza.
Random random = new Random();
int i = random.nextInt(query.length);
vars.put("randomOption",bsh.args[i]);
I know this is an old post and there is a new function available:
__RandomFromMultipleVars(animalCat|animalDog|animalParakeet, query)
somewhere you need to define the variables:
animalCat=cat
animalDog=dog
animalParakeet=parakeet
It looks like this is not a feature of Jmeter natively. I'm using a plugin that accomplishes this goal. http://jmeter-plugins.org/wiki/Functions/ implements a new function that lets you choose a random string from a list of strings. From their website:
${__chooseRandom(red,green,blue,orange,violet,magenta,randomColor)}
See also:
Get random values from an array
This however requires writing some code in a PreProcessor.

Resources