org.jetbrains.spek.engine.lifecycle.LifecycleAwareAdapter.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of spek-junit-platform-engine Show documentation
Show all versions of spek-junit-platform-engine Show documentation
Spek TestEngine for the JUnit Platform
package org.jetbrains.spek.engine.lifecycle
import org.jetbrains.spek.api.lifecycle.ActionScope
import org.jetbrains.spek.api.lifecycle.GroupScope
import org.jetbrains.spek.api.lifecycle.LifecycleAware
import org.jetbrains.spek.api.lifecycle.LifecycleListener
import org.jetbrains.spek.api.lifecycle.TestScope
import kotlin.reflect.KProperty
/**
* @author Ranie Jade Ramiso
*/
sealed class LifecycleAwareAdapter(val factory: () -> T)
: LifecycleAware, LifecycleListener {
var cached: T? = null
override fun getValue(thisRef: Any?, property: KProperty<*>) = invoke()
override fun invoke(): T {
if (cached == null) {
cached = factory()
}
return cached!!
}
class GroupCachingModeAdapter(factory: () -> T): LifecycleAwareAdapter(factory) {
val stack = mutableListOf()
override fun beforeExecuteGroup(group: GroupScope) {
stack.add(0, cached)
cached = null
}
override fun afterExecuteGroup(group: GroupScope) {
if (stack.isNotEmpty()) {
cached = stack.removeAt(0)
}
}
}
class ScopeCachingModeAdapter(val group: GroupScope, factory: () -> T): LifecycleAwareAdapter(factory) {
override fun afterExecuteGroup(group: GroupScope) {
if (this.group == group) {
cached = null
}
}
}
class TestCachingModeAdapter(factory: () -> T): LifecycleAwareAdapter(factory) {
override fun afterExecuteTest(test: TestScope) {
if (test.parent !is ActionScope) {
cached = null
}
}
override fun afterExecuteAction(action: ActionScope) {
cached = null
}
}
}