1

I am just wondering how can I do conditional schema validation. The API response is dynamic based on customerType key. If customerType is person then, person details will be included and if the customerType is org organization details will be included in the JSON response. So the response can be in either of the following forms

{
    "customerType" : "person",
    "person" : {
        "fistName" : "A",
        "lastName" : "B"
    },
    "id" : 1,
    "requestDate" : "2021-11-11"
}

{
    "customerType" : "org",
    "organization" : {
        "orgName" : "A",
        "orgAddress" : "B"
    },
    "id" : 2,
    "requestDate" : "2021-11-11"
}

The schema I created to validate above 2 scenario is as follows

{
    "customerType" : "#string",
    "organization" : "#? response.customerType=='org' ? karate.match(_,personSchema) : karate.match(_,null)",
    "person" : "#? response.customerType=='person' ? karate.match(_,orgSchema) : karate.match(_,null)",
    "id" : "#number",
    "requestDate" : "#string"
}

but the schema fails to match with the actual response. What changes should I make in the schema to make it work?

Note : I am planning to reuse the schema in multiple tests so I will be keeping the schema in separate files, independent of the feature file
stackoverflow
  • 2,134
  • 3
  • 19
  • 35

1 Answers1

1

Can you refer to this answer which I think is the better approach: https://stackoverflow.com/a/47336682/143475

That said, I think you missed that the JS karate.match() API doesn't return a boolean, but a JSON that contains a pass boolean property.

So you have to do things like this:

* def someVar = karate.match(actual, expected).pass ? {} : {}
Peter Thomas
  • 54,465
  • 21
  • 84
  • 248
  • Now the problem half solved. The problem I now face is, if customerType is person, then getting error all key-values did not match, expected has un-matched keys: [organization]. Modified schema is { "customerType" : "#string", "organization" : "#? karate.match(response.customerType, 'org').pass ? karate.match(_, organizationSchema).pass : true)", "person" : "#? karate.match(response.customerType, 'person').pass ? karate.match(_, personSchema).pass : true", "id" : "#number", "requestDate" : "#string" } – stackoverflow Nov 17 '21 at 09:53