Search code examples
jsonkaratejsonpath

Karate API framework - How can I check that a particular field value is not coming as duplicate under an array


Using karate framework how can I make sure that below personId under the persons array should not be coming as a duplicate value

If you see below response the id:1 record has duplicate personIds, hence my test should be failed in this case. Also the persons array is dynamic in nature, there could be some records which hold more than 4 personsIds too.

So a common approach should be helpful. Please help.

    {
        "total": 10,
        "count": 10,
        "results": [
            {
                "id": "1",
                "source": {
                    "authors": {
                        "persons": [
                            {
                                "personId": 11
                            },
                            {
                                "personId": 11
                            }
                        ]
                    }
              }
          },
          {
                "id": "2",
                "source": {
                    "authors": {
                        "persons": [
                            {
                                "personId": 11
                            },
                            {
                                "personId": 15
                            }
                        ]
                    }
              }
          }
    ]
}

Solution

  • Here you go, one possible solution using a JS function and using Java Set:

    * def isValid =
    """
    function(x) {
      var personIds = karate.jsonPath(x, '$[*].personId');
      var distinct = new java.util.HashSet(personIds);
      return personIds.size() == distinct.size();
    }
    """
    * match each $..persons == '#? isValid(_)'