run.qontract.core.value.JSONObjectValue.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of qontract-core Show documentation
Show all versions of qontract-core Show documentation
A Contract Testing Tool that leverages Gherkin to describe APIs in a human readable and machine enforceable manner
package run.qontract.core.value
import run.qontract.core.ExampleDeclarations
import run.qontract.core.pattern.DeferredPattern
import run.qontract.core.pattern.JSONObjectPattern
import run.qontract.core.pattern.toJSONObjectPattern
import run.qontract.core.pattern.Pattern
import run.qontract.core.pattern.toTabularPattern
import run.qontract.core.utilities.valueMapToPrettyJsonString
data class JSONObjectValue(val jsonObject: Map = emptyMap()) : Value {
override val httpContentType = "application/json"
override fun displayableValue() = toStringValue()
override fun toStringValue() = valueMapToPrettyJsonString(jsonObject)
override fun displayableType(): String = "json object"
override fun exactMatchElseType(): Pattern = toJSONObjectPattern(jsonObject.mapValues { it.value.exactMatchElseType() })
override fun type(): Pattern = JSONObjectPattern()
override fun toString() = valueMapToPrettyJsonString(jsonObject)
override fun typeDeclarationWithKey(key: String, types: Map, exampleDeclarations: ExampleDeclarations): Pair {
val (jsonTypeMap, newTypes, newExamples) = dictionaryToDeclarations(jsonObject, types, exampleDeclarations)
val newType = toTabularPattern(jsonTypeMap.mapValues {
DeferredPattern(it.value.pattern)
})
val newTypeName = exampleDeclarations.getNewName(key.capitalize(), newTypes.keys)
val typeDeclaration = TypeDeclaration("($newTypeName)", newTypes.plus(newTypeName to newType))
return Pair(typeDeclaration, newExamples)
}
override fun listOf(valueList: List): Value {
return JSONArrayValue(valueList)
}
override fun typeDeclarationWithoutKey(exampleKey: String, types: Map, exampleDeclarations: ExampleDeclarations): Pair =
typeDeclarationWithKey(exampleKey, types, exampleDeclarations)
fun getString(key: String): String {
return (jsonObject.getValue(key) as StringValue).string
}
fun getBoolean(key: String): Boolean {
return (jsonObject.getValue(key) as BooleanValue).booleanValue
}
fun getInt(key: String): Int {
return (jsonObject.getValue(key) as NumberValue).number.toInt()
}
fun getJSONObject(key: String): Map {
return (jsonObject.getValue(key) as JSONObjectValue).jsonObject
}
fun getJSONObjectValue(key: String): JSONObjectValue {
return jsonObject.getValue(key) as JSONObjectValue
}
fun getJSONArray(key: String): List {
return (jsonObject.getValue(key) as JSONArrayValue).list
}
}
internal fun dictionaryToDeclarations(jsonObject: Map, types: Map, exampleDeclarations: ExampleDeclarations): Triple