run.smt.ktest.rest.api.Deserialization.kt Maven / Gradle / Ivy
package run.smt.ktest.rest.api
import com.fasterxml.jackson.databind.JavaType
import com.fasterxml.jackson.databind.JsonNode
import com.jayway.jsonpath.DocumentContext
import io.restassured.path.json.JsonPath
import io.restassured.path.xml.XmlPath
import io.restassured.response.Response
import io.restassured.response.ResponseBodyExtractionOptions
import run.smt.ktest.json.TypeDSL
import run.smt.ktest.json.deserialize
import run.smt.ktest.util.reflection.canBeAssignedTo
import java.io.InputStream
import kotlin.reflect.KClass
/**
* Deserialization part of REST DSL
*/
interface Deserialization {
@Suppress("UNCHECKED_CAST")
fun ResponseBodyExtractionOptions.`as`(type: JavaType): T {
val mainType = type.rawClass
return when {
mainType.canBeAssignedTo() -> this.asInputStream() as T
mainType.canBeAssignedTo() -> this.asString() as T
mainType.canBeAssignedTo() -> this.asByteArray() as T
mainType.canBeAssignedTo() -> this.jsonPath() as T
mainType.canBeAssignedTo() -> this.xmlPath() as T
mainType.canBeAssignedTo() -> this.asJsonTree() as T
mainType.canBeAssignedTo() -> this as T
mainType.canBeAssignedTo() -> (asInputStream() deserialize DocumentContext::class) as T
mainType.canBeAssignedTo>() -> {
val (l, r) = type.bindings.typeParameters
if (l.rawClass.canBeAssignedTo()) {
Pair((this as Response).statusCode, `as`(r)) as T
} else {
this.`as`(type.rawClass) as T
}
}
else -> this.`as`(type.rawClass) as T
}
}
fun ResponseBodyExtractionOptions.`as`(clazz: KClass): T = `as` { simple(clazz) }
fun ResponseBodyExtractionOptions.`as`(type: TypeDSL): T = `as`(run.smt.ktest.json.type(type))
fun ResponseBodyExtractionOptions.asJsonTree(): JsonNode = this.asInputStream().deserialize()
}