空手道框架重试,直到无法按预期工作

ita*_*ind 2 karate

我在 JUnit 中使用空手道框架。

使用此功能:

Given path 'save_token'
And request
"""
{
  "token": "test_token"
}
"""
And retry until response.tokens ==
"""
[
    "test_token"
]
"""
When method POST
Run Code Online (Sandbox Code Playgroud)

我有这个例外:

java.lang.ArrayIndexOutOfBoundsException: 1
    at com.intuit.karate.core.MethodMatch.convertArgs(MethodMatch.java:60)
    at com.intuit.karate.core.Engine.executeStep(Engine.java:141)
    at com.intuit.karate.core.ScenarioExecutionUnit.execute(ScenarioExecutionUnit.java:171)
Run Code Online (Sandbox Code Playgroud)

当 response.tokens 列表为空时:

{
    "tokens": []
}
Run Code Online (Sandbox Code Playgroud)

我不明白为什么 == 在这种情况下不起作用(它应该返回 false,并继续重试)。

提前致谢!

Pet*_*mas 10

retry until表达式必须是纯JavaScript和特殊空手道匹配关键字,例如contains不支持,你不能做一个“深等于”像你如何努力,因为这同样是不可能的JS。

编辑:在 0.9.6 中。以后你可以match在 JS 中做一个复杂的:https : //stackoverflow.com/a/50350442/143475

还要注意,支持JsonPath ,这意味着*..不能出现在表达式中。

所以如果你的回答是{ "tokens": [ "value1" ] },你可以这样做:

And retry until response.tokens.contains('value1')
Run Code Online (Sandbox Code Playgroud)

或者:

And retry until response.tokens[0] == 'value1'
Run Code Online (Sandbox Code Playgroud)

要进行实验,您可以尝试这样的表达式:

* def response = { "tokens": [ "value1" ] }
* assert response.tokens.contains('value1')
Run Code Online (Sandbox Code Playgroud)

在运行时,您可以使用 JS 来处理轮询时响应尚未准备好的情况:

And retry until response.tokens && response.tokens.length
Run Code Online (Sandbox Code Playgroud)

编辑:实际上,一种更优雅的方式来执行上述操作如下所示,因为karate.get()优雅地处理 JS 或 JsonPath 评估失败并返回null

And retry until karate.get('response.tokens.length')
Run Code Online (Sandbox Code Playgroud)

或者,如果您正在处理 XML,则可以使用karate.xmlPath()API:

And retry until karate.xmlPath(response, '//result') == 5
Run Code Online (Sandbox Code Playgroud)

如果你真的想使用 Karatematch语法的强大功能,你可以使用JS API

And retry until karate.match(response, { tokens: '##[_ > 0]' }).pass
Run Code Online (Sandbox Code Playgroud)

请注意,如果您有更复杂的逻辑,您可以随时将其包装成一个可重用的函数:

* def isValid = function(x){ return karate.match(x, { tokens: '##[_ > 0]' }).pass }
# ...
And retry until isValid(response)
Run Code Online (Sandbox Code Playgroud)

最后,如果上述方法均无效,您可以随时切换到自定义轮询例程: polling.feature

编辑:另请参阅此答案,了解如何使用karate.filter()代替 JsonPath 的示例:https ://stackoverflow.com/a/60537602/143475

编辑:从 0.9.6 版本开始,空手道可以match在 JS 中做一个,这可以简化上面的一些:https : //stackoverflow.com/a/50350442/143475