Best Spek code snippet using org.spekframework.spek2.junit.SpekTestDescriptor
ReadmeTestEngine.kt
Source:ReadmeTestEngine.kt  
...4import ch.tutteli.niok.readText5import ch.tutteli.niok.writeText6import org.junit.platform.engine.*7import org.spekframework.spek2.junit.JUnitEngineExecutionListenerAdapter8import org.spekframework.spek2.junit.SpekTestDescriptor9import org.spekframework.spek2.junit.SpekTestDescriptorFactory10import org.spekframework.spek2.junit.SpekTestEngine11import org.spekframework.spek2.runtime.SpekRuntime12import org.spekframework.spek2.runtime.execution.ExecutionRequest13import java.nio.file.Paths14import java.util.*15import kotlin.collections.HashSet16import kotlin.collections.component117import kotlin.collections.component218import kotlin.collections.filterIsInstance19import kotlin.collections.forEach20import kotlin.collections.isNotEmpty21import kotlin.collections.map22import kotlin.collections.mutableMapOf23import kotlin.collections.set24import org.junit.platform.engine.ExecutionRequest as JUnitExecutionRequest25class ReadmeTestEngine : TestEngine {26    private val spek = SpekTestEngine()27    private val examples = mutableMapOf<String, String>()28    private val code = HashSet<String>()29    private val snippets = mutableMapOf<String, String>()30    override fun getId(): String = "spek2-readme"31    override fun discover(discoveryRequest: EngineDiscoveryRequest, uniqueId: UniqueId): TestDescriptor {32        val descriptor = spek.discover(discoveryRequest, uniqueId)33        require(descriptor.children.isNotEmpty()) {34            "Could not find any specification, check your runtime classpath"35        }36        return descriptor37    }38    override fun execute(request: JUnitExecutionRequest) {39        val default = Locale.getDefault()40        try {41            Locale.setDefault(Locale.UK)42            val classes = runSpekWithCustomListener(request)43            processExamples(classes, request)44        } catch (t: Throwable) {45            t.printStackTrace()46            Locale.setDefault(default)47            request.fail(t)48        }49    }50    private fun processExamples(classes: List<String>, request: JUnitExecutionRequest) {51        val specContents = classes.map { qualifiedClass ->52            qualifiedClass to fileContent("src/main/kotlin/$qualifiedClass.kt", request)53        }54        specContents.forEach { (_, specContent) ->55            extractSnippets(specContent, request)56        }57        var readmeContent = fileContent(readmeStringPath, request)58        if (examples.isEmpty()) {59            request.fail("no examples found")60            return61        }62        if (code.isEmpty()) {63            request.fail("no code found")64            return65        }66        if (snippets.isEmpty()) {67            request.fail("no snippets found")68            return69        }70        examples.forEach { (exampleId, output) ->71            readmeContent = updateExampleLikeInReadme(readmeContent, specContents, exampleId, output, request)72        }73        code.forEach { codeId ->74            readmeContent = updateCodeInReadme(readmeContent, specContents, codeId, request)75        }76        snippets.forEach { (snippetId, snippetContent) ->77            readmeContent = updateSnippetInReadme(readmeContent, snippetId, snippetContent, request)78        }79        Paths.get(readmeStringPath).writeText(readmeContent)80    }81    private fun extractSnippets(specContent: String, request: JUnitExecutionRequest) {82        Regex("//(snippet-.+)-start([\\S\\s]*?)//(snippet-.+)-end").findAll(specContent).forEach {83            val (tag, content, endTag) = it.destructured84            request.failIf(tag != endTag) { "tag $tag-start did not end with $tag-end but with $endTag" }85            snippets[tag] = content.trimIndent()86        }87    }88    private fun runSpekWithCustomListener(request: JUnitExecutionRequest) : List<String> {89        val roots = request.rootTestDescriptor.children90            .filterIsInstance<SpekTestDescriptor>()91            .map(SpekTestDescriptor::scope)92        val executionListener = ReadmeExecutionListener(93            JUnitEngineExecutionListenerAdapter(request.engineExecutionListener, SpekTestDescriptorFactory()),94            examples,95            code96        )97        val executionRequest = ExecutionRequest(roots, executionListener)98        SpekRuntime().execute(executionRequest)99        return roots.map { it.path.toString() }100    }101    private fun fileContent(path: String, request: JUnitExecutionRequest): String {102        val file = Paths.get(path)103        request.failIf(!file.exists) { "could not find ${file.absolutePathAsString}" }104        return file.readText()105    }106    private inline fun JUnitExecutionRequest.failIf(predicate: Boolean, errorMessage: () -> String) {107        if (predicate) fail(errorMessage())...SpekTestEngine.kt
Source:SpekTestEngine.kt  
...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>()46                var current = it.javaClass.superclass47                while (current != null) {48                    superClasses.add(current.name)49                    current = current.superclass50                }51                superClasses.contains("org.spekframework.spek2.Spek")52            }53            .filter {54                !(it.javaClass.isAnonymousClass55                    || it.javaClass.isLocalClass56                    || it.javaClass.isSynthetic57                    || Modifier.isAbstract(it.javaClass.modifiers))58            }.map {59                PathBuilder60                    .from(it.javaClass.kotlin)61                    .build()62            }63        val packageSelectors = discoveryRequest.getSelectorsByType(PackageSelector::class.java)64            .map {65                PathBuilder()66                    .appendPackage(it.packageName)67                    .build()68            }69        val filters = linkedSetOf<Path>()70        filters.addAll(classSelectors)71        filters.addAll(packageSelectors)72        // todo: empty filter should imply root73        if (filters.isEmpty()) {74            filters.add(PathBuilder.ROOT)75        }76        val context = JvmDiscoveryContextFactory.create(sourceDirs)77        val discoveryResult = runtime.discover(DiscoveryRequest(context, filters.toList()))78        discoveryResult.roots79            .map { descriptorFactory.create(it) }80            .forEach(engineDescriptor::addChild)81        return engineDescriptor82    }83    override fun execute(request: JUnitExecutionRequest) {84        val roots = request.rootTestDescriptor.children85            .filterIsInstance<SpekTestDescriptor>()86            .map(SpekTestDescriptor::scope)87        val executionRequest = ExecutionRequest(88            roots, JUnitEngineExecutionListenerAdapter(request.engineExecutionListener, descriptorFactory)89        )90        runtime.execute(executionRequest)91    }92    private fun containsUnsupportedSelector(discoveryRequest: EngineDiscoveryRequest): Boolean {93        for (selector in UNSUPPORTED_SELECTORS) {94            if (discoveryRequest.getSelectorsByType(selector).isNotEmpty()) {95                return true96            }97        }98        return false99    }100}...SpekTestDescriptor.kt
Source:SpekTestDescriptor.kt  
...8import org.spekframework.spek2.runtime.scope.ScopeImpl9import org.spekframework.spek2.runtime.scope.ScopeType10import org.spekframework.spek2.runtime.scope.TestScopeImpl11import java.util.*12class SpekTestDescriptor internal constructor(13    val scope: ScopeImpl,14    private val factory: SpekTestDescriptorFactory15) : TestDescriptor {16    companion object {17        private val ENGINE_ID = UniqueId.forEngine(SpekTestEngine.ID)18    }19    private val id by lazy { computeId(scope) }20    private fun computeId(scope: ScopeImpl?): UniqueId = if (scope == null) {21        ENGINE_ID22    } else {23        computeId(scope.parent as ScopeImpl?).append("${scope.id.type}", scope.id.name)24    }25    private var engineDescriptor: SpekEngineDescriptor? = null26    private val childDescriptors = mutableSetOf<TestDescriptor>()27    override fun getUniqueId() = id28    override fun getDisplayName(): String = scope.path.name29    override fun getType(): TestDescriptor.Type = when (scope) {30        is GroupScopeImpl -> TestDescriptor.Type.CONTAINER31        is TestScopeImpl -> TestDescriptor.Type.TEST32    }33    override fun getSource(): Optional<TestSource> = when (scope.id.type) {34        ScopeType.Class -> Optional.of(ClassSource.from(scope.id.name))35        ScopeType.Scope -> Optional.empty()36    }37    override fun setParent(parent: TestDescriptor?) {38        // Called only when adding as a child of the engine's descriptor.39        // Will be null only if it's not the root scope.40        if (parent != null && parent is SpekEngineDescriptor) {41            engineDescriptor = parent42        }43    }44    override fun getParent(): Optional<TestDescriptor> {45        val parent = scope.parent as ScopeImpl?46        return Optional.of(47            if (parent != null) {48                factory.create(parent)49            } else {50                // Root scope, setParent(...) was called before.51                engineDescriptor!!52            }53        )54    }55    override fun addChild(descriptor: TestDescriptor) {56        childDescriptors.add(descriptor)57    }58    override fun getChildren() = childDescriptors59    override fun getTags(): MutableSet<TestTag> = mutableSetOf()60    override fun removeFromHierarchy() {61        parent.ifPresent { parent ->62            parent.removeChild(this)63        }64    }65    override fun removeChild(descriptor: TestDescriptor) {66        if (scope is GroupScopeImpl) {67            childDescriptors.remove(descriptor)68            scope.removeChild((descriptor as SpekTestDescriptor).scope)69        }70    }71    override fun findByUniqueId(uniqueId: UniqueId): Optional<out TestDescriptor> =72        throw UnsupportedOperationException()73}...Spek2ForgivingTestEngine.kt
Source:Spek2ForgivingTestEngine.kt  
1package ch.tutteli.atrium.bctest.spek2import org.junit.platform.engine.*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}...SpekTestDescriptorFactory.kt
Source:SpekTestDescriptorFactory.kt  
1package org.spekframework.spek2.junit2import org.spekframework.spek2.runtime.scope.GroupScopeImpl3import org.spekframework.spek2.runtime.scope.ScopeImpl4class SpekTestDescriptorFactory {5    private val cache = mutableMapOf<ScopeImpl, SpekTestDescriptor>()6    fun create(scope: ScopeImpl): SpekTestDescriptor = createDescriptor(scope)7    private fun createDescriptor(scope: ScopeImpl): SpekTestDescriptor {8        var cached = true9        val descriptor = cache.computeIfAbsent(scope) {10            cached = false11            SpekTestDescriptor(scope, this)12        }13        if (!cached) {14            descriptor.apply {15                if (scope is GroupScopeImpl) {16                    scope.getChildren().forEach { child ->17                        this.addChild(create(child))18                    }19                }20            }21        }22        return descriptor23    }24}...SpekTestDescriptor
Using AI Code Generation
1import org.spekframework.spek2.Spek 2import org.spekframework.spek2.style.specification.describe 3object CalculatorSpec : Spek({ 4    describe("a calculator") { 5    } 6})7import org.spekframework.spek2.Spek 8import org.spekframework.spek2.style.specification.describe 9object CalculatorSpec : Spek({ 10    describe("a calculator") { 11    } 12})13plugins { 14} 15test { 16    useJUnitPlatform() 17}18plugins { 19} 20test { 21    useJUnitPlatform() 22}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!!
