groovy returning different node count - groovy

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.

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

Cannot replace string text in Groovy script

I am trying to replace a test in pom.xml using a groovy script. These are my two approaches. The text should be replaced is {env.AM_$environment.toUpperCase()_SERVER_CREDS_USR}
Approach one
File mainPomXml = new File(rootDir,'/pom.xml')
mainPomXml.text.replace('{env.AM_$environment.toUpperCase()_SERVER_CREDS_USR}','${env.AM_$environment.toUpperCase()_SERVER_CREDS_USR}');
Approach two
def mainPomXml = new File(rootDir,'/pom.xml')
def mainPom = mainPomXml.text.replace('{env.AM_$environment.toUpperCase()_SERVER_CREDS_USR}','${env.AM_$environment.toUpperCase()_SERVER_CREDS_USR}');
mainPomXml.write(mainPom);
But none of these approaches work. That means both executes but the test is not get replaced. How to fix this issue?
Change the mainPom part as below.
def mainPomXml = new File(rootDir, '/pom.xml')
def mainPom = mainPomXml.text.replace('AM_SERVER_CREDS_USR', '${env.AM_'+ env.toUpperCase() +'_SERVER_CREDS_USR}')
mainPomXml.write(mainPom)

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

Second map value is always null, even if it prints out 1

I have some code getting data and then selecting it in order. For this I use simple maps that I may later access with ease (I thought..).
I use the following code within a loop to insert maps to another map named "companies":
def x = [:]
x.put(it.category[i], it.amount[i])
companies.put(it.company, x)
And I can surely write the result out: [Microsoft:[Food:1], Apple:[Food:1]]
But then, when I am about to get the food value of each company it always is null. This is the code I use to get the values:
def val = companies.get(it.company).get(key.toString())
def val = companies[it.company][key] // doesn't make a difference
Val is always null. Can someone help and / or explain why I have this error. What am I doing wrong? I mean, I can clearly see the 1 when I print it out..
My guess is that it.category[i] and key are completely different types...
One thing you could try is:
x.put(it.category[i].toString(), it.amount[i])
and then
def val = companies[it.company][key.toString()] // doesn't make a difference
The solution was simple to make the category as a string:
x.put(it.category[i].toString(), it.amount[i])
And after that little fix it all works as expected.

Resources