All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.jetbrains.spek.engine.lifecycle.LifecycleAwareAdapter.kt Maven / Gradle / Ivy

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
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy