Escolar Documentos
Profissional Documentos
Cultura Documentos
VS-1120
V skills
Certified
Jmeter Tester
www.vskills.in
Proficiency Testing Programme
of
VS-1120
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License
is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the specific language governing
permissions and limitations under the License.
Disclaimer:
Due care and diligence has been taken while editing and printing this book. Neither the Author, publisher nor the printer of the
book holds any responsibility for any mistake that may have crept in inadvertently. Cubezoid Solutions Private Limited the
publishers, will be free from any liability for damages and loss of any nature arising out or related to the content. All disputes
are subject to the jurisdiction of the competent courts in Delhi.
www.vskills.in
Page 2
TABLE OF CONTENTS
1. Introduction............................................................................................................................... 7
1.1. History................................................................................................................................................................7
1.2. The Future .........................................................................................................................................................7
www.vskills.in
Page 3
Page 4
www.vskills.in
Page 5
17. Help! My boss wants me to load test our web app! ......................................................... 103
17.1. Questions to ask ...........................................................................................................................................103
17.2. Resources .....................................................................................................................................................103
17.3. Network........................................................................................................................................................103
17.4. Application ...................................................................................................................................................103
17.5. What platform should I use to run the benchmarks/load-tests ?...................................................................104
17.6. Tools ............................................................................................................................................................104
17.7. What other products are there ?...................................................................................................................105
17.8. Why Java ? ...................................................................................................................................................105
www.vskills.in
Page 6
1. INTRODUCTION
Apache JMeter is a 100% pure Java desktop application designed to load test client/server software
(such as a web application). It may be used to test performance both on static and dynamic
resources such as static files, Java Servlets, CGI scripts, Java objects, databases, FTP servers, and
more. JMeter can be used to simulate a heavy load on a server, network or object to test its
strength or to analyze overall performance under different load types.
Additionally, JMeter can help you regression test your application by letting you create test scripts
with assertions to validate that your application is returning the results you expect. For maximum
flexibility, JMeter lets you create these assertions using regular expressions.
But please note that JMeter is not a browser, it works at protocol level.
1.1. History
Stefano Mazzocchi of the Apache Software Foundation was the original developer of JMeter. He
wrote it primarily to test the performance of Apache JServ (a project that has since been replaced
by the Apache Tomcat project). We redesigned JMeter to enhance the GUI and to add functionaltesting capabilities.
JMeter became a Top Level Apache project in November 2011, which means it has a Project
Management Commitee and a dedicated website.
www.vskills.in
Page 7
2. GETTING STARTED
The easiest way to begin using JMeter is to first download the latest production release and install
it. The release contains all of the files you need to build and run most types of tests, e.g. Web
(HTTP/HTTPS), FTP, JDBC, LDAP, Java, JUnit and more.
If you want to perform JDBC testing, then you will, of course, need the appropriate JDBC driver
from your vendor. JMeter does not come with any JDBC drivers.
JMeter includes the JMS API jar, but does not include a JMS client implementation. If you want to
run JMS tests, you will need to download the appropriate jars from the JMS provider.
Next, start JMeter and go through the Building a Test Plan section of the User Guide to familiarize
yourself with JMeter basics (for example, adding and removing elements).
Finally, go through the appropriate section on how to build a specific type of Test Plan. For
example, if you are interested in testing a Web application, then see the section Building a Web
Test Plan. The other specific Test Plan sections are:
Advanced Web Test Plan
JDBC
FTP
JMS Point-to-Point
JMS Topic
LDAP
LDAP Extended
WebServices (SOAP)
Once you are comfortable with building and running JMeter Test Plans, you can look into the
various configuration elements (timers, listeners, assertions, and others) which give you more
control over your Test Plans.
A popup appears, you can then choose a template among the list:
www.vskills.in
Page 8
Templates popup
A documentation for each template explains what to do once test plan is created from template.
2.1. Requirements
JMeter requires your computing environment meets some minimum requirements.
Java Version
JMeter requires a fully compliant JVM 6 or higher.
Because JMeter uses only standard Java APIs, please do not file bug reports if your JRE fails to run
JMeter because of JRE implementation issues.
Operating Systems
JMeter is a 100% Java application and should run correctly on any system that has a compliant Java
implementation.
Operating systems tested with JMeter can be view on this page on JMeter wiki.
Even if your OS is not listed on the wiki page, JMeter should run on it provided that the JVM is
compliant.
2.2. Optional
If you plan on doing JMeter development, then you will need one or more optional packages listed
below.
Java Compiler
If you want to build the JMeter source or develop JMeter plugins, then you will need a fully
compliant JDK 6 or higher.
www.vskills.in
Page 9
SSL Encryption
To test a web server using SSL encryption (HTTPS), JMeter requires that an implementation of
SSL be provided, as is the case with Sun Java 1.4 and above. If your version of Java does not
include SSL support, then it is possible to add an external implementation. Include the necessary
encryption packages in JMeter's classpath . Also, update system.properties to register the SSL
Provider.
JMeter HTTP defaults to protocol level TLS. This can be changed by editing the JMeter property
https.default.protocol in jmeter.properties or user.properties.
The JMeter HTTP samplers are configured to accept all certificates, whether trusted or not,
regardless of validity periods, etc. This is to allow the maximum flexibility in testing servers.
If the server requires a client certificate, this can be provided.
There is also the SSL Manager , for greater control of certificates.
The JMeter proxy server (see below) supports recording HTTPS (SSL)
The SMTP sampler can optionally use a local trust store or trust all certificates.
JDBC Driver
You will need to add your database vendor's JDBC driver to the classpath if you want to do JDBC
testing. Make sure the file is a jar file, not a zip.
JMS client
JMeter now includes the JMS API from Apache Geronimo, so you just need to add the
appropriate JMS Client implementation jar(s) from the JMS provider. Please refer to their
documentation for details. There may also be some information on the JMeter Wiki .
2.3. Installation
We recommend that most users run the latest release .
www.vskills.in
Page 10
Note: the special name LAST can be used with jmeter-n.cmd, jmeter-t.cmd and jmeter-n-r.cmd
and means the last test plan that was run interactively.
The environment variable JVM_ARGS can be used to override JVM settings in the jmeter.bat
script. For example:
set JVM_ARGS="-Xms1024m -Xmx1024m -Dpropname=propvalue"
jmeter -t test.jmx ...
www.vskills.in
Page 11
JMeter's Classpath
JMeter automatically finds classes from jars in the following directories:
JMETER_HOME/lib - used for utility jars
JMETER_HOME/lib/ext - used for JMeter components and plugins
If you have developed new JMeter components, then you should jar them and copy the jar into
JMeter's lib/ext directory. JMeter will automatically find JMeter components in any jars found here.
Do not use lib/ext for utility jars or dependency jars used by the plugins; it is only intended for
JMeter components and plugins.
If you don't want to put JMeter plugin jars in the lib/ext
lib/e directory, then define the property
search_paths in jmeter.properties.
Utility and dependency jars (libraries etc) can be placed in the lib directory.
If you don't want to put such jars in the lib directory, then define the property user.classpath or
plugin_dependency_paths in jmeter.properties. See below for an explanation of the differences.
Other jars (such as JDBC, JMS implementations and any other support libraries needed by the
JMeter code) should be placed in the lib directory - not the lib/ext directory, or added to
user.classpath .
Page 12
www.vskills.in
Page 13
Server
Server Mode
For distributed testing , run JMeter in server mode on the remote node(s), and then control the
server(s) from the GUI. You can also use non-GUI mode to run remote tests. To start the
server(s), run jmeter-server[.bat] on each server host.
The script also lets you specify the optional firewall/proxy server information:
-H [proxy server hostname or ip address]
-P [proxy server port]
www.vskills.in
Page 14
Examples :
jmeter -Duser.dir=/home/mstover/jmeter_stuff \
-Jremote_hosts=127.0.0.1 -Ljmeter.engine=DEBUG
jmeter -LDEBUG
N.B.
The command line properties are processed early in startup, but after the logging system has been
set up. Attempts to use the -J flag to update log_level or log_file properties will have no effect.
Error/fatal counter
The command-line option -j jmeterlogfile allow to process after the initial properties file is read,
and before any further properties are processed. It therefore allows the default of jmeter.log to be
overridden. The jmeter scripts that take a test plan name as a parameter (e.g. jmeter-n.cmd) have
www.vskills.in
Page 15
Page 16
Note: the JMeter log file name is formatted as a SimpleDateFormat (applied to the current date) if
it contains paired single-quotes, .e.g. 'jmeter_'yyyyMMddHHmmss'.log'
If the special name LAST is used for the -t, -j or -l flags, then JMeter takes that to mean the last test
plan that was run in interactive mode.
nonnon-GUI shutdown
Prior to version 2.5.1, JMeter invoked System.exit() when a non-GUI test completed. This caused
problems for applications that invoke JMeter directly, so JMeter no longer invokes System.exit()
for a normal test completion. [Some fatal errors may still invoke System.exit()] JMeter will exit all
the non-daemon threads it starts, but it is possible that some non-daemon threads may still remain;
these will prevent the JVM from exitting. To detect this situation, JMeter starts a new daemon
thread just before it exits. This daemon thread waits a short while; if it returns from the wait, then
clearly the JVM has not been able to exit, and the thread prints a message to say why.
The property jmeter.exit.check.pause can be used to override the default pause of 2000ms (2secs).
If set to 0, then JMeter does not start the daemon thread.
www.vskills.in
Page 17
Note: You can define additional JMeter properties in the file defined by the JMeter property
user.properties which has the default value user.properties . The file will be automatically loaded if
it is found in the current directory or if it is found in the JMeter bin directory. Similarly,
system.properties is used to update system properties.
Parameters
Attribute
Description
Required
You can specify the class for your SSL implementation if you
No
ssl.provider
don't want to use the built-in Java implementation.
You can specify an implementation as your XML parser. The
No
xml.parser
default value is: org.apache.xerces.parsers.SAXParser
Comma-delimited list of remote JMeter hosts (or host:port if
required). If you are running JMeter in a distributed
remote_hosts
environment, list the machines where you have JMeter remote No
servers running. This will allow you to control those servers
from this machine's GUI
A list of components you do not want to see in JMeter's menus.
As JMeter has more and more components added, you may
wish to customize your JMeter to show only those components
not_in_menu
No
you are interested in. You may list their classname or their class
label (the string that appears in JMeter's UI) here, and they will
no longer appear in the menus.
List of paths (separated by ;) that JMeter will search for JMeter
plugin classes, for example additional samplers. A path item
can either be a jar file or a directory. Any jar file in such a
No
search_paths
directory will be automatically included in search_paths, jar
files in sub directories are ignored. The given value is in
addition to any jars found in the lib/ext directory.
List of paths that JMeter will search for utility and plugin
dependency classes. Use your platform path separator to
separate multiple paths. A path item can either be a jar file or a
directory. Any jar file in such a directory will be automatically
user.classpath
included in user.classpath, jar files in sub directories are No
ignored. The given value is in addition to any jars found in the
lib directory. All entries will be added to the class path of the
system class loader and also to the path of the JMeter internal
loader.
plugin_dependenc List of paths (separated by ;) that JMeter will search for utility
No
y_paths
and plugin dependency classes. A path item can either be a jar
www.vskills.in
Page 18
Description
Required
file or a directory. Any jar file in such a directory will be
automatically included in plugin_dependency_paths, jar files in
sub directories are ignored. The given value is in addition to
any jars found in the lib directory or given by the user.classpath
property. All entries will be added to the path of the JMeter
internal loader only. For plugin dependencies using
plugin_dependency_paths should be preferred over
user.classpath.
Name of file containing additional JMeter properties. These
user.properties
are added after the initial property file, but before the -q and -J No
options are processed.
Name of file containing additional system properties. These are
system.properties
No
added before the -S and -D options are processed.
The command line options and properties files are processed in the following order:
-p propfile
jmeter.properties (or the file from the -p option) is then loaded
-j logfile
Logging is initialized
user.properties is loaded
system.properties is loaded
all other command-line options are processed
www.vskills.in
Page 19
www.vskills.in
Page 20
Stopping a Test
There are two types of stop command available from the menu:
Stop (Control + '.') - stops the threads immediately if possible. In Versions of JMeter after 2.3.2,
many samplers are now Interruptible which means that active samples can be terminated early.
The stop command will check that all threads have stopped within the default timeout, which is
5000
ms
=
5
seconds.
[This
can be
changed
using
the JMeter
propertyjmeterengine.threadstop.wait ] If the threads have not stopped, then a message is
displayed. The Stop command can be retried, but if it fails, then it is necessary to exit JMeter to
clean up.
Shutdown (Control + ',')- requests the threads to stop at the end of any current work. Will not
interrupt any active samples. The modal shutdown dialog box will remain active until all threads
have stopped.
Versions of JMeter after 2.3.2 allow a Stop to be initiated if Shutdown is taking too long. Close the
Shutdown dialog box and select Run/Stop, or just press Control + '.'.
When running JMeter in non-GUI mode, there is no Menu, and JMeter does not react to
keystrokes such as Control + '.'. So in versions after 2.3.2, JMeter non-GUI mode will listen for
commands on a specific port (default 4445, see the JMeter property jmeterengine.nongui.port ). In
versions after 2.4, JMeter supports automatic choice of an alternate port if the default port is being
used (for example by another JMeter instance). In this case, JMeter will try the next higher port,
continuing until it reaches the JMeter property jmeterengine.nongui.maxport) which defaults to
4455. If maxport is less than or equal to port , port scanning will not take place. Note that JMeter
2.4 and earlier did not set up the listener for non-GUI clients, only non-GUI standalone tests; this
has been fixed.
The chosen port is displayed in the console window.
The commands currently supported are:
Shutdown - graceful shutdown
StopTestNow - immediate shutdown
www.vskills.in
Page 21
www.vskills.in
Page 22
4.1. ThreadGroup
Thread group elements are the beginning points of any test plan. All controllers and samplers must
be under a thread group. Other elements, e.g. Listeners, may be placed directly under the test
plan, in which case they will apply to all the thread groups. As the name implies, the thread group
element controls the number of threads JMeter will use to execute your test. The controls for a
thread group allow you to:
Set the number of threads
Set the ramp-up period
Set the number of times to execute the test
Each thread will execute the test plan in its entirety and completely independently of other test
threads. Multiple threads are used to simulate concurrent connections to your server application.
The ramp-up period tells JMeter how long to take to "ramp-up" to the full number of threads
chosen. If 10 threads are used, and the ramp-up period is 100 seconds, then JMeter will take 100
seconds to get all 10 threads up and running. Each thread will start 10 (100/10) seconds after the
previous thread was begun. If there are 30 threads and a ramp-up period of 120 seconds, then
each successive thread will be delayed by 4 seconds.
Ramp-up needs to be long enough to avoid too large a work-load at the start of a test, and short
enough that the last threads start running before the first ones finish (unless one wants that to
happen).
Start with Ramp-up = number of threads and adjust up or down as needed.
By default, the thread group is configured to loop once through its elements.
Version 1.9 introduces a test run scheduler . Click the checkbox at the bottom of the Thread
Group panel to reveal extra fields in which you can enter the start and end times of the run. When
the test is started, JMeter will wait if necessary until the start-time has been reached. At the end of
each cycle, JMeter checks if the end-time has been reached, and if so, the run is stopped, otherwise
the test is allowed to continue until the iteration limit is reached.
www.vskills.in
Page 23
4.2. Controllers
JMeter has two types of Controllers: Samplers and Logical Controllers. These drive the processing
of a test.
Samplers tell JMeter to send requests to a server. For example, add an HTTP Request Sampler if
you want JMeter to send an HTTP request. You can also customize a request by adding one or
more Configuration Elements to a Sampler. For more information, see Samplers .
Logical Controllers let you customize the logic that JMeter uses to decide when to send requests.
For example, you can add an Interleave Logic Controller to alternate between two HTTP Request
Samplers. For more information, see Logical Controllers .
Samplers
Samplers tell JMeter to send requests to a server and wait for a response. They are processed in
the order they appear in the tree. Controllers can be used to modify the number of repetitions of a
sampler.
JMeter samplers include:
FTP Request
HTTP Request
JDBC Request
Java object request
LDAP Request
SOAP/XML-RPC Request
WebService (SOAP) Request
Each sampler has several properties you can set. You can further customize a sampler by adding
one or more Configuration Elements to the Test Plan.
If you are going to send multiple requests of the same type (for example, HTTP Request) to the
same server, consider using a Defaults Configuration Element. Each controller has one or more
Defaults elements (see below).
Remember to add a Listener to your test plan to view and/or store the results of your requests to
disk.
If you are interested in having JMeter perform basic validation on the response of your request,
add an Assertion to the sampler. For example, in stress testing a web application, the server may
return a successful "HTTP Response" code, but the page may have errors on it or may be missing
sections. You could add assertions to check for certain HTML tags, common error strings, and so
on. JMeter lets you create these assertions using regular expressions.
www.vskills.in
Page 24
www.vskills.in
Page 25
Test Fragments
The Test Fragment element is a special type of controller that exists on the Test Plan tree at the
same level as the Thread Group element. It is distinguished from a Thread Group in that it is not
executed unless it is referenced by either a Module Controlleror an Include_Controller .
This element is purely for code re-use within Test Plans and was introduced in Version 2.5
4.3. Listeners
Listeners provide access to the information JMeter gathers about the test cases while JMeter runs.
The Graph Results listener plots the response times on a graph. The "View Results Tree" Listener
shows details of sampler requests and responses, and can display basic HTML and XML
representations of the response. Other listeners provide summary or aggregation information.
Additionally, listeners can direct the data to a file for later use. Every listener in JMeter provides a
field to indicate the file to store data to. There is also a Configuration button which can be used to
choose which fields to save, and whether to use CSV or XML format. Note that all Listeners save
the same data; the only difference is in the way the data is presented on the screen.
Listeners can be added anywhere in the test, including directly under the test plan. They will
collect data only from elements at or below their level.
There are several listeners that come with JMeter.
4.4. Timers
By default, a JMeter thread sends requests without pausing between each request. We recommend
that you specify a delay by adding one of the available timers to your Thread Group. If you do not
add a delay, JMeter could overwhelm your server by making too many requests in a very short
amount of time.
The timer will cause JMeter to delay a certain amount of time before each sampler which is in its
scope .
If you choose to add more than one timer to a Thread Group, JMeter takes the sum of the timers
and pauses for that amount of time before executing the samplers to which the timers apply.
www.vskills.in
Page 26
4.5. Assertions
Assertions allow you to assert facts about responses received from the server being tested. Using an
assertion, you can essentially "test" that your application is returning the results you expect it to.
For instance, you can assert that the response to a query will contain some particular text. The text
you specify can be a Perl-style regular expression, and you can indicate that the response is to
contain the text, or that it should match the whole response.
You can add an assertion to any Sampler. For example, you can add an assertion to a HTTP
Request that checks for the text, "</HTML>". JMeter will then check that the text is present in the
HTTP response. If JMeter cannot find the text, then it will mark this as a failed request.
Note that assertions apply to all samplers which are in its scope . To restrict the assertion to a
single sampler, add the assertion as a child of the sampler.
To view the assertion results, add an Assertion Listener to the Thread Group. Failed Assertions
will also show up in the Tree View and Table Listeners, and will count towards the error %age for
example in the Aggregate and Summary reports.
www.vskills.in
Page 27
www.vskills.in
Page 28
www.vskills.in
Page 29
Hierarchy example
Assertion #1 is applied only to Request One, while Assertion #2 is applied to Requests Two and
Three.
Another example, this time using Timers:
complex example
In this example, the requests are named to reflect the order in which they will be executed. Timer
#1 will apply to Requests Two, Three, and Four (notice how order is irrelevant for hierarchical
elements). Assertion #1 will apply only to Request Three. Timer #2 will affect all the requests.
www.vskills.in
Page 30
Hopefully these examples make it clear how configuration (hierarchical) elements are applied. If
you imagine each Request being passed up the tree branches, to its parent, then to its parent's
parent, etc, and each time collecting all the configuration elements of that parent, then you will see
how it works.
The Configuration elements Header Manager, Cookie Manager and Authorization manager are
treated differently from the Configuration Default elements. The settings from the Configuration
Default elements are merged into a set of values that the Sampler
Sampler has access to. However, the
settings from the Managers are not merged. If more than one Manager is in the scope of a
Sampler, only one Manager is used, but there is currently no way to specify which is used.
www.vskills.in
Page 31
www.example.com
10
20
You can refer to these in the test plan as ${HOST} ${THREADS} etc. If you later want to change
the host, just change the value of the HOST variable. This works fine for small numbers of tests,
but becomes tedious when testing lots of different combinations. One solution is to use a property
to define the value of the variables, for example:
HOST
THREADS
LOOPS
${__P(host,www.example.com)}
${__P(threads,10)}
${__P(loops,20)}
You can then change some or all of the values on the command-line as follows:
jmeter ... -Jhost=www3.example.org -Jloops=13
www.vskills.in
Page 32
Start by providing a more descriptive name for our Thread Group. In the name field, enter JMeter
Users.
Next, increase the number of users (called threads) to 5.
In the next field, the Ramp-Up Period, leave the default value of 1 seconds. This property tells
JMeter how long to delay between starting each user. For example, if you enter a Ramp-Up Period
of 5 seconds, JMeter will finish starting all of your users by the end of the 5 seconds. So, if we have
5 users and a 5 second Ramp-Up Period, then the delay between starting users would be 1 second
www.vskills.in
Page 33
www.vskills.in
Page 34
Like most JMeter elements, the HTTP Request Defaults Control Panel has a name field that you
can modify. In this example, leave this field with the default value.
Skip to the next field, which is the Web Server's Server Name/IP. For the Test Plan that you are
building, all HTTP requests will be sent to the same Web server, jmeter.apache.org. Enter this
domain name into the field. This is the only field that we will specify a default, so leave the
remaining fields with their default values.
The HTTP Request Defaults element does not tell JMeter to send an HTTP request. It
simply defines the default values that the HTTP Request elements use.
See Figure 5.4 for the completed HTTP Request Defaults element
www.vskills.in
Page 35
www.vskills.in
Page 36
www.vskills.in
Page 37
www.vskills.in
Page 38
www.vskills.in
Page 39
In Figure 2, we see the URL Re-writing modifier GUI, which just has a field for the user to specify
the name of the session ID parameter. There is also a checkbox for indicating that the session ID
should be part of the path (separated by a ";"), rather than a request parameter
www.vskills.in
Page 40
The HTTP Header Manager , like the HTTP Cookie Manager , should probably be added at the
Thread Group level, unless for some reason you wish to specify different headers for the
differentHTTP Request objects in your test.
www.vskills.in
Page 41
7. BUILDING A DATABASE
DATABASE TEST PLAN
In this section, you will learn how to create a basic Test Plan to test a database server. You will
create fifty users that send 2 SQL requests to the database server. Also, you will tell the users to
run their tests 100 times. So, the total number of requests is (50 users) x (2 requests) x (repeat 100
times) = 10'000 JDBC requests. To construct the Test Plan, you will use the following elements:
Thread Group , JDBC Request , Summary Report .
This example uses the MySQL database driver. To use this driver, its containing .jar file
(ex. mysql-connector-java-X.X.X-bin.jar) must be copied to the JMeter ./lib directory (see
JMeter's Classpath for more details).
Start by providing a more descriptive name for our Thread Group. In the name field, enter JDBC
Users.
You will need a valid database, database table, and user-level access to that table. In the
example shown here, the database is 'cloud' and the table name is 'vm_instance'.
www.vskills.in
Page 42
www.vskills.in
Page 43
Selecting the JDBC Users element again. Click your right mouse button to get the Add menu, and
then select Add --> Sampler --> JDBC Request . Then, select this new element to view its Control
Panel (see Figure 7.4).
www.vskills.in
Page 44
Next, add the second JDBC Request and edit the following properties (see Figure 7.6):
Change the Name to 'VM Expunging'.
Change the value of Parameter values to 'Expunging'.
www.vskills.in
Page 45
www.vskills.in
Page 46
www.vskills.in
Page 47
www.vskills.in
Page 48
Like most JMeter elements, the FTP Request Defaults Control Panel has a name field that you can
modify. In this example, leave this field with the default value.
Skip to the next field, which is the FTP Server's Server Name/IP. For the Test Plan that you are
building, all FTP requests will be sent to the same FTP server, ftp.domain.com in this case. Enter
this domain name into the field. This is the only field that we will specify a default, so leave the
remaining fields with their default values.
The FTP Request Defaults element does not tell JMeter to send an FTP request. It simply defines
the default values that the FTP Request elements use.
Page 49
Next, add the second FTP Request and edit the following properties (see Figure 8.6:
Change the Name to "File2".
Change the Remote File field to "/directory/file2.txt".
Change the Username field to "anonymous".
Change the Password field to "anonymous@test.com".
www.vskills.in
Page 50
www.vskills.in
Page 51
www.vskills.in
Page 52
www.vskills.in
Page 53
You do not have to set the Server Name field, port field, Username, Password and DN because
you already specified this value in the Login Config Element and LDAP Request Defaults.
Defaults
Next, add the second LDAP Request and edit the following properties
Rename to "Search" this element
Select the Search Test radio button in Test Configuration group
www.vskills.in
Page 54
www.vskills.in
Page 55
www.vskills.in
Page 56
www.vskills.in
Page 57
For each of the different operations, some default values can be filled in. In All cases, when a
default is filled in, this is used for the LDAP extended requests. For each request, you can override
the defaults by filling in the values in the LDAP extended request sampler. When no value is
entered which is necessary for a test, the test will fail in an unpredictable way!
Page 58
www.vskills.in
Page 59
www.vskills.in
Page 60
www.vskills.in
Page 61
www.vskills.in
Page 62
www.vskills.in
Page 63
www.vskills.in
Page 64
In this listener you have three tabs to view, the sampler result, the request and the response data.
The sampler result just contains the response time, the returncode and return message
The request gives a short description of the request that was made, in practice no relevant
information is contained here.
The response data contains the full details of the sent request, as well the full details of the
received answer, this is given in a (self defined) xml-style. The full description can be found
here.
www.vskills.in
Page 65
Start by providing a more descriptive name for our Thread Group. In the name field, enter Jakarta
Users.
Next, increase the number of users (called threads) to 10.
In the next field, the Ramp-Up Period, leave the default value of 0 seconds. This property tells
JMeter how long to delay between starting each user. For example, if you enter a Ramp-Up Period
www.vskills.in
Page 66
www.vskills.in
Page 67
If the WSDL file was loaded correctly, the "Web Methods" drop down should be populated. If the
drop down remains blank, it means there was a problem getting the WSDL. You can test the
WSDL using a browser that reads XML. For example, if you're testing an IIS web service the URL
will look like this: http://localhost/myWebService/Service.asmx?WSDL. At this point,
SOAPAction, URL and SOAP Data should be blank.
Next, select the web method and click "Configure". The sampler should populate the "URL" and
"SOAPAction" text fields. Assuming the WSDL is valid, the correct soap action should be entered.
The last step is to paste the SOAP message in the "SOAP/XML-RPC Data" text area. You can
optionally save the soap message to a file and browse to the location. For convenience, there is a
third option of using a message folder. The sampler will randomly select files from a given folder
and use the text for the soap message.
If you do not want JMeter to read the response from the SOAP Web service, uncheck "Read Soap
Responses." If the test plan is intended to stress test a web service, the box should be unchecked. If
the test plan is a functional test, the box should be checked. When "Read Soap Responses" is
unchecked, no result will be displayed in view result tree or view results in table.
An important note on the sampler. It will automatically use the proxy host and port passed to
JMeter from command line, if those fields in the sampler are left blank. If a sampler has values in
www.vskills.in
Page 68
Note: If you're using Cassini web server, it does not work correctly and is not a reliable web server.
Cassini is meant to be a simple example and isn't a full blown web server like IIS. Cassini does not
close connections correctly, which causes JMeter to hang or not get the response contents.
Currently, only .NET uses SOAPAction, so it is normal to have a blank SOAPAction for all other
web services. The list includes JWSDP, Weblogic, Axis, The Mind Electric Glue, and gSoap.
www.vskills.in
Page 69
Start by providing a more descriptive name for our Thread Group. In the name field, enter Pointto-Point.
Next, increase the number of users (called threads) to 5.
www.vskills.in
Page 70
www.vskills.in
Page 71
www.vskills.in
Page 72
Start by providing a more descriptive name for our Thread Group. In the name field, enter
Subscribers.
www.vskills.in
Page 73
www.vskills.in
Page 74
Next add the sampler JMS Publisher to the Publisher element (Add --> Sampler --> JMS
Subscriber). Then, select the JMS Publisher element in the tree and edit the following properties:
Change the Name field to "Sample Publisher".
If the JMS provider uses the jndi.properties file, check the box
Enter the name of the InitialContextFactory class. For example, with ActiveMQ 5.4, the value is
"org.apache.activemq.jndi.ActiveMQInitialContextFactory"
Enter the provider URL. This is the URL for the JNDI server, if there is one. For example,
with ActiveMQ 5.4 on local machine with default port, the value is "tcp://localhost:61616"
Enter the name of the connection factory. Please refer to the documentation of the JMS
provider for the information. For ActiveMQ, the default is "ConnectionFactory"
Enter the name of the message topic. For ActiveMQ Dynamic Topics (create topics
dynamically), example value is "dynamicTopics/MyStaticTopic1". Note: Setup at startup mean
that JMeter starting connection with the Destination at beginning of test without name change
possibility. Setup on Each sample mean that JMeter (re)starting the connection before run each
JMS Publisher sample, this last option permit to have Destination name with some JMeter
variables
If the JMS provider requires authentication, check "required" and enter the username and
password. For example, Orion JMS requires authentication, while ActiveMQ and MQSeries
does not
www.vskills.in
Page 75
Enter 10 in "Number of samples to aggregate". For performance reasons, the sampler will
aggregate messages, since small messages will arrive very quickly. If the sampler didn't aggregate
the messages, JMeter wouldn't be able to keep up.
Select the appropriate configuration for getting the message to publish. If you want the sampler
to randomly select the message, place the messages in a directory and select the directory using
browse.
Select the message type. If the message is in object format or map message, make sure the
message is generated correctly.
www.vskills.in
Page 76
www.vskills.in
Page 77
Change the loop count to forever (or some large number) so that enough samples are generated.
www.vskills.in
Page 78
www.vskills.in
Page 79
There are two tabs in the monitor results listener. The first is the "Health", which displays the status
of the last sample the monitor received. The second tab is "Performance", which shows a historical
view of the server's performance.
A quick note about how health is calculated. Typically, a server will crash if it runs out of memory,
or reached the maximum number of threads. In the case of Tomcat 5, once the threads are maxed
out, requests are placed in a queue until a thread is available. The relative importance of threads
vary between containers, so the current implementation uses 50/50 to be conservative. A container
that is more efficient with thread management might not see any performance degradation, but the
used memory definitely will show an impact.
www.vskills.in
Page 80
The performance graph shows four different lines. The free memory line shows how much free
memory is left in the current allocated block. Tomcat 5 returns the maximum memory, but it is
not graphed. In a well tuned environment, the server should never reach the maximum memory.
Note the graph has captions on both sides of the graph. On the left is percent and the right is
dead/healthy. If the memory line spikes up and down rapidly, it could indicate memory thrashing.
In those situations, it is a good idea to profile the application with Borland OptimizeIt or JProbe.
What you want to see is a regular pattern for load, memory and threads. Any erratic behavior
usually indicates poor performance or a bug of some sort.
www.vskills.in
Page 81
The corresponding jmeter.properties that need to be set are shown below. One oddity in this
example is that the output_format is set to csv, which typically indicates comma-separated values.
www.vskills.in
Page 82
However, the default_delimiter was set to be a vertical bar instead of a comma, so the csv tag is a
misnomer in this case. (Think of CSV as meaning character separated values)
The full set of properties that affect result file output is shown below.
#--------------------------------------------------------------------------# Results file configuration
#--------------------------------------------------------------------------# This section helps determine how result data will be saved.
# The commented out values are the defaults.
# legitimate values: xml, csv, db. Only xml and csv are currently supported.
#jmeter.save.saveservice.output_format=csv
# true when field should be saved; false otherwise
# assertion_results_failure_message only affects CSV output
#jmeter.save.saveservice.assertion_results_failure_message=false
#
#jmeter.save.saveservice.data_type=true
#jmeter.save.saveservice.label=true
#jmeter.save.saveservice.response_code=true
# response_data is not currently supported for CSV output
#jmeter.save.saveservice.response_data=false
# Save ResponseData for failed samples
#jmeter.save.saveservice.response_data.on_error=false
#jmeter.save.saveservice.response_message=true
#jmeter.save.saveservice.successful=true
#jmeter.save.saveservice.thread_name=true
#jmeter.save.saveservice.time=true
#jmeter.save.saveservice.subresults=true
#jmeter.save.saveservice.assertions=true
#jmeter.save.saveservice.latency=true
#jmeter.save.saveservice.samplerData=false
#jmeter.save.saveservice.responseHeaders=false
#jmeter.save.saveservice.requestHeaders=false
#jmeter.save.saveservice.encoding=false
#jmeter.save.saveservice.bytes=true
#jmeter.save.saveservice.url=false
#jmeter.save.saveservice.filename=false
#jmeter.save.saveservice.hostname=false
#jmeter.save.saveservice.thread_counts=false
www.vskills.in
Page 83
www.vskills.in
Page 84
Sample Variables
JMeter supports the sample_variables property to define a list of additional JMeter variables which
are to be saved with each sample in the JTL files. The values are written to CSV files as additional
columns, and as additional attributes in XML files. See above for an example.
Configuration dialogue
Note that cookies, method and the query string are saved as part of the "Sampler Data" option.
www.vskills.in
Page 85
www.vskills.in
Page 86
www.vskills.in
Page 87
Page 88
Versions 2.1 and 2.1.1 of JMeter saved the Response Code as "rs", but read it back expecting to
find "rc". This has been corrected so that it is always saved as "rc"; either "rc" or "rs" can be read.
Page 89
www.vskills.in
Page 90
www.vskills.in
Page 91
www.vskills.in
Page 92
15.2. Tips
JMeter/RMI requires a connection from the client to the server. This will use the port you chose,
default 1099.
JMeter/RMI also requires a reverse connection in order to return sample results from the server to
the client.
This will use a high-numbered port.
This port can be controlled by jmeter property called client.rmi.localport in jmeter.properties.
If there are any firewalls or other network filters between JMeter client and server, you will need to
make sure that they are set up to allow the connections through. If necessary, use monitoring
software to show what traffic is being generated.
If you're running Suse Linux, these tips may help. The default installation may enable the firewall.
In that case, remote testing will not work properly. The following tips were contributed by Sergey
Ten.
If you see connections refused, turn on debugging by passing the following options.
www.vskills.in
Page 93
www.vskills.in
Page 94
www.vskills.in
Page 95
www.vskills.in
Page 96
16.2. Limit
Limit the Number of Threads
Your hardware's capabilities will limit the number of threads you can effectively run with JMeter. It
will also depend on how fast your server is (a faster server makes JMeter work harder since it
returns request quicker). The more JMeter works, the less accurate its timing information may
become. The more work JMeter does, the more each thread has to wait to get access to the CPU,
the more inflated the timing information gets. If you need large-scale load testing, consider running
multiple non-GUI JMeter instances on multiple machines. The sample result files can be
combined for subsequent analysis. For testing how JMeter performs on a given platform, the
JavaTest sampler can be used. It does not require any network access so can give some idea as to
the maximum throughput achievable.
JMeter versions since 2.8 have an option to delay thread creation until the thread starts sampling,
i.e. after any thread group delay and the ramp-up time for the thread itself. This allows for a very
large total number of threads, provided that not too many are active concurrently.
www.vskills.in
Page 97
For example:
Create a text file containing the user names and passwords, separated by commas. Put this in
the same directory as your test plan.
Add a CSV DataSet configuration element to the test plan. Name the variables USER and
PASS.
Replace the login name with ${USER} and the password with ${PASS} on the appropriate
samplers
The CSV Data Set element will read a new line for each thread.
www.vskills.in
Page 98
www.vskills.in
Page 99
Sharing Variables
Variables can be defined in startup (initialization) scripts. These will be retained across invocations
of the test element, unless the reset option is used.\
Scripts can also access JMeter variables using the get() and put() methods of the "vars" variable, for
example:vars.get("HOST"); vars.put("MSG","Successful"); . The get() and put() methods only
support variables with String values, but there are also getObject() and putObject() methods which
can be used for arbitrary objects. JMeter variables are local to a thread, but can be used by all test
elements (not just Beanshell).
If you need to share variables between threads, then JMeter properties can be used:
import org.apache.jmeter.util.JMeterUtils;
String value=JMeterUtils.getPropDefault("name","");
JMeterUtils.setProperty("name", "value");
The sample .bshrc files contain sample definitions of getprop() and setprop() methods.
Another possible method of sharing variables is to use the "bsh.shared" shared namespace. For
example:
if (bsh.shared.myObj == void){
// not yet defined, so create it:
myObj=new AnyObject();
}
www.vskills.in
Page 100
JSR223 Elements
For intensive load testing, the recommended scripting language is one whose ScriptingEngine
implements the Compilable interface. Groovy scripting engine implements Compilable. However
neither Beanshell nor Javascript do so as of release date of JMeter 2.10, so it is recommended to
avoid them for intensive load testing. [Note: Beanshell implements the Compilable interface but it
has not been coded - the method just throws an Exception. JMeter has an explicit work-round for
this bug.] When using JSR 223 elements, always set caching key to a unique value to ensure the
script compilation is cached if underlying language supports it. Ensure the script does not use any
variable using ${varName} as caching would take only first value of ${varName}. Instead use :
vars.get("varName")
www.vskills.in
Page 101
www.vskills.in
Page 102
17.2. Resources
The following resources will prove very helpful. Bear in mind that if you cannot locate these
resources, you will become these resources. As you already have your work cut out for you, it is
worth knowing who the following people are, so that you can ask them for help if you need it.
17.3. Network
Who knows our network topology ? If you run into any firewall or proxy issues, this will become
very important. As well, a private testing network (which will therefore have very low network
latency) would be a very nice thing. Knowing who can set one up for you (if you feel that this is
necessary) will be very useful. If the application doesn't scale as expected, who can add additional
hardware ?
17.4. Application
Who knows how our application functions ? The normal sequence is
test (low-volume - can we benchmark our application?)
benchmark (the average number of users)
load-test (the maximum number of users)
test destructively (what is our hard limit?)
The test process may progress from black-box testing to white-box testing (the difference is that the
first requires no knowledge of the application [it is treated as a "black box"] while the second
www.vskills.in
Page 103
17.6. Tools
The following tools will all prove useful. It is definitely worthwhile to become familiar with them.
This should include trying them out, and reading the appropriate documentation (man-pages, infofiles, application --help messages, and any supplied documentation).
ping
This can be used to establish whether or not you can reach your target site. Options can be
specified so that 'ping' provides the same type of route reporting as 'traceroute'.
nslookup/dig
While the user will normally use a human-readable internet address, you may wish to avoid the
overhead of DNS lookups when performing benchmarking/load-testing. These can be used to
determine the unique address (dotted quad) of your target site.
traceroute
If you cannot "ping" your target site, this may be used to determine the problem (possibly a firewall
or a proxy). It can also be used to estimate the overall network latency (running locally should give
the lowest possible network latency - remember that your users will be running over a possibly busy
internet). Generally, the fewer hops the better.
www.vskills.in
Page 104
HttpUnit
This is worth a look. It is a library (and therefore of more interest to developers) that can be used
to perform HTTP tests/benchmarks. It is intended to be used instead of a web browser (therefore
no GUI) in conjunction with JUnit .
Microsoft WAS
This is definitely worth a look. It has an excellent user interface but it may not do exactly what you
want. If this is the case, be aware that the functionality of this product is not likely to change.
JMeter
If you have non-standard requirements, then this solution offers an open-source community to
provide them (of course, if you are readingthis , you are probably already committed to this one).
This product is free to evolve along with your requirements.
www.vskills.in
Page 105
18. FUNCTIONS
JMeter functions are special values that can populate fields of any Sampler or other element in a
test tree. A function call looks like this:
${__functionName(var1,var2,var3)}
Where "__functionName" matches the name of a function.
Parentheses surround the parameters sent to the function, for example ${__time(YMD)} The
actual parameters vary from function to function. Functions that require no parameters can leave
off the parentheses, for example ${__threadNum}.
If a function parameter contains a comma, then be sure to escape this with "\", otherwise JMeter
will treat it as a parameter delimiter. For example:
${__time(EEE\, d MMM yyyy)}
If the comma is not escaped - e.g. ${__javaScript(Math.max(2,5))} - you will get an error such as:
ERROR - jmeter.functions.JavaScript: Error processing Javascript: [Math.max(2]
org.mozilla.javascript.EvaluatorException: missing ) after argument list (#1)
This is because the string "Math.max(2,5)" is treated as being two parameters to the __javascript
function:
Math.max(2 and 5)
Other error messages are possible.
Variables are referenced as follows:
${VARIABLE}
If an undefined function or variable is referenced, JMeter does not report/log an error
error - the
reference is returned unchanged. For example if UNDEF is not defined as a variable, then the
case--sensitive.
value of ${UNDEF} is ${UNDEF}. Variables, functions (and properties) are all case
Versions of JMeter after 2.3.1 trim spaces from variable names
names before use, so for example
${__Random(1,63, LOTTERY )} will use the variable 'LOTTERY' rather than ' LOTTERY '.
List of functions, loosely grouped into types.
www.vskills.in
Page 106
www.vskills.in
Page 107
www.vskills.in
Page 108
vars.put("name","value")
Using the Function Helper, you can select a function from the pull down, and assign values for its
arguments. The left column in the table provides a brief description of the argument, and the right
column is where you write in the value for that argument. Different functions take different
arguments.
www.vskills.in
Page 109
18.5. Functions
regexFunction
The Regex Function is used to parse the previous response (or the value of a variable) using any
regular expression (provided by user). The function returns the template string with variable values
filled in.
The __regexFunction can also store values for future use. In the sixth parameter, you can specify a
reference name. After this function executes, the same values can be retrieved at later times using
the syntax for user-defined values. For instance, if you enter "refName" as the sixth parameter you
will be able to use:
${refName} to refer to the computed result of the second parameter ("Template for the
replacement string") parsed by this function
${refName_g0} to refer to the entire match parsed by this function.
${refName_g1} to refer to the first group parsed by this function.
${refName_g#} to refer to the n th group parsed by this function.
${refName_matchNr} to refer to the number of groups found by this function.
Parameters
Attribute
Description
Required
The first argument is the regular expression to be applied to the response
data. It will grab all matches. Any parts of this expression that you wish to
use in your template string, be sure to surround in parentheses. Example: <a
First
href="(.*)">. This will grab the value of the link and store it as the first group Yes
argument
(there is only 1 group). Another example: <input type="hidden" name="(.*)"
value="(.*)">. This will grab the name as the first group, and the value as the
second group. These values can be used in your template string
This is the template string that will replace the function at run-time. To refer
Second
to a group captured in the regular expression, use the syntax: Yes
argument
$[group_number]$. Ie: $1$, or $2$. Your template can be any string.
The third argument tells JMeter which match to use. Your regular
expression might find numerous matches. You have four choices:
An integer - Tells JMeter to use that match. '1' for the first found match, '2'
for the second, and so on
Third
RAND - Tells JMeter to choose a match at random.
No,
argument ALL - Tells JMeter to use all matches, and create a template string for each default=1
one and then append them all together. This option is little used.
A float number between 0 and 1 - tells JMeter to find the Xth match using
the formula: (number_of_matches_found * float_number) rounded to
nearest integer.
Fourth
If 'ALL' was selected for the above argument value, then this argument will No
www.vskills.in
Page 110
counter
The counter generates a new number each time it is called, starting with 1 and incrementing by +1
each time. The counter can be configured to keep each simulated user's values separate, or to use
the same counter for all users. If each user's values is incremented separately, that is like counting
the number of iterations through the test plan. A global counter is like counting how many times
that request was run.
The counter uses an integer variable to hold the count, which therefore has a maximum of
2,147,483,647.
The counter function instances are now completely independent. [JMeter 2.1.1 and earlier used a
fixed thread variable to keep track of the per-user count, so multiple counter functions operated on
the same value.] The global counter - "FALSE" - is separately maintained by each counter instance.
Multiple __counter function calls in the same iteration won't increment the value further.
If you want to have a count that increments for each sample, use the function in a Pre-Processor
such as User Parameters .
Parameters
Attribute
First
argument
Second
argument
Description
Required
TRUE if you wish each simulated user's counter to be kept
independent and separate from the other users. FALSE for a global Yes
counter.
A reference name for reusing the value created by this function.
Stored values are of the form ${refName}. This allows you to keep one
No
counter and refer to its value in multiple places. [For JMeter 2.1.1 and
earlier this parameter was required.]
threadNum
The thread number function simply returns the number of the thread currently being executed.
These numbers are independent of ThreadGroup, meaning thread #1 in one threadgroup is
indistinguishable from thread #1 in another threadgroup, from the point of view of this function.
www.vskills.in
Page 111
intSum
The intSum function can be used to compute the sum of two or more integer values.
Attribute
Description
Required
First
The first int value.
Yes
argument
Second
The second int value.
Yes
argument
nth
The nth int value.
No
argument
A reference name for reusing the value computed by this function. If
last
specified, the reference name must contain at least one non-numeric No
argument
character otherwise it will be treated as another int value to be added.
longSum
The longSum function can be used to compute the sum of two or more long values.
Parameters
Attribute
First
argument
Second
argument
nth
argument
last
argument
Description
Required
Yes
Yes
No
StringFromFile
The StringFromFile function can be used to read strings from a text file. This is useful for running
tests that require lots of variable data. For example when testing a banking application, 100s or
1000s of different account numbers might be required.
Each time it is called it reads the next line from the file. All threads share the same instance, so
different threads will get different lines. When the end of the file is reached, it will start reading
again from the beginning, unless the maximum loop count has been reached. If there are multiple
references to the function in a test script, each will open the file independently, even if the file
names are the same. [If the value is to be used again elsewhere, use different variable names for
each function call.]
www.vskills.in
Page 112
Description
Required
Path to the file name. (The path can be relative to the JMeter launch
directory) If using optional sequence numbers, the path name should be Yes
suitable for passing to DecimalFormat. See below for examples.
A reference name - refName - for reusing the value created by this
function. Stored values are of the form ${refName}. Defaults to No
"StringFromFile_".
Initial Sequence number (if omitted, the End sequence number is treated
No
as a loop count)
Final sequence number (if omitted, sequence numbers can increase
No
without limit)
The file name parameter is resolved when the file is opened or re-opened.
The reference name parameter (if supplied) is resolved every time the function is executed.
www.vskills.in
Page 113
machineName
The machineName function returns the local host name
Parameters
Attribute
Description
Required
Variable Name A reference name for reusing the value computed by this function. No
machineIP
The machineIP function returns the local IP address
Parameters
Attribute
Description
Required
Variable Name A reference name for reusing the value computed by this function. No
__javaScript
The javaScript function executes a piece of JavaScript (not Java!) code and returns its value
The JMeter Javascript function calls a standalone JavaScript interpreter. Javascript is used as a
scripting language, so you can do calculations etc.
For details of the language, please see Mozilla Rhino Overview
The following variables are made available to the script:
log - the logger for the function
ctx - JMeterContext object
vars - JMeterVariables object
threadName - String containing the current thread name (in 2.3.2 it was misspelt as
"theadName")
sampler - current Sampler object (if any)
sampleResult - previous SampleResult object (if any)
www.vskills.in
Page 114
Parameters
Attribute
Description
Required
The JavaScript expression to be executed. For example:
new Date() - return the current date and time
Math.floor(Math.random()*(${maxRandom}+1)) - a random number
between 0 and the variable maxRandom
Yes
Expression
${minRandom}+Math.floor(Math.random()*(${maxRandom}${minRandom}+1)) - a random number between the variables minRandom
and maxRandom
"${VAR}"=="abcd"
Variable
A reference name for reusing the value computed by this function.
No
Name
Random
The random function returns a random number that lies between the given min and max values.
Parameters
Attribute
Description
Required
Minimum value A number
Yes
Maximum value A bigger number
Yes
Variable Name A reference name for reusing the value computed by this function. No
RandomString
The RandomString function returns a random String of length using characters in chars to use.
Parameters
Attribute
Description
Required
Length
A number length of generated String
Yes
Characters to use Chars used to generate String
No
Variable Name A reference name for reusing the value computed by this function. No
UUID
The UUID function returns a pseudo random type 4 Universally Unique IDentifier (UUID).
CSVRead
The CSVRead function returns a string from a CSV file (c.f. StringFromFile )
www.vskills.in
Page 115
property
The property function returns the value of a JMeter property. If the property value cannot be
found, and no default has been supplied, it returns the property name. When supplying a default
value, there is no need to provide a function name - the parameter can be set to null, and it will be
ignored.
For example:
${__property(user.dir)} - return value of user.dir
www.vskills.in
Page 116
Parameters
Attribute
Description
Required
Property Name
The property name to be retrieved.
Yes
Variable Name A reference name for reusing the value computed by this function.
No
Default Value
The default value for the property.
No
P
This is a simplified property function which is intended for use with properties defined on the
command line. Unlike the __property function, there is no option to save the value in a variable,
and if no default value is supplied, it is assumed to be 1. The value of 1 was chosen because it is
valid for common test variables such as loops, thread count, ramp up etc.
For example:
Define the property value:
jmeter -Jgroup1.threads=7 -Jhostname1=www.realhost.edu
Fetch the values:
${__P(group1.threads)} - return the value of group1.threads
${__P(group1.loops)} - return the value of group1.loops
${__P(hostname,www.dummy.org)} - return value of
www.dummy.org if not defined
property
hostname
or
In the examples above, the first function call would return 7, the second would return 1 and the
last would return www.dummy.org (unless those properties were defined elsewhere!)
Parameters
Attribute
Description
Required
Property Name
The property name to be retrieved.
Yes
Default Value The default value for the property. If omitted, the default is set to "1".
No
log
The log function logs a message, and returns its input string
Parameters
www.vskills.in
Page 117
The OUT and ERR log level names are used to direct the output to System.out and System.err
respectively. In this case, the output is always printed - it does not depend on the current log
setting.
For example:
${__log(Message)} - written to the log file as "...thread Name : Message"
${__log(Message,OUT)} - written to console window
${__log(${VAR},,,VAR=)} - written to log file as "...thread Name VAR=value"
logn
The logn function logs a message, and returns the empty string
Parameters
Attribute
Description
String to be
A string
logged
Log Level
OUT, ERR, DEBUG, INFO (default), WARN or ERROR
Throwable text If non-empty, creates a Throwable to pass to the logger
If present, it is displayed in the string. Useful for identifying what is
Comment
being logged.
Required
Yes
No
No
No
The OUT and ERR log level names are used to direct the output to System.out and System.err
respectively. In this case, the output is always printed - it does not depend on the current log
setting.
For example:
example:
${__logn(VAR1=${VAR1},OUT)} - write the value of the variable to the console window
BeanShell
The BeanShell function evaluates the script passed to it, and returns the result.
For full details on using BeanShell, please see the BeanShell web-site at http://www.beanshell.org/
Note that a different Interpreter is used for each independent occurrence of the function in a test
script, but the same Interpreter is used for subsequent invocations. This means that variables
persist across calls to the function.
www.vskills.in
Page 118
Parameters
Attribute
Description
Required
BeanShell script A beanshell script (not a file name)
Yes
Name of variable A reference name for reusing the value computed by this function. No
Example:
${__BeanShell(123*456)} - returns 56088
${__BeanShell(source("function.bsh"))} - processes the script in function.bsh
split
The split function splits the string passed to it according to the delimiter, and returns the original
string. If any delimiters are adjacent, "?" is returned as the value. The split strings are returned in
the variables ${VAR_1}, ${VAR_2} etc. The count of variables is returned in ${VAR_n}. From
JMeter 2.1.2 onwards, a trailing delimiter is treated as a missing variable, and "?" is returned. Also,
to allow it to work better with the ForEach controller, __split now deletes the first unused variable
in case it was set by a previous split.
Example:
Define VAR="a||c|" in the test plan.
${__split(${VAR},VAR,|)}
This will return the contents of VAR, i.e. "a||c|" and set the following variables:
VAR_n=4 (3 in JMeter 2.1.1 and earlier)
VAR_1=a
VAR_2=?
VAR_3=c
VAR_4=? (null in JMeter 2.1.1 and earlier)
www.vskills.in
Page 119
Parameters
Attribute
Description
Required
String to split A delimited string, e.g. "a|b|c"
Yes
Name
of
A reference name for reusing the value computed by this function.
Yes
variable
The delimiter character, e.g. | . If omitted, , is used. Note that , would
No
Delimiter
need to be specified as \, .
XPath
The XPath function reads an XML file and matches the XPath. Each time the function is called,
the next match will be returned. At end of file, it will wrap around to the start. If no nodes
matched, then the function will return the empty string, and a warning message will be written to
the JMeter log file.
Example:
${__XPath(/path/to/build.xml, //target/@name)}
This will match all targets in build.xml and return the contents of the next name attribute
Parameters
Attribute
Description
Required
Attribute
XML file to parse a XML file to parse
Yes
XPath
a XPath expression to match nodes in the XML file Yes
setProperty
The setProperty function sets the value of a JMeter property. The default return value from the
function is the empty string, so the function call can be used anywhere functions are valid.
The original value can be returned by setting the optional 3rd parameter to "true".
Properties are global to JMeter, so can be used to communicate between threads and thread
groups
Parameters
Attribute
Description
Required
Property Name
The property name to be set.
Yes
Property Value
The value for the property.
Yes
True/False Should the original value be returned?
No
www.vskills.in
Page 120
jexl
The jexl function returns the result of evaluating a Commons JEXL expression . See links below
for more information on JEXL expressions.
The __jexl function uses Commons JEXL 1, and the __jexl2 function uses Commons JEXL 2
JEXL syntax description
JEXL examples
Parameters
Attribute
Description
Required
Expression The expression to be evaluated. For example, 6*(5+2) Yes
Name of variable The name of the variable to set.
No
The following variables are made available to the script:
log - the logger for the function
ctx - JMeterContext object
www.vskills.in
Page 121
V
The V (variable) function returns the result of evaluating a variable name expression. This can be
used to evaluate nested variable references (which are not currently supported).
For example, if one has variables A1,A2 and N=1:
${A1} - works OK
${A${N}} - does not work (nested variable reference)
${__V(A${N})} - works OK. A${N} becomes A1, and the __V function returns the value of A1
Parameters
Attribute
Description
Required
Variable name The variable to be evaluated. Yes
evalVar
evalVar
The eval function returns the result of evaluating an expression stored in a variable.
This allows one to read a string from a file, and process any variable references in it. For example,
if the variable "query" contains "select ${column} from ${table}" and "column" and "table" contain
"name" and "customers", then ${__evalVar(query)} will evaluate as "select name from customers".
Parameters
Attribute
Description
Required
Variable name The variable to be evaluated. Yes
eval
The eval function returns the result of evaluating a string expression.
www.vskills.in
Page 122
Parameters
Attribute
Description
Required
Variable name The variable to be evaluated. Yes
char
The char function returns the result of evaluating a list of numbers as Unicode characters. See also
__unescape(), below.
This allows one to add arbitrary character values into fields.
Parameters
Attribute
Description
Required
Unicode
character The decimal number (or hex number, if prefixed by 0x, or
number (decimal or octal, if prefixed by 0) to be converted to a Unicode Yes
0xhex)
character.
Examples:
Examples:
${__char(13,10)} = ${__char(0xD,0xA)} = ${__char(015,012)} = CRLF
${__char(165)} = (yen)
unescape
The unescape function returns the result of evaluating a Java-escaped string. See also __char()
above.
This allows one to add characters to fields which are otherwise tricky (or impossible) to define via
the GUI.
Parameters
www.vskills.in
Page 123
Examples:
${__unescape(\r\n)} = CRLF
${__unescape(1\t2)} = 1[tab]2
unescapeHtml
Function to unescape a string containing HTML entity escapes to a string containing the actual
Unicode characters corresponding to the escapes. Supports HTML 4.0 entities.
For example, the string "<Français>" will become "<Franais>" .
If an entity is unrecognized, it is left alone, and inserted verbatim into the result string. e.g.
">&zzzz;x" will become">&zzzz;x" .
Uses StringEscapeUtils#unescapeHtml(String) from Commons Lang.
Parameters
Attribute
Description
Required
String to escape The string to be escaped. Yes
escapeHtml
Function which escapes the characters in a String using HTML entities. Supports HTML 4.0
entities.
For example, "bread" & "butter" becomes: "bread" & "butter" .
Uses StringEscapeUtils#escapeHtml(String) from Commons Lang.
Parameters
Attribute
Description
Required
String to decode The string with URL encoded chars to decode. Yes
urldecode
Function to decode a application/x-www-form-urlencoded string. Note: use UTF-8 as the encoding
scheme.
For example, the string Word+%22school%22+is+%22%C3%A9cole%22+in+french would get
converted to Word "school" is "cole" in french .
www.vskills.in
Page 124
Parameters
Attribute
Description
Required
String to encode String to encode in URL encoded chars. Yes
urlencode
Function to encode a string to a application/x-www-form-urlencoded string.
For example, the string Word "school" is "cole" in french would get converted
toWord+%22school%22+is+%22%C3%A9cole%22+in+french .
Uses Java class URLEncoder .
Parameters
Parameters
Attribute
Description
Required
String to encode String to encode in URL encoded chars. Yes
FileToString
The FileToString function can be used to read an entire file. Each time it is called it reads the
entire file.
If an error occurs opening or reading the file, then the function returns the string "**ERR**"
Parameters
Attribute
Description
Required
Path to the file name. (The path can be relative to the JMeter
Yes
File Name
launch directory)
File encoding if not the The encoding to be used to read the file. If not specified, the
No
platform default
platform default is used.
A reference name - refName - for reusing the value created by
Variable Name
No
this function. Stored values are of the form ${refName}.
The file name, encoding and reference name parameters are resolved every time the function is
executed.
samplerName
The samplerName function returns the name (i.e. label) of the current sampler.
The function does not work in Test elements that don't have an associated sampler. For example
the Test Plan. Configuration elements also don't have an associated sampler. However some
Configuration elements are referenced directly by samplers, such as the HTTP Header Manager
www.vskills.in
Page 125
Parameters
Attribute
Variable
Name
Description
Required
A reference name - refName - for reusing the value created by this
No
function. Stored values are of the form ${refName}.
TestPlanName
The TestPlanName function returns the name of the current test plan (can be used in Including
Plans to know the name of the calling test plan).
escapeOroRegexpChars
Function which escapes the ORO Regexp meta characters, it is the equivalent of \Q \E in Java
Regexp Engine.
For example, [^"].+? becomes: \[\^\"\]\.\+\? .
Uses Perl5Compiler#quotemeta(String) from ORO.
Parameters
Attribute
Description
Required
String
to
The string to be escaped.
Yes
escape
Variable
A reference name - refName - for reusing the value created by this
No
Name
function. Stored values are of the form ${refName}.
PrePre-defined Variables
Most variables are set by calling functions or by test elements such as User Defined Variables; in
which case the user has full control over the variable name that is used. However some variables
are defined internally by JMeter. These are listed below.
COOKIE_cookiename - contains the cookie value (see HTTP Cookie Manager )
JMeterThread.last_sample_ok - whether or not the last sample was OK - true/false. Note: this is
updated after PostProcessors and Assertions have been run.
START variables (see next section)
PrePre-defined Properties
The set of JMeter properties is initialised from the system properties defined when JMeter starts;
additional JMeter properties are defined in jmeter.properties, user.properties or on the command
line.
Some built-in properties are defined by JMeter. These are listed below. For convenience, the
START properties are also copied to variables with the same names.
START.MS - JMeter start time in milliseconds
START.YMD - JMeter start time as yyyyMMdd
START.HMS - JMeter start time as HHmmss
www.vskills.in
Page 126
www.vskills.in
Page 127
19.2. Examples
Extract single string
Suppose you want to match the following portion of a web-page:
name="file" value="readme.txt">
and you want to extract readme.txt .
A suitable regular expression would be:
name="file" value="(.+?)">
The special characters above are:
www.vskills.in
Page 128
www.vskills.in
Page 129
SingleSingle-line mode
Single-line mode only affects how the '.' meta-character is interpreted.
Default behavior is that '.' matches any character except newline. In single-line mode, '.' also
matches newline.
MultiMulti-line mode
Multi-line mode only affects how the meta-characters '^' and '$' are interpreted.
Default behavior is that '^' and '$' only match at the very beginning and end of the string. When
Multi-line mode is used, the '^' metacharacter matches at the beginning of every line, and the '$'
metacharacter matches at the end of every line.
Page 130
(?!regexp)
A zero-width negative lookahead assertion. For example foo(?!bar) matches any occurrence
of "foo" that isn't followed by "bar". Remember that this is a zero-width assertion, which
means that a(?!b)d will match ad because a is followed by a character that is not b (the d)
and a d follows the zero-width assertion.
(?imsx)
One or more embedded pattern-match modifiers. i enables case insensitivity, m enables
multiline treatment of the input, s enables single line treatment of the input, and x enables
extended white space comments.
Note that (?<=regexp) - lookbehind - is not supported.
Placement of modifiers
Modifiers can be placed anywhere in the regex, and apply from that point onwards. [A bug in
ORO means that they cannot be used at the very end of the regex. However they would have no
effect there anyway.]
The single-line (?s) and multi-line (?m) modifiers are normally placed at the start of the regex.
The ignore-case modifier (?i) may be usefully applied to just part of a regex, for example:
Match ExAct case or (?i)ArBiTrARY(?-i) case
Testing Regular
Regular Expressions
Since JMeter 2.4, the listener View Results Tree include a RegExp Tester to test regular
expressions directly on sampler response data.
There is a demo applet for Apache JMeter ORO.
Another approach is to use a simple test plan to test the regular expressions. The Java Request
sampler can be used to generate a sample, or the HTTP Sampler can be used to load a file. Add a
Debug Sampler and a Tree View Listener and changes to the regular expression can be tested
quickly, without needing to access any external servers.
www.vskills.in
Page 131
20.2. Searching
It is sometimes hard to find in a Test Plan tree and elements using a variable or containing a
certain URL or parameter. A new feature is now available since 2.6, you can access it in Menu
Search. It provides search with following options:
Case Sensitive : Makes search case sensitive
www.vskills.in
Page 132
Figure 3 - Search Regexp in TreeView (in this example we search whole word)
www.vskills.in
Page 133
www.vskills.in
Page 134