jsontestingautomationkarate

Matching a subset of a json array with another super set of json array in karate


I am trying a validate if the values of all the attributes of a JSON object in a JSON array matches to another superset of JSON objects in another JSON array with few tweaks.

So, I was trying to use match each with karate.jsonPath, but seems like that is not possible. Is there a more simplified solution to this other than creating a function?

Example:

Say I have the subset of JSON array like this:

def subSet = [{userName: "JohnSmith", firstName: "John", lastName: "Smith", grade: 6.7}, {userName: "JohnDoe", firstName: "John", lastName: "Doe", grade: 6.9}, {userName: "WillSmith", firstName: "Will", lastName: "Smith", grade: 6.5}]

And a superset of JSON like this:

def superSet = [{USERNAME: "JohnSmith", FIRSTNAME: "John", LASTNAME: "Smith", GRADE: "6.7"}, {USERNAME: "BruceWayne", FIRSTNAME: "Bruce", LASTNAME: "Wayne", GRADE: "6.2"}, {USERNAME: "JohnDoe", FIRSTNAME: "John", LASTNAME: "Doe", GRADE: "6.9"}, {USERNAME: "JaneDoe", FIRSTNAME: "Jane", LASTNAME: "Doe", GRADE: "6.1"}, {USERNAME: "WillSmith", FIRSTNAME: "Will", LASTNAME: "Smith", GRADE: "6.5"}]

Note the difference in the case of the keys and also the value of the key 'grade' is float in subSet and string in superSet.

So, what I am trying is like this:

* match each subSet contains {grade: '#? _ == karate.jsonPath(superSet, "$[?(@.FIRSTNAME == _$.firstName && @.LASTNAME == _$.lastName)]")[0].GRADE * 1'}

Is there a way to match this in one liner?


Solution

  • Personally I would do a single transform before this kind of a complex match, it would much easier for others to understand and maintain.

    Doing a JSON transform is easy using a "map" operation.

    * def response = [{name: 'foo', age: 10}]
    * def fun = x => { let result = {}; Object.keys(x).forEach(k => result[k.toUpperCase()] = x[k] + ''); return result }
    * def data = response.map(fun)
    * match data contains {NAME: 'foo', AGE: '10'}
    

    For more details on the JS transforms you can do, refer: https://stackoverflow.com/a/76091034/143475