Home > Mobile >  How to validate an object inside a JSON schema in Karate whether its empty or contains a series of k
How to validate an object inside a JSON schema in Karate whether its empty or contains a series of k

Time:04-02

I am trying to validate an API response using Karate for either of these two states. Scenario 1 (when it returns a contractData object that contains a fee key):

{
    "customer": {
        "financialData": {
            "totalAmount": 55736.51,
            "CreateDate": "2022-04-01",
            "RequestedBy": "[email protected]"
        },
        "contractData": {
            "Fee": 78.00
        }
    }
}

Scenario 2 (when it returns an empty contractData object):

{
    "customer": {
        "financialData": {
            "totalAmount": 55736.51,
            "CreateDate": "2022-04-01",
            "RequestedBy": "[email protected]"
        },
        "contractData": {}
    }
}

How can I write my schema validation logic to validate both states? The best thing I could have done is to write it like this:

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

And it seems like it works for both above scenarios, but I am not sure whether this is the best approach or not. Problem with this approach is if I have more than one key:value pair inside "contractData" object and I want to be sure all those keys are present in there when it is not empty, I cannot check it via this approach because for each individual key:value pair, this approach assumes that they could either be present or not and will match the schema even if some of those keys will be present.

CodePudding user response:

Wow, I have to admit I've never come across this case ever, and that's saying something. I finally was able to figure out a possible solution:

* 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
  • Related