Karate 将部分对象与表数据匹配

Karate 将部分对象与表数据匹配,karate,Karate,我目前正在评估空手道作为我们自己的本土API测试的替代品。我有一个服务返回如下数据: { "items": [ { "id": "1", "enabled": true, "foo": 1, }, ... ], ... } 每个项目所属的属性具有不同的特性,我想分别测试它们 例如,为了测试项目启用,我想检查enabled属性

我目前正在评估空手道作为我们自己的本土API测试的替代品。我有一个服务返回如下数据:

{
  "items": [
    {
      "id": "1",
      "enabled": true,
      "foo": 1,
    },
    ...
  ],
  ...
}
每个项目所属的属性具有不同的特性,我想分别测试它们

例如,为了测试项目启用,我想检查
enabled
属性是否具有给定
id
的正确值

我试过这样设置它

Feature: Partial object matching
  Background:
    Given table items
    |id  |enabled|
    | '1'|true   |
    | '2'|true   |
    | '3'|false  |

  Scenario: match with all properties specified -- this passes
    * def response = { items: [ { id: '3', enabled: false }, { id: '1', enabled: true }, { id: '2', enabled: true } ] }
    * match $response.items contains only items


  Scenario: match with partial properties -- how can I make this pass (while also testing for something sensible)?
    * def response = { items: [ { id: '3', enabled: false, foo: 1 }, { id: '1', enabled: true, foo: 1 }, { id: '2', enabled: true, foo: 1 } ] }
    * match $response.items contains only items
真正的
对象相当粗,包含更多的属性和嵌套对象,我宁愿不指定完整的预期结构,因为它们与许多不同的功能相关,并且一些属性本质上是动态的


是否有一个优雅的
匹配
,或者我必须求助于脚本吗?

这似乎是正确的选择

Feature: Partial object matching
  Background:
    Given def filterTableKeys = read('filterTableKeys.js')
    Given table items
    |id  |enabled|
    | '1'|true   |
    | '2'|true   |
    | '3'|false  |

  Scenario: match with all attributes
    * def response = { items: [ { id: '3', enabled: false }, { id: '1', enabled: true }, { id: '2', enabled: true } ] }
    * match $response.items contains only items

  Scenario: match with partial attributes
    * def response = { items: [ { id: '3', enabled: false, foo: 1 }, { id: '1', enabled: true, foo: 1 }, { id: '2', enabled: true, foo: 1 } ] }
    * def responseItems = $response.items
    * def responseItems2 = filterTableKeys(responseItems, items)
    * match responseItems2 contains only items
其中,
filterTableKeys.js
定义为

function fn(items, table) {
    var mapper = function(v) { return karate.filterKeys(v, table[0]) }
    return karate.map(items, mapper)
}
不过,它感觉不太优雅,因此任何关于如何做得更具声明性/不那么强制性/更具“脚本性”的提示都将不胜感激


编辑

如下文所述,这似乎很有效

  Scenario: match with partial attributes
    * def response = { items: [ { id: '3', enabled: false, foo: 1 }, { id: '1', enabled: true, foo: 1 }, { id: '2', enabled: true, foo: 1 } ] }
    * match $response.items contains deep items

您可以尝试
*匹配$response.items包含深度项目
文档以供参考:-谢谢!成功了!