首页 文章

如何使用if条件检查其他值(使用空手道框架)?

提问于
浏览
1

我想用json架构检查来自GET / birds请求的响应 . 在我的功能:

* def abs = read (birds.json)
* match response == abs.birdsSchema

我需要将模式放在json文件中,而不是在功能中 . 我必须根据性别检查其他值 . 例如:如果性别是男性,则检查颜色是否为蓝色,尾巴是长还是短 . 如果性别是女性,那么检查“唱歌”是真还是假,以及鸡蛋的数量 .

所以我放入了birds.json:

"birdsSchema":{
    "id": "#string",
    "owner": "#number",
    "town": "#? _ == 'New York' || _ == 'Washington'",
    "type": "object",
    "oneOf": [
        {
            "properties": {
                "gender": {"enum": ["male"]},
                "color":"blue",
                "tail": "#? _ == 'long' || _ == 'short'"
            }
        },
        {
            "properties": {
                "gender": {"enum": ["female"]},
                "sings" : "#? _ == true || _ == false"
                "eggs": "##number"
            }
        }
    ]
}

但它不起作用 . 错误:com.intuit.karate.exception.KarateException:path:$ [0] .type,actual:'female',expected:'object',reason:not equal . 我如何在我的json文件中执行此条件检查?

1 回答

  • 2

    让我们承认这是非常困难的,因为如果我理解你的问题,你正在寻找的JSON键是动态的 .

    空手道的部分乐趣在于我至少有5种不同的方式来优雅地解决这个问题 . 这里只有一个:

    * def response = { color: 'black', aaa: 'foo' }
    
    * def schema = { color: '#? _ == "black" || _ == "white"' }
    * def extra = (response.color == 'black' ? { aaa: '#string' } : { fff: '#string' })
    
    * match response contains schema
    * match response contains extra
    

    如果你根据上面的提示创建一个JS函数,你可能会得到一个更好的解决方案 . 请记住,在JS函数中,您可以使用 karate.set 之类的方法来动态创建密钥 . 所以有很多可能性:)

    编辑:看起来上面的示例是错误的,并且键不是动态的 . 然后很容易,请记住 $ 指的是JSON根目录:

    * def response = { color: 'black', extra: 'foo' }    
    * def schema = { color: '#? _ == "black" || _ == "white"', extra: '#($.color == "black" ? "foo" : "bar")' }    
    * match response == schema
    

相关问题