Jmeter - groovy function not working as expected - groovy

I have a groovy function which performs some date operations. i.e. Returns a date 12 months forward. This date is encoded and stored into a variable.
snippet:
${__groovy(import groovy.time.TimeCategory; def now = new Date(); use(TimeCategory) { def nowPlusOneYear = now + 12.month - 1.day; return URLEncoder.encode(nowPlusOneYear.format('dd/MM/YYYY')\, 'UTF-8')},Policy_ExpiryDate)}
The above code works well with a JSR223 Sampler. Also, the variable name and its value gets displayed in debug sampler.
But, when I use this code along with a GET HTTP Request. The value doesn't gets substituted.
the request:
/IIMS/target/source/UNDERWRITING/ValidatorAction.action?dataString=%7B%22Testing%22%3A%22F%22%2C%22VCURRENTSTATUSNAME%22%3A%22%22%2C%22Entry%20Date%22%3A%22${__urlencode(${__time(dd/MM/YYYY,Entry_Date)})}%22%2C%22Policy%20Type%22%3A%22FLEET%22%2C%22Policy%20Inception%20Date%22%3A%22${__urlencode(${__time(dd/MM/YYYY,Policy_InceptionDate)})}%22%2C%22Policy%20Inception%20Time%22%3A%22${__urlencode(${__time(HH:mm:ss,Policy_InceptionTime)})}%22%2C%22Policy%20Duration%22%3A%2212%22%2C%22Unit%22%3A%22F%22%2C%22Policy%20Expiry%20Date%22%3A%22${__groovy(import groovy.time.TimeCategory; def now = new Date(); use(TimeCategory) { def nowPlusOneYear = now + 12.month - 1.day; return URLEncoder.encode(nowPlusOneYear.format('dd/MM/YYYY')\, 'UTF-8')},Policy_ExpiryDate)}%22%2C%22Policy%20Expiry%20Time%22%3A%2223%3A59%3A59%22%2C%22Type%20Of%20Business%22%3A%22CASH%22%2C%22Payment%20Frequency%22%3A%22B%22%2C%22Country%22%3A%22UAE%22%2C%22Source%20of%20Business%22%3A%220DIR%22%2C%22Policy%20branch%22%3A%22${UserDetails_g5}%22%2C%22UMR%20Number%22%3A%22%22%2C%22Equator%20Policy%22%3A%22N%22%2C%22Policy%20holder%22%3A%22${PolicyHolderDetails_g1}%22%2C%22Policy%20holderNew%22%3A%22${PolicyHolderDetails_g2}%22%2C%22SEC-POLPLANNumber%20of%20Vehicles%20in%20Fleet%22%3A%220%22%2C%22SEC-POLPLANPolicy%20Plan%22%3A%22NA%22%2C%22SEC-POLPLANDistribution%20Channel%22%3A%22DIROIC%22%2C%22SEC-POLPLANName%20of%20the%20Scheme%22%3A%22NA%22%2C%22SEC-PLRIDPolicy%20Level%20FAC%20R%2FI%22%3A%22N%22%2C%22SEC-PLRIDPolicy%20Level%20FAC%20R%2FI%20percentage%22%3A%220%22%2C%22SEC-PLRIDPolicy%20Level%20Proportional%20FAC%20R%2FI%20percentage%22%3A%220%22%2C%22SEC-PLRIDPolicy%20Level%20Non%20Proportional%20FAC%20R%2FI%20percentage%22%3A%220%22%2C%22SEC-PLRIDProp%20Non%20Prop%20FAC%20Date%22%3A%22Y%22%2C%22SEC-CEDANTNumber%20of%20Cedants%20Involved%22%3A%22%22%2C%22SEC-CEDANTCedant%20Country%22%3A%22%22%2C%22SEC-MDPMinimum%20Deposit%20Premium%20Applicable%22%3A%22N%22%2C%22SEC-MDPMinimum%20Deposit%20Premium%20Type%22%3A%22%22%2C%22SEC-MDPPercentage%20of%20Premium%22%3A%22%22%2C%22SEC-MDPMinimum%20Deposit%20Premium%22%3A%22%22%2C%22SEC-MDPMinimum%20premium%22%3A%22%22%2C%22SEC-CRMCRM%20Reference%20Number%22%3A%22${__Random(1111111,9999999,CRM_RefNo)}%22%2C%22pBusinessTranCode%22%3A%22SCR-BSCDTL%22%2C%22pSaveContinueIndicator%22%3A%22%22%2C%22pJSPName%22%3A%22BasicInformation.jsp%22%2C%22crtPartyFunctionInd%22%3A%22Y%22%2C%22strTOC%22%3A%22%22%2C%22existingPartyIndicator%22%3A%22Y%22%2C%22disabledSectionCode%22%3A%22%22%2C%22scriptaculous%22%3A%22%22%2C%22language%22%3A%22null%22%2C%22policyId%22%3A%22null%22%2C%22policyPlanUpgradation%22%3A%22N%22%2C%22reason%22%3A%22%22%2C%22isMasterQuote%22%3A%22FALSE%22%2C%22USERCODE%22%3A%22${UserDetails_g6}%22%2C%22pVersionDate%22%3A%22%22%2C%22__endorsementType%22%3A%22null%22%2C%22cSystemDate%22%3A%22${__urlencode(${__time(dd/MM/YYYY,cSystemDate)})}%22%2C%22cedantEndrDate%22%3A%2208%2F12%2F2117%22%2C%22CIMS_CSRFTOKEN%22%3A%22${CIMS_CSRFTOKEN}%22%7D%3B&productCode=0101&productId=1030885614052014
All values get substituted properly except for the groovy part. Am I missing something over here. The debug sampler doesn't shows a variable named Policy_ExpiryDate.

I cannot reproduce your issue, __groovy() function is normally getting evaluated and the substituted by its respective value:
If it doesn't for you - most probably it fails somewhere somehow, check jmeter.log file for any suspicious entries
Also you can execute the function anywhere else, for example in User Defined Variables configuration element and refer the value where required just as ${Policy_ExpiryDate}

__groovy() works well with Jmeter 5.4. But this function is not recognized in Jmeter 5.3.
Thanks a lot for your help #Dmitri T
Regards,
Ajith

Related

How to pass a random parameter to the response in SOAPUI, which would change every n calls

I am new in soapui. I make logic for a service stub and I meet a problem.
I have a simple service stub that returns a parameter with a random number (it is randomized in the answer in groovy language), but the problem is that this number is used 2 times per session and cannot be changed, otherwise the session will fail. How would I pass a random number to the next response and then start randomizing again and so on?
I could not find anything similar to my case on the Internet, so I ask the question here. Is it even possible to implement this in soapui, for example through TestSuite and groove scripts?
Groovy code I use in response script to generate random number:
requestContext.actreq = (10000000 + Math.abs(new Random().nextInt() % 9999999));
Then I substitute ${actreq} in the response
If the number 100001 is generated, then I would like to pass it to the next two response. In order for Random to work every 2 iterations.
you could try this aproach
class Glob{
static long callCount=0
static long randValue=0
static long rand(){
callCount ++
if(callCount % 2 == 1){
randValue = (10000000 + Math.abs(new Random().nextInt() % 9999999))
}
return randValue
}
}
requestContext.actreq = Glob.rand()
or official way like this:
https://www.soapui.org/docs/functional-testing/working-with-scripts/
use setup script to assign context variables
in script you could access those variables like i did in code above to increment call-count and re-calculate random if needed...

Vars.get returns a null value

def signValue = '${signature_value}.${timestamp}.${signature_value}'
def token_secret = '${APP_CLIENT_SECRET}'
log.info("token is " + signValue)
def signingKey = new javax.crypto.spec.SecretKeySpec(signValue.getBytes(),"HmacSHA256");
def mac = javax.crypto.Mac.getInstance("HmacSHA256")
mac.init(signingKey);
def hmac = mac.doFinal(token_secret.getBytes());
def result = hmac.encodeBase64().toString()
---- I want to use the above "result" variable into a Http sampler request body------
---- I tried many possible ways but I end up is getting value as null or some error--
//${__groovy(vars.get("result"))}
//vars.put("signature", vars.get(result))
I've been trying to extract the value of the variable "result" and use it in HTTP sampler results. But I ended up getting a null value or some other error. Anyone could help me to sort out this problem.
Thanks!
I don't get the point, result should be a String object, is it not what you are expecting to have?
Anyway, signValue and token_secret perhaps could be different from your expectations: using single quotes instead of double quotes you are not using GStrings (e.g. the value of token_secret will be always exactly '${APP_CLIENT_SECRET}', regardless of the value of APP_CLIENT_SECRET)
Change this line:
vars.put("signature", vars.get(result))
to this:
vars.put("signature", result)
Also don't inline JMeter variables into Groovy scripts like this:
def token_secret = '${APP_CLIENT_SECRET}'
use vars shorthand instead:
def token_secret = vars.get('APP_CLIENT_SECRET')
Because:
It conflicts with Groovy GStrings
For best performance it's recommended to cache compiled scripts (enabled by default)
and in this mode JMeter resolves only first value and caches it which means you will get the same value for every iteration
More information:
JSR223 Sampler Documentation
Apache Groovy - Why and How You Should Use It
Put vars the result:
vars.put("signature", hmac.encodeBase64().toString());
And in HTTP use ${signature}

SoapUI & Groovy - How to get properties from different TestCases using Run testCase

Sorry in advance. I am sure this is not a new question but I swear I've been looking for days and have tried several solutions but no one fits exactly what I need. I hope you guys can help me...
My problem:
I have a main script which sends bash commands to our server:
TestSuite: Tools;
TestCase: sendBashCommands;
TestStep: groovycript;
This test script is called by several test cases using "Run testCase". Each test case have a different bash command:
TestSuite: ServerInfo
TestCase: getServerVersion
Property: BashCommand="cat smt | grep Version"
TestStep: Run sendBashCommands
TestCase: getServerMessage
Property: BashCommand="cat smt | grep Message"
TestStep: Run sendBashCommands
...
On my sendBashCommands.groovyScript I have already tried the following:
//def bashCmd= context.expand( '${#BashCommand}' );
//it returns empty;
//def bashCmd= testRunner.testCase.getPropertyValue( "BashCommand" );
//it returns null;
//def bashCmd= context.getTestCase().getPropertyValue( "BashCommand" );
//it returns null;
def bashCmd = context.expand('${#TestCase#BashCommand}');
//it also returns empty;
Currently I use a solution which works with project properties but what I actually need is working with these properties on the level of the test case which is calling the sendBashCommand script. Is that possible? How could I do it?
I think you are doing it for maintenance purpose...
As per your approach, the result has to come as null or empty. Because your groovyscript cannot get the properties of other testcases directly. If you call a getProperty() Method directly, then it will refer to the current testStep's property. So the following approach could help you.
put the following code in your individual test cases, "getServerVersion" etc.
def currentProject = testRunner.testCase.testSuite.project
// the following is to store the names of the test suite and the test cases from which you want to call your main script
currentProject.setPropertyValue("TestSuiteName",testRunner.testCase.getTestSuite().getLabel().toString())
currentProject.setPropertyValue("TestCaseName", testRunner.getTestCase().getLabel().toString())
// call sendBashCommands here -> run sendBashCommands
put this code in your main groovy script (sendBashCommands.groovyscript)
def currentProject = testRunner.testCase.testSuite.project
def callingTestCase = currentProject.testSuites[currentProject.getPropertyValue("TestSuiteName")].testCases[currentProject.getPropertyValue("TestCaseName")]
def bashCmd = callingTestCase.getPropertyValue( "BashCommand" )
// to verify
log.info bashCmd
The project is common to all the test suites, so you have to use project property in any case, i.e., for your requirement :)
Enjoy :)

Property transfer in SOAPUI using groovy script

Hi i am new to soapui and have this situation.I have two service memberservice1 where the response has "Region" property.I need to check this property and see if its value is "SCR" i need to modify it to "SCA" and pass it to another WS memberservice2.
I tried this way but couldnt get it.Can anyone please suggest.
def smlholder = groovyUtils.getXMLholder("Webservice#request");
def node = smlholder.getnodevalue("//region");
if(node == 'SCA')
testRunner.testcase.testSteps("anotherwebservicename").setProperty('Region','SCR');
Your example code does not match you statement. Below I will follow your statement, and ignore the broken code example.
There are several different ways this cane be done. The easiest would probably be:
def region = context.expand("${Webservice#Response#//*:region}")
if (region == "SCR")
testRunner.testCase.testSteps["anotherwebservicename"].setProperty("Region", "SCA");
else
testRunner.testCase.testSteps["anotherwebservicename"].setProperty("Region", region);

groovy returning different node count

I am trying to get the count of result nodes in soapUI using groovy and the below code gave me the correct count
def groovyUtils = new com.eviware.soapui.support.GroovyUtils(context)
def holder = groovyUtils.getXmlHolder("StepName#ResponseAsXml")
def cnt = holder["count(//Results/ResultSet/Row)"]
but when i tried the below i got a count of 1. How are the two different?
def cnt = holder["count('//Results/ResultSet/Row')"]
Though I've never used SoapUI, in the second one, you are passing a String (wrapped in '...') to count.
The first passes a path which I guess gets evaluated into a list of nodes.
All the examples I can find do not wrap the path in a String, so my guess is the first example is the way to do it ;-)
EDIT
Refer Tips and Tricks for most of the SoapUI and Groovy related questions. And count in xpath.

Resources