Karate: Can I iterate on a Json array response and do some conditional statements

我与影子孤独终老i 提交于 2020-07-09 11:58:10

问题


My json array response is something like below:

response = [
{
"ID": "123",
"Name":"Test1",
"Data":{
      "Status":"Red",
      "Message":"user not valid",
      "Code": "ERROR-P1"
      }
},
{
"ID": "143",
"Name":"Test2",
"Data":{
      "Status":"Amber",
      "Message":"user data missing",
      "Code": "ERROR-P2"
      }
},
{
"ID": "133",
"Name":"Test3",
"Data":{
      "Status":"Green",
      "Message":"",
      "Code": ""
      }
}

There could be more entries in the json array with same data and status. My use case is to check, based on a condition that if my json array has Status as Red or Amber, then message and code is not empty and similarly if my status is Green then message and code is empty. I need to iterate to the entire array and validate this scenario. And also need to get a count of Status: Red, Amber and Greens from the Array Json response. What could be the best possible solution with karate? Any help would be appreciated. Thank you


回答1:


Here you go:

* def red = []
* def amber = []
* def green = []
* def fun = 
"""
function(x){ 
  if (x.Data.Status == 'Red') karate.appendTo(red, x);
  if (x.Data.Status == 'Amber') karate.appendTo(amber, x);
  if (x.Data.Status == 'Green') karate.appendTo(green, x);
}
"""
* karate.forEach(response, fun)
* assert red.length == 1
* match each red..Message == 'user not valid'
* match each amber contains { Data: { Status: 'Amber', Message: 'user data missing', Code: 'ERROR-P2' } }


来源:https://stackoverflow.com/questions/62564511/karate-can-i-iterate-on-a-json-array-response-and-do-some-conditional-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!