如何验证空手道 JSON 模式中的对象是空的还是包含一系列 key:value 对?

How to validate an object inside a JSON schema in Karate whether its empty or contains a series of key:value pairs?

我正在尝试使用空手道验证针对这两种状态之一的 API 响应。 场景 1(当它 returns 一个包含费用密钥的 contractData 对象时):

{
    "customer": {
        "financialData": {
            "totalAmount": 55736.51,
            "CreateDate": "2022-04-01",
            "RequestedBy": "user1@test.com"
        },
        "contractData": {
            "Fee": 78.00
        }
    }
}

场景 2(当它 returns 一个空的 contractData 对象时):

{
    "customer": {
        "financialData": {
            "totalAmount": 55736.51,
            "CreateDate": "2022-04-01",
            "RequestedBy": "user1@test.com"
        },
        "contractData": {}
    }
}

如何编写模式验证逻辑来​​验证这两种状态? 我能做的最好的事情就是这样写:

* def schema = {"customer":{"financialData":{"totalAmount":"#number","CreateDate":"#?isValidDate(_)","RequestedBy":"#string"},"contractData":{"Fee": ##number}}}
* match response == schema

而且它似乎适用于上述两种情况,但我不确定这是否是最佳方法。这种方法的问题是,如果我在“contractData”对象中有多个 key:value 对,并且我想确保所有这些键在它不为空时都存在,我无法通过这种方法检查它,因为对于每个单独的 key:value 对,此方法假定它们可能存在或不存在,并且即使存在其中一些键也会匹配模式。

哇,我不得不承认我从来没有遇到过这种情况,这说明了一些事情。我终于想出了一个可能的解决方案:

* def chunk = { foo: 'bar' }
* def valid = function(x){ return karate.match(x, {}).pass || karate.match(x, chunk).pass }
* def schema = { hey: '#? valid(_)' }
* def response1 = { hey: { foo: 'bar' } }
* def response2 = { hey: { } }
* match response1 == schema
* match response2 == schema