run.smt.ktest.db.registry.TestDataRegistry.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of ktest-db Show documentation
Show all versions of ktest-db Show documentation
Database intergration for kTest
package run.smt.ktest.db.registry
import run.smt.ktest.util.reflection.canBeAssignedTo
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.ConcurrentMap
import kotlin.reflect.KClass
/**
* Represents test resources that must be cleanly loaded into some storage
*/
abstract class TestDataRegistry {
private val registry: ConcurrentMap = ConcurrentHashMap()
abstract fun load(clazz: KClass, identifier: String): T?
abstract fun loadAll(clazz: KClass, identifier: String): List
protected abstract fun save(data: T)
protected abstract fun remove(data: T)
/**
* Drop previous values, load fresh once and return result
*/
inline operator fun get(identifier: String): T = get(T::class, identifier)
inline fun getAll(identifier: String): List = getAll(T::class, identifier)
/**
* Same as `get` but without returning
*/
inline fun setup(identifier: String) {
get(identifier)
}
inline fun setupAll(identifier: String) {
getAll(identifier)
}
/**
* Only return value extracted from resources
*/
inline fun load(identifier: String): T? = load(T::class, identifier)
inline fun loadAll(identifier: String): List = loadAll(T::class, identifier)
fun get(clazz: KClass, identifier: String): T {
val result = registry.computeIfAbsent(identifier) {
val loaded = load(clazz, it) ?: throw NoValueException("Can not load value with identifier \"$identifier\"")
remove(loaded)
save(loaded)
loaded
}
if (result.javaClass canBeAssignedTo clazz) {
@Suppress("UNCHECKED_CAST") return result as T
}
throw NoValueException("Requested type for element with identifier \"$identifier\" don't match actual!")
}
fun getAll(clazz: KClass, identifier: String): List {
val result = registry.computeIfAbsent(identifier) {
val loaded = loadAll(clazz, it)
loaded.forEach {
remove(it)
save(it)
}
loaded
}
return result as? List ?: throw NoValueException("Requested type for element with identifier \"$identifier\" don't match actual!")
}
companion object {
class NoValueException(message: String) : RuntimeException(message)
class SaveException(message: String) : RuntimeException(message)
}
}