orangain / json-fuzzy-match

Custom assertion to check whether a JSON string fuzzily matches a pattern for JVM languages.
MIT License
13 stars 0 forks source link

Compare array elements regardless of order #44

Open orangain opened 1 month ago

orangain commented 1 month ago

Motivation

There is a case when we want to compare JSON arrays regardless of their order. For example, an API for testing might return items in no guaranteed order.

Related work

AssertJ

AbstractIterableAssert#containsExactlyInAnyOrder provides comparison regardless of order.

Verifies that the actual group contains exactly the given values and nothing else, in any order.

 Iterable<Ring> elvesRings = newArrayList(vilya, nenya, narya, vilya);

 // assertion will pass
 assertThat(elvesRings).containsExactlyInAnyOrder(vilya, vilya, nenya, narya);

 // assertion will fail as vilya is contained twice in elvesRings.
 assertThat(elvesRings).containsExactlyInAnyOrder(nenya, vilya, narya);

Karate

Assertion match contains only provides comparison regardless of order.

For those cases where you need to assert that all array elements are present but in any order you can do this:

* def data = { foo: [1, 2, 3] }
* match data.foo contains 1
* match data.foo contains [2]
* match data.foo contains [3, 2]
* match data.foo contains only [3, 2, 1]
* match data.foo contains only [2, 3, 1]
# this will fail
# * match data.foo contains only [2, 3]

In addition, assertion match contains only deep provides order insensitive comparison for the deep array.

This is exactly like match == but the order of arrays does not matter. All arrays no matter the "depth" will be checked in this way.

* def response = { foo: [ 'a', 'b' ] }
* match response contains only deep { foo: [ 'b', 'a' ] }

Solution

To be determined. Ideas are welcome!