how to pass a dynamic file path to filename field of Flexible File Writer of jmeter - jmeter

I need to generate the dynamic file path in the setup thread group like below.
def result_file = new File(org.apache.jmeter.services.FileServer.getFileServer().getBaseDir() + File.separator + 'transactions_passed_' + new Date().format('MM_dd_yyyy_HH_mm_ss') + '.csv');
props.put("result_file", result_file);
Now I want to pass that file path as a filename value of Flexible File Writer plugin of jmeter so that variables are stored inside it.
Not able to make it work. Kindly help. Thanks
I have tried below options:
Filename: ${__groovy(props.get("result_file").text)}
tried to use preprocessor and set the value:
vars.put("result_file", '${__FileToString(props.get("result_file"),,)}');
Also tried to use below groovy script in the FileName field of Flexible File Writer, however it throws an exception of FileNotFound exception:
${__groovy(new File(org.apache.jmeter.services.FileServer.getFileServer().getBaseDir() + System.getProperty('file.separator') + 'transactions_passed_' + new Date().format('MM_dd_yyyy_HH_mm_ss') + '.csv').text)}
I want to use DYNAMIC FILE PATH (which I am setting as property in setup thread group) in the FILENAME field of FLEXIBLE FILE WRITER

The approach with __groovy() function should work however you need to remove this .text bit from there
${__groovy(new File(org.apache.jmeter.services.FileServer.getFileServer().getBaseDir() + System.getProperty('file.separator') + 'transactions_passed_' + new Date().format('MM_dd_yyyy_HH_mm_ss') + '.csv'))}
because .text returns you the file contents and as the file doesn't exist - you're getting this FileNotFound error. More information on Groovy scripting in JMeter - Apache Groovy: What Is Groovy Used For?

Related

Getting error in accessing Jmeter variables (variable_MarchNr) in yaml in beanshell script

I am trying to bulk edit one entity called issues, I call GetIssues API and via json extractor, get all issueId's in variable "issueIds"
json extractor to extract issueIds
Now I want to pass these Ids in other api bulk edit issues, If I directly use these array in next API, I get below error:
{"details":"Unexpected token $ in JSON at position 19","metadata":{}}
So I used to below code in Beanshell Post processor:
var mylist;
props.put("mylist", new ArrayList());
log.info("Detected " + vars.get("issueIds_matchNr") + " issueIds");
for (int i=1; i<= Integer.parseInt(vars.get("issueIds_matchNr")); i++) {
log.info("IDs # " + i + ": " + vars.get("issueIds_" + i));
props.get("mylist").add('"' + vars.get("issueIds_" + i) + '"' );
}
log.info(props.get("mylist").toString());
var issueIdList;
vars.put("issueIdList", props.get("mylist").toString());
log.info(vars.get("issueIdList"));
In my next api call if I pass issueIdList variable, then this works fine in jmeter.
sample variable values in debug sampler are like:
issueIdList=["555bcfc2", "33974d2c", "e58db1d6"]
issueIds_1=555bcfc2
issueIds_2=33974d2c
issueIds_3=e58db1d6
issueIds_matchNr=3
Problem I am facing if I convert my jmx2yaml and tried to run this file with
bzt issues.yml
then while executing above shell script, these issueIds_matchNr, issueIds_3 are not detected, I get below error;
2022-05-29 08:26:10,785 INFO o.a.j.e.J.JSR223PostProcessor: Detected null issueIds
2022-05-29 08:26:10,795 ERROR o.a.j.e.JSR223PostProcessor: Problem in JSR223 script, JSR223PostProcessor
javax.script.ScriptException: Sourced file: eval stream : Method Invocation Integer.parseInt : at Line: 4 : in file: eval stream : Integer .parseInt ( vars .get ( "issueIds_matchNr" ) )
Target exception: java.lang.NumberFormatException: null
in eval stream at line number 4
at bsh.engine.BshScriptEngine.evalSource(BshScriptEngine.java:87) ~[bsh-2.0b6.jar:2.0b6 2016-02-05 05:16:19]
My Yaml script is:
- extract-jsonpath:
issueIds:
default: NotFound
jsonpath: $..id
follow-redirects: true
jsr223:
- compile-cache: true
execute: after
language: beanshell
parameters: issueIds
script-file: script.bsh
label: Get Issue Id's
method: GET
url: https://${BASE_URL1}/${PROJECT_ID}/issues?limit=5&sortBy=-displayId&filter%5Bvalid%5D=true
You're missing one important bit: setting the Match Nr in your Taurus YAML
The correct definition of the JSON Extractor would be something like:
extract-jsonpath:
issueIds:
jsonpath: $..id
match-no: -1 #this is what you need to add
Also be informed that starting from JMeter 3.1 it's recommended to use Groovy as the scripting language so consider migrating, it will be as simple as removing the first line from your script.bsh

Jmeter BeanShellSampler error: Error invoking bsh method: eval import org.apache.commons.io.FileUtils

I use BeanShell code loading 100s of sql files in jmeter:
import org.apache.commons.io.FileUtils;
File folder = new File("D:\\sql99");
File[] sqlFiles = folder.listFiles();
for (int i = 0; i < sqlFiles.length; i++) {
File sqlFile = sqlFiles[i];
if (sqlFile.isFile()) {
vars.put("query_" + i,sqlFile.getName(),
FileUtils.readFileToString(sqlFiles[i]));
}
}
but get error info :
17:42:03,301 ERROR o.a.j.u.BeanShellInterpreter: Error invoking bsh method: eval Sourced file: inline evaluation of: ``import org.apache.commons.io.FileUtils; File folder = new File("D:\sql99"); Fi . . . '' : Error in method invocation: Method put( java.lang.String, java.lang.String, java.lang.String ) not found in class'org.apache.jmeter.threads.JMeterVariables'
I want to get each sql execute time in jmeter results tree. How to fix code?
Thanks!
You're trying to call JMeterVariables.put() function which accepts 2 Strings as the parameters passing 3 Strings
The correct syntax is vars.put("variable-name", "variable-value"); so you need to decide how to amend this line:
vars.put("query_" + i, sqlFile.getName(), FileUtils.readFileToString(sqlFiles[i]));
so it would contain only 2 parameters instead of 3.
Also since JMeter 3.1 it's recommended to use JSR223 Test Elements and Groovy language for scripting mainly for performance reasons so it might be a good option for switching (the same code will work in Groovy without changes assuming you fix the issue with vars.put() function call)

Error on accessing Output Variable in beanshell preprocessor in Jmeter

I am unable to print 'Output Variable' value of foreach Controller in Beanshell Pre/Post-processor in Jmeter.
log.info("inside hash"+ ${current_file} ); //current_file is the Output variable name defined in foreach controller and has the value of current file path.
File file=new File(${current_file});
byte[] content = FileUtils.readFileToByteArray(file);
Whenever I execute the tests, I get this error:
2021-12-15 19:58:25,208 ERROR o.a.j.u.BeanShellInterpreter: Error invoking bsh method: eval In file: inline evaluation of: ``import org.apache.commons.io.FileUtils; import org.apache.jmeter.services.FileSe . . . '' Encountered "( "inside hash" + C :" at line 4, column 9.
Can anyone help me fix this error?
Don't inline JMeter functions or variables in form of ${current_file}, use vars shorthand for JMeterVariables class instance instead
Something like:
String current_file = vars.get("current_file");
log.info("inside hash"+ current_file );
File file=new File(current_file);
Don't use Beanshell, since JMeter 3.1 it's recommended to use JSR223 Test Elements and Groovy language for scripting, there is a chance that your code will just start working after switching to Groovy or at least you will get more informative errors.

Jmeter Construct Parameter Value based on DataSet

In JMeter, I want to construct the request parameter value from a dataset file based on the PropertyCount.
Dataset
PropertyCount propertyid1 propertyid2 propertyid3
2 13029526 15763743
3 13029526 15763743 12345645
2 13029526 15763743
Request Input Parameter
"values":["13029526","15763743"]
"values":[${outputString}]
PreProcessor Script
With the the below preprocessor script, I am getting the following output but looking to get the values as in Request Input Parameter, with quotes.
2021-08-29 22:15:04,706 INFO o.a.j.m.J.JSR223 PreProcessor: Required output: 13029526,15763743,
2021-08-29 22:15:04,785 INFO o.a.j.m.J.JSR223 PreProcessor: Required output: 13029526,15763743,
JSR223 PreProcessor
def requiredOutput = new StringBuilder()
1.upto(vars.get('propertycount') as int, {
requiredOutput.append(vars.get('propertyid' + it))
requiredOutput
requiredOutput.append(',')
vars.put("outputString",requiredOutput.toString());
})
You're seem to be constructing a JSON Array therefore it makes more sense to consider using Groovy's JsonBuilder instead of doing manual string concatenation:
def outputString = []
1.upto(vars.get('PropertyCount') as int, {
outputString.add(vars.get("propertyid$it"))
})
vars.put('outputString', new groovy.json.JsonBuilder(outputString).toPrettyString())
More information:
Apache Groovy - Parsing and producing JSON
Apache Groovy - Why and How You Should Use It

ML Gradle task.Server.Eval.Task setting variables using xquery

I'm using ml-gradle to run a block of XQuery to update the MarkLogic database. The problem I am running into is I need to wrap all of the code in quotes, but since the code itself has quotes in it I am running into some errors when I try to declare variables i.e. let $config. Does anyone know a way around this? I was thinking I could concatenate all of the code into one big string so it ignores the first and last quotation.
task addCron(type: com.marklogic.gradle.task.ServerEvalTask) {
xquery = "xquery version \"1.0-ml\";\n" +
"import module namespace admin = \"http://marklogic.com/xdmp/admin\" at \"/MarkLogic/admin.xqy\";\n" +
"declare namespace group = \"http://marklogic.com/xdmp/group\";\n" +
" let $config := admin:get-configuration()\n" +
It bombs out when it is trying to declare $config as a variable. With the error:
> Could not get unknown property 'config' for task ':
Here is an example that works
task setSchemasPermissions(type: com.marklogic.gradle.task.ServerEvalTask) {
doFirst {
println "Changing permissions in " + mlAppConfig.schemasDatabaseName + " for:"
}
xquery = "xdmp:invoke('/admin/fix-permissions.xqy', (), map:entry('database', xdmp:database('" + mlAppConfig.schemasDatabaseName + "')))"
}
Here is some documentation for ServerEvalTask: https://github.com/marklogic-community/ml-gradle/wiki/Writing-your-own-task
I suspect you are hitting some string template mechanism in Groovy/Gradle. Try escaping the $ sign as well.
Note that you can use both single and double quotes in XQuery code.
HTH!

Resources