gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 20:50:12 29 4
gpt4 key购买 nike

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

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

  • 鲍勃
  • 伊迪丝
  • 埃格伯特
  • 尼尔
  • 西蒙
  • 萨莎
  • 亚伦
  • 伯莎
  • 查理
  • 等等

我可以使用 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 和 Karate Feature 文件之间共享变量。我需要在 Javascript 中使用 karate.get('varName')。排序仍然是一个问题。我已经编辑了功能文件以反射(reflect)这一点。

最佳答案

首先,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"
]

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

关于javascript - 使用 JsonPath 和 karate.eval 在 Karate 中进行数组排序和匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48265698/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com