Best Spek code snippet using org.spekframework.spek2.runtime.Executor
build.gradle.kts
Source:build.gradle.kts  
...229            // Truth assertion lib230            testImplementation("com.google.truth:truth:1.1.3")231            // Coroutines test232            testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.5.1")233            // For InstantTaskExecutorRule234            testImplementation("androidx.arch.core:core-testing:2.1.0")235            // test kotlinx.coroutines Flow236            testImplementation("app.cash.turbine:turbine:0.6.0")237            // Roboelectric - Testing Room238            testImplementation("org.robolectric:robolectric:4.6.1")239            testImplementation("app.cash.turbine:turbine:0.7.0")240        }...ReactNativeTimersIdlingResourceSpec.kt
Source:ReactNativeTimersIdlingResourceSpec.kt  
...10import org.mockito.ArgumentMatchers11import org.spekframework.spek2.Spek12import org.spekframework.spek2.style.specification.describe13import java.util.*14import java.util.concurrent.Executors15private const val BUSY_INTERVAL_MS = 150016private const val MEANINGFUL_TIMER_INTERVAL = BUSY_INTERVAL_MS17private fun now() = System.nanoTime() / 1000000L18private fun aTimer(interval: Int, isRepeating: Boolean) = aTimer(now() + interval + 10, interval, isRepeating)19private fun aTimer(targetTime: Long, interval: Int, isRepeating: Boolean): Any {20    val timerClass = Class.forName("com.facebook.react.modules.core.Timing\$Timer")21    return Reflect.on(timerClass).create(-1, targetTime, interval, isRepeating).get()22}23private fun aOneShotTimer(interval: Int) = aTimer(interval, false)24private fun aRepeatingTimer(interval: Int) = aTimer(interval, true)25private fun anOverdueTimer() = aTimer(now() - 100, 123, false)26private fun anIdlingResourceCallback() = mock<IdlingResource.ResourceCallback>()27object ReactNativeTimersIdlingResourceSpec : Spek({28    describe("React Native timers idling-resource") {29        lateinit var reactAppContext: ReactApplicationContext30        lateinit var timersLock: String31        lateinit var timersNativeModule: Timing32        lateinit var choreographer: Choreographer33        lateinit var pendingTimers: PriorityQueue<Any>34        fun uut() = ReactNativeTimersIdlingResource(reactAppContext) { choreographer }35        fun givenTimer(timer: Any) {36            pendingTimers.add(timer)37        }38        fun getChoreographerCallback(): Choreographer.FrameCallback {39            argumentCaptor<Choreographer.FrameCallback>().apply {40                verify(choreographer).postFrameCallback(capture())41                return firstValue42            }43        }44        fun invokeChoreographerCallback() {45            getChoreographerCallback().doFrame(0L)46        }47        beforeEachTest {48            pendingTimers = PriorityQueue(2) { _, _ -> 0}49            timersNativeModule = mock()50            timersLock = "Lock-Mock"51            Reflect.on(timersNativeModule).set("mTimers", pendingTimers)52            Reflect.on(timersNativeModule).set("mTimerGuard", timersLock)53            choreographer = mock()54            reactAppContext = mock {55                on { hasNativeModule<Timing>(ArgumentMatchers.any()) }.doReturn(true)56                on { getNativeModule<Timing>(ArgumentMatchers.any()) }.doReturn(timersNativeModule)57            }58        }59        it("should be idle if there are no timers in queue") {60            Assertions.assertThat(uut().isIdleNow).isTrue()61        }62        it("should transition to idle if found idle in query") {63            val callback = anIdlingResourceCallback()64            with(uut()) {65                registerIdleTransitionCallback(callback)66                isIdleNow67            }68            verify(callback).onTransitionToIdle()69        }70        it("should NOT transition to idle if found busy in query") {71            val callback = anIdlingResourceCallback()72            givenTimer(aOneShotTimer(MEANINGFUL_TIMER_INTERVAL))73            with(uut()) {74                registerIdleTransitionCallback(callback)75                isIdleNow76            }77            verify(callback, never()).onTransitionToIdle()78        }79        it("should be busy if there's a meaningful pending timer") {80            givenTimer(aOneShotTimer(MEANINGFUL_TIMER_INTERVAL))81            Assertions.assertThat(uut().isIdleNow).isFalse()82        }83        it("should be idle if pending timer is too far away (ie not meaningful)") {84            givenTimer(aOneShotTimer(BUSY_INTERVAL_MS + 1))85            Assertions.assertThat(uut().isIdleNow).isTrue()86        }87        it("should be idle if the only timer is a repeating one") {88            givenTimer(aRepeatingTimer(MEANINGFUL_TIMER_INTERVAL))89            Assertions.assertThat(uut().isIdleNow).isTrue()90        }91        it("should be busy if a meaningful pending timer lies beyond a repeating one") {92            givenTimer(aRepeatingTimer(BUSY_INTERVAL_MS / 10))93            givenTimer(aOneShotTimer(BUSY_INTERVAL_MS))94            Assertions.assertThat(uut().isIdleNow).isFalse()95        }96        /**97         * Note: Reversed logic due to this issue: https://github.com/wix/Detox/issues/1171 !!!98         *99         * Apparently at times (rare) this caused Espresso to think we're idle too soon, rendering100         * it never to query any idling resource again even after the timer effectively expires...101         */102        it("should be *busy* even if all timers are overdue") {103            givenTimer(anOverdueTimer())104            givenTimer(anOverdueTimer())105            Assertions.assertThat(uut().isIdleNow).isFalse()106        }107        it("should be busy if has a meaningful pending timer set beyond an overdue timer") {108            givenTimer(anOverdueTimer())109            givenTimer(aOneShotTimer(MEANINGFUL_TIMER_INTERVAL))110            Assertions.assertThat(uut().isIdleNow).isFalse()111        }112        it("should be idle if paused") {113            givenTimer(aOneShotTimer(MEANINGFUL_TIMER_INTERVAL))114            val uut = uut().apply {115                pause()116            }117            Assertions.assertThat(uut.isIdleNow).isTrue()118        }119        it("should be busy if paused and resumed") {120            givenTimer(aOneShotTimer(MEANINGFUL_TIMER_INTERVAL))121            val uut = uut().apply {122                pause()123                resume()124            }125            Assertions.assertThat(uut.isIdleNow).isFalse()126        }127        it("should notify of transition to idle upon pausing") {128            val callback = anIdlingResourceCallback()129            givenTimer(aOneShotTimer(MEANINGFUL_TIMER_INTERVAL))130            with(uut()) {131                registerIdleTransitionCallback(callback)132                pause()133            }134            verify(callback).onTransitionToIdle()135        }136        it("should enqueue an is-idle check using choreographer when a callback gets registered") {137            with(uut()) {138                registerIdleTransitionCallback(mock())139            }140            verify(choreographer).postFrameCallback(any())141        }142        it("should transition to idle when preregistered choreographer is dispatched") {143            val callback = anIdlingResourceCallback()144            uut().registerIdleTransitionCallback(callback)145            invokeChoreographerCallback()146            verify(callback).onTransitionToIdle()147        }148        it("should NOT transition to idle if not idle when preregistered choreographer is dispatched") {149            val callback = anIdlingResourceCallback()150            givenTimer(aOneShotTimer(MEANINGFUL_TIMER_INTERVAL))151            uut().registerIdleTransitionCallback(callback)152            invokeChoreographerCallback()153            verify(callback, never()).onTransitionToIdle()154        }155        it("should re-register choreographer if found idle while preregistered choreographer is dispatched") {156            val callback = anIdlingResourceCallback()157            givenTimer(aOneShotTimer(MEANINGFUL_TIMER_INTERVAL))158            val uut = uut()159            uut.registerIdleTransitionCallback(callback)160            invokeChoreographerCallback()161            verify(choreographer, times(2)).postFrameCallback(any())162        }163        it("should adhere to pausing also when invoked via choreographer callback") {164            val callback = anIdlingResourceCallback()165            givenTimer(aOneShotTimer(MEANINGFUL_TIMER_INTERVAL))166            uut().apply {167                pause()168                registerIdleTransitionCallback(callback)169            }170            val runtimeChoreographerCallback = getChoreographerCallback()171            reset(callback, choreographer)172            runtimeChoreographerCallback.doFrame(0L)173            verify(callback, never()).onTransitionToIdle()174            verify(choreographer, never()).postFrameCallback(any())175        }176        it("should enqueue an additional idle check (using choreographer) if found busy") {177            givenTimer(aOneShotTimer(MEANINGFUL_TIMER_INTERVAL))178            uut().isIdleNow179            verify(choreographer).postFrameCallback(any())180        }181        it("should NOT enqueue an additional idle check (using choreographer) if found idle") {182            givenTimer(aOneShotTimer(BUSY_INTERVAL_MS + 1))183            uut().isIdleNow184            verify(choreographer, never()).postFrameCallback(any())185        }186        it("should yield to other threads using the timers module") {187            val executor = Executors.newSingleThreadExecutor()188            var isIdle: Boolean? = null189            synchronized(timersLock) {190                executor.submit {191                    isIdle = uut().isIdleNow192                }193                yieldToOtherThreads(executor)194                Assertions.assertThat(isIdle).isNull()195            }196            yieldToOtherThreads(executor)197            Assertions.assertThat(isIdle).isNotNull()198        }199    }200})...Dependency.kt
Source:Dependency.kt  
...122    const val hilt_android_testing = "com.google.dagger:hilt-android-testing:${Versions.hilt}"123    const val hilt_android_compiler = "com.google.dagger:hilt-android-compiler:${Versions.hilt}"124    //flow125    const val turbine = "app.cash.turbine:turbine:0.5.1"126    //instanttaskExecutorRule127    const val instant_taskexecutor_rule = "androidx.arch.core:core-testing:2.1.0"128    //faker129    const val kotlin_faker = "io.github.serpro69:kotlin-faker:1.7.1"130    const val spek_dsl_test = "org.spekframework.spek2:spek-dsl-jvm:${VersionsTest.spek}"131    const val spek_runner_junit5_test = "org.spekframework.spek2:spek-runner-junit5:${VersionsTest.spek}"132    const val junit_jupiter_test =  "org.junit.jupiter:junit-jupiter-api:5.7.0"133    const val junit_jupiter_engine_test_runtime = "org.junit.jupiter:junit-jupiter-engine:5.7.0"134    const val junit_jupiter_params_test = "org.junit.jupiter:junit-jupiter-params:5.7.0"135}...CustomRuntimeTest.kt
Source:CustomRuntimeTest.kt  
...13import java.net.ConnectException14import java.time.Duration15import java.time.Instant16import java.util.concurrent.Callable17import java.util.concurrent.Executors18import kotlin.math.max19import kotlin.test.assertEquals20import kotlin.test.assertTrue21val GSON = GsonBuilder().create()22class TestHandler : RequestHandler<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> {23    override fun handleRequest(input: APIGatewayProxyRequestEvent, context: Context): APIGatewayProxyResponseEvent? {24        return APIGatewayProxyResponseEvent()25                .withBody(GSON.toJson(mapOf("a" to "b")))26    }27}28class BrokenHandler : RequestHandler<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> {29    override fun handleRequest(input: APIGatewayProxyRequestEvent, context: Context): APIGatewayProxyResponseEvent? {30        throw Exception("Something went wrong")31    }32}33object Environment {34    private val environment = Class.forName("java.lang.ProcessEnvironment")35            .getDeclaredField("theUnmodifiableEnvironment").let {36                it.isAccessible = true;37                val modifiersField = Field::class.java.getDeclaredField("modifiers")38                modifiersField.isAccessible = true39                modifiersField.setInt(it, it.modifiers and Modifier.FINAL.inv())40                @Suppress("UNCHECKED_CAST")41                val environmentMap = (it.get(null) as Map<String, String>).toMutableMap()42                it.set(null, environmentMap)43                environmentMap44            }45    operator fun set(name: String, value: String) {46        environment[name] = value47    }48    operator fun get(name: String) = environment[name]49}50@Suppress("unused")51object CustomRuntimeTest : Spek({52    Environment["_HANDLER"] = TestHandler::class.java.name53    val handlers = mapOf(54            "ANY" to mapOf(55                    "/hello" to TestHandler::class.java.name,56                    "/broken" to BrokenHandler::class.java.name57            )58    )59    group("JVM") {60        beforeGroup {61            CustomRuntime.process(GSON.toJson(handlers))62            CustomRuntime.onError = {63                if (it !is ConnectException) {64                    it.printStackTrace()65                }66            }67            CustomRuntime.onFatalError = {68                if (it !is ConnectException) {69                    throw it70                }71            }72        }73        describe("Test runtime") {74            val expectation = GSON.toJson(mapOf("body" to GSON.toJson(mapOf("a" to "b"))))75            //make sure server is up76            Thread.sleep(1000)77            it("should handle a single request") {78                duration {79                    assertEquals(expectation, "http://localhost:3000/hello".openConnection().textResult)80                }.print()81            }82            it("should handle several requests") {83                duration {84                    assertEquals(expectation, "http://localhost:3000/hello".openConnection().textResult)85                    assertEquals(expectation, "http://localhost:3000/hello".openConnection().textResult)86                    assertEquals(expectation, "http://localhost:3000/hello".openConnection().textResult)87                }.print()88            }89            it("should handle several concurrent requests") {90                val count = max(Runtime.getRuntime().availableProcessors() / 2, 1)91                val duration = duration {92                    val expectations = Array(count) {93                        expectation94                    }.toList()95                    val results = Parallel.waitAll(Array(count) {96                        Callable {97                            "http://localhost:3000/hello".openConnection().textResult98                        }99                    }.toList())100                    assertEquals(expectations, results)101                }.print()102                assertTrue(duration.toMillis() < 40)103            }104            it("should return exception of lambda throws") {105                val exception = GSON.toJson(Exception("Something went wrong"))106                duration {107                    assertEquals(exception, "http://localhost:3000/broken".openConnection().textResult)108                }.print()109            }110        }111        afterGroup {112            CustomRuntime.stop()113        }114    }115    group("GraalVM") {116        //        beforeGroup {117//            val builder = ProcessBuilder("native-image", "-jar", File("./build/libs").listFiles { dir, name -> name.endsWith(".jar") }!!.maxBy {118//                it.length()119//            }.toString(), "--no-server", "--enable-all-security-services").inheritIO()120//            builder.start().waitFor()121//        }122//123//        describe("Test GraalVM Runtime") {124//125//            it("should be able to run using GraalVM") {126//127//            }128//        }129    }130})131private fun Duration.print(): Duration {132    println("\u001b[0;94m" + "Duration: ${this.toMillis()}ms" + "\u001b[0m")133    return this134}135fun duration(function: () -> Unit): Duration {136    val start = Instant.now()137    function()138    return Duration.between(start, Instant.now())139}140class Parallel private constructor() {141    companion object {142        fun <T> waitAll(tasks: List<Callable<T>>, threadCount: Int = -1): List<T> {143            val threads = if (threadCount == -1) Runtime.getRuntime().availableProcessors().let {144                if (it > tasks.size) {145                    return@let tasks.size146                }147                it148            } else threadCount149            val executor = Executors.newFixedThreadPool(threads)150            val results = executor.invokeAll(tasks).map {151                it.get()152            }153            executor.shutdown()154            return results155        }156    }157}...DetoxActionHandlersSpec.kt
Source:DetoxActionHandlersSpec.kt  
...6import org.spekframework.spek2.Spek7import org.spekframework.spek2.style.specification.describe8import java.lang.reflect.InvocationTargetException9import java.util.*10import java.util.concurrent.Executors11object DetoxActionHandlersSpec: Spek({12    describe("Action handlers") {13        val params = "{\"mock\": \"params\"}"14        val messageId = 666L15        lateinit var rnContext: ReactContext16        lateinit var wsClient: WebSocketClient17        lateinit var testEngineFacade: TestEngineFacade18        beforeEachTest {19            rnContext = mock()20            wsClient = mock()21            testEngineFacade = mock()22            whenever(testEngineFacade.awaitIdle()).then {23                synchronized(testEngineFacade) {}24            }25            whenever(testEngineFacade.syncIdle()).then {26                synchronized(testEngineFacade) {}27            }28        }29        describe("Ready action") {30            fun uut() = ReadyActionHandler(wsClient, testEngineFacade)31            it("should reply with a 'ready' ACK if ready") {32                uut().handle(params, messageId)33                verify(wsClient).sendAction(eq("ready"), eq(Collections.emptyMap<Any, Any>()), eq(messageId))34            }35            it("should block waiting for idle before ACK-ing") {36                val executor = Executors.newSingleThreadExecutor()37                synchronized(testEngineFacade) {38                    executor.submit {39                        uut().handle(params, messageId)40                    }41                    yieldToOtherThreads(executor)42                    verify(testEngineFacade).awaitIdle()43                    verify(wsClient, never()).sendAction(any(), any(), any())44                }45                yieldToOtherThreads(executor)46                verify(wsClient, times(1)).sendAction(any(), any(), any())47            }48        }49        describe("React-native reload action") {50            fun uut() = ReactNativeReloadActionHandler(rnContext, wsClient, testEngineFacade)51            it("should reload the app") {52                uut().handle(params, messageId)53                verify(testEngineFacade).reloadReactNative(rnContext)54            }55            it("should reply with a 'ready' ACK when ready") {56                uut().handle(params, messageId)57                verify(wsClient).sendAction(eq("ready"), eq(emptyMap<Any, Any>()), eq(messageId))58            }59            it("should sync before ACK-ing") {60                val executor = Executors.newSingleThreadExecutor()61                synchronized(testEngineFacade) {62                    executor.submit {63                        uut().handle(params, messageId)64                    }65                    yieldToOtherThreads(executor)66                    verify(testEngineFacade).syncIdle()67                    verify(testEngineFacade, never()).reloadReactNative(any())68                    verify(wsClient, never()).sendAction(any(), any(), any())69                }70                yieldToOtherThreads(executor)71                verify(testEngineFacade, times(1)).reloadReactNative(any())72                verify(wsClient, times(1)).sendAction(any(), any(), any())73            }74        }...Executor.kt
Source:Executor.kt  
...6import org.spekframework.spek2.runtime.execution.ExecutionResult7import org.spekframework.spek2.runtime.scope.GroupScopeImpl8import org.spekframework.spek2.runtime.scope.ScopeImpl9import org.spekframework.spek2.runtime.scope.TestScopeImpl10class Executor {11    fun execute(request: ExecutionRequest) {12        request.executionListener.executionStart()13        request.roots.forEach { execute(it, request.executionListener) }14        request.executionListener.executionFinish()15    }16    private fun execute(scope: ScopeImpl, listener: ExecutionListener): ExecutionResult? {17        if (scope.skip is Skip.Yes) {18            scopeIgnored(scope, scope.skip.reason, listener)19            return null20        } else {21            scopeExecutionStarted(scope, listener)22            val result = executeSafely {23                try {24                    when (scope) {...SmSpek.kt
Source:SmSpek.kt  
...10import org.spekframework.spek2.style.specification.describe11import java.io.File12import java.lang.RuntimeException13import java.nio.file.Paths14import java.util.concurrent.Executors15import javax.jms.Message16import javax.jms.TextMessage17import javax.xml.parsers.DocumentBuilderFactory18import javax.xml.xpath.XPathFactory19@ImplicitReflectionSerializer20object SmSpek : Spek({21    val inputMessage = getFileAsStringUTF8("src/test/resources/generated_fellesformat_le.xml")22    val activeMQServer = ActiveMQServers.newActiveMQServer(23        ConfigurationImpl()24            .setPersistenceEnabled(false)25            .setJournalDirectory("target/data/journal")26            .setSecurityEnabled(false)27            .addAcceptorConfiguration("invm", "vm://1"))28    activeMQServer.start()29    val credentials = Credentials("", "")30    val connectionFactory = ActiveMQConnectionFactory("vm://1")31    val queueConnection = connectionFactory.createConnection()32    queueConnection.start()33    val session = queueConnection.createSession()34    val exceptionHandler = CoroutineExceptionHandler { ctx, e ->35        log.error("Exception caught in coroutine {}", StructuredArguments.keyValue("context", ctx), e)36    }37    val config = readConfig<Config>(Paths.get("config-preprod.json"))38    val inputQueue = session.createProducer(session.createQueue(config.routes[0].inputQueue))39    val pale2Queue = session.createConsumer(session.createQueue(config.routes[0].outputQueues[0].name))40    val eiaQueue = session.createConsumer(session.createQueue(config.routes[0].outputQueues[1].name))41    afterGroup {42        activeMQServer.stop()43    }44    describe("Configuration for sm2013") {45        val applicationState = ApplicationState()46        val route = GlobalScope.launch(Executors.newSingleThreadExecutor().asCoroutineDispatcher()) {47            createListeners(applicationState, connectionFactory, credentials, config.routes, exceptionHandler).flatten().forEach { it.join() }48        }49        afterGroup {50            runBlocking {51                applicationState.running = false52                route.cancel()53                route.join()54            }55        }56        it("Message with an invalid fnr should end up at the EIA input queue") {57            val sentMessage = inputMessage58            inputQueue.send(session.createTextMessage(sentMessage))59            eiaQueue.receive(10000).text() shouldEqual sentMessage60            pale2Queue.receive(100) shouldEqual null...SpekRuntime.kt
Source:SpekRuntime.kt  
...25            }26            .filter { spec -> !spec.isEmpty() }27        return DiscoveryResult(scopes)28    }29    fun execute(request: ExecutionRequest) = Executor().execute(request)30    private fun resolveSpec(instance: Spek, path: Path): GroupScopeImpl {31        val fixtures = FixturesAdapter()32        val lifecycleManager = LifecycleManager().apply {33            addListener(fixtures)34        }35        val (packageName, className) = ClassUtil.extractPackageAndClassNames(instance::class)36        val qualifiedName = if (packageName.isNotEmpty()) {37            "$packageName.$className"38        } else {39            className40        }41        val classScope = GroupScopeImpl(ScopeId(ScopeType.Class, qualifiedName), path, null, Skip.No, lifecycleManager, false)42        val collector = Collector(classScope, lifecycleManager, fixtures, CachingMode.TEST, DEFAULT_TIMEOUT)43        try {...Executor
Using AI Code Generation
1val executor = Executor()2executor.execute(SimpleTest::class, SimpleTest::class.java)3val executor = Executor()4executor.execute(SimpleTest::class, SimpleTest::class.java)5val executor = Executor()6executor.execute(SimpleTest::class, SimpleTest::class.java)7val executor = Executor()8executor.execute(SimpleTest::class, SimpleTest::class.java)9val executor = Executor()10executor.execute(SimpleTest::class, SimpleTest::class.java)11val executor = Executor()12executor.execute(SimpleTest::class, SimpleTest::class.java)13val executor = Executor()14executor.execute(SimpleTest::class, SimpleTest::class.java)15val executor = Executor()16executor.execute(SimpleTest::class, SimpleTest::class.java)17val executor = Executor()18executor.execute(SimpleTest::class, SimpleTest::class.java)19val executor = Executor()20executor.execute(SimpleTest::class, SimpleTest::class.java)21val executor = Executor()22executor.execute(SimpleTest::class, SimpleTest::class.java)23val executor = Executor()24executor.execute(SimpleTest::class, SimpleTest::class.java)25val executor = Executor()26executor.execute(SimpleTest::class, SimpleExecutor
Using AI Code Generation
1val executor = Executor()2executor.executeGroup(test)3val executor = Executor()4executor.executeGroup(test)5val executor = Executor()6executor.executeGroup(test)7val executor = Executor()8executor.executeGroup(test)9val executor = Executor()10executor.executeGroup(test)11val executor = Executor()12executor.executeGroup(test)13val executor = Executor()14executor.executeGroup(test)15val executor = Executor()16executor.executeGroup(test)17val executor = Executor()18executor.executeGroup(test)19val executor = Executor()20executor.executeGroup(test)21val executor = Executor()22executor.executeGroup(test)Executor
Using AI Code Generation
1class MySpec : Spek({2})3class MySpec : Spek({4})5class MySpec : Spek({6})Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
