How to use test method of io.kotest.assertions.json.schema.matchSchema class

Best Kotest code snippet using io.kotest.assertions.json.schema.matchSchema.test

matchSchema.kt

Source:matchSchema.kt Github

copy

Full Screen

1package io.kotest.assertions.json.schema2import io.kotest.assertions.json.JsonNode3import io.kotest.assertions.json.JsonTree4import io.kotest.assertions.json.toJsonTree5import io.kotest.common.ExperimentalKotest6import io.kotest.matchers.Matcher7import io.kotest.matchers.MatcherResult8import io.kotest.matchers.and9import io.kotest.matchers.should10import 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)...

Full Screen

Full Screen

test

Using AI Code Generation

copy

Full Screen

1import io.kotest.assertions.json.schema.matchSchema2import io.kotest.core.spec.style.StringSpec3import io.kotest.matchers.shouldBe4import io.restassured.RestAssured.given5import io.restassured.http.ContentType6import io.restassured.response.Response7import org.junit.jupiter.api.Assertions.assertEquals8import org.junit.jupiter.api.Assertions.assertNotNull9import org.junit.jupiter.api.Assertions.assertTrue10import org.junit.jupiter.api.Test11import org.junit.jupiter.api.TestInstance12import java.io.File13import java.io.IOException14import java.nio.file.Files15import java.nio.file.Paths16@TestInstance(TestInstance.Lifecycle.PER_CLASS)17class BookStoreTest : StringSpec({18"Book Store Test" {19given()20.contentType(ContentType.JSON)21.basePath("/Books")22.when()23.get()24.then()25.statusCode(200)26.log().all()27.matchSchema(File("src/test/resources/schemas/books.json"))28}29})30import io.kotest.assertions.json.schema.matchSchema31import io.kotest.core.spec.style.StringSpec32import io.kotest.matchers.shouldBe33import io.restassured.RestAssured.given34import io.restassured.http.ContentType35import io.restassured.response.Response36import org.junit.jupiter.api.Assertions.assertEquals37import org.junit.jupiter.api.Assertions.assertNotNull38import org.junit.jupiter.api.Assertions.assertTrue39import org.junit.jupiter.api.Test40import org.junit.jupiter.api.TestInstance41import java.io.File42import java.io.IOException43import java.nio.file.Files44import java.nio.file.Paths45@TestInstance(TestInstance.Lifecycle.PER_CLASS)46class BookStoreTest : StringSpec({47"Book Store Test" {48given()49.contentType(ContentType.JSON)50.basePath("/Books")51.when()52.get()53.then()54.statusCode(200)55.log().all()56.matchSchema(File("src/test/resources/schemas/books.json"))57}58})59import io.kotest.assertions.json.schema.matchSchema60import io.kotest.core.spec.style.StringSpec61import io.kotest.matchers.shouldBe62import io.restassured.RestAss

Full Screen

Full Screen

test

Using AI Code Generation

copy

Full Screen

1val jsonSchema = JsonSchemaLoader.load(File("src/test/resources/test.json"))2val json = JsonNodeFactory.instance.objectNode()3json.put("name", "John Doe")4json.put("age", 42)5json.put("address", "123 Fake Street")6json.put("city", "Springfield")7json.put("state", "Illinois")8json.put("zip", "12345")9json.put("phone", "123-456-7890")10json.put("email", "

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