【问题标题】:How to check additional values with if condition (using karate framework)?如何使用 if 条件检查附加值(使用空手道框架)?
【发布时间】:2018-03-22 00:34:13
【问题描述】:

我想使用 json 模式检查来自 GET/birds 请求的响应。在我的功能中:

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

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

所以我输入了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:路径:$[0].type,实际:'female',预期:'object',原因:不相等。 如何在我的 json 文件中进行此条件检查?

【问题讨论】:

    标签: json jsonschema karate jsonschema2pojo


    【解决方案1】:

    让我们承认这非常困难,因为如果我正确理解您的问题,那么您正在寻找的 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 之类的方法来动态创建键。所以有很多可能性:)

    edit:看起来上面的例子是错误的,键是 not 动态的。那么就很简单了,记住$指的是JSON根:

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

    【讨论】:

    • 感谢您的快速回复。感谢空手道官方教程,我知道如何在功能中执行此操作,但我想在 json 文件中执行此操作。这个想法是只有一个带有轮子模式的 json 文件,并且不同的功能将在响应验证中使用它。我如何在 json 文件中做同样的事情?
    • JSON 键不是动态的
    • 请问您能帮我们吗?我编辑了问题以使其更容易理解
    • 我认为您的编辑让您更难理解:P 您的预期行为是什么?空手道不支持“oneOf”,以防这是您所期望的。换句话说,空手道不直接支持 JSON 模式。如果您想通过 Java 库使用 JSON 模式,请查看此示例:github.com/intuit/karate/blob/master/karate-demo/src/test/java/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-09-26
    • 1970-01-01
    • 2018-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多