Jmeter Tips and Tricks

Using Roles/Permission in JMeter for API Testing

I was working in a project where there was one Admin user and there were more than 100 HTTP API Request. I wrote my API script and had an assertion accordingly. Later, the requirement for the business changed. They introduced 10 more roles (SuperAdmin, SalesManager, Sales, Finance etc) with different permission level. The HTTP Request were same but they want to validate specific user should not be able to perform certain action. So I cannot have 100 different HTTP Request for 10 roles, the maintenance cost will be very high. So, instead I updated my script in the following ways:

  1. Create a CSV file. Add ${users} in the CSV file.
  2. Create a thread group. (This thread will be executed for each users in CSV file. Once the Request for module controller is finished for one user, it will be execute for another user and so on until all users in CSV file has been executed.)Screen Shot 2020-11-09 at 3.23.21 pm
    1. Add a While Controller. ( ${__javaScript(“${users}” != “<EOF>”,)}) Screen Shot 2020-11-09 at 3.24.46 pm
      1. Add IF Controller. (“${users}” != “<EOF>”)Screen Shot 2020-11-09 at 3.24.52 pm
        1. Add HTTP Request for getting authorization token
        2. Add Module controller
          1. Module controller should point the thread which we want to execute for multiple users
  3. Go to the main thread group which has our HTTP API Requests.
    1. Since, my script is working fine for one user and I am following the data-driven approach. I am only updating few thing here.
      1. While loop should be as: ${__javaScript(“${iterationApprovalLSettings}” != “<EOF>”,)} 
      2. IF controller should be as: “${iterationApprovalLSettings}” != “<EOF>” && “${iterationApprovalLSettings}” != “iterationApprovalLSettings”
      3. The CSV data set config should be as in the image. The sharing mode should be All Threads.Screen Shot 2020-11-09 at 3.33.39 pm
      4. Add a Beanshell Sampler immediately after exiting the while loop. This Beanshell Sampler will close the CSV file. The reason for closing CSV file is, when second user tries to access the it need to start from the beginning. Otherwise, the value for the variable in CSV will have <EOF>.  import org.apache.jmeter.services.FileServer;
        FileServer.getFileServer().closeFile(“${testPlanFileDir}${__BeanShell(File.separator,)}adminApprovalSettings.csv”);
        vars.put(“iterationApprovalLSettings”, “”);Screen Shot 2020-11-09 at 3.37.07 pmScreen Shot 2020-11-09 at 3.50.47 pm
  4. Instead of using Response Assertion in HTTP Request, we must use Beanshell Assertion. We can verify different response for different users for the same API Request.if(“${users}”.equals(“SuperAdmin”))
    {
    if (ResponseCode.equals (“${response}”) == true )
    {
    Failure= false ;
    prev.setResponseOK();
    }

    else
    {
    Failure=true ;
    FailureMessage =”Response code was not, ” +${response} + “it was” + ResponseCode + “.” ;
    }
    }

    else
    {
    if (ResponseCode.equals (“403”) == true )
    {
    Failure= false ;
    prev.setResponseOK();
    }

    else
    {
    Failure=true ;
    FailureMessage =”Response code was not 403, it was ” + ResponseCode + “.” ;
    }
    }Screen Shot 2020-11-09 at 3.56.59 pm

  5. In this way, the HTTP Request will be executed for each user mentioned in CSV file and the response will be verified accordingly.

Notes:  for Response Text

if(“${users}”.equals(“SuperAdmin”)||”${users}”.equals(“Admin”))
{
if (prev.getResponseDataAsString().contains (“${buyerID}”) == true )
{
Failure= false ;
prev.setResponseOK();
}

else
{
Failure=true ;
FailureMessage =”Response Text was not ${buyerID}, it was” + prev.getResponseDataAsString() + “.” ;
}
}

Read Data from CSV and Continue

The problem with csv data set config is we can’t continue to another step when the last row of CSV is read. The thread will be closed and we need to execute another thread.

What if we want to execute immediate step csv read??

we can do it by using the while loop and if condition inside the while loop.

  • the condition for while loop is as follows:
    • ${__javaScript(“${var}” != “<EOF>”,)}
      • where “var” is the variable name in the CSV file.
  • the condition for if statement is as follows:
    • “${var}” != “<EOF>”
  • inside the if statement we can implement our request.
  • stop thread on EOF must be false.

The order of the while loop, csv and if controller should be as shown in the image.

Follow image for more details:

1
while controller
2
csv data set config
3
if controller

 Extract Value From Jmeter Post Request

Extracting value from jmeter response is easy. We can use either Regex Extractor or Json Extractor. 

But, sometime you need to extract the value from post request and extracting value from post request is tricky.

Follow following steps:

  • add a BeanShell post processor in your HTTP request with following code
import org.apache.jmeter.config.Argument;
import org.apache.jmeter.config.Arguments;

Arguments argz = ctx.getCurrentSampler().getArguments();
for (int i = 0; i < argz.getArgumentCount(); i++) {
   Argument arg = argz.getArgument(i);
    String a = arg.getValue();
    vars.put("EMAIL",a);
 }    

— get request as a JSON and put it in EMAL. Now, you can use EMAIL as a variable in another request.

Then, add Json Path Extractor and apply it to the JMeter Variable. Here, EMAIL will be used as a variable which contains your json request. And now you can extract data using JSON Extractor.

Using Unicode in Jmeter

If you want to use Unicode in JMeter and want the response in Unicode to follow following steps:

  1. Open jmeter.properties file (which is in /bin folder of jmeter)
  2. Change encoding as follow:
    1. # The encoding to be used if none is provided (default ISO-8859-1)
      sampleresult.default.encoding=UTF-8
  3. Save the file and restart JMeter.

Download Plugin for Jmeter

To download an external plugin for JMeter, follow following steps:

  1. Download jar file from here (jar_file).
  2. Extract it.
  3. Copy it to Jmeter's lib/ext directory.
  4. Restart Jmeter
  5. Go to option menu of Jmeter
  6. Click on Plugins Manager
  7. Plugin manager window will open. You can install/uninstall/upgrade the plugin.
  8. For more details visit (jmeter_plugin_manager).

To Store Random Variable in a Variable

TEST_${__RandomString(20,ABCDEFEGEG,Variable)}

  • RandomString is a javascript function, it will generate a random string of 20 characters from “ABCDEFEGEG” and store its value to “Variable”.

Function Help in Jmeter

If you want to generate a function or want to know the list of function supported in Jmeter the follow following Steps:

  1. Go to Options menu in Jmeter.
  2. Click Function Helper Dialogue.
  3. Function Helper Dialogue window will appear from where you can view the list of function in the dropdown, view details about it and generate it.

Screen Shot 2017-06-16 at 11.39.05 AM

Executing Testplan in Loop From Terminal

  1. Go to terminal
  2. Go to Jmeter’s /bin folder
  3. Type:

    1. for i in {1..5}

      > do

      > ./jmeter -n -t /test_script.jmx

      done

    2. The script will execute 5 times.

Set Http Response Code to Ok

If you are getting HTTP response code as 500 but you want to pass the test then add a BeanShell assertion and insert following code:

if (prev.getResponseCode() == “500”)

{

prev.setResponseOK();

}

Inter-Thread Variable In Jmeter

If you want to pass a variable from one thread group to another thread group then you need to function: __setProperty and __property

  1. In the first thread group, extract variable (varaible1) using regular expression extractor or json extractor or any.
  2. Add BeanShell assertion in that thread group and use the following function
    1. ${__setProperty(varaible1, ${varaible1})};
  3. ${varaible1} is extracted using variable extractor in Thread Group 1 and store its value to  variable1.
  4. From another Thread Group, we can call that variable using the following function:
  5. ${__property(varaible1)}

Absolute Directory Path for .jmx file – JME

While I was creating JMeter script, the problem I faced was using the absolute directory path. In my script, I used .csv file and the file path I had given to .csv works fine only on my system. When I tried to run that script on my colleague’s machine or in Jenkins, then the script failed because the file didn’t match (Jmeter could not find the file). And changing file path for every .csv file was too tedious.

So, to overcome this problem, I used Beanshell variable. I created a global variable called testPlanFileDir with value ${__BeanShell(import org.apache.jmeter.services.FileServer; FileServer.getFileServer().getBaseDir();)}${__BeanShell(File.separator,)} as below

testPlanFileDir    ${__BeanShell(import org.apache.jmeter.services.FileServer; FileServer.getFileServer().getBaseDir();)}${__BeanShell(File.separator,)}

screen-shot-2016-10-03-at-11-16-42-am
Global Variable

Now, I can call global variable “testPlanFileDir” from anywhere inside the JMeter script and it will return the absolute path of mine .jmx file. No matter, from where I run the script either from other machines or Jenkins, it worked fine for me.

Published by Kishor Sharma

✔ QA Engineer since Jan 2014 ✔ Passionate to deliver the quality product. ✔ Requirement Analysis/ Requirement Engineering ✔ Manual Testing (Regression Engineer) ✔ Test Automation (Selenium Webdriver, Cucumber, Robot Framework, Protractor) ✔ Performance Testing (JMeter, Blazemeter, Taurus) ✔ Agile software development ✔ Scrum/JIRA/Kanban ✔ Jmeter (API Testing)

Leave your feedback...