Best Kotest code snippet using io.kotest.common.runBlocking.runBlocking
BeskjedQueriesTest.kt
Source:BeskjedQueriesTest.kt
...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}...
BandServiceTest.kt
Source:BandServiceTest.kt
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()...
OppgaveQueriesTest.kt
Source:OppgaveQueriesTest.kt
...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.done.DoneObjectMother12import org.junit.jupiter.api.Test13import java.sql.SQLException14import java.time.LocalDateTime15import java.time.temporal.ChronoUnit16class OppgaveQueriesTest {17 private val database = LocalPostgresDatabase.migratedDb()18 private val fodselsnummer1 = "12345"19 private val fodselsnummer2 = "54321"20 private val oppgave1: Oppgave21 private val oppgave2: Oppgave22 private val oppgave3: Oppgave23 private val expiredOppgave: Oppgave24 private val oppgaveWithOffsetForstBehandlet: Oppgave25 private val systembruker = "dummySystembruker"26 private val eventId = "2"27 private val allEvents: List<Oppgave>28 private val allEventsForSingleUser: List<Oppgave>29 init {30 oppgave1 = createOppgave("1", fodselsnummer1)31 oppgave2 = createOppgave("2", fodselsnummer2)32 oppgave3 = createOppgave("3", fodselsnummer1)33 expiredOppgave = createExpiredOppgave("4", "5678")34 oppgaveWithOffsetForstBehandlet = createOppgaveWithOffsetForstBehandlet("5", fodselsnummer1)35 allEvents = listOf(oppgave1, oppgave2, oppgave3, expiredOppgave, oppgaveWithOffsetForstBehandlet)36 allEventsForSingleUser = listOf(oppgave1, oppgave3, oppgaveWithOffsetForstBehandlet)37 }38 private fun createOppgave(eventId: String, fodselsnummer: String): Oppgave {39 var oppgave = OppgaveObjectMother.giveMeAktivOppgave(eventId, fodselsnummer)40 runBlocking {41 database.dbQuery {42 val generatedId = createOppgave(oppgave).entityId43 oppgave = oppgave.copy(id = generatedId)44 }45 }46 return oppgave47 }48 private fun createExpiredOppgave(eventId: String, fodselsnummer: String): Oppgave {49 var oppgave = OppgaveObjectMother.giveMeAktivOppgave(eventId, fodselsnummer)50 .copy(synligFremTil = LocalDateTime.now().minusDays(1).truncatedTo(ChronoUnit.MILLIS))51 runBlocking {52 database.dbQuery {53 val generatedId = createOppgave(oppgave).entityId54 oppgave = oppgave.copy(id = generatedId)55 }56 }57 return oppgave58 }59 private fun createOppgaveWithOffsetForstBehandlet(eventId: String, fodselsnummer: String): Oppgave {60 val offsetDate = LocalDateTime.now().minusDays(1).truncatedTo(ChronoUnit.MILLIS)61 var oppgave = OppgaveObjectMother.giveMeOppgaveWithForstBehandlet(eventId, fodselsnummer, offsetDate)62 runBlocking {63 database.dbQuery {64 val generatedId = createOppgave(oppgave).entityId65 oppgave = oppgave.copy(id = generatedId)66 }67 }68 return oppgave69 }70 @Test71 fun `Finner alle cachede Oppgave-eventer`() {72 runBlocking {73 val result = database.dbQuery { getAllOppgave() }74 result.size shouldBe allEvents.size75 result.toSet() shouldBe allEvents.toSet()76 }77 }78 @Test79 fun `Finner alle aktive cachede Oppgave-eventer`() {80 val doneEvent = DoneObjectMother.giveMeDone(eventId, systembruker, fodselsnummer2)81 runBlocking {82 database.dbQuery { setOppgaverAktivFlag(listOf(doneEvent), false) }83 val result = database.dbQuery { getAllOppgaveByAktiv(true) }84 result shouldContainAll listOf(oppgave1, oppgave3)85 result shouldNotContain oppgave286 database.dbQuery { setOppgaverAktivFlag(listOf(doneEvent), true) }87 }88 }89 @Test90 fun `Finner alle cachede Oppgave-event for fodselsnummer`() {91 runBlocking {92 val result = database.dbQuery { getOppgaveByFodselsnummer(fodselsnummer1) }93 result.size shouldBe allEventsForSingleUser.size94 result shouldContainAll allEventsForSingleUser95 }96 }97 @Test98 fun `Gir tom liste dersom Oppgave-event med gitt fodselsnummer ikke finnes`() {99 runBlocking {100 val result = database.dbQuery { getOppgaveByFodselsnummer("-1") }101 result.isEmpty() shouldBe true102 }103 }104 @Test105 fun `Finner cachet Oppgave-event for Id`() {106 runBlocking {107 val result = database.dbQuery { oppgave2.id?.let { getOppgaveById(it) } }108 result shouldBe oppgave2109 }110 }111 @Test112 fun `Kaster exception dersom Oppgave-event med Id ikke finnes`() {113 shouldThrow<SQLException> {114 runBlocking {115 database.dbQuery { getOppgaveById(-1) }116 }117 }.message shouldBe "Found no rows"118 }119 @Test120 fun `Finner cachet Oppgave-event med eventId`() {121 runBlocking {122 val result = database.dbQuery { getOppgaveByEventId(eventId) }123 result shouldBe oppgave2124 }125 }126 @Test127 fun `Kaster exception dersom Oppgave-event med eventId ikke finnes`() {128 shouldThrow<SQLException> {129 runBlocking {130 database.dbQuery { getOppgaveByEventId("-1") }131 }132 }.message shouldBe "Found no rows"133 }134 @Test135 fun `Persister ikke entitet dersom rad med samme eventId og produsent finnes`() {136 runBlocking {137 database.dbQuery {138 createOppgave(oppgave1)139 val numberOfEvents = getAllOppgave().size140 createOppgave(oppgave1)141 getAllOppgave().size shouldBe numberOfEvents142 }143 }144 }145 @Test146 fun `Skal haandtere at prefererteKanaler er tom`() {147 val oppgave = OppgaveObjectMother.giveMeAktivOppgaveWithEksternVarslingAndPrefererteKanaler(true, emptyList())148 runBlocking {149 database.dbQuery { createOppgave(oppgave) }150 val result = database.dbQuery { getOppgaveByEventId(oppgave.eventId) }151 result.prefererteKanaler.shouldBeEmpty()152 database.dbQuery { deleteOppgaveWithEventId(oppgave.eventId) }153 }154 }155 @Test156 fun `Skal skrive eventer i batch`() {157 val oppgave1 = OppgaveObjectMother.giveMeAktivOppgave("o-1", "123")158 val oppgave2 = OppgaveObjectMother.giveMeAktivOppgave("o-2", "123")159 runBlocking {160 database.dbQuery {161 createOppgaver(listOf(oppgave1, oppgave2))162 }163 val oppgave1FraDb = database.dbQuery { getOppgaveByEventId(oppgave1.eventId) }164 val oppgave2FraDb = database.dbQuery { getOppgaveByEventId(oppgave2.eventId) }165 oppgave1FraDb.eventId shouldBe oppgave1.eventId166 oppgave2FraDb.eventId shouldBe oppgave2.eventId167 database.dbQuery { deleteOppgaveWithEventId(oppgave1.eventId) }168 database.dbQuery { deleteOppgaveWithEventId(oppgave2.eventId) }169 }170 }171 @Test172 fun `Finner utaatt oppgaver`() {173 runBlocking {174 val result = database.dbQuery {175 getExpiredOppgave()176 }177 result shouldHaveSize 1178 result shouldContain expiredOppgave179 }180 }181}...
DatabasesTest.kt
Source:DatabasesTest.kt
...6import endpoints.databases.dto.request.*7import endpoints.databases.dto.response.DatabaseResponse8import endpoints.databases.dto.response.Parent9import http.getKtorClient10import io.kotest.common.runBlocking11import io.kotest.core.spec.style.AnnotationSpec12import io.kotest.matchers.shouldNotBe13import org.junit.jupiter.api.DisplayName14internal class DatabasesTest : AnnotationSpec() {15 private val databases: Databases = Databases(getKtorClient(Config.notionApiKey))16 @Test17 @DisplayName("[Databases] Create a database")18 fun createDatabase() {19 val result = runBlocking {20 databases.create(21 DatabaseCreateRequest(22 parent = Parent.Page(23 pageId = Config.Database.pageId24 ),25 title = listOf(26 RichTextObject.Text(27 text = TextObject(28 content = "Grocery List",29 link = null30 ),31 )32 ),33 properties = mapOf(34 "Name" to DatabaseCreateProperties.Title(),35 "Description" to DatabaseCreateProperties.Text(),36 "In stock" to DatabaseCreateProperties.Checkbox(),37 "Food group" to DatabaseCreateProperties.Select(38 select = SelectObject(39 options = listOf(40 SelectOptionsObject(41 name = "Vegetable",42 color = Color.GREEN,43 ),44 SelectOptionsObject(45 name = "Fruit",46 color = Color.RED,47 ),48 SelectOptionsObject(49 name = "Protein",50 color = Color.YELLOW,51 )52 )53 )54 ),55 "Price" to DatabaseCreateProperties.Number(56 number = NumberObject(57 format = "dollar",58 )59 ),60 "Last ordered" to DatabaseCreateProperties.Date(),61 "Store availability" to DatabaseCreateProperties.MultiSelect(62 multiSelect = SelectObject(63 options = listOf(64 SelectOptionsObject(65 name = "Duc Loi Market",66 color = Color.BLUE,67 ),68 SelectOptionsObject(69 name = "Rainbow Grocery",70 color = Color.GRAY,71 ),72 SelectOptionsObject(73 name = "Nijiya Market",74 color = Color.PURPLE,75 ),76 SelectOptionsObject(77 name = "Gus'\''s Community Market",78 color = Color.YELLOW,79 ),80 )81 )82 ),83 "+1" to DatabaseCreateProperties.People(),84 "Photo" to DatabaseCreateProperties.Files()85 )86 )87 )88 }89 result shouldNotBe null90 result is DatabaseResponse91 }92 @Test93 @DisplayName("[Databases] Update a database")94 fun updateDatabase() {95 val database = runBlocking {96 databases.create(97 DatabaseCreateRequest(98 parent = Parent.Page(99 pageId = Config.Database.pageId100 ),101 title = listOf(102 RichTextObject.Text(103 text = TextObject(104 content = "Grocery List",105 link = null106 ),107 )108 ),109 properties = mapOf(110 "Name" to DatabaseCreateProperties.Title(),111 "Description" to DatabaseCreateProperties.Text(),112 "In stock" to DatabaseCreateProperties.Checkbox(),113 "Food group" to DatabaseCreateProperties.Select(114 select = SelectObject(115 options = listOf(116 SelectOptionsObject(117 name = "Vegetable",118 color = Color.GREEN,119 ),120 SelectOptionsObject(121 name = "Fruit",122 color = Color.RED,123 ),124 SelectOptionsObject(125 name = "Protein",126 color = Color.YELLOW,127 )128 )129 )130 ),131 "Price" to DatabaseCreateProperties.Number(132 number = NumberObject(133 format = "dollar",134 )135 ),136 "Last ordered" to DatabaseCreateProperties.Date(),137 "Store availability" to DatabaseCreateProperties.MultiSelect(138 multiSelect = SelectObject(139 options = listOf(140 SelectOptionsObject(141 name = "Duc Loi Market",142 color = Color.BLUE,143 ),144 SelectOptionsObject(145 name = "Rainbow Grocery",146 color = Color.GRAY,147 ),148 SelectOptionsObject(149 name = "Nijiya Market",150 color = Color.PURPLE,151 ),152 SelectOptionsObject(153 name = "Gus'\''s Community Market",154 color = Color.YELLOW,155 ),156 )157 )158 ),159 "+1" to DatabaseCreateProperties.People(),160 "Photo" to DatabaseCreateProperties.Files()161 )162 )163 )164 }165 database shouldNotBe null166 database is DatabaseResponse167 val result = runBlocking {168 databases.update(169 DatabaseUpdateRequest(170 databaseId = database!!.id,171 body = DatabaseUpdateBodyObject(172 title = listOf(173 RichTextObject.Text(174 text = TextObject(175 content = "Today's grocery list"176 )177 )178 ),179 properties = mapOf(180 "+1" to null,181 "Photo" to DatabaseUpdateBodyProperty.Url(),182 "Store availability" to DatabaseUpdateBodyProperty.MultiSelect(183 multiSelect = UpdateSelectObject(184 options = listOf(185 UpdateSelectOptionsObject(186 name = "Duc Loi Market"187 ),188 UpdateSelectOptionsObject(189 name = "Rainbow Grocery"190 ),191 UpdateSelectOptionsObject(192 name = "Gus's Community Market"193 ),194 UpdateSelectOptionsObject(195 name = "The Good Life Grocery",196 color = Color.ORANGE,197 ),198 )199 )200 )201 )202 )203 )204 )205 }206 result shouldNotBe null207 result is DatabaseResponse208 }209 @Test210 @DisplayName("[Databases] Retrieve a database")211 fun retrieveDatabase() {212 val result = runBlocking {213 databases.retrieve(DatabaseRetrieveRequest(Config.Database.databaseId))214 }215 result shouldNotBe null216 result is DatabaseResponse217 }218}...
CharacterRepositoryTest.kt
Source:CharacterRepositoryTest.kt
...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 = "",...
VarselbestillingQueriesTest.kt
Source:VarselbestillingQueriesTest.kt
1package no.nav.personbruker.dittnav.varselbestiller.varselbestilling2import io.kotest.matchers.collections.shouldBeEmpty3import io.kotest.matchers.shouldBe4import kotlinx.coroutines.runBlocking5import no.nav.personbruker.dittnav.varselbestiller.common.database.LocalPostgresDatabase6import org.junit.jupiter.api.AfterAll7import org.junit.jupiter.api.Test8class VarselbestillingQueriesTest {9 private val database = LocalPostgresDatabase.cleanDb()10 private val varselbestillingBeskjed: Varselbestilling = VarselbestillingObjectMother.createVarselbestillingWithBestillingsIdAndEventId(bestillingsId = "B-test-001", eventId = "001")11 private val varselbestillingOppgave: Varselbestilling = VarselbestillingObjectMother.createVarselbestillingWithBestillingsIdAndEventId(bestillingsId = "O-test-001", eventId = "001")12 init {13 createVarselbestillinger(listOf(varselbestillingBeskjed, varselbestillingOppgave))14 }15 private fun createVarselbestillinger(varselbestillinger: List<Varselbestilling>) {16 runBlocking {17 database.dbQuery {18 createVarselbestillinger(varselbestillinger)19 }20 }21 }22 @AfterAll23 fun tearDown() {24 runBlocking {25 database.dbQuery {26 deleteAllVarselbestilling()27 }28 }29 }30 @Test31 fun `Finner Varselbestillinger med bestillingsIds`() {32 runBlocking {33 val result = database.dbQuery { getVarselbestillingerForBestillingsIds(listOf(varselbestillingBeskjed.bestillingsId, varselbestillingOppgave.bestillingsId)) }34 result.size shouldBe 235 result shouldBe listOf(varselbestillingBeskjed, varselbestillingOppgave)36 }37 }38 @Test39 fun `Returnerer tom liste hvis Varselbestilling med bestillingsId ikke finnes`() {40 runBlocking {41 val result = database.dbQuery { getVarselbestillingerForBestillingsIds(listOf("idFinnesIkke")) }42 result.shouldBeEmpty()43 }44 }45 @Test46 fun `Finner Varselbestillinger med eventIds`() {47 runBlocking {48 val result = database.dbQuery { getVarselbestillingerForEventIds(listOf(varselbestillingBeskjed.eventId, varselbestillingOppgave.eventId)) }49 result.size shouldBe 250 result shouldBe listOf(varselbestillingBeskjed, varselbestillingOppgave)51 }52 }53 @Test54 fun `Returnerer tom liste hvis Varselbestilling med eventId ikke finnes`() {55 runBlocking {56 val result = database.dbQuery { getVarselbestillingerForEventIds(listOf("idFinnesIkke")) }57 result.shouldBeEmpty()58 }59 }60 @Test61 fun `Setter avbestilt for Varselbestilling`() {62 runBlocking {63 database.dbQuery {64 setVarselbestillingAvbestiltFlag(listOf(varselbestillingBeskjed.bestillingsId), true)65 val result = getVarselbestillingerForBestillingsIds(listOf(varselbestillingBeskjed.bestillingsId))66 result.first().bestillingsId shouldBe varselbestillingBeskjed.bestillingsId67 result.first().avbestilt shouldBe true68 }69 }70 }71 @Test72 fun `Persister ikke entitet dersom rad med samme bestillingsId finnes`() {73 runBlocking {74 database.dbQuery {75 val numberOfEntities = getAllVarselbestilling().size76 createVarselbestillinger(listOf(varselbestillingBeskjed, varselbestillingOppgave))77 getAllVarselbestilling().size shouldBe numberOfEntities78 }79 }80 }81 @Test82 fun `Skal haantere at prefererteKanaler er tom`() {83 val varselbestilling = VarselbestillingObjectMother.createVarselbestillingWithPrefererteKanaler(prefererteKanaler = emptyList())84 runBlocking {85 database.dbQuery { createVarselbestillinger(listOf(varselbestilling)) }86 val result = database.dbQuery { getVarselbestillingerForBestillingsIds(listOf(varselbestilling.bestillingsId)) }87 result.size shouldBe 188 result shouldBe listOf(varselbestilling)89 result[0].prefererteKanaler.shouldBeEmpty()90 }91 }92}...
SimplifiedRationalTest.kt
Source:SimplifiedRationalTest.kt
...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`() {...
BlocksTest.kt
Source:BlocksTest.kt
...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}...
runBlocking
Using AI Code Generation
1import io.kotest.common.runBlocking2import io.kotest.core.spec.style.FunSpec3import kotlinx.coroutines.delay4class MyTest : FunSpec({5test("some test") {6runBlocking {7delay(1000)8}9}10})11import kotlinx.coroutines.runBlocking12import io.kotest.core.spec.style.FunSpec13import kotlinx.coroutines.delay14class MyTest : FunSpec({15test("some test") {16runBlocking {17delay(1000)18}19}20})21import kotlinx.coroutines.runBlocking22import io.kotest.core.spec.style.FunSpec23import kotlinx.coroutines.delay24class MyTest : FunSpec({25test("some test") {26runBlocking {27delay(1000)28}29}30})31import kotlinx.coroutines.runBlocking32import io.kotest.core.spec.style.FunSpec33import kotlinx.coroutines.delay34class MyTest : FunSpec({35test("some test") {36runBlocking {37delay(1000)38}39}40})41import kotlinx.coroutines.runBlocking42import io.kotest.core.spec.style.FunSpec43import kotlinx.coroutines.delay44class MyTest : FunSpec({45test("some test") {46runBlocking {47delay(1000)48}49}50})51import kotlinx.coroutines.runBlocking52import io.kotest.core.spec.style.FunSpec53import kotlinx.coroutines.delay54class MyTest : FunSpec({55test("some test") {56runBlocking {57delay(1000)58}59}60})61import kotlinx.coroutines.runBlocking62import io.kotest.core.spec.style.FunSpec63import kotlinx.coroutines.delay64class MyTest : FunSpec({65test("some test") {66runBlocking {67delay(1000)68}69}70})71import kotlinx.coroutines.runBlocking72import io.kotest.core.spec.style.FunSpec73import kotlinx.coroutines.delay74class MyTest : FunSpec({75test("some test") {76runBlocking {77delay(1000)78}79}80})81import kotlinx.coroutines.runBlocking82import
runBlocking
Using AI Code Generation
1val result = runBlocking {2}3val result = coroutineScope {4}5coroutineScope {6}7runBlocking {8}9coroutineScope {10}11runBlocking {12}13coroutineScope {14}15runBlocking {16}17coroutineScope {18}19runBlocking {20}21coroutineScope {22}
runBlocking
Using AI Code Generation
1 runBlocking {2 println("Hello World!")3 }4 runBlockingTest {5 println("Hello World!")6 }7 runBlockingTest {8 println("Hello World!")9 }10 runBlockingTest {11 println("Hello World!")12 }13 runBlockingTest {14 println("Hello World!")15 }16 runBlockingTest {17 println("Hello World!")18 }19 runBlockingTest {20 println("Hello World!")21 }22 runBlockingTest {23 println("Hello World!")24 }
runBlocking
Using AI Code Generation
1runBlocking {2}3}4runBlocking {5}6}7runBlocking {8}9}
runBlocking
Using AI Code Generation
1class MyTest : StringSpec() {2 init {3 "test" {4 runBlocking {5 }6 }7 }8}9class MyTest : StringSpec() {10 init {11 "test" {12 runTest {13 }14 }15 }16}
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!!