Best Kotest code snippet using io.kotest.assertions.json.schema.JsonSchema.typeName
builder.kt
Source:builder.kt
...10@JsonSchemaMarker11@ExperimentalKotest12@Serializable(with = SchemaDeserializer::class)13sealed interface JsonSchemaElement {14 fun typeName(): String15}16internal interface ValueNode<T> {17 val matcher: Matcher<T>?18 get() = null19}20@ExperimentalKotest21data class JsonSchema(22 val root: JsonSchemaElement23) {24 /**25 * Provides a way to access pre-defined schemas in a conventional way (e.g. `type()`). Example:26 * ```kotlin27 * val addressSchema = jsonSchema {28 * obj {29 * withProperty("street") { string() }30 * withProperty("zipCode") { integer { beEven() } }31 * }32 * }33 *34 * val personSchema = jsonSchema {35 * obj {36 * withProperty("name") { string() }37 * withProperty("address") { addressSchema() }38 * }39 * }40 * ```41 */42 @ExperimentalKotest43 operator fun invoke() = root44 object Builder45 internal interface JsonNumber46 @Serializable47 data class JsonArray(val elementType: JsonSchemaElement) : JsonSchemaElement {48 override fun typeName() = "array"49 }50 class JsonObjectBuilder {51 var additionalProperties: Boolean = true52 var minProperties: Int = 053 var maxProperties: Int? = null54 var properties: MutableMap<String, JsonSchemaElement> = mutableMapOf()55 /**56 * https://json-schema.org/understanding-json-schema/reference/object.html#required-properties57 */58 var requiredProperties: MutableList<String> = mutableListOf()59 /**60 * By default properties are optional.61 * Using [required], you can specify that it must be included.62 */63 fun withProperty(64 name: String,65 required: Boolean = false,66 elementBuilder: JsonSchema.Builder.() -> JsonSchemaElement67 ) {68 properties[name] = JsonSchema.Builder.elementBuilder()69 if (required) requiredProperties.add(name)70 }71 fun build() = JsonObject(72 additionalProperties = additionalProperties,73 minProperties = minProperties,74 maxProperties = maxProperties,75 properties = properties,76 requiredProperties = requiredProperties.toTypedArray()77 )78 }79 @Serializable80 data class JsonObject(81 /**82 * Controls whether this node allows additional properties to be defined or not.83 * By default, additional properties are _allowed_84 *85 * https://json-schema.org/understanding-json-schema/reference/object.html#additional-properties86 */87 val additionalProperties: Boolean = true,88 val minProperties: Int = 0,89 val maxProperties: Int? = null,90 val properties: Map<String, JsonSchemaElement>,91 /**92 * https://json-schema.org/understanding-json-schema/reference/object.html#required-properties93 */94 val requiredProperties: Array<String> = emptyArray(),95 ) : JsonSchemaElement {96 operator fun get(name: String) = properties.get(name)97 override fun typeName() = "object"98 }99 data class JsonString(override val matcher: Matcher<String>? = null) : JsonSchemaElement, ValueNode<String> {100 override fun typeName() = "string"101 }102 data class JsonInteger(103 override val matcher: Matcher<Long>? = null104 ) : JsonSchemaElement, JsonNumber, ValueNode<Long> {105 override fun typeName() = "integer"106 }107 data class JsonDecimal(108 override val matcher: Matcher<Double>? = null109 ) : JsonSchemaElement, JsonNumber, ValueNode<Double> {110 override fun typeName() = "number"111 }112 @Serializable113 object JsonBoolean : JsonSchemaElement, ValueNode<Boolean> {114 override fun typeName() = "boolean"115 }116 @Serializable117 object Null : JsonSchemaElement {118 override fun typeName() = "null"119 }120}121/**122 * Creates a [JsonSchema.JsonString] node, which is a leaf node that will hold a [String] value.123 * Optionally, you can provide a [matcherBuilder] that constructs a [Matcher] which the node will be tested with.124 */125@ExperimentalKotest126fun JsonSchema.Builder.string(matcherBuilder: () -> Matcher<String>? = { null }) =127 JsonSchema.JsonString(matcherBuilder())128/**129 * Creates a [JsonSchema.JsonInteger] node, which is a leaf node that will hold a [Long] value.130 * Optionally, you can provide a [matcherBuilder] that constructs a [Matcher] which the node will be tested with.131 */132@ExperimentalKotest...
matchSchema.kt
Source:matchSchema.kt
...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)...
typeName
Using AI Code Generation
1val jsonSchema = JsonSchema(2properties = mapOf(3"firstName" to JsonSchema(type = "string"),4"lastName" to JsonSchema(type = "string"),5"age" to JsonSchema(type = "integer"),6"address" to JsonSchema(7properties = mapOf(8"streetAddress" to JsonSchema(type = "string"),9"city" to JsonSchema(type = "string"),10"state" to JsonSchema(type = "string")11val json = """{12"address": {13}14}"""15jsonSchema.validate(json)16val jsonSchema = JsonSchema(17properties = mapOf(18"firstName" to JsonSchema(type = "string"),19"lastName" to JsonSchema(type = "string"),20"age" to JsonSchema(type = "integer"),21"address" to JsonSchema(22properties = mapOf(23"streetAddress" to JsonSchema(type = "string"),24"city" to JsonSchema(type = "string"),25"state" to JsonSchema(type = "string")26val json = """{27"address": {28}29}"""30jsonSchema.validate(json)31val jsonSchema = JsonSchema(32properties = mapOf(33"firstName" to JsonSchema(type = "string"),34"lastName" to JsonSchema(type = "string"),35"age" to JsonSchema(type = "integer"),36"address" to JsonSchema(37properties = mapOf(38"streetAddress" to JsonSchema(type = "string"),39"city" to JsonSchema(type = "string"),40"state" to JsonSchema(type = "string")41val json = """{
typeName
Using AI Code Generation
1val schema = JsonSchema.typeName("string")2val schema = JsonSchema.property("type", "string")3val schema = JsonSchema.properties(4val schema = JsonSchema.required(5val schema = JsonSchema.array(6val schema = JsonSchema.oneOf(7 JsonSchema.typeName("string"),8 JsonSchema.typeName("number")9val schema = JsonSchema.anyOf(10 JsonSchema.typeName("string"),11 JsonSchema.typeName("number")12val schema = JsonSchema.allOf(13 JsonSchema.typeName("string"),14 JsonSchema.property("maxLength", 3)
typeName
Using AI Code Generation
1val jsonSchema = JsonSchema . from ( " { \" type \" : \" string \" } " ) 2 val result = jsonSchema . typeName () 3val jsonSchema = JsonSchema . from ( " { \" type \" : \" string \" } " ) 4 val result = jsonSchema . type () 5val jsonSchema = JsonSchema . from ( " { \" items \" : \" string \" } " ) 6 val result = jsonSchema . items () 7val jsonSchema = JsonSchema . from ( " { \" properties \" : \" string \" } " ) 8 val result = jsonSchema . properties () 9val jsonSchema = JsonSchema . from ( " { \" additionalProperties \" : \" string \" } " ) 10 val result = jsonSchema . additionalProperties () 11val jsonSchema = JsonSchema . from ( " { \" patternProperties \" : \" string \" } " ) 12 val result = jsonSchema . patternProperties () 13val jsonSchema = JsonSchema . from ( " { \" additionalItems \" : \" string \" } " ) 14 val result = jsonSchema . additionalItems () 15val jsonSchema = JsonSchema . from ( " { \" definitions \" : \" string \" } " ) 16 val result = jsonSchema . definitions ()
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!!