Best Kotest code snippet using io.kotest.core.spec.style.scopes.state
DetailViewModelTest.kt
Source:DetailViewModelTest.kt
1package com.hyejineee.todo.viewmodel.todo2import com.hyejineee.todo.Context3import com.hyejineee.todo.data.entity.TodoEntity4import com.hyejineee.todo.domain.todo.DeleteTodoListUseCase5import com.hyejineee.todo.domain.todo.InsertTodoUseCase6import com.hyejineee.todo.presentation.detail.DetailMode7import com.hyejineee.todo.presentation.detail.DetailViewModel8import com.hyejineee.todo.presentation.detail.TodoDetailState9import com.hyejineee.todo.presentation.todo.ListViewModel10import com.hyejineee.todo.presentation.todo.TodoListState11import com.hyejineee.todo.viewmodel.ViewModelTest12import io.kotest.common.ExperimentalKotest13import io.kotest.core.spec.style.scopes.DescribeSpecContainerContext14import io.kotest.core.test.createTestName15import kotlinx.coroutines.ExperimentalCoroutinesApi16import kotlinx.coroutines.test.runBlockingTest17import org.koin.core.parameter.parametersOf18import org.koin.test.get19import org.koin.test.inject20/**21 * [DetailViewModel]를 í
ì¤í¸í기 ìí ë¨ì í
ì¤í¸22 *23 * 1. initData()24 * 2. test viewModel fetch25 * 3. test delete todo26 * 4. test update todo27 * */28@ExperimentalKotest29@ExperimentalCoroutinesApi30internal class DetailViewModelTest : ViewModelTest() {31 private val id = 1L32 private lateinit var detailViewModel: DetailViewModel33 private lateinit var listViewModel: ListViewModel34 private val insertTodoUseCase by inject<InsertTodoUseCase>()35 private val deleteTodoListUseCase by inject<DeleteTodoListUseCase>()36 private val todo = TodoEntity(37 id = id,38 title = "title $id",39 description = "DetailViewModelTest $id",40 hasCompleted = false41 )42 override fun initData() = runBlockingTest {43 detailViewModel = get { parametersOf(DetailMode.DETAIL, id) }44 listViewModel = get()45 insertTodoUseCase(todo)46 }47 override fun removeData() = runBlockingTest {48 deleteTodoListUseCase()49 }50 init {51 runBlockingTest {52 describe("DetailViewModel for detail mode") {53 context("when fetchData() is called ").config(tags = setOf(Context)) {54 it("todo item is posted to liveData") {55 val testObservable = detailViewModel.todoDetailLiveData.test()56 detailViewModel.fetchData()57 testObservable.assertValueSequence(58 listOf(59 TodoDetailState.UnInitialized,60 TodoDetailState.Loading,61 TodoDetailState.Success(todo)62 )63 )64 }65 }66 context("when delete a todo Item").config(tags = setOf(Context)) {67 it("todoDetail livedata is changed to Delete") {68 val deleteTestObservable = detailViewModel.todoDetailLiveData.test()69 detailViewModel.delete(id)70 deleteTestObservable.assertValueSequence(71 listOf(72 TodoDetailState.UnInitialized,73 TodoDetailState.Loading,74 TodoDetailState.Delete75 )76 )77 val listTestObservable = listViewModel.todoListLiveData.test()78 listViewModel.fetchData()79 listTestObservable.assertValueSequence(80 listOf(81 TodoListState.UnInitialized,82 TodoListState.Loading,83 TodoListState.Success(listOf())84 )85 )86 }87 }88 context("when title or description is changed").config(tags = setOf(Context)) {89 it("todo is updated") {90 val testObservable = detailViewModel.todoDetailLiveData.test()91 val updateTitle = "update title"92 val updateDescription = "update description"93 val updateTodo = todo.copy(94 title = updateTitle,95 description = updateDescription96 )97 detailViewModel.writeTodo(98 title = updateTitle,99 description = updateDescription100 )101 testObservable.assertValueSequence(102 listOf(103 TodoDetailState.UnInitialized,104 TodoDetailState.Loading,105 TodoDetailState.Success(updateTodo)106 )107 )108 }109 }110 }111 }112 }113}...
ClassSignatureTest.kt
Source:ClassSignatureTest.kt
1package com.anatawa12.relocator.classes2import io.kotest.assertions.throwables.shouldThrow3import io.kotest.core.spec.style.DescribeSpec4import io.kotest.core.spec.style.scopes.DescribeSpecContainerScope5import io.kotest.matchers.shouldBe6import io.kotest.matchers.types.shouldBeSameInstanceAs7internal class ClassSignatureTest : DescribeSpec() {8 private inline fun testParse(9 signature: String,10 expect: ClassSignature,11 crossinline extraTests: suspend DescribeSpecContainerScope.(signature: String, parsed: ClassSignature, expect: ClassSignature) -> Unit12 ) {13 describe(signature) {14 val parsed = ClassSignature.parse(signature)15 it("signature of parsed signature should be same instance as parameter: '$signature'") {16 parsed.signature shouldBeSameInstanceAs signature17 }18 it("toString of parsed signature should be same instance as parameter: '$signature'") {19 parsed.toString() shouldBeSameInstanceAs signature20 }21 it("check the signature of built instance: '$signature'") {22 expect.signature shouldBe signature23 }24 it("check toString of built instance: '$signature'") {25 expect.toString() shouldBe signature26 }27 it("equality of signature: '$signature'") {28 expect.signature shouldBe signature29 }30 extraTests(signature, parsed, expect)31 }32 }33 init {34 val objectSignature = TypeSignature.parse("L${"java/lang/Object"};")35 val listSignature = TypeSignature.parse("L${"java/util/List"};")36 testParse("<T:$objectSignature>$objectSignature", ClassSignature.Builder()37 .addTypeParam(TypeParameter.of("T", objectSignature))38 .superClass(objectSignature)39 .build()) { signature, parsed, _ ->40 it("type parameter of '$signature'") {41 parsed.typeParameters shouldBe listOf(TypeParameter.of("T", objectSignature))42 }43 it("type super class of '$signature'") {44 parsed.superClass shouldBe objectSignature45 }46 }47 testParse("<T:$objectSignature>$objectSignature$listSignature", ClassSignature.Builder()48 .addTypeParam(TypeParameter.of("T", objectSignature))49 .superClass(objectSignature)50 .addInterface(listSignature)51 .build()) { signature, parsed, _ ->52 it("type parameter of '$signature'") {53 parsed.typeParameters shouldBe listOf(TypeParameter.of("T", objectSignature))54 }55 it("type super class of '$signature'") {56 parsed.superClass shouldBe objectSignature57 }58 it("type super interface of '$signature'") {59 parsed.superInterfaces shouldBe listOf(listSignature)60 }61 }62 testParse("<T::$listSignature>$objectSignature$listSignature", ClassSignature.Builder()63 .addTypeParam(TypeParameter.Builder("T").addInterfaceBound(listSignature).build())64 .superClass(objectSignature)65 .addInterface(listSignature)66 .build()) { signature, parsed, _ ->67 it("type parameter of '$signature'") {68 parsed.typeParameters shouldBe listOf(TypeParameter.Builder("T")69 .addInterfaceBound(listSignature)70 .build())71 }72 it("type super class of '$signature'") {73 parsed.superClass shouldBe objectSignature74 }75 it("type super interface of '$signature'") {76 parsed.superInterfaces shouldBe listOf(listSignature)77 }78 }79 describe("falling builders") {80 it ("building with missing super class name") {81 shouldThrow<IllegalStateException> {82 ClassSignature.Builder().build()83 }84 }85 it ("setting primitive as super class") {86 shouldThrow<IllegalArgumentException> {87 ClassSignature.Builder().superClass(TypeSignature.INT)88 }89 }90 it ("setting double super class") {91 shouldThrow<IllegalStateException> {92 ClassSignature.Builder().superClass(objectSignature).superClass(objectSignature)93 }94 }95 it ("adding primitive as super interface") {96 shouldThrow<IllegalArgumentException> {97 ClassSignature.Builder().addInterface(TypeSignature.INT)98 }99 }100 }101 }102}...
AuthScopeTest.kt
Source:AuthScopeTest.kt
1/*2 * Copyright (c) 2020. Pela Cristian3 * Permission is hereby granted, free of charge, to any person obtaining a4 * copy of this software and associated documentation files (the "Software"),5 * to deal in the Software without restriction, including without limitation6 * the rights to use, copy, modify, merge, publish, distribute, sublicense,7 * and/or sell copies of the Software, and to permit persons to whom the8 * Software is furnished to do so, subject to the following conditions:9 *10 * The above copyright notice and this permission notice shall be included in11 * all copies or substantial portions of the Software.12 *13 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS14 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,15 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE16 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER17 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING18 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER19 * DEALINGS IN THE SOFTWARE.20 */21package pcf.crskdev.koonsplash.auth22import io.kotest.assertions.throwables.shouldThrow23import io.kotest.core.spec.style.StringSpec24import io.kotest.matchers.shouldBe25import java.lang.IllegalStateException26internal class AuthScopeTest : StringSpec({27 "ALL should show all scopes delimited by `+`" {28 AuthScope.ALL.value shouldBe """29 public30 +read_user31 +write_user32 +read_photos33 +write_photos34 +write_likes35 +write_followers36 +read_collections37 +write_collections38 """.trimIndent().replace("\n", "")39 }40 "should add two 2 scopes" {41 (AuthScope.PUBLIC + AuthScope.READ_USER).value shouldBe "public+read_user"42 }43 "should ignore adding the same scope" {44 (AuthScope.PUBLIC + AuthScope.READ_USER + AuthScope.READ_USER).value shouldBe "public+read_user"45 }46 "should subtract scope" {47 (AuthScope.ALL - AuthScope.WRITE_PHOTOS).value shouldBe """48 public49 +read_user50 +write_user51 +read_photos52 +write_likes53 +write_followers54 +read_collections55 +write_collections56 """.trimIndent().replace("\n", "")57 }58 "should ignore + if it is first char when subtracting scope" {59 (AuthScope.ALL - AuthScope.PUBLIC).value shouldBe """60 read_user61 +write_user62 +read_photos63 +write_photos64 +write_likes65 +write_followers66 +read_collections67 +write_collections68 """.trimIndent().replace("\n", "")69 }70 "should subtract from a sum of scopes" {71 (AuthScope.ALL - (AuthScope.PUBLIC + AuthScope.WRITE_PHOTOS + AuthScope.WRITE_COLLECTIONS)).value shouldBe """72 read_user73 +write_user74 +read_photos75 +write_likes76 +write_followers77 +read_collections78 """.trimIndent().replace("\n", "")79 }80 "should have at least one scope after subtracting" {81 shouldThrow<IllegalStateException> {82 (AuthScope.PUBLIC + AuthScope.READ_USER) - (AuthScope.PUBLIC + AuthScope.READ_USER)83 }84 }85 "should ignore if scope not presented after subtracting again" {86 ((AuthScope.PUBLIC + AuthScope.READ_USER) - AuthScope.PUBLIC - AuthScope.PUBLIC).value shouldBe "read_user"87 }88 "should ignore empty scope" {89 (AuthScopeNone + AuthScope.PUBLIC - AuthScopeNone).value shouldBe "public"90 (AuthScopeNone - AuthScope.PUBLIC + AuthScopeNone + AuthScopeNone).value shouldBe "public"91 (AuthScopeNone + AuthScopeNone).value shouldBe ""92 (AuthScopeNone - AuthScopeNone).value shouldBe ""93 }94 "should decode scopes" {95 AuthScope.decode("read_user write_user").value shouldBe "read_user+write_user"96 AuthScope.decode("read_user+write_user").value shouldBe "read_user+write_user"97 }98})...
CompilerTests.kt
Source:CompilerTests.kt
1package io.littlelanguages.mil.compiler2import io.kotest.core.spec.style.FunSpec3import io.kotest.core.spec.style.scopes.FunSpecContainerContext4import io.kotest.matchers.shouldBe5import io.littlelanguages.data.Either6import io.littlelanguages.data.Left7import io.littlelanguages.data.Right8import io.littlelanguages.mil.Errors9import io.littlelanguages.mil.compiler.llvm.Context10import io.littlelanguages.mil.compiler.llvm.Module11import io.littlelanguages.mil.compiler.llvm.targetTriple12import io.littlelanguages.mil.dynamic.Binding13import io.littlelanguages.mil.dynamic.translate14import io.littlelanguages.mil.static.Scanner15import io.littlelanguages.mil.static.parse16import org.bytedeco.llvm.LLVM.LLVMValueRef17import org.yaml.snakeyaml.Yaml18import java.io.*19private val yaml = Yaml()20class CompilerTests : FunSpec({21 context("Conformance Tests") {22 val context = Context(targetTriple())23 val content = File("./src/test/kotlin/io/littlelanguages/mil/compiler/compiler.yaml").readText()24 val scenarios: Any = /*emptyList<String>() */ yaml.load(content)25 if (scenarios is List<*>) {26 parserConformanceTest(builtinBindings, context, this, scenarios)27 }28 context.dispose()29 }30})31fun compile(builtinBindings: List<Binding<CompileState, LLVMValueRef>>, context: Context, input: String): Either<List<Errors>, Module> =32 parse(Scanner(StringReader(input))) mapLeft { listOf(it) } andThen { translate(builtinBindings, it) } andThen { compile(context, "./test.mlsp", it) }33suspend fun parserConformanceTest(34 builtinBindings: List<Binding<CompileState, LLVMValueRef>>,35 context: Context,36 ctx: FunSpecContainerContext,37 scenarios: List<*>38) {39 scenarios.forEach { scenario ->40 val s = scenario as Map<*, *>41 val nestedScenario = s["scenario"] as Map<*, *>?42 if (nestedScenario == null) {43 val name = s["name"] as String44 val input = s["input"] as String45 val output = s["output"]46 ctx.test(name) {47 val lhs = when (val llvmState = compile(builtinBindings, context, input)) {48 is Left ->49 llvmState.left.joinToString("")50 is Right -> {51 val module = llvmState.right52// LLVM.LLVMDumpModule(module)53// System.err.println(LLVM.LLVMPrintModuleToString(module).string)54 module.writeBitcodeToFile("test.bc")55 runCommand(arrayOf("clang", "test.bc", "src/main/c/lib.o", "./src/main/c/main.o", "./bdwgc/gc.a", "-o", "test.bin"))56 val commandOutput = runCommand(arrayOf("./test.bin"))57 module.dispose()58 commandOutput59 }60 }61 val rhs =62 (output as Any).toString().trim()63 lhs shouldBe rhs64 }65 } else {66 val name = nestedScenario["name"] as String67 val tests = nestedScenario["tests"] as List<*>68 ctx.context(name) {69 parserConformanceTest(builtinBindings, context, this, tests)70 }71 }72 }73}74private fun runCommand(commands: Array<String>): String {75 val rt = Runtime.getRuntime()76 val proc = rt.exec(commands)77 val sb = StringBuffer()78 fun readInputStream(input: InputStream) {79 BufferedReader(InputStreamReader(input)).use { reader ->80 var s: String?81 while (reader.readLine().also { s = it } != null) {82 sb.append(s)83 sb.append("\n")84 }85 }86 }87 readInputStream(proc.inputStream)88 readInputStream(proc.errorStream)89 return sb.toString().trim()90}...
DynamicTests.kt
Source:DynamicTests.kt
...34})35private class DummyVariableArityExternalProcedure(36 override val name: String37) : ExternalProcedureBinding<S, T>(name, null) {38 override fun compile(state: S, lineNumber: Int, arguments: Expressionss<S, T>): T? = null39}40fun translate(builtinBindings: List<Binding<S, T>>, input: String): Either<List<Errors>, Program<S, T>> =41 parse(Scanner(StringReader(input))) mapLeft { listOf(it) } andThen { translate(builtinBindings, it) }42suspend fun parserConformanceTest(builtinBindings: List<Binding<S, T>>, ctx: FunSpecContainerContext, scenarios: List<*>) {43 scenarios.forEach { scenario ->44 val s = scenario as Map<*, *>45 val nestedScenario = s["scenario"] as Map<*, *>?46 if (nestedScenario == null) {47 val name = s["name"] as String48 val input = s["input"] as String49 val output = s["output"]50 ctx.test(name) {51 val rhs =52 output.toString()...
UnfinishedTestDefinitionTest.kt
Source:UnfinishedTestDefinitionTest.kt
1package com.sksamuel.kotest.engine.spec.dsl2import io.kotest.core.spec.style.DescribeSpec3import io.kotest.core.spec.style.ExpectSpec4import io.kotest.core.spec.style.FeatureSpec5import io.kotest.core.spec.style.FunSpec6import io.kotest.core.spec.style.ShouldSpec7import io.kotest.core.spec.style.scopes.TestDslState8import io.kotest.engine.TestEngineLauncher9import io.kotest.engine.listener.NoopTestEngineListener10import io.kotest.inspectors.forAtLeastOne11import io.kotest.matchers.string.shouldContain12class UnfinishedTestDefinitionTest : FunSpec() {13 init {14 afterEach {15 TestDslState.reset()16 }17 test("fun spec") {18 val result = TestEngineLauncher(NoopTestEngineListener)19 .withClasses(FunSpecUnfinishedTestDefinitionTest::class)20 .launch()21 result.errors.forAtLeastOne { it.message!!.shouldContain("unfinished test") }22 }23 test("describe spec") {24 val result = TestEngineLauncher(NoopTestEngineListener)25 .withClasses(DescribeSpecUnfinishedTestDefinitionTest::class)26 .launch()27 result.errors.forAtLeastOne { it.message!!.shouldContain("unfinished it") }28 }29 test("should spec") {30 val result = TestEngineLauncher(NoopTestEngineListener)31 .withClasses(ShouldSpecUnfinishedTestDefinitionTest::class)32 .launch()33 result.errors.forAtLeastOne { it.message!!.shouldContain("unfinished should") }34 }35 test("feature spec") {36 val result = TestEngineLauncher(NoopTestEngineListener)37 .withClasses(FeatureSpecUnfinishedTestDefinitionTest::class)38 .launch()39 result.errors.forAtLeastOne { it.message!!.shouldContain("unfinished scenario") }40 }41 test("expect spec") {42 val result = TestEngineLauncher(NoopTestEngineListener)43 .withClasses(ExpectSpecUnfinishedTestDefinitionTest::class)44 .launch()45 result.errors.forAtLeastOne { it.message!!.shouldContain("unfinished expect") }46 }47 }48}49private class FunSpecUnfinishedTestDefinitionTest : FunSpec({50 context("context") {51 test("unfinished test")52 }53})54private class FeatureSpecUnfinishedTestDefinitionTest : FeatureSpec({55 feature("feature") {56 scenario("unfinished scenario")57 }58})59private class ShouldSpecUnfinishedTestDefinitionTest : ShouldSpec({60 context("context") {61 should("unfinished should")62 }63})64private class ExpectSpecUnfinishedTestDefinitionTest : ExpectSpec({65 context("context") {66 expect("unfinished expect")67 }68})69private class DescribeSpecUnfinishedTestDefinitionTest : DescribeSpec({70 describe("describe") {71 it("unfinished it")72 }73})...
ItCallsFor.kt
Source:ItCallsFor.kt
...43 testFlow: TestFlow<*>,44 testContainer: ViewModelTestContainer45) {46 it("starts $flowDesc") {47 testFlow.state shouldBe TestFlow.State.Started48 }49 describe("when cleared") {50 testContainer.clear()51 it("cancels $flowDesc collection") {52 testFlow.state shouldBe TestFlow.State.Cancelled53 }54 }55}56suspend fun DescribeScope.itCollects(57 flowDesc: String,58 testFlow: TestFlow<*>,59 testCollector: FlowTestCollector<*>60) {61 it("starts $flowDesc") {62 testFlow.state shouldBe TestFlow.State.Started63 }64 describe("when collection is cancelled") {65 testCollector.close()66 it("cancels $flowDesc collection") {67 testFlow.state shouldBe TestFlow.State.Cancelled68 }69 }70}...
ProfileDataShouldSpec.kt
Source:ProfileDataShouldSpec.kt
1package de.jlnstrk.transit.util.testing2import io.kotest.core.spec.style.ShouldSpec3import io.kotest.core.spec.style.scopes.ShouldSpecContainerScope4import io.kotest.core.test.TestContext5import kotlinx.coroutines.delay6public abstract class ProfileDataShouldSpec<Endpoint : Any, Profile : ServiceTestProfile<Endpoint, *>>(7 allProfiles: List<Profile>,8 test: suspend ShouldSpecContainerScope.(Endpoint, Profile) -> Unit9) :10 ShouldSpec(spec@{11 for (profile in allProfiles) {12 val client = profile.makeTestEndpoint()13 context("For profile ${profile.name}") {14 test(client, profile)15 }16 }17 }) {18}19public suspend inline fun <reified DataSet : Any> ShouldSpecContainerScope.givenAll(20 from: ServiceTestProfile<*, *>,21 require: Boolean = true,22 crossinline test: suspend TestContext.(DataSet) -> Unit23) {24 val dataSets = from.testData[DataSet::class].orEmpty() as List<DataSet>25 if (dataSets.isEmpty()) {26 if (require) {27 throw IllegalStateException("No ${DataSet::class.simpleName} specified for ${from.name}")28 } else {29 println("${this::class.simpleName} did not run for ${from.name}")30 }31 }32 for (dataSet in dataSets) {33 context("Given dataSet $dataSet") {34 test(dataSet)35 }36 delay(500)37 }38}39public suspend inline fun <Profile : ServiceTestProfile<*, DataSet>, reified DataSet : Any> ShouldSpecContainerScope.givenOne(40 from: Profile,41 require: Boolean = true,42 crossinline test: suspend TestContext.(DataSet) -> Unit43) {44 val dataSet = from.testData[DataSet::class].orEmpty().firstOrNull()45 if (dataSet == null) {46 if (require) {47 throw IllegalStateException("No ${DataSet::class.simpleName} specified for ${from.name}")48 } else {49 println("${this::class.simpleName} did not run for ${from.name}")50 }51 } else {52 context("Given dataSet $dataSet") {53 test(dataSet)54 }55 }56}...
state
Using AI Code Generation
1"test name" - { }2"test name" { }3"test name" should { }4"test name" should { }5"test name" should "test name" { }6"test name" should "test name" { }7"test name" When { }8"test name" When { }9"test name" When "test name" { }10"test name" When "test name" { }11"test name" When "test name" should { }12"test name" When "test name" should { }13"test name" When "test name" should "test name" { }14"test name" When "test name" should "test name" { }15"test name" Given { }16"test name" Given { }17"test name" Given "test name" { }18"test name" Given "test name" { }19"test name" Given "test name" should { }20"test name" Given "test name" should { }21"test name" Given "test name" should "test name" { }22"test name" Given "test name" should "test name" { }23"test name" And { }24"test name" And { }25"test name" And "test name" { }26"test name" And "test name" { }27"test name" And "test name" should { }28"test name" And "test name" should { }29"test name" And "test name" should "test name" { }30"test name" And "test name" should "test name" { }31"test name" AndGiven { }32"test name" AndGiven { }33"test name" AndGiven "test name" { }34"test name" AndGiven "test name" { }35"test name" AndGiven "test name" should { }36"test name" AndGiven "test name" should { }
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!!