Parsing child nodes of JSON response in SOAP UI using groovy json slurper - groovy

I am getting a JSON response from an webservice like below . I want to parse all childs of results node using Groovy Json slurper and assert the value is correct.
{
"status": "Healthy",
"results": [
{
"name": "Microservice one",
"status": "Healthy",
"description": "Url check MSOneURI success : status(OK)"
},
{
"name": "Microservice two",
"status": "Healthy",
"description": "Url check MSTwoURI success : status(OK)"
},
{
"name": "Microservice three",
"status": "Healthy",
"description": "Url check MSThreeURI success : status(OK)"
},
{
"name": "Microservice four",
"status": "Healthy",
"description": "Url check MSFourURI success : status(OK)"
},
{
"name": "Microservice five",
"status": "Healthy",
"description": "Url check MSFiveURI success : status(OK)"
}
]
}
This is what I have done - this works .
//imports
import groovy.json.JsonSlurper
import groovy.json.*
//grab the response
def ResponseMessage = messageExchange.response.responseContent
// trim starting and ending double quotes
def TrimResponse =ResponseMessage.replaceAll('^\"|\"$','').replaceAll('/\\/','')
//define a JsonSlurper
def jsonSlurper = new JsonSlurper().parseText(TrimResponse)
//verify the response to be validated isn't empty
assert !(jsonSlurper.isEmpty())
//verify the Json response Shows Correct Values
assert jsonSlurper.status == "Healthy"
def ActualMsNames = jsonSlurper.results*.name.toString()
def ActualMsStatus = jsonSlurper.results*.status.toString()
def ActualMsDescription = jsonSlurper.results*.description.toString()
def ExpectedMsNames = "[Microservice one,Microservice two,Microservice three,Microservice four,Microservice five]"
def ExpectedMsStatus = "[Healthy, Healthy, Healthy, Healthy, Healthy]"
def ExpectedMsDescription = "[Url check MSOneURI success : status(OK),Url check MSTwoURI success : status(OK),Url check MSThreeURI success : status(OK),Url check MSFourURI success : status(OK),Url check MSFiveURI success : status(OK)]"
assert ActualMsNames==ExpectedMsNames
assert ActualMsStatus==ExpectedMsStatus
assert ActualMsDescription==ExpectedMsDescription
But I want to make it better using some kind of for loop which will parse each collection one at a time and assert the value of "name", "status" and "descriptions" at once for each child
Is that possible?

Yes, that's certainly possible.
Without knowing more about your actual data it's not possible to give a perfect example, but you could do something like:
jsonSlurper.results?.eachWithIndex { result, i ->
assert result.name == expectedNames[i]
assert result.status == expectedStatus[i] // or just "Healthy" if that's the only one
assert result.description == expectedDescriptions[i]
}
where expectedWhatever is a list of expected result fields. If your expected results really are based on index like in your example, then you could even calculate them within the loop, but I'm guessing that's not the case for real data.

Related

How to extract two value from json under one condition and randomize it in jmeter?

Below is the server response in a JSON format which I need to work on, In this JSON some of the objects I need to pass in the next request, which I am successfully able to do for the first occurrence, but the problem is coming on randomization in the below JSON
{
"store": {
"book": [
{
"category": "reference",
"author": "Nigel Rees",
"title": "Sword of Honour",
"price": 8.95
},
{
"category": "fiction",
"author": "Evelyn Waugh",
"title": "test_title",
"price": 12.99
},
{
"category": "fiction",
"author": "Herman Melville",
"title": "Sword of Honour",
"isbn": "0-553-21311-3",
"price": 8.99
},
{
"category": "fiction",
"author": "J. R. R. Tolkien",
"title": "India",
"isbn": "0-395-19395-8",
"price": 22.99
}
],
"bicycle": {
"color": "red",
"price": 19.95
}
},
"expensive": 10
}
if I apply $..book[0][?(#.title == 'Sword of Honour')] condition I am seeing successful output
test_1={"category":"reference","title":"Sword of Honour","author":"Nigel Rees","price":8.95}
test_2={"category":"fiction","title":"Sword of Honour","author":"Herman Melville","price":8.99,"isbn":"0-553-21311-3"}
if I apply $..book[0][?(#.title == 'Sword of Honour')].author condition I am seeing successful output
test_1=Nigel Rees
test_2=Herman Melville
But I want to extract both author's name and price for the book that has the title == 'Sword of Honour'
Actual output = able to retrieve one value with the condition $..book[0][?(#.title == 'Sword of Honour')].author
Expected output = I want to receive two values from the same list randomly. and it should look like this
Iteration 1-
test_1={"author":"Nigel Rees","price":8.95}
Iteration 2-
test_2={"author":"Herman Melville","price":8.99,}
Iteration 3-
test_2={"author":"Herman Melville","price":8.99,}
I had tried with the V function as well but got only one value. (book{__V([?(#.title == 'Sword of Honour')]_${__Random(1,${title_matchNr},)},)})
Add JSR223 PostProcessor as a child of the request which returns the above JSON
Put the following code into "Script" area:
def swords = new groovy.json.JsonSlurper().parse(prev.getResponseData()).store.book.findAll { book -> book.title == 'Sword of Honour' }
swords.eachWithIndex { def sword, int index ->
def payload = [:]
payload.put('author', sword.author)
payload.put('price', sword.price)
vars.put('test_' + (index + 1), new groovy.json.JsonBuilder(payload).toPrettyString())
}
vars.put('test_matchNr', swords.size() as String)
Now you should be able to refer random author/price pair using __V() and __Random() functions combination like: ${__V(test_${__Random(1,${test_matchNr},)},)}
More information:
Apache Groovy - Parsing and producing JSON
Apache Groovy: What Is Groovy Used For?

How to iterate through each property element in API response in Katalon studio?

I'm writing test script in katalon studio to verify response body of the API.My response body is of format:
{
"status": "Success",
"correlationCode": "1234-5678",
"type": {
"id": 51247,
"name": "Student",
},
"data": {
"name": "Sara Nieves",
"gender": "Female",
"dob": "1995-08-06",
"libraryCard": {
"id": "11178",
"type": "Seniors"
},
"qualifications": [
{
"id": "45650986546",
"name": "Graduate Certificate in Environmental Engineering Management"
}
]
}
}
I want to verify that none of the elements return 'null' value. Since, the elements returned for the API response are not static(meaning name, gender etc might not get returned every time) therefore, i can't use something like "data.name" to verify if it has null value. So, i want a generic way to loop through each and every attribute returned and check if its value is returned as null or not.
Any help will be much appreciated. Thanks!
You have the error message:
groovy.lang.MissingMethodException: No signature of method: WSVerification1569811424284$_run_closure1.doCall() is applicable for argument types: (com.kms.katalon.core.testobject.ResponseObject) values: [200 1 KB] 22572.groovy:21)
I assume your response object type: com.kms.katalon.core.testobject.ResponseObject
The code to parse response as json and validate it:
import groovy.json.JsonSlurper
/**
* the recursive method to validate that json object does not have null values
* #param obj - the parsed json object (sequence of maps and lists)
* #param path - a variable to know where the error occurred in json data.
*/
void assertNoNullValue(Object obj, String path='ROOT'){
//the main assertion
assert obj!=null : "value in json could not be null: $path"
if(obj instanceof Map){
//iterate each key-value in map and validate the value recursively
obj.each{k,v-> assertNoNullValue(v,path+".$k") }
} else if(obj instanceof List){
//iterate each value in list and validate the value recursively
obj.eachWithIndex{v,i-> assertNoNullValue(v,path+"[$i]") }
}
}
def response = ...
assert response.isJsonContentType()
def responseText = response.getResponseText()
//parse body
def data = new JsonSlurper().parseText(responseText)
assertNoNullValue(data)
This solution is not as precise as the one suggested by #dagget, but it is a quick check:
def response = '''
{
"status": "Success",
"correlationCode": "1234-5678",
"type": {
"id": 51247,
"name": "Student",
},
"data": {
"name": "Sara Nieves",
"gender": "femmina",
"dob": "1995-08-06",
"libraryCard": {
"id": "11178",
"type": "Seniors"
},
"qualifications": [
{
"id": "45650986546",
"name": "Graduate Certificate in Environmental Engineering Management"
}
]
}
}
'''
assert !response.contains("null")

How to fix "error": "'parameter_name'" when using IBM Cloud Function's REST API?

I have an action in IBM Cloud Functions that only receives one parameter: "frame". I'm using Postman to test the REST API endpoint provided with the action. However, when I provide the "frame" parameter it returns the following:
"response": {
"result": {
"error": "'frame'"
},
"status": "application error",
"success": false
}
I've experienced this problem when I invoke this action in the IBM Cloud Functions' console. I resolve it by erasing a space in the input modal and adding it again, then it works like a charm in the console. However, I can't do the same thing with an HTTP request.
The way I'm currently doing the HTTP request is like this:
POST https://us-south.functions.cloud.ibm.com/api/v1/namespaces/{namespace}/actions/{action_name}?blocking=true&frame={value}
The action should return the result I'm expecting but it doesn't do that right now. Please help me, any answers would be great!
EDIT:
This is the action's code:
import requests, base64, json, cv2
from PIL import Image
from six import BytesIO
def json_to_dict(json_str):
return json.loads(json.dumps(json_str))
def frame_to_bytes(frame):
frame_im = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
pil_im = Image.fromarray(frame_im)
stream = BytesIO()
pil_im.save(stream, format="JPEG")
stream.seek(0)
img_for_post = stream.read()
img_base64 = base64.b64encode(img_for_post)
return img_base64
def main(dict):
cap = cv2.VideoCapture(dict['frame'])
if not cap.isOpened():
return { "error": "Unable to open video source" }
ret, frame = cap.read()
if ret is False:
return { "error": "Unable to read video source" }
# openALPR API part
OPENALPR_SECRET_KEY = {my_secret_key}
url = "https://api.openalpr.com/v2/recognize_bytes?recognize_vehicle=1&country=us&secret_key=%s" % (
OPENALPR_SECRET_KEY)
r = requests.post(url, data=frame_to_bytes(frame))
resp = json_to_dict(r.json())
print(resp)
if not resp['results']:
return { "error": "Plate number not recognized" }
plates = []
for plate in resp['results']:
if plate['confidence'] < 75:
pass
else:
print(plate['plate'])
plates.append(plate['plate'])
return { "plates": plates }
This is the activation response (the status returned was 502 Bad Gateway according to Postman):
{
"activationId": "5a83396b9f53447483396b9f53e47452",
"annotations": [
{
"key": "path",
"value": "{namespace}/{name}"
},
{
"key": "waitTime",
"value": 5531
},
{
"key": "kind",
"value": "python:3.7"
},
{
"key": "timeout",
"value": false
},
{
"key": "limits",
"value": {
"concurrency": 1,
"logs": 10,
"memory": 1024,
"timeout": 60000
}
},
{
"key": "initTime",
"value": 3226
}
],
"duration": 3596,
"end": 1560669652454,
"logs": [],
"name": "{name}",
"namespace": "{namesapce}",
"publish": false,
"response": {
"result": {
"error": "'frame'"
},
"status": "application error",
"success": false
},
"start": 1560669648858,
"subject": "{my_email}",
"version": "0.0.7"
}
EDIT 2:
I've also tried to enable it as a web action to see if it changes anything. However, it's no use. When I use this HTTP request:
https://us-south.functions.cloud.ibm.com/api/v1/web/{namespace}/default/{action_name}?frame={value}
I get:
{
"code": "e1c36666f4db1884c48f028ef58243fc",
"error": "Response is not valid 'message/http'."
}
which is understandable since what my functions returns is json. However, when I use this HTTP request:
https://us-south.functions.cloud.ibm.com/api/v1/web/{namespace}/default/{action_name}.json?frame={value}
I get:
{
"code": "010fc0efaa29f96b47f92735ff763f50",
"error": "Response is not valid 'application/json'."
}
I really don't know what to do here
After googling a bit I found something that works for me right now although it might not work for everyone. Apache has a python "client" example for using an action's REST API which uses the requests library.
Thing is that in order to use it you need to provide your API KEY, which I don't know how to get by any other means than getting it directly from the IBM Cloud CLI. Since I'm trying to access the function from a web server, I would need to save the key in an environment variable or save it in a text file and access it from there or install the CLI on the server, login with my credentials and call ibmcloud wsk property get --auth.
Also, this method didn't work with the web action endpoint when I tried it.

Create an object that has a key where the value is an array

Basically, I want to somehow create a JSON object from a Groovy object. The Groovy object has key value pairs, and one of the values is a Groovy Array:
import groovy.json.*
// Imagine "handler" gets called somehow and an event gets passed to it.
def handler(event) {
def capabilitiesList = event.device.capabilities.findAll { attr -> attr.name != null }
def json = new JsonBuilder({
id event.deviceId
displayName event.displayName
value event.value
})
}
log.debug capabilitiesList
log.debug json.toPrettyString()
At this point, json.toPrettyString() gives me this:
{
"id": "asdfl469934623sdglsi3aqaq",
"displayName": "Some Lightbulb",
"value": "on"
}
And capabilitiesList gives me this:
["Test 1", "Test 2", "Test 3"]
How can I add the capabilitiesList array to the Groovy object so it gets converted to JSON?
I can't seem to get anything to work; the only thing that does work is this:
// ...
def json = new JsonBuilder({
id event.deviceId
displayName event.displayName
value event.value
capabilitiesList "Test 1", "Test 2", "Test 3"
})
// ...
Which gives me this (correct) JSON output:
{
"id": "asdfl469934623sdglsi3aqaq",
"displayName": "Some Lightbulb",
"value": "on",
"capabilitiesList": ["Test 1", "Test 2", "Test 3"]
}
But that obviously isn't useful because it's hard coded. So I tried referencing the Array directly like this:
// ...
def capabilitiesList = event.device.capabilities.findAll { attr -> attr.name != null }
def json = new JsonBuilder({
id event.deviceId
displayName event.displayName
value event.value
capabilitiesList capabilitiesList
})
// ...
But that breaks the JsonBuilder somehow, and it doesn't output anything.
I'm probably doing something really silly here but I can't quite figure out how to get this done. First time with Groovy as well. Thanks for the help!
Using the builder DSL should work. For example:
List list = ['Test1', 'Test2', 'Test3']
def builder = new groovy.json.JsonBuilder()
builder {
id "asdfl469934623sdglsi3aqaq"
displayName "Some Lightbulb"
value "on"
capabilitiesList list
}
println builder.toPrettyString()
prints
{
"id": "asdfl469934623sdglsi3aqaq",
"displayName": "Some Lightbulb",
"value": "on",
"capabilitiesList": [
"Test1",
"Test2",
"Test3"
]
}

How to get data from json format using groovy?

i have a request in soapui which returns a json response.
i'm using groovy to retrieve the content of the response.
response :
<item><response>{
"timestamp": "2016-04-01T16:40:34",
"data": [
{
"deleted_at": null,
"userid": "b6d66002-8da4-4c03-928c-46871f084fb8",
"updated_by": null,
"created_at": "2016-03-01T16:40:34",
"updated_at": "2016-03-01T16:40:34",
"created_by": null,
"value": "hBeO",
"setting": "test",
"name": "test2"
}
],
"success": true
}</response></item>
From this response i want to retrieve each node like:
deleted_at
created_at
so i use this groovy
import groovy.json.JsonSlurper
def response = context.expand( '${set_settings#Response#declare namespace ns1=\'https://wato.io/ns/20160131\'; //ns1:set_settings_resp[1]/ns1:item[1]/ns1:response[1]}' )
def slurper = new JsonSlurper()
def result = slurper.parseText(response)
testRunner.testCase.setPropertyValue("user_id", result.data.userid)
and i receive this error message:
groovy.lang.MissingMethodException: No signature of method: com.eviware.soapui.impl.wsdl.WsdlTestCasePro.setPropertyValue() is applicable for argument types: (java.lang.String, java.util.ArrayList) values: [userid, [b6df6662-8da4-4c03-928c-46871f084fb8]] Possible solutions: setPropertyValue(java.lang.String, java.lang.String), getPropertyValue(java.lang.String) error at line: 8
It works only for timestamp node.
any help please.
Thank you
It's because result.data is a list, so it returns a list (containing one item) for userid
You need to just get the first item from the list, so try:
testRunner.testCase.setPropertyValue("user_id", result.data.userid.head())

Resources