使用 JsonPath 和 karate.eval 在空手道中进行数组排序和匹配

Array sorting and matching in Karate using JsonPath and karate.eval

我正在尝试验证返回的集合是否按字母顺序排列。

虽然这个集合有两个部分,因为前六个与其余部分分开排序。例如

我可以使用 JsonPath 对前六个进行硬编码并进行简单匹配,但我不确定如何匹配其余部分(有很多,并且数据集可以更改)。

这是我的功能文件:

Feature: Array should be sorted alphabetically, with the first important 6 sorted separately

  Background:
    * call read('common-config.feature')

  @wip
  Scenario: I request brand options by region
    Given url baseUrl
    And path '/importantEmployees'
    When method GET
    Then status 200

    # match first six
    And def importantSix = $..employees[0:6]
    And def importantSixNames = get importantSix[*].name
    And match importantSixNames == [ 'Bob', 'Edith', 'Egbert', 'Nial', 'Simone', 'Sasha' ]

    # match the rest to a sorted array
    And def otherPeople = $..employees[6:]
    And def otherPeopleNames = get otherPeople[*].name
    And eval
    """
    var sortedOtherPeopleNames = karate.get('otherPeopleNames').sort();
    karate.set('sortedOtherPeopleNames', sortedOtherPeopleNames);
    """
    And match otherPeopleNames == sortedOtherPeopleNames

我尝试按照使用 eval 调用的示例进行操作,但无法正常工作。

https://github.com/intuit/karate#eval

编辑:我发现了如何在 Javascript 和空手道特征文件之间共享变量。我需要在 Javascript 中使用 karate.get('varName')。排序仍然是一个问题。我已经编辑了功能文件以反映这一点。

首先,eval 是在 0.7.0 之后引入的,很抱歉,文档正在修改中。我建议您使用本 post.

时可用的版本 0.7.0.RC4

好问题!我认为在这种情况下,深入研究 Java 是有道理的。好消息是您可以 'as JS' 自己完成。下面的代码使用了 eval 关键字,但是如果您无法升级,您应该能够找到一种使用您已经知道的 JS 函数的方法。

* def ArrayList = Java.type('java.util.ArrayList')
* def Collections = Java.type('java.util.Collections')

* def json = [{ v: 'C' }, { v: 'b' }, { v: 'A' }]
* def actual = $json[*].v
* print actual
* def list = new ArrayList()
* eval for(var i = 0; i < actual.length; i++) list.add(actual[i])
* print list
* eval Collections.sort(list, java.lang.String.CASE_INSENSITIVE_ORDER)
* print list
* match list != actual
* match list == ['A', 'b', 'C']

这是 3 个 print 语句的输出:

21:59:34.211 [main] INFO  com.intuit.karate - [print] [
  "C",
  "b",
  "A"
]

21:59:34.241 [main] INFO  com.intuit.karate - [print] [
  "C",
  "b",
  "A"
]

21:59:34.273 [main] INFO  com.intuit.karate - [print] [
  "A",
  "b",
  "C"
]

编辑:更新为不区分大小写