Yuriy Shpyluk
Yuriy Shpyluk

Reputation: 23

Karate match two JSON files: array of objects which contains inner shuffled arrays of object

Task:

Have 3 endpoints:

1st returns random data for request to two other endpoints.

Two other endpoints operates with different DBs but on, more or less, similar data.

I need to validate that response from one endpoint is matching response from another, both endpoints send the same data but in different order.

e.g.:

endpoint 'A':

{
  "items": [
    {
      "field1": 111,
      "array1": [
        {
          "field11": 102,
          "field22": 231
        },
        {
          "field11": 103,
          "field22": 231
        },
        {
          "field11": 102,
          "field22": 256
        },
        {
          "field11": 104,
          "field22": 256
        }
      ],
      "field2": 122,
      "array2": [
        1,
        2,
        3
      ]
    },
    {
      "field1": 211,
      "field2": 222,
      "field3": 233
    }
  ]
}

endpoint 'B':

{
  "items": [
    {
      "field1": 211,
      "field2": 222,
      "field3": 233
    },
    {
      "field1": 111,
      "array1": [
        {
          "field11": 104,
          "field22": 256
        },
        {
          "field11": 102,
          "field22": 256
        },
        {
          "field11": 103,
          "field22": 231
        },
        {
          "field11": 102,
          "field22": 231
        }
      ],
      "field2": 222,
      "array2": [
        1,
        2,
        3
      ]
    }
  ]
}

endpointA_response.items contains only endpointB_response.items verification fails because it considers inner array1 from one response doesn't match array1 from another response because array items are in different order.

endpointA_response.items[0].array1 contains only endpointB_response.items[1].array1 works OK though, but it is not what I need. I need to compare whole response regardless of ordering.

Is there any possibility to apply contains only verification to array of objects which contains arrays which could have items in different order?

Upvotes: 2

Views: 793

Answers (1)

Peter Thomas
Peter Thomas

Reputation: 58153

You were on the right track with endpointA_response.items[0].array1 contains only endpointB_response.items[1].array1

I need to compare whole response regardless of ordering.

Then you have to do some "extra" work. There is no magic.

I would suggest sorting. In Karate 1.0, there is a karate.sort() API. For example, if you are sure that the value of field1 is a unique-identfier

* def expected = karate.sort(responseA, x => x.field1)

Then hopefully it aligns things so that you can do a contains match.

Read this answer for other ideas: https://stackoverflow.com/a/53120851/143475

Upvotes: 1

Related Questions