Best Kotest code snippet using io.kotest.assertions.json.print.prettyPrint
build.gradle.kts
Source:build.gradle.kts  
...249        }250        doLast {251            val expected = parseExpected("${test.absolutePath}/src/test/resources/expected.json")252            val actual = parseOutput(standardOutput.toString())253            val actualString = JsonOutput.prettyPrint(JsonOutput.toJson(actual))254            if (expected == actual) {255                file("${outputDir.absolutePath}/actual.json").writeText(actualString)256            } else {257                throw GradleException(258                    """259                    |Expected:260                    |${JsonOutput.prettyPrint(JsonOutput.toJson(expected))}261                    |262                    |Actual:263                    |${actualString}264                    |265                    |Output:266                    |${standardOutput}267                    |268                    |Error:269                    |${errorOutput}270                    """.trimMargin()271                )272            }273            // NOTE: Benign errors printed by IntelliJ IDEA 2019+274            val stderr = errorOutput.toString()...DidServiceTest.kt
Source:DidServiceTest.kt  
1package id.walt.services.did2import com.beust.klaxon.Klaxon3import id.walt.common.prettyPrint4import id.walt.crypto.KeyAlgorithm5import id.walt.crypto.decodeBase586import id.walt.model.Did7import id.walt.model.DidEbsi8import id.walt.model.DidMethod9import id.walt.model.DidUrl10import id.walt.servicematrix.ServiceMatrix11//ANDROID PORT12import id.walt.servicematrix.utils.AndroidUtils13//ANDROID PORT14import id.walt.services.key.KeyService15import id.walt.test.RESOURCES_PATH16import io.kotest.assertions.json.shouldMatchJson17import io.kotest.core.spec.style.AnnotationSpec18import io.kotest.matchers.collections.shouldBeOneOf19import io.kotest.matchers.shouldBe20import io.kotest.matchers.shouldNotBe21import java.io.File22//ANDROID PORT23import java.io.FileInputStream24//ANDROID PORT25class DidServiceTest : AnnotationSpec() {26    @Before27    fun setup() {28        //ANDROID PORT29        AndroidUtils.setAndroidDataDir(System.getProperty("user.dir"))30        ServiceMatrix(FileInputStream(File("$RESOURCES_PATH/service-matrix.properties")))31        //ANDROID PORT32    }33    private val keyService = KeyService.getService()34    fun readExampleDid(fileName: String) =35        File("$RESOURCES_PATH/dids/${fileName}.json").readText(Charsets.UTF_8)36    val ds = DidService37    @Test38    fun parseDidUrlTest() {39        val didUrl = DidUrl("method", "identifier", "key1")40        "did:method:identifier#key1" shouldBe didUrl.url41        val obj: DidUrl = DidUrl.from(didUrl.url)42        didUrl shouldBe obj43    }44    @Test45    //ANDROID PORT46    @Ignore //Android Lazy Sodium47    //ANDROID PORT48    fun createResolveDidKeyTest() {49        // Create50        val did = ds.create(DidMethod.key)51        val didUrl = DidUrl.from(did)52        did shouldBe didUrl.did53        "key" shouldBe didUrl.method54        print(did)55        // Resolve56        val resolvedDid = ds.resolve(did)57        val encoded = Klaxon().toJsonString(resolvedDid)58        println(encoded)59    }60    @Test61    fun createResolveDidWebTest() {62        // Create63        val did = ds.create(DidMethod.web)64        val didUrl = DidUrl.from(did)65        did shouldBe didUrl.did66        "web" shouldBe didUrl.method67        print(did)68        // Resolve69        val resolvedDid = ds.resolve(did)70        val encoded = Klaxon().toJsonString(resolvedDid)71        println(encoded)72    }73    @Test74    fun createDidEbsiV2Identifier() {75        val didUrl = DidUrl.generateDidEbsiV2DidUrl()76        val did = didUrl.did77        did.substring(0, 9) shouldBe  "did:ebsi:"78        didUrl.identifier.length shouldBeOneOf listOf(23, 24)79        didUrl.identifier[0] shouldBe 'z'80        didUrl.identifier.substring(1).decodeBase58()[0] shouldBe 0x0181        didUrl.method shouldBe "ebsi"82    }83    @Test84    fun createDidEbsiTest() {85        // Create86        val keyId = keyService.generate(KeyAlgorithm.ECDSA_Secp256k1)87        val did = ds.create(DidMethod.ebsi, keyId.id)88        // Load89        val resolvedDid = ds.loadDidEbsi(did)90        val encoded = Klaxon().toJsonString(resolvedDid)91        println(encoded)92        // Update93        resolvedDid.assertionMethod = listOf(resolvedDid.verificationMethod!!.get(0).id)94        ds.updateDidEbsi(resolvedDid)95        val encodedUpd = Klaxon().toJsonString(resolvedDid)96        println(encodedUpd)97    }98    @Test99    @Ignore // TODO: ESSIF backend issue100    fun resolveDidEbsiTest() {101        val did = "did:ebsi:22S7TBCJxzPS2Vv1UniBSdzFD2ZDFjZeYvQuFQWSeAQN5nTG"102        val didDoc = DidService.resolveDidEbsi(did)103        val encDidEbsi = Klaxon().toJsonString(didDoc)104        println(encDidEbsi)105    }106    @Test107    @Ignore // TODO: ESSIF backend issue108    fun resolveDidEbsiRawTest() {109        val did = "did:ebsi:22S7TBCJxzPS2Vv1UniBSdzFD2ZDFjZeYvQuFQWSeAQN5nTG"110        val didDoc = DidService.resolveDidEbsiRaw(did)111        println(didDoc.prettyPrint())112    }113    @Test114    //ANDROID PORT115    @Ignore //Android Lazy Sodium116    //ANDROID PORT117    fun listDidsTest() {118        ds.create(DidMethod.key)119        val dids = ds.listDids()120        dids.isNotEmpty() shouldBe true121        dids.forEach { s -> s shouldBe DidUrl.from(s).did }122    }123    @Test124    fun parseDidWithSingleValueContext() {125        val didDoc = "{\n" +...JsonMatchers.kt
Source:JsonMatchers.kt  
...10import kotlinx.serialization.json.JsonElement11import kotlinx.serialization.json.JsonObject12import kotlin.reflect.KClass13@OptIn(ExperimentalSerializationApi::class)14internal val pretty by lazy { Json { prettyPrint = true; prettyPrintIndent = "  " } }15/**16 * Verifies that the [expected] string is valid json, and that it matches this string.17 *18 * This matcher will consider two json strings matched if they have the same key-values pairs,19 * regardless of order.20 *21 */22infix fun String?.shouldMatchJson(expected: String?) = this should matchJson(expected)23infix fun String?.shouldNotMatchJson(expected: String?) = this shouldNot matchJson(expected)24@OptIn(ExperimentalSerializationApi::class)25fun matchJson(expected: String?) = object : Matcher<String?> {26   override fun test(value: String?): MatcherResult {27      val actualJson = try {28         value?.let(pretty::parseToJsonElement)29      } catch (ex: Exception) {30         return MatcherResult(31            false,32            { "expected: actual json to be valid json: $value" },33            {34               "expected: actual json to be invalid json: $value"35            })36      }37      val expectedJson = try {38         expected?.let(pretty::parseToJsonElement)39      } catch (ex: Exception) {40         return MatcherResult(41            false,42            { "expected: expected json to be valid json: $expected" },43            { "expected: expected json to be invalid json: $expected" }44         )45      }46      return ComparableMatcherResult(47         actualJson == expectedJson,48         { "expected json to match, but they differed\n\n" },49         { "expected not to match with: $expectedJson but match: $actualJson" },50         actualJson.toString(),51         expectedJson.toString()52      )53   }54}55@OptIn(ExperimentalSerializationApi::class)56fun beValidJson() = object : Matcher<String?> {57   override fun test(value: String?): MatcherResult {58      return try {59         value?.let(pretty::parseToJsonElement)60         MatcherResult(61              true,62              { "expected: actual json to be valid json: $value" },63              { "expected: actual json to be invalid json: $value" }64         )65      } catch (ex: Exception) {66         MatcherResult(67              false,68              { "expected: actual json to be valid json: $value" },69              { "expected: actual json to be invalid json: $value" }70         )71      }72   }73}74@OptIn(ExperimentalSerializationApi::class)75fun beJsonType(kClass: KClass<*>) = object : Matcher<String?> {76   override fun test(value: String?): MatcherResult {77      val element = try {78         value?.let(pretty::parseToJsonElement)79      } catch (ex: Exception) {80         return MatcherResult(81            false,82            { "expected: actual json to be valid json: $value" },83            { "expected: actual json to be invalid json: $value" }84         )85      }86      return MatcherResult(87         kClass.isInstance(element),88         { "expected: $value to be valid json of type: ${kClass.simpleName}" },89         { "expected: $value to not be of type: ${kClass.simpleName}" }90      )91   }92}93/**94 * Verifies that the [expected] string is valid json, and that it matches this string.95 *96 * This matcher will consider two json strings matched if they have the same key-values pairs,97 * regardless of order.98 *99 */100fun String.shouldEqualJson(expected: String, mode: CompareMode, order: CompareOrder) =101   this.shouldEqualJson(expected, legacyOptions(mode, order))102fun String.shouldEqualJson(expected: String, options: CompareJsonOptions) {103   val (e, a) = parse(expected, this)104   a should equalJson(e, options)105}106fun String.shouldNotEqualJson(expected: String, mode: CompareMode, order: CompareOrder) =107   this.shouldNotEqualJson(expected, legacyOptions(mode, order))108fun String.shouldNotEqualJson(expected: String, options: CompareJsonOptions) {109   val (e, a) = parse(expected, this)110   a shouldNot equalJson(e, options)111}112fun String.shouldBeEmptyJsonArray(): String {113   this should matchJson("[]")114   return this115}116fun String.shouldBeEmptyJsonObject(): String {117   this should matchJson("{}")118   return this119}120fun String.shouldBeJsonArray(): String {121   this should beJsonType(JsonArray::class)122   return this123}124fun String.shouldNotBeJsonArray(): String {125   this shouldNot beJsonType(JsonArray::class)126   return this127}128fun String.shouldBeJsonObject(): String {129   this should beJsonType(JsonObject::class)130   return this131}132fun String.shouldNotBeJsonObject(): String {133   this shouldNot beJsonType(JsonObject::class)134   return this135}136fun String.shouldBeValidJson(): String {137   this should beValidJson()138   return this139}140fun String.shouldNotBeValidJson(): String {141   this shouldNot beValidJson()142   return this143}144internal fun parse(expected: String, actual: String): Pair<JsonTree, JsonTree> {145   val enode = pretty.parseToJsonElement(expected)146   val anode = pretty.parseToJsonElement(actual)147   val e = toJsonTree(enode)148   val a = toJsonTree(anode)149   return Pair(e, a)150}151internal fun toJsonTree(root: JsonElement) =152   with(root.toJsonNode()) {153      JsonTree(this, prettyPrint(this))154   }...PostControllerTest.kt
Source:PostControllerTest.kt  
...DeserializationTests.kt
Source:DeserializationTests.kt  
...11import java.io.InputStreamReader12@DisplayName("Deserialization Verification Tests")13class DeserializationTests : FunSpec() {14    private val json = Json {15        prettyPrint = true16    }17    private inline fun <reified T> assertDeserializes(resourcePath: String) {18        val stream = this::class.java.getResourceAsStream("/io/github/paulgriffith/tagkreator/model/$resourcePath.json")19        stream.shouldNotBeNull()20        val text = stream.use { resource ->21            resource.reader().use(InputStreamReader::readText)22        }23        // Make sure we can deserialize the given .json into a model type24        shouldNotThrowAny {25            TAG_JSON.decodeFromString<T>(text)26                .shouldNotBeNull()27        }28        val decoded = TAG_JSON.decodeFromString(JsonElement.serializer(), text)29        val expected = json.decodeFromString(JsonElement.serializer(), text)...print.kt
Source:print.kt  
1package io.kotest.assertions.json2private const val indent = "  "3internal fun prettyPrint(node: JsonNode, depth: Int = 0): String {4   return when (node) {5      is JsonNode.ArrayNode -> prettyPrintElements(depth, "[", "]", node.elements) { child ->6         indent.repeat(depth + 1) + prettyPrint(child, depth = depth + 1)7      }8      is JsonNode.ObjectNode -> prettyPrintElements(depth, "{", "}", node.elements.entries) {9         indent.repeat(depth + 1) + "\"${it.key}\": ${prettyPrint(it.value, depth = depth + 1)}"10      }11      is JsonNode.BooleanNode -> node.value.toString()12      JsonNode.NullNode -> "null"13      is JsonNode.NumberNode -> node.content14      is JsonNode.StringNode -> "\"${node.value.replace("\"", "\\\"")}\""15   }16}17private fun <S, T : Collection<S>> prettyPrintElements(18   depth: Int,19   prefix: String,20   suffix: String,21   elements: T,22   transform: (S) -> CharSequence23) = buildString {24   if (elements.isEmpty()) append(prefix + suffix)25   else {26      appendLine(prefix)27      appendLine(elements.joinToString(",\n", transform = transform))28      append(indent.repeat(depth) + suffix)29   }30}...prettyPrint
Using AI Code Generation
1+import io.kotest.assertions.json.print.prettyPrint2 import io.kotest.core.spec.style.StringSpec3 import io.kotest.matchers.shouldBe4 import io.kotest.matchers.shouldNotBe5 import io.kotest.matchers.string.shouldContain6 import io.kotest.matchers.string.shouldMatch7 import io.kotest.matchers.string.shouldNotBeBlank8 import io.kotest.matchers.string.shouldNotBeEmpty9 import io.kotest.matchers.string.shouldNotContain10 import io.kotest.matchers.string.shouldNotHaveLength11 import io.kotest.matchers.string.shouldNotMatch12 import io.kotest.matchers.string.shouldNotStartWith13 import io.kotest.matchers.string.shouldStartWith14 import io.kotest.matchers.string.shouldStartWithAnyOf15 import io.kotest.matchers.string.shouldStartWithOneOf16 import io.kotest.matchers.string.shouldStartWithOnly17 import io.kotest.matchers.string.shouldStartWithOnlyOneOf18 import io.kotest.matchers.string.shouldStartWithOnlyOneOfIgnoringCase19 import io.kotest.matchers.string.shouldStartWithOnlyOneOfIgnoringCaseAndWhitespace20 import io.kotest.matchers.string.shouldStartWithOnlyOneOfIgnoringCaseAndWhitespaceAndPunctuation21 import io.kotest.matchers.string.shouldStartWithOnlyOneOfIgnoringCaseAndWhitespaceAndPunctuationAndSpecialCharacters22 import io.kotest.matchers.string.shouldStartWithOnlyOneOfIgnoringCaseAndWhitespaceAndPunctuationAndSpecialCharactersAndDigits23 import io.kotest.matchers.string.shouldStartWithOnlyOneOfIgnoringCaseAndWhitespaceAndPunctuationAndSpecialCharactersAndDigitsAndUnderscore24 import io.kotest.matchers.string.shouldStartWithOnlyOneOfIgnoringCaseAndWhitespaceAndPunctuationAndSpecialCharactersAndDigitsAndUnderscoreAndMinus25 import io.kotest.matchers.string.shouldStartWithOnlyOneOfIgnoringCaseAndWhitespaceAndPunctuationAndSpecialCharactersAndDigitsAndUnderscoreAndMinusAndSpace26 import io.kotest.matchers.string.shouldStartWithOnlyOneOfIgnoringCaseAndWhitespaceAndPunctuationAndSpecialCharactersAndDigitsAndUnderscoreAndMinusAndSpaceAndAt27 import io.kotest.matchers.string.shouldStartWithOnlyOneOfIgnoringCaseAndWhitespaceAndPunctuationAndSpecialCharactersAndDigitsAndUnderscoreAndMinusAndSpaceAndAtAndDollar28 importprettyPrint
Using AI Code Generation
1import io.kotest.assertions.json.print.prettyPrint2val json = """{3    { "name":"Ford", "models":[ "Fiesta", "Focus", "Mustang" ] },4    { "name":"BMW", "models":[ "320", "X3", "X5" ] },5    { "name":"Fiat", "models":[ "500", "Panda" ] }6}"""7val actual = prettyPrint(json)8import io.kotest.assertions.json.print.compactPrint9val json = """{10    { "name":"Ford", "models":[ "Fiesta", "Focus", "Mustang" ] },11    { "name":"BMW", "models":[ "320", "X3", "X5" ] },12    { "name":"Fiat", "models":[ "500", "Panda" ] }13}"""14val actual = compactPrint(json)prettyPrint
Using AI Code Generation
1+    val json = """{"name":"John","age":30,"cars":["Ford","BMW","Fiat"]}"""2+    json.shouldBeJson("""{"name":"John","age":30,"cars":["Ford","BMW","Fiat"]}""")3+}4+val json = """{"name":"John","age":30,"cars":["Ford","BMW","Fiat"]}"""5+val jsonNode = Json.parseToJsonNode(json)6+jsonNode.shouldBeJson("""{"name":"John","age":30,"cars":["Ford","BMW","Fiat"]}""")7+val json = """{"name":"John","age":30,"cars":["Ford","BMW","Fiat"]}"""8+val jsonElement = Json.parseToJsonElement(json)9+jsonElement.shouldBeJson("""{"name":"John","age":30,"cars":["Ford","BMW","Fiat"]}""")10+val json = """{"name":"John","age":30,"cars":["Ford","BMW","Fiat"]}"""11+val jsonDocument = Json.parseToJsonDocument(json)12+jsonDocument.shouldBeJson("""{"name":"John","age":30,"cars":["Ford","BMW","Fiat"]}""")13+val json = """{"name":"John","age":30,"cars":["Ford","BMW","Fiat"]}"""14+json.shouldBeJson("""{"name":"John","age":30,"cars":["Ford","BMW","Fiat"]}""")15+val json = """{"name":"John","age":30,"cars":["Ford","BMW","Fiat"]}"""16+val jsonNode = Json.parseToJsonNode(json)17+jsonNode.shouldBeJsonIgnoringFields("""{"name":"John","age":30,"cars":["Ford","BMW","Fiat"]}""", "age")18+val json = """{"name":"John","age":30,"cars":["Ford","BMW","Fiat"]}"""prettyPrint
Using AI Code Generation
1+prettyPrint(json)2+prettyPrint(json, indent)3+prettyPrint(json, indent, indentSize)4+prettyPrint(json, indent, indentSize, indentChar)5+prettyPrint(json, indent, indentSize, indentChar, indentType)6+prettyPrint(json, indent, indentSize, indentChar, indentType, indentFirst)7+prettyPrint(json, indent, indentSize, indentChar, indentType, indentFirst, sortKeys)8+prettyPrint(json, indent, indentSize, indentChar, indentType, indentFirst, sortKeys, skipNulls)9+prettyPrint(json, indent, indentSize, indentChar, indentType, indentFirst, sortKeys, skipNulls, escapeForwardSlashes)10+prettyPrint(json, indent, indentSize, indentChar, indentType, indentFirst, sortKeys, skipNullsprettyPrint
Using AI Code Generation
1println(prettyPrint(json, indent = 5, newLine = "2println(prettyPrint(json, indent = 5, newLine = "3println(prettyPrint(json, indent = 5, newLine = "4println(prettyPrint(json, indent = 5, newLine = "5println(prettyPrint(json, indent = 5, newLine = "6println(prettyPrint(json, indent = 5, newLine = "prettyPrint
Using AI Code Generation
1println(prettyPrint(jsonString))2println(prettyPrint(jsonString, PrettyPrintConfig()))3println(prettyPrint(jsonString, PrettyPrintConfig(), 4))4println(prettyPrint(jsonString, PrettyPrintConfig(), 4, " "))5println(prettyPrint(jsonString, PrettyPrintConfig(), 4, " ", true))6println(prettyPrint(jsonString, PrettyPrintConfig(), 4, " ", true, "\n"))7println(prettyPrint(jsonString, PrettyPrintConfig(), 4, " ", true, "\n", true))8println(prettyPrint(jsonString, PrettyPrintConfig(), 4, " ", true, "\n", true, true))9println(prettyPrint(jsonString, PrettyPrintConfig(), 4, " ", true, "\n", true, true, trueprettyPrint
Using AI Code Generation
1+            val actual = Json.encodeToString(listOf(1, 2, 3))2+        }3+        test("json assertion should fail with mismatched json") {4+            val actual = Json.encodeToString(listOf(1, 2, 3))5+            shouldThrow<AssertionError> {6+                |""".trimMargin()7+        }8+        test("json assertion should fail with mismatched json and pretty print") {9+            val actual = Json.encodeToString(listOf(1, 2, 3))10+            shouldThrow<AssertionError> {11+                |""".trimMargin()12+        }13+        test("json assertion should fail with mismatched json and pretty print with custom indent") {14+            val actual = Json.encodeToString(listOf(1, 2, 3))15+            shouldThrow<AssertionError> {16+                |""".trimMargin()17+        }18+        test("json assertion should fail with mismatched json and prettyLearn 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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
