How to use short class of io.kotest.matchers.short package

Best Kotest code snippet using io.kotest.matchers.short.short

UrlDataProviderImplTest.kt

Source:UrlDataProviderImplTest.kt Github

copy

Full Screen

...27    inner class Save {28        @Test29        fun `Should convert before sending to repository and returning`() {30            // Given31            val shortUrl = "dummy-url"32            val longUrl = "long-url"33            val user = "user"34            val urlType = UrlType.RANDOM35            val request = Url(shortUrl, longUrl, user, urlType, expirationDate = null)36            val expectedRequest = UrlEntity(shortUrl, longUrl, user, urlType)37            every { repository.save(expectedRequest) } returns expectedRequest38            // When39            val result = provider.save(request)40            // Then41            verify(exactly = 1) { repository.save(expectedRequest) }42            result.shouldBeTypeOf<Url>()43        }44    }45    @Nested46    inner class UrlAlreadyExists {47        @Test48        fun `Should return true if exists by ID`() {49            // Given50            val request = "dummy-url"51            every { repository.existsById(request) } returns true52            // When53            val result = provider.urlAlreadyExists(request)54            // Then55            verify(exactly = 1) { repository.existsById(request) }56            result.shouldBeTrue()57        }58        @Test59        fun `Should return false if does not exist by ID`() {60            // Given61            val request = "dummy-url"62            every { repository.existsById(request) } returns false63            // When64            val result = provider.urlAlreadyExists(request)65            // Then66            verify(exactly = 1) { repository.existsById(request) }67            result.shouldBeFalse()68        }69    }70    @Nested71    inner class Delete {72        @Test73        fun `Should convert before sending to repository and return Unit`() {74            // Given75            val shortUrl = "dummy-url"76            val longUrl = "long-url"77            val user = "user"78            val urlType = UrlType.RANDOM79            val request = Url(shortUrl, longUrl, user, urlType, expirationDate = null)80            val expectedRequest = UrlEntity(shortUrl, longUrl, user, urlType)81            justRun { repository.delete(expectedRequest) }82            // When83            val result = provider.delete(request)84            // Then85            verify(exactly = 1) { repository.delete(expectedRequest) }86            result.shouldBeTypeOf<Unit>()87        }88    }89    @Nested90    inner class GetByShortUrl {91        @Test92        fun `Should convert and return if url exists`() {93            // Given94            val shortUrl = "dummy-url"95            val longUrl = "long-url"96            val user = "user"97            val urlType = UrlType.RANDOM98            val response = UrlEntity(shortUrl, longUrl, user, urlType)99            val expectedResponse = Url(shortUrl, longUrl, user, urlType, expirationDate = null)100            every { repository.findByShortUrl(shortUrl) } returns response101            // When102            val result = provider.getByShortUrl(shortUrl)103            // Then104            verify(exactly = 1) { repository.findByShortUrl(shortUrl) }105            result.shouldBe(expectedResponse)106        }107        @Test108        fun `Should return null if url does not exist`() {109            // Given110            val shortUrl = "dummy-url"111            every { repository.findByShortUrl(shortUrl) } returns null112            // When113            val result = provider.getByShortUrl(shortUrl)114            // Then115            verify(exactly = 1) { repository.findByShortUrl(shortUrl) }116            result.shouldBe(null)117        }118    }119    @Nested120    inner class GetByShortUrlAndUserIdentifier {121        @Test122        fun `Should return null if url and user exist`() {123            // Given124            val shortUrl = "dummy-url"125            val userIdentifier = "test"126            val urlEntity = UrlEntity("", "", "", UrlType.RANDOM, 1)127            every { repository.findByShortUrlAndUserIdentifier(shortUrl, userIdentifier) } returns urlEntity128            // When129            val result = provider.getByShortUrlAndUserIdentifier(shortUrl, userIdentifier)130            // Then131            verify(exactly = 1) { repository.findByShortUrlAndUserIdentifier(shortUrl, userIdentifier) }132            result.shouldNotBeNull()133        }134        @Test135        fun `Should return null if url and user does not exist`() {136            // Given137            val shortUrl = "dummy-url"138            val userIdentifier = "test"139            every { repository.findByShortUrlAndUserIdentifier(shortUrl, userIdentifier) } returns null140            // When141            val result = provider.getByShortUrlAndUserIdentifier(shortUrl, userIdentifier)142            // Then143            verify(exactly = 1) { repository.findByShortUrlAndUserIdentifier(shortUrl, userIdentifier) }144            result.shouldBe(null)145        }146        @Nested147        inner class GetAllUrlsByUserIdentifier {148            @Test149            fun `Should return null if user exist`() {150                // Given151                val userIdentifier = "test"152                val urlEntity = UrlEntity("", "", "", UrlType.RANDOM, 1)153                val list = listOf(urlEntity)154                every { repository.findAllByUserIdentifier(userIdentifier) } returns list155                // When156                val result = provider.getAllUrlsByUserIdentifier(userIdentifier)157                // Then...

Full Screen

Full Screen

AttemptTest.kt

Source:AttemptTest.kt Github

copy

Full Screen

1package com.domingoslatorre.teacherbot.teacherbotdiscord.modules.quiz2import com.domingoslatorre.teacherbot.teacherbotdiscord.modules.quiz.attempt.Attempt3import com.domingoslatorre.teacherbot.teacherbotdiscord.modules.quiz.question.ChoiceAnswer4import com.domingoslatorre.teacherbot.teacherbotdiscord.modules.quiz.question.MultipleChoiceQuestion5import com.domingoslatorre.teacherbot.teacherbotdiscord.modules.quiz.question.ShortAnswer6import com.domingoslatorre.teacherbot.teacherbotdiscord.modules.quiz.question.ShortQuestion7import com.domingoslatorre.teacherbot.teacherbotdiscord.modules.quiz.question.TrueFalseAnswer8import com.domingoslatorre.teacherbot.teacherbotdiscord.modules.quiz.question.TrueFalseQuestion9import io.kotest.core.spec.style.StringSpec10import io.kotest.matchers.booleans.shouldBeFalse11import io.kotest.matchers.booleans.shouldBeTrue12import io.kotest.matchers.collections.shouldHaveSize13import io.kotest.matchers.nulls.shouldBeNull14import io.kotest.matchers.nulls.shouldNotBeNull15import io.kotest.matchers.shouldBe16class AttemptTest : StringSpec({17    "Create a quiz attempt" {18        val member1 = MemberFactory.member1()19        val question1 = ShortQuestion(20            text = "One plus one equals to ____",21            answers = ShortAnswer(setOf("dois", "2", "two"), "Correct!", true)22        )23        val question2 = TrueFalseQuestion(24            text = "One plus one equals to two",25            answers = listOf(26                TrueFalseAnswer(true, "Correct!", true),27                TrueFalseAnswer(false, "False!", false)28            )29        )30        val question3 = MultipleChoiceQuestion(31            text = "Which city in Brazil is known as the Marvelous City?",32            answers = listOf(33                ChoiceAnswer("São Paulo", false),34                ChoiceAnswer("Curitiba", false),35                ChoiceAnswer("Rio de Janeiro", true),36                ChoiceAnswer("Santos", false),37                ChoiceAnswer("Guarulhos", false)38            )39        )40        val quiz1 = Quiz(title = "Quiz 1", questions = listOf(question1, question2, question3))41        val attempt = Attempt(quiz = quiz1, member = member1)42        with(attempt) {43            id.shouldNotBeNull()44            start.shouldNotBeNull()45            end.shouldBeNull()46            currentQuestion shouldBe question147            quiz shouldBe quiz148            member shouldBe member149            attemptAnswers shouldHaveSize 050        }51    }52    "Answer a quiz attempt" {53        val member1 = MemberFactory.member1()54        val question1 = ShortQuestion(55            text = "One plus one equals to ____",56            answers = ShortAnswer(setOf("dois", "2", "two"), "Correct!", true)57        )58        val question2 = TrueFalseQuestion(59            text = "One plus one equals to two",60            answers = listOf(61                TrueFalseAnswer(true, "Correct!", true),62                TrueFalseAnswer(false, "False!", false)63            )64        )65        val question3 = MultipleChoiceQuestion(66            text = "Which city in Brazil is known as the Marvelous City?",67            answers = listOf(68                ChoiceAnswer("São Paulo", false),69                ChoiceAnswer("Curitiba", false),70                ChoiceAnswer("Rio de Janeiro", true),71                ChoiceAnswer("Santos", false),72                ChoiceAnswer("Guarulhos", false)73            )74        )75        val quiz1 = Quiz(title = "Quiz 1", questions = listOf(question1, question2, question3))76        val attempt = Attempt(quiz = quiz1, member = member1)77        attempt.answer("dois")78        attempt.attemptAnswers shouldHaveSize 179        attempt.currentQuestion shouldBe question280        attempt.isOpen().shouldBeTrue()81        attempt.answer("true")82        attempt.attemptAnswers shouldHaveSize 283        attempt.currentQuestion shouldBe question384        attempt.isOpen().shouldBeTrue()85        attempt.answer("3")86        attempt.attemptAnswers shouldHaveSize 387        attempt.currentQuestion shouldBe null88        attempt.isOpen().shouldBeFalse()89        attempt.numberCorrectAnswers() shouldBe 390        attempt.numberIncorrectAnswers() shouldBe 091    }92    "Answer a quiz attempt with a invalid value" {93        val member1 = MemberFactory.member1()94        val question1 = ShortQuestion(95            text = "One plus one equals to ____",96            answers = ShortAnswer(setOf("dois", "2", "two"), "Correct!", true)97        )98        val question2 = TrueFalseQuestion(99            text = "One plus one equals to two",100            answers = listOf(101                TrueFalseAnswer(true, "Correct!", true),102                TrueFalseAnswer(false, "False!", false)103            )104        )105        val question3 = MultipleChoiceQuestion(106            text = "Which city in Brazil is known as the Marvelous City?",107            answers = listOf(108                ChoiceAnswer("São Paulo", false),109                ChoiceAnswer("Curitiba", false),110                ChoiceAnswer("Rio de Janeiro", true),111                ChoiceAnswer("Santos", false),112                ChoiceAnswer("Guarulhos", false)113            )114        )115        val quiz1 = Quiz(title = "Quiz 1", questions = listOf(question1, question2, question3))116        val attempt = Attempt(quiz = quiz1, member = member1)117        attempt.answer(" ")118        attempt.attemptAnswers shouldHaveSize 0119        attempt.currentQuestion shouldBe question1120        attempt.isOpen().shouldBeTrue()121        attempt.answer("true")122        attempt.attemptAnswers shouldHaveSize 2123        attempt.currentQuestion shouldBe question3124        attempt.isOpen().shouldBeTrue()125        attempt.answer("3")126        attempt.attemptAnswers shouldHaveSize 3127        attempt.currentQuestion shouldBe null128        attempt.isOpen().shouldBeFalse()129        attempt.numberCorrectAnswers() shouldBe 3130        attempt.numberIncorrectAnswers() shouldBe 0131    }132})...

Full Screen

Full Screen

RoomsKtTest.kt

Source:RoomsKtTest.kt Github

copy

Full Screen

1package com.tylerkindy.betrayal.db2import com.tylerkindy.betrayal.Direction3import io.kotest.assertions.throwables.shouldThrow4import io.kotest.core.spec.style.DescribeSpec5import io.kotest.matchers.collections.shouldBeEmpty6import io.kotest.matchers.collections.shouldContainExactlyInAnyOrder7import io.kotest.matchers.should8import io.kotest.matchers.shouldBe9import io.kotest.property.Arb10import io.kotest.property.Exhaustive11import io.kotest.property.arbitrary.ShortShrinker12import io.kotest.property.arbitrary.arbitrary13import io.kotest.property.arbitrary.enum14import io.kotest.property.arbitrary.set15import io.kotest.property.checkAll16import io.kotest.property.exhaustive.ints17import io.kotest.property.exhaustive.map18import io.kotest.property.forAll19import org.jetbrains.exposed.sql.insert20import org.jetbrains.exposed.sql.select21import org.jetbrains.exposed.sql.selectAll22import org.jetbrains.exposed.sql.transactions.transaction23import kotlin.random.nextInt24val directionSets = Arb.set(Arb.enum<Direction>(), 0..Direction.values().size)25val rotations = Exhaustive.ints(0..3).map { it.toShort() }26val invalidRotationValues = (Short.MIN_VALUE..Short.MAX_VALUE) - (0..3)27val invalidRotations = arbitrary(listOf(Short.MIN_VALUE, -1, 4, Short.MAX_VALUE), ShortShrinker) {28    it.random.nextInt(invalidRotationValues.indices).let { i -> invalidRotationValues[i] }.toShort()29}30class RoomsKtTest : DescribeSpec({31    useDatabase()32    describe("returnRoomToStack") {33        it("returns to empty stack") {34            transaction {35                val gameId = "ABCDEF"36                val stackId =37                    RoomStacks.insert {38                        it[this.gameId] = gameId39                        it[curIndex] = null40                        it[flipped] = false41                    } get RoomStacks.id42                val roomId =43                    Rooms.insert {44                        it[this.gameId] = gameId45                        it[roomDefId] = 1446                        it[gridX] = 047                        it[gridY] = 048                        it[rotation] = 049                    } get Rooms.id50                returnRoomToStack(gameId, roomId)51                Rooms.selectAll().shouldBeEmpty()52                val stackRows = RoomStacks.select { RoomStacks.id eq stackId }53                stackRows.count().shouldBe(1)54                stackRows.first().should {55                    it[RoomStacks.curIndex].shouldBe(0)56                }57                RoomStackContents.select { RoomStackContents.stackId eq stackId }58                    .first().should {59                        it[RoomStackContents.index].shouldBe(0)60                        it[RoomStackContents.roomDefId].shouldBe(14)61                    }62            }63        }64        it("returns to non-empty stack") {65            transaction {66                val gameId = "ABCDEF"67                val stackId = RoomStacks.insert {68                    it[this.gameId] = gameId69                    it[curIndex] = 1770                    it[flipped] = false71                } get RoomStacks.id72                RoomStackContents.insert {73                    it[this.stackId] = stackId74                    it[index] = 2575                    it[roomDefId] = 976                }77                RoomStackContents.insert {78                    it[this.stackId] = stackId79                    it[index] = 1780                    it[roomDefId] = 1381                }82                RoomStackContents.insert {83                    it[this.stackId] = stackId84                    it[index] = 385                    it[roomDefId] = 2386                }87                val roomId = Rooms.insert {88                    it[this.gameId] = gameId89                    it[roomDefId] = 1490                    it[gridX] = 091                    it[gridY] = 092                    it[rotation] = 093                } get Rooms.id94                returnRoomToStack(gameId, roomId)95                Rooms.selectAll().shouldBeEmpty()96                RoomStackContents.selectAll()97                    .map { it[RoomStackContents.index] }98                    .shouldContainExactlyInAnyOrder(0, 1, 2, 3)99            }100        }101    }102    describe("rotateDoors") {103        it("maintains number of directions") {104            forAll(directionSets, rotations) { dirs, rotation ->105                rotateDoors(dirs, rotation).size == dirs.size106            }107        }108        it("throws for invalid rotations") {109            checkAll(directionSets, invalidRotations) { dirs, rotation ->110                shouldThrow<IllegalArgumentException> { rotateDoors(dirs, rotation) }111            }112        }113        it("returns the same directions with no rotation") {114            forAll(directionSets) { dirs ->115                rotateDoors(dirs, 0) == dirs116            }117        }118        it("always returns all directions") {119            val allDirections = Direction.values().toSet()120            forAll(rotations) { rotation ->121                rotateDoors(allDirections, rotation) == allDirections122            }123        }124        it("rotates doors") {125            rotateDoors(126                setOf(Direction.NORTH, Direction.WEST),127                3128            ) shouldBe setOf(Direction.NORTH, Direction.EAST)129        }130    }131})...

Full Screen

Full Screen

RandomShortUrlUseCaseTest.kt

Source:RandomShortUrlUseCaseTest.kt Github

copy

Full Screen

1package com.falcon.falcon.core.usecase.url.shortenurl2import com.falcon.falcon.core.entity.Url3import com.falcon.falcon.core.entity.User4import com.falcon.falcon.core.enumeration.UrlType5import com.falcon.falcon.core.enumeration.UserType6import com.falcon.falcon.core.exception.ShortenUrlLimitExceededException7import com.falcon.falcon.dataprovider.persistence.url.UrlDataProvider8import io.kotest.assertions.throwables.shouldThrowExactly9import io.kotest.matchers.ints.shouldBeExactly10import io.kotest.matchers.shouldBe11import io.kotest.matchers.types.shouldBeTypeOf12import io.mockk.clearAllMocks13import io.mockk.every14import io.mockk.mockk15import io.mockk.spyk16import io.mockk.verify17import org.junit.jupiter.api.BeforeEach18import org.junit.jupiter.api.Nested19import org.junit.jupiter.api.Test20import org.junit.jupiter.api.TestInstance21@TestInstance(TestInstance.Lifecycle.PER_CLASS)22class RandomShortUrlUseCaseTest {23    private val urlDataProvider: UrlDataProvider = mockk()24    private val useCase = spyk(RandomShortUrlUseCase(urlDataProvider, 1))25    @BeforeEach26    fun init() {27        clearAllMocks()28    }29    @Nested30    inner class Shorten {31        @Test32        fun `Should save the random URL successfully`() {33            // Given34            val generatedShortUrl = "abcdefg"35            val request = Url(longUrl = "dummy-long-url", type = UrlType.RANDOM)36            val user = User("dummy-user", "dummy-password")37            val expectedRequest = Url(38                longUrl = "dummy-long-url",39                shortUrl = generatedShortUrl,40                userIdentifier = user.username,41                expirationDate = null42            )43            every { urlDataProvider.getAllUrlsByUserIdentifier(user.username) } returns emptyList()44            every { useCase.getUrlCountByUser(user) } returns (user.type.urlLimit - 1).toInt()45            every { urlDataProvider.save(expectedRequest) } returns expectedRequest46            every { useCase.generateUniqueShortUrl() } returns generatedShortUrl47            // When48            val result = useCase.execute(request, user)49            // Then50            verify(exactly = 1) {51                useCase.generateUniqueShortUrl()52                urlDataProvider.save(expectedRequest)53            }54            result.shouldBe(expectedRequest)55        }56        @Test57        fun `If random URL already exists, should regenerate and try to save again`() {58            // Given59            val generatedShortUrl = "abcdefg"60            val request = Url(longUrl = "dummy-long-url")61            val user = User("dummy-user", "dummy-password")62            val expectedRequest = Url(63                longUrl = "dummy-long-url",64                shortUrl = generatedShortUrl,65                type = UrlType.RANDOM,66                userIdentifier = user.username,67                expirationDate = null68            )69            every { urlDataProvider.getAllUrlsByUserIdentifier(user.username) } returns emptyList()70            every { useCase.generateUniqueShortUrl() } returns generatedShortUrl71            every { useCase.getUrlCountByUser(user) } returns (user.type.urlLimit - 1).toInt()72            every { urlDataProvider.urlAlreadyExists(generatedShortUrl) } returns true andThen false73            every { urlDataProvider.save(expectedRequest) } returns expectedRequest74            // When75            val result = useCase.execute(request, user)76            // Then77            verify(exactly = 1) {78                useCase.generateUniqueShortUrl()...

Full Screen

Full Screen

ResolversTest.kt

Source:ResolversTest.kt Github

copy

Full Screen

1package org.tesserakt.diskordin.commands.resolver2import arrow.core.Either3import arrow.core.sequenceEither4import io.kotest.assertions.arrow.core.shouldBeLeft5import io.kotest.assertions.arrow.core.shouldBeRight6import io.kotest.core.spec.style.FunSpec7import io.kotest.matchers.collections.shouldContainInOrder8import io.kotest.matchers.should9import io.kotest.matchers.shouldBe10import io.kotest.matchers.types.beOfType11import io.kotest.property.Arb12import io.kotest.property.Gen13import io.kotest.property.PropertyTesting14import io.kotest.property.RandomSource15import io.kotest.property.arbitrary.string16import io.kotest.property.arbitrary.stringPattern17import io.kotest.property.exhaustive.exhaustive18import org.tesserakt.diskordin.commands.CommandContext19import org.tesserakt.diskordin.core.data.DeferredIdentified20import org.tesserakt.diskordin.core.data.EagerIdentified21import org.tesserakt.diskordin.core.entity.IMessage22import org.tesserakt.diskordin.core.entity.IMessageChannel23import org.tesserakt.diskordin.core.entity.IUser24import java.math.BigDecimal25import java.math.BigInteger26class ResolversTest : FunSpec() {27    private val testCount = PropertyTesting.defaultIterationCount.coerceAtMost(256)28    private suspend fun <T : Any, C : CommandContext> test(29        resolver: TypeResolver<T, C>,30        badInput: Gen<String>,31        goodInput: Gen<String>,32        ctx: C33    ): Pair<Either<ParseError, List<T>>, Either<ParseError, List<T>>> {34        val badResult = badInput.generate(RandomSource.default())35            .take(testCount).toList().map { resolver.parse(ctx, it.value) }.sequenceEither()36        val goodResult = goodInput.generate(RandomSource.default())37            .take(testCount).toList().map { resolver.parse(ctx, it.value) }.sequenceEither()38        return badResult to goodResult39    }40    init {41        val fakeContext = object : CommandContext {42            override val message: EagerIdentified<IMessage>43                get() = error("Fake")44            override val author: EagerIdentified<IUser>45                get() = error("Fake")46            override val commandArgs: Array<String>47                get() = error("Fake")48            override val channel: DeferredIdentified<IMessageChannel>49                get() = error("Fake")50        }51        test("Boolean resolver") {52            val bad = Arb.string(0, 100)53            val good = listOf("true", "TRuE", "FalSe", "false").exhaustive()54            val (fail, success) = test(BooleanResolver(), bad, good, fakeContext)55            fail.shouldBeLeft() should beOfType<BooleanResolver.BooleanConversionError>()56            success.shouldBeRight() shouldContainInOrder listOf(true, true, false, false)57        }58        test("String resolver") {59            val bad = Arb.string(0..100)60            val good = Arb.string(0..100)61            val (fail, success) = test(StringResolver(), bad, good, fakeContext)62            fail.shouldBeRight()63            success.shouldBeRight()64        }65        test("Char resolver") {66            val bad = Arb.string(2..100)67            val good = Arb.stringPattern(".")68            val (fail, success) = test(CharResolver(), bad, good, fakeContext)69            fail.shouldBeLeft() shouldBe beOfType<CharResolver.LengthError>()70            success.shouldBeRight()71        }72        context("Number resolvers") {73            fun generateNumberValues(maxSize: Int) =74                Arb.stringPattern("-?\\d{1,$maxSize}")75            suspend fun <N : Number> generateAndTest(maxValue: N, resolver: TypeResolver<N, CommandContext>) {76                val length = BigDecimal(maxValue.toString()).toPlainString().length - 177                println("Next length is $length")78                val bad = Arb.string(0, length)79                val (fail, success) = test(resolver, bad, generateNumberValues(length), fakeContext)80                fail.shouldBeLeft()81                success.shouldBeRight()82            }83            test("Int") { generateAndTest(Int.MAX_VALUE, IntResolver()) }84            test("Long") { generateAndTest(Long.MAX_VALUE, LongResolver()) }85            test("Short") { generateAndTest(Short.MAX_VALUE, ShortResolver()) }86            test("Byte") { generateAndTest(Byte.MAX_VALUE, ByteResolver()) }87            test("Float") { generateAndTest(Float.MAX_VALUE, FloatResolver()) }88            test("Double") { generateAndTest(Double.MAX_VALUE, DoubleResolver()) }89            test("BigInteger") { generateAndTest(BigInteger.valueOf(10).pow(1024), BigIntegerResolver()) }90            test("BigDecimal") { generateAndTest(BigDecimal(10).pow(1024), BigDecimalResolver()) }91        }92    }93}...

Full Screen

Full Screen

ByteBufShortSmart.kt

Source:ByteBufShortSmart.kt Github

copy

Full Screen

...26private suspend fun doShortSmartRWTest(27    writer: ByteBuf.(Int) -> ByteBuf,28    reader: ByteBuf.() -> Short29) = checkAll(30    Arb.shortArray(collectionSizeArb, Arb.short(Smart.MIN_SHORT_VALUE.toShort(), Smart.MAX_SHORT_VALUE.toShort()))31) { testData ->32    val buf = ByteBufAllocator.DEFAULT.buffer(testData.size * Short.SIZE_BYTES)33    try {34        testData.forEach { expected -> buf.writer(expected.toInt()) }35        testData.forEach { expected ->36            val read = buf.reader()37            read shouldBe expected38        }39    } finally {40        buf.release()41    }42}43@ExperimentalUnsignedTypes44private suspend fun doUShortSmartRWTest(...

Full Screen

Full Screen

InMemoryMaltRepositoryTest.kt

Source:InMemoryMaltRepositoryTest.kt Github

copy

Full Screen

1package infrastructure2import domain.beertype.model.BeerType3import domain.malt.model.Malt4import domain.malt.model.MaltType5import domain.quantities.Percent6import fixtures.sampleMalt7import io.kotest.core.spec.style.ShouldSpec8import io.kotest.matchers.collections.shouldHaveSize9import io.kotest.matchers.maps.shouldHaveKeys10import io.kotest.matchers.maps.shouldHaveSize11import io.kotest.matchers.shouldBe12class InMemoryMaltRepositoryTest : ShouldSpec({13    val repoUnderTest = InMemoryMaltRepository()14    beforeEach {15        repoUnderTest.clear()16    }17    should("find malt by name") {18        // Given19        repoUnderTest.save(sampleMalt)20        repoUnderTest.save(21            sampleMalt.copy(22                name = "Munich II",23                type = MaltType.MUNICH,24                ebc = 25,25                bestFor = listOf(BeerType.DUBBEL, BeerType.BOCK),26            ),27        )28        repoUnderTest.save(29            sampleMalt.copy(30                name = "Marris Otter",31                type = MaltType.MARRIS_OTTER,32                ebc = 6,33                bestFor = listOf(BeerType.ALE, BeerType.PALE_ALE, BeerType.IPA, BeerType.PORTER, BeerType.STOUT),34            ),35        )36        // When & Then37        repoUnderTest.findByName("Munich II") shouldBe Malt(38            name = "Munich II",39            type = MaltType.MUNICH,40            ebc = 25,41            recommendedMax = Percent(value = 100.0),42            description = "Short description",43            bestFor = listOf(BeerType.DUBBEL, BeerType.BOCK),44        )45    }46    should("get all") {47        // Given48        repoUnderTest.save(sampleMalt)49        repoUnderTest.save(50            sampleMalt.copy(51                name = "Munich II",52                type = MaltType.MUNICH,53                ebc = 25,54                bestFor = listOf(BeerType.DUBBEL, BeerType.BOCK),55            ),56        )57        repoUnderTest.save(58            sampleMalt.copy(59                name = "Marris Otter",60                type = MaltType.MARRIS_OTTER,61                ebc = 6,62                bestFor = listOf(BeerType.ALE, BeerType.PALE_ALE, BeerType.IPA, BeerType.PORTER, BeerType.STOUT),63            ),64        )65        // When66        val result = repoUnderTest.getAll()67        // Then68        result shouldHaveSize 369        result.shouldHaveKeys("PILSNER 2RP", "MUNICH II", "MARRIS OTTER")70    }71    should("find from beer type") {72        // Given73        repoUnderTest.save(sampleMalt)74        repoUnderTest.save(75            sampleMalt.copy(76                name = "Munich II",77                type = MaltType.MUNICH,78                ebc = 25,79                bestFor = listOf(BeerType.DUBBEL, BeerType.BOCK),80            ),81        )82        repoUnderTest.save(83            sampleMalt.copy(84                name = "Marris Otter",85                type = MaltType.MARRIS_OTTER,86                ebc = 6,87                bestFor = listOf(BeerType.ALE, BeerType.PALE_ALE, BeerType.IPA, BeerType.PORTER, BeerType.STOUT),88            ),89        )90        // When & Then91        repoUnderTest.findBestForType(BeerType.BOCK).shouldHaveSize(1).toList()[0].name.shouldBe("Munich II")92    }93})...

Full Screen

Full Screen

ValuedEnumLaws.kt

Source:ValuedEnumLaws.kt Github

copy

Full Screen

1package org.tesserakt.diskordin.util.enums2import io.kotest.core.spec.style.FreeSpec3import io.kotest.core.spec.style.stringSpec4import io.kotest.inspectors.forAll5import io.kotest.matchers.booleans.shouldBeTrue6import io.kotest.matchers.collections.shouldNotContainDuplicates7import io.kotest.matchers.longs.shouldBeLessThanOrEqual8import org.tesserakt.diskordin.core.data.Permission9import org.tesserakt.diskordin.core.entity.IUser10import org.tesserakt.diskordin.core.entity.`object`.IActivity11import org.tesserakt.diskordin.gateway.shard.Intents12import org.tesserakt.diskordin.impl.util.typeclass.numeric13import org.tesserakt.diskordin.util.typeclass.Numeric14import java.util.*15class ValuedEnumLaws : FreeSpec({16    include("Permissions ", Long.numeric().testValuedEnum<Permission, Long>())17    include("Intents ", Short.numeric().testValuedEnum<Intents, Short>())18    include("User.Flags ", Int.numeric().testValuedEnum<IUser.Flags, Int>())19    include("Activity.Flags ", Short.numeric().testValuedEnum<IActivity.Flags, Short>())20})21fun <N> Numeric<N>.isPowerOf2(n: N): Boolean {22    tailrec fun f(init: N, input: N): Boolean = when {23        init > input -> false24        init < input -> f(init * 2.fromInt(), input)25        else -> true26    }27    return f(1.fromInt(), n)28}29inline fun <reified E, N : Any> Numeric<N>.testValuedEnum() where E : Enum<E>, E : IValued<E, N> = stringSpec {30    "All values should be power of two" {31        EnumSet.allOf(E::class.java)32            .map { it.code }.forAll { isPowerOf2(it).shouldBeTrue() }33    }34    "Sum of all codes should be less then MAX_VALUE" {35        EnumSet.allOf(E::class.java).map { it.code }36            .fold(zero) { acc, i -> acc + i }.toLong() shouldBeLessThanOrEqual maxValue.toLong()37    }38    "All values should be unique" {39        EnumSet.allOf(E::class.java).map { it.code }.shouldNotContainDuplicates()40    }41}...

Full Screen

Full Screen

short

Using AI Code Generation

copy

Full Screen

1    import io.kotest.matchers.string.*2    import io.kotest.matchers.throwable.*3    import io.kotest.matchers.types.*4    import io.kotest.matchers.uri.*5    import io.kotest.matchers.uri.*6    import io.kotest.matchers.uri.*7    import io.kotest.matchers.uri.*8    import io.kotest.matchers.uri.*9    import io.kotest.matchers.uri.*10    import io.kotest.matchers.uri.*11    import io.kotest.matchers.uri.*12    import io.kotest.matchers.uri.*13    import io.kotest.matchers.uri.*14    import io.kotest.matchers.uri.*15    import io.kotest.matchers.uri.*16    import io.kotest.matchers.uri.*17    import io.kotest.matchers.uri.*18    import io.kotest.matchers.uri.*19    import io.kotest.matchers.uri.*

Full Screen

Full Screen

short

Using AI Code Generation

copy

Full Screen

1import io.kotest.matchers.short.shouldBeLessThan2import io.kotest.matchers.int.shouldBeGreaterThan3import io.kotest.matchers.long.shouldBeLessThan4import io.kotest.matchers.float.shouldBeGreaterThan5import io.kotest.matchers.double.shouldBeLessThan6import io.kotest.matchers.char.shouldBeGreaterThan7import io.kotest.matchers.string.shouldBeLessThan8import io.kotest.matchers.boolean.shouldBeFalse9import io.kotest.matchers.byte.shouldBeGreaterThanOrEqual10import io.kotest.matchers.short.shouldBeLessThanOrEqual11import io.kotest.matchers.int.shouldBeGreaterThanOrEqual12import io.kotest.matchers.long.shouldBeLessThanOrEqual13import io.kotest.matchers.float.shouldBeGreaterThanOrEqual14import io.kotest.matchers.double.shouldBeLessThanOrEqual15import io.kotest.matchers.char.shouldBeGreaterThanOrEqual16import io.kotest.matchers.string.shouldBeLessThanOrEqual17import io.kotest.matchers.boolean.shouldBeTrue18import io

Full Screen

Full Screen

short

Using AI Code Generation

copy

Full Screen

1import io.kotest.matchers.short.shouldBeBetween2import io.kotest.matchers.short.shouldBeLessThan3import io.kotest.matchers.float.shouldBeBetween4import io.kotest.matchers.float.shouldBeLessThan5import io.kotest.matchers.double.shouldBeBetween6import io.kotest.matchers.double.shouldBeLessThan7import io.kotest.matchers.char.shouldBeBetween8import io.kotest.matchers.char.shouldBeLessThan9import io.kotest.matchers.boolean.shouldBeTrue10import io.kotest.matchers.boolean.shouldBeFalse11import io.kotest.matchers.array.shouldContain12import io.kotest.matchers.array.shouldNotContain13import io.kotest.matchers.list.shouldContain14import io.kotest.matchers.list.shouldNotContain15import io.kotest.matchers.map.shouldContain16import io.kotest.matchers.map.shouldNotContain17import io.kotest.matchers.set.shouldContain18import io.kotest.matchers.set.shouldNotContain19import io.kotest.matchers.string.shouldContain20import io.kotest.matchers.string.shouldNotContain21import io.kotest.matchers.collection.shouldContain22import io.kotest.matchers.collection.shouldNotContain23import io.kotest.matchers.iterable.shouldContain24import io.kotest.matchers.iterable.shouldNotContain25import io.kotest.matchers.sequence.shouldContain26import io.kotest.matchers

Full Screen

Full Screen

short

Using AI Code Generation

copy

Full Screen

1    import io.kotest.matchers.shouldBe2    import io.kotest.matchers.shouldNotBe3    import io.kotest.matchers.shouldNotThrow4    import io.kotest.matchers.string.shouldContain5    import io.kotest.matchers.string.shouldNotContain6    import io.kotest.matchers.types.shouldBeInstanceOf7    import io.kotest.matchers.types.shouldNotBeInstanceOf8    import io.kotest.matchers.types.shouldNotBeNull9    import io.kotest.matchers.types.shouldBeNull10    import io.kotest.matchers.types.shouldNotBeSameInstanceAs11    import io.kotest.matchers.types.shouldBeSameInstanceAs12    import io.kotest.matchers.types.shouldBeTypeOf13    import io.kotest.matchers.types.shouldNotBeTypeOf14    import io.kotest.matchers.types.shouldBeTheSameInstanceAs15    import io.kotest.matchers.types.shouldNotBeTheSameInstanceAs16    import io.kotest.matchers.types.shouldBeDataClassOf17    import io.kotest.matchers.types.shouldNotBeDataClassOf18    import io.kotest.matchers.types.shouldBeSealedClassOf19    import io.kotest.matchers.types.shouldNotBeSealedClassOf20    import io.kotest.matchers.types.shouldBeEnumClassOf21    import io.kotest.matchers.types.shouldNotBeEnumClassOf22    import io.kotest.matchers.types.shouldBeObjectOf23    import io.kotest.matchers.types.shouldNotBeObjectOf24    import io.kotest.matchers.types.shouldBeUnit25    import io.kotest.matchers.types.shouldNotBeUnit26    import io.kotest.matchers.types.shouldBeBoolean27    import io.kotest.matchers.types.shouldNotBeBoolean28    import io.kotest.matchers.types.shouldBeByte29    import io.kotest.matchers.types.shouldNotBeByte30    import io.kotest.matchers.types.shouldBeChar31    import io.kotest.matchers.types.shouldNotBeChar32    import io.kotest.matchers.types.shouldBeShort33    import io.kotest.matchers.types.shouldNotBeShort34    import io.kotest.matchers.types.shouldBeInt35    import io.kotest.matchers.types.shouldNotBeInt36    import io.kotest.match

Full Screen

Full Screen

short

Using AI Code Generation

copy

Full Screen

1import io.kotest.matchers.shouldBe2import io.kotest.matchers.shouldNotBe3import io.kotest.matchers.shouldNotThrow4import io.kotest.matchers.shouldThrow5import io.kotest.matchers.string.shouldContain6import io.kotest.matchers.string.shouldEndWith7import io.kotest.matchers.string.shouldHaveLength8import io.kotest.matchers.string.shouldHaveSameLengthAs9import io.kotest.matchers.string.shouldHaveSubstring10import io.kotest.matchers.string.shouldNotContain11import io.kotest.matchers.string.shouldNotEndWith12import io.kotest.matchers.string.shouldNotHaveLength13import io.kotest.matchers.string.shouldNotHaveSameLengthAs14import io.kotest.matchers.string.shouldNotHaveSubstring15import io.kotest.matchers.string.shouldStartWith16import io.kotest.matchers.string.shouldNotStartWith17import io.kotest.matchers.throwable.shouldHaveCause18import io.kotest.matchers.throwable.shouldHaveMessage19import io.kotest.matchers.throwable.shouldHaveMessageContaining20import io.kotest.matchers.throwable.shouldHaveMessageMatching21import io.kotest.matchers.types.beInstanceOf22import io.kotest.matchers.types.beNull23import io.kotest.matchers.types.beOfType24import io.kotest.matchers.types.shouldBeSameInstanceAs25import io.kotest.matchers.types.shouldNotBeSameInstanceAs26import io.kotest.matchers.collections.*27import io.kotest.matchers.collections.shouldBeEmpty28import io.kotest.matchers.collections.shouldBeIn29import io.kotest.matchers.collections.shouldBeInstanceOf30import io.kotest.matchers.collections.shouldBeSorted31import io.kotest.matchers.collections.shouldBeSortedBy32import io.kotest.matchers.collections.shouldContain33import io.kotest.matchers.collections.shouldContainAll34import io.kotest.matchers.collections.shouldContainAnyOf35import io.kotest.matchers.collections.shouldContainExactly36import io.kotest

Full Screen

Full Screen

short

Using AI Code Generation

copy

Full Screen

1import io.kotest.matchers.shouldBe2class ShortMatchersTest : StringSpec() {3   init {4      "short should" {5         1.toShort() shouldBe 1.toShort()6         2.toShort() shouldNotBe 1.toShort()7         1.toShort() shouldBeLessThan 2.toShort()8         1.toShort() shouldBeLessThanOrEqual 2.toShort()9         1.toShort() shouldBeLessThanOrEqual 1.toShort()10         2.toShort() shouldBeGreaterThan 1.toShort()11         2.toShort() shouldBeGreaterThanOrEqual 1.toShort()12         2.toShort() shouldBeGreaterThanOrEqual 2.toShort()13      }14   }15}16import io.kotest.matchers.shouldBe17class ByteMatchersTest : StringSpec() {18   init {19      "byte should" {20         1.toByte() shouldBe 1.toByte()21         2.toByte() shouldNotBe 1.toByte()22         1.toByte() shouldBeLessThan 2.toByte()23         1.toByte() shouldBeLessThanOrEqual 2.toByte()24         1.toByte() shouldBeLessThanOrEqual 1.toByte()25         2.toByte() shouldBeGreaterThan 1.toByte()26         2.toByte() shouldBeGreaterThanOrEqual 1.toByte()27         2.toByte() shouldBeGreaterThanOrEqual 2.toByte()28      }29   }30}31import io.kotest.matchers.shouldBe32class DoubleMatchersTest : StringSpec() {33   init {34      "double should" {35      }36   }37}38import io.kotest.matchers.shouldBe39class FloatMatchersTest : StringSpec() {

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 short

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful