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

时间:2018-01-15 15:12:16

标签: javascript arrays jsonpath karate

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

这个系列有两个部分,因为前六个部分与其余部分分开排序。 e.g。

  • 鲍勃
  • 伊迪丝
  • 埃格伯
  • 的NiAl
  • 西蒙
  • 萨莎
  • 亚伦
  • 伯莎
  • 查理

我可以使用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')。但排序仍然是一个问题。我编辑了功能文件以反映这一点。

1 个答案:

答案 0 :(得分:1)

首先,在eval之后引入0.7.0,我对文档进行修订表示歉意。我建议您使用版本0.7.0.RC4,该版本在本文发布时可用。

好问题!我认为这是一个潜入Java的情况。好消息是你可以做到这一点,因为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"
]

编辑:针对不区分大小写进行了更新