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

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

Related

JMeter : Using the JSON Postprocessor _ALL variable in one more postprocessor to fetch the data

I'm having a JSON data, from which I'm able to fetch some data from JSON Extractor post-processor.
And the data looks something like this,
group_1 = ["Scooter"]
group_2 = ["Bus","Jeep","Car"]
group_ALL = ["Scooter"],["Bus","Jeep","Car"]
group_matchNr = 2
So I want to fetch all this data (or accumulate) in only one array variable,
Example : groups=["Scooter","Bus","Jeep","Car"]
so that I loop it through all the individual data in the api calls in a foreach loop.
example api call in foreach loop: https://vehicles.com/${groups}
My question is, I'm trying to write the groovy script to get all the data in groups variable. But unable to. I need your help in this and to configure the foreach controller also.
Groovy Script I tried in JSR223 Postprocessor which did not work:
import groovy.json.JsonSlurper;
groups= vars.get("group_ALL");
def jsonSlurper = new JsonSlurper();
jsonData = JSON.stringify(vars.get("groups"))
String tempRemoveBr = jsonData.replaceAll("[","");
String tempRemoveBr1 = tempRemoveBr.replaceAll("]","");
String[] arrVehicles = tempRemoveBr1.split(",")
for (int i=0;i<arrVehicles.size();i++)
{
log.info("arrVehicles[i]")
}
vars.put("arrVehicles",arrVehicles)
foreach controller configured as :
Input variable : arrVehicles
start index : 0
output variable name : vehicleN
Most probably you could achieve it using JSON JMESPath Extractor, however I cannot come up with a proper configuration without seeing your full response.
If you want to process existing variables here is a Groovy script you could use:
def group1 = new groovy.json.JsonSlurper().parseText(vars.get('group_1'))
def group2 = new groovy.json.JsonSlurper().parseText(vars.get('group_2'))
def arrVehicles = group1 + group2
vars.put('arrVehicles', new groovy.json.JsonBuilder(arrVehicles).toString())
More information:
Apache Groovy - Parsing and Producing JSON
Apache Groovy: What Is Groovy Used For?

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}

How to send array of ids (stored in csv) in jmeter post request

I have getuserdetails api where I need to send purchased item in array
API: api/getuserdetails/${id}
Method: post
body: {"uname":{
"purchaseitem": ["121","11","4","12345"]
}
}
In jmeter setup looks like
>>TP_1
>>CSVDataSet_ids
>>CSVDataSet_purchaseitem
>> ThreadGroup1
>>HTTP Req
>>JSR223 PreProcessor
>>View result tree
purchaseitem csv has values like
1231
12121
312232
13
1
42435
133
I want to pass "purchaseitem" array values fetched from CSV in comma separated manner as shown in body
I've tried something like this in JSR223 PreProcessor
def list = ${purchaseitem}
for (i=0;i<=list.size()-1;i=i+10)
{
def mylist = list.subList(i,i+10);
props.put ("mylist"+i,mylist)
}
Can someone please help? Or is there any function to solve this simple problem?
You're doing something weird
You won't be able to use CSV Data Set Config because it reads the next value with next virtual user/iteration
Your code doesn't make sense at all
If you need to send all the values from the CSV file at once you should be rather using JsonBuilder class, example code which generates JSON and prints it to jmeter.log file:
def payload = [:]
def purchasedtem = [:]
purchasedtem.put('purchaseitem', new File('/path/to/your/purchase.csv').readLines().collect())
payload.put('uname', purchasedtem)
log.info(new groovy.json.JsonBuilder(payload).toPrettyString())
More information:
Apache Groovy - Parsing and Producing JSON
Apache Groovy - Why and How You Should Use It

Transfer list between Groovy test steps (SoapUI)

I have one test case which is called (started and finished) before every run of other test cases. It is something like 'test data preparation' test case. Output from this test case is list with some elements, list looks like this:
def list = ['Login', 'Get Messages', 'Logout', etc.]
List is different on every run. I need to transfer this list from 'test data preparation' test case to other test cases. Transfer will be between two Groovy scripts.
How to transfer list between two Groovy test steps in SoapUI?
As I understand it:
You have one TestCase, which you call from every other TestCase.
I assume this is done using a "Run TestCase" teststep?
You would like to be able to pass a list of strings
As I read it, parameters go one way. From the "external testcase" and back to the calling testcase. There is no "input" from each testcase to this "external testcase"?
The Groovy Script in your "external testcase" may then generate a String result, which in turn can be converted to something like an Array or ArrayList of Strings.
This could be a string with values separated by ;
def result = ""
result += "Entry1;"
result += "Entry2;"
result += "Entry3;"
// You may want to add a line of code that removes the last ;
return result
This result will then be easily retrieved from Groovy Scripts elsewhere, by adding a few lines of code.
If the Groovy Script is placed in another TestCase, but in the same TestSuite, you may retrieve the result using:
def input = testRunner.testCase.testSuite.getTestCaseByName("Name of TestCase").getTestStepByName("Groovy Script Name").getPropertyValue("result")
If it is placed in a TestCase in a different TestSuite, you may use:
def input = testRunner.testCase.testSuite.project.getTestSuiteByName("Test Suite Name").getTestCaseByName("Test Case Name").getTestStepByName("Groovy Script Name").getPropertyValue("result")
and then loop over the input doing something like:
for (def s : input.split(";")) {
log.info s
// Do your stuff here
}
I hope that makes sense...? :)
from groovy step 1 you shall return the list:
def list = ['Login', 'Get Messages', 'Logout']
return list
from groovy step 2 you can get this returned list
def result = context.expand( '${Groovy Script 1#result}' )
list = result.tokenize('[,] ')
list.each{
log.info it
}
note that you get a string that you have to convert back to a list (tokenize).
I did this with SOAPUI pro.
Another way (ugly) would be to store the list in a custom property in groovy script 1 (using testRunner.testCase.setPropertyValue("myList",list.toString())
and to recover it in groovy step 2 (testRunner.testCase.getPropertyValue("myList")
I hope that will help
EDIT : if list elements contain spaces
this is not very clean and I hope someone will help to provide something better but you can do the following :
list = "['Login - v1', 'Get Messages - v2', 'Logout - v1']"
list = list.replace('\'','\"')
def jsonSlurper = new groovy.json.JsonSlurper()
list = jsonSlurper.parseText(list)
list.each{
log.info it
}
Alex

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