How to use compareString method of io.kotest.assertions.json.CompareJsonOptions class

Best Kotest code snippet using io.kotest.assertions.json.CompareJsonOptions.compareString

compare.kt

Source:compare.kt Github

copy

Full Screen

...160         is JsonNode.ArrayNode -> compareArrays(path, expected, actual, options)161         else -> JsonError.ExpectedArray(path, actual)162      }163      is JsonNode.BooleanNode -> compareBoolean(path, expected, actual, options)164      is JsonNode.StringNode -> compareString(path, expected, actual, options)165      is JsonNode.NumberNode -> compareNumbers(path, expected, actual, options)166      JsonNode.NullNode -> compareNull(path, actual)167   }168}169internal fun compareObjects(170   path: List<String>,171   expected: JsonNode.ObjectNode,172   actual: JsonNode.ObjectNode,173   options: CompareJsonOptions,174): JsonError? {175   if (FieldComparison.Strict == options.fieldComparison) {176      val keys1 = expected.elements.keys177      val keys2 = actual.elements.keys178      if (keys1.size < keys2.size) {179         val missing = keys2 - keys1180         return JsonError.ObjectMissingKeys(path, missing)181      }182      if (keys2.size < keys1.size) {183         val extra = keys1 - keys2184         return JsonError.ObjectExtraKeys(path, extra)185      }186   }187   // when using strict order mode, the order of elements in json matters, normally, we don't care188   when (options.propertyOrder) {189      PropertyOrder.Strict ->190         expected.elements.entries.withIndex().zip(actual.elements.entries).forEach { (e, a) ->191            if (a.key != e.value.key) return JsonError.NameOrderDiff(path, e.index, e.value.key, a.key)192            val error = compare(path + a.key, e.value.value, a.value, options)193            if (error != null) return error194         }195      PropertyOrder.Lenient ->196         expected.elements.entries.forEach { (name, e) ->197            val a = actual.elements[name] ?: return JsonError.ObjectMissingKeys(path, setOf(name))198            val error = compare(path + name, e, a, options)199            if (error != null) return error200         }201   }202   return null203}204internal fun compareArrays(205   path: List<String>,206   expected: JsonNode.ArrayNode,207   actual: JsonNode.ArrayNode,208   options: CompareJsonOptions,209): JsonError? {210   if (expected.elements.size != actual.elements.size)211      return JsonError.UnequalArrayLength(path, expected.elements.size, actual.elements.size)212   when (options.arrayOrder) {213      ArrayOrder.Strict -> {214         expected.elements.withIndex().zip(actual.elements.withIndex()).forEach { (a, b) ->215            val error = compare(path + "[${a.index}]", a.value, b.value, options)216            if (error != null) return error217         }218      }219      /**220       * In [ArrayOrder.Lenient], we try to allow array contents to be out-of-order.221       * We do this by searching for a match for each element in [actual], in the [expected] array,222       * flagging used matches so they can't be used twice. This will probably be slow for very big arrays.223       */224      ArrayOrder.Lenient -> {225         val consumedIndexes = BooleanArray(expected.elements.size) { false }226         fun availableIndexes() = consumedIndexes227            .mapIndexed { index, isConsumed -> if (!isConsumed) index else null }228            .filterNotNull()229         fun findMatchingIndex(element: JsonNode): Int? {230            for (i in availableIndexes()) {231               // Comparison with no error -> matching element232               val isMatch = compare(path + "[$i]", element, expected.elements[i], options) == null233               if (isMatch) {234                  return i235               }236            }237            return null238         }239         for ((i, element) in actual.elements.withIndex()) {240            val match = findMatchingIndex(element)241               ?: return JsonError.UnequalArrayContent(path + "[$i]", expected, element)242            consumedIndexes[match] = true243         }244      }245   }246   return null247}248/**249 * When comparing a string, if the [mode] is [CompareMode.Lenient] we can convert the actual node to a string.250 */251internal fun compareString(252   path: List<String>,253   expected: JsonNode.StringNode,254   actual: JsonNode,255   options: CompareJsonOptions256): JsonError? {257   return when {258      actual is JsonNode.StringNode -> compareStrings(path, expected.value, actual.value)259      options.typeCoercion.isEnabled() -> when {260         actual is JsonNode.BooleanNode -> compareStrings(path, expected.value, actual.value.toString())261         actual is JsonNode.NumberNode && expected.contentIsNumber() -> compareNumberNodes(262            path,263            expected.toNumberNode(),264            actual265         )266         else -> JsonError.IncompatibleTypes(path, expected, actual)267      }268      else -> JsonError.IncompatibleTypes(path, expected, actual)269   }270}271internal fun compareStrings(path: List<String>, expected: String, actual: String): JsonError? {272   return when (expected) {273      actual -> null274      else -> JsonError.UnequalStrings(path, expected, actual)275   }276}277/**278 * When comparing a boolean, if the [mode] is [CompareMode.Lenient] and the actual node is a text279 * node with "true" or "false", then we convert.280 */281internal fun compareBoolean(282   path: List<String>,283   expected: JsonNode.BooleanNode,284   actual: JsonNode,285   options: CompareJsonOptions...

Full Screen

Full Screen

compareString

Using AI Code Generation

copy

Full Screen

1        compareJsonOptions {2            compareString = { a, b ->3            }4        }5        compareJsonOptions {6            compareNumber = { a, b ->7            }8        }9        compareJsonOptions {10            compareBoolean = { a, b ->11            }12        }13        compareJsonOptions {14            compareNull = { a, b ->15            }16        }17        compareJsonOptions {18            compareArray = { a, b ->19            }20        }21        compareJsonOptions {22            compareObject = { a, b ->23            }24        }25        compareJsonOptions {26            compareJsonOptions = CompareJsonOptions()27        }28    }29    jsonAssertionOptions {30        compareJsonOptions = CompareJsonOptions()31    }32}33fun jsonAssertionOptions(34    config: JsonAssertionOptions.() -> Unit35fun jsonAssertionOptions(36    config: JsonAssertionOptions.() -> Unit37): JsonAssertionOptions {38    jsonAssertionOptions {39        compareJsonOptions = CompareJsonOptions()40    }41}42fun jsonDiff(43    options: CompareJsonOptions = CompareJsonOptions()

Full Screen

Full Screen

compareString

Using AI Code Generation

copy

Full Screen

1		val expected = """{"name":"John","age":30,"cars":["Ford","BMW","Fiat"]}"""2		val actual = """{"name":"John","age":30,"cars":["Ford","BMW"]}"""3		compareJson(expected, actual, CompareJsonOptions(compareString = { expected, actual ->4			if (expected == "Fiat" && actual == "Fiat") {5			} else {6			}7		})).shouldBeSame()8	}9}10fun compareJson(expected: String, actual: String, compareJsonOptions: CompareJsonOptions = CompareJsonOptions()): CompareResult11enum class CompareResult {12}13class CompareJsonOptions(14    val compareString: (String, String) -> CompareResult = { expected, actual ->15        if (expected == actual) CompareResult.Same else CompareResult.NotSame16    },17    val compareNumber: (Number, Number) -> CompareResult = { expected, actual ->18        if (expected == actual) CompareResult.Same else CompareResult.NotSame19    },20    val compareBoolean: (Boolean, Boolean) -> CompareResult = { expected, actual ->21        if (expected == actual) CompareResult.Same else CompareResult.NotSame22    },23    val compareNull: () -> CompareResult = { CompareResult.Same },24    val compareArray: (JsonArray, JsonArray) -> CompareResult = { expected, actual ->25        if (expected ==

Full Screen

Full Screen

compareString

Using AI Code Generation

copy

Full Screen

1compareString(result, expected, CompareJsonOptions().ignoreExtraKeys(true))2compareString(result, expected, CompareJsonOptions().ignoreArrayOrder(true))3compareString(result, expected, CompareJsonOptions().ignoreExtraKeys(true).ignoreArrayOrder(true))4compareString(result, expected, CompareJsonOptions().ignoreExtraKeys(true).ignoreArrayOrder(true).ignoreArraySize(true))5compareString(result, expected, CompareJsonOptions().ignoreExtraKeys(true).ignoreArrayOrder(true).ignoreArraySize(true).ignoreNulls(true))6compareString(result, expected, CompareJsonOptions().ignoreExtraKeys(true).ignoreArrayOrder(true).ignoreArraySize(true).ignoreNulls(true).ignoreNumberType(true))7compareString(result, expected, CompareJsonOptions().ignoreExtraKeys(true).ignoreArrayOrder(true).ignoreArraySize(true).ignoreNulls(true).ignoreNumberType(true).ignoreStringType(true))8compareString(result, expected, CompareJsonOptions().ignoreExtraKeys(true).ignoreArrayOrder(true).ignoreArraySize(true).ignoreNulls(true).ignoreNumberType(true).ignoreStringType(true).ignoreCase(true))9compareString(result, expected, CompareJsonOptions().ignoreExtraKeys(true).ignoreArrayOrder(true).ignoreArraySize(true).ignoreNulls(true).ignoreNumberType(true).ignoreStringType(true).ignoreCase(true).ignoreWhitespace(true))10compareString(result, expected, CompareJsonOptions().ignoreExtraKeys(true).ignoreArrayOrder(true).ignoreArraySize(true).ignoreNulls(true).ignoreNumberType(true).ignoreStringType(true).ignoreCase(true).ignoreWhitespace

Full Screen

Full Screen

compareString

Using AI Code Generation

copy

Full Screen

1+fun main() {2+    val jsonString1 = """{"name":"kotest","age":3}"""3+    val jsonString2 = """{"name":"kotest","age":4}"""4+    val result = compareString(jsonString1, jsonString2, CompareJsonOptions(compareString = { s1, s2 -> s1.toInt() == s2.toInt() }))5+    println(result)6+}

Full Screen

Full Screen

compareString

Using AI Code Generation

copy

Full Screen

1		val json1 = """{"name":"foo"}"""2		val json2 = """{"name":"foo"}"""3		json1.shouldBeJson(json2, CompareJsonOptions(compareString = { a, b -> a.length == b.length }))4		val json3 = """{"name":"foo"}"""5		val json4 = """{"name":"foo"}"""6		json3.shouldBeJson(json4, CompareJsonOptions(compareString = { a, b -> a.length == b.length }))7		val json5 = """{"name":"foo"}"""8		val json6 = """{"name":"foo"}"""9		json5.shouldBeJson(json6, CompareJsonOptions(compareString = { a, b -> a.length == b.length }))10		val json7 = """{"name":"foo"}"""11		val json8 = """{"name":"foo"}"""12		json7.shouldBeJson(json8, CompareJsonOptions(compareString = { a, b -> a.length == b.length }))13		val json9 = """{"name":"foo"}"""14		val json10 = """{"name":"foo"}"""15		json9.shouldBeJson(json10, CompareJsonOptions(compareString = { a, b -> a.length == b.length }))16		val json11 = """{"name":"foo"}"""17		val json12 = """{"name":"foo"}"""18		json11.shouldBeJson(json12, CompareJsonOptions(compareString = { a, b -> a.length == b.length }))

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Kotest automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful