Get response body on success in HTTPBuilder-NG - groovy

I'm trying to use Httpbuilder-NG in the Gradle script of an Android Studio project. The script uploads some files to a web server for validation, the server responds with 'ok' or the name of the file that did not validate.
I am trying
response.success { FromServer fs, Object body ->
println "Success: ${fs.statusCode}, Text is: ${body}, Properties are: ${body.properties}"
}
and the result is always:
Success: 200, Text is: [102, 105, 108, 101], Properties are: [class:class [B, length:4]
Note it is a 4-element array, not a text string. And the array stays the same whether the server returns 'ok' or something else. I recognize my server may be returning something non-standard but it works fine in Postman.
I have also tried
response.success { FromServer fs, Object body ->
println "has body = ${fs.hasBody}"
println "content type = ${fs.contentType}"
println "charset = ${fs.charset}"
println "files uploaded, result = ${fs.reader.text}"
//println "Success: ${fs.statusCode}, Text is: ${body}, Properties are: ${body.properties}"
}
and the result is always
has body = true
content type = text/html
charset = UTF-8
files uploaded, result =
i.e. a blank string where the body should be.
fs.hasBody returns true
Any help would be appreciated.

def httpBin = configure {
request.uri = 'http://groovy-lang.org/processing-xml.html'
}
def result = httpBin.get() {
response.success { fromServer,body ->
body
}
}
assert result instanceof groovy.util.slurpersupport.NodeChild
println result
Code snippet above returns all text inside <body> tag of this web page http//...processing-xml
To narrow your result, you need to parse groovy.util.slurpersupport.NodeChild futher.

Related

Groovy OkHttpBuilder with GET Method - getting groovy.json.JsonException

Hi I'm using Groovy HTTPBuilder to make a GET call with request body similar like this:
def obj = [:]
// add the data in map - obj
def http = OkHttpBuilder.configure {
request.uri = "URL"
request.uri.path = "/path"
request.headers.put("Authorization", "token value")
request.cookie("fingerprint", "fingerprint value")
request.accept ="application/json"
request.headers.put("Content-Type", "application/json;")
def jsonBody = JsonOutput.toJson(obj)
request.body = jsonBody
response.failure { FromServer fromServer, Object body ->
assertHttpFailure(fromServer, body)
}
}
http.get()
But, getting an groovy.json.JsonException with below details
Unable to determine the current character, it is not a string, number, array, or object
The current character read is 'R' with an int value of 82
Unable to determine the current character, it is not a string, number, array, or object
line number 1
index number 0
Required request body is missing: public org.springframework.http.ResponseEntity<java.util.List
Any suggestions ? why request body says missing

How to test for Empty array value in Unirest json Response

I have the following code snipet used in Jira Script Runner cloud
String _userId
def result = get(graph_base_user_url + "?")
.header("Authorization","Bearer " + AuthToken )
.queryString("\$filter","mail eq '$userEmail'")
.asJson()
if (result.getStatus().toString() =="200")
{
**if (result.getBody().value){ // <<<<< is Value is not empty ???
_userId=result.getBody().value[0].id
}**
else
_userId="-1" // user does not exist
}
// user ID not found : error 404
if (result.getStatus().toString()=="404")
_userId="User not found"
This code is returning in the result.getBody() the following output
{"#odata.context":"https://graph.microsoft.com/v1.0/$metadata#users","value":[]}
What I am trying to achieve is to test if the value array of the response is empty or not and if not empty I need to fetch the first element item as value[0].Id, but I could not get it correctly
How can I define my code in BOLD above to perform my correct test ?
Error I get from my code is : " Value is not a property of JsonNode object
Thanks for help
regards
from official doc http://kong.github.io/unirest-java/#responses
String result = Unirest.get("http://some.json.com")
.asJson()
.getBody()
.getObject()
.getJSONObject("car")
.getJSONArray("wheels")
.get(0)
so, something like this should work for you:
def a = result.getBody().getObject().getJSONArray("value")
if(a.length()>0) _userId = a.get(0).get("id")

How to catch null value on http response

I have the following code method which is used to test for an existing user in MSGraph API
public String getGuestUserId(String AuthToken,String userEmail){
String _userId
def http = new HTTPBuilder(graph_base_user_url + "?")
http.request(GET) {
requestContentType = ContentType.JSON
//uri.query = [ $filter:"mail eq '$userEmail'"].toString()
uri.query=[$filter:"mail eq '$userEmail'"]
headers.'Authorization' = "Bearer " + AuthToken
response.success = { resp, json ->
//as the retunr json alue is an array collection we need to get the first element as we request all time one record from the filter
**_userId=json.value[0].id**
}
// user ID not found : error 404
response.'404' = { resp ->
_userId = 'Not Found'
}
}
_userId
}
This method works fine when the user is existing and will return properly from the success response the user ID property.
The issue I get is that if the user is not existing, the ID field is not existing either and the array is empty.
How can I handle efficiently that case and return a meaning full value to the caller like "User Does not exist"
I have try a catch exception in the response side but seems doe snot to work
Any idea how can I handle the test like if the array[0] is empty or does not contains any Id property, then return something back ?
Thanks for help
regards
It seems to be widely accepted practice not to catch NPE. Instead, one should check if something is null.
In your case:
You should check if json.value is not empty
You also should check if id is not null.
Please also note that handling exceptions in lambdas is always tricky.
You can change the code to:
http.request(GET) {
requestContentType = ContentType.JSON
uri.query=[$filter:"mail eq '$userEmail'"]
headers.'Authorization' = "Bearer " + AuthToken
if (json.value && json.value[0].id) {
response.success = { resp, json -> **_userId=json.value[0].id** }
} else {
// Here you can return generic error response, like the one below
// or consider more granular error reporting
response.'404' = { resp -> _userId = 'Not Found'}
}
}

SOAP UI - Return two different responses for two different POST Request Payloads for same REST API end point

I have a REST POST API end point - "abc/def".
It's request payload has (out of many other fields) a field "yourId" which can take either 1 or 2 as shown below:
{
"yourId":"1"
}
OR
{
"yourId":"2
}
On the basis of the value of "yourId", I need to return two different responses either 1. YOUR_RESPONSE_1 OR 2. YOUR_RESPONSE_2 for which I have written a groovy script as shown below:
def requestBody = mockRequest.getRequestContent()
log.info "Request body: " + requestBody
yourId="yourId"
id1="1"
id2="2"
if(requestBody.contains(yourId+":"+id1)){
return "YOUR_RESPONSE_1"
}else if(requestBody.contains(yourId+":"+id2)){
return "YOUR_RESPONSE_2"
}else return "ERROR_RESPONSE"
When I hit the end point "localhost:8080/abc/def" from postman, I get ERROR_RESPONSE. How can I fix it.
I would suggest you to use the JSONSlurper() as this avoids the use of escape characters and makes the script legible, Also it come in handy when the input JSON is complex
def requestBody = mockRequest.getRequestContent()
def parsedJson = new groovy.json.JsonSlurper().parseText(requestBody)
def ID = parsedJson.yourId
if(ID=="1"){
return "YOUR_RESPONSE_1"
}
else if(ID=="2"){
return "YOUR_RESPONSE_2"
}
else return "ERROR_RESPONSE"

How to print all assertion failure messages into HTML report of SoapUI

I am running test case and asserting data using groovy. I want to print each and every failed message to html junit generate report.
Example Code
import groovy.json.JsonSlurper
def ResponseMessage = messageExchange.response.responseContent
def jsonString = new JsonSlurper().parseText(ResponseMessage)
assert !(jsonString.isEmpty())
assert jsonString.code == 200
assert jsonString.status == "success"
def accountInfo = jsonString.data
assert !(accountInfo.isEmpty())
def inc=0
//CHECKING LANGUAGES IN RESPONSE
if(accountInfo.languages.id!=null)
{
log.info("Language added successfully")
}
else
{
log.info("Language NOT added.") //want to display this in html report
inc++
}
if(accountInfo.educations!=null)
{
log.info("Educations added successfully")
}
else
{
log.info("Educations NOT added.") //want to display this in html report
inc++
}
assert inc<=0,"API unable to return all parameters, Please check logs"
Scenario
What I am doing here is , IF test condition does not match and go to ELSE, I do increment of variable inc by 1. So at the end if fail my test if inc>0.
Report
In junit style html generated report, if test failed it display only one message called API unable to return all parameters, Please check logs
But what I want is to display each IF condition message into HTML report if for any condition goes into ELSE section.
Couple of pointers:
assert stops at first failure and only this failure message is part of junit report.
having said that, user will not know if there are any further verification failures for the current response.
the messages that are part of if..else are not part of junit report
in order to achieve that, need to collect all those messages and finally show the collected error messages.
below solution uses a variable, messages and appends each failure which allows to show them at the end. this way all failures can be shown in the report if that is desirable which OP requested for.
user can also show the messages in the report using below statement apart from assert statement
if (messages) throw new Error(messages.toString())
Script Assertion
import groovy.json.JsonSlurper
//check if the response is empty
assert context.response, 'Response is empty or null'
def jsonString = new JsonSlurper().parseText(context.response)
def messages = new StringBuffer()
jsonString.code == 200 ?: messages.append("Code does not match: actual[${jsonString.code}], expected[200]\n")
jsonString.status == "success" ?: messages.append("Status does not match: actual[${jsonString.status}], expected[success]\n")
def accountInfo = jsonString.data
accountInfo ?: messages.append('AccountInfo is empty or null\n')
def inc=0
//CHECKING LANGUAGES IN RESPONSE
if(accountInfo.languages.id) {
log.info('Language added successfully')
} else {
log.error('Language NOT added.') //want to display this in html report
messages.append('Language not added.\n')
inc++
}
if(accountInfo.educations) {
log.info('Educations added successfully')
} else {
log.error('Educations NOT added.') //want to display this in html report
messages.append('Educations NOT added.\n')
inc++
}
//inc<=0 ?: messages.append('API unable to return all parameters, Please check logs.')
//if(messages.toString()) throw new Error(messages.toString())
assert inc<=0, messages.append('API unable to return all parameters, Please check logs.').toString()

Resources