Best Kotest code snippet using io.kotest.assertions.json.schema.parse
JsonSerializeVerifiableCredentialTest.kt
Source:JsonSerializeVerifiableCredentialTest.kt
...53 // TODO: remove / replace functions below as they are using the old data model54 @Test55 fun vcSerialization() {56 val input = File("templates/vc-template-default.json").readText().replace("\\s".toRegex(), "")57 val vc = Klaxon().parse<VerifiableCredential>(input)58 println(vc)59 val enc = Klaxon().toJsonString(vc)60 println(enc)61 input shouldEqualJson enc62 }63 @Test64 fun vcConstructTest() {65 val proof =66 Proof(67 type = "EidasSeal2019",68 created = LocalDateTime.now().withNano(0).toString(),69 creator = "did:creator",70 proofPurpose = "assertionMethod",71 verificationMethod = "EidasCertificate2019",//VerificationMethodCert("EidasCertificate2019", "1088321447"),72 jws = "BD21J4fdlnBvBA+y6D...fnC8Y="73 )74 val vc = VerifiableAttestation(75 context = listOf(76 "https://www.w3.org/2018/credentials/v1",77 "https://essif.europa.eu/schemas/v-a/2020/v1",78 "https://essif.europa.eu/schemas/eidas/2020/v1"79 ),80 id = "education#higherEducation#3fea53a4-0432-4910-ac9c-69ah8da3c37f",81 issuer = "did:ebsi:2757945549477fc571663bee12042873fe555b674bd294a3",82 issued = "2019-06-22T14:11:44Z",83 validFrom = "2019-06-22T14:11:44Z",84 credentialSubject = VerifiableAttestation.VerifiableAttestationSubject(85 id = "id123"86 ),87 credentialStatus = CredentialStatus(88 id = "https://essif.europa.eu/status/identity#verifiableID#1dee355d-0432-4910-ac9c-70d89e8d674e",89 type = "CredentialStatusList2020"90 ),91 credentialSchema = CredentialSchema(92 id = "https://essif.europa.eu/tsr-vid/verifiableid1.json",93 type = "JsonSchemaValidator2018"94 ),95 evidence = listOf(96 VerifiableAttestation.Evidence(97 id = "https://essif.europa.eu/tsr-va/evidence/f2aeec97-fc0d-42bf-8ca7-0548192d5678",98 type = listOf("DocumentVerification"),99 verifier = "did:ebsi:2962fb784df61baa267c8132497539f8c674b37c1244a7a",100 evidenceDocument = "Passport",101 subjectPresence = "Physical",102 documentPresence = "Physical"103 )104 ),105 proof = Proof(106 type = "EidasSeal2021",107 created = "2019-06-22T14:11:44Z",108 proofPurpose = "assertionMethod",109 verificationMethod = "did:ebsi:2757945549477fc571663bee12042873fe555b674bd294a3#2368332668",110 jws = "HG21J4fdlnBvBA+y6D...amP7O="111 )112 )113 val encoded = format.toJsonString(vc)114 // println(encoded)115 val obj = Klaxon().parse<VerifiableCredential>(encoded)116 // println(obj)117 vc shouldBe obj118 }119 @Test120 fun vcTemplatesOldTest() {121 File("templates/").walkTopDown()122 .filter { it.toString().endsWith(".json") }123 .forEach {124 println("serializing: $it")125 //val obj = Json { ignoreUnknownKeys = true }.decodeFromString<VerifiableCredential>(it.readText())126 val obj = Klaxon().parse<VerifiableCredential>(it.readText())127 println(obj)128 }129 }130}...
ByteParserTest.kt
Source:ByteParserTest.kt
1package insulator.jsonhelper.jsontoavro.fieldparser2import insulator.jsonhelper.jsontoavro.JsonFieldParsingException3import io.kotest.assertions.arrow.either.shouldBeLeft4import io.kotest.assertions.arrow.either.shouldBeRight5import io.kotest.core.spec.style.StringSpec6import io.kotest.matchers.types.shouldBeInstanceOf7import org.apache.avro.Conversions8import org.apache.avro.Schema9import java.nio.ByteBuffer10class ByteParserTest : StringSpec({11 "happy path - bytes" {12 // arrange13 val sut = ByteParser()14 val schema = Schema.Parser().parse("""{ "type": "bytes"}""")15 val binaryString = "0x00010203"16 // act17 val res = sut.parse(binaryString, schema)18 // assert19 res shouldBeRight ByteBuffer.wrap(byteArrayOf(0, 1, 2, 3))20 }21 "happy path - decimal" {22 // arrange23 val sut = ByteParser()24 val schema = Schema.Parser().parse("""{ "type": "bytes", "logicalType": "decimal", "precision": 4, "scale": 2}""")25 val decimal = 1.1226 // act27 val res = sut.parse(decimal, schema)28 // assert29 res shouldBeRight {30 Conversions.DecimalConversion().toBytes(decimal.toBigDecimal(), schema, schema.logicalType)31 }32 }33 "parsing a decimal set the scale to the schema one" {34 // arrange35 val sut = ByteParser()36 val schema = Schema.Parser().parse("""{ "type": "bytes", "logicalType": "decimal", "precision": 6, "scale": 4}""")37 val decimal = 1.338 // act39 val res = sut.parse(decimal, schema)40 // assert41 res shouldBeRight {42 val scaledDecimal = decimal.toBigDecimal().setScale(4)43 Conversions.DecimalConversion().toBytes(scaledDecimal, schema, schema.logicalType)44 }45 }46 "parsing a decimal return left if exceed scale" {47 // arrange48 val sut = ByteParser()49 val schema = Schema.Parser().parse("""{ "type": "bytes", "logicalType": "decimal", "precision": 6, "scale": 4}""")50 val decimal = 1.31234551 // act52 val res = sut.parse(decimal, schema)53 // assert54 res shouldBeLeft {}55 }56 "return left if try to parse number to bytes" {57 // arrange58 val sut = ByteParser()59 val schema = Schema.Parser().parse("""{ "type": "bytes"}""")60 val decimal = 1.1261 // act62 val res = sut.parse(decimal, schema)63 // assert64 res shouldBeLeft {65 it.shouldBeInstanceOf<JsonFieldParsingException>()66 }67 }68 "return left if try to parse an int to decimal" {69 // arrange70 val sut = ByteParser()71 val schema = Schema.Parser().parse("""{ "type": "bytes", "logicalType": "decimal", "precision": 6, "scale": 4}""")72 val integer = 173 // act74 val res = sut.parse(integer, schema)75 // assert76 res shouldBeLeft {77 it.shouldBeInstanceOf<JsonFieldParsingException>()78 }79 }80 "return left if try to parse an invalid string to bytes" {81 // arrange82 val sut = ByteParser()83 val schema = Schema.Parser().parse("""{ "type": "bytes"}""")84 val invalidString = "0123"85 // act86 val res = sut.parse(invalidString, schema)87 // assert88 res shouldBeLeft {89 it.shouldBeInstanceOf<JsonFieldParsingException>()90 }91 }92})...
json.kt
Source:json.kt
...25 ValidationConfiguration.newBuilder().setDefaultVersion(26 SchemaVersion.DRAFTV427 ).freeze()28).freeze()29suspend fun HttpResponse.json() = Json.parseToJsonElement(body())30suspend fun HttpResponse.firstLinkedItemHref() = json()._links.items.first().href31infix fun HttpResponse.shouldEqualJson(json: String) =32 runBlocking {33 body<String>() shouldEqualJson json34 }35infix fun HttpResponse.shouldMatchJsonSchema(schema: String) =36 runBlocking {37 body<String>() shouldMatchJsonSchema schema38 }39infix fun String.shouldMatchJsonSchema(schema: String) {40 assertionCounter.inc()41 val schemaJson = JsonLoader.fromString(schema.trimIndent())42 val contentJson = JsonLoader.fromString(this)43 val report = schemaFactory.getJsonSchema(schemaJson).validate(contentJson) as ListProcessingReport...
JsonToAvroConverterTest.kt
Source:JsonToAvroConverterTest.kt
...12 "return left if the json provided is invalid" {13 // arrange14 val sut = JsonToAvroConverter(ObjectMapper(), mockk(), mockk())15 // act16 val res = sut.parse("invalid json!!", testSchema)17 // assert18 res shouldBeLeft {19 it.shouldBeInstanceOf<JsonParsingException>()20 }21 }22 "return left if the schema provided is invalid" {23 // arrange24 val sut = JsonToAvroConverter(ObjectMapper(), mockk(), mockk())25 // act26 val res = sut.parse("{}", "invalid schema!")27 // assert28 res shouldBeLeft {29 it.shouldBeInstanceOf<SchemaParsingException>()30 }31 }32 "return the record parse value if the input schema and json are correct" {33 // arrange34 val mockOutputRecord = mockk<GenericRecord>()35 val sut = JsonToAvroConverter(36 ObjectMapper(),37 mockk {38 every { parseField(any(), any()) } returns mockOutputRecord.right()39 },40 mockk {41 every { validate(any(), any()) } returns true42 }43 )44 // act45 val res = sut.parse("{}", testSchema)46 // assert47 res shouldBeRight mockOutputRecord48 }49})50private val testSchema =51 """52 {53 "type": "record", 54 "name": "value_test_schema", 55 "namespace": "com.mycorp.mynamespace", 56 "doc": "Sample schema to help you get started.", 57 "fields": [{ "name": "testArray", "type": {"type" : "array", "items" : "string"} }]58 }59 """.trimIndent()...
RecordParserTest.kt
Source:RecordParserTest.kt
1package insulator.jsonhelper.jsontoavro.fieldparser2import arrow.core.right3import insulator.jsonhelper.jsontoavro.JsonInvalidFieldException4import insulator.jsonhelper.jsontoavro.JsonMissingFieldException5import io.kotest.assertions.arrow.either.shouldBeLeft6import io.kotest.assertions.arrow.either.shouldBeRight7import io.kotest.core.spec.style.StringSpec8import io.kotest.matchers.types.shouldBeInstanceOf9import io.mockk.every10import io.mockk.mockk11import org.apache.avro.Schema12class RecordParserTest : StringSpec({13 val schema = Schema.Parser().parse(14 """15 {16 "type": "record",17 "name": "recordName",18 "fields": [19 { "name": "field1", "type": "string" }20 ]21 }22 """.trimIndent()23 )24 "happy path" {25 // arrange26 val sut = RecordParser(27 mockk {28 every { parseField(any(), any()) } returns "".right()29 }30 )31 // act32 val res = sut.parse(mapOf("field1" to "fieldValue"), schema)33 // assert34 res shouldBeRight {}35 }36 "invalid record" {37 // arrange38 val sut = RecordParser(39 mockk {40 every { parseField(any(), any()) } returns "".right()41 }42 )43 // act44 val res = sut.parse("", schema)45 // assert46 res shouldBeLeft {47 it.shouldBeInstanceOf<JsonInvalidFieldException>()48 }49 }50 "record with a missing field" {51 // arrange52 val sut = RecordParser(53 mockk {54 every { parseField(any(), any()) } returns "".right()55 }56 )57 // act58 val res = sut.parse(emptyMap<String, String>(), schema)59 // assert60 res shouldBeLeft {61 it.shouldBeInstanceOf<JsonMissingFieldException>()62 }63 }64})...
UnionParserTest.kt
Source:UnionParserTest.kt
1package insulator.jsonhelper.jsontoavro.fieldparser2import arrow.core.left3import arrow.core.right4import insulator.jsonhelper.jsontoavro.JsonFieldParsingException5import io.kotest.assertions.arrow.either.shouldBeLeft6import io.kotest.assertions.arrow.either.shouldBeRight7import io.kotest.core.spec.style.StringSpec8import io.kotest.matchers.shouldBe9import io.kotest.matchers.types.shouldBeInstanceOf10import io.mockk.every11import io.mockk.mockk12import org.apache.avro.Schema13class UnionParserTest : StringSpec({14 val schema = Schema.Parser()15 .parse(""" {"type": "record", "name": "unionTest", "fields": [{ "name": "t", "type": [ "null", "string"] }] } """)16 .fields.first().schema()17 "happy path right union" {18 // arrange19 val sut = UnionParser(20 mockk {21 every { parseField(any(), any()) } returns "".right()22 }23 )24 // act25 val res = sut.parse("test-string", schema)26 // assert27 res shouldBeRight {}28 }29 "happy path left union" {30 // arrange31 val sut = UnionParser(32 mockk {33 every { parseField(any(), any()) } returns null.right()34 }35 )36 // act37 val res = sut.parse(null, schema)38 // assert39 res shouldBeRight {}40 }41 "join errors if value doesn't match any type in the union" {42 // arrange43 val sut = UnionParser(44 mockk {45 every { parseField(any(), any()) } returnsMany46 listOf("error1", "error2").map { JsonFieldParsingException(it).left() }47 }48 )49 // act50 val res = sut.parse(1, schema)51 // assert52 res shouldBeLeft {53 it.shouldBeInstanceOf<JsonFieldParsingException>()54 it.message shouldBe "error1\nerror2"55 }56 }57})...
JsonToAvroIntegrationTest.kt
Source:JsonToAvroIntegrationTest.kt
1package insulator.jsonhelper.jsontoavro2import com.fasterxml.jackson.databind.ObjectMapper3import insulator.jsonhelper.jsontoavro.fieldparser.ComplexTypeParsersFactory4import insulator.jsonhelper.jsontoavro.fieldparser.SimpleTypeParsersFactory5import io.kotest.assertions.arrow.either.shouldBeLeft6import io.kotest.assertions.arrow.either.shouldBeRight7import io.kotest.core.spec.style.FreeSpec8import io.kotest.matchers.types.shouldBeInstanceOf9import org.apache.avro.generic.GenericData10class JsonToAvroIntegrationTest : FreeSpec({11 "Happy path" - {12 // arrange13 val fieldParser = FieldParser(SimpleTypeParsersFactory(), ComplexTypeParsersFactory())14 val sut = JsonToAvroConverter(ObjectMapper(), fieldParser, GenericData.get())15 "parse a schema with only a string" {16 val schema = schemaTemplate("""{"name":"test", "type":"string"}""")17 val json =18 """{"test":"123"}"""19 // act20 val res = sut.parse(json, schema)21 // assert22 res shouldBeRight {}23 }24 "left if not all fields are used " {25 val schema = schemaTemplate("""{"name":"test", "type":"string"}""")26 val json =27 """{"test":"123", "unused": 321}"""28 // act29 val res = sut.parse(json, schema)30 // assert31 res shouldBeLeft {32 it.shouldBeInstanceOf<JsonUnexpectedFieldException>()33 }34 }35 }36})37fun schemaTemplate(vararg fieldDef: String) =38 """39 {40 "type": "record",41 "name": "Sample",42 "fields" : [43 ${fieldDef.joinToString()}...
ArrayParserTest.kt
Source:ArrayParserTest.kt
1package insulator.jsonhelper.jsontoavro.fieldparser2import arrow.core.right3import insulator.jsonhelper.jsontoavro.JsonInvalidFieldException4import io.kotest.assertions.arrow.either.shouldBeLeft5import io.kotest.assertions.arrow.either.shouldBeRight6import io.kotest.core.spec.style.StringSpec7import io.kotest.matchers.types.shouldBeInstanceOf8import io.mockk.every9import io.mockk.mockk10import org.apache.avro.Schema11class ArrayParserTest : StringSpec({12 val sampleSchema = Schema.Parser().parse(13 """14 {15 "type": "array",16 "items" : "int"17 }18 """.trimIndent()19 )20 "happy path" {21 // arrange22 val field = ArrayList<Int>(listOf(1, 1, 1, 1, 1))23 val sut = ArrayParser(24 mockk {25 every { parseField(any(), any()) } returns 1.right()26 }27 )28 // act29 val res = sut.parse(field, sampleSchema)30 // assert31 res shouldBeRight field.toList()32 }33 "return left if not an array" {34 // arrange35 val field = 12336 val sut = ArrayParser(mockk())37 // act38 val res = sut.parse(field, sampleSchema)39 // assert40 res shouldBeLeft {41 it.shouldBeInstanceOf<JsonInvalidFieldException>()42 }43 }44 "parse empty arrays successfully" {45 // arrange46 val field = ArrayList<Int>()47 val sut = ArrayParser(mockk())48 // act49 val res = sut.parse(field, sampleSchema)50 // assert51 res shouldBeRight emptyList<Any>()52 }53})...
parse
Using AI Code Generation
1 import io.kotest.assertions.json.schema.parse2 import io.kotest.assertions.json.schema.schema3 import io.kotest.core.spec.style.StringSpec4 import io.kotest.matchers.shouldBe5 class JsonSchemaTest : StringSpec({6 "should validate json against a schema" {7 {8 }9 """.trimIndent()10 {11 "properties": {12 "name": {13 },14 "age": {15 }16 }17 }
parse
Using AI Code Generation
1import io.kotest.assertions.json.schema.*2import io.kotest.core.spec.style.StringSpec3import io.kotest.matchers.shouldBe4import io.kotest.matchers.shouldNotBe5class JsonSchemaTest : StringSpec({6 "json schema test"{7 val json = """{"name": "Kotlin", "age": 2}"""8 val schema = """{"type": "object", "properties": {"name": {"type": "string"}, "age": {"type": "integer"}}, "required": ["name", "age"]}"""9 val result = parse(json, schema)10 }11})
parse
Using AI Code Generation
1 {2 { "name":"Ford", "models":[ "Fiesta", "Focus", "Mustang" ] },3 { "name":"BMW", "models":[ "320", "X3", "X5" ] },4 { "name":"Fiat", "models":[ "500", "Panda" ] }5 }6 """.trimIndent()7 {8 "properties": {9 "name": { "type": "string" },10 "age": { "type": "integer" },11 "cars": {12 "items": {13 "properties": {14 "name": { "type": "string" },15 "models": {16 "items": { "type": "string" }17 }18 },19 }20 }21 },22 }23 """.trimIndent()24json should matchJsonSchema(schema)25 {26 { "name":"Ford", "models":[ "Fiesta", "Focus", "Mustang" ] },27 { "name":"BMW", "models":[ "320", "X3", "X5" ] },28 { "name":"Fiat", "models":[ "500", "Panda" ] }29 }30 """.trimIndent()31 {32 "properties": {33 "name": { "type": "string" },34 "age": { "type": "integer" },35 "cars": {36 "items": {37 "properties": {38 "name": { "type": "string" },39 "models": {
parse
Using AI Code Generation
1{2}3""".trimIndent()4val schema = JsonSchema.parse(5{6 "properties": {7 "name": { "type": "string" },8 "version": { "type": "string" }9 },10}11""".trimIndent()12json should matchJsonSchema(schema)
parse
Using AI Code Generation
1val result = JsonSchemaValidator.validateJsonSchema(json, schema)2val result = JsonSchemaValidator.validateJsonSchema(json, schema, JsonSchemaValidatorConfig(Option.ENABLE))3val result = JsonSchemaValidator.validateJsonSchema(json, schema, JsonSchemaValidatorConfig(Option.ENABLE, Option.ENABLE))4val result = JsonSchemaValidator.validateJsonSchema(json, schema, JsonSchemaValidatorConfig(Option.ENABLE, Option.ENABLE, Option.ENABLE))5val result = JsonSchemaValidator.validateJsonSchema(json, schema, JsonSchemaValidatorConfig(Option.ENABLE, Option.ENABLE, Option.ENABLE, Option.ENABLE))6val result = JsonSchemaValidator.validateJsonSchema(json, schema, JsonSchemaValidatorConfig(Option.ENABLE, Option.ENABLE, Option.ENABLE, Option.ENABLE, Option.ENABLE))7val result = JsonSchemaValidator.validateJsonSchema(json, schema, JsonSchemaValidatorConfig(Option.ENABLE, Option.ENABLE, Option.ENABLE, Option.ENABLE, Option.ENABLE, Option.ENABLE))8val result = JsonSchemaValidator.validateJsonSchema(json, schema, JsonSchemaValidatorConfig(Option.ENABLE, Option.ENABLE, Option.ENABLE, Option.ENABLE, Option.ENABLE, Option.ENABLE, Option.ENABLE))9val result = JsonSchemaValidator.validateJsonSchema(json, schema, JsonSchemaValidatorConfig(Option.ENABLE, Option.ENABLE, Option.ENABLE, Option.ENABLE, Option.ENABLE, Option.ENABLE, Option.ENABLE, Option.ENABLE))
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.
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!!