How to use Sequence.toString method of io.kotest.matchers.sequences.matchers class

Best Kotest code snippet using io.kotest.matchers.sequences.matchers.Sequence.toString

AnalyzerTest.kt

Source:AnalyzerTest.kt Github

copy

Full Screen

1package com.sourcegraph.semanticdb_kotlinc.test2import com.sourcegraph.semanticdb_kotlinc.*3import com.sourcegraph.semanticdb_kotlinc.Semanticdb.Language.KOTLIN4import com.sourcegraph.semanticdb_kotlinc.Semanticdb.SymbolOccurrence.Role5import com.sourcegraph.semanticdb_kotlinc.Semanticdb.TextDocument6import com.tschuchort.compiletesting.KotlinCompilation7import com.tschuchort.compiletesting.PluginOption8import com.tschuchort.compiletesting.SourceFile9import io.kotest.assertions.assertSoftly10import io.kotest.assertions.fail11import io.kotest.assertions.withClue12import io.kotest.matchers.collections.shouldContain13import io.kotest.matchers.shouldBe14import io.kotest.matchers.shouldNotBe15import java.io.File16import java.nio.file.Path17import kotlin.contracts.ExperimentalContracts18import kotlin.test.Test19import kotlin.test.assertEquals20import org.intellij.lang.annotations.Language21import org.junit.jupiter.api.io.TempDir22@ExperimentalContracts23class AnalyzerTest {24 fun compileSemanticdb(path: Path, @Language("kotlin") code: String): TextDocument {25 val buildPath = File(path.resolve("build").toString()).apply { mkdir() }26 val source = SourceFile.testKt(code)27 lateinit var document: TextDocument28 val result =29 KotlinCompilation()30 .apply {31 sources = listOf(source)32 compilerPlugins = listOf(AnalyzerRegistrar { document = it })33 verbose = false34 pluginOptions =35 listOf(36 PluginOption("semanticdb-kotlinc", "sourceroot", path.toString()),37 PluginOption("semanticdb-kotlinc", "targetroot", buildPath.toString()))38 commandLineProcessors = listOf(AnalyzerCommandLineProcessor())39 workingDir = path.toFile()40 }41 .compile()42 result.exitCode shouldBe KotlinCompilation.ExitCode.OK43 document shouldNotBe null44 return document45 }46 @Test47 fun `basic test`(@TempDir path: Path) {48 val document =49 compileSemanticdb(50 path,51 """52 package sample53 class Banana {54 fun foo() { }55 }""")56 val occurrences =57 arrayOf(58 SymbolOccurrence {59 role = Role.REFERENCE60 symbol = "sample/"61 range {62 startLine = 063 startCharacter = 864 endLine = 065 endCharacter = 1466 }67 },68 SymbolOccurrence {69 role = Role.DEFINITION70 symbol = "sample/Banana#"71 range {72 startLine = 173 startCharacter = 674 endLine = 175 endCharacter = 1276 }77 },78 SymbolOccurrence {79 role = Role.DEFINITION80 symbol = "sample/Banana#foo()."81 range {82 startLine = 283 startCharacter = 884 endLine = 285 endCharacter = 1186 }87 })88 assertSoftly(document.occurrencesList) {89 withClue(this) { occurrences.forEach(::shouldContain) }90 }91 val symbols =92 arrayOf(93 SymbolInformation {94 symbol = "sample/Banana#"95 language = KOTLIN96 displayName = "Banana"97 documentation =98 Documentation {99 format = Semanticdb.Documentation.Format.MARKDOWN100 message = "```kt\npublic final class Banana\n```"101 }102 },103 SymbolInformation {104 symbol = "sample/Banana#foo()."105 language = KOTLIN106 displayName = "foo"107 documentation =108 Documentation {109 format = Semanticdb.Documentation.Format.MARKDOWN110 message = "```kt\npublic final fun foo()\n```"111 }112 })113 assertSoftly(document.symbolsList) { withClue(this) { symbols.forEach(::shouldContain) } }114 }115 @Test116 // shamelessly stolen code snippet from https://learnxinyminutes.com/docs/kotlin/117 fun `learn x in y test`(@TempDir path: Path) {118 val buildPath = File(path.resolve("build").toString()).apply { mkdir() }119 val source =120 SourceFile.testKt(121 """122 @file:Suppress("UNUSED_VARIABLE", "UNUSED_PARAMETER", "NAME_SHADOWING", "ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE", "UNUSED_VALUE")123 package sample124 fun main(args: Array<String>) {125 val fooVal = 10 // we cannot later reassign fooVal to something else126 var fooVar = 10127 fooVar = 20 // fooVar can be reassigned128 /*129 In most cases, Kotlin can determine what the type of a variable is,130 so we don't have to explicitly specify it every time.131 We can explicitly declare the type of a variable like so:132 */133 val foo: Int = 7134 /*135 Strings can be represented in a similar way as in Java.136 Escaping is done with a backslash.137 */138 val fooString = "My String Is Here!"139 val barString = "Printing on a new line?\nNo Problem!"140 val bazString = "Do you want to add a tab?\tNo Problem!"141 println(fooString)142 println(barString)143 println(bazString)144 /*145 Strings can contain template expressions.146 A template expression starts with a dollar sign (${'$'}).147 */148 val fooTemplateString = "$'fooString' has ${"fooString.length"} characters"149 println(fooTemplateString) // => My String Is Here! has 18 characters150 /*151 For a variable to hold null it must be explicitly specified as nullable.152 A variable can be specified as nullable by appending a ? to its type.153 We can access a nullable variable by using the ?. operator.154 We can use the ?: operator to specify an alternative value to use155 if a variable is null.156 */157 var fooNullable: String? = "abc"158 println(fooNullable?.length) // => 3159 println(fooNullable?.length ?: -1) // => 3160 fooNullable = null161 println(fooNullable?.length) // => null162 println(fooNullable?.length ?: -1) // => -1163 /*164 Functions can be declared using the "fun" keyword.165 Function arguments are specified in brackets after the function name.166 Function arguments can optionally have a default value.167 The function return type, if required, is specified after the arguments.168 */169 fun hello(name: String = "world"): String {170 return "Hello, $'name'!"171 }172 println(hello("foo")) // => Hello, foo!173 println(hello(name = "bar")) // => Hello, bar!174 println(hello()) // => Hello, world!175 /*176 A function parameter may be marked with the "vararg" keyword177 to allow a variable number of arguments to be passed to the function.178 */179 fun varargExample(vararg names: Int) {180 println("Argument has ${"names.size"} elements")181 }182 varargExample() // => Argument has 0 elements183 varargExample(1) // => Argument has 1 elements184 varargExample(1, 2, 3) // => Argument has 3 elements185 /*186 When a function consists of a single expression then the curly brackets can187 be omitted. The body is specified after the = symbol.188 */189 fun odd(x: Int): Boolean = x % 2 == 1190 println(odd(6)) // => false191 println(odd(7)) // => true192 // If the return type can be inferred then we don't need to specify it.193 fun even(x: Int) = x % 2 == 0194 println(even(6)) // => true195 println(even(7)) // => false196 // Functions can take functions as arguments and return functions.197 fun not(f: (Int) -> Boolean): (Int) -> Boolean {198 return {n -> !f.invoke(n)}199 }200 // Named functions can be specified as arguments using the :: operator.201 val notOdd = not(::odd)202 val notEven = not(::even)203 // Lambda expressions can be specified as arguments.204 val notZero = not {n -> n == 0}205 /*206 If a lambda has only one parameter207 then its declaration can be omitted (along with the ->).208 The name of the single parameter will be "it".209 */210 val notPositive = not {it > 0}211 for (i in 0..4) {212 println("${"notOdd(i)"} ${"notEven(i)"} ${"notZero(i)"} ${"notPositive(i)"}")213 }214 // The "class" keyword is used to declare classes.215 class ExampleClass(val x: Int) {216 fun memberFunction(y: Int): Int {217 return x + y218 }219 infix fun infixMemberFunction(y: Int): Int {220 return x * y221 }222 }223 /*224 To create a new instance we call the constructor.225 Note that Kotlin does not have a "new" keyword.226 */227 val fooExampleClass = ExampleClass(7)228 // Member functions can be called using dot notation.229 println(fooExampleClass.memberFunction(4)) // => 11230 /*231 If a function has been marked with the "infix" keyword then it can be232 called using infix notation.233 */234 println(fooExampleClass infixMemberFunction 4) // => 28235 /*236 Data classes are a concise way to create classes that just hold data.237 The "hashCode"/"equals" and "toString" methods are automatically generated.238 */239 data class DataClassExample (val x: Int, val y: Int, val z: Int)240 val fooData = DataClassExample(1, 2, 4)241 println(fooData) // => DataClassExample(x=1, y=2, z=4)242 // Data classes have a "copy" function.243 val fooCopy = fooData.copy(y = 100)244 println(fooCopy) // => DataClassExample(x=1, y=100, z=4)245 // Objects can be destructured into multiple variables.246 val (a, b, c) = fooCopy247 println("$'a' $'b' $'c'") // => 1 100 4248 // destructuring in "for" loop249 for ((a, b, c) in listOf(fooData)) {250 println("$'a' $'b' $'c'") // => 1 2 4251 }252 val mapData = mapOf("a" to 1, "b" to 2)253 // Map.Entry is destructurable as well254 for ((key, value) in mapData) {255 println("$'key' -> $'value'")256 }257 // The "with" function is similar to the JavaScript "with" statement.258 data class MutableDataClassExample (var x: Int, var y: Int, var z: Int)259 val fooMutableData = MutableDataClassExample(7, 4, 9)260 with (fooMutableData) {261 x -= 2262 y += 2263 z--264 }265 println(fooMutableData) // => MutableDataClassExample(x=5, y=6, z=8)266 /*267 We can create a list using the "listOf" function.268 The list will be immutable - elements cannot be added or removed.269 */270 val fooList = listOf("a", "b", "c")271 println(fooList.size) // => 3272 println(fooList.first()) // => a273 println(fooList.last()) // => c274 // Elements of a list can be accessed by their index.275 println(fooList[1]) // => b276 // A mutable list can be created using the "mutableListOf" function.277 val fooMutableList = mutableListOf("a", "b", "c")278 fooMutableList.add("d")279 println(fooMutableList.last()) // => d280 println(fooMutableList.size) // => 4281 // We can create a set using the "setOf" function.282 val fooSet = setOf("a", "b", "c")283 println(fooSet.contains("a")) // => true284 println(fooSet.contains("z")) // => false285 // We can create a map using the "mapOf" function.286 val fooMap = mapOf("a" to 8, "b" to 7, "c" to 9)287 // Map values can be accessed by their key.288 println(fooMap["a"]) // => 8289 /*290 Sequences represent lazily-evaluated collections.291 We can create a sequence using the "generateSequence" function.292 */293 val fooSequence = generateSequence(1, { it + 1 })294 val x = fooSequence.take(10).toList()295 println(x) // => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]296 // An example of using a sequence to generate Fibonacci numbers:297 fun fibonacciSequence(): Sequence<Long> {298 var a = 0L299 var b = 1L300 fun next(): Long {301 val result = a + b302 a = b303 b = result304 return a305 }306 return generateSequence(::next)307 }308 val y = fibonacciSequence().take(10).toList()309 println(y) // => [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]310 // Kotlin provides higher-order functions for working with collections.311 val z = (1..9).map {it * 3}312 .filter {it < 20}313 .groupBy {it % 2 == 0}314 .mapKeys {if (it.key) "even" else "odd"}315 println(z) // => {odd=[3, 9, 15], even=[6, 12, 18]}316 // A "for" loop can be used with anything that provides an iterator.317 for (c in "hello") {318 println(c)319 }320 // "while" loops work in the same way as other languages.321 var ctr = 0322 while (ctr < 5) {323 println(ctr)324 ctr++325 }326 do {327 println(ctr)328 ctr++329 } while (ctr < 10)330 /*331 "if" can be used as an expression that returns a value.332 For this reason the ternary ?: operator is not needed in Kotlin.333 */334 val num = 5335 val message = if (num % 2 == 0) "even" else "odd"336 println("$'num' is $'message'") // => 5 is odd337 // "when" can be used as an alternative to "if-else if" chains.338 val i = 10339 when {340 i < 7 -> println("first block")341 fooString.startsWith("hello") -> println("second block")342 else -> println("else block")343 }344 // "when" can be used with an argument.345 when (i) {346 0, 21 -> println("0 or 21")347 in 1..20 -> println("in the range 1 to 20")348 else -> println("none of the above")349 }350 // "when" can be used as a function that returns a value.351 var result = when (i) {352 0, 21 -> "0 or 21"353 in 1..20 -> "in the range 1 to 20"354 else -> "none of the above"355 }356 println(result)357 /*358 We can check if an object is of a particular type by using the "is" operator.359 If an object passes a type check then it can be used as that type without360 explicitly casting it.361 */362 fun smartCastExample(x: Any) : Boolean {363 if (x is Boolean) {364 // x is automatically cast to Boolean365 return x366 } else if (x is Int) {367 // x is automatically cast to Int368 return x > 0369 } else if (x is String) {370 // x is automatically cast to String371 return x.isNotEmpty()372 } else {373 return false374 }375 }376 println(smartCastExample("Hello, world!")) // => true377 println(smartCastExample("")) // => false378 println(smartCastExample(5)) // => true379 println(smartCastExample(0)) // => false380 println(smartCastExample(true)) // => true381 // Smartcast also works with when block382 fun smartCastWhenExample(x: Any) = when (x) {383 is Boolean -> x384 is Int -> x > 0385 is String -> x.isNotEmpty()386 else -> false387 }388 /*389 Extensions are a way to add new functionality to a class.390 This is similar to C# extension methods.391 */392 fun String.remove(c: Char): String {393 return this.filter {it != c}394 }395 println("Hello, world!".remove('l')) // => Heo, word!396 }397 // Enum classes are similar to Java enum types.398 enum class EnumExample {399 A, B, C // Enum constants are separated with commas.400 }401 fun printEnum() = println(EnumExample.A) // => A402 // Since each enum is an instance of the enum class, they can be initialized as:403 enum class EnumExample1(val value: Int) {404 A(value = 1),405 B(value = 2),406 C(value = 3)407 }408 fun printProperty() = println(EnumExample1.A.value) // => 1409 410 // Every enum has properties to obtain its name and ordinal(position) in the enum class declaration:411 fun printName() = println(EnumExample1.A.name) // => A412 fun printPosition() = println(EnumExample1.A.ordinal) // => 0413 /*414 The "object" keyword can be used to create singleton objects.415 We cannot instantiate it but we can refer to its unique instance by its name.416 This is similar to Scala singleton objects.417 */418 object ObjectExample {419 fun hello(): String {420 return "hello"421 }422 override fun toString(): String {423 return "Hello, it's me, ${"ObjectExample::class.simpleName"}"424 }425 }426 fun useSingletonObject() {427 println(ObjectExample.hello()) // => hello428 // In Kotlin, "Any" is the root of the class hierarchy, just like "Object" is in Java429 val someRef: Any = ObjectExample430 println(someRef) // => Hello, it's me, ObjectExample431 }432 /* The not-null assertion operator (!!) converts any value to a non-null type and433 throws an exception if the value is null.434 */435 var b: String? = "abc"436 val l = b!!.length437 data class Counter(var value: Int) {438 // overload Counter += Int439 operator fun plusAssign(increment: Int) {440 this.value += increment441 }442 // overload Counter++ and ++Counter443 operator fun inc() = Counter(value + 1)444 // overload Counter + Counter445 operator fun plus(other: Counter) = Counter(this.value + other.value)446 // overload Counter * Counter447 operator fun times(other: Counter) = Counter(this.value * other.value)448 // overload Counter * Int449 operator fun times(value: Int) = Counter(this.value * value)450 // overload Counter in Counter451 operator fun contains(other: Counter) = other.value == this.value452 // overload Counter[Int] = Int453 operator fun set(index: Int, value: Int) {454 this.value = index + value455 }456 // overload Counter instance invocation457 operator fun invoke() = println("The value of the counter is $'value'")458 }459 /* You can also overload operators through extension methods */460 // overload -Counter461 operator fun Counter.unaryMinus() = Counter(-this.value)462 fun operatorOverloadingDemo() {463 var counter1 = Counter(0)464 var counter2 = Counter(5)465 counter1 += 7466 println(counter1) // => Counter(value=7)467 println(counter1 + counter2) // => Counter(value=12)468 println(counter1 * counter2) // => Counter(value=35)469 println(counter2 * 2) // => Counter(value=10)470 println(counter1 in Counter(5)) // => false471 println(counter1 in Counter(7)) // => true472 counter1[26] = 10473 println(counter1) // => Counter(value=36)474 counter1() // => The value of the counter is 36475 println(-counter2) // => Counter(value=-5)476 }477 """)478 val result =479 KotlinCompilation()480 .apply {481 sources = listOf(source)482 compilerPlugins = listOf(AnalyzerRegistrar())483 verbose = false484 pluginOptions =485 listOf(486 PluginOption("semanticdb-kotlinc", "sourceroot", path.toString()),487 PluginOption("semanticdb-kotlinc", "targetroot", buildPath.toString()))488 commandLineProcessors = listOf(AnalyzerCommandLineProcessor())489 workingDir = path.toFile()490 }491 .compile()492 result.exitCode shouldBe KotlinCompilation.ExitCode.OK493 }494 @Test495 fun documentation(@TempDir path: Path) {496 val document =497 compileSemanticdb(498 path,499 """500 package sample501 import java.io.Serializable502 abstract class DocstringSuperclass503 /** Example class docstring */504 class Docstrings: DocstringSuperclass(), Serializable505 506 /** 507 * Example method docstring508 *509 **/510 inline fun docstrings(msg: String): Int { return msg.length }511 """.trimIndent())512 document.assertDocumentation("sample/Docstrings#", "Example class docstring")513 document.assertDocumentation("sample/TestKt#docstrings().", "Example method docstring")514 }515 private fun TextDocument.assertDocumentation(symbol: String, expectedDocumentation: String) {516 val markdown =517 this.symbolsList.find { it.symbol == symbol }?.documentation?.message518 ?: fail("no documentation for symbol $symbol")519 val obtainedDocumentation = markdown.split("----").last().trim()520 assertEquals(expectedDocumentation, obtainedDocumentation)521 }522}...

Full Screen

Full Screen

matchers.kt

Source:matchers.kt Github

copy

Full Screen

1package io.kotest.matchers.sequences2import io.kotest.matchers.Matcher3import io.kotest.matchers.MatcherResult4import io.kotest.matchers.neverNullMatcher5import io.kotest.matchers.should6import io.kotest.matchers.shouldHave7import io.kotest.matchers.shouldNot8private fun <T> Sequence<T>.toString(limit: Int = 10) = this.joinToString(", ", limit = limit)9/*10How should infinite sequences be detected, and how should they be dealt with?11Sequence<T>.count() may run through the whole sequence (sequences from `generateSequence()` do so), so isn't always a safe way to detect infinite sequences.12For now, the documentation should mention that infinite sequences will cause these matchers never to halt.13*/14fun <T> Sequence<T>.shouldContainOnlyNulls() = this should containOnlyNulls()15fun <T> Sequence<T>.shouldNotContainOnlyNulls() = this shouldNot containOnlyNulls()16fun <T> containOnlyNulls() = object : Matcher<Sequence<T>> {17 override fun test(value: Sequence<T>) =18 MatcherResult(19 value.all { it == null },20 "Sequence should contain only nulls",21 "Sequence should not contain only nulls"22 )23}24fun <T> Sequence<T>.shouldContainNull() = this should containNull()25fun <T> Sequence<T>.shouldNotContainNull() = this shouldNot containNull()26fun <T> containNull() = object : Matcher<Sequence<T>> {27 override fun test(value: Sequence<T>) =28 MatcherResult(29 value.any { it == null },30 "Sequence should contain at least one null",31 "Sequence should not contain any nulls"32 )33}34fun <T> Sequence<T>.shouldHaveElementAt(index: Int, element: T) = this should haveElementAt(index, element)35fun <T> Sequence<T>.shouldNotHaveElementAt(index: Int, element: T) = this shouldNot haveElementAt(index, element)36fun <T, S : Sequence<T>> haveElementAt(index: Int, element: T) = object : Matcher<S> {37 override fun test(value: S) =38 MatcherResult(39 value.elementAt(index) == element,40 { "Sequence should contain $element at index $index" },41 { "Sequence should not contain $element at index $index" }42 )43}44fun <T> Sequence<T>.shouldContainNoNulls() = this should containNoNulls()45fun <T> Sequence<T>.shouldNotContainNoNulls() = this shouldNot containNoNulls()46fun <T> containNoNulls() = object : Matcher<Sequence<T>> {47 override fun test(value: Sequence<T>) =48 MatcherResult(49 value.all { it != null },50 { "Sequence should not contain nulls" },51 { "Sequence should have at least one null" }52 )53}54infix fun <T, C : Sequence<T>> C.shouldContain(t: T) = this should contain(t)55infix fun <T, C : Sequence<T>> C.shouldNotContain(t: T) = this shouldNot contain(t)56fun <T, C : Sequence<T>> contain(t: T) = object : Matcher<C> {57 override fun test(value: C) = MatcherResult(58 value.contains(t),59 { "Sequence should contain element $t" },60 { "Sequence should not contain element $t" }61 )62}63infix fun <T, C : Sequence<T>> C?.shouldNotContainExactly(expected: C) = this shouldNot containExactly(expected)64fun <T, C : Sequence<T>> C?.shouldNotContainExactly(vararg expected: T) = this shouldNot containExactly(*expected)65infix fun <T, C : Sequence<T>> C?.shouldContainExactly(expected: C) = this should containExactly(expected)66fun <T, C : Sequence<T>> C?.shouldContainExactly(vararg expected: T) = this should containExactly(*expected)67fun <T> containExactly(vararg expected: T): Matcher<Sequence<T>?> = containExactly(expected.asSequence())68/** Assert that a sequence contains exactly the given values and nothing else, in order. */69fun <T, C : Sequence<T>> containExactly(expected: C): Matcher<C?> = neverNullMatcher { value ->70 var passed: Boolean = value.count() == expected.count()71 var failMessage = "Sequence should contain exactly $expected but was $value"72 if (passed) {73 val diff = value.zip(expected) { a, b -> Triple(a, b, a == b) }.withIndex().find { !it.value.third }74 if (diff != null) {75 passed = false76 failMessage += " (expected ${diff.value.second} at ${diff.index} but found ${diff.value.first})"77 }78 } else {79 failMessage += " (expected ${expected.count()} elements but found ${value.count()})"80 }81 MatcherResult(82 passed,83 failMessage,84 "Sequence should not be exactly $expected"85 )86}87@Deprecated("use shouldNotContainAllInAnyOrder", ReplaceWith("shouldNotContainAllInAnyOrder"))88infix fun <T, C : Sequence<T>> C?.shouldNotContainExactlyInAnyOrder(expected: C) =89 this shouldNot containAllInAnyOrder(expected)90@Deprecated("use shouldNotContainAllInAnyOrder", ReplaceWith("shouldNotContainAllInAnyOrder"))91fun <T, C : Sequence<T>> C?.shouldNotContainExactlyInAnyOrder(vararg expected: T) =92 this shouldNot containAllInAnyOrder(*expected)93@Deprecated("use shouldContainAllInAnyOrder", ReplaceWith("shouldContainAllInAnyOrder"))94infix fun <T, C : Sequence<T>> C?.shouldContainExactlyInAnyOrder(expected: C) =95 this should containAllInAnyOrder(expected)96@Deprecated("use shouldContainAllInAnyOrder", ReplaceWith("shouldContainAllInAnyOrder"))97fun <T, C : Sequence<T>> C?.shouldContainExactlyInAnyOrder(vararg expected: T) =98 this should containAllInAnyOrder(*expected)99@Deprecated("use containAllInAnyOrder", ReplaceWith("containAllInAnyOrder"))100fun <T> containExactlyInAnyOrder(vararg expected: T): Matcher<Sequence<T>?> =101 containAllInAnyOrder(expected.asSequence())102@Deprecated("use containAllInAnyOrder", ReplaceWith("containAllInAnyOrder"))103/** Assert that a sequence contains the given values and nothing else, in any order. */104fun <T, C : Sequence<T>> containExactlyInAnyOrder(expected: C): Matcher<C?> = containAllInAnyOrder(expected)105infix fun <T, C : Sequence<T>> C?.shouldNotContainAllInAnyOrder(expected: C) =106 this shouldNot containAllInAnyOrder(expected)107fun <T, C : Sequence<T>> C?.shouldNotContainAllInAnyOrder(vararg expected: T) =108 this shouldNot containAllInAnyOrder(*expected)109infix fun <T, C : Sequence<T>> C?.shouldContainAllInAnyOrder(expected: C) =110 this should containAllInAnyOrder(expected)111fun <T, C : Sequence<T>> C?.shouldContainAllInAnyOrder(vararg expected: T) =112 this should containAllInAnyOrder(*expected)113fun <T> containAllInAnyOrder(vararg expected: T): Matcher<Sequence<T>?> =114 containAllInAnyOrder(expected.asSequence())115/** Assert that a sequence contains all the given values and nothing else, in any order. */116fun <T, C : Sequence<T>> containAllInAnyOrder(expected: C): Matcher<C?> = neverNullMatcher { value ->117 val passed = value.count() == expected.count() && expected.all { value.contains(it) }118 MatcherResult(119 passed,120 { "Sequence should contain the values of $expected in any order, but was $value" },121 { "Sequence should not contain the values of $expected in any order" }122 )123}124infix fun <T : Comparable<T>, C : Sequence<T>> C.shouldHaveUpperBound(t: T) = this should haveUpperBound(t)125fun <T : Comparable<T>, C : Sequence<T>> haveUpperBound(t: T) = object : Matcher<C> {126 override fun test(value: C) = MatcherResult(127 (value.maxOrNull() ?: t) <= t,128 { "Sequence should have upper bound $t" },129 { "Sequence should not have upper bound $t" }130 )131}132infix fun <T : Comparable<T>, C : Sequence<T>> C.shouldHaveLowerBound(t: T) = this should haveLowerBound(t)133fun <T : Comparable<T>, C : Sequence<T>> haveLowerBound(t: T) = object : Matcher<C> {134 override fun test(value: C) = MatcherResult(135 (value.minOrNull() ?: t) >= t,136 { "Sequence should have lower bound $t" },137 { "Sequence should not have lower bound $t" }138 )139}140fun <T> Sequence<T>.shouldBeUnique() = this should beUnique()141fun <T> Sequence<T>.shouldNotBeUnique() = this shouldNot beUnique()142fun <T> beUnique() = object : Matcher<Sequence<T>> {143 override fun test(value: Sequence<T>) = MatcherResult(144 value.toSet().size == value.count(),145 { "Sequence should be Unique" },146 { "Sequence should contain at least one duplicate element" }147 )148}149fun <T> Sequence<T>.shouldContainDuplicates() = this should containDuplicates()150fun <T> Sequence<T>.shouldNotContainDuplicates() = this shouldNot containDuplicates()151fun <T> containDuplicates() = object : Matcher<Sequence<T>> {152 override fun test(value: Sequence<T>) = MatcherResult(153 value.toSet().size < value.count(),154 { "Sequence should contain duplicates" },155 { "Sequence should not contain duplicates" }156 )157}158fun <T : Comparable<T>> Sequence<T>.shouldBeSorted() = this should beSorted()159fun <T : Comparable<T>> Sequence<T>.shouldNotBeSorted() = this shouldNot beSorted()160fun <T : Comparable<T>> beSorted(): Matcher<Sequence<T>> = sorted()161fun <T : Comparable<T>> sorted(): Matcher<Sequence<T>> = object : Matcher<Sequence<T>> {162 override fun test(value: Sequence<T>): MatcherResult {163 @Suppress("UNUSED_DESTRUCTURED_PARAMETER_ENTRY")164 val failure = value.zipWithNext().withIndex().firstOrNull { (i, it) -> it.first > it.second }165 val snippet = value.joinToString(",", limit = 10)166 val elementMessage = when (failure) {167 null -> ""168 else -> ". Element ${failure.value.first} at index ${failure.index} was greater than element ${failure.value.second}"169 }170 return MatcherResult(171 failure == null,172 { "Sequence $snippet should be sorted$elementMessage" },173 { "Sequence $snippet should not be sorted" }174 )175 }176}177infix fun <T> Sequence<T>.shouldBeSortedWith(comparator: Comparator<in T>) = this should beSortedWith(comparator)178infix fun <T> Sequence<T>.shouldBeSortedWith(cmp: (T, T) -> Int) = this should beSortedWith(cmp)179fun <T> beSortedWith(comparator: Comparator<in T>): Matcher<Sequence<T>> = sortedWith(comparator)180fun <T> beSortedWith(cmp: (T, T) -> Int): Matcher<Sequence<T>> = sortedWith(cmp)181fun <T> sortedWith(comparator: Comparator<in T>): Matcher<Sequence<T>> = sortedWith { a, b ->182 comparator.compare(a, b)183}184fun <T> sortedWith(cmp: (T, T) -> Int): Matcher<Sequence<T>> = object : Matcher<Sequence<T>> {185 override fun test(value: Sequence<T>): MatcherResult {186 @Suppress("UNUSED_DESTRUCTURED_PARAMETER_ENTRY")187 val failure = value.zipWithNext().withIndex().firstOrNull { (i, it) -> cmp(it.first, it.second) > 0 }188 val snippet = value.joinToString(",", limit = 10)189 val elementMessage = when (failure) {190 null -> ""191 else -> ". Element ${failure.value.first} at index ${failure.index} shouldn't precede element ${failure.value.second}"192 }193 return MatcherResult(194 failure == null,195 { "Sequence $snippet should be sorted$elementMessage" },196 { "Sequence $snippet should not be sorted" }197 )198 }199}200infix fun <T> Sequence<T>.shouldNotBeSortedWith(comparator: Comparator<in T>) = this shouldNot beSortedWith(comparator)201infix fun <T> Sequence<T>.shouldNotBeSortedWith(cmp: (T, T) -> Int) = this shouldNot beSortedWith(cmp)202infix fun <T> Sequence<T>.shouldHaveSingleElement(t: T) = this should singleElement(t)203infix fun <T> Sequence<T>.shouldNotHaveSingleElement(t: T) = this shouldNot singleElement(t)204fun <T> singleElement(t: T) = object : Matcher<Sequence<T>> {205 override fun test(value: Sequence<T>) = MatcherResult(206 value.count() == 1 && value.first() == t,207 { "Sequence should be a single element of $t but has ${value.count()} elements" },208 { "Sequence should not be a single element of $t" }209 )210}211infix fun <T> Sequence<T>.shouldHaveCount(count: Int) = this should haveCount(count)212infix fun <T> Sequence<T>.shouldNotHaveCount(count: Int) = this shouldNot haveCount(213 count)214infix fun <T> Sequence<T>.shouldHaveSize(size: Int) = this should haveCount(size)215infix fun <T> Sequence<T>.shouldNotHaveSize(size: Int) = this shouldNot haveCount(size)216//fun <T> haveSize(size: Int) = haveCount(size)217fun <T> haveSize(size: Int): Matcher<Sequence<T>> = haveCount(size)218fun <T> haveCount(count: Int): Matcher<Sequence<T>> = object : Matcher<Sequence<T>> {219 override fun test(value: Sequence<T>) =220 MatcherResult(221 value.count() == count,222 { "Sequence should have count $count but has count ${value.count()}" },223 { "Sequence should not have count $count" }224 )225}226infix fun <T, U> Sequence<T>.shouldBeLargerThan(other: Sequence<U>) = this should beLargerThan(other)227fun <T, U> beLargerThan(other: Sequence<U>) = object : Matcher<Sequence<T>> {228 override fun test(value: Sequence<T>) = MatcherResult(229 value.count() > other.count(),230 { "Sequence of count ${value.count()} should be larger than sequence of count ${other.count()}" },231 { "Sequence of count ${value.count()} should not be larger than sequence of count ${other.count()}" }232 )233}234infix fun <T, U> Sequence<T>.shouldBeSmallerThan(other: Sequence<U>) = this should beSmallerThan(other)235fun <T, U> beSmallerThan(other: Sequence<U>) = object : Matcher<Sequence<T>> {236 override fun test(value: Sequence<T>) = MatcherResult(237 value.count() < other.count(),238 { "Sequence of count ${value.count()} should be smaller than sequence of count ${other.count()}" },239 { "Sequence of count ${value.count()} should not be smaller than sequence of count ${other.count()}" }240 )241}242infix fun <T, U> Sequence<T>.shouldBeSameCountAs(other: Sequence<U>) = this should beSameCountAs(243 other)244fun <T, U> beSameCountAs(other: Sequence<U>) = object : Matcher<Sequence<T>> {245 override fun test(value: Sequence<T>) = MatcherResult(246 value.count() == other.count(),247 { "Sequence of count ${value.count()} should be the same count as sequence of count ${other.count()}" },248 { "Sequence of count ${value.count()} should not be the same count as sequence of count ${other.count()}" }249 )250}251infix fun <T, U> Sequence<T>.shouldBeSameSizeAs(other: Sequence<U>) = this.shouldBeSameCountAs(other)252infix fun <T> Sequence<T>.shouldHaveAtLeastCount(n: Int) = this shouldHave atLeastCount(n)253fun <T> atLeastCount(n: Int) = object : Matcher<Sequence<T>> {254 override fun test(value: Sequence<T>) = MatcherResult(255 value.count() >= n,256 { "Sequence should contain at least $n elements" },257 { "Sequence should contain less than $n elements" }258 )259}260infix fun <T> Sequence<T>.shouldHaveAtLeastSize(n: Int) = this.shouldHaveAtLeastCount(n)261infix fun <T> Sequence<T>.shouldHaveAtMostCount(n: Int) = this shouldHave atMostCount(n)262fun <T> atMostCount(n: Int) = object : Matcher<Sequence<T>> {263 override fun test(value: Sequence<T>) = MatcherResult(264 value.count() <= n,265 { "Sequence should contain at most $n elements" },266 { "Sequence should contain more than $n elements" }267 )268}269infix fun <T> Sequence<T>.shouldHaveAtMostSize(n: Int) = this shouldHave atMostCount(n)270infix fun <T> Sequence<T>.shouldExist(p: (T) -> Boolean) = this should exist(p)271fun <T> exist(p: (T) -> Boolean) = object : Matcher<Sequence<T>> {272 override fun test(value: Sequence<T>) = MatcherResult(273 value.any { p(it) },274 { "Sequence should contain an element that matches the predicate $p" },275 { "Sequence should not contain an element that matches the predicate $p" }276 )277}278fun <T : Comparable<T>> Sequence<T>.shouldContainInOrder(vararg ts: T) =279 this should containsInOrder(ts.asSequence())280infix fun <T : Comparable<T>> Sequence<T>.shouldContainInOrder(expected: Sequence<T>) =281 this should containsInOrder(expected)282fun <T : Comparable<T>> Sequence<T>.shouldNotContainInOrder(expected: Sequence<T>) =283 this shouldNot containsInOrder(expected)284/** Assert that a sequence contains a given subsequence, possibly with values in between. */285fun <T> containsInOrder(subsequence: Sequence<T>): Matcher<Sequence<T>?> = neverNullMatcher { actual ->286 val subsequenceCount = subsequence.count()287 require(subsequenceCount > 0) { "expected values must not be empty" }288 var subsequenceIndex = 0289 val actualIterator = actual.iterator()290 while (actualIterator.hasNext() && subsequenceIndex < subsequenceCount) {291 if (actualIterator.next() == subsequence.elementAt(subsequenceIndex)) subsequenceIndex += 1292 }293 MatcherResult(294 subsequenceIndex == subsequence.count(),295 { "[$actual] did not contain the elements [$subsequence] in order" },296 { "[$actual] should not contain the elements [$subsequence] in order" }297 )298}299fun <T> Sequence<T>.shouldBeEmpty() = this should beEmpty()300fun <T> Sequence<T>.shouldNotBeEmpty() = this shouldNot beEmpty()301fun <T> beEmpty(): Matcher<Sequence<T>> = object : Matcher<Sequence<T>> {302 override fun test(value: Sequence<T>): MatcherResult = MatcherResult(303 value.count() == 0,304 { "Sequence should be empty" },305 { "Sequence should not be empty" }306 )307}308fun <T> Sequence<T>.shouldContainAll(vararg ts: T) = this should containAll(ts.asSequence())309infix fun <T> Sequence<T>.shouldContainAll(ts: Collection<T>) = this should containAll(ts.asSequence())310infix fun <T> Sequence<T>.shouldContainAll(ts: Sequence<T>) = this should containAll(ts)311fun <T> Sequence<T>.shouldNotContainAll(vararg ts: T) = this shouldNot containAll(ts.asSequence())312infix fun <T> Sequence<T>.shouldNotContainAll(ts: Collection<T>) = this shouldNot containAll(ts.asSequence())313infix fun <T> Sequence<T>.shouldNotContainAll(ts: Sequence<T>) = this shouldNot containAll(ts)314fun <T, C : Sequence<T>> containAll(ts: C): Matcher<Sequence<T>> = object : Matcher<Sequence<T>> {315 override fun test(value: Sequence<T>): MatcherResult = MatcherResult(316 ts.all { value.contains(it) },317 { "Sequence should contain all of ${value.joinToString(",", limit = 10)}" },318 { "Sequence should not contain all of ${value.joinToString(",", limit = 10)}" }319 )320}...

Full Screen

Full Screen

ReplTests.kt

Source:ReplTests.kt Github

copy

Full Screen

1package org.jetbrains.kotlinx.jupyter.test.repl2import io.kotest.assertions.throwables.shouldThrow3import io.kotest.assertions.throwables.shouldThrowAny4import io.kotest.matchers.booleans.shouldBeTrue5import io.kotest.matchers.collections.shouldBeEmpty6import io.kotest.matchers.collections.shouldHaveAtLeastSize7import io.kotest.matchers.nulls.shouldNotBeNull8import io.kotest.matchers.sequences.shouldBeEmpty9import io.kotest.matchers.sequences.shouldHaveSize10import io.kotest.matchers.shouldBe11import io.kotest.matchers.string.shouldContain12import io.kotest.matchers.string.shouldNotContain13import io.kotest.matchers.types.shouldBeInstanceOf14import jupyter.kotlin.JavaRuntime15import kotlinx.coroutines.runBlocking16import kotlinx.serialization.json.Json17import kotlinx.serialization.serializer18import org.jetbrains.kotlinx.jupyter.OutputConfig19import org.jetbrains.kotlinx.jupyter.exceptions.ReplCompilerException20import org.jetbrains.kotlinx.jupyter.exceptions.ReplEvalRuntimeException21import org.jetbrains.kotlinx.jupyter.generateDiagnostic22import org.jetbrains.kotlinx.jupyter.generateDiagnosticFromAbsolute23import org.jetbrains.kotlinx.jupyter.repl.CompletionResult24import org.jetbrains.kotlinx.jupyter.repl.ListErrorsResult25import org.jetbrains.kotlinx.jupyter.test.getOrFail26import org.jetbrains.kotlinx.jupyter.withPath27import org.junit.jupiter.api.Test28import java.io.File29import java.nio.file.Path30import kotlin.script.experimental.api.SourceCode31class ReplTests : AbstractSingleReplTest() {32 override val repl = makeSimpleRepl()33 @Test34 fun testRepl() {35 eval("val x = 3")36 val res = eval("x*2")37 res.resultValue shouldBe 638 }39 @Test40 fun testPropertiesGeneration() {41 // Note, this test should actually fail with ReplEvalRuntimeException, but 'cause of eval/compile42 // histories are out of sync, it fails with another exception. This test shows the wrong behavior and43 // should be fixed after fixing https://youtrack.jetbrains.com/issue/KT-3639744 // In fact, this shouldn't compile, but because of bug in compiler it fails in runtime45 shouldThrow<ReplCompilerException> {46 eval(47 """48 fun stack(vararg tup: Int): Int = tup.sum()49 val X = 150 val x = stack(1, X)51 """.trimIndent()52 )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 }451 class Child: Base()452 453 Child::class.simpleName454 """.trimIndent()455 ).resultValue shouldBe "Child"456 }457 @Test458 fun testIssue360() {459 eval("val a = 1")460 eval("fun b() = a")461 eval("b()").resultValue shouldBe 1462 }463}...

Full Screen

Full Screen

CoordinateTest.kt

Source:CoordinateTest.kt Github

copy

Full Screen

1package de.gleex.pltcmd.model.world.coordinate2import de.gleex.pltcmd.util.measure.compass.points.CardinalPoint.*3import io.kotest.assertions.assertSoftly4import io.kotest.core.spec.style.WordSpec5import io.kotest.data.forAll6import io.kotest.data.row7import io.kotest.matchers.collections.containDuplicates8import io.kotest.matchers.collections.shouldContainInOrder9import io.kotest.matchers.collections.shouldHaveSize10import io.kotest.matchers.comparables.beGreaterThan11import io.kotest.matchers.comparables.beLessThan12import io.kotest.matchers.nulls.shouldBeNull13import io.kotest.matchers.sequences.shouldContainExactly14import io.kotest.matchers.should15import io.kotest.matchers.shouldBe16import io.kotest.matchers.shouldNot17import io.kotest.matchers.string.shouldHaveMinLength18import io.kotest.matchers.string.shouldMatch19import io.kotest.property.checkAll20import mu.KotlinLogging21private val log = KotlinLogging.logger {}22class CoordinateTest : WordSpec({23 val testCoordinate = Coordinate(123, 345)24 "A coordinate $testCoordinate" should {25 val expectedMainCoordinate = MainCoordinate(1, 3)26 "have main coordinate $expectedMainCoordinate" {27 testCoordinate.toMainCoordinate() shouldBe expectedMainCoordinate28 }29 "return the correct Coordinate when moving it east/west" {30 for (eastingDelta in -1000..1000) {31 testCoordinate.withRelativeEasting(eastingDelta) shouldBe Coordinate(123 + eastingDelta, 345)32 }33 }34 "return the correct Coordinate when moving it north/south" {35 for (northingDelta in -1000..1000) {36 testCoordinate.withRelativeNorthing(northingDelta) shouldBe Coordinate(123, 345 + +northingDelta)37 }38 }39 "must be subtract able" {40 forAll(41 row(Coordinate.zero, Coordinate(testCoordinate.eastingFromLeft - 0, testCoordinate.northingFromBottom - 0)),42 row(Coordinate.oneEast, Coordinate(testCoordinate.eastingFromLeft - 1, testCoordinate.northingFromBottom - 0)),43 row(Coordinate.oneNorth, Coordinate(testCoordinate.eastingFromLeft - 0, testCoordinate.northingFromBottom - 1)),44 row(Coordinate.one, Coordinate(testCoordinate.eastingFromLeft - 1, testCoordinate.northingFromBottom - 1)),45 row(Coordinate.minusOneEast, Coordinate(testCoordinate.eastingFromLeft - -1, testCoordinate.northingFromBottom - 0)),46 row(Coordinate.minusOneNorth, Coordinate(testCoordinate.eastingFromLeft - 0, testCoordinate.northingFromBottom - -1)),47 row(Coordinate.minusOne, Coordinate(testCoordinate.eastingFromLeft - -1, testCoordinate.northingFromBottom - -1))48 ) { other, expected ->49 (testCoordinate - other) shouldBe expected50 }51 }52 }53 "A coordinate $testCoordinate" When {54 val coordinateWithDifferentNorthing = Coordinate(123, 344)55 "compared to $coordinateWithDifferentNorthing" should {56 "be bigger (because of higher northing)" {57 testCoordinate should beGreaterThan(coordinateWithDifferentNorthing)58 }59 }60 "being compared with $coordinateWithDifferentNorthing" should {61 "be less (because of lower northing)" {62 coordinateWithDifferentNorthing should beLessThan(testCoordinate)63 }64 }65 val coordinateWithDifferentEasting = Coordinate(122, 345)66 "compared to $coordinateWithDifferentEasting" should {67 "be bigger (because of higher easting)" {68 testCoordinate should beGreaterThan(coordinateWithDifferentEasting)69 }70 }71 "being compared with $coordinateWithDifferentEasting" should {72 "be less (because of lower easting)" {73 coordinateWithDifferentEasting should beLessThan(testCoordinate)74 }75 }76 "compared to itself" should {77 "be 0" {78 testCoordinate.compareTo(testCoordinate) shouldBe 079 }80 }81 }82 "The minimum coordinate" should {83 "be less than zero" {84 Coordinate.minimum should beLessThan(Coordinate.zero)85 }86 "be less than one" {87 Coordinate.minimum should beLessThan(Coordinate.one)88 }89 "be less than minusOne" {90 Coordinate.minimum should beLessThan(Coordinate.minusOne)91 }92 "be less than maximum" {93 Coordinate.minimum should beLessThan(Coordinate.maximum)94 }95 }96 "The maximum coordinate" should {97 "be greater than zero" {98 Coordinate.maximum should beGreaterThan(Coordinate.zero)99 }100 "be greater than one" {101 Coordinate.maximum should beGreaterThan(Coordinate.one)102 }103 "be greater than minusOne" {104 Coordinate.maximum should beGreaterThan(Coordinate.minusOne)105 }106 "be greater than minimum" {107 Coordinate.maximum should beGreaterThan(Coordinate.minimum)108 }109 }110 val c11 = Coordinate.one111 val c12 = Coordinate(1, 2)112 val c13 = Coordinate(1, 3)113 val c21 = Coordinate(2, 1)114 val c22 = Coordinate(2, 2)115 val c23 = Coordinate(2, 3)116 val c31 = Coordinate(3, 1)117 val c32 = Coordinate(3, 2)118 val c33 = Coordinate(3, 3)119 val unorderedListOfCoordinates = listOf(c31, c21, c11, c32, c33, c23, c12, c22, c13)120 "A list of ${unorderedListOfCoordinates.size} coordinates" should {121 "have the correct order when sorted" {122 val sorted = unorderedListOfCoordinates.sorted()123 assertSoftly {124 sorted shouldHaveSize 9125 sorted shouldNot containDuplicates()126 sorted shouldContainInOrder listOf(c11, c21, c31, c12, c22, c32, c13, c23, c33)127 }128 }129 }130 "The string representation of a coordinate in the form of (xxx|yyy)" should {131 val regex = Coordinate.REGEX_STRING.pattern132 "always have a length of at least 9 and match '$regex'" {133 var checkedCoordinates = 0134 checkAll<Int, Int> { x, y ->135 val coordinateString = Coordinate(x, y).toString()136 assertSoftly {137 coordinateString shouldHaveMinLength 9138 coordinateString shouldMatch regex139 }140 checkedCoordinates++141 }142 log.info { "checked $checkedCoordinates different string representations of Coordinate" }143 }144 val expectedString = "(123|345)"145 "be $expectedString for $testCoordinate" {146 testCoordinate.toString() shouldBe expectedString147 }148 "be padded for single digits" {149 toCoordinateString(1, 1) shouldBe "(001|001)"150 toCoordinateString(0, 0) shouldBe "(000|000)"151 toCoordinateString(2, 9) shouldBe "(002|009)"152 toCoordinateString(-1, -9) shouldBe "(-001|-009)"153 toCoordinateString(7, -9) shouldBe "(007|-009)"154 toCoordinateString(-2, 8) shouldBe "(-002|008)"155 }156 "be padded for two digits" {157 toCoordinateString(99, 10) shouldBe "(099|010)"158 toCoordinateString(33, 33) shouldBe "(033|033)"159 toCoordinateString(-11, -99) shouldBe "(-011|-099)"160 toCoordinateString(58, -10) shouldBe "(058|-010)"161 toCoordinateString(-75, 45) shouldBe "(-075|045)"162 }163 }164 "A coordinate created from a string" should {165 forAll(166 row("(001|001)", Coordinate(1, 1)),167 row("(000|000)", Coordinate(0, 0)),168 row("(-100|001)", Coordinate(-100, 1)),169 row("(001|-100)", Coordinate(1, -100)),170 row("(-100|-100)", Coordinate(-100, -100)),171 row("(-123456789|123456789)", Coordinate(-123456789, 123456789)),172 row(" (-100|-100)\t", Coordinate(-100, -100))173 ) { string, validCoordinate ->174 "be valid when created from string '$string'" {175 Coordinate.fromString(string) shouldBe validCoordinate176 }177 }178 forAll(179 row("(123456789|1)"),180 row("(123456789|11)"),181 row("(123456789|-11)"),182 row("(00a1|001)"),183 row("(|000)"),184 row("(--100|001)"),185 row("001|-100)"),186 row("(-100-100)"),187 row("(123456789|1"),188 row(""),189 row(" "),190 row("coordinate")191 ) { someString ->192 "be null when created from invalid string '$someString'" {193 Coordinate.fromString(someString)194 .shouldBeNull()195 }196 }197 }198 "The bearing between coordinates" should {199 "be due for 45° angles" {200 for (delta in 1..100) {201 assertSoftly(202 testCoordinate bearingTo testCoordinate.withRelativeNorthing(delta)203 ) {204 angle shouldBe 0205 roundedCardinal shouldBe N206 isDue shouldBe true207 }208 assertSoftly(209 testCoordinate bearingTo testCoordinate.movedBy(delta, delta)210 ) {211 angle shouldBe 45212 roundedCardinal shouldBe NE213 isDue shouldBe true214 }215 assertSoftly(216 testCoordinate bearingTo testCoordinate.withRelativeEasting(delta)217 ) {218 angle shouldBe 90219 roundedCardinal shouldBe E220 isDue shouldBe true221 }222 assertSoftly(223 testCoordinate bearingTo testCoordinate.movedBy(delta, -delta)224 ) {225 angle shouldBe 135226 roundedCardinal shouldBe SE227 isDue shouldBe true228 }229 assertSoftly(230 testCoordinate bearingTo testCoordinate.withRelativeNorthing(-delta)231 ) {232 angle shouldBe 180233 roundedCardinal shouldBe S234 isDue shouldBe true235 }236 assertSoftly(237 testCoordinate bearingTo testCoordinate.movedBy(-delta, -delta)238 ) {239 angle shouldBe 225240 roundedCardinal shouldBe SW241 isDue shouldBe true242 }243 assertSoftly(244 testCoordinate bearingTo testCoordinate.withRelativeEasting(-delta)245 ) {246 angle shouldBe 270247 roundedCardinal shouldBe W248 isDue shouldBe true249 }250 assertSoftly(251 testCoordinate bearingTo testCoordinate.movedBy(-delta, delta)252 ) {253 angle shouldBe 315254 roundedCardinal shouldBe NW255 isDue shouldBe true256 }257 }258 }259 }260 "The range between two coordinates" should {261 val other = Coordinate(125, 342)262 val range = testCoordinate..other263 "contain all coordinates in the rectangle ordered by the direction from the first to the second point" {264 range shouldContainExactly sequenceOf(265 Coordinate(123, 345),266 Coordinate(124, 345),267 Coordinate(125, 345),268 Coordinate(123, 344),269 Coordinate(124, 344),270 Coordinate(125, 344),271 Coordinate(123, 343),272 Coordinate(124, 343),273 Coordinate(125, 343),274 Coordinate(123, 342),275 Coordinate(124, 342),276 Coordinate(125, 342)277 )278 }279 }280})281fun toCoordinateString(easting: Int, northing: Int): String {282 return Coordinate(easting, northing).toString()283}...

Full Screen

Full Screen

SequenceKTest.kt

Source:SequenceKTest.kt Github

copy

Full Screen

1package arrow.core2import arrow.core.test.UnitSpec3import arrow.core.test.generators.option4import arrow.core.test.laws.MonoidLaws5import arrow.typeclasses.Monoid6import arrow.typeclasses.Semigroup7import io.kotest.matchers.sequences.shouldBeEmpty8import io.kotest.property.Arb9import io.kotest.property.checkAll10import io.kotest.matchers.shouldBe11import io.kotest.property.arbitrary.int12import io.kotest.property.arbitrary.list13import io.kotest.property.arbitrary.positiveInts14import io.kotest.property.arbitrary.string15import kotlin.math.max16import kotlin.math.min17class SequenceKTest : UnitSpec() {18 init {19 testLaws(MonoidLaws.laws(Monoid.sequence(), Arb.sequence(Arb.int())) { s1, s2 -> s1.toList() == s2.toList() })20 "traverseEither stack-safe" {21 // also verifies result order and execution order (l to r)22 val acc = mutableListOf<Int>()23 val res = generateSequence(0) { it + 1 }.traverseEither { a ->24 if (a > 20_000) {25 Either.Left(Unit)26 } else {27 acc.add(a)28 Either.Right(a)29 }30 }31 acc shouldBe (0..20_000).toList()32 res shouldBe Either.Left(Unit)33 }34 "traverseOption stack-safe" {35 // also verifies result order and execution order (l to r)36 val acc = mutableListOf<Int>()37 val res = generateSequence(0) { it + 1 }.traverseOption { a ->38 (a <= 20_000).maybe {39 acc.add(a)40 a41 }42 }43 acc shouldBe (0..20_000).toList()44 res shouldBe None45 }46 "traverseValidated stack-safe" {47 // also verifies result order and execution order (l to r)48 val acc = mutableListOf<Int>()49 val res = (0..20_000).asSequence().traverseValidated(Semigroup.string()) {50 acc.add(it)51 Validated.Valid(it)52 }.map { it.toList() }53 res shouldBe Validated.Valid(acc)54 res shouldBe Validated.Valid((0..20_000).toList())55 }56 "traverseValidated acummulates" {57 checkAll(Arb.sequence(Arb.int())) { ints ->58 val res: ValidatedNel<Int, Sequence<Int>> = ints.map { i -> if (i % 2 == 0) i.validNel() else i.invalidNel() }59 .sequenceValidated(Semigroup.nonEmptyList())60 val expected: ValidatedNel<Int, Sequence<Int>> = NonEmptyList.fromList(ints.filterNot { it % 2 == 0 }.toList())61 .fold({ ints.filter { it % 2 == 0 }.validNel() }, { it.invalid() })62 res.map { it.toList() } shouldBe expected.map { it.toList() }63 }64 }65 "zip3" {66 checkAll(Arb.sequence(Arb.int()), Arb.sequence(Arb.int()), Arb.sequence(Arb.int())) { a, b, c ->67 val result = a.zip(b, c, ::Triple)68 val expected = a.zip(b, ::Pair).zip(c) { (a, b), c -> Triple(a, b, c) }69 result.toList() shouldBe expected.toList()70 }71 }72 "zip4" {73 checkAll(74 Arb.sequence(Arb.int()),75 Arb.sequence(Arb.int()),76 Arb.sequence(Arb.int()),77 Arb.sequence(Arb.int())78 ) { a, b, c, d ->79 val result = a.zip(b, c, d, ::Tuple4)80 val expected = a.zip(b, ::Pair)81 .zip(c) { (a, b), c -> Triple(a, b, c) }82 .zip(d) { (a, b, c), d -> Tuple4(a, b, c, d) }83 result.toList() shouldBe expected.toList()84 }85 }86 "zip5" {87 checkAll(88 Arb.sequence(Arb.int()),89 Arb.sequence(Arb.int()),90 Arb.sequence(Arb.int()),91 Arb.sequence(Arb.int()),92 Arb.sequence(Arb.int())93 ) { a, b, c, d, e ->94 val result = a.zip(b, c, d, e, ::Tuple5)95 val expected = a.zip(b, ::Pair)96 .zip(c) { (a, b), c -> Triple(a, b, c) }97 .zip(d) { (a, b, c), d -> Tuple4(a, b, c, d) }98 .zip(e) { (a, b, c, d), e -> Tuple5(a, b, c, d, e) }99 result.toList() shouldBe expected.toList()100 }101 }102 "zip6" {103 checkAll(104 Arb.sequence(Arb.int()),105 Arb.sequence(Arb.int()),106 Arb.sequence(Arb.int()),107 Arb.sequence(Arb.int()),108 Arb.sequence(Arb.int()),109 Arb.sequence(Arb.int())110 ) { a, b, c, d, e, f ->111 val result = a.zip(b, c, d, e, f, ::Tuple6)112 val expected = a.zip(b, ::Pair)113 .zip(c) { (a, b), c -> Triple(a, b, c) }114 .zip(d) { (a, b, c), d -> Tuple4(a, b, c, d) }115 .zip(e) { (a, b, c, d), e -> Tuple5(a, b, c, d, e) }116 .zip(f) { (a, b, c, d, e), f -> Tuple6(a, b, c, d, e, f) }117 result.toList() shouldBe expected.toList()118 }119 }120 "zip7" {121 checkAll(122 Arb.sequence(Arb.int()),123 Arb.sequence(Arb.int()),124 Arb.sequence(Arb.int()),125 Arb.sequence(Arb.int()),126 Arb.sequence(Arb.int()),127 Arb.sequence(Arb.int()),128 Arb.sequence(Arb.int())129 ) { a, b, c, d, e, f, g ->130 val result = a.zip(b, c, d, e, f, g, ::Tuple7)131 val expected = a.zip(b, ::Pair)132 .zip(c) { (a, b), c -> Triple(a, b, c) }133 .zip(d) { (a, b, c), d -> Tuple4(a, b, c, d) }134 .zip(e) { (a, b, c, d), e -> Tuple5(a, b, c, d, e) }135 .zip(f) { (a, b, c, d, e), f -> Tuple6(a, b, c, d, e, f) }136 .zip(g) { (a, b, c, d, e, f), g -> Tuple7(a, b, c, d, e, f, g) }137 result.toList() shouldBe expected.toList()138 }139 }140 "zip8" {141 checkAll(142 Arb.sequence(Arb.int()),143 Arb.sequence(Arb.int()),144 Arb.sequence(Arb.int()),145 Arb.sequence(Arb.int()),146 Arb.sequence(Arb.int()),147 Arb.sequence(Arb.int()),148 Arb.sequence(Arb.int()),149 Arb.sequence(Arb.int())150 ) { a, b, c, d, e, f, g, h ->151 val result = a.zip(b, c, d, e, f, g, h, ::Tuple8)152 val expected = a.zip(b, ::Pair)153 .zip(c) { (a, b), c -> Triple(a, b, c) }154 .zip(d) { (a, b, c), d -> Tuple4(a, b, c, d) }155 .zip(e) { (a, b, c, d), e -> Tuple5(a, b, c, d, e) }156 .zip(f) { (a, b, c, d, e), f -> Tuple6(a, b, c, d, e, f) }157 .zip(g) { (a, b, c, d, e, f), g -> Tuple7(a, b, c, d, e, f, g) }158 .zip(h) { (a, b, c, d, e, f, g), h -> Tuple8(a, b, c, d, e, f, g, h) }159 result.toList() shouldBe expected.toList()160 }161 }162 "zip9" {163 checkAll(164 Arb.sequence(Arb.int()),165 Arb.sequence(Arb.int()),166 Arb.sequence(Arb.int()),167 Arb.sequence(Arb.int()),168 Arb.sequence(Arb.int()),169 Arb.sequence(Arb.int()),170 Arb.sequence(Arb.int()),171 Arb.sequence(Arb.int()),172 Arb.sequence(Arb.int())173 ) { a, b, c, d, e, f, g, h, i ->174 val result = a.zip(b, c, d, e, f, g, h, i, ::Tuple9)175 val expected = a.zip(b, ::Pair)176 .zip(c) { (a, b), c -> Triple(a, b, c) }177 .zip(d) { (a, b, c), d -> Tuple4(a, b, c, d) }178 .zip(e) { (a, b, c, d), e -> Tuple5(a, b, c, d, e) }179 .zip(f) { (a, b, c, d, e), f -> Tuple6(a, b, c, d, e, f) }180 .zip(g) { (a, b, c, d, e, f), g -> Tuple7(a, b, c, d, e, f, g) }181 .zip(h) { (a, b, c, d, e, f, g), h -> Tuple8(a, b, c, d, e, f, g, h) }182 .zip(i) { (a, b, c, d, e, f, g, h), i -> Tuple9(a, b, c, d, e, f, g, h, i) }183 result.toList() shouldBe expected.toList()184 }185 }186 "zip10" {187 checkAll(188 Arb.sequence(Arb.int()),189 Arb.sequence(Arb.int()),190 Arb.sequence(Arb.int()),191 Arb.sequence(Arb.int()),192 Arb.sequence(Arb.int()),193 Arb.sequence(Arb.int()),194 Arb.sequence(Arb.int()),195 Arb.sequence(Arb.int()),196 Arb.sequence(Arb.int()),197 Arb.sequence(Arb.int())198 ) { a, b, c, d, e, f, g, h, i, j ->199 val result = a.zip(b, c, d, e, f, g, h, i, j, ::Tuple10)200 val expected = a.zip(b, ::Pair)201 .zip(c) { (a, b), c -> Triple(a, b, c) }202 .zip(d) { (a, b, c), d -> Tuple4(a, b, c, d) }203 .zip(e) { (a, b, c, d), e -> Tuple5(a, b, c, d, e) }204 .zip(f) { (a, b, c, d, e), f -> Tuple6(a, b, c, d, e, f) }205 .zip(g) { (a, b, c, d, e, f), g -> Tuple7(a, b, c, d, e, f, g) }206 .zip(h) { (a, b, c, d, e, f, g), h -> Tuple8(a, b, c, d, e, f, g, h) }207 .zip(i) { (a, b, c, d, e, f, g, h), i -> Tuple9(a, b, c, d, e, f, g, h, i) }208 .zip(j) { (a, b, c, d, e, f, g, h, i), j -> Tuple10(a, b, c, d, e, f, g, h, i, j) }209 result.toList() shouldBe expected.toList()210 }211 }212 "can align sequences - 1" {213 checkAll(Arb.sequence(Arb.int()), Arb.sequence(Arb.string())) { a, b ->214 a.align(b).toList().size shouldBe max(a.toList().size, b.toList().size)215 }216 }217 "can align sequences - 2" {218 checkAll(Arb.sequence(Arb.int()), Arb.sequence(Arb.string())) { a, b ->219 a.align(b).take(min(a.toList().size, b.toList().size)).forEach {220 it.isBoth shouldBe true221 }222 }223 }224 "can align sequences - 3" {225 checkAll(Arb.sequence(Arb.int()), Arb.sequence(Arb.string())) { a, b ->226 val ls = a.toList()227 val rs = b.toList()228 a.align(b).drop(min(ls.size, rs.size)).forEach {229 if (ls.size < rs.size) {230 it.isRight shouldBe true231 } else {232 it.isLeft shouldBe true233 }234 }235 }236 }237 "align empty sequences" {238 val a = emptyList<String>().asSequence()239 a.align(a).shouldBeEmpty()240 }241 "align infinite sequences" {242 val seq1 = generateSequence("A") { it }243 val seq2 = generateSequence(0) { it + 1 }244 checkAll(10, Arb.positiveInts(max = 10_000)) { idx: Int ->245 val element = seq1.align(seq2).drop(idx).first()246 element shouldBe Ior.Both("A", idx)247 }248 }249 "mapNotNull" {250 checkAll(Arb.sequence(Arb.int())) { a ->251 val result = a.mapNotNull {252 when (it % 2 == 0) {253 true -> it.toString()254 else -> null255 }256 }257 val expected =258 a.toList()259 .mapNotNull {260 when (it % 2 == 0) {261 true -> it.toString()262 else -> null263 }264 }265 .asSequence()266 result.toList() shouldBe expected.toList()267 }268 }269 "filterOption should filter None" {270 checkAll(Arb.list(Arb.option(Arb.int()))) { ints ->271 ints.asSequence().filterOption().toList() shouldBe ints.filterOption()272 }273 }274 }275}...

Full Screen

Full Screen

SequenceTest.kt

Source:SequenceTest.kt Github

copy

Full Screen

1package com.mattmik.rapira.objects2import com.mattmik.rapira.CONST_YES3import io.kotest.core.spec.style.WordSpec4import io.kotest.data.forAll5import io.kotest.data.row6import io.kotest.matchers.shouldBe7import io.kotest.property.Arb8import io.kotest.property.arbitrary.list9import io.kotest.property.arbitrary.negativeInts10import io.kotest.property.checkAll11class SequenceTest : WordSpec({12 "vararg constructor" should {13 "set entries list" {14 val obj1 = Text("Hello, world!")15 val obj2 = RInteger(123)16 val obj3 = CONST_YES17 val sequence = Sequence(obj1, obj2, obj3)18 sequence.entries shouldBe listOf(obj1, obj2, obj3)19 }20 }21 "plus" should {22 val sequence = listOf(23 1.toRInteger(),24 "Hello, world!".toText(),25 2.toRInteger(),26 "This is a test.".toText()27 ).toSequence()28 "succeed with sequence when given sequence" {29 sequence + sequence shouldSucceedWith Sequence(sequence.entries + sequence.entries)30 }31 "error when given other types" {32 forAll(33 row(Empty),34 row(Procedure()),35 row(Function()),36 row(RInteger(1)),37 row(CONST_YES),38 row(Real(1.0)),39 row(Text("Hello, world!"))40 ) { obj ->41 (sequence + obj).shouldError()42 }43 }44 }45 "times" should {46 val sequence = listOf(47 1.toRInteger(),48 "Hello, world!".toText(),49 2.toRInteger(),50 "This is a test.".toText()51 ).toSequence()52 "succeed with empty sequence when given 0" {53 sequence * RInteger(0) shouldSucceedWith Sequence(emptyList())54 }55 "succeed with sequence when given positive integer" {56 sequence * RInteger(3) shouldSucceedWith listOf(57 1.toRInteger(),58 "Hello, world!".toText(),59 2.toRInteger(),60 "This is a test.".toText(),61 1.toRInteger(),62 "Hello, world!".toText(),63 2.toRInteger(),64 "This is a test.".toText(),65 1.toRInteger(),66 "Hello, world!".toText(),67 2.toRInteger(),68 "This is a test.".toText()69 ).toSequence()70 }71 "error when given negative integer" {72 checkAll(Arb.negativeInts()) { num ->73 (sequence * RInteger(num)).shouldError()74 }75 }76 "error when given other types" {77 forAll(78 row(Empty),79 row(Procedure()),80 row(Function()),81 row(Text("Hello, world!")),82 row(CONST_YES),83 row(Real(1.0)),84 row(Sequence())85 ) { obj ->86 (sequence * obj).shouldError()87 }88 }89 }90 "length" should {91 "succeed with integer" {92 checkAll(Arb.list(rapiraObjectArb)) { objectList ->93 objectList.toSequence().length() shouldSucceedWith objectList.size.toRInteger()94 }95 }96 }97 "element at" should {98 val sequence = listOf(99 1.toRInteger(),100 "Hello, world!".toText(),101 2.toRInteger(),102 "This is a test.".toText()103 ).toSequence()104 "succeed with object when given valid integer" {105 sequence.elementAt(1.toRInteger()) shouldSucceedWith 1.toRInteger()106 sequence.elementAt(2.toRInteger()) shouldSucceedWith "Hello, world!".toText()107 sequence.elementAt(3.toRInteger()) shouldSucceedWith 2.toRInteger()108 sequence.elementAt(4.toRInteger()) shouldSucceedWith "This is a test.".toText()109 }110 "error when given out of bounds integer" {111 sequence.elementAt(0.toRInteger()).shouldError()112 sequence.elementAt(5.toRInteger()).shouldError()113 }114 "error when given other types" {115 forAll(116 row(Empty),117 row(Procedure()),118 row(Function()),119 row(Text("Hello, world!")),120 row(CONST_YES),121 row(Real(1.0)),122 row(Sequence())123 ) { obj ->124 sequence.elementAt(obj).shouldError()125 }126 }127 }128 "slice" should {129 "succeed with object when given integer" {130 val sequence = listOf(131 1.toRInteger(),132 2.toRInteger(),133 3.toRInteger(),134 4.toRInteger()135 ).toSequence()136 sequence.slice(null, null) shouldSucceedWith sequence137 sequence.slice(2.toRInteger(), null) shouldSucceedWith listOf(138 2.toRInteger(),139 3.toRInteger(),140 4.toRInteger()141 ).toSequence()142 sequence.slice(2.toRInteger(), 3.toRInteger()) shouldSucceedWith listOf(143 2.toRInteger(),144 3.toRInteger()145 ).toSequence()146 sequence.slice(null, 3.toRInteger()) shouldSucceedWith listOf(147 1.toRInteger(),148 2.toRInteger(),149 3.toRInteger()150 ).toSequence()151 sequence.slice(1.toRInteger(), 0.toRInteger()) shouldSucceedWith emptyList<RObject>().toSequence()152 sequence.slice(5.toRInteger(), 4.toRInteger()) shouldSucceedWith emptyList<RObject>().toSequence()153 }154 "error when start index is out of bounds" {155 val sequence = listOf(156 1.toRInteger(),157 2.toRInteger(),158 3.toRInteger(),159 ).toSequence()160 sequence.slice(0.toRInteger(), null).shouldError()161 sequence.slice((-1).toRInteger(), null).shouldError()162 }163 "error when end index is out of bounds" {164 val sequence = listOf(165 1.toRInteger(),166 2.toRInteger(),167 3.toRInteger(),168 ).toSequence()169 sequence.slice(null, 4.toRInteger()).shouldError()170 }171 "error when given other types" {172 forAll(173 row(Empty),174 row(Procedure()),175 row(Function()),176 row(Text("Hello, world!")),177 row(CONST_YES),178 row(Real(1.0)),179 row(Sequence())180 ) { obj ->181 val testSequence = listOf(182 1.toRInteger(),183 "Hello, world!".toText(),184 2.toRInteger(),185 "This is a test.".toText()186 ).toSequence()187 testSequence.slice(null, obj).shouldError()188 testSequence.slice(obj, null).shouldError()189 testSequence.slice(obj, obj).shouldError()190 }191 }192 }193 "toString" should {194 "return user friendly representation" {195 val emptySequence = emptyList<RObject>().toSequence()196 emptySequence shouldConvertToString "<* *>"197 val simpleNumberSequence = listOf(1, 2, 3)198 .map { num -> num.toRInteger() }199 .toSequence()200 simpleNumberSequence shouldConvertToString "<* 1, 2, 3 *>"201 val nestedSequences = listOf(202 1.toRInteger(),203 listOf(204 2.toRInteger(),205 3.toRInteger(),206 4.toRInteger()207 ).toSequence(),208 5.toRInteger()209 ).toSequence()210 nestedSequences shouldConvertToString "<* 1, <* 2, 3, 4 *>, 5 *>"211 val sequenceOfMixedTypes = listOf(212 1.toRInteger(),213 Real(2.5),214 "okay".toText()215 ).toSequence()216 sequenceOfMixedTypes shouldConvertToString "<* 1, 2.5, \"okay\" *>"217 }218 }219})...

Full Screen

Full Screen

evalTest.kt

Source:evalTest.kt Github

copy

Full Screen

1package brainfuck2import arrow.core.extensions.id.comonad.extract3import arrow.fx.IO4import arrow.fx.extensions.io.monad.monad5import arrow.fx.fix6import arrow.mtl.State7import arrow.mtl.run8import io.kotest.core.spec.style.StringSpec9import io.kotest.matchers.nulls.shouldNotBeNull10import io.kotest.matchers.sequences.shouldBeEmpty11import io.kotest.matchers.shouldBe12import kotlinx.collections.immutable.persistentListOf13import kotlinx.collections.immutable.toPersistentList14class EvalTest : StringSpec({15 val emptyMemory = List(1024) {0.toByte()}.toPersistentList()16 val helloWorld = "++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++."17 val fibonacci = "+++++++++++\n" +18 ">+>>>>++++++++++++++++++++++++++++++++++++++++++++\n" +19 ">++++++++++++++++++++++++++++++++<<<<<<[>[>>>>>>+>\n" +20 "+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]<[>++++++++++[-\n" +21 "<-[>>+>+<<<-]>>>[<<<+>>>-]+<[>[-]<[-]]>[<<[>>>+<<<\n" +22 "-]>>[-]]<<]>>>[>>+>+<<<-]>>>[<<<+>>>-]+<[>[-]<[-]]\n" +23 ">[<<+>>[-]]<<<<<<<]>>>>>[+++++++++++++++++++++++++\n" +24 "+++++++++++++++++++++++.[-]]++++++++++<[->-<]>++++\n" +25 "++++++++++++++++++++++++++++++++++++++++++++.[-]<<\n" +26 "<<<<<<<<<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-]<-[>>.>.<<<\n" +27 "[-]]<<[>>+>+<<<-]>>>[<<<+>>>-]<<[<+>-]>[<+>-]<<<-]"28 val head = "+>>>>>>>>>>-[,+[-.----------[[-]>]<->]<]" // taken from http://www.hevanet.com/cristofd/brainfuck/head.b29 "add two numbers in State" {30 val emptyIo = MemIO(emptySequence(), emptyList())31 val machine = Machine(persistentListOf(25, 40), 0, StateMachine)32 val program: Program? = parse("[->+<]>.") // add 25 and 40, then print it33 program.shouldNotBeNull()34 val e = State().monad<MemIO>().eval(machine, program)35 val (ioAfter, machineAfter) = e.run(emptyIo).extract()36 ioAfter.machineOut shouldBe listOf(65.toByte())37 ioAfter.machineIn.shouldBeEmpty()38 machineAfter.memory shouldBe listOf(0,65).map {it.toByte()}39 machineAfter.pointer shouldBe 140 }41 "add two numbers in IO" {42 val machine = Machine(persistentListOf(25, 40), 0, IOMachine.std)43 val program: Program? = parse("[->+<]>.") // add 25 and 40, then print it44 program.shouldNotBeNull()45 val e = IO.monad().eval(machine, program)46 val machineAfter = e.fix().unsafeRunSync()47 machineAfter.memory shouldBe listOf(0,65).map {it.toByte()}48 machineAfter.pointer shouldBe 149 }50 "multiply two numbers in State" {51 val a: Byte = 1052 val b: Byte = 1153 val emptyIo = MemIO(emptySequence(), emptyList())54 val machine = Machine(persistentListOf(a, b, 0, 0), 0, StateMachine)55 // taken from https://www.codingame.com/playgrounds/50426/getting-started-with-brainfuck/multiplication56 val program: Program? = parse("[>[->+>+<<]>[-<+>]<<-]")57 program.shouldNotBeNull()58 val e = State().monad<MemIO>().eval(machine, program)59 val (_, machineAfter) = e.run(emptyIo).extract()60 machineAfter.memory shouldBe listOf(0,b,0,a*b).map {it.toByte()}61 }62 "multiply two numbers in IO" {63 val a: Byte = 1064 val b: Byte = 1165 val machine = Machine(persistentListOf(a, b, 0, 0), 0, IOMachine.std)66 // taken from https://www.codingame.com/playgrounds/50426/getting-started-with-brainfuck/multiplication67 val program: Program? = parse("[>[->+>+<<]>[-<+>]<<-]")68 program.shouldNotBeNull()69 val machineAfter = IO.monad().eval(machine, program).fix().unsafeRunSync()70 println(machineAfter.memory.toList())71 machineAfter.memory shouldBe listOf(0,b,0,a*b).map {it.toByte()}72 }73 "print Hello World in State" {74 val emptyIo = MemIO(emptySequence(), emptyList())75 val machine = Machine(emptyMemory, 0, StateMachine)76 val program: Program? = parse(helloWorld)77 program.shouldNotBeNull()78 val e = State().monad<MemIO>().eval(machine, program)79 val (ioAfter) = e.run(emptyIo).extract()80 ioAfter.printOut() shouldBe "Hello World!\n"81 }82 "print Hello World in IO" {83 val machine = Machine(emptyMemory, 0, IOMachine.std)84 val program: Program? = parse(helloWorld)85 program.shouldNotBeNull()86 val e = IO.monad().eval(machine, program)87 e.fix().unsafeRunSync()88 }89 "print fibonacci in State" {90 val emptyIo = MemIO(emptySequence(), emptyList())91 val machine = Machine(emptyMemory, 0, StateMachine)92 val program: Program? = parse(fibonacci)93 program.shouldNotBeNull()94 val e = State().monad<MemIO>().eval(machine, program)95 val (ioAfter) = e.run(emptyIo).extract()96 ioAfter.printOut() shouldBe "1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89"97 }98 "print fibonacci in IO" {99 val machine = Machine(emptyMemory, 0, IOMachine.std)100 val program: Program? = parse(fibonacci)101 program.shouldNotBeNull()102 IO.monad().eval(machine, program).fix().unsafeRunSync()103 }104 "print 10 lines of input in State" {105 val input = (1..20).joinToString(separator = "\n").toByteArray().asSequence()106 val emptyIo = MemIO(input, emptyList())107 val machine = Machine(emptyMemory, 0, StateMachine)108 val program: Program? = parse(head)109 program.shouldNotBeNull()110 val e = State().monad<MemIO>().eval(machine, program)111 val (ioAfter) = e.run(emptyIo).extract()112 ioAfter.printOut() shouldBe (1..10).joinToString(separator = "\n", postfix = "\n")113 }114 "print 10 lines of input in IO" {115 val input = (1..20).joinToString(separator = "\n").toByteArray().toTypedArray()116 val (iomac, output) = IOMachine.memory(input)117 val machine = Machine(emptyMemory, 0, iomac)118 val program: Program? = parse(head)119 program.shouldNotBeNull()120 IO.monad().eval(machine, program).fix().unsafeRunSync()121 val ioAfter = output.toString()122 ioAfter shouldBe (1..10).joinToString(separator = "\n", postfix = "\n")123 }124})...

Full Screen

Full Screen

Sequence.toString

Using AI Code Generation

copy

Full Screen

1Sequence(1, 2, 3).toString() shouldBe "[1, 2, 3]"2Sequence().shouldBeEmpty()3Sequence(1, 2, 3).shouldNotBeEmpty()4Sequence(1, 2, 3).shouldContainAll(1, 2, 3)5Sequence(1, 2, 3).shouldContainNone(4, 5, 6)6Sequence(1, 2, 3).shouldContain(1)7Sequence(1, 2, 3).shouldContain(1, 2, 3)8Sequence(1, 2, 3).shouldContain(1, 2, 3) { it > 0 }9Sequence(1, 2, 3).shouldContain(1, 2, 3) { it > 1 }10Sequence(1, 2, 3).shouldContain(1, 2, 3) { it shouldBeGreaterThan 1 }11Sequence(1, 2, 3).shouldContain(1, 2, 3) { it shouldBeGreaterThan 1 }12Sequence(1, 2, 3).shouldContainInOrder(1, 2, 3)

Full Screen

Full Screen

Sequence.toString

Using AI Code Generation

copy

Full Screen

1Sequence(1, 2, 3).toString() shouldBe "[1, 2, 3]"2Sequence().shouldBeEmpty()3Sequence(1, 2, 3).shouldBeInfinite()4Sequence(1, 2, 3).shouldBeNotEmpty()5Sequence(1, 2, 3).shouldBeSequenceOf(1, 2, 3)6Sequence(1).shouldBeSingleton()7Sequence(1, 2, 3).shouldContainAll(1, 2, 3)8Sequence(1, 2, 3).shouldContainExactly(1, 2, 3)9Sequence(1, 2, 3).shouldContainInOrder(1, 2, 3)10Sequence(1, 2, 3).shouldContainInOrderOnly(1, 2, 3)11Sequence(1, 2, 3).shouldContainNone(4, 5, 6)12Sequence(1, 2, 3).shouldContainOnly(1, 2, 3)

Full Screen

Full Screen

Sequence.toString

Using AI Code Generation

copy

Full Screen

1val seq = sequenceOf(1, 2, 3, 4, 5)2seq should containInOrder(1, 2, 3, 4, 5)3seq should containInOrder(1, 2, 3, 4, 5).inAnyOrder()4seq should containInOrder(1, 2, 3, 4, 5).inAnyOrder().reversed()5seq should containInOrder(1, 2, 3, 4, 5).reversed()6seq should containInOrder(1, 2, 3, 4, 5).reversed().inAnyOrder()7val seq = sequenceOf(1, 2, 3, 4, 5)8seq should containInOrder(1, 2, 3, 4, 5)9seq should containInOrder(1, 2, 3, 4, 5).inAnyOrder()10seq should containInOrder(1, 2, 3, 4, 5).inAnyOrder().reversed()11seq should containInOrder(1, 2, 3, 4, 5).reversed()12seq should containInOrder(1, 2, 3, 4, 5).reversed().inAnyOrder()13val seq = sequenceOf(1, 2, 3, 4, 5)14seq should containInOrder(1, 2, 3, 4, 5)15seq should containInOrder(1, 2, 3, 4, 5).inAnyOrder()16seq should containInOrder(1, 2, 3, 4, 5).inAnyOrder().reversed()17seq should containInOrder(1, 2, 3, 4, 5).reversed()18seq should containInOrder(1, 2, 3, 4, 5).reversed().inAnyOrder()19val seq = sequenceOf(1, 2, 3,

Full Screen

Full Screen

Sequence.toString

Using AI Code Generation

copy

Full Screen

1val seq = sequenceOf(1, 2, 3, 4)2seq should containInOrder(1, 2, 3, 4)3seq should containInOrder(1, 2, 3)4seq should containInOrder(2, 3, 4)5seq should containInOrder(2, 3)6seq shouldNot containInOrder(1, 3, 2)7seq shouldNot containInOrder(1, 3)8seq shouldNot containInOrder(1, 2, 3, 4, 5)9seq shouldNot containInOrder(5, 4, 3, 2, 1)10val seq = sequenceOf(1, 2, 3, 4)11seq should containInOrder(1, 2, 3, 4)12seq should containInOrder(1, 2, 3)13seq should containInOrder(2, 3, 4)14seq should containInOrder(2, 3)15seq shouldNot containInOrder(1, 3, 2)16seq shouldNot containInOrder(1, 3)17seq shouldNot containInOrder(1, 2, 3, 4, 5)18seq shouldNot containInOrder(5, 4, 3, 2, 1)19val seq = sequenceOf(1, 2, 3, 4)20seq should containInOrder(1, 2, 3, 4)21seq should containInOrder(1, 2, 3)22seq should containInOrder(2, 3, 4)23seq should containInOrder(2, 3)24seq shouldNot containInOrder(1, 3, 2)25seq shouldNot containInOrder(1, 3)26seq shouldNot containInOrder(1, 2, 3, 4, 5)27seq shouldNot containInOrder(5, 4, 3, 2, 1)28val seq = sequenceOf(1, 2,

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.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful