How to read node name via Groovy script in soapUI - groovy

How do I read the nodename from a given XML response? I was using xmlSlurper in readyAPI Groovy editor but not able to get the values
I wanted to fetch the ROOM,GENR values from rom1:RoomType Code from xml response.
def RoomTypes = new XmlSlurper().parseText(responseTestSuite1)
Sample XML as below
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Header/>
<soap:Body>
<rom1:GetRoomTypesListResponse xsi:schemaLocation="xsdlocation" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:rom1="service">
<rom1:Success/>
<rom1:Hotels>
<rom1:Hotel HCode="ABSCD"/>
</rom1:Hotels>
<rom1:RoomTypes>
<rom1:RoomType Code="ROOM">
<rom1:Name Language="en">Guest room, King or Queen or Double</rom1:Name>
</rom1:RoomType>
<rom1:RoomType Code="GENR">
<rom1:Name Language="en">Guest room, 1 King</rom1:Name>
</rom1:RoomType>
</rom1:RoomTypes>
</rom1:GetRoomTypesListResponse>
</soap:Body>
</soap:Envelope>

Here is what you need :
//Pass xml string in to below parseText method
println new XmlSlurper().parseText(xml).'**'.findAll { it.name() == 'RoomType'}*.#Code
Output
You get the list of values i.e., ROOM, GENR as output
You can quickly try this online Demo
If you are using ReadyAPI / SoapUI, use following Script Assertion instead of separate groovy script test step
//check if response is ok
assert context.response,'Resonse is empty'
def pXml = new XmlSlurper().parseText(context.response)
def codes = pXml.'**'.findAll { it.name() == 'RoomType' }*.#Code
log.info codes

Related

can not pass groovy parameter value to soapUI request xml

Want to pass bankaTalimatNo parameter to following request from groovy script.
I created a test case level property called bankaTalimatiNo.
Inside the groovy script i iterate an array to set values property values correcty but the generated request does not change in parallel with the property value.
What should be the correct XML expression to achieve this?
thanks in advance
<soapenv:Header/>
<soapenv:Body>
<wso:kurumOdemesiSorgulaRequest>
<wso:bankaTalimatiNo>${Properties#bankaTalimatiNo}</wso:bankaTalimatiNo>
</wso:kurumOdemesiSorgulaRequest>
</soapenv:Body>
</soapenv:Envelope>
and the groovy script is as follows
project = testRunner.getTestCase().getTestSuite().getProject().getWorkspace().getProjectByName("maliye")
testSuite = project.getTestSuiteByName("TestSuite 1");
testCase = testSuite.getTestCaseByName("TestCase 1");
testStep=testCase.testSteps["SOAP Request1"]
File file = new File("C:/temp/test.txt")
file.write "This is the first line\n"
def String[] talimatNoArray = [
"3"
];
talimatNoArray.eachWithIndex{talimatNo, i->
testCase.setPropertyValue("bankaTalimatiNo" , "${talimatNo}");
log.info "aaa"+ testCase.getPropertyValue("bankaTalimatiNo");
def groovyUtils = new com.eviware.soapui.support.GroovyUtils(context);
context.bankaTalimatiNo=testStep.getPropertyValue("bankaTalimatiNo");
def responseHolder=testStep.getPropertyValue("response");
//Check if the response is not empty
assert responseHolder, 'Response is empty or null'
}
Generated request is always the same , the expression is never evaluated
> <soapenv:Envelope
> xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
> xmlns:wso="http://maliye.yte.bilgem.tubitak.gov.tr/odeme/kurumodemesi/server/wso">
> <soapenv:Header/> <soapenv:Body>
> <wso:kurumOdemesiSorgulaRequest>
> <wso:bankaTalimatiNo>${bankaTalimatiNo}</wso:bankaTalimatiNo>
> </wso:kurumOdemesiSorgulaRequest> </soapenv:Body> </soapenv:Envelope>
In the request, change from:
<wso:bankaTalimatiNo>${Properties#bankaTalimatiNo}</wso:bankaTalimatiNo>
To:
<wso:bankaTalimatiNo>${#TestCase#bankaTalimatiNo}</wso:bankaTalimatiNo>

Unable to retrieve data while parsing soap message with escaped xml using groovy

I try to select value of node from soap message (with gt and lt symbols) , but cant do that, i can only get body (root.Body) and other nodes are not visible, it is empty result. What i'm making wrong?
Thanks!
import groovy.util.slurpersupport.Node
import groovy.util.slurpersupport.NodeChild
import groovy.xml.XmlUtil
String source=
'''<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Body>
<ns0:GetListBy_QualificationResponse xmlns:ns0="urn:WS_CTM_People_ICEVA">
<ns0:getListValues>
<ns0:Person_ID>PPL000000301739</ns0:Person_ID>
<ns0:Submitter>soehler</ns0:Submitter>
<ns0:Profile_Status>Enabled</ns0:Profile_Status>
<ns0:Locale2>en_US</ns0:Locale2>
<ns0:VIP>No</ns0:VIP>
<ns0:Client_Sensitivity>Standard</ns0:Client_Sensitivity>
</ns0:getListValues>
</ns0:GetListBy_QualificationResponse>
</soapenv:Body>
</soapenv:Envelope>'''
def root = new XmlSlurper().parseText(source)
def Submitter =root.Body.GetListBy_QualificationResponse.getListValues.'*'.find { node->
node.name() == 'Submitter'
}
It is because the xml is escaped. In order to be able to retrieve the data property, it is required to unescape the xml string and pass it XmlSlurper.
Here is how it can be done:
String source='''<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Body>
<ns0:GetListBy_QualificationResponse xmlns:ns0="urn:WS_CTM_People_ICEVA">
<ns0:getListValues>
<ns0:Person_ID>PPL000000301739</ns0:Person_ID>
<ns0:Submitter>soehler</ns0:Submitter>
<ns0:Profile_Status>Enabled</ns0:Profile_Status>
<ns0:Locale2>en_US</ns0:Locale2>
<ns0:VIP>No</ns0:VIP>
<ns0:Client_Sensitivity>Standard</ns0:Client_Sensitivity>
</ns0:getListValues>
</ns0:GetListBy_QualificationResponse>
</soapenv:Body>
</soapenv:Envelope>'''
//map the unescape characters
def map = ['<' : '<', '>' : '>', '"' : '"', '&apos;':'\'', '&':'&']
//Replace them in source string
map.collect {k,v -> source = source.replaceAll(k,v)}
//Now parse it
def root = new XmlSlurper().parseText(source)
//Get the submitter
def submitter = root.'**'.find { it.name() == 'Submitter' }
println submitter
You can quickly try online Demo

how to get the attribute value inside cdata from the response and use it in other request

This is my response, how to get HIndex attribute value?
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<HResponse xmlns="http://demo.org/">
<HResult>
<![CDATA[
<HRS>
<Header>
<Currency>INR</Currency>
<SessionId>1313123123123123123</SessionId>
</Header>
<HotelDetails>
<Stay></Stay>
<Hotel HIndex="1701" PrefContract="" HDIndex="28">
<HNm> Demo</HNm>
<HImg>demo</HImg>
</Hotel>
<Hotel HIndex="1702" PrefContract="" HDIndex="29">
<HNm> Demo</HNm>
<HImg>demo</HImg>
</Hotel>
<Hotel HIndex="1703" PrefContract="" HDIndex="30">
<HNm> Demo</HNm>
<HImg>demo</HImg>
</Hotel>
</HotelDetails>
</HRS>
]]>
</HResult>
</HResponse>
</soap:Body>
</soap:Envelope>
I want to use HIndex value in the other request.Am able to select the other node value. But, when I am selecting attribute, I am getting the null value
You can use a Groovy script testStep, to parse your SOAP testStep response. More exactly use XmlSlurper to parse your response, get the CDATA finding in the slurper by tag name, and parse the CDATA again due that XmlSlurper returns CDATA as String. Finally find your desired node by its name and then access its attribute value using node.#attributeName notation. Something like this must works for your case:
def xml = '''<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<HResponse xmlns="http://demo.org/">
<HResult>
<![CDATA[
<HRS>
<Header>
<Currency>INR</Currency>
<SessionId>1313123123123123123</SessionId>
</Header>
<HotelDetails>
<Stay></Stay>
<Hotel HIndex="1701" PrefContract="" HDIndex="28">
<HNm> Demo</HNm>
<HImg>demo</HImg>
</Hotel>
<Hotel HIndex="1702" PrefContract="" HDIndex="29">
<HNm> Demo</HNm>
<HImg>demo</HImg>
</Hotel>
<Hotel HIndex="1703" PrefContract="" HDIndex="30">
<HNm> Demo</HNm>
<HImg>demo</HImg>
</Hotel>
</HotelDetails>
</HRS>
]]>
</HResult>
</HResponse>
</soap:Body>
</soap:Envelope>'''
def slurper = new XmlSlurper().parseText(xml)
def cdataAsStr = slurper.'**'.find { it.name() == 'HResult' }.toString()
def cdataSlurper = new XmlSlurper().parseText(cdataAsStr)
// get all HIndex attribute values from `<Hotel>`
def hIndexValues = cdataSlurper.'**'.findAll { it.name() == 'Hotel' }*.#HIndex as List
Notes:
In your question the Xml inside CDATA is not well formed, use <Stay></Stay> instead of <Stay></stay> (note the lower case).
If your are interested only in the attribute value from the first <Hotel> then access the first element from the list as: hIndexValues[0].
If instead of a String as in the example you want to get the Xml content from a SOAP testStep use:
testRunner.testCase.getTestStepByName('TestStepName').getPropertyValue('response') to define the def xml object.
To use the attribute values in other testSteps save it at some level (for example testCase testRunner.testCase.setPropertyValue('myAttrValue',hIndexValues[0].toString())) an then use the property expansion notation inside other testStep request ${#TestCase#myAttrValue}.
If you want to use the above script in the Script Assertion instead of in the Groovy testStep you can use the same script as above only changing the way you get the response Xml from you testStep:
// in the script assertion you can access the
// response from the current testStep simply with
// messageExchange.getResponseContent()
def xml = messageExchange.getResponseContent()
def slurper = new XmlSlurper().parseText(xml)
def cdataAsStr = slurper.'**'.find { it.name() == 'HResult' }.toString()
def cdataSlurper = new XmlSlurper().parseText(cdataAsStr)
// get all HIndex attribute values from `<Hotel>`
def hIndexValues = cdataSlurper.'**'.findAll { it.name() == 'Hotel' }*.#HIndex as List
Here is the Script Assertion for the first request step. This will avoid additional groovy script step in the test case.
Please follow the appropriate comments in-line:
/**
* This is Script Assertion for the first
* request step which extracts cdata from response,
* then HIndex'es from extracted cdata. And
* Assigns first value at test case level, so that
* it can be used in the rest of the test steps of
* the same test case.
* */
/**
* Closure to parse and retrieve the data
* retrieves element or attribute
*/
def searchData = { data, item, itemType ->
def parsedData = new XmlSlurper().parseText(data)
if ('attribute' == itemType) {
return parsedData?.'**'.findAll{it.#"$item".text()}*.#"$item"
}
parsedData?.'**'.find { it.name() == item} as String
}
//Assert response xml
assert context.response, "Response data is empty or null"
//Get the CDATA from response which is inside of HResult
def cData = searchData(context.response, 'HResult', 'element')
//Assert retrieved CDATA is not empty
assert cData, "Data inside of HResult is empty or null"
//Get the HIndex list
def hIndexes = searchData(cData, 'HIndex', 'attribute')
//Print list of hIndexes
log.info hIndexes
//Print the first in the list
log.info "First HIndex is : ${hIndexes?.first()}"
//Print the last in the list
log.info "Last HIndex is : ${hIndexes?.last()}"
//Use the required HIndex from the list
context.testCase.setPropertyValue('HINDEX', hIndexes?.first().toString())
//or the below one using index
//context.testCase.setPropertyValue('HINDEX', hIndexes[0]?.toString())
In the following test steps, you can use the saved HINDEX in the following ways:
If the following step is request step (REST, SOAP, HTTP, JDBC etc), then use property expansion ${#TestCase#HINDEX} like <Index>${#TestCase#HINDEX}</Index>
If the following step is groovy script, then use one of the below:
context.expand('${#TestCase#HINDEX}') or
context.testCase.getPropertyValue('HINDEX') or
testRunner.testCase.getPropertyValue('HINDEX')
You can quickly try & execute the script from here.

Getting context using groovyutils outside SoapUI

I am trying to hold the response of my request in a holder variable but I am not able to.
In SoapUI groovyutils is in-built and can be used easily. But I am sending my soap request using groovy and it is working fine. Now I want to get the response in a holder and put some assertions.
My piece of code for this is :
import com.eviware.soapui.*
def groovyUtils = new com.eviware.soapui.support.GroovyUtils()
def responseHolder = groovyUtils.getXmlHolder( messageExchange.responseContent )
Here I am not able to get as how I should pass the context in groovyutils and what all classes to call.
I'm not sure that I fully understand your problem, however seems that you want to check a SOAP response out of SOAPUI but using the facilities from SOAPUI jar isn't it?
If you want simply perform some assert in the response, then I would recommend you to avoid the use of GroovyUtils. Simply use XmlSlurper to parse the response, then get the desired values from the xml nodes and perform your asserts.
Since your Groovy code to you invoke the service and the response is missing I simply show you a possible example using XmlSlurper:
def response = '''<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope/">
<soap:Body>
<myResponse>
<someNode>myText</someNode>
</myResponse>
</soap:Body>
</soap:Envelope>'''
def xml = new XmlSlurper().parseText(response)
// find the <someNode> element
def someNode = xml.'**'.find { it.name() == 'someNode' }
// check that the <someNode> has a value equals of 'myText'
assert someNode.text() == 'myText'
Hope it helps,

Using XMLParser on SoapUI response

Trouble using XmlParser in SoapUI Pro
Hi, I am trying to use 'xml parser' to validate my xml responses in SoapUI Pro.
I have been playing around with this in a groovy script and I can access the tags if I declare and assign my xml within the groovy script like so
This works if I declare the xml in the script ..
def xml = """
<NS1:createShipmentResponse xmlns:NS1="http://www.royalmailgroup.com/api/ship/V1">
<NS1:integrationHeader>
<dateTime xmlns="http://www.royalmailgroup.com/integration /core/V1">2013-12-24T22:20:34</dateTime>
<version xmlns="http://www.royalmailgroup.com/integration/core/V1">1</version>
<identification xmlns="http://www.royalmailgroup.com/integration/core/V1">
<applicationId>111111113</applicationId>
<transactionId>420642961</transactionId>
</identification>
</NS1:integrationHeader>
<NS1:completedShipmentInfo>
//xml not complete, other info in here.
</NS1:completedShipmentInfo>
<NS1:integrationFooter>
<warnings xmlns="http://www.royalmailgroup.com/integration/core/V1">
<warning>
<warningCode>W0022</warningCode>
<warningDescription>The customerReference specified is longer than 12 characters and has been truncated</warningDescription>
</warning>
<warning>
<warningCode>W0026</warningCode>
<warningDescription>The departmentReference specified is invalid and will be ignored</warningDescription>
</warning>
</warnings>
</NS1:integrationFooter>
</NS1:createShipmentResponse>
"""
def parser = new XmlParser().parseText(xml)
parser.'NS1:integrationFooter'.warnings.warning.warningCode.each{
log.info it.text()
}
But it doesn't seem to work within a running test instance when I instantiate the xmlParser variable from my Soap response as below.
def response = context.expand( '${createShipment_v04#Response}' );
I know that the parser variable has been assigned the xml response because when I can print it to the log ..
i.e. log.info parser prints ...
Wed Jan 08 16:33:38 GMT 2014:INFO:{http://schemas.xmlsoap.org/soap/envelope /}Envelope[attributes={}; value=[{http://schemas.xmlsoap.org/soap/envelope/}Body[attributes={}; value=[{http://www.royalmailgroup.com/api/ship/V1}createShipmentResponse[attributes={}; value=[{http://www.royalmailgroup.com/api/ship/V1}integrationHeader[attributes={}; .......
But below code does not print anything when I instantiate the xmlParser request from the soap response.
parser.'NS1:integrationFooter'.warnings.warning.warningCode.each{
log.info it.text()
}
Any help would be much appreciated.
I believe you are working at the wrong level.
parser.Body….
Ok. It turns out I don't need the 'NS1:' part. The below works ..
slurper.Body.createShipmentResponse.integrationFooter.warnings.warning.warningCode.each{
log.info it.text()
}
Following should work:
def response = context.expand( '${createShipment_v04#Response}' );
def parser = new XmlSlurper().parseText(response)
def warningCodes = parser.'**'.findAll {
it.name()=='warningCode'
}
warningCodes.each {
log.info it
}

Resources