Best Kotest code snippet using io.kotest.matchers.collections.empty.fail
ComputeInstanceSpec.kt
Source:ComputeInstanceSpec.kt
1package utils2import io.kotest.assertions.fail3import io.kotest.assertions.timing.eventually4import io.kotest.core.spec.style.WordSpec5import io.kotest.matchers.be6import io.kotest.matchers.collections.shouldExist7import io.kotest.matchers.or8import io.kotest.matchers.should9import io.kotest.matchers.shouldBe10import io.kotest.matchers.string.shouldEndWith11import io.kotest.matchers.string.shouldInclude12import io.kotest.matchers.string.shouldNotBeBlank13import kotlinx.coroutines.FlowPreview14import kotlinx.coroutines.async15import kotlinx.coroutines.runBlocking16import kotlinx.serialization.ExperimentalSerializationApi17import utils.Compute.Instance18import kotlin.time.ExperimentalTime19import kotlin.time.minutes20import kotlin.time.seconds21// todo: afterTest Instance.delete22@ExperimentalSerializationApi23@FlowPreview24@ExperimentalTime25class ComputeInstanceSpec : WordSpec({26 val projectId = System.getenv("PROJECT_ID") ?: fail("Must set PROJECT_ID env var")27 val regionId = System.getenv("REGION_ID") ?: fail("Must set REGION_ID env var")28 val dbPass = System.getenv("DB_PASS") ?: fail("Most set DB_PASS env var")29 val dbInstance = System.getenv("DB_INSTANCE") ?: fail("Most set DB_INSTANCE env var")30 val maybeServiceAccount = System.getenv("SERVICE_ACCOUNT")31 val accessToken = Auth.accessTokenFromGcloud(maybeServiceAccount)32 val name = Instance.randomName()33 val zone = "us-central1-a"34 val machineType = "e2-medium"35 val defaultImage = "docker.io/hello-world"36 val testImage = "gcr.io/$projectId/one-off-cloud-run-test"37 val instance1 = Instance(projectId, zone, machineType, defaultImage, name, null, emptyList(), emptyMap(), false)38 val instance2 = instance1.copy(39 name = ""40 )41 val instance3 = instance1.copy(42 name = Instance.randomName(),43 serviceAccountName = maybeServiceAccount44 )45 val instance4 = instance1.copy(46 name = Instance.randomName(),47 containerImage = testImage,48 containerEnvs = mapOf("NAME" to "world"),49 containerEntrypoint = "/bin/sh",50 containerArgs = listOf("-c", "echo \"hello, \$NAME\"")51 )52 val instance5 = instance1.copy(53 name = Instance.randomName(),54 shutdownOnComplete = true55 )56 val instance6 = instance1.copy(57 name = Instance.randomName(),58 containerImage = testImage,59 containerEntrypoint = "psql",60 containerEnvs = mapOf("PGPASSWORD" to dbPass),61 containerArgs = listOf("-h", "/cloudsql/$projectId:$regionId:$dbInstance", "-U", "postgres", "-c", "SELECT 1"),62 instanceConnectionName = "$projectId:$regionId:$dbInstance"63 )64 "instance name" should {65 "not start with a number" {66 instance1.copy(name = "0").validName shouldBe "x-0"67 }68 "not be empty" {69 instance1.copy(name = null).validName.shouldNotBeBlank()70 }71 "fix invalid names" {72 instance1.copy(name = "a/b").validName shouldBe "a-b"73 }74 }75 "an instance" should {76 "be creatable" {77 val operation = Instance.create(instance1, maybeServiceAccount)78 operation.getOrThrow() shouldEndWith "RUNNING"79 }80 "be creatable with an invalid name" {81 val operation = Instance.create(instance2, maybeServiceAccount)82 operation.getOrThrow() shouldEndWith "RUNNING"83 }84 "be describable" {85 val operation = Instance.describe(instance1, maybeServiceAccount)86 operation.getOrThrow().status shouldBe "RUNNING"87 }88 "fail when trying to describe an non-existent instance" {89 val operation = Instance.describe(instance1.copy(name = Instance.randomName()), maybeServiceAccount)90 operation.isFailure shouldBe true91 }92 "be updatable" {93 val operation = Instance.update(instance1, maybeServiceAccount)94 operation.getOrThrow() shouldEndWith "done."95 }96 "be startable" {97 val operation = Instance.start(instance1, maybeServiceAccount)98 operation.getOrThrow() shouldInclude "Updated"99 }100 "be creatable with a custom service account" {101 val operation = Instance.create(instance3, maybeServiceAccount)102 operation.getOrThrow() shouldEndWith "RUNNING"...
KesTestSetupTest.kt
Source:KesTestSetupTest.kt
1package no.ks.kes.test2import io.kotest.assertions.asClue3import io.kotest.assertions.fail4import io.kotest.assertions.failure5import io.kotest.assertions.timing.eventually6import io.kotest.core.spec.style.FunSpec7import io.kotest.matchers.collections.shouldContain8import io.kotest.matchers.collections.shouldHaveSize9import io.kotest.matchers.shouldBe10import io.kotest.matchers.shouldNotBe11import io.kotest.matchers.types.shouldBeSameInstanceAs12import io.kotest.property.Arb13import io.kotest.property.arbitrary.UUIDVersion14import io.kotest.property.arbitrary.uuid15import io.kotest.property.checkAll16import no.ks.kes.lib.Projections17import no.ks.kes.lib.Sagas18import no.ks.kes.serdes.jackson.JacksonCmdSerdes19import no.ks.kes.serdes.jackson.JacksonEventSerdes20import no.ks.kes.test.example.*21import java.util.*22import kotlin.time.DurationUnit23import kotlin.time.ExperimentalTime24import kotlin.time.toDuration25@ExperimentalTime26class KesTestSetupTest : FunSpec({27 test("Creates subscriberFactory") {28 withKes(eventSerdes = JacksonEventSerdes(emptySet()), cmdSerdes = JacksonCmdSerdes(emptySet())) {29 kesTestSetup -> kesTestSetup.subscriberFactory shouldNotBe null30 }31 }32 test("Creates aggregateRepository") {33 withKes(eventSerdes = JacksonEventSerdes(emptySet()), cmdSerdes = JacksonCmdSerdes(emptySet())) {34 kesTestSetup -> kesTestSetup.aggregateRepository shouldNotBe null35 }36 }37 test("Exposes eventSerdes") {38 val eventSerdes = JacksonEventSerdes(emptySet())39 withKes(eventSerdes = eventSerdes, cmdSerdes = JacksonCmdSerdes(emptySet())) {40 kesTestSetup -> kesTestSetup.eventSerdes shouldBeSameInstanceAs eventSerdes41 }42 }43 test("Exposes cmdSerdes") {44 val cmdSerdes = JacksonCmdSerdes(emptySet())45 withKes(eventSerdes = JacksonEventSerdes(emptySet()), cmdSerdes = cmdSerdes) {46 kesTestSetup -> kesTestSetup.cmdSerdes shouldBeSameInstanceAs cmdSerdes47 }48 }49 test("Projections using test framework") {50 val enginesProjection = EnginesProjection()51 withKes(eventSerdes = Events.serdes, cmdSerdes = Cmds.serdes) {52 Projections.initialize(53 eventSubscriberFactory = it.subscriberFactory,54 subscriber = testCase.displayName,55 projectionRepository = it.projectionRepository,56 projections = setOf(enginesProjection)57 )58 val cmdHandler = EngineCmdHandler(repository = it.aggregateRepository)59 val aggregateId = UUID.randomUUID()60 cmdHandler.handle(Cmds.Create(aggregateId))61 eventually(5.toDuration(DurationUnit.SECONDS)) {62 enginesProjection.all shouldContain aggregateId63 }64 }65 }66 test("Project a lot of events") {67 val enginesProjection = EnginesProjection()68 withKes(eventSerdes = Events.serdes, cmdSerdes = Cmds.serdes) { kes ->69 Projections.initialize(70 eventSubscriberFactory = kes.subscriberFactory,71 subscriber = testCase.displayName,72 projectionRepository = kes.projectionRepository,73 projections = setOf(enginesProjection)74 )75 val cmdHandler = EngineCmdHandler(repository = kes.aggregateRepository)76 val aggregatesToCreate = 10_00077 checkAll(iterations = aggregatesToCreate, Arb.uuid(UUIDVersion.V4, false)) { aggregationId ->78 cmdHandler.handle(Cmds.Create(aggregationId))79 }80 eventually(5.toDuration(DurationUnit.SECONDS)) {81 enginesProjection.all shouldHaveSize aggregatesToCreate82 kes.eventStream.eventCount() shouldBe aggregatesToCreate83 }84 }85 }86 test("Sagas using test framework") {87 withKes(eventSerdes = Events.serdes, cmdSerdes = Cmds.serdes) { kes ->88 val cmdHandler = EngineCmdHandler(repository = kes.aggregateRepository)89 val commandQueue = kes.createCommandQueue(setOf(cmdHandler))90 val sagaRepository = kes.createSagaRepository(commandQueue)91 Sagas.initialize(eventSubscriberFactory = kes.subscriberFactory,92 sagaRepository = sagaRepository,93 sagas = setOf(EngineSaga),94 commandQueue = commandQueue,95 pollInterval = 1096 ) {97 e -> failure("Failed to process event for saga", e)98 }99 val aggregateId = UUID.randomUUID()100 cmdHandler.handle(Cmds.Create(aggregateId)).asClue {101 it.id shouldBe aggregateId102 }103 eventually(10.toDuration(DurationUnit.SECONDS)) {104 sagaRepository.getSagaState(aggregateId, SAGA_SERILIZATION_ID, EngineSagaState::class)?.asClue {105 it.stoppedBySaga shouldBe true106 } ?: fail("EngineSaga did not change state of aggregate to be stopped")107 }108 }109 }110})...
InMemoryHopRepositoryTest.kt
Source:InMemoryHopRepositoryTest.kt
...5import domain.quantities.PercentRange6import domain.quantities.QuantityRange7import fixtures.sampleHop8import io.kotest.assertions.assertSoftly9import io.kotest.assertions.fail10import io.kotest.core.spec.style.ShouldSpec11import io.kotest.matchers.collections.shouldContainExactlyInAnyOrder12import io.kotest.matchers.maps.shouldHaveSize13import io.kotest.matchers.nulls.shouldNotBeNull14import io.kotest.matchers.shouldBe15import io.kotest.matchers.string.shouldNotBeBlank16class InMemoryHopRepositoryTest : ShouldSpec({17 val repoUnderTest = InMemoryHopRepository()18 beforeEach {19 repoUnderTest.clear()20 }21 should("find hop by name") {22 // Givent23 repoUnderTest.save(sampleHop)24 repoUnderTest.save(sampleHop.copy(name = "Cascade", similarTo = listOf("Citra")))25 repoUnderTest.save(sampleHop.copy(name = "Chinook", similarTo = listOf("Cascade", "Citra", "Chinook")))26 // When & Then27 repoUnderTest.findByName("Citra").shouldNotBeNull().apply {28 assertSoftly {29 name shouldBe "Citra"30 country.shouldContainExactlyInAnyOrder(Country.USA)31 alpha shouldBe PercentRange(10.0, 12.0)32 beta shouldBe PercentRange(3.5, 4.5)33 coH shouldBe PercentRange(22.0, 24.0)34 type.shouldContainExactlyInAnyOrder(HopType.AROMATIC, HopType.BITTERING)35 profile.shouldNotBeBlank()36 similarTo.shouldContainExactlyInAnyOrder("Cascade", "Centennial", "Chinook")37 }38 }39 }40 should("get all") {41 // Given42 repoUnderTest.save(sampleHop)43 repoUnderTest.save(sampleHop.copy(name = "Cascade", similarTo = listOf("Citra")))44 repoUnderTest.save(sampleHop.copy(name = "Chinook", similarTo = listOf("Cascade", "Citra", "Chinook")))45 // When46 val res = repoUnderTest.getAll()47 // Then48 res shouldHaveSize 349 res["CASCADE"] shouldBe Hop(50 name = "Cascade",51 country = listOf(Country.USA),52 alpha = PercentRange(from = 10.0, to = 12.0),53 beta = PercentRange(from = 3.5, to = 4.5),54 coH = PercentRange(from = 22.0, to = 24.0),55 oil = QuantityRange(from = 1.5, to = 3.0),56 type = listOf(HopType.BITTERING, HopType.AROMATIC),57 profile = "Agrumes, pamplemousse, fruit de la passion",58 similarTo = listOf("Citra"),59 )60 }61 should("find all similar hops") {62 // Given63 repoUnderTest.save(sampleHop)64 repoUnderTest.save(sampleHop.copy(name = "Cascade", similarTo = listOf("Citra")))65 repoUnderTest.save(sampleHop.copy(name = "Centennial", similarTo = emptyList()))66 repoUnderTest.save(sampleHop.copy(name = "Chinook", similarTo = listOf("Cascade", "Citra", "Centennial")))67 val rootHop = repoUnderTest.findByName("Chinook") ?: fail("initialization error")68 // When & Then69 repoUnderTest.findSimilar(rootHop).shouldContainExactlyInAnyOrder(70 repoUnderTest.findByName("Cascade"),71 repoUnderTest.findByName("Centennial"),72 repoUnderTest.findByName("Citra"),73 )74 }75})...
UnitsTest.kt
Source:UnitsTest.kt
...47 }48 "result in an empty list with factor 0" {49 MainBattleTank * 0 should io.kotest.matchers.collections.beEmpty()50 }51 "fail with a negative factor" {52 shouldThrowAny {53 APC * -354 }55 }56 }57 }58}...
ParserTest.kt
Source:ParserTest.kt
1package xyz.noahsc.hibanana.parser2import io.kotest.assertions.withClue3import io.kotest.matchers.collections.shouldBeEmpty4import io.kotest.matchers.collections.shouldHaveSize5import io.kotest.matchers.ints.shouldBeExactly6import io.kotest.matchers.shouldBe7import io.kotest.matchers.types.shouldBeInstanceOf8import org.junit.jupiter.api.Test;9import xyz.noahsc.hibanana.lexer.Lexer10import xyz.noahsc.hibanana.ast.*11class ParserTest {12 @Test13 fun testVarStatement() {14 val input = """15 var x: int = 516 var y: int = 1017 """.trimIndent()18 val parser = Parser(Lexer(input))19 val program = parser.parse()20 parser.errors.shouldBeEmpty()21 program.statements.shouldHaveSize(2)22 val tests = arrayOf("x", "y")23 program.statements.withIndex().forEach { 24 checkVar(it.value, tests[it.index])25 }26 }27 @Test28 fun testVarStatementFail() {29 val input = """30 var x: int = 531 var y int = 1032 """.trimIndent()33 val parser = Parser(Lexer(input))34 parser.parse()35 parser.errors.shouldHaveSize(1)36 }37 private fun checkVar(statement: Statement, name: String) {38 statement.shouldBeInstanceOf<VarStatement>()39 name shouldBe statement.name.value40 name shouldBe statement.name.value41 }42 @Test43 fun testReturnStatement() {44 val input = """45 return 546 return 12347 return value48 """.trimIndent()49 val program = Parser(Lexer(input)).parse()50 program.statements.size shouldBeExactly 351 program.statements.forEach {52 withClue("each statement must be a return statement") {53 it.shouldBeInstanceOf<ReturnStatement>()54 }55 }56 }57}...
CloudRunSpec.kt
Source:CloudRunSpec.kt
1package utils2import io.kotest.assertions.fail3import io.kotest.core.spec.style.StringSpec4import io.kotest.matchers.collections.shouldExist5import io.kotest.matchers.collections.shouldNotBeEmpty6import io.kotest.matchers.shouldBe7class CloudRunSpec : StringSpec({8 val projectId = System.getenv("PROJECT_ID") ?: fail("Must set PROJECT_ID env var")9 val regionId = System.getenv("REGION_ID") ?: fail("Must set REGION_ID env var")10 val maybeServiceAccount = System.getenv("SERVICE_ACCOUNT")11 "regions" {12 CloudRun.regions(projectId, maybeServiceAccount).getOrThrow() shouldExist { it.locationId == regionId }13 }14 "services" {15 CloudRun.services(projectId, regionId, maybeServiceAccount).getOrThrow().shouldNotBeEmpty()16 }17 "revision" {18 val serviceName = "one-off-cloud-run-test"19 val service = CloudRun.services(projectId, regionId, maybeServiceAccount).getOrThrow().find { it.metadata.name == serviceName }20 if (service == null) {21 fail("Could not find service $serviceName")22 } else {23 val latestRevision = service.status.latest24 if (latestRevision == null) {25 fail("Could not get latest revision for $serviceName")26 } else {27 val revision = CloudRun.revision(projectId, regionId, latestRevision.revisionName, maybeServiceAccount).getOrThrow()28 revision.metadata.annotations.cloudSqlInstances shouldBe("$projectId:$regionId:one-off-cloud-run-test")29 }30 }31 }32})...
DirectoryTests.kt
Source:DirectoryTests.kt
...6import io.kotest.matchers.collections.shouldNotBeEmpty7import io.kotest.matchers.nulls.shouldNotBeNull8import java.io.File9class DirectoryTests : FunSpec({10 test("A directory called '$exists' should not fail the instantiation of a Directory class") {11 shouldNotThrowAny {12 Directory(exists)13 }14 }15 test("A directory called '$existsNot' should fail the instantiation of a Directory class") {16 shouldThrow<IllegalArgumentException> {17 Directory(existsNot)18 }19 }20 test("A directory called '$create' should be created when instantiating Directory(path, true)") {21 shouldNotThrowAny {22 Directory(create, true)23 }24 File(create).exists().shouldBeTrue()25 }26 test("A directory called '$existsNot' should not fail the instantiation Directory(path, require = false)") {27 shouldNotThrowAny {28 Directory(existsNot, require = false)29 }30 }31 test("A directory called '$exists' should contain some files obtainable via Directory(path).list()") {32 val files: Array<String>? = shouldNotThrowAny {33 Directory(exists).list()34 }35 files.shouldNotBeNull()36 files.shouldNotBeEmpty()37 }38})...
example-cont-01.kt
Source:example-cont-01.kt
...17 val x = Either.Right(1).bind()18 val y = Validated.Valid(2).bind()19 val z = Option(3).bind { "Option was empty" }20 x + y + z21 }.fold({ fail("Shift can never be the result") }, { it shouldBe 6 })22 cont<String, Int> {23 val x = Either.Right(1).bind()24 val y = Validated.Valid(2).bind()25 val z: Int = None.bind { "Option was empty" }26 x + y + z27 }.fold({ it shouldBe "Option was empty" }, { fail("Int can never be the result") })28}...
fail
Using AI Code Generation
1@DisplayName("Test for empty method of io.kotest.matchers.collections.empty class")2fun testEmpty() {3val list = listOf(1, 2, 3)4list shouldNotBe empty()5}6}
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!!