writing a soap request in groovywslite - groovy

I am new to groovy wslite and I ma trying to write a soap request in wslite.
My soap request in xml is-
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:get="http://WSA.francetelecom.com/types/GetSoftPhoneInfos">
<soapenv:Header/>
<soapenv:Body>
<get:getClientSOFTPHONEInfo>
<get:businessUnit>${#TestSuite#BU_FR}</get:businessUnit>
<get:cpeType>${#TestSuite#CPETYPE}</get:cpeType>
<get:customerId>
<!--Optional:-->
<get:type>${#TestSuite#ID_TYPE_NDIP}</get:type>
<!--Optional:-->
<get:value>${#TestSuite#NDIP_Nominal}</get:value>
</get:customerId>
</get:getClientSOFTPHONEInfo>
</soapenv:Body>
</soapenv:Envelope>
and the groovy script I am running is as below-
import wslite.soap.*
import wslite.http.auth.*
import groovy.xml.XmlUtil
def client = new SOAPClient( 'http://10.170.194.214:1080/PapyrusSAV/services/GetSoftPhoneInfos-v2?wsdl')
client.authorization = new HTTPBasicAuthorization( "papyihm", "papypapyihm" )
def response = client.send(SOAPAction:'')
body{
getClientSOFTPHONEInfo('xmlns':'http://WSA.francetelecom.com/types/GetSoftPhoneInfos'){
businessUnit('FR')
cpeType('SOFTPHONE')
customerId('xmlns':'http://WSA.francetelecom.com/types/GetSoftPhoneInfos'){
type('NDIP')
value('+33155886791')
}
}
}
println XmlUtil.serialize( response.getClientSOFTPHONEInfo)
When I execute my groovy I get error
groovy.lang.MissingMethodException: No signature of method: wslite.soap.SOAPClient.send() is applicable for argument types: (java.util.LinkedHashMap) values: [[SOAPAction:]]
Possible solutions: send(groovy.lang.Closure), send(java.lang.String), send(java.util.Map, groovy.lang.Closure), send(java.util.Map, java.lang.String), send(wslite.soap.SOAPVersion, java.lang.String), find()
what am I doing wrong.
PS: SoapAction is "" in the wsdl which I am using

You need a Closure to send request as below :-
def response = client.send(SOAPAction:'') {
body {
getClientSOFTPHONEInfo('xmlns':'http://WSA.francetelecom.com/types/GetSoftPhoneInfos'){
businessUnit('FR')
cpeType('SOFTPHONE')
customerId('xmlns':'http://WSA.francetelecom.com/types/GetSoftPhoneInfos') {
type('NDIP')
value('+33155886791')
}
}
}
}
Hope it will help you..:)

Related

HTTP POST in GROOVY

I'm trying desperately to translate this python code into groovy, but I can't find the right solution.
It could be great if someone could help me a bit. :)
#! /usr/bin/env python3
# coding: utf-8
import requests
url = "http://localhost:8088/mockServiceSoapBinding"
xml = '''<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:sam="http://www.soapui.org/sample/">
<soapenv:Header/>
<soapenv:Body>
<sam:login>
<username>Login</username>
<password>Login123</password>
</sam:login>
</soapenv:Body>
</soapenv:Envelope>'''
headers = {'content-type': 'text/xml;charset=UTF-8', 'Accept-Encoding': 'gzip,deflate'}
r1 = requests.post(url, data=xml, headers=headers, auth=('user', 'pass'))
print(r1.text)
Making HTTP POST call from Groovy can be done by initializing the URL connection.
Here is a working example:
url = 'http://localhost:8088/mockServiceSoapBinding'
def username = 'user'
def password = 'pass'
xml = '''<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:sam="http://www.soapui.org/sample/">
<soapenv:Header/>
<soapenv:Body>
<sam:login>
<username>Login</username>
<password>Login123</password>
</sam:login>
</soapenv:Body>
</soapenv:Envelope>'''
def connection = new URL(url).openConnection()
connection.setRequestMethod('POST')
// set headers
connection.setRequestProperty('Content-Type', 'text/xml;charset=UTF-8')
connection.setRequestProperty('Accept-Encoding', 'gzip,deflate')
if (username && password) {
String userCredentials = username + ':' + password
String basicAuth = 'Basic ' + Base64.getEncoder().encode(userCredentials.getBytes())
connection.setRequestProperty('Authorization', basicAuth)
}
connection.doOutput = true
connection.outputStream.write(xml.getBytes('UTF-8'))
println "XX: connect"
connection.connect()
println "XX: get content"
def text = connection.content.text
println(text)

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 read node name via Groovy script in soapUI

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

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.

Resources