Best Spek code snippet using org.spekframework.spek2.runtime.SpekRuntime
TestSupport.kt
Source:TestSupport.kt
1package org.spekframework.spek22import org.spekframework.spek2.dsl.Root3import org.spekframework.spek2.runtime.SpekRuntime4import org.spekframework.spek2.runtime.discovery.DiscoveryContext5import org.spekframework.spek2.runtime.discovery.DiscoveryContextBuilder6import org.spekframework.spek2.runtime.execution.DiscoveryRequest7import org.spekframework.spek2.runtime.execution.ExecutionListener8import org.spekframework.spek2.runtime.execution.ExecutionRequest9import org.spekframework.spek2.runtime.execution.ExecutionResult10import org.spekframework.spek2.runtime.scope.GroupScopeImpl11import org.spekframework.spek2.runtime.scope.Path12import org.spekframework.spek2.runtime.scope.PathBuilder13import org.spekframework.spek2.runtime.scope.TestScopeImpl14import kotlin.test.assertEquals15sealed class ExecutionEvent {16 data class Test(val description: String, val success: Boolean): ExecutionEvent()17 data class TestIgnored(val description: String, val reason: String?): ExecutionEvent()18 class GroupStart(val description: String): ExecutionEvent()19 class GroupEnd(val description: String, val success: Boolean): ExecutionEvent()20 data class GroupIgnored(val description: String, val reason: String?): ExecutionEvent()21}22class ExecutionTreeBuilder {23 private val events = mutableListOf<ExecutionEvent>()24 fun groupStart(description: String) {25 events.add(ExecutionEvent.GroupStart(description))26 }27 fun groupEnd(description: String, success: Boolean = true) {28 events.add(ExecutionEvent.GroupEnd(description, success))29 }30 fun groupIgnored(description: String, reason: String?) {31 events.add(ExecutionEvent.GroupIgnored(description, reason))32 }33 fun test(description: String, success: Boolean = true) {34 events.add(ExecutionEvent.Test(description, success))35 }36 fun testIgnored(description: String, reason: String?) {37 events.add(ExecutionEvent.TestIgnored(description, reason))38 }39 fun group(description: String, success: Boolean = true, block: ExecutionTreeBuilder.() -> Unit) {40 groupStart(description)41 this.block()42 groupEnd(description, success)43 }44 fun build() = events.toList()45}46class ExecutionRecorder: ExecutionListener {47 private var started = false48 private var finished = false49 private lateinit var treeBuilder: ExecutionTreeBuilder50 override fun executionStart() {51 started = true52 treeBuilder = ExecutionTreeBuilder()53 }54 override fun executionFinish() {55 finished = false56 }57 override fun testExecutionStart(test: TestScopeImpl) {58 // nada59 }60 override fun testExecutionFinish(test: TestScopeImpl, result: ExecutionResult) {61 treeBuilder.test(test.path.name, result is ExecutionResult.Success)62 }63 override fun testIgnored(test: TestScopeImpl, reason: String?) {64 treeBuilder.testIgnored(test.path.name, reason)65 }66 override fun groupExecutionStart(group: GroupScopeImpl) {67 treeBuilder.groupStart(group.path.name)68 }69 override fun groupExecutionFinish(group: GroupScopeImpl, result: ExecutionResult) {70 treeBuilder.groupEnd(group.path.name, result is ExecutionResult.Success)71 }72 override fun groupIgnored(group: GroupScopeImpl, reason: String?) {73 treeBuilder.groupIgnored(group.path.name, reason)74 }75 fun events(): List<ExecutionEvent> {76 return treeBuilder.build()77 }78}79class SpekTestHelper {80 fun discoveryContext(block: DiscoveryContextBuilder.() -> Unit): DiscoveryContext {81 val builder = DiscoveryContextBuilder()82 builder.block()83 return builder.build()84 }85 fun executeTests(context: DiscoveryContext, vararg paths: Path): ExecutionRecorder {86 val runtime = SpekRuntime()87 val recorder = ExecutionRecorder()88 val discoveryResult = runtime.discover(DiscoveryRequest(context, listOf(*paths)))89 runtime.execute(ExecutionRequest(discoveryResult.roots, recorder))90 return recorder91 }92 fun<T: Spek> executeTest(test: T): ExecutionRecorder {93 val path = PathBuilder.from(test::class)94 .build()95 return executeTests(discoveryContext {96 addTest(test::class) { test }97 }, path)98 }99 fun assertExecutionEquals(actual: List<ExecutionEvent>, block: ExecutionTreeBuilder.() -> Unit) {100 val builder = ExecutionTreeBuilder()...
SpecificationStyleTest.kt
Source:SpecificationStyleTest.kt
...18 at org.spekframework.spek2.runtime.lifecycle.MemoizedValueAdapter.get(MemoizedValueAdapter.kt:33)19 at org.spekframework.spek2.runtime.lifecycle.MemoizedValueAdapter.getValue(MemoizedValueAdapter.kt:22)20 at com.example.spek.SpecificationStyleTest$1.invoke(SpecificationStyleTest.kt:18)21 at com.example.spek.SpecificationStyleTest$1.invoke(SpecificationStyleTest.kt:9)22 at org.spekframework.spek2.runtime.SpekRuntime.resolveSpec(SpekRuntime.kt:49)23 at org.spekframework.spek2.runtime.SpekRuntime.discover(SpekRuntime.kt:23)24 at org.spekframework.spek2.junit.SpekTestEngine.discover(SpekTestEngine.kt:92)25 at org.junit.platform.launcher.core.DefaultLauncher.discoverEngineRoot(DefaultLauncher.java:181)26 ... 31 more27 */28 logger.info("init, list: {}", list)29 describe("desc 1") {30 // cannot access items31// add("desc 1")32// logger.info("desc 1, memoized: {}, list: {}", items, list)33/*34Caused by: java.lang.AssertionError: 'items' can not be accessed in this context.35 at org.spekframework.spek2.runtime.lifecycle.MemoizedValueAdapter.get(MemoizedValueAdapter.kt:33)36 at org.spekframework.spek2.runtime.lifecycle.MemoizedValueAdapter.getValue(MemoizedValueAdapter.kt:22)37 at com.example.spek.SpecificationStyleTest$1$1.invoke(SpecificationStyleTest.kt:16)...
ConsoleLauncher.kt
Source:ConsoleLauncher.kt
1package org.spekframework.spek2.launcher2import org.spekframework.spek2.launcher.reporter.BasicConsoleReporter3import org.spekframework.spek2.runtime.SpekRuntime4import org.spekframework.spek2.runtime.discovery.DiscoveryContext5import org.spekframework.spek2.runtime.execution.DiscoveryRequest6import org.spekframework.spek2.runtime.execution.ExecutionListener7import org.spekframework.spek2.runtime.execution.ExecutionRequest8import org.spekframework.spek2.runtime.execution.ExecutionResult9import org.spekframework.spek2.runtime.scope.GroupScopeImpl10import org.spekframework.spek2.runtime.scope.Path11import org.spekframework.spek2.runtime.scope.PathBuilder12import org.spekframework.spek2.runtime.scope.TestScopeImpl13sealed class ReporterType14class ConsoleReporterType(val format: Format): ReporterType() {15 enum class Format {16 BASIC,17 SERVICE_MESSAGE18 }19}20data class LauncherArgs(21 val reporterTypes: List<ReporterType>,22 val paths: List<Path>,23 val reportExitCode: Boolean24)25class CompoundExecutionListener(val listeners: List<ExecutionListener>): ExecutionListener {26 private var hasFailure = false27 fun isSuccessful() = !hasFailure28 override fun executionStart() {29 listeners.forEach { it.executionStart() }30 }31 override fun executionFinish() {32 listeners.forEach { it.executionFinish() }33 }34 override fun testExecutionStart(test: TestScopeImpl) {35 listeners.forEach { it.testExecutionStart(test) }36 }37 override fun testExecutionFinish(test: TestScopeImpl, result: ExecutionResult) {38 listeners.forEach { it.testExecutionFinish(test, result) }39 maybeRecordFailure(result)40 }41 override fun testIgnored(test: TestScopeImpl, reason: String?) {42 listeners.forEach { it.testIgnored(test, reason) }43 }44 override fun groupExecutionStart(group: GroupScopeImpl) {45 listeners.forEach { it.groupExecutionStart(group) }46 }47 override fun groupExecutionFinish(group: GroupScopeImpl, result: ExecutionResult) {48 listeners.forEach { it.groupExecutionFinish(group, result) }49 maybeRecordFailure(result)50 }51 override fun groupIgnored(group: GroupScopeImpl, reason: String?) {52 listeners.forEach { it.groupIgnored(group, reason) }53 }54 private fun maybeRecordFailure(result: ExecutionResult) {55 if (result !is ExecutionResult.Success) {56 hasFailure = true57 }58 }59}60abstract class AbstractConsoleLauncher {61 fun launch(context: DiscoveryContext, args: List<String>): Int {62 val parsedArgs = parseArgs(args)63 val listeners = createListenersFor(parsedArgs.reporterTypes)64 val runtime = SpekRuntime()65 val paths = mutableListOf<Path>()66 paths.addAll(parsedArgs.paths)67 // todo: empty paths implies run everything68 if (paths.isEmpty()) {69 paths.add(PathBuilder.ROOT)70 }71 val discoveryRequest = DiscoveryRequest(context, paths)72 val discoveryResult = runtime.discover(discoveryRequest)73 val listener = CompoundExecutionListener(listeners)74 val executionRequest = ExecutionRequest(discoveryResult.roots, listener)75 runtime.execute(executionRequest)76 return when {77 parsedArgs.reportExitCode && !listener.isSuccessful() -> -178 parsedArgs.reportExitCode && listener.isSuccessful() -> 0...
SpekTestEngine.kt
Source:SpekTestEngine.kt
...4import org.junit.platform.engine.TestEngine5import org.junit.platform.engine.UniqueId6import org.junit.platform.engine.discovery.*7import org.spekframework.spek2.runtime.JvmDiscoveryContextFactory8import org.spekframework.spek2.runtime.SpekRuntime9import org.spekframework.spek2.runtime.execution.DiscoveryRequest10import org.spekframework.spek2.runtime.execution.ExecutionRequest11import org.spekframework.spek2.runtime.scope.Path12import org.spekframework.spek2.runtime.scope.PathBuilder13import java.lang.reflect.Modifier14import java.nio.file.Paths15import org.junit.platform.engine.ExecutionRequest as JUnitExecutionRequest16class SpekTestEngine : TestEngine {17 companion object {18 const val ID = "spek2"19 // Spek does not know how to handle these selectors, fallback to no matching tests.20 private val UNSUPPORTED_SELECTORS = listOf(21 MethodSelector::class.java,22 FileSelector::class.java,23 ModuleSelector::class.java,24 ClasspathResourceSelector::class.java,25 UniqueIdSelector::class.java,26 UriSelector::class.java,27 DirectorySelector::class.java28 )29 }30 private val descriptorFactory = SpekTestDescriptorFactory()31 private val runtime by lazy { SpekRuntime() }32 override fun getId() = ID33 override fun discover(discoveryRequest: EngineDiscoveryRequest, uniqueId: UniqueId): TestDescriptor {34 val engineDescriptor = SpekEngineDescriptor(uniqueId, id)35 if (containsUnsupportedSelector(discoveryRequest)) {36 return engineDescriptor37 }38 val sourceDirs = discoveryRequest.getSelectorsByType(ClasspathRootSelector::class.java)39 .map { it.classpathRoot }40 .map { Paths.get(it) }41 .map { it.toString() }42 val classSelectors = discoveryRequest.getSelectorsByType(ClassSelector::class.java)43 .filter {44 // get all super classes45 val superClasses = mutableListOf<String>()...
dependencies.kt
Source:dependencies.kt
1private object Versions {2 const val kotlin = "1.3.61"3 const val spek = "2.0.8"4 const val retrofit = "2.6.2"5 const val motif = "0.3.1"6 const val groupie = "2.7.2"7 const val navComponent = "2.2.0-rc03"8 const val mockk = "1.9.3"9}10object Dep {11 val plugins = Plugins12 val kotlin = Kotlin13 val android = Android14 object Plugins {15 const val kotlin = "org.jetbrains.kotlin:kotlin-gradle-plugin:${Versions.kotlin}"16 const val kotlinSerialization =17 "org.jetbrains.kotlin:kotlin-serialization:${Versions.kotlin}"18 const val ktlint = "org.jlleitschuh.gradle:ktlint-gradle:9.1.1"19 const val gradleVersions = "com.github.ben-manes:gradle-versions-plugin:0.27.0"20 const val navSafeArgs =21 "androidx.navigation:navigation-safe-args-gradle-plugin:${Versions.navComponent}"22 }23 object Kotlin {24 private val v = Versions25 const val std = "org.jetbrains.kotlin:kotlin-stdlib:${v.kotlin}"26 const val std8 = "org.jetbrains.kotlin:kotlin-stdlib-jdk8:${v.kotlin}"27 const val kotlinTest = "org.jetbrains.kotlin:kotlin-test:${v.kotlin}"28 const val reflect = "org.jetbrains.kotlin:kotlin-reflect:${v.kotlin}"29 const val kotlinAssertions = "io.kotlintest:kotlintest-assertions:3.4.2"30 const val kotlinSerialization = "org.jetbrains.kotlinx:kotlinx-serialization-runtime:0.14.0"31 const val junit = "junit:junit:4.12"32 const val rxJava = "io.reactivex.rxjava2:rxjava:2.2.15"33 const val rxKotlin = "io.reactivex.rxjava2:rxkotlin:2.4.0"34 const val spekJvm = "org.spekframework.spek2:spek-dsl-jvm:${v.spek}"35 const val spekRuntime = "org.spekframework.spek2:spek-runner-junit5:${v.spek}"36 const val threeTenBp = "org.threeten:threetenbp:1.4.0"37 const val threeTenBpNoTz = "org.threeten:threetenbp:1.4.0:no-tzdb"38 const val okHttpLogging = "com.squareup.okhttp3:logging-interceptor:4.2.1"39 const val retrofit = "com.squareup.retrofit2:retrofit:${v.retrofit}"40 const val retrofitRxJava = "com.squareup.retrofit2:adapter-rxjava2:${v.retrofit}"41 const val retrofitKotlinSerialization =42 "com.jakewharton.retrofit:retrofit2-kotlinx-serialization-converter:0.4.0"43 const val motif = "com.uber.motif:motif:${v.motif}"44 const val motifCompiler = "com.uber.motif:motif-compiler:${v.motif}"45 const val kelm = "com.github.AllanHasegawa:kelm:1.0.3"46 const val mockk = "io.mockk:mockk:${v.mockk}"47 const val mockWebServer = "com.squareup.okhttp3:mockwebserver:4.2.1"48 }49 object Android {50 private val v = Versions51 const val appCompat = "androidx.appcompat:appcompat:1.1.0"52 const val coreKtx = "androidx.core:core-ktx:1.2.0-rc01"53 const val junit = "androidx.test.ext:junit:1.1.1"54 const val testRunner = "androidx.test:runner:1.1.0"55 const val fragmentTesting = "androidx.fragment:fragment-testing:1.2.0-rc03"56 const val lifecycleExt = "androidx.lifecycle:lifecycle-extensions:2.2.0-rc01"57 const val navComponent = "androidx.navigation:navigation-fragment-ktx:${v.navComponent}"58 const val navComponentUi = "androidx.navigation:navigation-ui-ktx:${v.navComponent}"59 const val materialComponents = "com.google.android.material:material:1.2.0-alpha02"60 const val rxAndroid = "io.reactivex.rxjava2:rxandroid:2.1.1"61 const val constraintLayout = "androidx.constraintlayout:constraintlayout:2.0.0-beta3"62 const val picasso = "com.squareup.picasso:picasso:2.71828"63 const val threeTenAbp = "com.jakewharton.threetenabp:threetenabp:1.2.1"64 const val viewPager2 = "androidx.viewpager2:viewpager2:1.0.0"65 const val tomo = "com.github.AllanHasegawa:Tomo:0.0.1"66 const val groupie = "com.xwray:groupie:${v.groupie}"67 const val groupieKotlin = "com.xwray:groupie-kotlin-android-extensions:${v.groupie}"68 const val flexbox = "com.google.android:flexbox:2.0.0"69 const val kaspresso = "com.kaspersky.android-components:kaspresso:1.0.1"70 const val mockk = "io.mockk:mockk-android:${v.mockk}"71 }72}...
SpekRuntime.kt
Source:SpekRuntime.kt
...8import org.spekframework.spek2.runtime.lifecycle.LifecycleManager9import org.spekframework.spek2.runtime.scope.*10import org.spekframework.spek2.runtime.util.ClassUtil11private const val DEFAULT_TIMEOUT = 10000L12class SpekRuntime {13 fun discover(discoveryRequest: DiscoveryRequest): DiscoveryResult {14 val scopes = discoveryRequest.context.getTests()15 .map { testInfo ->16 val matchingPath = discoveryRequest.paths.firstOrNull { it.intersects(testInfo.path) }17 testInfo to matchingPath18 }19 .filter { (_, matchingPath) -> matchingPath != null }20 .map { (testInfo, matchingPath) ->21 checkNotNull(matchingPath)22 val spec = resolveSpec(testInfo.createInstance(), testInfo.path)23 spec.filterBy(matchingPath)24 spec25 }26 .filter { spec -> !spec.isEmpty() }...
Spek2ForgivingTestEngine.kt
Source:Spek2ForgivingTestEngine.kt
...3import org.spekframework.spek2.junit.JUnitEngineExecutionListenerAdapter4import org.spekframework.spek2.junit.SpekTestDescriptor5import org.spekframework.spek2.junit.SpekTestDescriptorFactory6import org.spekframework.spek2.junit.SpekTestEngine7import org.spekframework.spek2.runtime.SpekRuntime8import org.spekframework.spek2.runtime.execution.ExecutionRequest9import java.util.*10import org.junit.platform.engine.ExecutionRequest as JUnitExecutionRequest11class Spek2ForgivingTestEngine : TestEngine {12 private val spek = SpekTestEngine()13 private lateinit var forgiveRegex: Regex14 override fun getId(): String = "spek2-forgiving"15 override fun discover(discoveryRequest: EngineDiscoveryRequest, uniqueId: UniqueId): TestDescriptor {16 val descriptor = spek.discover(discoveryRequest, uniqueId)17 val forgive = discoveryRequest.configurationParameters.get("forgive").orElse(null)18 forgiveRegex = Regex(forgive)19 require(descriptor.children.isNotEmpty()) {20 "Could not find any specification, check your runtime classpath"21 }22 return descriptor23 }24 override fun execute(request: JUnitExecutionRequest) {25 val default = Locale.getDefault()26 try {27 Locale.setDefault(Locale.UK)28 runSpekWithCustomListener(request)29 } catch (t: Throwable) {30 t.printStackTrace()31 Locale.setDefault(default)32 request.fail(t)33 }34 }35 private fun runSpekWithCustomListener(request: JUnitExecutionRequest) {36 val roots = request.rootTestDescriptor.children37 .filterIsInstance<SpekTestDescriptor>()38 .map(SpekTestDescriptor::scope)39 val executionListener = Spek2ForgivingExecutionListener(40 JUnitEngineExecutionListenerAdapter(request.engineExecutionListener, SpekTestDescriptorFactory()),41 forgiveRegex42 )43 val executionRequest = ExecutionRequest(roots, executionListener)44 SpekRuntime().execute(executionRequest)45 }46 private fun JUnitExecutionRequest.fail(throwable: Throwable) {47 engineExecutionListener.executionFinished(48 rootTestDescriptor,49 TestExecutionResult.failed(throwable)50 )51 }52}...
console.kt
Source:console.kt
1package org.spekframework.ide2import com.xenomachina.argparser.ArgParser3import com.xenomachina.argparser.mainBody4import org.spekframework.spek2.runtime.JvmDiscoveryContextFactory5import org.spekframework.spek2.runtime.SpekRuntime6import org.spekframework.spek2.runtime.execution.DiscoveryRequest7import org.spekframework.spek2.runtime.execution.ExecutionRequest8import org.spekframework.spek2.runtime.scope.PathBuilder9class Spek2ConsoleLauncher {10 fun run(args: LauncherArgs) {11 val paths = args.paths.map {12 PathBuilder.parse(it)13 .build()14 }15 val context = JvmDiscoveryContextFactory.create(args.sourceDirs.toList())16 val discoveryRequest = DiscoveryRequest(context, paths)17 val runtime = SpekRuntime()18 val discoveryResult = runtime.discover(discoveryRequest)19 val executionRequest = ExecutionRequest(discoveryResult.roots, ServiceMessageAdapter())20 runtime.execute(executionRequest)21 }22}23class LauncherArgs(parser: ArgParser) {24 val sourceDirs by parser.adding("--sourceDirs", help="Spec source dirs")25 val paths by parser.adding("--paths", help = "Spek paths to execute")26}27fun main(args: Array<String>) = mainBody {28 val launcherArgs = ArgParser(args).parseInto(::LauncherArgs)29 Spek2ConsoleLauncher().run(launcherArgs)30}...
SpekRuntime
Using AI Code Generation
1val runtime = SpekRuntime()2val listener = object : ExecutionListener {3override fun executionStart() {4println("execution started")5}6override fun executionFinish() {7println("execution finished")8}9override fun executionSkip() {10println("execution skipped")11}12override fun executionFinish(failure: Throwable?) {13println("execution failed")14}15override fun executionFinish(spec: Executable, result: ExecutionResult) {16println("execution of spec ${spec.path} finished with result ${result.status}")17}18}19runtime.execute(listOf(MySpec::class), listener)
SpekRuntime
Using AI Code Generation
1class TestSpek : Spek({2group("Group 1") {3group("Group 2") {4test("Test 1") {5println("Test 1")6}7}8}9})10val runtime = SpekRuntime()11runtime.execute(listOf(TestSpek::class.java))12java -cp spek-dsl-jvm-2.0.0-rc.2.jar;spek-runtime-jvm-2.0.0-rc.2.jar org.spekframework.spek2.runtime.SpekRuntime TestSpek
SpekRuntime
Using AI Code Generation
1SpekRuntime.runTests("TestSuite", object: TestExecutionListener {2override fun testFinished(test: TestResult) {3println("Test finished: ${test.testCase.name}")4}5override fun testStarted(test: TestResult) {6println("Test started: ${test.testCase.name}")7}8})9}10}
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!!