Vars.get returns a null value - groovy

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}

Related

Unable to fetch only values from a List in Groovy with Jmeter script

In groovy, I am getting below output in List. I am using Jmeter JSR223 Post processor for the script. My List print below data in result.
def a = [{Zip=36448, CountryID=2}]
I want to fetch only values (36448 and 2) from this List and not Key. How Can I do that?
For simple single instance fetch do this:
def zip = a.first().Zip
def countryId = a.first().CountryID
Seems pretty straight forward if those are only known values that you want.
If you want all Zips and CountryIDs then you can do this:
def zips = a*.Zip
def countryIds = a*.CountryID
That will return 2 Lists one with all the Zips, and one with all the CountryIDs using the spread operator.
I don't know what is the data structure is inside your list your code is not a valid Groovy code.
For Map it would be something like:
a[0].collect {it -> it.value}
More information on Groovy scripting in JMeter: Apache Groovy - Why and How You Should Use It

Jmeter - groovy function not working as expected

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

Groovy script to validate ResponseData in JMeter

I have written this script to verify field types, but i'm not sure if it is being validated correctly. Also i want to verify all the expected fields are seen.
This is my BSF Assertion:
import groovy.json.*;
def response = prev.getResponseDataAsString();
def json = new JsonSlurper().parseText(response)
def eventName = json.event_name
(eventName.getClass() == String)
def eventDate = json.event_start
(eventDate.getClass() == Date)
def attendeeLimit = json.attendee_limit
(attendeeLimit.getClass() == Integer)
def orderCount = json.order_count
(orderCount.getClass() == Integer)
def attendanceLimit = json.attendance_limit_on
(attendanceLimit.getClass() == String)
If you want to check JSON response data types change your lines like
(eventName.getClass() == String)
to
assert eventName instanceof String
See Groovy Testing Guide for details
I would suggest switching fro BSF Assertion to JSR223 Assertion as it is able to compile the script and cache hence your script will perform much better. See Beanshell vs JSR223 vs Java JMeter Scripting: The Performance-Off You've Been Waiting For! article for comprehensive explanation and scripting best practices.
There is also a JSON Path Assertion available via JMeter Plugins, this one is mainly used to check response content

Calling groovy method from script

I'm writing a program in groovy, I want it to run a script with dynamically changing variables. The script is supposed to execute a method with its variables. This method is located in the program that runs the script.
The script would contain something like this:
// getAttribute is a method in my main program, the program which also runs the script
value = getValue("java.lang:type=OperatingSystem", "FreePhysicalMemorySize")
// do something with the value
if (value > 9000) { output = "ERROR" }
// the same thing maybe a few more times
value = getValue(...
I want to keep it as simple as possible.
I was working with these examples: http://groovy.codehaus.org/Embedding+Groovy
I already tried to use the GroovyScriptEngine, but it seems like the script only accepts Strings as input values. It would be great if I could hand over method pointers.
Just trying to hand over an integer like this:
def roots = 'PATH\\script.groovy'
def groscreng = new GroovyScriptEngine(roots)
def binding = new Binding()
def input = 42
binding.setVariable("input", input)
groscreng.run("script.groovy", binding)
println binding.getVariable("output")
With this script.groovy
output = ${input}
results in this error:
Caught: groovy.lang.MissingMethodException: No signature of method: script.$() is applicable for argument types: (script$_run_closure1) values: [script$_run_closure1#fcf50]
Possible solutions: is(java.lang.Object), run(), run(), any(), any(groovy.lang.Closure), use([Ljava.lang.Object;)
Receiving the value in the script as a String like "${input}" works just fine.
I know it has to work somehow and I would appreciate any help or other suggestions!
output = ${input}
isn't valid groovy
Try:
output = input

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