How to use executors class of org.spekframework.spek2.runtime package

Best Spek code snippet using org.spekframework.spek2.runtime.executors

ReactNativeTimersIdlingResourceSpec.kt

Source:ReactNativeTimersIdlingResourceSpec.kt Github

copy

Full Screen

1package com.wix.detox.espresso2import android.view.Choreographer3import androidx.test.espresso.IdlingResource4import com.facebook.react.bridge.ReactApplicationContext5import com.facebook.react.modules.core.Timing6import com.nhaarman.mockitokotlin2.*7import com.wix.detox.UTHelpers.yieldToOtherThreads8import org.assertj.core.api.Assertions9import org.joor.Reflect10import 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})...

Full Screen

Full Screen

CustomRuntimeTest.kt

Source:CustomRuntimeTest.kt Github

copy

Full Screen

1package se.davison.aws.lambda.customruntime2import com.amazonaws.services.lambda.runtime.Context3import com.amazonaws.services.lambda.runtime.RequestHandler4import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent5import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent6import com.google.gson.GsonBuilder7import org.spekframework.spek2.Spek8import org.spekframework.spek2.style.specification.describe9import se.davison.aws.lambda.customruntime.util.openConnection10import se.davison.aws.lambda.customruntime.util.textResult11import java.lang.reflect.Field12import java.lang.reflect.Modifier13import 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}...

Full Screen

Full Screen

DetoxActionHandlersSpec.kt

Source:DetoxActionHandlersSpec.kt Github

copy

Full Screen

1package com.wix.detox2import com.facebook.react.bridge.ReactContext3import com.nhaarman.mockitokotlin2.*4import com.wix.detox.UTHelpers.yieldToOtherThreads5import com.wix.invoke.MethodInvocation6import 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 }75 describe("Invoke actions") {76 lateinit var methodInvocationMock: MethodInvocation77 fun uut() = InvokeActionHandler(methodInvocationMock, wsClient)78 beforeEachTest {79 methodInvocationMock = mock()80 }81 it("should invoke the right target") {82 uut().handle(params, messageId)83 verify(methodInvocationMock).invoke(params)84 }85 it("should reply with an 'invokeResult' ACK") {86 uut().handle(params, messageId)87 verify(wsClient).sendAction(eq("invokeResult"), any(), eq(messageId))88 }89 it("should reply with empty result data") {90 uut().handle(params, messageId)91 verify(wsClient).sendAction(any(), argThat { size == 1 && this["result"] == null }, any())92 }93 it("should reply with actual result data") {94 val someResult = "some_result"95 whenever(methodInvocationMock.invoke(isA<String>())).thenReturn(someResult)96 uut().handle(params, messageId)97 verify(wsClient).sendAction(any(), argThat { size == 1 && this["result"] == someResult }, any())98 }99 it("should handle runtime errors") {100 whenever(methodInvocationMock.invoke(isA<String>())).thenThrow(IllegalStateException("mock-error-reason"))101 uut().handle(params, messageId)102 verify(wsClient).sendAction(103 eq("testFailed"),104 argThat { size == 1 && this["details"] == "mock-error-reason" },105 eq(messageId))106 }107 it("should handle an InvocationTargetException") {108 val exception = InvocationTargetException(Exception("mock-error-reason"))109 whenever(methodInvocationMock.invoke(isA<String>())).thenThrow(exception)110 uut().handle(params, messageId)111 verify(wsClient).sendAction(112 eq("error"),113 argThat { size == 1 && this["error"] == "mock-error-reason" },114 eq(messageId))115 }116 }117 }118})...

Full Screen

Full Screen

SmSpek.kt

Source:SmSpek.kt Github

copy

Full Screen

1package no.nav.helse2import kotlinx.coroutines.*3import kotlinx.serialization.ImplicitReflectionSerializer4import net.logstash.logback.argument.StructuredArguments5import org.amshove.kluent.shouldEqual6import org.apache.activemq.artemis.core.config.impl.ConfigurationImpl7import org.apache.activemq.artemis.core.server.ActiveMQServers8import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory9import org.spekframework.spek2.Spek10import 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 null61 }62 it("Message with an valid fnr from 1998 should end up at the pale2 input") {63 val sentMessage1998 = getFileAsStringISO88591("src/test/resources/generated_fellesformat_le_fnr_1998.xml")64 inputQueue.send(session.createTextMessage(sentMessage1998))65 pale2Queue.receive(10000).text() shouldEqual sentMessage199866 eiaQueue.receive(100) shouldEqual null67 }68 it("Invalid XML should be routed to EIA input queue") {69 val sentMessage = "HELLOTHISISNOTXML"70 inputQueue.send(session.createTextMessage(sentMessage))71 eiaQueue.receive(10000).text() shouldEqual sentMessage72 pale2Queue.receive(100) shouldEqual null73 }74 }75})76fun Message.text(): String? = when (this) {77 is TextMessage -> text78 else -> throw RuntimeException("Unexpected message type ${this::class}")79}80fun main() {81 val xpath = XPathFactory.newInstance().newXPath().compile("/EI_fellesformat/MsgHead/Document/RefDoc/Content[1]/Legeerklaring/Pasient/Fodselsnummer")82 val document = DocumentBuilderFactory.newDefaultInstance().newDocumentBuilder().parse(File("src/test/resources/generated_fellesformat_le.xml"))83 val value = xpath.evaluate(document)84 println(value)85}...

Full Screen

Full Screen

TaskRunner.kt

Source:TaskRunner.kt Github

copy

Full Screen

1package org.spekframework.spek2.runtime2import kotlinx.coroutines.runBlocking3import java.util.concurrent.CompletableFuture4import java.util.concurrent.ExecutionException5import java.util.concurrent.Executors6actual class TaskRunner actual constructor(concurrency: Int) {7 private val executor = Executors.newFixedThreadPool(concurrency) { r ->8 Thread(r).also {9 it.isDaemon = true10 }11 }12 actual fun runTask(test: suspend () -> Unit): TaskHandle {13 val handle = CompletableFuture<Unit>()14 executor.submit {15 runBlocking {16 test()17 handle.complete(null)18 }19 }20 return object : TaskHandle {21 override fun await() {22 try {23 handle.get()24 } catch (e: ExecutionException) {25 throw e.cause!!26 }27 }28 }29 }30}...

Full Screen

Full Screen

executors

Using AI Code Generation

copy

Full Screen

1val executor = Executors.newSingleThreadExecutor()2val listener = object : ExecutionListener {3override fun executionStart() {4println("executionStart")5}6override fun executionFinish() {7println("executionFinish")8}9override fun testRunStart() {10println("testRunStart")11}12override fun testRunFinish() {13println("testRunFinish")14}15override fun testStart(description: Description) {16println("testStart: $description")17}18override fun testFinish(description: Description, result: TestResult) {19println("testFinish: $description, result: $result")20}21}22SpekRuntime.runTest(this, executor, listener)23}24}25}26testImplementation("org.spekframework.spek2:spek2-junit-platform-engine:2.0.12")

Full Screen

Full Screen

executors

Using AI Code Generation

copy

Full Screen

1import org.spekframework.spek2.runtime.scope.*2import java.util.concurrent.ExecutorService3import java.util.concurrent.Executors4object MySpec : Spek({5 val executorService: ExecutorService = Executors.newFixedThreadPool(5)6 val executor = Executors.newExecutor(executorService)7 group("My Group", executor = executor) {8 test("My Test") {9 }10 }11})12import org.spekframework.spek2.runtime.scope.*13import java.util.concurrent.ExecutorService14import java.util.concurrent.Executors15object MySpec : Spek({16 val executorService: ExecutorService = Executors.newFixedThreadPool(5)17 val executor = Executors.newExecutor(executorService)18 group("My Group", executor = executor) {19 test("My Test") {20 }21 }22})23import org.spekframework.spek2.runtime.scope.*24import java.util.concurrent.ExecutorService25import java.util.concurrent.Executors26object MySpec : Spek({27 val executorService: ExecutorService = Executors.newFixedThreadPool(5)28 val executor = Executors.newExecutor(executorService)29 group("My Group", executor = executor) {30 test("My Test") {31 }32 }33})34import org.spekframework.spek2.runtime.scope.*35import java.util.concurrent.ExecutorService36import java.util.concurrent.Executors37object MySpec : Spek({38 val executorService: ExecutorService = Executors.newFixedThreadPool(5)39 val executor = Executors.newExecutor(executorService)40 group("My Group", executor = executor) {41 test("My Test") {42 }43 }44})

Full Screen

Full Screen

executors

Using AI Code Generation

copy

Full Screen

1+fun main() {2+ val executors = Executors()3+ val listener = object : ExecutionListener {4+ override fun executionStart() {5+ println("Execution started")6+ }7+ override fun executionFinish() {8+ println("Execution finished")9+ }10+ override fun testStart(test: Test) {11+ println("Test started: ${test.path}")12+ }13+ override fun testFinish(test: Test, result: TestResult) {14+ println("Test finished: ${test.path}")15+ }16+ override fun testSkipped(test: Test, reason: String?) {17+ println("Test skipped: ${test.path}")18+ }19+ override fun testIgnored(test: Test) {20+ println("Test ignored: ${test.path}")21+ }22+ }23+ executors.execute(listener)24+}25+plugins {26+ kotlin("jvm") version "1.3.40"27+ id("org.spekframework.spek2") version "2.0.0-RC.1"28+}29+repositories {30+ jcenter()31+}32+dependencies {33+ testImplementation("org.spekframework.spek2:spek-dsl-jvm:2.0.0-RC.1")34+}35+== The JVM Test Suite Plugin (incubating)

Full Screen

Full Screen

executors

Using AI Code Generation

copy

Full Screen

1import org.spekframework.spek2.runtime.scope.Path2class SpekExecutorFactoryImpl : SpekExecutorFactory {3 override fun createExecutor(): SpekExecutor = SpekExecutorImpl()4 override fun createExecutor(paths: Set<Path>): SpekExecutor = SpekExecutorImpl(paths)5}6class SpekExecutorImpl(private val paths: Set<Path> = emptySet()) : SpekExecutor {7 override fun execute(spek: ExecutableSpek) {8 val engine = Engine()9 val listener = if (paths.isEmpty()) {10 ExecutionListener()11 } else {12 FilteredExecutionListener(paths)13 }14 engine.execute(spek, listener)15 }16}17import org.junit.platform.engine.*18import org.junit.platform.engine.support.descriptor.*19import org.junit.platform.launcher.*20import org.junit.platform.launcher.core.*21import org.spekframework.spek2.runtime.*22class SpekTestEngine : TestEngine {23 override fun getId(): String = "spek"24 override fun discover(discoveryRequest: EngineDiscoveryRequest, uniqueId: UniqueId): TestDescriptor {25 val engineId = uniqueId.append("engine", "spek")26 val engineDescriptor = EngineDescriptor(engineId, "spek")27 val executorFactory = SpekExecutorFactoryImpl()28 val executor = executorFactory.createExecutor()29 val spek = SpekTestEngineDescriptor(engineDescriptor, executor)30 engineDescriptor.addChild(spek)31 }32 override fun execute(request: ExecutionRequest) {33 root.children.forEach {34 (it as SpekTestEngineDescriptor).execute()35 }36 }37}38class SpekTestEngineDescriptor(39) : EngineDescriptor(engineDescriptor.uniqueId, engineDescriptor.displayName) {40 fun execute() {41 executor.execute(object : ExecutableSpek() {42 override fun execute() {43 children.forEach {44 (it as SpekTestEngineDescriptor).execute()45 }46 }47 })48 }49}50class SpekTestEngineLauncher {51 companion object {52 fun main(args: Array<String>) {

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Spek automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used methods in executors

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful