How to use StringFromFile function within a JSR223 Sampler? - jmeter

I can't find any good docs/examples on how to use the StringFromFile function to get multiple records from a source data file from within a JSR223 Sampler. Could somebody please help me?
My code which doesn't work:
String filename = "filename.csv";
String record = StringFromFile(filename,"id");

You shouldn't be using it directly in the scripts, as per JSR223 Sampler documentation:
When using this feature, ensure your script code does not use JMeter variables directly in script code as caching would only cache first replacement. Instead use script parameters.
So the solution would be using File.readLines() function which reads the file into a List of strings
More information: The Groovy Templates Cheat Sheet for JMeter

Related

JMeter loop index always return 0 in Loop Controller

When I use the command ${__jm__myLoopControllerName__idx} in JSR223 Sampler, it always returns 0 as the index.
The sampler is in the Loop Controller. But I can see that the CSV file I'm looping is done for each line because in the listener "View Result Tree" I can see in the Request Headers, that the data is from each line. What am I doing wrong ?
Thanks for your help.
M.
Use vars to get variable in JSR223 script:
String index = vars.get("__jm__myLoopControllerName__idx");
variable inside ${} syntax is getting cached
ensure the script does not use any variable using ${varName} as caching would take only first value of ${varName}. Instead use : vars.get("varName")
As per JSR223 Sampler documentation:
The JSR223 test elements have a feature (compilation) that can significantly increase performance. To benefit from this feature:
Use Script files instead of inlining them. This will make JMeter compile them if this feature is available on ScriptEngine and cache them.
Or Use Script Text and check Cache compiled script if available property.>
When using this feature, ensure your script code does not use JMeter variables or JMeter function calls directly in script code as caching would only cache first replacement. Instead use script parameters.
So either put your ${__jm__myLoopControllerName__idx} to "Parameters" section and refer it as "Parameters" in your script:
or use vars shorthand for JMeterVariables class instance like:
vars.get('__jm__myLoopControllerName__idx')

jmeter beanshell call jmeter function

I have a HTTP request sampler configured. In the request body, I call out to a beanshell function I wrote:
${__BeanShell(createHeader("GET"\,"Customer"\,"${__UUID}"\,"${__time(yyyy-MM-dd'T'hh:mm:ss)}"))}
The function just builds some request strings with the passed-in parameters. I want to remove the jmeter function calls (__UUID and __time), and call them directly from within the beanshell function. I could not find a way to do that.
Thanks
Don't inline JMeter Functions or Variables into scripts, in your case you will have to go for code-based equivalents instead, to wit:
__UUID() -> UUID.randomUUID().toString()
__time() -> new java.text.SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss").format(new Date())
Since JMeter 3.1 it's recommended to use JSR223 Test Elements and Groovy language for scripting, in your case it would be __groovy() function. If you want to re-use createHeader method - you can put it into a separate .groovy file and define groovy.utilities property pointing to this file.
See Apache Groovy - Why and How You Should Use It article for more information on using Groovy scripting in JMeter tests.

On using a CSV config with JSON data the quotes are read incorrectly for the key value pair

I have a POST data from CSV used in excel
{"Name":"","Token":-1,"TimeScheduleToken":"1","AccessRule":[{"ObjectToken":"528","ObjectName":"Common_ wash_Room_Exit","RuleToken":"528","RuleType":2,"StartDate":null,"EndDate":null,"ArmingRightsId":null,"ControlModeId":null}]}
When performing a post-execution the JSON data in the request is not as same as from the CSV. Find the request in the image
Quotes given for the key value pair is doubled up and showed in the request. How to resolve this, kindly suggest
Vittal,
I have tried to reproduce your issue in JMeter 3.3 and noticed that its working fine. Please find below the settings that you need to do in 'CSV Data Config' element.
Moreover, I would recommend that when you are creating any csv file for the data then open the notepad and enter your data and then save it as .csv file to avoid any unnecessary elements/characters in the data.
You can also refer to the blog post to get more information on API load testing using JMeter: JMeter Load Testing Against APIs
I have no idea regarding how you're getting these double quotation marks, however here is how you can remove them in the runtime:
Add JSR223 PreProcessor as a child of the HTTP Request sampler
Put the following code into "Script" area:
def originalData = sampler.getArguments().getArgument(0).getValue()
def normalizedData = originalData.replaceAll("\"\"","\"")
sampler.getArguments().removeAllArguments()
sampler.addNonEncodedArgument("",normalizedData,"")
sampler.setPostBodyRaw(true)
That's it, the JSR223 PreProcessor will replace all occurrences of double quotation marks with single quotation marks.
sampler is a shorthand to parent sampler class implementation, in case of HTTP Request sampler it would be HTTPSamplerProxy, see class documentation for all available functions and properties.
See Apache Groovy - Why and How You Should Use It article to learn more about using Groovy scripting in JMeter tests.

how can i pass dynamic values to url in jmeter

I have to give dynamic values to url which takes number of users and their age , which can be selected though web page. but I want to give it in Jmeter using BeanShell PostProcessor.
Help me in this,since I'm new to Jmeter.
This is the path:
/destinations/packages?airports%5B%5D=LGW&units%5B%5D=000577%3ADESTINATION&when=29-05-2016&until=&flexibility=true&flexibleDays=3&noOfAdults=2&noOfSeniors=0&noOfChildren=1&childrenAge=3&duration=7114&first=0&searchType=search&searchRequestType=ins&sp=true&multiSelect=true
from what I've got looks like you can use CSV Data Set Config.
Create .txt file with the data you want to feed your test with;
Place the above .txt file to the folder where your .jmx file lies;
In your Test plan: Under your request sampler - place CSV Data set Config;
Then if you need to use your dynamic values within one threadgroup => refer these data as ${quanity}, ${age} in you url.
If you need to pass these values across the threadgroups => add BeanShell Assertion
Then (in the other Tread group) refer those as ${__property(_quantity)},${__property(_age)}.
Hope, it helps.
First of all you need Beanshell PreProcessor, not Beanshell PostProcessor.
All this parameters are basically name/value pairs which can be defined via HTTPSamplerBase class. HTTPSamplerBase class instance is available to Beanshell PreProcessor as sampler pre-defined variable so if you add the following code into the Beanshell PreProcessor "Script" area
sampler.addEncodedArgument("airports[]","LGW");
sampler.addEncodedArgument("units[]","000577:DESTINATION");
sampler.addEncodedArgument("when","29-05-2016");
sampler.addEncodedArgument("until","");
sampler.addEncodedArgument("flexibility", "true");
sampler.addEncodedArgument("flexibleDays","3");
sampler.addEncodedArgument("noOfAdults","2");
//etc
Your HTTP request will be populated with the values, you set via Beanshell.
JMeter Variables can be accessed via vars shorthand which stands for JMeterVariables class instance.
String airport = vars.get("airport");
sampler.addEncodedArgument("airports[]", airport);
//etc
See How to Use BeanShell: JMeter's Favorite Built-in Component article for comprehensive information on how to use Beanshell Test Elements in Jmeter.
Remember that it is recommended to avoid scripting where possible so if there is another way of implementing your task - go for it.

How do I call a Custom Function in JMeter

I've created a custom function in JMeter that returns a n length string with random characters. Where should I define the function, and how do I call it?
As long as your function is in the jmeter classpath, you should be able to call it just like any standard function with ${...} syntax, as described here.
Do make sure your jar file containing your function is in lib/ext, or added to the jmeter classpath via search_path's input option
You can do this in a beanshell script or via a javascript call. See the manual on
functions and on the beanshell preprocessor.

Resources