如何在数组中声明一个并不总是返回值的值

时间:2019-11-06 12:36:29

标签: karate

有些棘手的问题,我将尽力解释清楚。

架构:

    "dogs": {
        "dogId": "string",
        "breed": [
            {
                "canaan": true,
                "akita": false
            }
        ]
    }
}

回复:

{
    "dogs": {
        "dogId": "70872490",
        "breed": []
    }
}

功能文件:

[...] 

    And match each response.dogs contains
"""
    {
        "dogId": "##regex ^[0-9A-Za-z]*$",
        "breed": [
            {
                "canaan": "##boolean",
                "akita": "##boolean"
            }
        ]
    }
"""

错误:

path: $[0].breed[*], actual: [], expected: {canaan=##string, akita=##string}, reason: actual value does not contain expected

从上面您可以看到,breed数组有时不返回任何值,有时甚至不返回任何值,该数组可能填充了canaanakita价值观。断言这种行为的最优雅方法是什么?我尝试了可选断言,但似乎总是希望数组值存在。

让我知道您的想法,感谢您的支持。谢谢!

1 个答案:

答案 0 :(得分:1)

示例代码:

Feature: Validation

    Scenario:
        * def isValid = function(x){ return x == "[]" || karate.match(x,karate.valuesOf([{"canaan":"#boolean","akita":"#boolean"}])).pass }    
        * def schema =
            """
            {
                "dogs": {
                        "dogId": "##regex ^[0-9A-Za-z]*$",
                        "breed": '#? isValid(_)'
                }
            }
            """         
        * def resp1 =
        """
            {
                "dogs": {
                    "dogId": "70872490",
                    "breed": []
                }
            }
        """
        * def resp2 =
        """
            {
                "dogs": {
                    "dogId": "70872490",
                    "breed": [
                            {
                                "canaan": true,
                                "akita": false
                            }
                        ]
                }
            }
        """
        * match resp1 == schema
        * match resp2 == schema