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.
Related
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)
I am using the below script in a Beanshell Postprocessor
import java.io.*;
File f =new File ("C:\Users\xxxxx\Desktop\testresults.csv");
FileWriter fw=new FileWriter(f,true);
BufferedWriter bw=new BufferedWriter(fw);
var r=prev.getResponseCode();
if (r.equals("200"))
{
bw.write("Test Passed");
}
else
{
bw.write("Test failed");
}
bw.close();
fw.close();
But I am getting the below error
BeanShellInterpreter: Error invoking bsh method: eval Sourced file: inline evaluation of: ``import java.io.*; File f =new File ("C:\Users\xxxxx\Desktop\testresults.csv") . . . '' Token Parsing Error: Lexical error at line 2, column 23. Encountered: "U" (85), after : ""C:\".
What could cause the above error.
You need to escape a backslash with a backslash like:
C:\\Users\\xxxxx\\Desktop\\testresults.csv
or use a forward slash instead:
C:/Users/xxxxx/Desktop/testresults.csv
A couple more hints:
Since JMeter 3.1 you should be using JSR223 Test Elements and Groovy language for scripting
If you run your test with 2 or more concurrent threads they will be writing into the same file resulting in data corruption due to a race condition so maybe it worth considering switching to Flexible File Writer instead
Change to JSR223 Post Processor and write as one line (groovy default)
new File("C:\\Users\\xxxx\\Desktop\\\testresults.csv") << (prev.getResponseCode().equals("200") ? "Test Passed" : "Test failed")
For encrypting the input I am using the below code but facing the error
import java.util.Base64;
String plainPassword=vars.get("PW");
log.info(plainPassword);
String encodedPassword = new String(Base64.encodeBase64(plainPassword.getBytes()));
vars.put("encodedpassword", encodedPassword);
log.info("encodedpassword");
ctx.getCurrentSampler().getArguments().getArgument(0).setValue(encryptedpassword);
Error says:
Problem in BeanShell script. org.apache.jorphan.util.JMeterException: Error invoking bsh method: eval
Sourced file: inline evaluation of: import java.util.Base64;
String plainPassword=vars.get("PW");
log.info(plainPa . . . : Typed variable dec
I fail to see encodeBase64() function in java.util.Base64 JavaDoc so double check the source from which you copied and pasted it.
Since JMeter 3.1 it's recommended to use JSR223 Test Elements and Groovy language for scripting so you can change 2nd line of your "script" to something like:
String encodedPassword = plainPassword.bytes.encodeBase64().toString()
Full correct code just in case:
String plainPassword=vars.get("PW");
log.info(plainPassword);
String encodedPassword = plainPassword.bytes.encodeBase64().toString();
vars.put("encodedpassword", encodedPassword);
log.info(encodedPassword);
sampler.addNonEncodedArgument('', encodedPassword, '');
Demo:
More information: Apache Groovy - Why and How You Should Use It
Getting below error in log:
2020-06-24 13:23:51,091 ERROR o.a.j.u.BeanShellInterpreter: Error invoking bsh method: eval Sourced file: inline evaluation of: //to output the execution flow in the jmeter.log to help demonstrate how the scr . . . '' : Typed variable declaration : Attempt to resolve method: getName() on undefined variable or class name: sampler 2020-06-24 13:23:51,091 WARN o.a.j.e.BeanShellPostProcessor: Problem in BeanShell script: org.apache.jorphan.util.JMeterException: Error invoking bsh method: eval Sourced file: inline evaluation of: //to output the execution flow in the jmeter.log to help demonstrate how the scr . . . '' : Typed variable declaration : Attempt to resolve method: getName() on undefined variable or class name: sampler 2020-06-24 13:23:51,154 ERROR o.a.j.u.BeanShellInterpreter: Error invoking bsh method: eval Sourced file: inline evaluation of: //to output the execution flow in the jmeter.log to help demonstrate how the scr . . . '' : Typed variable declaration : Attempt to resolve method: getName() on undefined variable or class name: sampler 2020-06-24 13:23:51,154 WARN o.a.j.e.BeanShellPostProcessor: Problem in BeanShell script: org.apache.jorphan.util.JMeterException: Error invoking bsh method: eval Sourced file: inline evaluation of: //to output the execution flow in the jmeter.log to help demonstrate how the scr . . . '' : Typed variable declaration : Attempt to resolve method: getName() on undefined variable or class name: sampler 2020-06-24 13:23:51,236 ERROR o.a.j.u.BeanShellInterpreter: Error invoking bsh method: eval Sourced file: inline evaluation of: //to output the execution flow in the jmeter.log to help demonstrate how the scr . . . '' : Typed variable declaration : Attempt to resolve method: getName() on undefined variable or class name: sampler 2020-06-24 13:23:51,236 WARN o.a.j.e.BeanShellPostProcessor: Problem in BeanShell script: org.apache.jorphan.util.JMeterException: Error invoking bsh method: eval Sourced file: inline evaluation of://to output the execution flow in the jmeter.log to help demonstrate how the scr . . . '' : Typed variable declaration : Attempt to resolve method: getName() on undefined variable or class name: sampler
Below is the code used in Beanshell postprocessor.
import java.text.DecimalFormat;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
int tdNumber = ctx.getThreadNum();
int noThreads = ctx.getThreadGroup().getNumThreads();
long tdstart = ctx.getThread().getStartTime();
long tdEnd = ctx.getThread().getEndTime();
String respCode = ctx.getPreviousResult().getResponseCode();
String respCode = ctx.getPreviousResult().getResponseMessage();
String samplerName = sampler.getName();
Date date = new Date();
date.setDate(date.getDate());
SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
String formattedDate = df.format(date);
log.info("sampler::"+ sampleName +"....ThreadNo::"+ (tdNumber + 1) +" ....Starttime::"+ formattedDate +
"....StatusCode::" + respCode +"....TotalThreads::"+ noThreads +" ....Iterationno::"+vars.getIteration());
undefined variable or class name: sampler
There is no sampler shorthand in the Beanshell PostProcessor, you should use one of the following alternatives:
prev.getSampleLabel(false)
ctx.getCurrentSampler().getName()
Also be aware that starting from JMeter 3.1 you should be using JSR223 Test Elements and Groovy language for scripting so consider migrating to Groovy on next available opportunity.
More information on this ctx, prev and friends: Top 8 JMeter Java Classes You Should Be Using with Groovy
Move to JSR223_PostProcessor which is the best practice and include also sampler
Migration to JSR223 PostProcessor+Groovy is highly recommended for performance, support of new Java features and limited maintenance of the BeanShell library.
I cannot seem to get past the BeanShellInterpreter whenever I try and use __FileToString built-in function in a BeanShell PreProcessor script. The FileContents variable does get populated, but the script fails and I cannot work with it. Here is the code and the error messages...
try {
Integer count=vars.get("SessionId").length()-5;
vars.put("vAuth", vars.get("v_username") + vars.get("SessionId").substring(count) + ":" );
log.info("Writing a info message");
${__FileToString(C:/tmp/DeltaConnectDemoTool_3_2_0S1_5515/bin/request.txt,,FileContents)};
log.info("Writing a second info message");
}
catch (Throwable ex ) {
log.error("Failed to do this or that", ex);
}
The Error is
2016/11/17 15:52:18 ERROR - jmeter.util.BeanShellInterpreter: Error invoking bsh method: eval In file: inline evaluation of: ``try { Integer count=vars.get("SessionId").length()-5; vars.put("vAuth", vars.get . . . '' Encountered ":" at line 5, column 8.
2016/11/17 15:52:18 WARN - jmeter.modifiers.BeanShellPreProcessor: Problem in BeanShell script org.apache.jorphan.util.JMeterException: Error invoking bsh method: eval In file: inline evaluation of: ``try { Integer count=vars.get("SessionId").length()-5; vars.put("vAuth", vars.get . . . '' Encountered ":" at line 5, column 8.
try putting the string path to file in double quotes, like:
${__FileToString("C:/tmp/DeltaConnectDemoTool_3_2_0S1_5515/bin/request.txt",,FileContents)};
That's why inlining functions or variables into the script body is not recommended. You have 2 alternative options:
Use the function in the "Parameters" section. If the functions returns some value you will be able to refer in later in the Beanshell code as Parameters or bsh.args[0] like:
Implement the function in the Beanshell code. In your case it can be FileUtils.readFileToString() function:
String FileContent = org.apache.commons.io.FileUtils.readFileToString(new File("request.txt"));
vars.put("FileContent", FileContent);
See How to Use BeanShell: JMeter's Favorite Built-in Component for some extra information on scripting in JMeter