Best Kotest code snippet using io.kotest.assertions.json.schema.JsonSchema.jsonSchema
BigQuerySchemaTest.kt
Source:BigQuerySchemaTest.kt
...6import io.kotest.core.spec.style.FunSpec7import io.kotest.inspectors.shouldForAny8import io.kotest.matchers.shouldBe9import no.vegvesen.saga.modules.gcp.bigquery.BigQuerySchema10val jsonSchemaForRecordsAndArrays = """11[{12 "name": "structField",13 "type": "RECORD",14 "description": "Description of field",15 "mode": "REQUIRED",16 "fields": [17 {18 "mode": "NULLABLE",19 "type": "STRING",20 "name": "stringField",21 "description": "Description of field"22 },23 {24 "name": "structField2",25 "type": "RECORD",26 "description": "Description of field",27 "mode": "REPEATED",28 "fields": [29 {30 "mode": "NULLABLE",31 "type": "STRING",32 "name": "stringField2",33 "description": "Description of field"34 }35 ]36 }37 ]38}]39""".trimIndent()40val jsonSchemaForStructsAndArrays = """41[{42 "name": "structField",43 "type": "STRUCT",44 "description": "Description of field",45 "mode": "REQUIRED",46 "fields": [47 {48 "mode": "NULLABLE",49 "type": "INT64",50 "name": "int64Field",51 "description": "Description of int64field"52 },53 {54 "name": "structField2",55 "type": "STRUCT",56 "description": "Description of field",57 "mode": "REPEATED",58 "fields": [59 {60 "mode": "NULLABLE",61 "type": "GEOGRAPHY",62 "name": "geoField",63 "description": "Description of field"64 }65 ]66 }67 ]68}]69""".trimIndent()70// Missing fields definition71val invalidJsonSchemaForStruct = """72[{73 "name": "structField",74 "type": "RECORD",75 "description": "Description of field",76 "mode": "REQUIRED"77}]78""".trimIndent()79enum class SimpleMode {80 REQUIRED,81 NULLABLE82}83fun fieldJson(type: StandardSQLTypeName, mode: SimpleMode) = """84{85 "description": "Test description for field",86 "name": "${type}_${mode}_name",87 "type": "$type",88 "mode": "$mode"89}90""".trimIndent()91fun generateJsonSchemaForSimpleTypes() =92 combineTypes(StandardSQLTypeName.values(), SimpleMode.values())93 .filter { it.first != StandardSQLTypeName.ARRAY && it.first != StandardSQLTypeName.STRUCT }94 .joinToString { (type, mode) -> fieldJson(type, mode) }95 .let { "[ $it ]" }96private fun combineTypes(types: Array<StandardSQLTypeName>, modes: Array<SimpleMode>) = types97 .flatMap { type ->98 modes.map { mode ->99 Pair(type, mode)100 }101 }102class BqQuerySchemaTest : FunSpec({103 test("list of simple field types works as expected") {104 val jsonSchema = generateJsonSchemaForSimpleTypes()105 val schema = BigQuerySchema.fromJsonSchema(jsonSchema)106 schema.fields.size shouldBe 28107 schema.fields.shouldForAny { it.mode == Field.Mode.REQUIRED && it.type == LegacySQLTypeName.STRING }108 schema.fields.shouldForAny { it.mode == Field.Mode.NULLABLE && it.type == LegacySQLTypeName.BOOLEAN }109 }110 test("schema for nested records and arrays is correctly parsed") {111 val jsonSchema = jsonSchemaForRecordsAndArrays112 val schema = BigQuerySchema.fromJsonSchema(jsonSchema)113 schema.fields.size shouldBe 1114 schema.fields["structField"].mode shouldBe Field.Mode.REQUIRED115 schema.fields["structField"].subFields.size shouldBe 2116 schema.fields["structField"].subFields["structField2"].mode shouldBe Field.Mode.REPEATED117 schema.fields["structField"].subFields["structField2"].subFields["stringField2"].mode shouldBe Field.Mode.NULLABLE118 schema.fields["structField"].subFields["structField2"].subFields["stringField2"].description shouldBe "Description of field"119 }120 test("invalid struct schema throws exception") {121 val jsonSchema = invalidJsonSchemaForStruct122 shouldThrow<IllegalArgumentException> {123 BigQuerySchema.fromJsonSchema(jsonSchema)124 }125 }126 test("schema with Standard SQL is correctly parsed") {127 val schema = BigQuerySchema.fromJsonSchema(jsonSchemaForStructsAndArrays)128 schema.fields.size shouldBe 1129 schema.fields["structField"].subFields["int64Field"].description shouldBe "Description of int64field"130 }131})...
build.gradle.kts
Source:build.gradle.kts
1import org.jetbrains.kotlin.gradle.tasks.KotlinCompile2plugins {3 kotlin("jvm") version "1.6.21"4 kotlin("plugin.serialization") version "1.6.21"5 jacoco6 application7 `maven-publish`8}9group = "id.walt"10version = "1.19.0-SNAPSHOT"11repositories {12 mavenCentral()13 maven("https://maven.walt.id/repository/waltid/")14}15dependencies {16 /* JSON */17 implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.3.2")18 implementation("com.github.victools:jsonschema-generator:4.24.2")19 implementation("com.networknt:json-schema-validator:1.0.69")20 implementation("net.pwall.json:json-kotlin-schema:0.34")21 implementation("com.beust:klaxon:5.6")22 /* Logging */23 implementation("org.lighthousegames:logging-jvm:1.2.0")24 implementation("org.slf4j:slf4j-simple:1.7.36")25 /* Kotlin */26 // Reflection27 implementation("org.jetbrains.kotlin:kotlin-reflect:1.6.21")28 // Kotlin29 implementation("org.jetbrains.kotlin:kotlin-stdlib:1.6.21")30 /* JWT */31 implementation("com.nimbusds:nimbus-jose-jwt:9.22")32 /* Testing */33 testImplementation("io.kotest:kotest-runner-junit5:5.3.0")34 testImplementation("io.kotest:kotest-assertions-core:5.3.0")35 testImplementation("io.kotest:kotest-assertions-json:5.3.0")36}37tasks.withType<Test> {38 useJUnitPlatform()39}40publishing {41 publications {42 create<MavenPublication>("mavenJava") {43 pom {44 name.set("waltid-ssikit-vclib")45 description.set("Typesafe implementation of W3C Verifiable Credentials in order to facilitate interoperability among various applications.")46 url.set("https://walt.id")47 }48 from(components["java"])49 }50 }51 repositories {52 maven {53 url = uri("https://maven.walt.id/repository/waltid-ssi-kit/")54 val usernameFile = File("secret_maven_username.txt")55 val passwordFile = File("secret_maven_password.txt")56 val secretMavenUsername = System.getenv()["SECRET_MAVEN_USERNAME"] ?: if (usernameFile.isFile) { usernameFile.readLines()[0] } else { "" }57 val secretMavenPassword = System.getenv()["SECRET_MAVEN_PASSWORD"] ?: if (passwordFile.isFile) { passwordFile.readLines()[0] } else { "" }58 credentials {59 username = secretMavenUsername60 password = secretMavenPassword61 }62 }63 }64}65java {66 toolchain {67 languageVersion.set(JavaLanguageVersion.of(16))68 }69}70tasks.withType<KotlinCompile> {71 kotlinOptions.jvmTarget = "16"72}73jacoco.toolVersion = "0.8.8"74tasks.jacocoTestReport {75 reports {76 xml.required.set(true)77 }78}...
SchemaServiceImplTest.kt
Source:SchemaServiceImplTest.kt
...18import org.factcast.schema.registry.cli.validation.ProjectError19import java.nio.file.Paths20class SchemaServiceImplTest : StringSpec() {21 val fs = mockk<FileSystemService>()22 val jsonSchemaFactory = mockk<JsonSchemaFactory>()23 val schemaMock = mockk<JsonSchema>()24 val jsonNodeMock = mockk<JsonNode>()25 val dummyPath = Paths.get(".")26 val uut = SchemaServiceImpl(fs, jsonSchemaFactory)27 override fun afterTest(testCase: TestCase, result: TestResult) {28 clearAllMocks()29 }30 init {31 "loadSchema for invalid path" {32 every { fs.readToJsonNode(dummyPath) } returns null33 uut.loadSchema(dummyPath).shouldBeLeft().also {34 it.shouldBeInstanceOf<ProjectError.NoSuchFile>()35 }36 verifyAll {37 fs.readToJsonNode(dummyPath)38 }39 }40 "loadSchema for corrupted schema" {41 every { fs.readToJsonNode(dummyPath) } returns jsonNodeMock42 every { jsonSchemaFactory.getJsonSchema(any<JsonNode>()) } throws ProcessingException("")43 uut.loadSchema(dummyPath).shouldBeLeft().also {44 it.shouldBeInstanceOf<ProjectError.CorruptedSchema>()45 }46 verifyAll {47 fs.readToJsonNode(dummyPath)48 jsonSchemaFactory.getJsonSchema(any<JsonNode>())49 }50 }51 "loadSchema for valid schema" {52 every { fs.readToJsonNode(dummyPath) } returns jsonNodeMock53 every { jsonSchemaFactory.getJsonSchema(any<JsonNode>()) } returns schemaMock54 uut.loadSchema(dummyPath).shouldBeRight().also {55 it shouldBe schemaMock56 }57 verifyAll {58 fs.readToJsonNode(dummyPath)59 jsonSchemaFactory.getJsonSchema(any<JsonNode>())60 }61 }62 }63}...
json.kt
Source:json.kt
1package com.acme.web.test2import com.github.fge.jackson.JsonLoader3import com.github.fge.jsonschema.SchemaVersion4import com.github.fge.jsonschema.cfg.ValidationConfiguration5import com.github.fge.jsonschema.core.report.ListProcessingReport6import com.github.fge.jsonschema.main.JsonSchemaFactory7import io.kotest.assertions.assertionCounter8import io.kotest.assertions.failure9import io.kotest.assertions.json.shouldEqualJson10import io.kotest.common.runBlocking11import io.ktor.client.call.body12import io.ktor.client.statement.HttpResponse13import kotlinx.serialization.json.Json14import kotlinx.serialization.json.JsonElement15import kotlinx.serialization.json.JsonObject16import kotlinx.serialization.json.jsonArray17import kotlinx.serialization.json.jsonObject18import kotlinx.serialization.json.jsonPrimitive19@Suppress("ObjectPropertyName")20val JsonElement._links get() = this.jsonObject["_links"]!!.jsonObject21val JsonObject.self get() = this["self"]!!.jsonObject22val JsonObject.href get() = this["href"]!!.jsonPrimitive.content23val JsonObject.items get() = this["items"]!!.jsonArray.map { it.jsonObject }24private val schemaFactory = JsonSchemaFactory.newBuilder().setValidationConfiguration(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 ListProcessingReport44 if (!report.isSuccess) {45 failure(report.asJson().toPrettyString())46 }47}...
jsonSchema
Using AI Code Generation
1val json = """{"name": "John", "age": 30}"""2val schema = """{"type": "object", "properties": {"name": {"type": "string"}, "age": {"type": "number"}}}"""3jsonSchema(schema, json)4val json = """{"name": "John", "age": 30}"""5val schema = """{"type": "object", "properties": {"name": {"type": "string"}, "age": {"type": "number"}}}"""6jsonSchema(schema, json, errorMessage)7val json = """{"name": "John", "age": 30}"""8val schema = """{"type": "object", "properties": {"name": {"type": "string"}, "age": {"type": "number"}}}"""9val errorMessage = { "Custom error message" }10jsonSchema(schema, json, errorMessage)11val json = """{"name": "John", "age": 30}"""12val schemaFile = File("path/to/jsonSchema.json")13jsonSchema(schemaFile, json)14val json = """{"name": "John", "age": 30}"""15val schemaFile = File("path/to/jsonSchema.json")16jsonSchema(schemaFile, json, errorMessage)17val json = """{"name": "John", "age": 30}"""18val schemaFile = File("path/to/jsonSchema.json")19val errorMessage = { "Custom error message" }
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!!