Best Kotest code snippet using io.kotest.matchers.collections.contain
ServerTest.kt
Source:ServerTest.kt
1/*2 * Tabletop Game Library3 * Copyright (c) 2021 Carl W Spain4 *5 * Permission is hereby granted, free of charge, to any person obtaining a copy6 * of this software and associated documentation files (the "Software"), to deal7 * in the Software without restriction, including without limitation the rights8 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell9 * copies of the Software, and to permit persons to whom the Software is10 * furnished to do so, subject to the following conditions:11 *12 * The above copyright notice and this permission notice shall be included in all13 * copies or substantial portions of the Software.14 *15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE18 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,20 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE21 * SOFTWARE.22 *23 */24package ttgamelib.net25import io.kotest.core.spec.style.FunSpec26import io.kotest.data.forAll27import io.kotest.data.row28import io.kotest.inspectors.forAll29import io.kotest.matchers.booleans.shouldBeFalse30import io.kotest.matchers.booleans.shouldBeTrue31import io.kotest.matchers.collections.shouldBeEmpty32import io.kotest.matchers.collections.shouldContain33import io.kotest.matchers.collections.shouldHaveSize34import io.kotest.matchers.maps.shouldContainValue35import io.kotest.matchers.shouldBe36import io.kotest.matchers.shouldNotBe37import io.kotest.matchers.types.shouldBeInstanceOf38import io.kotest.matchers.types.shouldBeTypeOf39import io.ktor.http.cio.websocket.*40import io.mockk.*41import kotlinx.serialization.json.Json42import ttgamelib.GameEngine43private inline fun<reified T: Packet> List<Frame>.decode(): List<T> {44 return map {45 Json.decodeFromString(Packet.serializer(), (it as Frame.Text).readText()) as T46 }47}48private fun createConnection(userName: String, clientId: Int): Pair<ClientConnection, MutableList<Frame>> {49 val sentPackets = mutableListOf<Frame>()50 val session = mockk<DefaultWebSocketSession>().also {51 coEvery {52 it.send(capture(sentPackets))53 } just Runs54 }55 val connection = ClientConnection(session).apply {56 name = userName57 id = clientId58 }59 return connection to sentPackets60}61internal class ServerTest : FunSpec({62 val engine = mockk<GameEngine>(relaxed = true)63 val (connection, sentPackets) = createConnection("player1", 1)64 lateinit var server: Server65 beforeEach {66 sentPackets.clear()67 }68 context("SendNamePacket") {69 val userName = "New User"70 server = Server("localhost", 1000, engine)71 test("should create new user if name is not in use") {72 server.handlePacket(SendNamePacket(userName), connection)73 val sent = sentPackets.decode<Packet>()74 sent[0].shouldBeInstanceOf<InitClientPacket>()75 (sent[0] as InitClientPacket).clientId shouldBe connection.id76 sent[1].shouldBeInstanceOf<ChatMessagePacket>()77 coVerify {78 engine.playerConnected(connection.id, userName)79 }80 }81 test("should request another name if in use") {82 val (connection2, sentPackets2) = createConnection("player2", 2)83 server.handlePacket(SendNamePacket(userName), connection2)84 val sent = sentPackets2.decode<SuggestNamePacket>()85 with (sent[0]) {86 name shouldNotBe userName87 taken.shouldContain(userName)88 disconnected.shouldBeFalse()89 }90 }91 test("should check for reconnection if disconnected") {92 server.connections.remove(connection.id)93 server.handlePacket(SendNamePacket(userName), connection)94 val sent = sentPackets.decode<SuggestNamePacket>()95 with (sent[0]) {96 name shouldNotBe userName97 taken.shouldContain(userName)98 disconnected.shouldBeTrue()99 }100 }101 test("should replace player on reconnection") {102 server.handlePacket(SendNamePacket(userName, true), connection)103 val sent = sentPackets.decode<Packet>()104 sent[0].shouldBeInstanceOf<InitClientPacket>()105 (sent[0] as InitClientPacket).clientId shouldBe connection.id106 sent[1].shouldBeInstanceOf<ChatMessagePacket>()107 coVerify {108 engine.playerReconnected(connection.id)109 }110 }111 test("should not replace player that is connected") {112 server.handlePacket(SendNamePacket(userName, true), connection)113 val sent = sentPackets.decode<SuggestNamePacket>()114 with (sent[0]) {115 name shouldNotBe userName116 disconnected.shouldBeFalse()117 }118 }119 }120 test("GameCommandPacket should be sent to game engine") {121 val packet = MessagePacket(object : GameMessage{})122 server.handlePacket(packet, connection)123 sentPackets.shouldBeEmpty()124 coVerify {125 engine.handle(connection.id, packet)126 }127 }128 context("chat command") {129 server = Server("localhost", 1000, engine)130 val connections = mutableListOf<ClientConnection>()131 val outgoing = mutableListOf<MutableList<Frame>>()132 for (i in 1..3) {133 with (createConnection("player$i", i)) {134 connections += first135 outgoing += second136 server.handlePacket(SendNamePacket(first.name), first)137 }138 }139 beforeEach {140 outgoing.forEach { it.clear() }141 }142 test("there should be three connected players") {143 connections.forAll {144 server.connections.shouldContainValue(it)145 }146 }147 test("emote should send message to all users") {148 forAll(149 row("/em is here"),150 row("/me is here")151 ) { msg ->152 server.handlePacket(ChatCommandPacket(connection.id, msg), connection)153 }154 outgoing.forEach {155 with (it.decode<ChatMessagePacket>()) {156 shouldHaveSize(2)157 forAll { it.message.shouldBeTypeOf<EmoteMessage>() }158 }159 }160 }161 test("whisper should send message to one user") {162 server.handlePacket(ChatCommandPacket(connections[0].id, "/w player2 a secret"), connections[0])163 outgoing[0].shouldHaveSize(1)164 outgoing[1].shouldHaveSize(1)165 outgoing[2].shouldBeEmpty()166 }167 test("whisper to unknown user should send info message to sender") {168 server.handlePacket(ChatCommandPacket(connections[1].id, "/w nobody a secret"), connections[1])169 outgoing[0].shouldHaveSize(0)170 outgoing[2].shouldHaveSize(0)171 outgoing[1].shouldHaveSize(1)172 outgoing[1].decode<ChatMessagePacket>().forAll {173 it.message.shouldBeTypeOf<InfoMessage>()174 }175 }176 test("unknown command should send info message to sender") {177 server.handlePacket(ChatCommandPacket(connections[1].id, "/foo bar baz"), connections[1])178 outgoing[0].shouldHaveSize(0)179 outgoing[2].shouldHaveSize(0)180 outgoing[1].shouldHaveSize(1)181 outgoing[1].decode<ChatMessagePacket>().forAll {182 it.message.shouldBeTypeOf<InfoMessage>()183 }184 }185 }186})...
FailingKotestAsserts.kt
Source:FailingKotestAsserts.kt
1package testing.failing2import arrow.core.*3import io.kotest.assertions.arrow.either.shouldBeLeft4import io.kotest.assertions.arrow.either.shouldBeRight5import io.kotest.assertions.arrow.nel.shouldContain6import io.kotest.assertions.arrow.nel.shouldContainNull7import io.kotest.assertions.arrow.option.shouldBeNone8import io.kotest.assertions.arrow.option.shouldBeSome9import io.kotest.assertions.arrow.validation.shouldBeInvalid10import io.kotest.assertions.arrow.validation.shouldBeValid11import io.kotest.assertions.asClue12import io.kotest.assertions.assertSoftly13import io.kotest.assertions.json.*14import io.kotest.assertions.throwables.shouldThrowAny15import io.kotest.assertions.throwables.shouldThrowExactly16import io.kotest.assertions.withClue17import io.kotest.matchers.Matcher18import io.kotest.matchers.MatcherResult19import io.kotest.matchers.booleans.shouldBeFalse20import io.kotest.matchers.booleans.shouldBeTrue21import io.kotest.matchers.collections.shouldBeEmpty22import io.kotest.matchers.collections.shouldBeOneOf23import io.kotest.matchers.collections.shouldBeSameSizeAs24import io.kotest.matchers.collections.shouldBeSorted25import io.kotest.matchers.collections.shouldContain26import io.kotest.matchers.date.shouldBeAfter27import io.kotest.matchers.ints.shouldBeEven28import io.kotest.matchers.ints.shouldBeGreaterThan29import io.kotest.matchers.ints.shouldBeGreaterThanOrEqual30import io.kotest.matchers.ints.shouldBeLessThan31import io.kotest.matchers.ints.shouldBeLessThanOrEqual32import io.kotest.matchers.ints.shouldBeZero33import io.kotest.matchers.maps.shouldBeEmpty34import io.kotest.matchers.maps.shouldContain35import io.kotest.matchers.maps.shouldContainKey36import io.kotest.matchers.maps.shouldContainValue37import io.kotest.matchers.nulls.shouldBeNull38import io.kotest.matchers.should39import io.kotest.matchers.shouldBe40import io.kotest.matchers.shouldNot41import io.kotest.matchers.string.shouldBeBlank42import io.kotest.matchers.string.shouldBeEmpty43import io.kotest.matchers.string.shouldBeUpperCase44import io.kotest.matchers.string.shouldContain45import io.kotest.matchers.string.shouldNotBeBlank46import java.time.LocalDate47import org.junit.jupiter.api.Test48/**49 * Kotest assertions50 *51 * - [Kotest Assertions Documentation](https://kotest.io/assertions/)52 * - [Github](https://github.com/kotest/kotest/)53 */54class FailingKotestAsserts {55 @Test56 fun `General assertions`() {57 assertSoftly {58 "text" shouldBe "txet"59 "hi".shouldBeBlank()60 " ".shouldNotBeBlank()61 "hi".shouldBeEmpty()62 "hi".shouldBeUpperCase()63 "hello".shouldContain("hi")64 false.shouldBeTrue()65 true.shouldBeFalse()66 "not null".shouldBeNull()67 10 shouldBeLessThan 1068 10 shouldBeLessThanOrEqual 969 11 shouldBeGreaterThan 1170 11 shouldBeGreaterThanOrEqual 1271 9.shouldBeEven()72 1.shouldBeZero()73 }74 }75 @Test76 fun `Exception assertions`() {77 assertSoftly {78 shouldThrowExactly<IllegalArgumentException> {79 angryFunction()80 }81 shouldThrowAny {82 "I'm not throwing anything"83 }84 }85 }86 @Test87 fun `Collection assertions`() {88 assertSoftly {89 listOf(1, 2, 3).shouldBeEmpty()90 listOf(1, 2, 3) shouldContain 491 listOf(1, 3, 2).shouldBeSorted()92 listOf(1, 2, 3, 4) shouldBeSameSizeAs listOf(4, 5, 6)93 1 shouldBeOneOf listOf(2, 3)94 mapOf(1 to "one", 2 to "two", 3 to "three").shouldBeEmpty()95 mapOf(1 to "one", 2 to "two", 3 to "three") shouldContainKey 496 mapOf(1 to "one", 2 to "two", 3 to "three") shouldContainValue "five"97 mapOf(1 to "one", 2 to "two", 3 to "three") shouldContain (6 to "six")98 }99 }100 @Test101 fun `Arrow assertions`() {102 assertSoftly {103 val optionNone = none<String>()104 val optionSome = Some("I am something").toOption()105 optionSome.shouldBeNone()106 optionNone.shouldBeSome()107 val rightEither = Either.Right(1)108 val leftEither = Either.Left("ERROR!!")109 leftEither.shouldBeRight()110 leftEither shouldBeRight 1111 rightEither.shouldBeLeft()112 rightEither shouldBeLeft "ERROR!!"113 val nonEmptyList = NonEmptyList.of(1, 2, 3, 4, 5)114 nonEmptyList shouldContain 6115 nonEmptyList.shouldContainNull()116 val valid = Validated.valid()117 val invalid = Validated.invalid()118 invalid.shouldBeValid()119 valid.shouldBeInvalid()120 }121 }122 @Test123 fun `Json assertions`() {124 val jsonString = "{\"test\": \"property\", \"isTest\": true }"125 assertSoftly {126 jsonString shouldMatchJson "{\"test\": \"otherProperty\"}"127 jsonString shouldContainJsonKey "$.anotherTest"128 jsonString shouldNotContainJsonKey "$.test"129 jsonString.shouldContainJsonKeyValue("$.isTest", false)130 }131 }132 @Test133 fun `Custom assertions`() {134 assertSoftly {135 val sentMail = Mail(136 dateCreated = LocalDate.of(2020, 10, 27),137 sent = true, message = "May you have an amazing day"138 )139 val unsentMail = Mail(140 dateCreated = LocalDate.of(2020, 10, 27),141 sent = false, message = "May you have an amazing day"142 )143 // This is possible144 unsentMail.sent should beSent()145 sentMail.sent shouldNot beSent()146 // This is recommended147 unsentMail.shouldBeSent()148 sentMail.shouldNotBeSent()149 }150 }151 @Test152 fun `withClue usage`() {153 val mail = Mail(154 dateCreated = LocalDate.of(2020, 10, 27),155 sent = false, message = "May you have an amazing day"156 )157 withClue("sent field should be true") {158 mail.sent shouldBe true159 }160 mail.asClue {161 it.dateCreated shouldBeAfter LocalDate.of(2020, 10, 26)162 it.sent shouldBe true163 }164 }165 @Test166 fun `asClue usage`() {167 val mail = Mail(168 dateCreated = LocalDate.of(2020, 10, 27),169 sent = false, message = "May you have an amazing day"170 )171 mail.asClue {172 it.dateCreated shouldBeAfter LocalDate.of(2020, 10, 26)173 it.sent shouldBe true174 }175 }176 fun beSent() = object : Matcher<Boolean> {177 override fun test(value: Boolean) = MatcherResult(value, "Mail.sent should be true", "Mail.sent should be false")178 }179 fun Mail.shouldBeSent() = this.sent should beSent()180 fun Mail.shouldNotBeSent() = this.sent shouldNot beSent()181}182data class Mail(val dateCreated: LocalDate, val sent: Boolean, val message: String)183fun angryFunction() {184 throw IllegalStateException("How dare you!")185}...
KotestAsserts.kt
Source:KotestAsserts.kt
1package testing.asserts2import arrow.core.*3import io.kotest.assertions.arrow.either.shouldBeLeft4import io.kotest.assertions.arrow.either.shouldBeRight5import io.kotest.assertions.arrow.nel.shouldContain6import io.kotest.assertions.arrow.nel.shouldContainNull7import io.kotest.assertions.arrow.option.shouldBeNone8import io.kotest.assertions.arrow.option.shouldBeSome9import io.kotest.assertions.arrow.validation.shouldBeInvalid10import io.kotest.assertions.arrow.validation.shouldBeValid11import io.kotest.assertions.asClue12import io.kotest.assertions.json.*13import io.kotest.assertions.throwables.shouldThrowAny14import io.kotest.assertions.throwables.shouldThrowExactly15import io.kotest.assertions.withClue16import io.kotest.matchers.Matcher17import io.kotest.matchers.MatcherResult18import io.kotest.matchers.booleans.shouldBeFalse19import io.kotest.matchers.booleans.shouldBeTrue20import io.kotest.matchers.collections.shouldBeEmpty21import io.kotest.matchers.collections.shouldBeOneOf22import io.kotest.matchers.collections.shouldBeSameSizeAs23import io.kotest.matchers.collections.shouldBeSorted24import io.kotest.matchers.collections.shouldContain25import io.kotest.matchers.date.shouldBeAfter26import io.kotest.matchers.ints.shouldBeEven27import io.kotest.matchers.ints.shouldBeGreaterThan28import io.kotest.matchers.ints.shouldBeGreaterThanOrEqual29import io.kotest.matchers.ints.shouldBeLessThan30import io.kotest.matchers.ints.shouldBeLessThanOrEqual31import io.kotest.matchers.ints.shouldBeZero32import io.kotest.matchers.maps.shouldBeEmpty33import io.kotest.matchers.maps.shouldContain34import io.kotest.matchers.maps.shouldContainKey35import io.kotest.matchers.maps.shouldContainValue36import io.kotest.matchers.nulls.shouldBeNull37import io.kotest.matchers.should38import io.kotest.matchers.shouldBe39import io.kotest.matchers.shouldNot40import io.kotest.matchers.string.shouldBeBlank41import io.kotest.matchers.string.shouldBeEmpty42import io.kotest.matchers.string.shouldBeUpperCase43import io.kotest.matchers.string.shouldContain44import io.kotest.matchers.string.shouldNotBeBlank45import java.time.LocalDate46import org.junit.jupiter.api.Test47/**48 * Kotest assertions49 *50 * - [Kotest Assertions Documentation](https://kotest.io/assertions/)51 * - [Github](https://github.com/kotest/kotest/)52 */53class KotestAsserts {54 @Test55 fun `General assertions`() {56 "text" shouldBe "text"57 " ".shouldBeBlank()58 "hi".shouldNotBeBlank()59 "".shouldBeEmpty()60 "HI".shouldBeUpperCase()61 "hello".shouldContain("ll")62 true.shouldBeTrue()63 false.shouldBeFalse()64 null.shouldBeNull()65 10 shouldBeLessThan 1166 10 shouldBeLessThanOrEqual 1067 11 shouldBeGreaterThan 1068 11 shouldBeGreaterThanOrEqual 1169 10.shouldBeEven()70 0.shouldBeZero()71 }72 @Test73 fun `Exception assertions`() {74 shouldThrowExactly<IllegalStateException> {75 angryFunction()76 }77 shouldThrowAny {78 angryFunction()79 }80 }81 @Test82 fun `Collection assertions`() {83 emptyList<Int>().shouldBeEmpty()84 listOf(1, 2, 3) shouldContain 385 listOf(1, 2, 3).shouldBeSorted()86 listOf(1, 2, 3) shouldBeSameSizeAs listOf(4, 5, 6)87 1 shouldBeOneOf listOf(1, 2, 3)88 emptyMap<Int, String>().shouldBeEmpty()89 mapOf(1 to "one", 2 to "two", 3 to "three") shouldContainKey 190 mapOf(1 to "one", 2 to "two", 3 to "three") shouldContainValue "two"91 mapOf(1 to "one", 2 to "two", 3 to "three") shouldContain (3 to "three")92 }93 @Test94 fun `Arrow assertions`() {95 val optionNone = none<String>()96 val optionSome = Some("I am something").toOption()97 optionNone.shouldBeNone()98 optionSome.shouldBeSome()99 val rightEither = Either.Right(1)100 val leftEither = Either.Left("ERROR!!")101 rightEither.shouldBeRight()102 rightEither shouldBeRight 1103 leftEither.shouldBeLeft()104 leftEither shouldBeLeft "ERROR!!"105 val nonEmptyList = NonEmptyList.of(1, 2, 3, 4, 5, null)106 nonEmptyList shouldContain 1107 nonEmptyList.shouldContainNull()108 val valid = Validated.valid()109 val invalid = Validated.invalid()110 valid.shouldBeValid()111 invalid.shouldBeInvalid()112 }113 @Test114 fun `Json assertions`() {115 val jsonString = "{\"test\": \"property\", \"isTest\": true }"116 jsonString shouldMatchJson jsonString117 jsonString shouldContainJsonKey "$.test"118 jsonString shouldNotContainJsonKey "$.notTest"119 jsonString.shouldContainJsonKeyValue("$.isTest", true)120 }121 @Test122 fun `Custom assertions`() {123 val sentMail = Mail(124 dateCreated = LocalDate.of(2020, 10, 27),125 sent = true, message = "May you have an amazing day"126 )127 val unsentMail = Mail(128 dateCreated = LocalDate.of(2020, 10, 27),129 sent = false, message = "May you have an amazing day"130 )131 // This is possible132 sentMail.sent should beSent()133 unsentMail.sent shouldNot beSent()134 // This is recommended135 sentMail.shouldBeSent()136 unsentMail.shouldNotBeSent()137 }138 @Test139 fun `withClue usage`() {140 val mail = Mail(141 dateCreated = LocalDate.of(2020, 10, 27),142 sent = false, message = "May you have an amazing day"143 )144 withClue("sent field should be false") {145 mail.sent shouldBe false146 }147 mail.asClue {148 it.dateCreated shouldBeAfter LocalDate.of(2020, 10, 26)149 it.sent shouldBe false150 }151 }152 @Test153 fun `asClue usage`() {154 val mail = Mail(155 dateCreated = LocalDate.of(2020, 10, 27),156 sent = false, message = "May you have an amazing day"157 )158 mail.asClue {159 it.dateCreated shouldBeAfter LocalDate.of(2020, 10, 26)160 it.sent shouldBe false161 }162 }163 fun beSent() = object : Matcher<Boolean> {164 override fun test(value: Boolean) = MatcherResult(value, "Mail.sent should be true", "Mail.sent should be false")165 }166 fun Mail.shouldBeSent() = this.sent should beSent()167 fun Mail.shouldNotBeSent() = this.sent shouldNot beSent()168}169data class Mail(val dateCreated: LocalDate, val sent: Boolean, val message: String)170fun angryFunction() {171 throw IllegalStateException("How dare you!")172}...
RoomsKtTest.kt
Source:RoomsKtTest.kt
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})...
WordRiddleSpec.kt
Source:WordRiddleSpec.kt
...33 }34 }35 When("Guess lower case ${letter.lowercaseChar()}") {36 riddle.guess(letter)37 Then("Guessed letters should contain $letter") {38 guessedLetters shouldContain letter.lowercaseChar()39 }40 }41 When("Guess upper case ${letter.uppercaseChar()}") {42 riddle.guess(letter)43 Then("Guessed letters should contain $letter") {44 guessedLetters shouldContain letter.lowercaseChar()45 }46 }47 }48 And("Another letter") {49 val letter = 'a'50 When("Check if $letter is left") {51 val left = riddle.left(letter)52 Then("The riddle should not have $letter left") {53 left shouldNotBe true54 }55 }56 When("Guess $letter") {57 riddle.guess(letter)58 Then("$letter should not be guessed") {59 guessedLetters.shouldBeEmpty()60 }61 }62 }63 When("Write riddle") {64 riddle.write(writer)65 Then("Writer string should contain masked word") {66 writer.toString() shouldBe "??????????"67 }68 }69 }70 }71 And("All letters from the word collection") {72 val guessedLetters = mutableSetOf('s', 'i', 'm', 'p', 'l', 'c', 't', 'y')73 And("Word riddle") {74 val riddle = WordRiddle(word, guessedLetters)75 When("Check if the riddle is guessed") {76 val guessed = riddle.guessed()77 Then("Riddle should be guessed") {78 guessed shouldBe true79 }80 }81 And("Letter from the word") {82 val letter = 'o'83 When("Check if $letter is left") {84 val left = riddle.left(letter)85 Then("The riddle should not have $letter left") {86 left shouldBe false87 }88 }89 }90 When("Write riddle") {91 riddle.write(writer)92 Then("Writer string should contain unmasked word") {93 writer.toString() shouldBe "simplicity"94 }95 }96 }97 }98 }99})...
VendedorTest.kt
Source:VendedorTest.kt
1package ar.edu.unahur.obj2.vendedores2import io.kotest.assertions.throwables.shouldThrowAny3import io.kotest.core.spec.style.DescribeSpec4import io.kotest.matchers.booleans.shouldBeFalse5import io.kotest.matchers.booleans.shouldBeTrue6import io.kotest.matchers.collections.shouldContain7import io.kotest.matchers.collections.shouldContainAll8import io.kotest.matchers.collections.shouldNotContain9import io.kotest.matchers.should10import io.kotest.matchers.shouldBe11class ComercioTest : DescribeSpec({12 val buenosAires = Provincia(15000000)13 val santaFe = Provincia(9000000)14 val cordoba = Provincia(12000000)15 val entreRios = Provincia(1500000)16 val chivilcoy = Ciudad(buenosAires)17 val bragado = Ciudad(buenosAires)18 val lobos = Ciudad(buenosAires)19 val pergamino = Ciudad(buenosAires)20 val zarate = Ciudad(buenosAires)21 val rosario = Ciudad(santaFe)22 val rafaela = Ciudad(santaFe)23 val sanFrancisco = Ciudad(cordoba)24 val diamante = Ciudad(entreRios)25 val armstrong = Ciudad(santaFe)26 describe("Es influyente1") {27 val corresponsal = ComercioCorresponsal(listOf(chivilcoy, bragado, lobos, pergamino, zarate))28 it("5 ciudades") {29 corresponsal.esInfluyente().shouldBeTrue()30 }31 }32 describe("Es influyente2") {33 val corresponsal2 = ComercioCorresponsal(listOf(rosario, rafaela, sanFrancisco, diamante))34 it("3 provincias") {35 corresponsal2.esInfluyente().shouldBeTrue()36 }37 }38 describe("Es influyente3") {39 val corresponsal3 = ComercioCorresponsal(listOf(rosario, rafaela, armstrong, diamante))40 it("4 ciudades, 2 pcias") {41 corresponsal3.esInfluyente().shouldBeFalse()42 }43 }44})45class VendedorTest : DescribeSpec({46 val misiones = Provincia(1300000)47 val sanIgnacio = Ciudad(misiones)48 val certif1 = Certificacion(esDeProducto = true, puntaje = 10)49 val certif2 = Certificacion(esDeProducto = true, puntaje = 5)50 val certif3 = Certificacion(esDeProducto = false, puntaje = 9)51 describe("Vendedor fijo") {52 val obera = Ciudad(misiones)53 val vendedorFijo = VendedorFijo(obera)54 vendedorFijo.certificaciones.addAll(listOf(certif1, certif2, certif3))55 describe("Es versatil o firme") {56 it("es versatil") {57 vendedorFijo.esVersatil().shouldBeTrue()58 }59 it("es firme") {60 vendedorFijo.esFirme().shouldBeFalse()61 }62 }63 describe("puedeTrabajarEn") {64 it("su ciudad de origen") {65 vendedorFijo.puedeTrabajarEn(obera).shouldBeTrue()66 }67 it("otra ciudad") {68 vendedorFijo.puedeTrabajarEn(sanIgnacio).shouldBeFalse()69 }70 }71 }72 describe("Viajante") {73 val cordoba = Provincia(2000000)74 val villaDolores = Ciudad(cordoba)75 val viajante = Viajante(listOf(misiones))76 describe("puedeTrabajarEn") {77 it("una ciudad que pertenece a una provincia habilitada") {78 viajante.puedeTrabajarEn(sanIgnacio).shouldBeTrue()79 }80 it("una ciudad que no pertenece a una provincia habilitada") {81 viajante.puedeTrabajarEn(villaDolores).shouldBeFalse()82 }83 }84 }85})86class CentroDistribucionTest : DescribeSpec({87 val buenosAires = Provincia(15000000)88 val chivilcoy = Ciudad(buenosAires)89 val centro1 = CentroDeDistribucion(chivilcoy)90 val valeria = VendedorFijo(chivilcoy)91 val certif4 = Certificacion(esDeProducto = true, puntaje = 60)92 val certif5 = Certificacion(esDeProducto = true, puntaje = 5)93 val certif6 = Certificacion(esDeProducto = false, puntaje = 9)94 val malena = VendedorFijo(chivilcoy)95 valeria.certificaciones.addAll(listOf(certif5, certif6))96 malena.certificaciones.addAll(listOf(certif4, certif5, certif6))97 describe("Agregar vendedores") {98 it("Agregar un vendedor") {99 centro1.agregarVendedor(valeria)100 centro1.vendedores.shouldContain(valeria)101 }102 it("no permite agregar dos veces al mismo vendedor") {103 shouldThrowAny {104 centro1.agregarVendedor(valeria)105 }106 }107 }108 describe("Vendedores estrella") {109 centro1.agregarVendedor(malena)110 centro1.agregarVendedor(valeria)111 it("vendedor estrella") {112 centro1.vendedorEstrella().shouldBe(malena)113 }114 }115})...
InMemoryHopRepositoryTest.kt
Source:InMemoryHopRepositoryTest.kt
1package infrastructure2import domain.country.model.Country3import domain.hop.model.Hop4import domain.hop.model.HopType5import 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})...
ArbitraterApiTest.kt
Source:ArbitraterApiTest.kt
1/*2 * Copyright [2018] Tyro Payments Limited.3 *4 * Licensed under the Apache License, Version 2.0 (the "License");5 * you may not use this file except in compliance with the License.6 * You may obtain a copy of the License at7 *8 * http://www.apache.org/licenses/LICENSE-2.09 *10 * Unless required by applicable law or agreed to in writing, software11 * distributed under the License is distributed on an "AS IS" BASIS,12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13 * See the License for the specific language governing permissions and14 * limitations under the License.15 */16package com.tyro.oss.arbitrater17import io.kotest.matchers.collections.shouldContainAll18import io.kotest.matchers.collections.shouldNotContain19import io.kotest.matchers.collections.shouldNotContainNoNulls20import io.kotest.matchers.collections.shouldNotContainNull21import io.kotest.matchers.shouldBe22import io.kotest.matchers.shouldNotBe23import org.junit.jupiter.api.Test24class ArbitraterApiTest {25 @Test26 fun `arbitrary instance`() {27 arbitrary<DefaultValue>().int shouldNotBe null28 }29 @Test30 fun `nullable types generate values by default`() {31 val arbitraryInstance = NullableValue::class.arbitraryInstance()32 arbitraryInstance.date shouldNotBe null33 }34 @Test35 fun `can generate nulls for null values if desired`() {36 val arbitraryInstance = NullableValue::class.arbitrater()37 .generateNulls()38 .createInstance()39 arbitraryInstance.date shouldBe null40 }41 @Test42 fun `uses default values by default`() {43 val arbitraryInstances = (1..100).map {44 DefaultValue::class.arbitraryInstance()45 }46 arbitraryInstances.map { it.int }.shouldContainAll(10)47 }48 @Test49 fun `can elect not to use default values`() {50 val arbitraryInstances = (1..100).map {51 DefaultValue::class.arbitrater()52 .useDefaultValues(false)53 .createInstance()54 }55 arbitraryInstances shouldNotContain DefaultValue(10)56 }57 @Test58 fun `null and default type options propagate when generating nested classes`() {59 val instances = (1..10).map {60 NestedTypesWithNullableAndDefaultValues::class.arbitrater()61 .generateNulls(true)62 .useDefaultValues(false)63 .createInstance()64 }65 instances.map { it.defaultValue.int } shouldNotContain 1066 instances.map { it.nullableValue.date }.shouldNotContainNoNulls()67 }68 @Test69 fun `convenience method 'WithAllPropertiesRandomized' will not generate nulls and generates values for default types`() {70 val arbitraryInstances = (1..100).map {71 NullableAndDefaultValues::class.arbitraryInstanceWithAllPropertiesRandomized()72 }73 arbitraryInstances.map { it.int } shouldNotContain 1074 arbitraryInstances.map { it.date }.shouldNotContainNull()75 }76}...
contain
Using AI Code Generation
1val list = listOf(1, 2, 3, 4, 5)2list should contain(1, 2, 3, 4, 5)3list shouldNot contain(1, 2, 3, 4, 5, 6)4list should contain(1, 2, 3)5list shouldNot contain(1, 2, 3, 4, 5)6list should contain(1)7list shouldNot contain(1, 2)8list should contain(5)9list shouldNot contain(1, 5)10list should contain(5, 4, 3, 2, 1)11list shouldNot contain(1, 2, 3, 4, 5, 6)12list should contain(5, 4, 3, 2, 1, 6)13list shouldNot contain(1, 2, 3, 4, 5, 6)14list should contain(6)15list shouldNot contain(1, 6)16list should contain(6, 5, 4, 3, 2, 1)17list shouldNot contain(1, 2, 3, 4, 5, 6)18list should contain(6, 5, 4, 3, 2, 1, 6)19list shouldNot contain(1, 2, 3, 4, 5, 6)20list should contain(1, 2, 3, 4, 5, 6)21list shouldNot contain(1, 2, 3, 4, 5)22list should contain(1, 2, 3, 4, 5, 6, 7)23list shouldNot contain(1, 2, 3, 4, 5)24list should contain(1, 2, 3, 4, 5, 6, 7, 8)25list shouldNot contain(1, 2, 3, 4, 5)26list should contain(1, 2, 3, 4, 5, 6, 7, 8, 9)27list shouldNot contain(1, 2, 3, 4, 5)28list should contain(1, 2,
contain
Using AI Code Generation
1assertThat( list ).contains( 1 )2assertThat( "Hello World" ).contains( "Hello" )3assertThat( map ).contains( "key" to "value" )4assertThat( iterable ).contains( 1 )5assertThat( list ).contains( 1 )6assertThat( "Hello World" ).contains( "Hello" )7assertThat( map ).contains( "key" to "value" )8assertThat( iterable ).contains( 1 )9assertThat( list ).contains( 1 )10assertThat( "Hello World" ).contains( "Hello" )11assertThat( map ).contains( "key" to "value" )12assertThat( iterable ).contains( 1 )13assertThat( list ).contains( 1 )14assertThat( "Hello World" ).contains( "Hello" )15assertThat( map ).contains( "key" to "value" )16assertThat( iterable ).contains( 1 )17assertThat( list ).contains( 1 )18assertThat( "Hello World" ).contains( "Hello" )
contain
Using AI Code Generation
1@DisplayName("Test for List")2class ListTest {3 @DisplayName("Test for List")4 fun testList() {5 val list = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)6 list should contain(5)7 list shouldNot contain(11)8 list should containAll(5, 6, 7)9 list should containAll(listOf(5, 6, 7))10 list shouldNot containAll(5, 6, 7, 11)11 list shouldNot containAll(listOf(5, 6, 7, 11))12 list should containNone(11, 12, 13)13 list should containNone(listOf(11, 12, 13))14 list shouldNot containNone(5, 6, 7)15 list shouldNot containNone(listOf(5, 6, 7))16 list should containExactly(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)17 list should containExactly(listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))18 list should containExactlyInAnyOrder(5, 4, 3, 2, 1, 6, 7, 8, 9, 10)19 list should containExactlyInAnyOrder(listOf(5, 4, 3, 2, 1, 6, 7, 8, 9, 10))20 list should containExactlyInAnyOrder(5, 4, 3, 2, 1, 6, 7, 8, 9, 10)21 list should containExactlyInAnyOrder(listOf(5, 4, 3, 2, 1, 6, 7, 8, 9, 10))22 list should containInOrder(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)23 list should containInOrder(listOf(1, 2, 3, 4, 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!!