How to use runBlocking class of io.kotest.common package

Best Kotest code snippet using io.kotest.common.runBlocking

BeskjedQueriesTest.kt

Source:BeskjedQueriesTest.kt Github

copy

Full Screen

...5import io.kotest.matchers.collections.shouldContainAll6import io.kotest.matchers.collections.shouldHaveSize7import io.kotest.matchers.collections.shouldNotContain8import io.kotest.matchers.shouldBe9import kotlinx.coroutines.runBlocking10import no.nav.personbruker.dittnav.eventaggregator.common.database.LocalPostgresDatabase11import no.nav.personbruker.dittnav.eventaggregator.common.database.util.countTotalNumberOfEvents12import no.nav.personbruker.dittnav.eventaggregator.common.database.util.countTotalNumberOfEventsByActiveStatus13import no.nav.personbruker.dittnav.eventaggregator.config.EventType14import no.nav.personbruker.dittnav.eventaggregator.done.DoneObjectMother15import org.junit.jupiter.api.Test16import java.sql.SQLException17import java.time.LocalDateTime18import java.time.temporal.ChronoUnit19class BeskjedQueriesTest {20    private val database = LocalPostgresDatabase.migratedDb()21    private val beskjed1: Beskjed22    private val beskjed2: Beskjed23    private val beskjed3: Beskjed24    private val beskjed4: Beskjed25    private val expiredBeskjed: Beskjed26    private val beskjedWithOffsetForstBehandlet: Beskjed27    private val systembruker = "dummySystembruker"28    private val fodselsnummer = "12345"29    private val eventId = "2"30    private val allEvents: List<Beskjed>31    private val allEventsForSingleUser: List<Beskjed>32    init {33        beskjed1 = createBeskjed("1", "12345")34        beskjed2 = createBeskjed("2", "12345")35        beskjed3 = createBeskjed("3", "12345")36        beskjed4 = createBeskjed("4", "6789")37        expiredBeskjed = createExpiredBeskjed("123", "4567")38        beskjedWithOffsetForstBehandlet = createBeskjedWithOffsetForstBehandlet("5", "12345")39        allEvents = listOf(beskjed1, beskjed2, beskjed3, beskjed4, expiredBeskjed, beskjedWithOffsetForstBehandlet)40        allEventsForSingleUser = listOf(beskjed1, beskjed2, beskjed3, beskjedWithOffsetForstBehandlet)41    }42    private fun createBeskjed(eventId: String, fodselsnummer: String): Beskjed {43        val beskjed = BeskjedObjectMother.giveMeAktivBeskjed(eventId, fodselsnummer)44        return runBlocking {45            database.dbQuery {46                createBeskjed(beskjed).entityId.let {47                    beskjed.copy(id = it)48                }49            }50        }51    }52    private fun createExpiredBeskjed(eventId: String, fodselsnummer: String): Beskjed {53        val beskjed = BeskjedObjectMother.giveMeAktivBeskjed(eventId, fodselsnummer)54            .copy(synligFremTil = LocalDateTime.now().minusDays(1).truncatedTo(ChronoUnit.MILLIS))55        return runBlocking {56            database.dbQuery {57                createBeskjed(beskjed).entityId.let {58                    beskjed.copy(id = it)59                }60            }61        }62    }63    private fun createBeskjedWithOffsetForstBehandlet(eventId: String, fodselsnummer: String): Beskjed {64        val offsetDate = LocalDateTime.now().minusDays(1).truncatedTo(ChronoUnit.MILLIS)65        val beskjed = BeskjedObjectMother.giveMeBeskjedWithForstBehandlet(eventId, fodselsnummer, offsetDate)66        return runBlocking {67            database.dbQuery {68                createBeskjed(beskjed).entityId.let {69                    beskjed.copy(id = it)70                }71            }72        }73    }74    @Test75    fun `Finner alle aktive cachede Beskjed-eventer`() {76        val doneEvent = DoneObjectMother.giveMeDone(eventId, systembruker, fodselsnummer)77        runBlocking {78            database.dbQuery { setBeskjederAktivflagg(listOf(doneEvent), false) }79            val result = database.dbQuery { getAllBeskjedByAktiv(true) }80            result shouldContainAll listOf(beskjed1, beskjed3, beskjed4)81            result shouldNotContain beskjed282            database.dbQuery { setBeskjederAktivflagg(listOf(doneEvent), true) }83        }84    }85    @Test86    fun `Finner cachet Beskjed-event med Id`() {87        runBlocking {88            val result = database.dbQuery { beskjed2.id?.let { getBeskjedById(it) } }89            result shouldBe beskjed290        }91    }92    @Test93    fun `Kaster Exception hvis Beskjed-event med Id ikke finnes`() {94        shouldThrow<SQLException> {95            runBlocking {96                database.dbQuery { getBeskjedById(999) }97            }98        }.message shouldBe "Found no rows"99    }100    @Test101    fun `Finner cachede Beskjeds-eventer for fodselsnummer`() {102        runBlocking {103            val result = database.dbQuery { getBeskjedByFodselsnummer(fodselsnummer) }104            result.size shouldBe 4105            result shouldContainAll allEventsForSingleUser106        }107    }108    @Test109    fun `Returnerer tom liste hvis Beskjeds-eventer for fodselsnummer ikke finnes`() {110        runBlocking {111            val result = database.dbQuery { getBeskjedByFodselsnummer("-1") }112            result.isEmpty() shouldBe true113        }114    }115    @Test116    fun `Finner cachet Beskjed-event med eventId`() {117        runBlocking {118            val result = database.dbQuery { getBeskjedByEventId(eventId) }119            result shouldBe beskjed2120        }121    }122    @Test123    fun `Kaster Exception hvis Beskjed-event med eventId ikke finnes`() {124        shouldThrow<SQLException> {125            runBlocking {126                database.dbQuery { getBeskjedByEventId("-1") }127            }128        }.message shouldBe "Found no rows"129    }130    @Test131    fun `Skal haandtere at prefererteKanaler er tom`() {132        val beskjed = BeskjedObjectMother.giveMeAktivBeskjedWithEksternVarslingAndPrefererteKanaler(true, emptyList())133        runBlocking {134            database.dbQuery { createBeskjed(beskjed) }135            val result = database.dbQuery { getBeskjedByEventId(beskjed.eventId) }136            result.prefererteKanaler.shouldBeEmpty()137            database.dbQuery { deleteBeskjedWithEventId(beskjed.eventId) }138        }139    }140    @Test141    fun `Skal skrive eventer i batch`() {142        val beskjed1 = BeskjedObjectMother.giveMeAktivBeskjed("b-1", "123")143        val beskjed2 = BeskjedObjectMother.giveMeAktivBeskjed("b-2", "123")144        runBlocking {145            database.dbQuery {146                createBeskjeder(listOf(beskjed1, beskjed2))147            }148            val beskjed1FraDb = database.dbQuery { getBeskjedByEventId(beskjed1.eventId) }149            val beskjed2FraDb = database.dbQuery { getBeskjedByEventId(beskjed2.eventId) }150            beskjed1FraDb.eventId shouldBe beskjed1.eventId151            beskjed2FraDb.eventId shouldBe beskjed2.eventId152            database.dbQuery { deleteBeskjedWithEventId(beskjed1.eventId) }153            database.dbQuery { deleteBeskjedWithEventId(beskjed2.eventId) }154        }155    }156    @Test157    fun `Skal telle det totale antall beskjeder`() {158        runBlocking {159            database.dbQuery {160                countTotalNumberOfEvents(EventType.BESKJED_INTERN)161            }162        } shouldBe allEvents.size.toLong()163    }164    @Test165    fun `Skal telle det totale antall aktive beskjeder`() {166        runBlocking {167            database.dbQuery {168                countTotalNumberOfEventsByActiveStatus(EventType.BESKJED_INTERN, true)169            }170        } shouldBe allEvents.size.toLong()171    }172    @Test173    fun `Skal telle det totale antall inaktive beskjeder`() {174        runBlocking {175            database.dbQuery {176                countTotalNumberOfEventsByActiveStatus(EventType.BESKJED_INTERN, false)177            }178        } shouldBe 0179    }180    @Test181    fun `Finner utgått beskjeder`() {182        runBlocking {183            val result = database.dbQuery {184                getExpiredBeskjedFromCursor()185            }186            result shouldHaveSize 1187            result shouldContain expiredBeskjed188        }189    }190}...

Full Screen

Full Screen

BandServiceTest.kt

Source:BandServiceTest.kt Github

copy

Full Screen

1package org.jesperancinha.vma.vmaservice.service2import com.ninjasquad.springmockk.MockkBean3import io.kotest.common.runBlocking4import io.kotest.matchers.collections.shouldContain5import io.kotest.matchers.collections.shouldHaveSize6import io.kotest.matchers.longs.shouldBeLessThanOrEqual7import io.kotest.matchers.shouldBe8import io.mockk.coEvery9import io.mockk.coVerify10import io.mockk.every11import kotlinx.coroutines.Dispatchers12import kotlinx.coroutines.asCoroutineDispatcher13import kotlinx.coroutines.async14import kotlinx.coroutines.awaitAll15import kotlinx.coroutines.coroutineScope16import kotlinx.coroutines.delay17import kotlinx.coroutines.flow.flow18import kotlinx.coroutines.flow.toList19import kotlinx.coroutines.launch20import kotlinx.coroutines.withContext21import org.jesperancinha.vma.common.domain.Band22import org.jesperancinha.vma.common.domain.BandRepository23import org.junit.jupiter.api.Test24import org.junit.jupiter.api.extension.ExtendWith25import org.springframework.beans.factory.annotation.Autowired26import org.springframework.test.context.ContextConfiguration27import org.springframework.test.context.junit.jupiter.SpringExtension28import java.util.UUID29import java.util.concurrent.Executors.newFixedThreadPool30import kotlin.system.measureTimeMillis31@ExtendWith(SpringExtension::class)32@ContextConfiguration(classes = [BandService::class])33internal class BandServiceTest(34    @Autowired35    private val bandService: BandService36) {37    @MockkBean38    lateinit var bandRepository: BandRepository39    @Test40    fun `should get all bands when summoning findAll`() = runBlocking {41        val testBand = Band(name = "The Doors")42        every { bandRepository.findAll() } returns flow { emit(testBand) }43        val fetchAllBands = bandService.fetchAllBands()44        fetchAllBands.toList() shouldContain testBand45    }46    @Test47    fun `should get band by Id`() = runBlocking {48        val id = "the-doors" + UUID.randomUUID().toString()49        val testBand = Band(name = "The Doors")50        coEvery { bandRepository.findById(id) } returns testBand51        val band = bandService.getBandById(id)52        band shouldBe testBand53    }54    @Test55    fun `should take exactly 100ms to get two bands with minimum 100ms delay`(): Unit = runBlocking {56        val id = "the-doors" + UUID.randomUUID().toString()57        val testBand = Band(name = "The Doors")58        coEvery { bandRepository.findById(id) } returns testBand59        val processingTime = measureTimeMillis {60            val dispatcher = newFixedThreadPool(2)61                .asCoroutineDispatcher()62            withContext(dispatcher) {63                delay(100)64                val band = bandService.getBandById(id)65                band shouldBe testBand66            }67            withContext(dispatcher) {68                delay(100)69                val band = bandService.getBandById(id)70                band shouldBe testBand71            }72        }73        processingTime.shouldBeLessThanOrEqual(300)74        coVerify(exactly = 2) { bandRepository.findById(id) }75    }76    /**77     * withContext suspends until completion78     */79    @Test80    fun `should read two using withContext if one takes 100ms and the other 200ms and no waiting on the main thread`(): Unit =81        runBlocking {82            val id = "the-doors" + UUID.randomUUID().toString()83            val testBand = Band(name = "The Doors")84            coEvery { bandRepository.findById(id) } returns testBand85            val dispatcher = newFixedThreadPool(2)86                .asCoroutineDispatcher()87            withContext(dispatcher) {88                delay(100)89                val band = bandService.getBandById(id)90                band shouldBe testBand91            }92            withContext(dispatcher) {93                delay(2000)94                val band = bandService.getBandById(id)95                band shouldBe testBand96            }97            coVerify(exactly = 2) { bandRepository.findById(id) }98        }99    /**100     * coroutineScope waits until completion101     */102    @Test103    fun `should read two using coroutineScope if one takes 100ms and the other 200ms and no waiting on the main thread`() =104        runBlocking {105            val id = "the-doors" + UUID.randomUUID().toString()106            val testBand = Band(name = "The Doors")107            coEvery { bandRepository.findById(id) } returns testBand108            coroutineScope {109                val band = bandService.getBandById(id)110                band shouldBe testBand111                delay(100)112            }113            coroutineScope {114                val band = bandService.getBandById(id)115                band shouldBe testBand116                delay(200)117            }118            coVerify(exactly = 2) { bandRepository.findById(id) }119        }120    /**121     * coroutineScope + async may not wait until completion122     */123    @Test124    fun `should read one using async if one takes 100ms and the other 200ms and no waiting on the main thread`(): Unit =125        runBlocking {126            val id = "the-doors" + UUID.randomUUID().toString()127            val testBand = Band(name = "The Doors")128            coEvery { bandRepository.findById(id) } returns testBand129            val coroutineResult = coroutineScope {130                listOf(131                    async(Dispatchers.IO) {132                        delay(100)133                        val band = bandService.getBandById(id)134                        band shouldBe testBand135                        band136                    }, async(Dispatchers.IO) {137                        suspend {138                            delay(200)139                            val band = bandService.getBandById(id)140                            band shouldBe testBand141                            band142                        }143                    })144            }145            delay(200)146            coVerify(exactly = 1) { bandRepository.findById(id) }147            val result = coroutineResult.awaitAll()148            result.shouldHaveSize(2)149        }150    /**151     * launch coroutines152     */153    @Test154    suspend fun `should run launch asynchronously within the same coroutineScope`() {155        runBlocking {156            val id = "the-doors" + UUID.randomUUID().toString()157            val testBand = Band(name = "The Doors")158            coEvery { bandRepository.findById(id) } returns testBand159            coroutineScope {160                launch {161                    val band = bandService.getBandById(id)162                    band shouldBe testBand163                    delay(100)164                }165                launch {166                    val band = bandService.getBandById(id)167                    band shouldBe testBand168                    delay(200)169                }170            }171            coVerify(exactly = 0) { bandRepository.findById(id) }172            delay(100)173            coVerify(exactly = 1) { bandRepository.findById(id) }174            delay(100)175            coVerify(exactly = 2) { bandRepository.findById(id) }176        }177    }178    /**179     * await for asynchronous routinr180     */181    @Test182    fun `should await for the asynchronous coroutine to complete`(): Unit =183        runBlocking {184            val id = "the-doors" + UUID.randomUUID().toString()185            val testBand = Band(name = "The Doors")186            coEvery { bandRepository.findById(id) } returns testBand187            val coroutineResult = coroutineScope {188                    async(Dispatchers.IO) {189                        delay(100)190                        val band = bandService.getBandById(id)191                        band shouldBe testBand192                        band193                    }194            }195            delay(100)196            coVerify(exactly = 1) { bandRepository.findById(id) }197            val result = coroutineResult.await()...

Full Screen

Full Screen

KernelServerIntegTest.kt

Source:KernelServerIntegTest.kt Github

copy

Full Screen

...30import io.kotest.matchers.collections.shouldHaveSingleElement31import io.kotest.matchers.ints.shouldBeGreaterThanOrEqual32import io.kotest.matchers.shouldBe33import kotlinx.coroutines.flow.toCollection34import kotlinx.coroutines.runBlocking35import org.junit.jupiter.api.Test36import org.junit.jupiter.api.Timeout37import org.junit.jupiter.api.io.TempDir38import java.io.File39import java.util.concurrent.TimeUnit40@Timeout(value = 5, unit = TimeUnit.MINUTES)41internal class KernelServerIntegTest {42    @Test43    fun `run test script`(@TempDir tempDir: File) {44        val server = KernelServer()45        server.port.shouldBe(-1)46        server.ensureStarted(gitHubCacheDirectory = tempDir.toPath())47        server.port.shouldBeGreaterThanOrEqual(0)48        val channel = ManagedChannelBuilder.forAddress("localhost", server.port)49            .usePlaintext()50            .build()51        val policyService = PolicyServiceGrpcKt.PolicyServiceCoroutineStub(channel)52        val scriptHost = ScriptHostGrpcKt.ScriptHostCoroutineStub(channel)53        val policy = PolicyDocument.newBuilder().apply {54            version = "2021-04-17"55            addStatements(56                PolicyContainer.newBuilder().apply {57                    credentialPolicyBuilder.credentials = "anonymous"58                    credentialPolicyBuilder.addScopes("github:repo:CommonWealthRobotics/bowler-kernel-test-repo")59                }.build()60            )61        }.build()62        val runRequest = RunRequest.newBuilder().apply {63            fileBuilder.projectBuilder.repoRemote =64                "https://github.com/CommonWealthRobotics/bowler-kernel-test-repo.git"65            fileBuilder.projectBuilder.revision = "master"66            fileBuilder.projectBuilder.patchBuilder.patch = ByteString.EMPTY67            fileBuilder.path = "scriptA.groovy"68        }.build()69        runBlocking {70            policyService.setPolicyDocument(policy).accepted.shouldBeTrue()71        }72        repeat(10) {73            val result = runBlocking {74                scriptHost.runScript(runRequest).toCollection(mutableListOf())75            }76            result[0].shouldHaveNewTask(1, Float.NaN)77            result[1].shouldHaveTaskEnd(1)78            result[2].shouldHaveNewTask(2, Float.NaN)79            result.subList(3, result.size).shouldHaveSingleElement {80                it.hasTaskEnd() && it.taskEnd.taskId == 2L81            }82            result.subList(3, result.size).filter { it.hasIntermediateOutput() }.shouldHaveAtLeastSize(1)83            result.subList(3, result.size).shouldHaveSingleElement {84                it.hasScriptOutput() && it.scriptOutput.output == "42"85            }86        }87        server.ensureStopped()88        server.port.shouldBe(-1)89    }90    @Test91    fun `run script that tries to clone without creds`(@TempDir tempDir: File) {92        val server = KernelServer()93        server.port.shouldBe(-1)94        server.ensureStarted(gitHubCacheDirectory = tempDir.toPath())95        server.port.shouldBeGreaterThanOrEqual(0)96        val channel = ManagedChannelBuilder.forAddress("localhost", server.port)97            .usePlaintext()98            .build()99        val scriptHost = ScriptHostGrpcKt.ScriptHostCoroutineStub(channel)100        val runRequest = RunRequest.newBuilder().apply {101            fileBuilder.projectBuilder.repoRemote =102                "https://github.com/CommonWealthRobotics/bowler-kernel-test-repo.git"103            fileBuilder.projectBuilder.revision = "master"104            fileBuilder.projectBuilder.patchBuilder.patch = ByteString.EMPTY105            fileBuilder.path = "scriptA.groovy"106        }.build()107        // Don't set a policy document before running this script so that nothing is allowed108        runBlocking {109            // This should throw because the policy document has not been set, so the kernel must act as if an empty110            // policy document was set, which denies all authentication operations111            shouldThrow<StatusException> {112                scriptHost.runScript(runRequest).toCollection(mutableListOf())113            }114        }115        server.ensureStopped()116        server.port.shouldBe(-1)117    }118    companion object {119        private fun RunResponse.shouldHaveNewTask(taskId: Long, progress: Float) {120            hasNewTask().shouldBeTrue()121            newTask.hasTask().shouldBeTrue()122            newTask.task.taskId.shouldBe(taskId)...

Full Screen

Full Screen

ItemControllerTest.kt

Source:ItemControllerTest.kt Github

copy

Full Screen

...21import io.micronaut.test.extensions.kotest.annotation.MicronautTest22import io.mockk.mockk23import kotlinx.coroutines.flow.collect24import kotlinx.coroutines.flow.toList25import kotlinx.coroutines.runBlocking26import java.math.BigDecimal27import java.time.YearMonth28@ExperimentalKotest29@MicronautTest30class ItemControllerTest(31    private val userRepo: UserRepository,32    private val itemRepo: ItemRepository,33    private val itemClient: ItemClient,34    private val authClient: AuthClient35) : DescribeSpec({36    val testUsername = "admin"37    beforeSpec {38        userRepo.deleteAll()39        userRepo.save(fakeUsers().getValue(testUsername))40    }41    beforeEach {42        runBlocking {43            itemRepo.deleteAll()44        }45    }46    describe("paginate 25 items") {47        val userId = userRepo.findByUsername("admin")?.id!!48        val totalItems = 2549        itemRepo.saveAll(fakeItems(userId, totalItems)).collect()50        val allItems = itemRepo.findAll().toList().sortedBy { it.id }51        val token = authHeader(authClient, testUsername)52        val req = mockk<HttpRequest<Any>>()53        data class Page(val start: Int, val end: Int, val size: Int)54        withData(55            Page(0, 10, 10),56            Page(10, 20, 10),...

Full Screen

Full Screen

CharacterRepositoryTest.kt

Source:CharacterRepositoryTest.kt Github

copy

Full Screen

...6import fr.cedriccreusot.rickandmortyapi.domain.model.Object7import fr.cedriccreusot.rickandmortyapi.domain.model.Status8import fr.cedriccreusot.rickandmortyapi.domain.services.CharacterResponse9import io.kotest.common.ExperimentalKotest10import io.kotest.common.runBlocking11import io.kotest.core.spec.style.ShouldSpec12import io.kotest.matchers.shouldBe13import kotlinx.serialization.decodeFromString14import kotlinx.serialization.json.Json15@ExperimentalKotest16class CharacterRepositoryTest : ShouldSpec() {17    init {18        testCoroutineDispatcher = true19        coroutineDebugProbes = true20        context("CharacterRepository.getCharacters") {21            should("return an empty list if there is a problem") {22                runBlocking {23                    val repository =24                        CharacterRepository(RickAndMortyServiceMock.createSerivceThatFail())25                    val result = repository.getCharacters()26                    result.isEmpty() shouldBe true27                }28            }29            should("call the service then return a list of characters") {30                val json = JsonFileUtils.readJsonFile("character.json")31                val mocked = Json.decodeFromString<CharacterResponse>(json)32                runBlocking {33                    val repository =34                        CharacterRepository(35                            RickAndMortyServiceMock.createServiceThatSucceed(36                                characterResponse = mocked37                            )38                        )39                    val result = repository.getCharacters()40                    result shouldBe listOf(41                        Character(42                            id = 1,43                            name = "Rick Sanchez",44                            status = Status.Alive,45                            species = "Human",46                            type = "",...

Full Screen

Full Screen

SimplifiedRationalTest.kt

Source:SimplifiedRationalTest.kt Github

copy

Full Screen

...4import io.kotest.matchers.shouldNotBe5import io.kotest.property.Arb6import io.kotest.property.arbitrary.int7import io.kotest.property.checkAll8import kotlinx.coroutines.runBlocking9import org.junit.jupiter.api.Test10class SimplifiedRationalTest {11    @Test12    fun `create valid rational number from integer number`() {13        runBlocking {14            checkAll(Arb.int()) { number ->15                val rational = number.toRational()16                rational.numerator shouldBe number17                rational.denominator shouldBe 118            }19        }20    }21    @Test22    fun `create reciprocal for a given integer number`() {23        runBlocking {24            checkAll(Arb.int()) { number ->25                val rational = number.reciprocal()26                rational.numerator shouldBe 127                rational.denominator shouldBe number28            }29        }30    }31    @Test32    fun `rationalDiv should create ration number from two integers`() {33        runBlocking {34            checkAll(iterations = 20, Arb.int()) { numerator ->35                checkAll(iterations = 20, Arb.int()) { denominator ->36                    (numerator rationalDiv denominator) shouldBe SimplifiedRational(numerator, denominator)37                }38            }39        }40    }41    @Test42    fun `normalization of rational number`() {43        (4 rationalDiv 8).normalize() shouldBe (1 rationalDiv 2)44        (10 rationalDiv 4).normalize() shouldBe (5 rationalDiv 2)45        (6 rationalDiv 15).normalize() shouldBe (2 rationalDiv 5)46    }47    @Test48    fun `div operator should divide rational number by integer and return valid result`() {49        runBlocking {50            checkAll(iterations = 20, Arb.int()) { numerator ->51                checkAll(iterations = 20, Arb.int()) { denominator ->52                    checkAll(iterations = 10, Arb.int()) { divisor ->53                        (numerator rationalDiv denominator) / divisor shouldBe (numerator rationalDiv (divisor * denominator))54                    }55                }56            }57        }58    }59    @Test60    fun `half function should divide rational number by two`() {61        runBlocking {62            checkAll(iterations = 20, Arb.int()) { numerator ->63                checkAll(iterations = 20, Arb.int()) { denominator ->64                    (numerator rationalDiv denominator).half() shouldBe (numerator rationalDiv (2 * denominator))65                }66            }67        }68    }69    @Test70    fun `+ should add two rational numbers and return valid result`() {71        (1 rationalDiv 2) + (3 rationalDiv 5) shouldBe (11 rationalDiv 10)72        (3 rationalDiv 8) + (1 rationalDiv 8) shouldBe (4 rationalDiv 8)73    }74    @Test75    fun `== should return true for normalized and not normalized versions of same rational number`() {...

Full Screen

Full Screen

BlocksTest.kt

Source:BlocksTest.kt Github

copy

Full Screen

...7import endpoints.common.Link8import endpoints.common.RichTextObject9import endpoints.common.TextObject10import http.getKtorClient11import io.kotest.common.runBlocking12import io.kotest.core.spec.style.AnnotationSpec13import io.kotest.matchers.shouldNotBe14import org.junit.jupiter.api.DisplayName15class BlocksTest : AnnotationSpec() {16	private val blocks: Blocks = Blocks(getKtorClient((Config.notionApiKey)))17	@Test18	@DisplayName("[Blocks] Retrieve paragraph block")19	fun getParagraphBlock() {20		val result = runBlocking {21			blocks.retrieve(BlockIdRequest(Config.Block.paragraphId))22		}23		result shouldNotBe null24		result is BlockResponse25	}26	@Test27	@DisplayName("[Blocks] Update todo block")28	fun updateBlock() {29		val result = runBlocking {30			val todoRequest = BlockUpdateRequest(31				blockId = todoId,32				body = BlockBodyRequest.Todo(33					toDo = ToDoRequestType(34						richText = listOf(35							RichTextObject.Text(36								text = TextObject("Lacinato kale.", null)37							)38						),39						checked = true40					)41				)42			)43			blocks.update(todoRequest)44		}45		result shouldNotBe null46		result is BlockResponse47	}48	@Test49	@DisplayName("[Blocks] Retrieve children block")50	fun retrieveChildrenBlock() {51		val result = runBlocking {52			blocks.retrieveChildren(BlockRetrieveChildRequest(Config.Block.pageId))53		}54		result shouldNotBe null55		result is BlockListResponse56	}57	@Test58	@DisplayName("[Blocks] Append children block")59	fun appendChildrenBlock() {60		val result = runBlocking {61			val pageRequest = BlockAppendChildRequest(62				blockId = Config.Block.pageId,63				body = BlockListChildRequest(64					listOf(65						BlockListBodyRequest.Heading2(66							heading2 = HeadingRequestType(67								listOf(68									RichTextObject.Text(69										text = TextObject(70											content = "Lacinato kale",71											link = Link(72												url = "https://en.wikipedia.org/wiki/Lacinato_kale"73											)74										)75									)76								)77							)78						),79						BlockListBodyRequest.Paragraph(80							paragraph = ParagraphRequestType(81								listOf(82									RichTextObject.Text(83										text = TextObject(84											content = "Lacinato kale is a variety of kale with a long tradition in Italian cuisine, especially that of Tuscany.",85											link = Link(86												url = "https://en.wikipedia.org/wiki/Lacinato_kale"87											)88										)89									)90								)91							)92						)93					)94				)95			)96			blocks.appendChildren(pageRequest)97		}98		result shouldNotBe null99		result is BlockListResponse100	}101	@Test102	@DisplayName("[Blocks] Delete block")103	fun deleteBlock() {104		val result = runBlocking {105			blocks.delete(BlockIdRequest(Config.Block.codeId))106		}107		result shouldNotBe null108		result is BlockResponse109	}110}...

Full Screen

Full Screen

TestProjectConfig.kt

Source:TestProjectConfig.kt Github

copy

Full Screen

1package me.gubin.simple.service2import io.kotest.common.runBlocking3import io.kotest.core.config.AbstractProjectConfig4import io.kotest.core.listeners.ProjectListener5import io.ktor.server.engine.*6import io.ktor.server.netty.*7import me.gubin.simple.service.persistence.configureDatabase8import me.gubin.simple.service.routings.configureApiRouting9import me.gubin.simple.service.routings.configureSecurity10class TestProjectConfig : AbstractProjectConfig() {11    override fun extensions() = listOf(KtorServerListener)12    override val includeTestScopePrefixes = true13}14object KtorServerListener : ProjectListener {15    private val embeddedServer = embeddedServer(Netty, port = 0) {16        configurePlugins()17        configureDatabase()18        configureSecurity()19        configureApiRouting()20    }21    override suspend fun beforeProject() {22            embeddedServer.start()23    }24    override suspend fun afterProject() {25            embeddedServer.stop()26    }27    fun getServerPort() = runBlocking { embeddedServer.resolvedConnectors().first().port }28}...

Full Screen

Full Screen

runBlocking

Using AI Code Generation

copy

Full Screen

1import io.kotest.common.*2fun main() {3runBlocking {4println("Hello from runBlocking")5}6}7import io.kotest.core.*8fun main() {9runBlocking {10println("Hello from runBlocking")11}12}

Full Screen

Full Screen

runBlocking

Using AI Code Generation

copy

Full Screen

1import io.kotest.common.runBlocking2class MyTest {3fun test() {4runBlocking {5}6}7}8import kotlinx.coroutines.runBlocking9class MyTest {10fun test() {11runBlocking {12}13}14}

Full Screen

Full Screen

runBlocking

Using AI Code Generation

copy

Full Screen

1import io.kotest.core.spec.style.DescribeSpec2import io.kotest.matchers.shouldBe3import kotlinx.coroutines.runBlocking4class DescribeSpecTest : DescribeSpec({5    describe("DescribeSpecTest") {6        context("test case") {7            runBlocking {8                it("should be true") {9                }10            }11        }12    }13})14import io.kotest.core.spec.style.DescribeSpec15import io.kotest.matchers.shouldBe16import kotlinx.coroutines.runBlocking17class DescribeSpecTest : DescribeSpec({18    describe("DescribeSpecTest") {19        context("test case") {20            runBlocking {21                it("should be true") {22                }23            }24        }25    }26})27import io.kotest.core.spec.style.DescribeSpec28import io.kotest.matchers.shouldBe29import kotlinx.coroutines.runBlocking30class DescribeSpecTest : DescribeSpec({31    describe("DescribeSpecTest") {32        context("test case") {33            runBlocking {34                it("should be true") {35                }36            }37        }38    }39})40import io.kotest.core.spec.style.DescribeSpec41import io.kotest.matchers.shouldBe42import kotlinx.coroutines.runBlocking43class DescribeSpecTest : DescribeSpec({44    describe("DescribeSpecTest") {45        context("test case") {46            runBlocking {47                it("should be true") {48                }49            }50        }51    }52})

Full Screen

Full Screen

runBlocking

Using AI Code Generation

copy

Full Screen

1class MyUnitTest {  2fun test() = runBlocking {  3}  4}5class MyUnitTest {  6fun test() = runBlockingTest {  7}  8}9class MyUnitTest {  10fun test() = runBlockingTest {  11}  12}13class MyUnitTest {  14fun test() = runBlockingTest {  15}  16}17class MyUnitTest {  18fun test() = runBlockingTest {  19}  20}21class MyUnitTest {  22fun test() = runBlockingTest {  23}  24}25class MyUnitTest {  26fun test() = runBlockingTest {  27}  28}29class MyUnitTest {  30fun test() = runBlockingTest {  31}  32}33class MyUnitTest {  34fun test() = runBlockingTest {  35}  36}37class MyUnitTest {  38fun test() = runBlockingTest {  39}  40}

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 Kotest automation tests on LambdaTest cloud grid

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

Most used methods in runBlocking

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful