what is the easiest way to validate that an array

2019-08-07 11:29发布

问题:

I am testing a user search endpoint using karate. It receives a simple json object:

{
  "status" : ['ACTIVE', 'INACTIVE'],
  "activeDate" : '2017-11-27T17:51:13Z'
}

The result is a list of users created after the 'activeDate' with status ACTIVE or INACTIVE:

[ {
"name" : 'mike',
"status" : 'ACTIVE',
"date" : '2018-06-08T17:45:09Z'
},{
"name" : 'alice',
"status" : 'INACTIVE',
"date" : '2018-02-05T07:32:14Z'
}]

I'd like to ask your help to find the best way to assert the following conditions for each result:

  • The "status" string result is one of the status I've filtered.
  • The "date" is after the date I've filtered.

I thought It was possible to do it with a simple match each contains any but it doesn't work because one of the params is not an array (it's a simple string). Something similar happen with the other assert.

The only solution I've found is to create a generic javascript function which receives two params, an array of all status (from the response) and another array with the status seach filter. Then I can use this functions in a * assert step

I am sure there is a simpler solution to do it, but I can't figure out how to do it. Could anyone help me? Thanks a lot.

回答1:

Here you go:

* def payload = { "status" : ['ACTIVE', 'INACTIVE'], "activeDate" : '2017-11-27T17:51:13Z' }
* def response = 
"""
[
   {
      "name":"mike",
      "status":"ACTIVE",
      "date":"2017-11-27T17:51:13Z"
   },
   {
      "name":"alice",
      "status":"INACTIVE",
      "date":"2017-11-27T17:51:13Z"
   }
]
"""
* match response[*].status contains only payload.status
* match each response..date == payload.activeDate

Tip: get familiar with JsonPath ! It really helps for these cases.

I'm leaving the date validation as a homework for you, you may need to do some string to date conversion, refer this answer: https://stackoverflow.com/a/52892797/143475



标签: karate