Monday, January 20, 2020

Jmeter response header parsing using BeanShell scripting

Response is :Set-Cookie: ADCSESSID=e11dd94e-ee22-4313-84bc-df5040acf101; Domain=.auction.com; httponly; Path=/

I need only ADCSESSID value. So
Regular expression is : "ADCSESSID=(.+?);"

Check this using java regualr expression tester : http://ocpsoft.org/tutorials/regular-expressions/java-visual-regex-tester/#!;t=User%20clientId%3D23421.%20Some%20more%20text%20clientId%3D33432.%20This%20clientNum%3D100&r=(clientId%3D)(%5Cd%2B)&x=***masked***

Reference doc:
http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html
String jsonString = prev.getResponseHeaders();
//System.out.println(jsonString);
SampleResult.setResponseData( jsonString );
text = prev.getResponseHeaders();
patternText = "ADCSESSID=(.+?);";
//System.out.println(patternText);
p = java.util.regex.Pattern.compile(patternText, java.util.regex.Pattern.DOTALL);
System.out.println("p value is "+p);
m = p.matcher(text);
System.out.println("matcher m value is " +m);
if (m.find()) {
    vars.put("beanShellExecutionId", m.group(1));
} else {
    vars.put("beanShellExecutionId", "NOT_FOUND");
}

System.out.println(vars.get("beanShellExecutionId"));

print date in MM/dd/yyyy hh:mm:ss a

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.TimeZone;

SimpleDateFormat formatter, FORMATTER;
formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSz");
String oldDate = "2008-03-14T11:53:31.200+05:00";
Date date = formatter.parse(oldDate.substring(0, 26) + oldDate.substring(27, 29));
FORMATTER = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a");
System.out.println("OldDate-->"+oldDate);
log.info("NewDate-->"+FORMATTER.format(date));
vars.put("myvar", FORMATTER.format(date)); 

Share variables between thread groups

I was not able to do this with variables (since those are local to individual threads). However, I was able to solve this problem with properties!
Again, my first ThreadGroup does all of the set up, and I need some information from that work to be available to each of the threads in the second ThreadGroup. I have a BeanShell Assertion in the first ThreadGroup with the following:
${__setProperty(storeid, ${storeid})};
The ${storeid} was extracted with an XPath Extractor. The BeanShell Assertion does other stuff, like checking that storeid was returned from the previous call, etc.
Anyway, in the second ThreadGroup, I can use the value of the "storeid" property in Samplers with the following:
${__property(storeid)}
Works like a charm!

Thursday, July 7, 2016

Create output file using bean shell

import org.apache.jmeter.services.FileServer;
import java.util.Date;
import java.text.SimpleDateFormat;




String DirPath = FileServer.getFileServer().getBaseDir()+File.separator;
String fileName="jmeterDemo.txt";
//log.info(DirPath);
//System.out.println(DirPath);
f = new FileOutputStream(DirPath+"jmeterDemo2.txt", false);
p = new PrintStream(f);


SimpleDateFormat formatter = new SimpleDateFormat( "yyMMddHHmmssZ" ); 
String datetime = formatter.format( new java.util.Date() );

SimpleDateFormat formatter2 = new SimpleDateFormat( "dd/M/yyyy" ); 
String exportedDate = formatter2.format( new java.util.Date() );


for(int i=1;i<=100;i++) {

    if(i==1){
     p.println("id,primar_id,email,first_name,last_name,dob,team_name,dependent_type,start_date,end_date,export_date");
    }
    email="perf_"+datetime+""+i+"@google.com";
    p.println(i+",,"+email+",first,last,01/01/1980,,self,06/23/2016,,"+exportedDate);
}
p.close();
f.close();

Tuesday, June 28, 2016

Jmeter Beanshell script

import org.apache.jmeter.services.FileServer;
import org.apache.jmeter.services.FileServer;
import java.util.Date;
import java.text.SimpleDateFormat;

SimpleDateFormat formatter = new SimpleDateFormat( "yyyyMMddHHmmss" );  
String datetime = formatter.format( new java.util.Date() ); 
1 Get current running counter value(C refrence name deifned in Counter config element)
String counter= vars.get("C");
2 Get Jmeter variable value in bean shell script by vars.get method
String timer= vars.get("JmeterTimerVariable");
here JmeterTimerVariable defined in User Defined variable config element
3 Display value in Console
System.out.println("Current counter value = " + counter);

System.out.println("JmeterTimerVariable value = " + timer);
4 Store beanshell script variable into Jmeter variable by using vars.put method and we will use this jmetervariable in Wikisearch http request
vars.put("JmeterSearchVariable",datetime+counter);
5 Get JmeterSearchVariable value in beanshell script
String SearchVariable = vars.get("JmeterSearchVariable");

System.out.println("SearchVariable value = " + SearchVariable);
6 Here we can get the directory path of Jmeter script file
String DirPath = FileServer.getFileServer().getBaseDir();
7 Write into jmeter.log file under Jmeter/bin directory
log.info(DirPath);

System.out.println("Directory path of Jmeter script file = " + FileServer.getFileServer().getBaseDir());
8 We will create a file under directory of jmeter script file with name JmeterReords using File system True file will be created if not and data will //append into the file False will create a new file with fresh data
f = new FileOutputStream(FileServer.getFileServer().getBaseDir()+"\\JmeterReords.txt", true); 
p = new PrintStream(f); 
9 Write data into file
p.println("Current counter value = " + counter);
p.println("JmeterTimerVariable value = " + timer);
p.println("Directory path of Jmeter script file = " +DirPath);
p.close();
f.close();
10 If you want to create unique file for each loop counter refer below script
String uniquefilename = timer+counter;
f = new FileOutputStream(FileServer.getFileServer().getBaseDir()+"\\"+uniquefilename+".log", true); 
p = new PrintStream(f); 
11 Write data into file
p.println("Current counter value = " + counter);
p.println("JmeterTimerVariable value = " + timer);
p.println("Directory path of Jmeter script file = " +DirPath);
p.close();
f.close(); 
 
 
 
 
I ran into a similar situation a while ago where I had to upload a signature file as part of a POST request. This signature file lived relative to the folder structure in which my JMeter scripts were located.
Try using the following BeanShell expression (which can be accessed as a system-level property) to resolve the relative path from the location in which your JMeter test-cases are located/executed.
${__BeanShell(import org.apache.jmeter.services.FileServer; FileServer.getFileServer().getBaseDir();)}${__BeanShell(File.separator,)}
  • You can enter this with the name of the file you want to send/POST in the "Send Files With the Request" field by simply appending the file name.
    ${__BeanShell(import org.apache.jmeter.services.FileServer; FileServer.getFileServer().getBaseDir();)}${__BeanShell(File.separator,)}fileName.sig
  • A more cleaner implementation would be declare this as a variable (local or global depending on the scope) and use this variable within the appropriate fields.
    absolutePath = ${__BeanShell(import org.apache.jmeter.services.FileServer; FileServer.getFileServer().getBaseDir();)}${__BeanShell(File.separator,)}
    ${absolutePath}fileName.sig
NOTE: This approach is super useful if you intend to plug your JMeter test files into a Continuous Integration system such as Jenkins. It makes your test-cases more maintainable.
 

Friday, June 26, 2015

Create RandonString using Jmeter

I want to pass randomString to my request body , below is the request body

{
"http_session_id":"${RanDomCookie}",
"Name":"APP"
}


We have two ways ,
1. Using BeanShell scripting.
2. Using JMeter __RandomString()

1: Using BeanShell Scripting

Below are the Steps:
1. Add Http Sampler and add Add beanShell Preprocessor as child and enter below code.


import java.util.Random;


String str="abcdefghijklmnopqrst1234567890";
int String_Length=32;
String randomSting="";
for(int i=1;i<=String_Length;i++){
Random randomVal=new Random();
int randomInt=randomVal.nextInt(str.length());
randomSting+=str.substring(randomInt, randomInt+1);

       }
     
vars.put("RanDomCookie",randomSting);


Below is Output :

POST data:
{
"http_session_id":"qoxbkopzsendueghuivujhlyljystsik",
"Name":"APP"
}




2: Using JMeter "__RandomString()"

Below are the Steps:

1. Add Http Sampler and add __RandomString() as shown below


{
"http_session_id":"${__RandomString(32,abcdefghijklmnopqrstvuwxyz,0123456789)}",
"Name":"APP"
}

Explanation about RandomString():

Syntax:__RandomString(Perm1, Perm2 ,Perm3 )
Perm1: Length of the String , In my case , needed 32 character . So I passed "32", in about post method.

Perm2: Which values , server accepts, In my case lower case alphabets and numerics.

Perm3:  Name of variable in which to store the result ,Optional parameter (In my case),


Tuesday, September 23, 2014

JMeter file read methods

We can read a file in different way using JMeter, below are they

   1. FileReader.

            i. Char bu char.
           ii. Line by line.   
   2. FileInputStream.
           i. Char bu char.
          ii. Line by line.



















Below is the performance of the "File Reader" vs "File Input Stream". 





If we observe the results , File Reader is Faster when compared to "File Input Stream". So while using these two methodologies in your script , choose which one is good.
Note: In the script , I am reading single character at once.

File Reader: If we want to read file as a character/characters , we can opt "FileReader" class. User bean shell sampler/Bean shell post processor/Bean shell pre processor  to test this in your Jmeter

   We can read the file in two ways,
            1. char by char 
            2. line by line.

File Input Stream: If we want to read file as a stream/Streams , we can opt "File input Stream" class. User bean shell sampler/Bean shell post processor/Bean shell pre processor  to test this in your Jmeter

   We can read the file in two ways,

            1. char by char 
            2. line by line.

Below is the code
  1. File Reader - Read Char by char :
Java Version:
import java.io.FileReader;
import java.io.IOException;
public static void main(String[] args) throws IOException {
System.out.println("Method 1");

FileReader fileReader=new FileReader("C:/Work/java_practice/IODemo/src/madhu.txt");
int i =fileReader.read();
while(i!=-1){
System.out.print((char)i);
i=fileReader.read();
}

Jmeter Version:


import java.io.FileReader;
FileReader fileReader=new FileReader("C:/Work/java_practice/IODemo/src/madhu.txt");
   int i =fileReader.read();
   while(i!=-1){
    System.out.print((char)i);
    i=fileReader.read();
   }

2. File Reader - Read line by line:

Java Version:


import java.io.FileReader;

import java.io.IOException;
public static void main(String[] args) throws IOException {
FileReader fileReader1=new FileReader("C:/Work/java_practice/IODemo/src/madhu.txt"); BufferedReader bufferReader= new BufferedReader(fileReader1); String line=bufferReader.readLine();
 while(line!=null){
 System.out.println(line);
 line=bufferReader.readLine(); 
 }
 fileReader.close(); 
 bufferReader.close();
}

Jmeter Version:


import java.io.FileReader;
FileReader fileReader1=new FileReader("C:/Work/java_practice/IODemo/src/madhu.txt");
   BufferedReader bufferReader= new BufferedReader(fileReader1);
   String line=bufferReader.readLine();
   while(line!=null){
    System.out.println(line);
     line=bufferReader.readLine();
   }
   fileReader.close();

   bufferReader.close();

3. File Input Stream- Read Char by char :

Java Version:

import java.io.IOException;
import java.io.FileInputStream;
public static void main(String[] args) throws IOException {
FileInputStream fileInputStream=new FileInputStream("C:/Work/java_practice/IODemo/src/madhu.txt");
int j=fileInputStream.read();
while (j!=-1){
System.out.print((char)j);
j=fileInputStream.read();
}
fileInputStream.close();
}

Jmeter Version:

import java.io.FileInputStream;
System.out.println("Method 2");
FileInputStream fileInputStream=new FileInputStream("C:/Work/java_practice/IODemo/src/madhu.txt");
int j=fileInputStream.read();
while (j!=-1){
System.out.print((char)j);
j=fileInputStream.read();
}
fileInputStream.close();


4. File Input Stream -Read line by line:

Java Version:


import java.io.IOException;

import java.io.FileInputStream;
import java.io.InputStreamReader;
public static void main(String[] args) throws IOException {
FileInputStream in = new FileInputStream("C:/Work/java_practice/IODemo/src/madhu.txt");
 InputStreamReader inr=new InputStreamReader(in);//An InputStreamReader is a bridge from byte streams to character streams
 BufferedReader br = new BufferedReader(inr);
 String line1=br.readLine();
 while(line1!= null)
 {
  System.out.println(line1);
 }
 inr.close(); 
 in.close();
   }

Jmeter Version:


  FileInputStream in = new FileInputStream("C:/Work/java_practice/IODemo/src/madhu.txt");

 InputStreamReader inr=new InputStreamReader(in);//An InputStreamReader is a bridge from byte streams to character streams
 BufferedReader br = new BufferedReader(inr);
 String line1=br.readLine();
 while(line1!= null)
 {
  System.out.println(line1);
      line1=br.readLine();
 }
 inr.close(); 

 in.close();


Saturday, September 6, 2014

Base64 encode using Jmeter


In my application, we want to encode one of the jmeter varible to base64 variable  . We did this using using Bean shell pre processor. Below is the scenario


Scenario: I want to encode jmeter variable (session)  to Base64 and need to pass this value to Jmeter Sampler. Below is the steps to do this 

Download this project from GitHub

Step 1: Get dynamic session value using Regular expression extractor.
Add Thread Group to Test Plan and Add the sampler to Thread Group  , provide the necessary details to Http Sampler

IP:raw.githubusercontent.com
Port: 80
Path:/mcheepati/api/master/homepage
Method: Get


Step 2: Add the Regular expression extractor post processor as a child to Http Sampler. And add the below values to "Regular expression extractor" 



Step 3:Pass the encoded Base64 value(session) as a variable to http post method in this step.
Add the Http sampler as a child to Thread group 

 

Add the bean shell "pre Processor" as a child to this Http sampler and the below code to bean shell processor 



import org.apache.commons.codec.binary.Base64;

String emailIs= vars.get("email");

byte[] encryptedUid = Base64.encodeBase64(emailIs.getBytes());
      vars.put("genStringValue",new String(encryptedUid));

Note: We added Pre Processor as child, because  pre processor will executes before running the Http sampler.


Step 4:Save and run the Jmeter script and verify the post call values for Base64 encoded value.
Actual Value is              :jdwqoeendwqqm12sdw
Base64 encoded value is:amR3cW9lZW5kd3FxbTEyc2R3




Validate the jmeter Base64 response values from online Base64 http://www.base64encode.org/