How to use error method of io.kotest.data.errors class

Best Kotest code snippet using io.kotest.data.errors.error

ReplTests.kt

Source:ReplTests.kt Github

copy

Full Screen

...53            print("")54        }55    }56    @Test57    fun `compilation error`() {58        val ex = shouldThrow<ReplCompilerException> {59            eval(60                """61                val foobar = 7862                val foobaz = "dsdsda"63                val ddd = ppp64                val ooo = foobar65                """.trimIndent()66            )67        }68        val diag = ex.firstError69        val location = diag?.location70        val message = ex.message71        val expectedLocation = SourceCode.Location(SourceCode.Position(3, 11), SourceCode.Position(3, 14))72        val expectedMessage = "Line_0.${repl.fileExtension} (3:11 - 14) Unresolved reference: ppp"73        location shouldBe expectedLocation74        message shouldBe expectedMessage75    }76    @Test77    fun `runtime execution error`() {78        val ex = shouldThrow<ReplEvalRuntimeException> {79            eval(80                """81                try {82                    (null as String)83                } catch(e: NullPointerException) {84                    throw RuntimeException("XYZ", e)85                }86                """.trimIndent()87            )88        }89        with(ex.render()) {90            shouldContain(NullPointerException::class.qualifiedName!!)91            shouldContain("XYZ")92            shouldContain("""at Line_\d+.<init>\(Line_\d+\.jupyter-kts:2\)""".toRegex())93            shouldNotContain(ReplEvalRuntimeException::class.simpleName!!)94        }95    }96    @Test97    fun testDependsOnAnnotation() {98        eval("@file:DependsOn(\"de.erichseifert.gral:gral-core:0.11\")")99    }100    @Test101    fun testImportResolutionAfterFailure() {102        val errorsRes = repl.listErrorsBlocking("import net.pearx.kasechange.*")103        errorsRes.errors shouldHaveSize 1104        val res = eval(105            """106            @file:DependsOn("net.pearx.kasechange:kasechange-jvm:1.3.0")107            import net.pearx.kasechange.*108            1109            """.trimIndent()110        )111        res.resultValue shouldBe 1112    }113    @Test114    fun testDependsOnAnnotationCompletion() {115        eval(116            """117            @file:Repository("https://repo1.maven.org/maven2/")118            @file:DependsOn("com.github.doyaaaaaken:kotlin-csv-jvm:0.7.3")119            """.trimIndent()120        )121        val res = repl.completeBlocking("import com.github.", 18)122        res.shouldBeInstanceOf<CompletionResult.Success>()123        res.sortedMatches().contains("doyaaaaaken")124    }125    @Test126    fun testExternalStaticFunctions() {127        val res = eval(128            """129            @file:DependsOn("src/test/testData/kernelTestPackage-1.0.jar")130            import pack.*131            func()132            """.trimIndent()133        )134        res.resultValue shouldBe 42135    }136    @Test137    fun testScriptIsolation() {138        shouldThrowAny {139            eval("org.jetbrains.kotlinx.jupyter.ReplLineMagics.use")140        }141    }142    @Test143    fun testDependsOnAnnotations() {144        val res = eval(145            """146            @file:DependsOn("de.erichseifert.gral:gral-core:0.11")147            @file:Repository("https://maven.pkg.jetbrains.space/public/p/kotlinx-html/maven")148            @file:DependsOn("org.jetbrains.kotlinx:kotlinx-html-jvm:0.7.2")149            """.trimIndent()150        )151        val newClasspath = res.metadata.newClasspath152        newClasspath shouldHaveAtLeastSize 2153        val htmlLibPath = "org/jetbrains/kotlinx/kotlinx-html-jvm/0.7.2/kotlinx-html-jvm".replace('/', File.separatorChar)154        newClasspath.any { htmlLibPath in it }.shouldBeTrue()155    }156    @Test157    fun testCompletionSimple() {158        eval("val foobar = 42")159        eval("var foobaz = 43")160        val result = repl.completeBlocking("val t = foo", 11)161        result.getOrFail().sortedMatches() shouldBe arrayListOf("foobar", "foobaz")162    }163    @Test164    fun testNoCompletionAfterNumbers() {165        val result = repl.completeBlocking("val t = 42", 10)166        result.getOrFail().sortedMatches().shouldBeEmpty()167    }168    @Test169    fun testCompletionForImplicitReceivers() {170        eval(171            """172            class AClass(val c_prop_x: Int) {173                fun filter(xxx: (AClass).() -> Boolean): AClass {174                    return this175                }176            }177            val AClass.c_prop_y: Int178                get() = c_prop_x * c_prop_x179            180            fun AClass.c_meth_z(v: Int) = v * c_prop_y181            val df = AClass(10)182            val c_zzz = "some string"183            """.trimIndent()184        )185        val result = repl.completeBlocking("df.filter { c_ }", 14)186        result.getOrFail().sortedMatches() shouldBe arrayListOf("c_meth_z(", "c_prop_x", "c_prop_y", "c_zzz")187    }188    @Test189    fun testParametersCompletion() {190        eval("fun f(xyz: Int) = xyz * 2")191        val result = repl.completeBlocking("val t = f(x", 11)192        result.getOrFail().sortedMatches() shouldBe arrayListOf("xyz = ")193    }194    @Test195    fun testDeprecationCompletion() {196        eval(197            """198            @Deprecated("use id() function instead")199            fun id_deprecated(x: Int) = x200            """.trimIndent()201        )202        runBlocking {203            val result = repl.completeBlocking("val t = id_d", 12)204            result.getOrFail().sortedRaw().any {205                it.text == "id_deprecated(" && it.deprecationLevel == DeprecationLevel.WARNING206            }.shouldBeTrue()207        }208    }209    @Test210    fun testErrorsList() {211        eval(212            """213            data class AClass(val memx: Int, val memy: String)214            data class BClass(val memz: String, val mema: AClass)215            val foobar = 42216            var foobaz = "string"217            val v = BClass("KKK", AClass(5, "25"))218            """.trimIndent()219        )220        val result = repl.listErrorsBlocking(221            """222            val a = AClass("42", 3.14)223            val b: Int = "str"224            val c = foob225            """.trimIndent()226        )227        val actualErrors = result.errors.toList()228        val path = actualErrors.first().sourcePath229        actualErrors shouldBe withPath(230            path,231            listOf(232                generateDiagnostic(1, 16, 1, 20, "Type mismatch: inferred type is String but Int was expected", "ERROR"),233                generateDiagnostic(1, 22, 1, 26, "The floating-point literal does not conform to the expected type String", "ERROR"),234                generateDiagnostic(2, 14, 2, 19, "Type mismatch: inferred type is String but Int was expected", "ERROR"),235                generateDiagnostic(3, 9, 3, 13, "Unresolved reference: foob", "ERROR")236            )237        )238    }239    @Test240    fun testFreeCompilerArg() {241        val res = eval(242            """243            @file:CompilerArgs("-opt-in=kotlin.RequiresOptIn")244            """.trimIndent()245        )246        res.resultValue shouldBe Unit247        val actualErrors = repl.listErrorsBlocking(248            """249            import kotlin.time.*250            @OptIn(ExperimentalTime::class)251            val mark = TimeSource.Monotonic.markNow()252            """.trimIndent()253        ).errors.toList()254        actualErrors.shouldBeEmpty()255    }256    @Test257    fun testErrorsListWithMagic() {258        val result = repl.listErrorsBlocking(259            """260            %use krangl261            262            val x = foobar263            3 * 14264            %trackClasspath265            """.trimIndent()266        )267        val actualErrors = result.errors.toList()268        val path = actualErrors.first().sourcePath269        actualErrors shouldBe withPath(270            path,271            listOf(272                generateDiagnostic(3, 9, 3, 15, "Unresolved reference: foobar", "ERROR")273            )274        )275    }276    @Test277    fun testCompletionWithMagic() {278        eval("val foobar = 42")279        val code =280            """281                282            %trackClasspath283        284            foo285            """.trimIndent()286        val result = repl.completeBlocking(code, code.indexOf("foo") + 3)287        result.shouldBeInstanceOf<CompletionResult.Success>()288        result.sortedMatches() shouldBe arrayListOf("foobar")289    }290    @Test291    fun testCommands() {292        val code1 = ":help"293        val code2 = ":hex "294        runBlocking {295            repl.listErrors(code1) { result ->296                result.code shouldBe code1297                result.errors.shouldBeEmpty()298            }299            repl.listErrors(code2) { result ->300                result.code shouldBe code2301                val expectedList = listOf(generateDiagnosticFromAbsolute(code2, 0, 4, "Unknown command", "ERROR"))302                val actualList = result.errors.toList()303                actualList shouldBe expectedList304            }305            repl.complete(code2, 3) { result ->306                result.shouldBeInstanceOf<CompletionResult.Success>()307                result.sortedMatches() shouldBe listOf("help")308            }309        }310    }311    @Test312    fun testEmptyErrorsListJson() {313        val res = ListErrorsResult("someCode")314        Json.encodeToString(serializer(), res.message) shouldBe """{"code":"someCode","errors":[]}"""315    }316    @Test317    fun testOut() {318        eval("1+1", null, 1)319        val res = eval("Out[1]")320        res.resultValue shouldBe 2321        shouldThrowAny { eval("Out[3]") }322    }323    @Test324    fun testNoHistory() {325        eval("1+1", storeHistory = false)326        shouldThrow<ReplEvalRuntimeException> {327            eval("Out[1]")328        }329    }330    @Test331    fun testOutputMagic() {332        eval("%output --max-cell-size=100500 --no-stdout")333        repl.outputConfig shouldBe OutputConfig(334            cellOutputMaxSize = 100500,335            captureOutput = false336        )337        eval("%output --max-buffer=42 --max-buffer-newline=33 --max-time=2000")338        repl.outputConfig shouldBe OutputConfig(339            cellOutputMaxSize = 100500,340            captureOutput = false,341            captureBufferMaxSize = 42,342            captureNewlineBufferSize = 33,343            captureBufferTimeLimitMs = 2000344        )345        eval("%output --reset-to-defaults")346        repl.outputConfig shouldBe OutputConfig()347    }348    @Test349    fun testJavaRuntimeUtils() {350        val result = eval("JavaRuntimeUtils.version")351        val resultVersion = result.resultValue352        val expectedVersion = JavaRuntime.version353        resultVersion shouldBe expectedVersion354    }355    @Test356    fun testKotlinMath() {357        val result = eval("2.0.pow(2.0)").resultValue358        result shouldBe 4.0359    }360    @Test361    fun testNativeLibrary() {362        val libName = "GraphMolWrap"363        val testDataPath = "src/test/testData/nativeTest"364        val jarPath = "$testDataPath/org.RDKit.jar"365        val res = eval(366            """367            @file:DependsOn("$jarPath")368            import org.RDKit.RWMol369            import org.RDKit.RWMol.MolFromSmiles370            Native.loadLibrary(RWMol::class, "$libName", "$testDataPath")371            MolFromSmiles("c1ccccc1")372            """.trimIndent()373        ).resultValue374        res.shouldNotBeNull()375        res::class.qualifiedName shouldBe "org.RDKit.RWMol"376    }377    @Test378    fun testLambdaRendering() {379        val res = eval(380            """381            val foo: (Int) -> Int = {it + 1}382            foo383            """.trimIndent()384        ).resultValue385        @Suppress("UNCHECKED_CAST")386        (res as (Int) -> Int)(1) shouldBe 2387    }388    @Test389    fun testAnonymousObjectRendering() {390        eval("42")391        eval("val sim = object : ArrayList<String>() {}")392        val res = eval("sim").resultValue393        res.toString() shouldBe "[]"394    }395    @Test396    fun testAnonymousObjectCustomRendering() {397        eval("USE { render<ArrayList<*>> { it.size } }")398        eval(399            """400            val sim = object : ArrayList<String>() {}401            sim.add("42")402            """.trimIndent()403        )404        val res = eval("sim").resultValue405        res shouldBe 1406    }407    @Test408    fun testStdlibJdkExtensionsUsage() {409        eval("USE_STDLIB_EXTENSIONS()")410        val res = eval(411            """412            import kotlin.io.path.*413            import java.nio.file.Path414            415            Path.of(".").absolute()416            """.trimIndent()417        ).resultValue418        res.shouldBeInstanceOf<Path>()419    }420    @Test421    fun testArraysRendering() {422        eval("intArrayOf(1, 2, 3)").resultValue.toString() shouldBe "[1, 2, 3]"423        eval("arrayOf(1 to 2, 3 to 4)").resultValue.toString() shouldBe "[(1, 2), (3, 4)]"424        eval("booleanArrayOf(true, false)").resultValue.toString() shouldBe "[true, false]"425    }426    @Test427    fun testOutVarRendering() {428        eval("Out").resultValue.shouldNotBeNull()429    }430    @Test431    fun testMagicsErrorsReporting() {432        "%us".let { code ->433            listErrors(code).errors.toList() shouldBe listOf(generateDiagnosticFromAbsolute(code, 0, 3, "Unknown magic", "ERROR"))434        }435        "%use kmath".let { code ->436            listErrors(code).errors.toList().shouldBeEmpty()437        }438    }439    @Test440    fun testIssue356() {441        eval(442            """443            sealed class BaseObjClass444            object Obj : BaseObjClass()445            val topLevelSequence = sequence {446               yield(Obj)447            }448            open class Base {449                val iter = topLevelSequence.iterator()450            }...

Full Screen

Full Screen

AnalyseMessagesTest.kt

Source:AnalyseMessagesTest.kt Github

copy

Full Screen

...13class AnalyseMessagesTest : FreeSpec({14	"analyseMessages() returns results which" - {15		"given a single passing scenario" - {16			val result = openMessageSample("singlePassingScenario").use { analyseMessages(it) }17			"contains no errors" {18				result.problemCount shouldBe 019			}20		}21		"given a single failing scenario" - {22			val result = openMessageSample("singleFailingScenario").use { analyseMessages(it) }23//			result.appendTo(System.out)24			"contains a single error" {25				result.problemCount shouldBe 126				result.features shouldHaveSize 127				result.features[0].scenarios shouldHaveSize 128			}29			val feature = result.features[0]30			"references the correct feature" {31				feature.feature.name shouldBe "failing"32			}33			val error = feature.scenarios[0]34			"references the correct scenario" {35				error.scenario.name shouldBe "failing"36			}37			"references the correct step" {38				val step = error.step39				step should beInstanceOf(StepInfo::class)40				if(step is StepInfo) {41					step.text shouldBe "it fails"42				}43			}44			"has the correct status" {45				error.status shouldBe FAILED46			}47		}48		"given a single unimplemented scenario" - {49			val result = openMessageSample("singleUnimplementedScenario").use { analyseMessages(it) }50//			result.appendTo(System.out)51			"contains a single error" {52				result.problemCount shouldBe 153				result.features shouldHaveSize 154				result.features[0].scenarios shouldHaveSize 155			}56			"has the correct status" {57				result.features[0].scenarios[0].status shouldBe UNDEFINED58			}59		}60		"given multiple features & scenarios" - {61			val result = openMessageSample("1Failing1Passing1Unimplemented").use { analyseMessages(it) }62//			result.appendTo(System.out)63			"contains the correct number of error" {64				result.problemCount shouldBe 265			}66			"references the correct number of features" {67				result.features shouldHaveSize 268			}69			"associates errors with the correct features and scenarios" {70				result.features.forAll {71					it.scenarios shouldHaveSize 172				}73				result.features.forOne {74					it.feature.name shouldBe "failing"75					val s = it.scenarios[0]76					s.scenario.name shouldBe "failing"77					s.status shouldBe FAILED78				}79				result.features.forOne {80					it.feature.name shouldBe "unimplemented"81					val s = it.scenarios[0]82					s.scenario.name shouldBe "unimplemented"83					s.status shouldBe UNDEFINED84				}85			}86		}87		"given a feature containing rules" - {88			val result = openMessageSample("2RulesWith1ErrorInEach").use { analyseMessages(it) }89//			result.appendTo(System.out)90			"contains the correct number of errors" {91				result.problemCount shouldBe 292				result.features shouldHaveSize 193			}94			val feature = result.features[0]95			"references the correct number of rules" {96				feature.allChildren shouldHaveSize 297				feature.rules shouldHaveSize 298				feature.scenarios should beEmpty()99			}100			"associates errors with the correct rules and scenarios" {101				feature.rules.forAll {102					it.scenarios shouldHaveSize 1103				}104				feature.rules.forOne {105					it.rule.name shouldBe "Rules should be included"106					val s = it.scenarios[0]107					s.scenario.name shouldBe "This should fail"108					s.status shouldBe FAILED109				}110				feature.rules.forOne {111					it.rule.name shouldBe "Multiple rules are allowed"112					val s = it.scenarios[0]113					s.scenario.name shouldBe "This is unimplemented"114					s.status shouldBe UNDEFINED115				}116			}117		}118		"given rules with background steps" - {119			val result = openMessageSample("2RulesWithBackground").use { analyseMessages(it) }120//			result.appendTo(System.out)121			"contains the correct number of errors" {122				result.problemCount shouldBe 2123				result.features shouldHaveSize 1124			}125			val feature = result.features[0]126			"references the correct number of rules" {127				feature.allChildren shouldHaveSize 2128				feature.rules shouldHaveSize 2129				feature.scenarios should beEmpty()130			}131			"references the background when a background step fails" {132				feature.rules.forOne {133					it.rule.name shouldBe("backstories can fail")134					val s = it.scenarios[0]135					s.scenario.name shouldBe "pre-failure"136					val step = s.step137					step should beInstanceOf(BackgroundStepInfo::class)138					if(step is BackgroundStepInfo) {139						step.background.name shouldBe "bad backstory"140					}141				}142			}143			"references the scenario when a scenario step fails" {144				feature.rules.forOne {145					it.rule.name shouldBe("backstories can succeed")146					val s = it.scenarios[0]147					s.scenario.name shouldBe "failure"148					val step = s.step149					step.type shouldBe TestCaseStepType.STEP150				}151			}152		}153		"given a scenario with step variables" - {154			val result = openMessageSample("1ScenarioWithVariables").use { analyseMessages(it) }155//			result.appendTo(System.out)156			"contains a single error" {157				result.problemCount shouldBe 1158				result.features shouldHaveSize 1159				result.features[0].scenarios shouldHaveSize 1160			}161			val error = result.features[0].scenarios[0]162			"references the correct step" {163				(error.step as StepInfo).text shouldBe "3 equals 4"164			}165			"has the correct status" {166				error.status shouldBe FAILED167			}168		}169		"given a scenario outline" - {170			val result = openMessageSample("scenarioOutlineWith3Examples").use { analyseMessages(it) }171//			result.appendTo(System.out)172			"contains the correct number of errors error" {173				result.problemCount shouldBe 2174				result.features shouldHaveSize 1175				result.features[0].scenarios shouldHaveSize 2176			}177			"contains the expected errors" {178				result.features[0].scenarios.forOne {179					it.scenario.name shouldBe "Outline var"180					(it.step as StepInfo).text shouldBe "3 equals 4"181				}182				result.features[0].scenarios.forOne {183					it.scenario.name shouldBe "Outline baz"184					(it.step as StepInfo).text shouldBe "123 equals 3231"185				}186			}187		}188		"given a scenario containing a data table" - {189			val result = openMessageSample("scenarioWithDataTable").use { analyseMessages(it) }190//			result.appendTo(System.out)191			"contains a single error" {192				result.problemCount shouldBe 1193			}194			"references the correct step" {195				(result.features[0].scenarios[0].step as StepInfo).text shouldBe "this table fails:"196			}197		}198		"given a scenario with a failing hook" - {199			val result = openMessageSample("scenarioWithFailingHook").use { analyseMessages(it) }200//			result.appendTo(System.out)201			"contains a single error" {202				result.problemCount shouldBe 1203			}204			"references the failing hook" {205				val scenario = result.features[0].scenarios[0]206				scenario.scenario.name shouldBe "Hook"207				scenario.step.type shouldBe TestCaseStepType.HOOK208			}209		}210	}211})...

Full Screen

Full Screen

InstanceCreatorTest.kt

Source:InstanceCreatorTest.kt Github

copy

Full Screen

...25        )26        context("given provided field value is not null") {27            val expected = InstantiationWithErrors(28                result = ValidClass("value"),29                errors = emptyList()30            )31            should("create class instance correctly") {32                underTest.createInstance(33                    ValidClass::class.java,34                    arguments = listOf(argument.copy(value = "value")),35                    settings = ConversionSettings()36                ).shouldBe(expected)37            }38        }39        context("given provided field value is null") {40            val expected = InstantiationWithErrors(41                result = null,42                errors = listOf(43                    InstantiationError(44                        field = argument.field.name,45                        originalField = argument.originalTargetName,46                        type = InstantiationErrorType.NON_NULLABLE_FIELD_IS_NULL,47                        providedValue = null,48                        cause = null49                    )50                )51            )52            should("instantiation fails with an error") {53                underTest.createInstance(54                    ValidClass::class.java,55                    arguments = listOf(argument.copy(value = null)),56                    settings = ConversionSettings()57                ).shouldBe(expected)58            }59        }60    }61    context("creating an instance of kotlin data with nullable field") {62        data class NullableFieldClass(63            val field: String?64        )65        val argument = InstantiationArgument(66            field = InstantiationField(67                field = NullableFieldClass::field.javaField!!,68                property = NullableFieldClass::field69            ),70            value = "any",71            originalTargetName = "original_field"72        )73        context("given provided field value is not null") {74            val expected = InstantiationWithErrors(75                result = NullableFieldClass("value"),76                errors = emptyList()77            )78            should("create class instance correctly") {79                underTest.createInstance(80                    NullableFieldClass::class.java,81                    arguments = listOf(argument.copy(value = "value")),82                    settings = ConversionSettings()83                ).shouldBe(expected)84            }85        }86        context("given provided field value is null") {87            val expected = InstantiationWithErrors(88                result = NullableFieldClass(null),89                errors = emptyList()90            )91            should("create class instance correctly") {92                underTest.createInstance(93                    NullableFieldClass::class.java,94                    arguments = listOf(argument.copy(value = null)),95                    settings = ConversionSettings()96                ).shouldBe(expected)97            }98        }99    }100    context("given conversion of field fails") {101        data class InstantFieldClass(102            val field: Instant103        )104        val argument = InstantiationArgument(105            field = InstantiationField(106                field = InstantFieldClass::field.javaField!!,107                property = InstantFieldClass::field108            ),109            value = "not_an_instant",110            originalTargetName = "original_field"111        )112        val expected = InstantiationWithErrors(113            result = null,114            errors = listOf(115                InstantiationError(116                    field = argument.field.name,117                    originalField = argument.originalTargetName,118                    type = InstantiationErrorType.CONVERSION_OF_FIELD_FAILED,119                    providedValue = argument.value,120                    cause = null121                )122            )123        )124        should("return an error of conversion failed") {125            val result = underTest.createInstance(126                InstantFieldClass::class.java,127                arguments = listOf(argument),128                settings = ConversionSettings()129            )130            result.result.shouldBeNull()131            result.errors.shouldHaveSize(1)132            result.errors[0].shouldBeEqualToIgnoringFields(133                expected.errors[0],134                InstantiationError::cause135            )136            result.errors[0].cause.shouldNotBeNull()137        }138    }139    context("given an invalid target class") {140        class TestInvalid private constructor(val field: String)141        val argument = InstantiationArgument(142            field = InstantiationField(143                field = TestInvalid::field.javaField!!,144                property = TestInvalid::field145            ),146            value = "any",147            originalTargetName = "original_field"148        )149        should("throw an exception") {150            shouldThrow<InvalidTargetClass> {...

Full Screen

Full Screen

SearchLyricTest.kt

Source:SearchLyricTest.kt Github

copy

Full Screen

...53                    }54                }55            }56            `when`("the song does not exist") {57                val error = TransactionException.RecordNotFound58                val result: Result<Song> = Result.failure(error)59                coEvery { songs.findBy(title, author) } returns value(result)60                justRun { presenter.failure(error) }61                and("the use case is executed") {62                    searchLyric.execute(title, author, presenter)63                    then("the result should be unsuccessful") {64                        verify { presenter.failure(error) }65                    }66                }67            }68        }69    }70    given("a blank song title") {71        val title = ""72        and("a blank author name") {73            val author = ""74            `when`("the use case is executed") {75                val errors = mutableListOf<Throwable>()76                justRun { presenter.failure(capture(errors)) }77                searchLyric.execute(title, author, presenter)78                then("the result should be unsuccessful") {79                    coVerify(exactly = 0) { songs.findBy(title, author) }80                    verify(exactly = 2) { presenter.failure(any()) }81                    errors.should {82                        it.shouldNotBeEmpty()83                        it.size.shouldBe(2)84                        it.first().should { titleBlankError ->85                            titleBlankError.shouldBeInstanceOf<ValidationException.BlankField>()86                            titleBlankError.field.shouldBe(Song::title.name)87                        }88                        it.last().should { authorBlankError ->89                            authorBlankError.shouldBeInstanceOf<ValidationException.BlankField>()90                            authorBlankError.field.shouldBe(Song::author.name)91                        }92                    }93                }94            }95        }...

Full Screen

Full Screen

OrderWithoutIdValidatorTest.kt

Source:OrderWithoutIdValidatorTest.kt Github

copy

Full Screen

...13    describe("validate") {14        val validBeverage = "Valid Order"15        val validUsername = "teadrinker"16        describe("when OrderWithoutId is valid") {17            it("returns empty validation errors") {18                val validOrderWithoutId = OrderWithoutId(validBeverage, validUsername, OrderSize.S.toString())19                val validationErrors: ValidationErrors = OrderWithoutIdValidator.validate(validOrderWithoutId)20                validationErrors.shouldBeEmpty()21            }22        }23        describe("when OrderWithoutId is invalid") {24            val emptyString = ""25            val blankString = "     "26            val oversizeString = "a".repeat(256)27            val blankMessage = "must not be blank"28            val oversizeMessage = "size must be between 1 and 255"29            listOf(30                row(31                    "when beverage is empty",32                    "beverage",33                    OrderWithoutId(emptyString, validUsername, OrderSize.S.toString()),34                    listOf(blankMessage, oversizeMessage)35                ),36                row(37                    "when beverage is blank",38                    "beverage",39                    OrderWithoutId(blankString, validUsername, OrderSize.M.toString()),40                    listOf(blankMessage)41                ),42                row(43                    "when beverage has more than 255 characters",44                    "beverage",45                    OrderWithoutId(oversizeString, validUsername, OrderSize.L.toString()),46                    listOf(oversizeMessage)47                ),48                row(49                    "when username is empty",50                    "username",51                    OrderWithoutId(validBeverage, emptyString, OrderSize.L.toString()),52                    listOf(blankMessage, oversizeMessage)53                ),54                row(55                    "when username is blank",56                    "username",57                    OrderWithoutId(validBeverage, blankString, OrderSize.M.toString()),58                    listOf(blankMessage)59                ),60                row(61                    "when username has more than 255 characters",62                    "username",63                    OrderWithoutId(validBeverage, oversizeString, OrderSize.S.toString()),64                    listOf(oversizeMessage)65                ),66                row(67                    "when size is not S, M or L",68                    "size",69                    OrderWithoutId(validBeverage, validUsername, "XL"),70                    listOf("must be S, M or L")71                ),72            ).map { (73                context: String,74                field: String,75                invalidOrderWithoutId: OrderWithoutId,76                expectedErrors: List<String>77            ) ->78                describe(context) {79                    it("returns error messages: $expectedErrors") {80                        val validationErrors: ValidationErrors = OrderWithoutIdValidator81                            .validate(invalidOrderWithoutId)82                        validationErrors.apply {83                            shouldNotBeEmpty()84                            shouldHaveSize(1)85                            shouldContainKey(field)86                        }87                        val actualErrors: List<String> = validationErrors[field]!!88                        actualErrors.shouldContainExactlyInAnyOrder(expectedErrors)89                    }90                }91            }92        }93    }...

Full Screen

Full Screen

SnowflakeTest.kt

Source:SnowflakeTest.kt Github

copy

Full Screen

...24            checkAll(snowflakes) {25                it.asSnowflake().toString() shouldBe "$it"26            }27        }28        context("Non-safe converts should throw errors comparing their rules") {29            test("String, that hasn't digits") {30                checkAll(Exhaustive.azstring(1..30)) {31                    shouldThrow<IllegalArgumentException> {32                        it.asSnowflake()33                    }.message shouldEndWith "cannot be represented as Snowflake"34                }35            }36            test("Number, that less then 0") {37                checkAll(Arb.long(max = 0).filter { it < 0 }) {38                    shouldThrow<IllegalArgumentException> {39                        it.asSnowflake()40                    }.message shouldBe "id must be greater than 0"41                }42            }43            test("Number, that less then $MIN_SNOWFLAKE") {44                checkAll(arbitrary { it.random.nextLong(MIN_SNOWFLAKE) }) {45                    shouldThrow<IllegalArgumentException> {46                        it.asSnowflake()47                    }.message shouldBe "id must be greater than ${MIN_SNOWFLAKE - 1}"48                }49            }50        }51        context("Safe converts should wrap error in data-type") {52            test("Non-digit string should produce NotANumber") {53                checkAll(Exhaustive.azstring(1..30)) {54                    val snowflake = it.asSnowflakeEither()55                    snowflake.shouldBeLeft() shouldBe NotNumber56                }57            }58            test("Numbers, that less than $MIN_SNOWFLAKE") {59                checkAll(arbitrary { it.random.nextLong(MIN_SNOWFLAKE) }) {60                    val snowflake = it.toString().asSnowflakeEither()61                    snowflake.shouldBeLeft() shouldBe LessThenDiscordEpoch62                }63            }64            test("Right snowflake should unwrap without errors") {65                checkAll(snowflakes) { it.toString().asSnowflakeEither().shouldBeRight() }66            }67        }68    }69}...

Full Screen

Full Screen

UserResourceTest.kt

Source:UserResourceTest.kt Github

copy

Full Screen

1package com.github.hugovallada.user.resource2import com.github.hugovallada.errors.ErrorResponse3import com.github.hugovallada.user.dto.CreateUserRequest4import io.kotest.assertions.print.print5import io.kotest.matchers.nulls.shouldNotBeNull6import io.kotest.matchers.shouldBe7import io.kotest.matchers.shouldHave8import io.kotest.matchers.string.shouldContainIgnoringCase9import io.quarkus.test.junit.QuarkusTest10import io.restassured.RestAssured.given11import io.restassured.http.ContentType.JSON12import org.junit.jupiter.api.Test13@QuarkusTest14class UserResourceTest {15    @Test16    fun `should create an user successfully`() {...

Full Screen

Full Screen

RecipePhotoTest.kt

Source:RecipePhotoTest.kt Github

copy

Full Screen

1package model2import errors.ValidationError3import io.kotest.assertions.throwables.shouldThrow4import io.kotest.core.spec.style.DescribeSpec5import io.kotest.data.row6import io.kotest.matchers.shouldBe7import io.kotest.property.Arb8import io.kotest.property.arbitrary.*9internal class RecipePhotoTest : DescribeSpec({10    it("is created successfully") {11        val intSource = Arb.int(1..100)12        val id = intSource.next()13        val recipeId = intSource.next()14        val name = Arb.string(16).next()15        val data = Arb.byteArrays(intSource, Arb.byte()).next()16        val recipePhoto = RecipePhoto(...

Full Screen

Full Screen

error

Using AI Code Generation

copy

Full Screen

1val data = row(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)2forAll(data) { a ->3a.shouldBeGreaterThan(0)4a.shouldBeLessThan(11)5}6}7}8val data = row(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)9forAll(data) { a ->10a.shouldBeGreaterThan(0)11a.shouldBeLessThan(11)12}13}14Hi, I am trying to use the error() method of io.kotest.data.errors class. I am getting the following error when I run the test: java.lang.NoSuchMethodError: 'io.kotest.data.errors io.kotest.data.errors.error(java.lang.String)'. I am using the following versions of the dependencies: testImplementation("io.kotest:kotest-framework-api-jvm:5.0.0.M5") testImplementation("io.kotest:kotest-framework-engine-jvm:5.0.0.M5") testImplementation("io.kotest:kotest-assertions-core-jvm:5.0.0.M5") testImplementation("io.kotest:kotest-property-jvm:5.0.0.M5") testImplementation("io.kotest:kotest-runner-junit5-jvm:5.0.0.M5") testImplementation("io.kotest:kotest-assertions-arrow-jvm:5.0.0.M5") testImplementation("io.kotest:kotest-assertions-kotlinx-jvm:5.0.0.M5") testImplementation("io.kotest:kotest-assertions-kotlinx-serialization-jvm:5.0.0.M5") testImplementation("io.kotest:kotest-assertions-ktor-jvm:5.0.0.M5") testImplementation("io.kotest:kotest-assertions-kotest-jvm:5.0.0.M5") testImplementation("io.kotest:kotest-assertions-json-jvm:5.0.0.M5") testImplementation("io.kotest:kotest-assertions-shared-jvm:5.0

Full Screen

Full Screen

error

Using AI Code Generation

copy

Full Screen

1val data = table(2row("a", "b"),3row("c", "d"),4row("e", "f")5data.forAll { a, b ->6a.shouldNotBeEmpty()7b.shouldNotBeEmpty()8}9}10}11}

Full Screen

Full Screen

error

Using AI Code Generation

copy

Full Screen

1val list = listOf(1, 2, 3)2val list2 = listOf(4, 5, 6)3val data = table(4row("a", "b", "c"),5row("d", "e", "f")6val list = listOf(1, 2, 3)7val list2 = listOf(4, 5, 6)8val data = table(9row("a", "b", "c"),10row("d", "e", "f")11val list = listOf(1, 2, 3)12val list2 = listOf(4, 5, 6)13val data = table(14row("a", "b", "c"),15row("d", "e", "f")16val list = listOf(1, 2, 3)17val list2 = listOf(4, 5, 6)18val data = table(19row("a", "b", "c"),20row("d", "e", "f")21val list = listOf(1, 2, 3)22val list2 = listOf(4, 5, 6)23val data = table(24row("a", "b", "c"),25row("d", "e", "f")26val list = listOf(1, 2, 3)27val list2 = listOf(4, 5, 6)28val data = table(29row("a", "b", "c"),30row("d", "e", "f")31val list = listOf(1, 2, 3)32val list2 = listOf(4, 5, 6)33val data = table(34row("a", "b", "c"),35row("d", "e", "f")36val list = listOf(1, 2, 3)37val list2 = listOf(4,

Full Screen

Full Screen

error

Using AI Code Generation

copy

Full Screen

1assertThat ( result ). isError (). message (). isNotNull (). contains ( "some string" )2assertThat ( result ). isError (). message (). isNotNull (). contains ( "some string" )3class   StringLengthPropertyTest   :   FunSpec ({4  test ( "string length should return the length of the string" ) {5    checkAll ( StringGenerators . string ()) {6      it . length   ==   stringLength ( it )7    }8  }9})10fun   stringLength ( s :   String ) :   Int   =   s . length

Full Screen

Full Screen

error

Using AI Code Generation

copy

Full Screen

1@ValueSource(strings = ["1", "2", "3"])2fun `should return true`(value: String) {3val result = myClass.myFunction(value)4}5}6}

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 method in errors

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful