如何在数组中声明一个并不总是以响应形式返回的值

问题描述 投票:0回答:2

有点棘手,我将尝试尽可能清楚地解释它。

Schema:

    "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值。断言这种行为的最优雅方法是什么?我尝试了可选的断言,但似乎总是希望数组值存在。

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

karate
2个回答
0
投票

似乎我必须在数组级别而不是在数组内部的更深层次上执行断言。

功能文件应如下所示:


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


0
投票

示例代码:

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
© www.soinside.com 2019 - 2024. All rights reserved.