How to use JsonSchema class of io.kotest.assertions.json.schema package

Best Kotest code snippet using io.kotest.assertions.json.schema.JsonSchema

matchSchema.kt

Source:matchSchema.kt Github

copy

Full Screen

...10import io.kotest.matchers.shouldNot11import kotlinx.serialization.json.Json12import kotlinx.serialization.json.JsonElement13@ExperimentalKotest14infix fun String?.shouldMatchSchema(schema: JsonSchema) =15 this should parseToJson.and(matchSchema(schema).contramap<String?> { it?.let(Json::parseToJsonElement) })16@ExperimentalKotest17infix fun String?.shouldNotMatchSchema(schema: JsonSchema) =18 this shouldNot parseToJson.and(matchSchema(schema).contramap<String?> { it?.let(Json::parseToJsonElement) })19@ExperimentalKotest20infix fun JsonElement.shouldMatchSchema(schema: JsonSchema) = this should matchSchema(schema)21@ExperimentalKotest22infix fun JsonElement.shouldNotMatchSchema(schema: JsonSchema) = this shouldNot matchSchema(schema)23val parseToJson = object : Matcher<String?> {24 override fun test(value: String?): MatcherResult {25 if (value == null) return MatcherResult(26 false,27 { "expected null to match schema: " },28 { "expected not to match schema, but null matched JsonNull schema" }29 )30 val parsed = runCatching {31 Json.parseToJsonElement(value)32 }33 return MatcherResult(34 parsed.isSuccess,35 { "Failed to parse actual as JSON: ${parsed.exceptionOrNull()?.message}" },36 { "Failed to parse actual as JSON: ${parsed.exceptionOrNull()?.message}" },37 )38 }39}40@ExperimentalKotest41fun matchSchema(schema: JsonSchema) = object : Matcher<JsonElement?> {42 override fun test(value: JsonElement?): MatcherResult {43 if (value == null) return MatcherResult(44 false,45 { "expected null to match schema: " },46 { "expected not to match schema, but null matched JsonNull schema" }47 )48 val tree = toJsonTree(value)49 val violations = validate("$", tree.root, schema.root)50 return MatcherResult(51 violations.isEmpty(),52 { violations.joinToString(separator = "\n") { "${it.path} => ${it.message}" } },53 { "Expected some violation against JSON schema, but everything matched" }54 )55 }56}57@ExperimentalKotest58private fun validate(59 currentPath: String,60 tree: JsonNode,61 expected: JsonSchemaElement,62): List<SchemaViolation> {63 fun propertyViolation(propertyName: String, message: String) =64 listOf(SchemaViolation("$currentPath.$propertyName", message))65 fun violation(message: String) =66 listOf(SchemaViolation(currentPath, message))67 return when (tree) {68 is JsonNode.ArrayNode -> {69 if (expected is JsonSchema.JsonArray)70 tree.elements.flatMapIndexed { i, node ->71 validate("$currentPath[$i]", node, expected.elementType)72 }73 else violation("Expected ${expected.typeName()}, but was array")74 }75 is JsonNode.ObjectNode -> {76 if (expected is JsonSchema.JsonObject) {77 val extraKeyViolations =78 if (!expected.additionalProperties)79 tree.elements.keys80 .filterNot { it in expected.properties.keys }81 .flatMap {82 propertyViolation(it, "Key undefined in schema, and schema is set to disallow extra keys")83 }84 else emptyList()85 extraKeyViolations + expected.properties.flatMap { (propertyName, schema) ->86 val actual = tree.elements[propertyName]87 if (actual == null) {88 if (expected.requiredProperties.contains(propertyName)) {89 propertyViolation(propertyName, "Expected ${schema.typeName()}, but was undefined")90 } else {91 emptyList()92 }93 } else validate("$currentPath.$propertyName", actual, schema)94 }95 } else violation("Expected ${expected.typeName()}, but was object")96 }97 is JsonNode.NullNode -> TODO("Check how Json schema handles null")98 is JsonNode.NumberNode ->99 when (expected) {100 is JsonSchema.JsonInteger -> {101 if (tree.content.contains(".")) violation("Expected integer, but was number")102 else expected.matcher?.let {103 val matcherResult = it.test(tree.content.toLong())104 if (matcherResult.passed()) emptyList() else violation(matcherResult.failureMessage())105 } ?: emptyList()106 }107 is JsonSchema.JsonDecimal -> {108 expected.matcher?.let {109 val matcherResult = it.test(tree.content.toDouble())110 if (matcherResult.passed()) emptyList() else violation(matcherResult.failureMessage())111 } ?: emptyList()112 }113 else -> violation("Expected ${expected.typeName()}, but was ${tree.type()}")114 }115 is JsonNode.StringNode ->116 if (expected is JsonSchema.JsonString) {117 expected.matcher?.let {118 val matcherResult = it.test(tree.value)119 if (matcherResult.passed()) emptyList() else violation(matcherResult.failureMessage())120 } ?: emptyList()121 } else violation("Expected ${expected.typeName()}, but was ${tree.type()}")122 is JsonNode.BooleanNode ->123 if (!isCompatible(tree, expected))124 violation("Expected ${expected.typeName()}, but was ${tree.type()}")125 else emptyList()126 }127}128private class SchemaViolation(129 val path: String,130 message: String,131 cause: Throwable? = null132) : RuntimeException(message, cause)133private fun isCompatible(actual: JsonNode, schema: JsonSchemaElement) =134 (actual is JsonNode.BooleanNode && schema is JsonSchema.JsonBoolean) ||135 (actual is JsonNode.StringNode && schema is JsonSchema.JsonString) ||136 (actual is JsonNode.NumberNode && schema is JsonSchema.JsonNumber)...

Full Screen

Full Screen

BigQuerySchemaTest.kt

Source:BigQuerySchemaTest.kt Github

copy

Full Screen

...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})...

Full Screen

Full Screen

PrimitiveMatchSchemaTest.kt

Source:PrimitiveMatchSchemaTest.kt Github

copy

Full Screen

1package io.kotest.assertions.json.schema2import io.kotest.assertions.shouldFail3import io.kotest.core.spec.style.FunSpec4import io.kotest.matchers.shouldBe5import io.kotest.matchers.string.shouldContain6class PrimitiveMatchSchemaTest : FunSpec(7 {8 test("invalid json") {9 shouldFail {10 "[" shouldMatchSchema jsonSchema { obj() }11 }.message shouldContain "Failed to parse actual as JSON"12 }13 context("boolean schemas") {14 val boolSchema = jsonSchema { boolean() }15 test("boolean values match bool schema") {16 "true" shouldMatchSchema boolSchema17 "false" shouldMatchSchema boolSchema18 }19 test("number mismatches") {20 shouldFail {21 "0" shouldMatchSchema boolSchema22 }.message shouldBe """23 $ => Expected boolean, but was number24 """.trimIndent()25 }26 }27 context("String schema") {28 val schema = jsonSchema { string() }29 test("string matches string schema") {30 "\"hello, world!\"" shouldMatchSchema schema31 }32 test("boolean does not match string schema") {33 shouldFail { "false" shouldMatchSchema schema }.message shouldBe """34 $ => Expected string, but was boolean35 """.trimIndent()36 }37 test("object does not match string schema") {38 shouldFail { """{ "greeting": "hello" }""" shouldMatchSchema schema }.message shouldBe """39 $ => Expected string, but was object40 """.trimIndent()41 }42 }43 context("numbers") {44 val numberSchema = jsonSchema { number() }45 test("all numbers match number schema") {46 "5" shouldMatchSchema numberSchema47 "3.14" shouldMatchSchema numberSchema48 "0" shouldMatchSchema numberSchema49 "-1" shouldMatchSchema numberSchema50 }51 test("Non-number causes failure") {52 shouldFail { "false" shouldMatchSchema numberSchema }.message shouldBe """53 $ => Expected number, but was boolean54 """.trimIndent()55 }56 test("String cause failure") {57 shouldFail {58 "\"5\"" shouldMatchSchema numberSchema59 }.message shouldBe """60 $ => Expected number, but was string61 """.trimIndent()62 }63 test("negated assertion works") {64 "false" shouldNotMatchSchema numberSchema65 }66 }67 context("integers") {68 val intSchema = jsonSchema { integer() }69 test("integers match int schema") {70 "5" shouldMatchSchema intSchema71 "0" shouldMatchSchema intSchema72 "-1" shouldMatchSchema intSchema73 }74 test("decimals cause failures") {75 shouldFail { "5.2" shouldMatchSchema intSchema }.message shouldBe """76 $ => Expected integer, but was number77 """.trimIndent()78 }79 test("Non-number causes failure") {80 shouldFail { "false" shouldMatchSchema intSchema }.message shouldBe """81 $ => Expected integer, but was boolean82 """.trimIndent()83 }84 test("String cause failure") {85 shouldFail {86 "\"5\"" shouldMatchSchema intSchema87 }.message shouldBe """88 $ => Expected integer, but was string89 """.trimIndent()90 }91 test("negated assertion works") {92 "false" shouldNotMatchSchema intSchema93 }94 }95 }96)...

Full Screen

Full Screen

build.gradle.kts

Source:build.gradle.kts Github

copy

Full Screen

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}...

Full Screen

Full Screen

SchemaServiceImplTest.kt

Source:SchemaServiceImplTest.kt Github

copy

Full Screen

1package org.factcast.schema.registry.cli.utils2import com.fasterxml.jackson.databind.JsonNode3import com.github.fge.jsonschema.core.exceptions.ProcessingException4import com.github.fge.jsonschema.main.JsonSchema5import com.github.fge.jsonschema.main.JsonSchemaFactory6import io.kotest.assertions.arrow.core.shouldBeLeft7import io.kotest.assertions.arrow.core.shouldBeRight8import io.kotest.core.spec.style.StringSpec9import io.kotest.core.test.TestCase10import io.kotest.core.test.TestResult11import io.kotest.matchers.shouldBe12import io.kotest.matchers.types.shouldBeInstanceOf13import io.mockk.clearAllMocks14import io.mockk.every15import io.mockk.mockk16import io.mockk.verifyAll17import org.factcast.schema.registry.cli.fs.FileSystemService18import 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}...

Full Screen

Full Screen

SchemaWithMatcherTest.kt

Source:SchemaWithMatcherTest.kt Github

copy

Full Screen

1package io.kotest.assertions.json.schema2import io.kotest.assertions.shouldFail3import io.kotest.core.spec.style.FunSpec4import io.kotest.matchers.and5import io.kotest.matchers.doubles.beGreaterThanOrEqualTo6import io.kotest.matchers.doubles.beLessThanOrEqualTo7import io.kotest.matchers.doubles.beMultipleOf8import io.kotest.matchers.ints.beEven9import io.kotest.matchers.ints.beInRange10import io.kotest.matchers.longs.beInRange11import io.kotest.matchers.shouldBe12import io.kotest.matchers.string.haveMaxLength13import io.kotest.matchers.string.haveMinLength14import io.kotest.matchers.types.beInstanceOf15class SchemaWithMatcherTest : FunSpec(16 {17 test("Even numbers") {18 val evenNumbers = jsonSchema { number { beMultipleOf(2.0) } }19 "2" shouldMatchSchema evenNumbers20 shouldFail { "3" shouldMatchSchema evenNumbers }21 .message shouldBe """22 $ => 3.0 should be multiple of 2.023 """.trimIndent()24 }25 context("smoke") {26 val schema = jsonSchema {27 array {28 obj {29 withProperty("name") { string { haveMinLength(3) and haveMaxLength(20) } }30 withProperty("age") { number { beGreaterThanOrEqualTo(0.0) and beLessThanOrEqualTo(120.0) } }31 }32 }33 }34 test("Violating schema") {35 shouldFail {36 // language=JSON37 """38 [39 {40 "name": "bo",41 "age": 9242 },43 {44 "name": "sophie",45 "age": 3346 },47 {48 "name": "joe",49 "age": -150 },51 {52 "name": "alexander the extremely great",53 "age": 1254 }55 ]56 """ shouldMatchSchema schema57 }.message shouldBe """58 $[0].name => "bo" should have minimum length of 359 $[2].age => -1.0 should be >= 0.060 $[3].name => "alexander the extremely great" should have maximum length of 2061 """.trimIndent()62 }63 }64 }65)...

Full Screen

Full Screen

json.kt

Source:json.kt Github

copy

Full Screen

2import 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}...

Full Screen

Full Screen

ArraySchemaTest.kt

Source:ArraySchemaTest.kt Github

copy

Full Screen

1package io.kotest.assertions.json.schema2import io.kotest.assertions.shouldFail3import io.kotest.core.spec.style.FunSpec4import io.kotest.matchers.shouldBe5import org.intellij.lang.annotations.Language6class ArraySchemaTest : FunSpec(7 {8 fun json(@Language("JSON") raw: String) = raw9 val numberArray = jsonSchema { array { number() } }10 val person = jsonSchema {11 obj {12 withProperty("name", required = true) { string() }13 withProperty("age", required = true) { number() }14 }15 }16 val personArray = jsonSchema { array { person() } }17 test("Array with correct elements match") {18 """[1, 2]""" shouldMatchSchema numberArray19 }20 test("Problems compound") {21 shouldFail { """["one", "two"]""" shouldMatchSchema numberArray }.message shouldBe """22 $[0] => Expected number, but was string23 $[1] => Expected number, but was string24 """.trimIndent()25 }26 test("empty array is ok") {27 "[]" shouldMatchSchema personArray28 }29 test("array with partial inner match is not ok") {30 val missingAge =31 """32 [33 { "name": "bob" },34 { "name": "bob", "age": 3 },35 { "name": "bob" }36 ]37 """.trimIndent()38 missingAge shouldNotMatchSchema personArray39 shouldFail { missingAge shouldMatchSchema personArray }.message shouldBe """40 $[0].age => Expected number, but was undefined41 $[2].age => Expected number, but was undefined42 """.trimIndent()43 }44 }45)...

Full Screen

Full Screen

JsonSchema

Using AI Code Generation

copy

Full Screen

1import io.kotest.assertions.json.schema.JsonSchema2import io.kotest.assertions.json.schema.jsonSchema3import io.kotest.assertions.json.schema.shouldMatchJsonSchema4import io.kotest.core.spec.style.StringSpec5class JsonSchemaTest : StringSpec({6 "should validate json"{7 val schema = jsonSchema {8 "properties" to {9 "name" to {10 }11 "age" to {12 }13 }14 }15 {16 }17 """.trimIndent()18 }19})20import com.github.fge.jsonschema.SchemaVersion21import com.github.fge.jsonschema.main.JsonSchemaFactory22import com.github.fge.jsonschema.main.JsonSchemaFactoryBuilder23import io.kotest.assertions.json.shouldMatchJsonSchema24import io.kotest.core.spec.style.StringSpec25class JsonSchemaTest : StringSpec({26 "should validate json"{27 {28 "properties": {29 "name": {30 },31 "age": {32 }33 }34 }35 """.trimIndent()36 {37 }38 """.trimIndent()39 val factory: JsonSchemaFactory = JsonSchemaFactoryBuilder()40 .setValidationConfiguration(41 JsonSchemaFactoryBuilder.ValidationConfigurationBuilder()42 .setDefaultVersion(SchemaVersion.DRAFTV4)43 .freeze()44 ).freeze()45 }46})47import com.networknt.schema.JsonSchemaFactory48import io.kotest.assertions.json.shouldMatchJsonSchema49import io.kotest.core.spec.style.StringSpec50class JsonSchemaTest : StringSpec({51 "should validate json"{52 {53 "properties": {54 "name": {55 },56 "age": {

Full Screen

Full Screen

JsonSchema

Using AI Code Generation

copy

Full Screen

1val schema = JsonSchema . parse ( File ( "src/test/resources/schema.json" )) val json = File ( "src/test/resources/data.json" ). readText () schema . shouldMatchJson ( json )2val schema = JsonSchema . parse ( File ( "src/test/resources/schema.json" )) val json = File ( "src/test/resources/data.json" ). readText () schema . shouldNotMatchJson ( json )3val schema = JsonSchema . parse ( File ( "src/test/resources/schema.json" )) val json = File ( "src/test/resources/data.json" ). readText () schema . shouldContainJson ( json )4val schema = JsonSchema . parse ( File ( "src/test/resources/schema.json" )) val json = File ( "src/test/resources/data.json" ). readText () schema . shouldNotContainJson ( json )5val schema = JsonSchema . parse ( File ( "src/test/resources/schema.json" )) val json = File ( "src/test/resources/data.json" ). readText () schema . shouldContainJson ( json )6val schema = JsonSchema . parse ( File ( "src/test/resources/schema.json" )) val json = File ( "src/test/resources/data.json" ). readText () schema . shouldNotContainJson ( json )7val schema = JsonSchema . parse ( File

Full Screen

Full Screen

JsonSchema

Using AI Code Generation

copy

Full Screen

1val schema = JsonSchema (2{3"properties": {4"foo": {5},6"bar": {7}8}9}10{11}12schema . validate ( json )13val schema = JsonSchema (14{15"properties": {16"foo": {17},18"bar": {19}20}21}22{23}24schema . validate ( json )25val schema = JsonSchema (26{27"properties": {28"foo": {29},30"bar": {31}32}33}34{35}36schema . validate ( json )37val schema = JsonSchema (38{39"properties": {40"foo": {41},42"bar": {43}44}45}46{47}48schema . validate ( json )49val schema = JsonSchema (50{51"properties": {52"foo": {53},54"bar": {55}56}57}58{59}60schema . validate ( json )61val schema = JsonSchema (62{63"properties": {64"foo": {65},66"bar": {67}68}69}70{71}72schema . validate ( json )

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.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful