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),