Assert response starts with - groovy

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")

Related

SOAP UI Groovy JsonNull Handling

Hello I'm new to this Groovy Script thing in SOAP UI can anyone tell me what i'm doing wrong? i can't do a if null condition with this code
//Getting Request
def RequestMessage=context.request
log.info RequestMessage
def jsonSlurper = new JsonSlurper().parseText(RequestMessage)
try{
if(jsonSlurper.iso8583Request.iso8583Detail.bit127){
log.info "127 is null"
}else{
testRunner.testCase.setPropertyValue("revBit127", "${jsonSlurper.iso8583Request.iso8583Detail.bit127}")
}catch{
log.info "127 is null"
}
Any advice to handle if null condition from this Json object?
You're not far off.
Firstly, I don't chain when using JSON Slurper, I tend to use it like this...
import groovy.json.JsonSlurper;
def response = context.expand( '${SOME REST Request#Response#$[\'message\']}' )
// Create a slurper object.
def slurper = new groovy.json.JsonSlurper();
// Create the JSON
def json = slurper.parseText(response);
In your example, I think this is wrong...
if(jsonSlurper.iso8583Request.iso8583Detail.bit127){
log.info "127 is null"
You're actually checking it exists, instead try...
if(!jsonSlurper.iso8583Request.iso8583Detail.bit127){
log.info "127 is null"
}else{
testRunner.testCase.setPropertyValue("revBit127", "${jsonSlurper.iso8583Request.iso8583Detail.bit127}")
}

groovy to get the json key values to a string

I have a json file with values - {"testID":"smoke_01","testID":"smoke_02","testID":"smoke_04"}.
I read the values for testID and saved to array. Now I was trying to make it as a simple string like -
testcase = smoke_01,smoke_02,smoke_02. My code is below :
def props = readJSON file: 'input.json'
def list = []
props.each { key, value ->
list.push("$value")
}
echo "$list"
def asString = list.join(", ")
def testcase = asString.join(", ")
But when i print testcase - its printing as [smoke_01, smoke_02, smoke_04] . Please help me to understand where I am wrong.
Assuming you really have this invalid strange JSON (keys must be unique in an Object in basically every language you parse to, but yours are not), and that readJSON actually parses your custom JSON into something you can iterate over as if it were a Map... then, this should do what you want:
def props = readJSON file: 'input.json'
def testCase = props.values().join(', ')
println testCase
Assuming you use proper JSON
By proper JSON I mean something that does not break JSON semantics, hence can be parsed by any JSON parser, not your custom one.
You JSON file should look more like this:
{ "tests": [
{ "testID": "smoke_01" },
{ "testID": "smoke_02" },
{ "testID": "smoke_03" }
] }
In which case you would parse it with:
def json = new JsonSlurper().parse(new File('input.json'))
def testCase = json.tests.collect { it.testID }.join(', ')
println testCase
There are other ways to represent this in JSON, but you should study how JSON works and what suits you best depending on how it is going to be used.
Here's the JSON spec which is simple enough you can learn it in 20 minutes:
https://www.json.org/json-en.html

Groovy RestClient POST request sends invalid JSON

I found, that sending JSON, which has entry which starts with "function" produces invalid JSON.
Example:
#Grab('org.codehaus.groovy.modules.http-builder:http-builder:0.7.1')
import groovy.json.JsonSlurper
import groovy.json.JsonOutput
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
def jsonSlurper = new JsonSlurper()
// if you replace `function` on next line to any other word - it will work correctly
String baseContextJSON = '{ "afterResponse": "function (getParam, setParam, genInfo) { }" }'
def baseContext = jsonSlurper.parseText(baseContextJSON)
println JsonOutput.prettyPrint(JsonOutput.toJson(baseContext))
RESTClient http = new RESTClient('https://requestinspector.com')
http.post(
path: "/inspect/01dh7rs82be884ke89jcny061e",
body: baseContext, // if I use baseContextJSON here - correct JSON would be sent
query: null,
requestContentType: JSON
)
This code sends this payload:
{"afterResponse":function(getParam,setParam,genInfo){}}
That's invalid JSON - note missing quote around function.
You can see actual received payloads at https://requestinspector.com/p/01dh7rs82be884ke89jcny061e (until it expires, or you can generate you own)
I can't even figure out:
- is it bug in HTTPBuilder?
- is it bug in how Groovy handles and convert Map to JSON?
Any idea what can I do to pin root cause?

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 add XPath to XmlSlurper

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

Resources