将部分对象与 table 数据匹配

Matching partial objects to table data

我目前正在评估空手道作为我们自己开发的 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

真正的 item 对象相当多块,包含更多属性和嵌套对象,我宁愿不指定完整的预期结构,因为它们涉及许多不同的功能,并且一些属性本质上是动态的.

是否有优雅的 match 来执行此操作,还是我必须求助于脚本?

这似乎是对的;

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)
}

虽然它感觉不是很优雅,所以任何关于如何更好地完成它的提示 declarative/less 命令式/“脚本”将不胜感激。


编辑

如下 所述,这似乎工作得很好

  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