How to add XPath to XmlSlurper - groovy

I am trying to create a groovy script assertion in SoapUI. In the response, I and trying to pull a field called written. however there are +15 of these fields.
I is possible to add the XPath to the XmlSlurper to find the exact written fields I want to assert against.
Looking at the XML response below, I would like to assert the value in b:premium\written. not the one from the b:other. Given there are 15+ b:written fields i would like to assert the value using the xpath.
XML Response:
<s:Body>
<NewRateResponse>
<NewRateResult>
<b:policies>
<b:other>
<b:written>00.00</b:written>
</b:other>
<b:premium>
<b:written>31.21</b:written>
</b:premium>
</b:policies>
</NewRateResult>
</NewRateResponse>
</s:Body>
Assertion Code:
import org.junit.Assert
def response = messageExchange.getResponseContent()
def xml = new XmlSlurper().parseText(response)
def nodePremium = xml.'**'.find { it.name() == 'written'}
Assert.assertEquals(00.01, nodePremium.toDouble(),0)
I believe the area we need to change is def nodePremium = xml.'**'.find { it.name() == 'written'}. to be something like def nodePremium = xml.'**'.find { it.name() == 'premium\written'} but that does not work for me.

assert xml.'**'.find { it.name() == 'premium'}.written.text() as Double == 31.20

Related

Asserting object count in a JSON response using groovy script

I have a question on how to assert the element_count equals to the number of objects from response.
The link to the API is https://api.nasa.gov/neo/rest/v1/feed?start_date=2019-05-10&end_date=2019-05-16&api_key=*******
I tried using the below code but did not have any luck trying to count the objects from the JSON response using grrovy script.
import groovy.json.JsonSlurper
def ResponseMessage = messageExchange.response.responseContent
def response = new JsonSlurper().parseText(ResponseMessage)
def elementCount = response.element_count
def idCount = response.count { it.equals('neo_reference_id') }
I was trying to count the number of neo_reference_id which should equal element_count. Any help would be great.
def url = new URL('https://api.nasa.gov/neo/rest/v1/feed?start_date=2019-05-10&end_date=2019-05-16&api_key=***')
def response = new groovy.json.JsonSlurper().parse( url )
def neo_references = response.near_earth_objects.collectMany{date,objects-> objects.collect{it.neo_reference_id} }
println neo_references
println neo_references.size()
assert response.element_count == neo_references.size()

How to check if an xml element is displayed using a script assertion

I want to perform an assertion within SOAP UI to check if the 'BookingCode' is displayed but I am not sure how to do it. I am using .size() but it keeps failing whether there is or isn't any booking code:
Below is an xml example but I xxx out the information:
<soap:xxx">
<soap:Body>
<getBookingsResponse xmlns="http://xxx/">
<Bookings>
<Booking Id="xxx" BookingCode="xxx" >
Below is the script assertion itself:
def groovyUtils = new com.eviware.soapui.support.GroovyUtils(context)
def serviceResponse = context.expand( '${getBookings#Response}' )
def xml = new XmlSlurper().parseText( serviceResponse )
def BookingRef = xml.'soap:Body'.getBookingsResponse[0].Bookings[0].Booking.#BookingCode
assert BookingRef.size() != 0
Thank you
Here you go, comments in-line:
Script Assertion
//Pass the xml string to parseText method
def pxml = new XmlSlurper().parseText(context.response)
//Get the BookingCode attributes
def codes = pxml.'**'.findAll{ it.name() == 'Booking' }*.#BookingCode*.text()
log.info codes
assert codes.size !=0

Assert response starts with

I am trying to assert the response, to check if the response value starts with a certain text. I tried using the function startsWith but it seems like it does not work in SOPAUI script assertion.
This is what I have tried:
import groovy.json.JsonSlurper
//grab the response
def ResponseMessage = messageExchange.response.responseContent.records
//define a JsonSlurper
def jsonSlurper = new JsonSlurper().parseText(ResponseMessage)
//log.info jsonSlurper
assert jsonSlurper.startsWith("Text")
Here is the json response
{
"Name": "Natalie",
"message": "What are you doing"
}
I want to check if the Name starts with "Nat"
From documentation JsonSlurper().parseText(String text) returns:
data structure of lists and maps
so you can not use startsWith directly. To achieve what you want you have to go to the desired object in the path and use startsWith there. Something like must works for your case:
import groovy.json.JsonSlurper
def jsonStr = '{ "Name": "Natalie", "message": "What are you doing" }'
def jsonSlurper = new JsonSlurper().parseText(jsonStr)
assert jsonSlurper.Name.startsWith("Nat")

Soap UI: Groovy Script to call an API if the response is true

I am very new to use SoapUI. Writing test cases for my project APIs.
My requirement is to run a groovy script after an API call and if the response text of this API is "true", another API should call.
I found myself stuck to do this. Can anyone guide me to do this.
Thanks in advance!!!
I found answer but forgot to inform over here. I did asserted an script like this in TestStep:
def slurper = new groovy.json.JsonSlurper()
def responseJson = slurper.parseText(messageExchange.getResponseContent())
assert responseJson instanceof Map
assert responseJson.containsKey('authToken')
def id = "Bearer "+responseJson['authToken']
log.info(id.toString())
testRunner = new com.eviware.soapui.impl.wsdl.testcase.WsdlTestCaseRunner(context.testCase.testSuite.project.getTestSuiteByName("TestSuite").getTestCaseByName("TestCas"), null)
def tcase = testRunner.testCase
def tstep = tcase.getTestStepByName("TestStep")
testContext = new com.eviware.soapui.impl.wsdl.testcase.WsdlTestRunContext(tstep)
runner = tstep.run(testRunner, testContext)
Little idea for this :
def response = context.expand( '${TestRequest1#Response}' )
if ( response == 'true' )
{
testRunner.runTestStepByName( "TestRequest2")
}
Disable your first test Step(TestRequest1).

groovy.lang.MissingPropertyException: in groovy

I am new to groovy code. I have a map like this
response = {"data":{"--class":"java.util.HashMap","Enabled":false,"Adult":"[recursive reference removed]","TVMA":"[recursive reference removed]","Locks":[false,false,false,false,false,false],"PINEnabled":false,"AdvisoryLocks":[false,false,false,false,false,false,false,false,false,false,false,false],"safeSearch":"[recursive reference removed]","RatingLocks":[false,false,false,false,false,false]},"success":true}
Using groovy code I want to check the presence of the following keys:
Enabled,
Adult,
TVMA,
Locks,
PINEnabled,
AdvisoryLocks,
safeSearch,
RatingLocks,
I am using the following code:
for ( data in response.data ) {
println("-----------------------------------------")
assertNotNull(data.Enabled)
assertNotNull(data.Adult)
;;;;;;
.......
}
Am getting groovy.lang.MissingPropertyException: No such property: Enabled
How can I check the presence of the above keys from response map using groovy?
I think you can find keys value from the Json like below.
def slurper = new JsonSlurper()
def result = slurper.parseText(response)
assert result.data.Enabled != null
assert result.data.Enabled != ""
assert result.data.Adult != null
assert result.data.Adult != ""
I hope that will help you :)
How about using good'ol regexp?
String response = '{"data":{"--class":"java.util.HashMap","Enabled":false,"Adult":"[recursive reference removed]","TVMA":"[recursive reference removed]","Locks":[false,false,false,false,false,false],"PINEnabled":false,"AdvisoryLocks":[false,false,false,false,false,false,false,false,false,false,false,false],"safeSearch":"[recursive reference removed]","RatingLocks":[false,false,false,false,false,false]},"success":true}'
assert [ 'Enabled', 'Adult', 'TVMA',,,, ].every{ response =~ /"$it":/ }

Resources