代码之家  ›  专栏  ›  技术社区  ›  matthewh86

使用JsonPath和空手道在空手道中进行数组排序和匹配。评估

  •  1
  • matthewh86  · 技术社区  · 7 年前

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

    尽管如此,本系列共有两部分,因为前六部分与其余部分是分开排序的。例如

    • 上下快速移动
    • 埃格伯特
    • 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

    1 回复  |  直到 7 年前
        1
  •  1
  •   Peter Thomas    7 年前

    第一 eval 于中引入 0.7.0 很抱歉,文件正在修改中。我建议您使用版本0.7.0。RC4,在本帖发布时可用。

    好问题!我认为在这种情况下,深入Java是有意义的。好消息是,您可以“作为JS”自己来做这件事。下面的代码使用 评估 关键字,但如果您无法升级,您应该能够找到一种使用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"
    ]
    

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