1

I've been using something like this.

* def schema =
  """
    {
    eligible: #string,
    Reason: ##string,
    enrolled: '##regex ^\\d{4}-\\d{2}-\\d{2}$',
    modifiable: ##string,
    Date: '##regex ^\\d{4}-\\d{2}-\\d{2}$',
    status: #string,
    Id: #string,
    email: #string,
    serviceAddressDetails: ##[] firstSchema,
    DeviceIds: #[] #string
    }
  """

The expected response has two possible outcomes, I want to assert that if we get either of them, the test should pass.

First,

DeviceIds : ["abcderfg"]

Second

    DeviceIds : [
                  {
                     id : "abcd"
                   }
                ],

If we get either of them in the response, the test/schema should pass. How can I assert both these scenarios in the same schema? Any help is much appreciated. Thanks!

Dhamo
  • 1,171
  • 3
  • 19
  • 41

1 Answers1

0

Just run a second check. I know, it may not feel like a "single reusable schema" but take my advice, it is not worth it. Here's a solution:

* def response1 = { deviceIds: ['abcd'] }
* def firstDevice = response1.deviceIds[0]
* def isTypeOne = karate.typeOf(firstDevice) == 'string'
* def expectedDevice = isTypeOne ? '#[] #string' : '#object'
* match response1 == { deviceIds: '#(expectedDevice)' }

* def response2 = { deviceIds: { id: 'abcd' } }
* def firstDevice = response2.deviceIds[0]
* def isTypeOne = karate.typeOf(firstDevice) == 'string'
* def expectedDevice = isTypeOne ? '#[] #string' : '#object'
* match response2 == { deviceIds: '#(expectedDevice)' }

Other ideas:

https://stackoverflow.com/a/62567262/143475

Peter Thomas
  • 54,465
  • 21
  • 84
  • 248