This blog post aims to be a collection of sample JSR223, Beanshell and other useful reusable scripts. Use them freely in your JMeter projects to leverage the power of JMeter! Reuse them in JSR223 samplers directly as is, or modify them to fit your needs.
Many other example JSR223 samples can be found in our documentation.
Log a Message
1
2
3
|
log.info("This is the log for INFOR level");
log.warn("This is the log for WARNING level");
log.error("This is the log for ERROR level");
|
Print message in Console
Prints a message in the JMeter launch console.
1
|
OUT.println("INPUT MESSAGE HERE");
|
Manipulate a Variable
1
2
3
4
5
|
vars.get("VARIABLE_NAME");
vars.put("VARIABLE_NAME","VALUE");
String my_var = vars.get("MY_VARIABLE");
log.info("The value of my_var is " + my_var);
|
Increment an Integer
1
2
3
4
5
6
|
int my_number = vars.get("MY_NUMBER").toInteger();
int new_number = 3;
int add = my_number + new_number;
vars.put("MY_NUMBER", add.toString());
|
Read Write Properties
1
2
3
4
5
|
props.get("PROPERTY_NAME");
props.put("PROPERTY_NAME", "VALUE");
//update the existing property
props.put("jmeter.version","3.1")
|
Multiply Function
The following scripts are written in groovy.
1
2
3
4
|
def mutiplyTwoNumber = { a,b -> a * b};
//put the function in to JMeter property
props.put("MUTIPLY_TWO_NUMBER", mutiplyTwoNumber);
|
And later in another script:
1
2
3
4
5
6
7
8
9
|
//call the function from property (in another Thread Group
def multiplyTwoNumber = props.get("MUTIPLY_TWO_NUMBER");
//check the function to see how it work
def testResult = multiplyTwoNumber(4,5);
//print the log, it should see the value 20
log.info("The result of 4 * 5 = " + testResult);
|
Replace String in a Variable
Replaces characters in a variable and overwrites it.
1
2
|
// Replaces "\/" by "/"
vars.put("variable",vars.get("variable").replace("\\/","/"));
|
Next Working Day
Computes the next working day into nextworkingday.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public boolean isWorkingDay(Date date, Calendar calendar) {
// set calendar time with given date
calendar.setTime(date);
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
// check if it is Saturday(day=7) or Sunday(day=1)
if ((dayOfWeek == 7) || (dayOfWeek == 1)) {
return false;
}
return true;
}
Calendar c = Calendar.getInstance();
Date now = new Date();
c.setTime(now);
c.add(Calendar.DAY_OF_WEEK, 1);
while(!isWorkingDay(c.getTime(), c)) {
c.add(Calendar.DAY_OF_WEEK, 1);
}
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
vars.put("nextworkingday", df.format(c.getTime()));
|
Simulate Pacing
Iteration pacing is a good way to make sure every iteration will have the same duration whatever the response time. To implement it, we will use two scripts and a constant variable named “pacing” that contains the duration of the pacing in milliseconds.
Put a first script at the very beginning of your Virtual user profile:
1
2
|
import com.google.common.base.Stopwatch;
vars.putObject("watch",Stopwatch.createStarted());
|
Then the last action in your user profile should be a script with:
1
2
3
4
5
6
7
8
9
10
11
|
import com.google.common.base.Stopwatch;
import java.util.Map;
Map env = System.getenv();
Stopwatch watch = vars.getObject("watch");
long elapsed = watch.elapsed(java.util.concurrent.TimeUnit.MILLISECONDS);
long pacing = Long.parseLong(vars.get("pacing"));
long sleep = pacing - elapsed;
Thread.sleep(sleep);
|
Note the use of TEST_MODE to ensure the pacing is only used during a real test and not a during a validation.
Fibonacci
Computes 36th value of fibonacci series.
1
2
3
4
5
6
7
8
|
int fibonacci(int i) {
if (i == 1 || i == 2) {
return i;
}
return fibonacci(i - 1) + fibonacci(i - 2);
}
log.info("Fibonacci number 36: " + fibonacci(36));
|
Log Sampler Info
Logs some interesting infos to JMeter log file during the test.
1
2
3
4
|
log.info( "The Sample Label is : " + SampleResult.getSampleLabel() );
log.info( "The Start Time in miliseconds is : " + SampleResult.getStartTime() );
log.info( "The Response Code is : " + SampleResult.getResponseCode() );
log.info( "The Response Message is : " + SampleResult.getResponseMessage() );
|
Modifying Current SampleResult
The previous sample result can easily be modified by JSR223 scripts.
1
2
3
4
5
6
7
8
9
10
11
|
SampleResult.setSampleLabel("This test is modified by JSR223 script");
def start = System.currentTimeMillis(); //return current time in milliseconds
SampleResult.setStartTime(start); // set StartTime
log.info("Start Time should be: " + (new Date(start)).toString()); //print the start time in Date format
SampleResult.setResponseCode("201");
SampleResult.setResponseMessage("This is message returned from JSR223 script");
SampleResult.setResponseData("You will see this sentence in Response Data tab", "UTF-8")
|
Read Previous SampleResult
Reads the previous sample result data from prev variable.
1
2
3
4
5
6
7
8
9
10
11
|
log.info("Thread Group name is: " + prev.getThreadName());
def end_time = prev.getEndTime()
log.info("End Time is: " + (new Date(end_time).toString()));
log.info("Response Time is: " + prev.getTime().toString());
log.info("Connect Time is: " + prev.getConnectTime().toString());
log.info("Latency is: " + prev.getLatency().toString());
log.info("Size in bytes is: " + prev.getBytesAsLong().toString());
log.info("URL is: " + prev.getURL());
log.info("The result is passed: " + prev.isSuccessful().toString());
log.info("Headers are: " + prev.getResponseHeaders());
|
Modify Previous SampleResult
1
2
3
4
5
6
7
8
9
10
|
def response_time = prev.getTime().toInteger();
def expected_response_time = 500;
if (response_time > expected_response_time) {
prev.setSampleLabel("The response time is too long");
prev.setSuccessful(false);
prev.setResponseCode("500");
prev.setResponseMessage("The expected response time is : " + expected_response_time + "ms but it took: " + response_time + "ms");
}
|
Modify HTTP Request
Define the following script as an Http Sampler pre-processor.
1
2
3
4
|
sampler.setDomain("jmetervn.wordpress.com");
sampler.setProtocol("HTTPS");
sampler.setMethod("GET");
sampler.setPort(443);
|
JMeter Context
The following script demonstrates the usage of the ctx variable.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
log.info("Current Sampler class is: " + ctx.getCurrentSampler());
log.info("JMeter Engine class is: " + ctx.getEngine());
log.info("Previous Response Message is: " + ctx.getPreviousResult().getResponseMessage());
log.info("Previous Response Code is: " + ctx.getPreviousResult().getResponseCode());
log.info("Previous Response URL is: " + ctx.getPreviousResult().getURL());
log.info("Previous Response Time is: " + ctx.getPreviousResult().getTime());
log.info("Previous Domain is: " + ctx.getPreviousSampler().getDomain());
log.info("Previous Protocol is: " + ctx.getPreviousSampler().getProtocol());
log.info("Previous Port is: " + ctx.getPreviousSampler().getPort());
log.info("Previous Method is: " + ctx.getPreviousSampler().getMethod());
log.info("Thread Name is: " + ctx.getThread().getThreadName());
log.info("Thread Start Time is: " + ctx.getThread().getStartTime());
log.info("Thread End Time is: " + ctx.getThread().getEndTime());
log.info("Start Next Thread Loop on Error: " + ctx.getThreadGroup().getOnErrorStartNextLoop());
log.info("Stop Test on Error: " + ctx.getThreadGroup().getOnErrorStopTest());
|
This is an ever growing base of JMeter scripts. Feel free to come back as we are going to update it every once in a while.
Excellent blog here! Also your web site loads up very fast! What host are you using? Can I get your affiliate link to your host? I wish my website could load up as fast as yours lol
In reply to Vicki
Hi Vicki, OctoPerf’s website is statically generated using Hugo. The content is stored on Amazon S3 and accelerated by CloudFront CDN (which HTTP/2 enabled). We use Gulp to build it. (includes PNG Optimization, CSS and JS Minification etc.) Finally, we use S3_Website to deploy the website to Amazon S3 and refresh CloudFront. (and compress everything using GZIP)
I need how we get the token id from & print by Beanshell I am able to get the token id by regular expression during login. I need to print that token id in next HTTP Request
In reply to rohit
Hi, You can do this by using the script in Manipulate Variables section.
This was really helpful and very informative. All in one place. I need one more help. I could not set startTime or endTime using prev or SmpleResult. It throws error in compilation. Actually i want to override the response/load time for a request. Override with a variable value. I tried below but didnt work as I expected. SimpleDateFormat formatter1=new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss.SS”); Date startDate=formatter1.parse(startTime);
Long start = startDate.getTime(); log.info(“Start Time in Long: " + start); //print the start time in Date format SampleResult.setStartTime(start); // set StartTime log.info(“Start Time should be: " + (new Date(start)).toString()); //print the start time in Date format
Date endDate=formatter1.parse(endTime);
Long end = endDate.getTime(); SampleResult.setEndTime(end); // set StartTime log.info(“End Time should be: " + (new Date(end)).toString()); //print the start time in Date format
SampleResult.setResponseCode(“200”); SampleResult.createTestSample(start,end); SampleResult.createTestSample(end-start);//To set the elapsed time
I tried creating above script as JSR223 post-processer under HTTP sampler or JDBC sampler. Also tried with JSR223 sampler as well. Can you help me?