JMeter Complete Element Reference– Part VI

In this article, we will discuss about the next set of JMeter elements i.e Pre-Processors and Post-Processors. Lets discuss in detail, how do we use these elements to build a effective test scripts . In case if you have missed the older articles click here.

Pre Processor Elements

A Pre-Processor elements executes some action prior to a Sampler Request being made. If a Pre-Processor is attached to a Sampler element, then it will execute just prior to that sampler element running. A Pre-Processor is most often used to modify the settings of a Sample Request just before it runs, or to update variables that aren’t extracted from response text.

Post Processor Elements

A Post-Processor elements executes some action after a Sampler Request has been made. If a Post-Processor is attached to a Sampler element, then it will execute just after that sampler element runs. A Post-Processor is most often used to process the response data, often to extract values from it.

Execution order of the Elements:

Lets understand in which order JMeter process the elements when multiple elements are added to the thread group.

  1. Configuration elements
  2. Pre-Processors
  3. Timers
  4. Sampler
  5. Post-Processors
  6. Assertions
  7. Listeners

Please note that Timers, Assertions, Pre- and Post-Processors are only processed if there is a sampler to which they apply. Logic Controllers and Samplers are processed in the order in which they appear in the tree. Other test elements are processed according to the scope in which they are found, and the type of test element.

Lets examine with an example where my test plan consists of combination of samplers, listeners, pre-processors, post-processors, timers and config elements which looks exactly as below:

Controller
   Post-Processor 1
   Sampler 1
   Timer 1
   Assertion 1
   Pre-Processor 1
   Timer 2
   Post-Processor 2

When the above test plan is executed, JMeter process the elements in the following order:

Pre-Processor 1
Timer 1
Timer 2
Sampler 1
Post-Processor 1
Post-Processor 2
Assertion 1

Apache JMeter provides wide variety of pre and post processor elements and would like discuss about elements which are largely used and most advanced built-in components in this article. Please refer JMeter user manual for more processor elements.

User Parameters

This pre-processors allows the user to specify values for User Variables specific to individual threads. User Variables can also be specified in the Test Plan but not specific to individual threads. This panel allows you to specify a series of values for any User Variable.

For each thread, the variable will be assigned one of the values from the series in sequence. If there are more threads than values, the values get re-used. For example, this can be used to assign a distinct user id to be used by each thread. User variables can be referenced in any field of any JMeter Component.

The variable is specified by clicking the Add Variable button in the bottom of the panel and filling in the Variable name in the ‘Name:’ column. To add a new value to the series, click the ‘Add User’ button and fill in the desired value in the newly added column.

Values can be accessed in any test component in the same thread group, using the function syntax : ${variable}.

userParams

Regular Expression Extractor

Allows the user to extract values from a server response using a Perl-type regular expression. As a post-processor, this element will execute after each Sample request in its scope, applying the regular expression, extracting the requested values, generate the template string, and store the result into the given variable name.

regex_extractor

If the match number is set to a non-negative number, and a match occurs, the variables are set as follows:

refName - the value of the template
refName_gn, where n=0,1,2 - the groups for the match
refName_g - the number of groups in the Regex (excluding 0)

If no match occurs, then the refName variable is set to the default (unless this is absent). Also, the following variables are removed:

refName_g0
refName_g1
refName_g

If the match number is set to a negative number, then all the possible matches in the sampler data are processed. The variables are set as follows:

refName_matchNr - the number of matches found; could be 0
refName_n, where n = 1,2,3 etc-the strings as generated by the template
refName_n_gm, where m=0,1,2 - the groups for match n
refName - always set to the default value
refName_gn - not set

Note that the refName variable is always set to the default value in this case, and the associated group variables are not set.

And also regular expression extractor lets you to extract data not only from response body and also from headers, response code and many more as shown in the screenshot. Lets say if you want to extract some data from header section, add regular expression extractor as a child to the http sampler and in the response field check configuration just select Header option. You can also instruct Regular expression Extractor where to look for the dynamic data such as only main sample or sub samples etc.

How to use Beanshell processor

Beanshell is the most advanced of JMeter built-in components which supports Java syntax and extends it with scripting language features. Beanshell entities available in JMeter have access to both internal JMeter APIs and any external classes which are loaded into JMeter class-path (make sure that you drop necessary jars into /lib/ext folder of your JMeter installation and place all necessary “import” statements at the top of your Beanshell scripts).

Apache JMeter provides various Beanshell components such as:

Beanshell Sampler – a standalone Sampler

Beanshell Pre Processor – a Pre Processor to another Sampler which is executed before Sampler and can be used for pre-requisites setup, i.e. to generate some input 

Beanshell Post Processor – a Post Processor which is executed after Sampler and can be used for recovery or clean up

Beanshell Assertion – an advanced Assertion with full access to JMeter API .Java conditional logic can be used to set assertion result

__Beanshell function – a JMeter Function which allows the execution of custom Beanshell code during a Sampler run

Lets understand in detail with a simple example, we have a scenario where the extracted value from the response of a request sampler has to be saved in to a file. We can achieve this using Beanshell Post processor. The steps can be as follows:

  1. Add a request sampler to the thread group.
  2. To the request sampler, add a regular expression extractor post processor to extract a certain value from the response.
  3. Now add a beanshell post processor as a child to the request sampler to save extracted value into a file.

Now your test plan should look like below:

Bs

In order to save data into a file, following code has to be written in the beanshell processor:

import java.text.SimpleDateFormat;

String tempVar = "D:\\JmeterDownloads\\Scan.csv";
// Get the ScanDate and ScanName 
String scanDate = vars.get("scanDate");
String scanName = vars.get("scanName");

//Create a New fileoutput stream
f= new FileOutputStream(tempVar,true);

// Create new printStream to write data into file
p = new PrintStream(f); 

if(scanDate.equals("NONE")){
 p.println(scanName+", NA");
}
else{
 Long l = new Long(scanDate);
 Date d = new Date(l * 1000L);
 SimpleDateFormat ft = new SimpleDateFormat("dd/MM/yyyy");
 p.println(scanName+","+ft.format(d));
}
// Close fileoutput stream and printstream
p.close();
f.close();

Lets envision a scenario where we have a list of Scans that provides details about the vulnerabilities that are found in the system. Now our goal is to write the ScanName and ScanDate (timestamp) to file, from the above code, it is very clear that vars.get() method is used to get ScanName and ScanDate and then we are converting the ScanDate to human readable format. p.println() method is used to write data into a file. When you run the test, a file with Scan.csv is created on your specified directory with the ScanDate and ScanName values saved in it.

JMeter Pre-defined Beanshell variables:

JMeter pre-defined API is exposed to Beanshell components in order to build complex test scripts. Following are the few JMeter variables that can be used directly in you script:

SampleResult:
SampleResult maps to the JMeter class org.apache.jmeter.samplers.SampleResult, all fields and methods outlined in the javadoc can be accessed and invoked.
String currentURL = SampleResult.getUrlAsString();
ResponseCode:
ResponseCode is a java.lang.String which stands for sampler response code. In detail, response code provides information about the status of the request. The codes help identify the cause of the problem when a web page or other resource does not load properly. For more info visit here.
IsSuccess:
IsSuccess is java.lang.Boolean which reflects whether sampler succeeded. If it’s set to true – sampler will be considered “passed”, otherwise it will be marked as “failed”.
Label:
Label is java.lang.String which represents sampler Label. Can be get or set as usual String, will be listed in Test Results as sampler label.
FileName:
FileName is a java.lang.String which contains beanshell script file name (what is entered in “Script file” stanza of the BeanShell Sampler).
ctx:
ctx is the most powerful variable exposed to Beanshell. It represents threads.JMeterContext class which is pretty much JMeter itself, it provides read/write access to underlying JMeter Engine, Samplers and their Results as well as to variables/properties.
vars:
vars is the most frequently used component which represents JMeter Variables. It’s an instance of org.apache.jmeter.threads.JMeterVariables class and provides read/write access to current variables, capable of enumerating/changing existing, creating new ones and obtaining nested properties.
All JMeter variables are Java Strings, if you need to put something else to a JMeter variable – you’ll need to cast it to string first.
props
Basically it’s the same as “vars”, but it exposes JMeter Properties instead. See JavaDoc on java.util.Properties and JMeter Documentation on JMeter Properties for more information.
The main difference between props and vars is that props have “global” scope, and scope of “vars” is limited to current thread group only.
log
log represents org.apache.log.Logger class and can be used to append a message to jmeter.log file. See JavaDoc on logger for more details.
log.info("Log a message with info Level");

log.error("Log a message with info Level");
Basic Examples using Beanshell processor:

Changing JMeter variables:

Assuming that you have already defined a user defined variable called “LoopCount” with the value of “60”. Now we can get and set the JMeter variables on the fly using beanshell as below:

vars.get(): Returns the value saved in a JMeter variable.

Syntax: vars.get("Name_of_JMeter_Variable");

Example: vars.get("LoopCount"); 
vars.put(): Used to modify the value saved in a JMeter Variable

Syntax: vars.put("Name_of_New_JMeter_Variable","Value to be set");

Example: 

 String tempVar = vars.get("name");
 log.info("Value:"+tempVar);
 tempVar = tempVar + "_Concat_String";
 vars.put("newName",tempVar);
 log.info("Name:"+vars.get("newName"));

Convert JMeter variable to JMeter Property:

As we know that JMeter API is exposed to beanshell components, its very easy to convert a jmeter variable to Jmeter property. By doing so, the variable can know be accessible across multiple thread groups. Lets imagine that we have already defined a variable with a name “J_variable” and casting can be done as below:

props.put("J_variable",vars.get("J_variable"));

Above are the few simple example which explains you how to use beanshell processor in test script. Beanshell can be used in more complex ways depending in the complexity of the application. On the further note beanshell processor consumes memory, so avoid using more number of beanshell processors in single test script.

Reference from Blazemeter.com. If you enjoy reading article then you can subscribe our updates for FREE, just add your email id . I will keep on updating the article for latest testing information. Subscribe and stay tuned for updates, there’s lot more to come.

🙂 Happy Performance Testing !!  🙂

Advertisements

11 thoughts on “JMeter Complete Element Reference– Part VI

  1. Hi Gopi,

    Great work.
    I have a question, Currently I am test for multiple users in JMeter and I am making SOAP XML reuest calls to server.

    I am having multiple users login and do actions. so how can i put different assertions on each user. Based on the user name it should dynamically check assertions for each user which logs in from CSV file.

    Could you please guide me in this. Any help on this is greatly appreciable.

    Thanks,
    Sai

    1. Hello Sai,

      Thank you very much !!

      Would you care to explain why do you want have different set of assertions for different user ? Would like to understand your problem to provide the best solution possible. Anyways since you are working with SOAP XML, Regular Expression would do the trick for you !!

      1) Lets envision that below is the response that you have received for a login action:

      soapenv:Envelope xmlns:soapenv=”http://schemas.xmlsoap.org/soap/envelope/” xmlns:sam=”http://www.example.org/sample/”
      soapenv:Header
      soapenv:Body>
      sam:loginResponse
      sessionid 10873286937963711 sessionid
      sam:loginResponse
      soapenv:Body
      soapenv:Envelope

      You can add response assertion to the request with an assertion value like this “sessionid .+ sessionid”. If login is successful , a unique session ID will be generated for each and every user. the above assertion will validate the response irrespective of the user which will server your purpose. If the login is a failure, session ID wont be generated and the assertion fails.

      2) Else you can pass the assertion value from the CSV file itself. This process will be tedious if the user base is huge. For Example you can pass the response assertion for every user as below. And aslo JMeter will consume more memory while reading the file during the execution.

      User1,password1,assertion1
      User2,password2,assertion2

      If you different assertions for different users and for all the actions preparing test data will be a nightmare.

      3) XPath is a syntax for defining parts of an XML document. XPath uses path expressions to navigate in XML documents. XPath uses path expressions to select nodes or node-sets in an XML document.The XML Assertion checks that the returned response body is XML-compliant. Only the syntax is checked – any external resources are not downloaded and validated. When there is an invalid XML, the reason for failure will be reported in an ‘Assertion Failure’ message.

      I hope this might be the solution that you are looking for. If any further assistance is required you can reach me on gkp.anandi@gmail.com. Sorry my internal anitvirus has removed angle brackets !! errr !!

      🙂 Happy Performance Testing 🙂

      1. Hi Gopi,

        Thanks for your quick response.

        Your reply was really amazing and very informative.

        I have used the regEx and Xpath for getting seesionID and other information. I am also accessing multiple users login into the application from CSV file.

        I can login to the bank application and do transfers, transactions, payments, logout and other actions.

        I am stuck at the situation, where I need to check assertions for each user.

        I am accessing user information from CSV file like

        user1, password1
        user2,password2

        Here is the scenario , where i need to put assertions for each user like an
        example:

        1.)If user1 login and he has only “checking account” after login page.

        I need to put assertion in response checking that “user1 has checking account” in the response SOAP XML

        2.) if user2 login and he has both “checking and savings account” after login page…

        I need to put assertion in response checking that “user2 has both checking & savings account” in response…

        I need to do this dynamically.

        so, how can i put assertions dynamically based on user ID?

        like if user1 logs In, then JMeter should only check for his checking account only, it should not check for both or saving account.

        or if user2 login then it should check for both checking and saving. it should not check for single account i.e. checking or savings.

        is there any Beanshell script to write for it or can we directly put any assertions in JMeter?

        what happens if i have 10..20 users. how to check assertions dynamically based on user id information.

        Could you please guide me in this situation. Look forward for your response.

        Thanks,
        Sai

      2. Hi Gopi,

        Nice Blog, I am trying to hit webservices through soap sampler am getting response like java.io.IOException: Stream closed
        at java.io.BufferedInputStream.getBufIfOpen(Unknown Source)
        at java.io.BufferedInputStream.read(Unknown Source)
        at org.apache.commons.httpclient.ContentLengthInputStream.read(ContentLengthInputStream.java:170)
        at java.io.FilterInputStream.read(Unknown Source)
        at org.apache.commons.httpclient.AutoCloseInputStream.read(AutoCloseInputStream.java:108)
        at java.io.FilterInputStream.read(Unknown Source)
        at org.apache.commons.httpclient.AutoCloseInputStream.read(AutoCloseInputStream.java:127)
        at org.apache.jmeter.protocol.http.sampler.SoapSampler.sample(SoapSampler.java:293)
        at org.apache.jmeter.protocol.http.sampler.HTTPSamplerBase.sample(HTTPSamplerBase.java:1146)
        at org.apache.jmeter.protocol.http.sampler.HTTPSamplerBase.sample(HTTPSamplerBase.java:1135)
        at org.apache.jmeter.threads.JMeterThread.process_sampler(JMeterThread.java:434)
        at org.apache.jmeter.threads.JMeterThread.run(JMeterThread.java:261)
        at java.lang.Thread.run(Unknown Source)

        Could u pls help me on this regard

        Thanks in advance
        Sindhuja

  2. Hi Sai,

    As per my understanding from the above problem, you can try with this solution below. Lets say following accounts will be displayed after login.

    User1:
    Checking accounts

    User2:
    Checking accounts
    Savings accounts

    What you can do is write a RegEx that extracts checking accounts from response and write another RegEx that extracts Savings accounts. Lets assume that ${acc1} has checking account saved and ${acc2} has savings account saved. Now add a response assertion to the request and add the assertion value as stated below:

    ${acc1}||${acc2} and note that in the Pattern matchings rules section of response assertion,”contains” should be selected.

    || – the pipe matches everything on either side of it. If user 1 is logged in assertion will be validated for checking accounts and user2 is logged in assertion will b validated for checking and savings account. if assertions doesnot work with “||’ try using ‘|’.

    Regards/Gopikrishna

    1. prev – used to fetch previous SampleResult. You can get/set start time, end time, execution time, latency, URL, response code, response message, etc.
      Example usage:

      String code = prev.getResponseCode();
      String message = prev.getResponseMessage();

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s