Capture time difference between values of two regular expression reference names in Jmeter - jmeter

I defined regular expressions in my JMeter test plan and I'm able to capture the values in simple variables in user.variables. But I'm trying to calculate the time difference between two variables as follows in Beanshell post processor and I'm not getting any result in my report.
import javax.xml.bind.DatatypeConverter;
vars.put("old_date_submitted", "submittedDate"); // submittedDate, succeeddedDate and runningDates are regular expr. reference names
vars.put("old_date_succeeded", "succeededDate");
vars.put("old_date_running", "runningDate");
Calendar cal_s = DatatypeConverter.parseDateTime(vars.get("old_date_submitted"));
Calendar cal_c = DatatypeConverter.parseDateTime(vars.get("old_date_succeeded"));
Calendar cal_r = DatatypeConverter.parseDateTime(vars.get("old_date_running"));
Date new_date1 = cal_s.getTime(); // submitted Time
Date new_date2 = cal_c.getTime(); // succeeded Time
Date new_date3 = cal_r.getTime(); // running Time
long new_date1_ms = new_date1.getTime(); // submitted Time
long new_date2_ms = new_date2.getTime();
long new_date3_ms = new_date3.getTime();
log.info("Date in milliseconds: " + new_date1_ms);
long delta1 = new_date2_ms - new_date1_ms; //calculate the difference (succeededDate - submittedDate)
long delta2 = new_date3_ms - new_date1_ms; //calculate the difference (runningDate - submittedDate)
vars.put("delta1", String.valueOf("delta1")); // store the result into a JMeter Variable
vars.put("delta2", String.valueOf("delta2")); // store the result into a JMeter Variable

This bit:
vars.put("old_date_submitted", "submittedDate"); // submittedDate, succeeddedDate and runningDates are regular expr. reference names
vars.put("old_date_succeeded", "succeededDate");
vars.put("old_date_running", "runningDate");
seems odd to me. Given:
submittedDate, succeeddedDate and runningDates are regular expr. reference names
My expectation is that you should be using JMeter Variables instead of hardcoded strings there, so you should change your code to look like:
vars.put("old_date_submitted", vars.get("submittedDate")); // submittedDate, succeeddedDate and runningDates are regular expr. reference names
vars.put("old_date_succeeded", vars.get("succeededDate"));
vars.put("old_date_running", vars.get("runningDate"));
So most likely your code is failing at DatatypeConverter.parseDateTime.
Next time you face any problem with your Beanshell scripts consider the following troubleshooting techniques:
Check jmeter.log file - in case of Beanshell script failure the error will be printed there
Add debug(); directive to the very beginning of your Beanshell script - it will trigger debugging output to stdout
Put your Beanshell code in try/catch block like:
try {
//your code here
}
catch (Throwable ex) {
log.error("Something went wrong", ex);
throw ex;
}
This way you get more "human-friendly" stacktrace printed to jmeter.log file.
See How to Use BeanShell: JMeter's Favorite Built-in Component guide for more information on using Beanshell in JMeter tests.

Related

How to return a value from database in jmeter

I am trying to return a value from MSSQL server database and storing it in a variable inside JSR223 timer script in Jmeter. However I am getting the following error in log -
**WARN o.a.j.t.JSR223Timer: Script did not return a value
**
This is the code which i have written in the script -
try {
def promoName = ${promotionName}; //extracted the value using JSONExtractor
log.info("Promotion Name is " + promoName); //not displaying in the log
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
Connection con = DriverManager.getConnection("jdbc:sqlserver://ServerIP;databaseName="";integratedSecurity=true","<userId>","<password>");
String query ="select query";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
vars.put("promotionInstanceId", rs.getString(1)); //The query returns an instanceId which i need to store in a variable and use it later
log.info("Promotion Instance is " + ${promotionInstanceId});
}
conn.close();
}
catch (Exception e) {
e.printStackTrace();
Can anyone help me in understanding where i might have gone wrong ?
Any reason to use the timer? The warning you're getting is about missing return keyword as the JSR223 Timer is intended to be used for calculation of virtual user think time therefore it should return the value to "sleep" in milliseconds. Given you don't want to introduce the think time it makes sense to go for JSR223 PostProcessor instead.
Don't inline JMeter functions or variables into the scripts as it might cause script misbehavior due to clashing with GString template or the variable will be cached and the same value will be returned for the subsequent calls.
It is recommended to use JMeter's built-in components and avoid scripting where possible, you can use i.e. JDBC PostProcessor in order to extract the interesting value(s) and store it(them) into JMeter Variables. Check out Debugging JDBC Sampler Results in JMeter article to learn how to execute SQL statements and work with results
You should use vars.get to get variable value
vars.put("promotionInstanceId", rs.getString(1)); //The query returns an instanceId which i need to store in a variable and use it later
log.info("Promotion Instance is " + vars.get("promotionInstanceId"));

Cann't execute my test if I add __intSum function to the beanshell postprocessor

I have written a regular expression (regexpname) in my thread which returns a number Ex: 10 and when I try to use the regular expression in the BeanShell postprocessor by adding __intSum function to add a number to the regular expression out put Ex: to add 4 to the regular expression out put i.e., 10 and store the result to a variable Ex: Total, using the following function:
{__intSum(4,${regexpname},Total}
upon trying to run my test, it stops immediately with the message
"Jmeter: Uncaught exception: java.lang.NumberFormatException: For
input string: "${regexpname}".....".
Please let me know how to fix the issue:
Here is the code I have put in beanshell postprocessor:
import java.text.SimpleDateFormat;
SimpleDateFormat sdf = new SimpleDateFormat("m/dd/yyyy"); // change it according to your Date format
Date originalDate = sdf.parse(vars.get("SigDate"));
Calendar cal = Calendar.getInstance();
cal.setTime(originalDate);
${__intSum(4,${regexpname},Total)};
cal.add(Calendar.DAY_OF_YEAR, Total); // change it if you need to add something else
Date newDate = cal.getTime();
vars.put("newDepdate", sdf.format(newDate));
log.info("Original date: " + vars.get("SigDate"));
log.info("New date: " + vars.get("newDepdate"));
Don't inline JMeter Functions and/or variables into scripts as they can resolve into something which will cause script failure or inconsistent behaviour. Either use "Parameters" section or go for code-based equivalents
Don't use Beanshell test elements, it is recommended to switch to JSR223 Test Elements and Groovy language for any form of scripting since JMeter 3.1
Your date format looks flaky as m stands for "minutes in hour", if you need "month in year" - go for capital M
Actually you don't even need any scripting here as there is __timeShift() function since JMeter 3.2 which can do what you need, the relevant syntax would be something like:
Use int Total = Integer.parseInt(vars.get("regexpname"))+4; instead of ${__intSum(4,${regexpname},Total)}; in your beanshell pre processor
I have defined regexpname as 10 in test plan so its adding 14 days and storing new date in newDepdate.
For more information on beanshell please follow this link
Please let me know if it helps..

${__time} function output is incorrect

I'm trying to get today's date using time function of jmeter with the format "${__time(yyyy-MM-dd)}" in BeanShell postprocessor. But after executing the Beanshell postprocessor the result shows as "1996". Basically the "time" function is displaying result by subtracting the values like "2018-03-19"=1996.
Please help me to resolve this issue so that i can get current date and time.
Beanshell code as below
import org.apache.jmeter.gui.GuiPackage;
import org.apache.commons.io.FilenameUtils;
String testPlanFile = GuiPackage.getInstance().getTestPlanFile();
String testPlanFileDir = FilenameUtils.getFullPathNoEndSeparator(testPlanFile);
vars.put("testPlanFileDir", testPlanFileDir);
//create the file in test plan file dir and print current time and Date
FileOutputStream f = new FileOutputStream(testPlanFileDir+"/CurrentDate.txt", true);
PrintStream p = new PrintStream(f);
this.interpreter.setOut(p);
//current date and time;
print("Current date is:"+${__time(yyyy-MM-dd)});
f.close();
Set time function call as parameter of your PreProcessor (by the way migrate to JSR223 + Groovy for performances)
And use it then with variable Parameters:
Try this with JSR223 PostProcessor and language Groovy and put this into script area:
def a = new Date().format('yyyy-MM-dd')
new File('Example.txt').withWriter('utf-8') {
writer -> writer.writeLine 'Current date is : ' + a.toString() }
(It works on JMeter 4.0)
You should move to JSR223 postprocessor according to JMeter Best Practices:
Since JMeter 3.1, we advise switching from BeanShell to JSR223 Test Elements
Until then you can fix it by quoting the function call as
print("Current date is:"+"${__time(yyyy-MM-dd)})";
This fix will treat the function's return value as string.
Currenty it treat it as a numeric substraction: 2018-3-19=1996 and then convert it to string
Performance anti-pattern #1: given you use GuiPackage class you won't be able to execute your test in non-GUI mode, consider migrating to FileServer instead
Performance anti-pattern #2: using Beanshell is not recommended as in case of high loads it might become the bottleneck. Since JMeter 3.1 it is recommended to use JSR223 Test Elements and Groovy language for any form of scripting
Performance anti-pattern #3: don't inline JMeter Variables or Functions in script body they break Groovy compiled scripts caching function and might resolve into something which will cause unexpected behaviour (like in your case), compilation failure or even data loss.
So:
Add JSR223 PostProcessor instead of the Beanshell one
Put the following code into "Script" area:
String testPlanDir = org.apache.jmeter.services.FileServer.getFileServer().getBaseDir()
File currentDate = new File(testPlanDir + File.separator + "CurrentDate.txt")
currentDate << new Date().format("yyyy-MM-dd")

Jmeter: Comparison of multiple result for result response with JDBC variables

In j meter: In a bean-shell assertion or any other I want to match the content of response which I have fetched using Jason extractor suppose:
Result[1]=A, Result[2]=b, Result[3]=c
and so on Versus variables I have fetched using JDBC pre-processor which has saved as:
Result_1=, Result_2=B, Result_3=c.
I am able to match 1 variable at a time but not all at one time. so need help with bean-shell code to compare all result at once.
Add JSR223 Assertion somewhere to your test plan (normally as a child of a Sampler you would like to fail)
Put the following code into "Script" area
for (int i = 1; i <= Integer.parseInt(vars.get('ResultFromJSON_matchNr')); i++) {
if (!vars.get('ResultFromJSON' + i).equals(vars.get('ResultFromJDBC_' + i))) {
AssertionResult.setFailure(true)
AssertionResult.setFailureMessage('Variables mismatch')
}
}
Make sure you have groovy selected as the "Language" and have Cache compiled script if available box ticked
The above script assumes ResultFromJSON and ResultFromJDBC JMeter Variables reference names, amend them according to your real definitions.
More information: Scripting JMeter Assertions in Groovy - A Tutorial

JMeter Regular Expression Extractor I am not getting the value out of a variable from the url

In Jmeter I am trying to get a value out of a variable from the url using the Regular Expression Extractor. I am also using the BeanShell Sampler to get the value out of the variable and print it out to the log file. I can then see in the log file what value I am getting.
I don't think my Regular Expression Extractor setting is correct I am getting the following error from my BeanShell Script:
Response code: 500
Response message: org.apache.jorphan.util.JMeterException: Error invoking bsh method: eval In file: inline evaluation of: ``String session_ID = vars.get("sessionID"); log.info("session_ID = " + session_I . . . '' Encountered "vars" at line 4, column 1.
An example URL I have is:
http://localhost:8080/test1/gp/gw/ajax/desktop/herotator/record-impressions.html?ie=UTF8&aPTID=16001&cmpnId=205103067&cnttId=1&h=1A52D1&pIdent=desktop&rId=0DA6FXQ35E8JDNVES8C59&sid=14&slotName=PS4-some-testdata
I would like to get the value from the variable PTID and output it to the log file. I can then use the value in other Http requests when i need to.
My BeanShell Sampler script is:
String session_ID = vars.get("sessionID");
log.info("session_ID = " + session_ID)
vars.put("sessionID", session_ID);
My Regular Expression Extractor is:
Field to check = URL is ticked
Reference Name = sessionID
Regular Expression = PTID="(.+?)"
Template = $1$
Match No. (0 for Random): 1
Default value = session id not found
My Test Plan set up is as follows:
Test Plan
--Thread Group
----Http Request Default
----Http Header Manager
----Recording Controller
------Http Request
------Regular Expression Extractor
------BeanShell Sampler
------more Http Requests
----Access Log Sampler
----View Results Tree
Also nothing is being written to the log file when i run the script.
Access Log Sampler the log file location is to:
E:\RL Fusion\projects\JMeter\apache-jmeter-2.13\jmeter.log
In the View Results Tree for the Http Request I can see there is a PTID value in the Response data Tab.
My regular expression extractor is not getting this value out.
I am new to JMeter, If i have anything in the wrong order please do let me know.
Thanks,
Riaz
My expectation is that something is wrong with your Beanshell script. Most likely you're missing a semicolon at the end of statement on 3rd line.
To get to the bottom of a problem in Beanshell script you can use the following approaches:
Add debug(); directive to your Beanshell script (make it first line). It will trigger debug output to console window where you launched JMeter from
Put your Beanshell code into "try" block like:
try {
// your code here
}
catch (Throwable ex) {
log.error("Problem in Beanshell", ex);
throw ex;
}
See How to Use BeanShell: JMeter's Favorite Built-in Component article for more information on Beanshell scripting in JMeter.

Resources