How to use test method of io.kotest.matchers.collections.increasing class

Best Kotest code snippet using io.kotest.matchers.collections.increasing.test

CollectionMatchersTest.kt

Source:CollectionMatchersTest.kt Github

copy

Full Screen

1package com.sksamuel.kotest.matchers.collections2import io.kotest.assertions.shouldFail3import io.kotest.assertions.throwables.shouldNotThrow4import io.kotest.assertions.throwables.shouldThrow5import io.kotest.assertions.withClue6import io.kotest.core.spec.style.WordSpec7import io.kotest.equals.Equality8import io.kotest.equals.types.byObjectEquality9import io.kotest.matchers.collections.atLeastSize10import io.kotest.matchers.collections.atMostSize11import io.kotest.matchers.collections.beLargerThan12import io.kotest.matchers.collections.beSameSizeAs13import io.kotest.matchers.collections.beSmallerThan14import io.kotest.matchers.collections.contain15import io.kotest.matchers.collections.containDuplicates16import io.kotest.matchers.collections.containNoNulls17import io.kotest.matchers.collections.containNull18import io.kotest.matchers.collections.containOnlyNulls19import io.kotest.matchers.collections.matchInOrder20import io.kotest.matchers.collections.existInOrder21import io.kotest.matchers.collections.haveElementAt22import io.kotest.matchers.collections.haveSize23import io.kotest.matchers.collections.matchEach24import io.kotest.matchers.collections.matchInOrderSubset25import io.kotest.matchers.collections.monotonicallyDecreasing26import io.kotest.matchers.collections.monotonicallyDecreasingWith27import io.kotest.matchers.collections.monotonicallyIncreasing28import io.kotest.matchers.collections.monotonicallyIncreasingWith29import io.kotest.matchers.collections.shouldBeIn30import io.kotest.matchers.collections.shouldBeLargerThan31import io.kotest.matchers.collections.shouldBeMonotonicallyDecreasing32import io.kotest.matchers.collections.shouldBeMonotonicallyDecreasingWith33import io.kotest.matchers.collections.shouldBeMonotonicallyIncreasing34import io.kotest.matchers.collections.shouldBeMonotonicallyIncreasingWith35import io.kotest.matchers.collections.shouldBeSameSizeAs36import io.kotest.matchers.collections.shouldBeSingleton37import io.kotest.matchers.collections.shouldBeSmallerThan38import io.kotest.matchers.collections.shouldBeSorted39import io.kotest.matchers.collections.shouldBeSortedBy40import io.kotest.matchers.collections.shouldBeSortedWith41import io.kotest.matchers.collections.shouldBeStrictlyDecreasing42import io.kotest.matchers.collections.shouldBeStrictlyDecreasingWith43import io.kotest.matchers.collections.shouldBeStrictlyIncreasing44import io.kotest.matchers.collections.shouldBeStrictlyIncreasingWith45import io.kotest.matchers.collections.shouldContainAnyOf46import io.kotest.matchers.collections.shouldContainDuplicates47import io.kotest.matchers.collections.shouldContainNoNulls48import io.kotest.matchers.collections.shouldContainNull49import io.kotest.matchers.collections.shouldContainOnlyNulls50import io.kotest.matchers.collections.shouldExist51import io.kotest.matchers.collections.shouldHaveAtLeastSize52import io.kotest.matchers.collections.shouldHaveAtMostSize53import io.kotest.matchers.collections.shouldHaveElementAt54import io.kotest.matchers.collections.shouldHaveSingleElement55import io.kotest.matchers.collections.shouldHaveSize56import io.kotest.matchers.collections.shouldMatchInOrder57import io.kotest.matchers.collections.shouldMatchInOrderSubset58import io.kotest.matchers.collections.shouldNotBeIn59import io.kotest.matchers.collections.shouldNotBeMonotonicallyDecreasing60import io.kotest.matchers.collections.shouldNotBeMonotonicallyDecreasingWith61import io.kotest.matchers.collections.shouldNotBeMonotonicallyIncreasing62import io.kotest.matchers.collections.shouldNotBeMonotonicallyIncreasingWith63import io.kotest.matchers.collections.shouldNotBeSingleton64import io.kotest.matchers.collections.shouldNotBeSorted65import io.kotest.matchers.collections.shouldNotBeSortedBy66import io.kotest.matchers.collections.shouldNotBeSortedWith67import io.kotest.matchers.collections.shouldNotBeStrictlyDecreasing68import io.kotest.matchers.collections.shouldNotBeStrictlyDecreasingWith69import io.kotest.matchers.collections.shouldNotBeStrictlyIncreasing70import io.kotest.matchers.collections.shouldNotBeStrictlyIncreasingWith71import io.kotest.matchers.collections.shouldNotContainAnyOf72import io.kotest.matchers.collections.shouldNotContainDuplicates73import io.kotest.matchers.collections.shouldNotContainNoNulls74import io.kotest.matchers.collections.shouldNotContainNull75import io.kotest.matchers.collections.shouldNotContainOnlyNulls76import io.kotest.matchers.collections.shouldNotHaveElementAt77import io.kotest.matchers.collections.shouldNotHaveSize78import io.kotest.matchers.collections.shouldNotMatchEach79import io.kotest.matchers.collections.shouldNotMatchInOrder80import io.kotest.matchers.collections.shouldNotMatchInOrderSubset81import io.kotest.matchers.collections.singleElement82import io.kotest.matchers.collections.sorted83import io.kotest.matchers.collections.strictlyDecreasing84import io.kotest.matchers.collections.strictlyDecreasingWith85import io.kotest.matchers.collections.strictlyIncreasing86import io.kotest.matchers.collections.strictlyIncreasingWith87import io.kotest.matchers.ints.shouldBeGreaterThan88import io.kotest.matchers.ints.shouldBeInRange89import io.kotest.matchers.should90import io.kotest.matchers.shouldBe91import io.kotest.matchers.shouldHave92import io.kotest.matchers.shouldNot93import io.kotest.matchers.shouldNotBe94import io.kotest.matchers.shouldNotHave95import io.kotest.matchers.throwable.shouldHaveMessage96class CollectionMatchersTest : WordSpec() {97 private val countdown = (10 downTo 0).toList()98 private val asc = { a: Int, b: Int -> a - b }99 private val desc = { a: Int, b: Int -> b - a }100 init {101 "a descending non-empty list" should {102 "fail to ascend" {103 shouldFail {104 countdown.shouldBeSortedWith(asc)105 }106 }107 "descend" {108 countdown.shouldBeSortedWith(desc)109 }110 "not ascend" {111 countdown.shouldNotBeSortedWith(asc)112 }113 "fail not to descend" {114 shouldFail {115 countdown.shouldNotBeSortedWith(desc)116 }117 }118 }119 "sortedWith" should {120 val items = listOf(121 1 to "I",122 2 to "II",123 4 to "IV",124 5 to "V",125 6 to "VI",126 9 to "IX",127 10 to "X"128 )129 "work on non-Comparable given a Comparator" {130 items.shouldBeSortedWith(Comparator { a, b -> asc(a.first, b.first) })131 }132 "work on non-Comparable given a compare function" {133 items.shouldBeSortedWith { a, b -> asc(a.first, b.first) }134 }135 }136 "haveElementAt" should {137 "test that a collection contains the specified element at the given index" {138 listOf("a", "b", "c") should haveElementAt(1, "b")139 listOf("a", "b", "c") shouldNot haveElementAt(1, "c")140 listOf("a", "b", null) should haveElementAt(2, null)141 listOf("a", "b", null) shouldNot haveElementAt(3, null)142 listOf("a", "b", "c").shouldHaveElementAt(1, "b")143 listOf("a", "b", "c").shouldNotHaveElementAt(1, "c")144 listOf("a", "b", null).shouldHaveElementAt(2, null)145 }146 "support type inference for subtypes of collection" {147 val tests = listOf(148 TestSealed.Test1("test1"),149 TestSealed.Test2(2)150 )151 tests should haveElementAt(0, TestSealed.Test1("test1"))152 tests.shouldHaveElementAt(1, TestSealed.Test2(2))153 }154 }155 "containNull()" should {156 "test that a collection contains at least one null" {157 listOf(1, 2, null) should containNull()158 listOf(null) should containNull()159 listOf(1, 2) shouldNot containNull()160 listOf(1, 2, null).shouldContainNull()161 listOf(null).shouldContainNull()162 listOf(1, 2).shouldNotContainNull()163 }164 }165 "sorted" should {166 "test that a collection is sorted" {167 emptyList<Int>() shouldBe sorted<Int>()168 listOf(1) shouldBe sorted<Int>()169 listOf(1, 2, 3, 4) shouldBe sorted<Int>()170 shouldThrow<AssertionError> {171 listOf(2, 1) shouldBe sorted<Int>()172 }.shouldHaveMessage("List [2, 1] should be sorted. Element 2 at index 0 was greater than element 1")173 listOf(1, 2, 6, 9).shouldBeSorted()174 shouldThrow<AssertionError> {175 listOf(2, 1).shouldBeSorted()176 }.shouldHaveMessage("List [2, 1] should be sorted. Element 2 at index 0 was greater than element 1")177 shouldThrow<AssertionError> {178 listOf(1, 2, 3).shouldNotBeSorted()179 }.shouldHaveMessage("List [1, 2, 3] should not be sorted")180 }181 "restrict items at the error message" {182 val longList = (1..1000).toList()183 shouldThrow<AssertionError> {184 longList.shouldNotBeSorted()185 }.shouldHaveMessage("List [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...and 980 more (set the 'kotest.assertions.collection.print.size' JVM property to see more / less items)] should not be sorted")186 }187 }188 "sortedBy" should {189 val items = listOf(190 1 to "I",191 2 to "II",192 4 to "IV",193 5 to "V",194 6 to "VI",195 9 to "IX",196 10 to "X"197 )198 "compare by the tranformed value" {199 items.shouldBeSortedBy { it.first }200 items.shouldNotBeSortedBy { it.second }201 }202 }203 "shouldBeIncreasing" should {204 "test that a collection is monotonically increasing" {205 listOf(1, 2, 2, 3) shouldBe monotonicallyIncreasing<Int>()206 listOf(6, 5) shouldNotBe monotonicallyIncreasing<Int>()207 listOf(1, 2, 2, 3).shouldBeMonotonicallyIncreasing()208 listOf(6, 5).shouldNotBeMonotonicallyIncreasing()209 }210 "test that a collection is monotonically increasing according to comparator" {211 val comparator = Comparator(desc)212 listOf(3, 2, 2, 1) shouldBe monotonicallyIncreasingWith(comparator)213 listOf(5, 6) shouldNotBe monotonicallyIncreasingWith(comparator)214 listOf(3, 2, 2, 1).shouldBeMonotonicallyIncreasingWith(comparator)215 listOf(5, 6).shouldNotBeMonotonicallyIncreasingWith(comparator)216 }217 "test that a collection is strictly increasing" {218 listOf(1, 2, 3) shouldBe strictlyIncreasing<Int>()219 listOf(1, 2, 2, 3) shouldNotBe strictlyIncreasing<Int>()220 listOf(6, 5) shouldNotBe strictlyIncreasing<Int>()221 listOf(1, 2, 3).shouldBeStrictlyIncreasing()222 listOf(1, 2, 2, 3).shouldNotBeStrictlyIncreasing()223 listOf(6, 5).shouldNotBeStrictlyIncreasing()224 }225 "test that a collection is strictly increasing according to comparator" {226 val comparator = Comparator(desc)227 listOf(3, 2, 1) shouldBe strictlyIncreasingWith(comparator)228 listOf(3, 2, 2, 1) shouldNotBe strictlyIncreasingWith(comparator)229 listOf(5, 6) shouldNotBe strictlyIncreasingWith(comparator)230 listOf(3, 2, 1).shouldBeStrictlyIncreasingWith(comparator)231 listOf(3, 2, 2, 1).shouldNotBeStrictlyIncreasingWith(comparator)232 listOf(5, 6).shouldNotBeStrictlyIncreasingWith(comparator)233 }234 }235 "shouldBeDecreasing" should {236 "test that a collection is monotonically decreasing" {237 listOf(3, 2, 2, -4) shouldBe monotonicallyDecreasing<Int>()238 listOf(5, 6) shouldNotBe monotonicallyDecreasing<Int>()239 listOf(3, 2, 2, -4).shouldBeMonotonicallyDecreasing()240 listOf(5, 6).shouldNotBeMonotonicallyDecreasing()241 }242 "test that a collection is monotonically decreasing according to comparator" {243 val comparator = Comparator(desc)244 listOf(-4, 2, 2, 3) shouldBe monotonicallyDecreasingWith(comparator)245 listOf(6, 5) shouldNotBe monotonicallyDecreasingWith(comparator)246 listOf(-4, 2, 2, 3).shouldBeMonotonicallyDecreasingWith(comparator)247 listOf(6, 5).shouldNotBeMonotonicallyDecreasingWith(comparator)248 }249 "test that a collection is strictly decreasing" {250 listOf(3, 2, -4) shouldBe strictlyDecreasing<Int>()251 listOf(3, 2, 2, -4) shouldNotBe strictlyDecreasing<Int>()252 listOf(5, 6) shouldNotBe strictlyDecreasing<Int>()253 listOf(3, 2, -4).shouldBeStrictlyDecreasing()254 listOf(3, 2, 2, -4).shouldNotBeStrictlyDecreasing()255 listOf(5, 6).shouldNotBeStrictlyDecreasing()256 }257 "test that a collection is strictly decreasing according to comparator" {258 val comparator = Comparator(desc)259 listOf(-4, 2, 3) shouldBe strictlyDecreasingWith(comparator)260 listOf(-4, 2, 2, 3) shouldNotBe strictlyDecreasingWith(comparator)261 listOf(6, 5) shouldNotBe strictlyDecreasingWith(comparator)262 listOf(-4, 2, 3).shouldBeStrictlyDecreasingWith(comparator)263 listOf(-4, 2, 2, 3).shouldNotBeStrictlyDecreasingWith(comparator)264 listOf(6, 5).shouldNotBeStrictlyDecreasingWith(comparator)265 }266 }267 "haveDuplicates" should {268 "test that a collection is unique" {269 listOf(1, 2, 3, 3) should containDuplicates()270 listOf(1, 2, 3, 4) shouldNot containDuplicates()271 listOf(1, 2, 3, 3).shouldContainDuplicates()272 listOf(1, 2, 3, 4).shouldNotContainDuplicates()273 }274 }275 "singleElement" should {276 "test that a collection contains a single given element" {277 listOf(1) shouldBe singleElement(1)278 listOf(1).shouldHaveSingleElement(1)279 shouldThrow<AssertionError> {280 listOf(1) shouldBe singleElement(2)281 }.shouldHaveMessage("Collection should be a single element of 2 but has 1 elements: [1]")282 shouldThrow<AssertionError> {283 listOf(1, 2) shouldBe singleElement(2)284 }.shouldHaveMessage("Collection should be a single element of 2 but has 2 elements: [1, 2]")285 }286 }287 "singleElement with predicate" should {288 "test that a collection contains a single element by given predicate" {289 listOf(1) shouldHave singleElement { e -> e == 1 }290 listOf(1).shouldHaveSingleElement { e -> e == 1 }291 shouldThrow<AssertionError> {292 listOf(1) shouldHave singleElement { e -> e == 2 }293 }.shouldHaveMessage("Collection should have a single element by a given predicate but has 0 elements: [1]")294 shouldThrow<AssertionError> {295 listOf(2, 2) shouldHave singleElement { e -> e == 2 }296 }.shouldHaveMessage("Collection should have a single element by a given predicate but has 2 elements: [2, 2]")297 }298 }299 "should contain element" should {300 "test that a collection contains an element" {301 val col = listOf(1, 2, 3)302 col should contain(2)303 col should contain(2.0) // uses strict num equality = false304 shouldThrow<AssertionError> {305 col should contain(4)306 }.shouldHaveMessage("Collection should contain element 4 based on object equality; but the collection is [1, 2, 3]")307 }308 }309 "should contain element based on a custom equality object" should {310 "test that a collection contains an element" {311 val col = listOf(1, 2, 3.0)312 val verifier = Equality.byObjectEquality<Number>(strictNumberEquality = true)313 col should contain(2, verifier)314 col should contain(3.0, verifier)315 shouldThrow<AssertionError> {316 col should contain(3, verifier)317 }.shouldHaveMessage("Collection should contain element 3 based on object equality; but the collection is [1, 2, 3.0]")318 }319 }320 "shouldBeLargerThan" should {321 "test that a collection is larger than another collection" {322 val col1 = listOf(1, 2, 3)323 val col2 = setOf(1, 2, 3, 4)324 col2.shouldBeLargerThan(col1)325 col2 should beLargerThan(col1)326 col1 shouldNot beLargerThan(col2)327 shouldThrow<AssertionError> {328 col1.shouldBeLargerThan(col2)329 }.shouldHaveMessage("Collection of size 3 should be larger than collection of size 4")330 }331 }332 "shouldBeSmallerThan" should {333 "test that a collection is smaller than another collection" {334 val col1 = listOf(1, 2, 3)335 val col2 = setOf(1, 2, 3, 4)336 col1.shouldBeSmallerThan(col2)337 col1 should beSmallerThan(col2)338 col2 shouldNot beSmallerThan(col1)339 shouldThrow<AssertionError> {340 col2.shouldBeSmallerThan(col1)341 }.shouldHaveMessage("Collection of size 4 should be smaller than collection of size 3")342 }343 }344 "shouldBeSameSizeAs" should {345 "test that a collection is the same size as another collection" {346 val col1 = listOf(1, 2, 3)347 val col2 = setOf(1, 2, 3)348 val col3 = listOf(1, 2, 3, 4)349 col1.shouldBeSameSizeAs(col2)350 col1 should beSameSizeAs(col2)351 col1 shouldNot beSameSizeAs(col3)352 shouldThrow<AssertionError> {353 col1.shouldBeSameSizeAs(col3)354 }.shouldHaveMessage("Collection of size 3 should be the same size as collection of size 4")355 }356 }357 "haveSize" should {358 "test that a collection has a certain size" {359 val col1 = listOf(1, 2, 3)360 col1 should haveSize(3)361 col1.shouldHaveSize(3)362 shouldThrow<AssertionError> {363 col1 should haveSize(2)364 }365 val col2 = emptyList<String>()366 col2 should haveSize(0)367 shouldThrow<AssertionError> {368 col2 should haveSize(1)369 }370 listOf(1, 2, 3).shouldNotHaveSize(1)371 listOf(1, 2, 3).shouldNotHaveSize(4)372 shouldThrow<AssertionError> {373 listOf(1, 2, 3).shouldNotHaveSize(3)374 }.shouldHaveMessage("Collection should not have size 3. Values: [1, 2, 3]")375 }376 }377 "should be singleton" should {378 "pass for collection with a single element" {379 listOf(1).shouldBeSingleton()380 }381 "fail for collection with 0 elements" {382 shouldThrow<AssertionError> {383 listOf<Int>().shouldBeSingleton()384 }.shouldHaveMessage("Collection should have size 1 but has size 0. Values: []")385 }386 "fail for collection with 2+ elements" {387 shouldThrow<AssertionError> {388 listOf(1, 2).shouldBeSingleton()389 }.shouldHaveMessage("Collection should have size 1 but has size 2. Values: [1, 2]")390 shouldThrow<AssertionError> {391 listOf(1, 2, 3, 4).shouldBeSingleton()392 }.shouldHaveMessage("Collection should have size 1 but has size 4. Values: [1, 2, 3, 4]")393 }394 }395 "should be singleton with block" should {396 "pass for collection with a single element" {397 listOf(1).shouldBeSingleton { it shouldBe 1 }398 }399 "fail for collection with 0 elements" {400 shouldThrow<AssertionError> {401 listOf<Int>().shouldBeSingleton { it shouldBe 1 }402 }.shouldHaveMessage("Collection should have size 1 but has size 0. Values: []")403 }404 "fail for collection with a single incorrect elements" {405 shouldThrow<AssertionError> {406 listOf(2).shouldBeSingleton { it shouldBe 1 }407 }.shouldHaveMessage("expected:<1> but was:<2>")408 }409 "fail for collection with 2+ elements" {410 shouldThrow<AssertionError> {411 listOf(1, 2).shouldBeSingleton { it shouldBe 1 }412 }.shouldHaveMessage("Collection should have size 1 but has size 2. Values: [1, 2]")413 shouldThrow<AssertionError> {414 listOf(1, 2, 3, 4).shouldBeSingleton { it shouldBe 1 }415 }.shouldHaveMessage("Collection should have size 1 but has size 4. Values: [1, 2, 3, 4]")416 }417 }418 "should not be singleton" should {419 "pass for collection with 0 elements" {420 listOf<Int>().shouldNotBeSingleton()421 }422 "pass for collection with 2+ elements" {423 listOf(1, 2).shouldNotBeSingleton()424 listOf(1, 2, 3, 4).shouldNotBeSingleton()425 }426 "fail for collection with a single element" {427 shouldThrow<AssertionError> {428 listOf(1).shouldNotBeSingleton()429 }.shouldHaveMessage("Collection should not have size 1. Values: [1]")430 }431 }432 "shouldExist" should {433 "test that a collection contains at least one element that matches a predicate" {434 val list = listOf(1, 2, 3)435 list.shouldExist { it == 2 }436 }437 }438 "shouldHaveAtLeastSize" should {439 "test that a collection has at least a certain number of elements" {440 val list = listOf(1, 2, 3)441 list.shouldHaveAtLeastSize(2)442 list shouldHave atLeastSize(2)443 val set = setOf(1, 2, 3)444 set.shouldHaveAtLeastSize(3)445 set shouldHave atLeastSize(3)446 shouldThrow<AssertionError> {447 list.shouldHaveAtLeastSize(4)448 }.shouldHaveMessage("Collection [1, 2, 3] should contain at least 4 elements")449 shouldThrow<AssertionError> {450 list shouldHave atLeastSize(4)451 }.shouldHaveMessage("Collection [1, 2, 3] should contain at least 4 elements")452 shouldThrow<AssertionError> {453 list shouldNotHave atLeastSize(2)454 }.shouldHaveMessage("Collection [1, 2, 3] should contain less than 2 elements")455 }456 }457 "shouldHaveAtMostSize" should {458 "test that a collection has at least a certain number of elements" {459 val list = listOf(1, 2, 3)460 list.shouldHaveAtMostSize(3)461 list shouldHave atMostSize(3)462 list.shouldHaveAtMostSize(4)463 list shouldHave atMostSize(4)464 val set = setOf(1, 2, 3)465 set.shouldHaveAtMostSize(3)466 set shouldHave atMostSize(3)467 set.shouldHaveAtMostSize(4)468 set shouldHave atMostSize(4)469 shouldThrow<AssertionError> {470 list.shouldHaveAtMostSize(2)471 }.shouldHaveMessage("Collection [1, 2, 3] should contain at most 2 elements")472 shouldThrow<AssertionError> {473 list shouldHave atMostSize(2)474 }.shouldHaveMessage("Collection [1, 2, 3] should contain at most 2 elements")475 shouldThrow<AssertionError> {476 list shouldNotHave atMostSize(4)477 }.shouldHaveMessage("Collection [1, 2, 3] should contain more than 4 elements")478 }479 }480 "containNoNulls" should {481 "test that a collection contains zero nulls" {482 emptyList<String>() should containNoNulls()483 listOf(1, 2, 3) should containNoNulls()484 listOf(null, null, null) shouldNot containNoNulls()485 listOf(1, null, null) shouldNot containNoNulls()486 emptyList<String>().shouldContainNoNulls()487 listOf(1, 2, 3).shouldContainNoNulls()488 listOf(null, null, null).shouldNotContainNoNulls()489 listOf(1, null, null).shouldNotContainNoNulls()490 shouldThrow<AssertionError> {491 listOf(null, null, null).shouldContainNoNulls()492 }.shouldHaveMessage("Collection should not contain nulls")493 shouldThrow<AssertionError> {494 listOf(1, 2, 3).shouldNotContainNoNulls()495 }.shouldHaveMessage("Collection should have at least one null")496 }497 "support type inference for subtypes of collection" {498 val tests = listOf(499 TestSealed.Test1("test1"),500 TestSealed.Test2(2)501 )502 tests should containNoNulls()503 tests.shouldContainNoNulls()504 }505 }506 "containOnlyNulls" should {507 "test that a collection contains only nulls" {508 emptyList<String>() should containOnlyNulls()509 listOf(null, null, null) should containOnlyNulls()510 listOf(1, null, null) shouldNot containOnlyNulls()511 listOf(1, 2, 3) shouldNot containOnlyNulls()512 listOf(null, 1, 2, 3).shouldNotContainOnlyNulls()513 listOf(1, 2, 3).shouldNotContainOnlyNulls()514 listOf(null, null, null).shouldContainOnlyNulls()515 }516 }517 "matchInOrder" should {518 "test that a collection matches the assertions in the given order, duplicates permitted" {519 withClue("Gaps not allowed") {520 shouldFail {521 listOf(1, 2, 2, 3) should matchInOrder(522 { it shouldBe 1 },523 { it shouldBe 2 },524 { it shouldBe 3 }525 )526 }527 }528 arrayOf(2, 2, 3).shouldMatchInOrder(529 { it shouldBe 2 },530 { it shouldBe 2 },531 { it shouldBe 3 },532 )533 }534 "failure shows best result" {535 shouldFail {536 listOf(1, 2, 3, 1, 2, 1, 2).shouldMatchInOrder(537 { it shouldBe 1 },538 { it shouldBe 2 },539 { it shouldBe 1 },540 { it shouldBe 3 },541 )542 }.message shouldBe """543 Expected a sequence of elements to pass the assertions, but failed to match all assertions544 Best result when comparing from index [3], where 3 elements passed, but the following elements failed:545 6 => expected:<3> but was:<2>546 """.trimIndent()547 }548 "Non existing element causes error" {549 shouldThrow<AssertionError> {550 listOf(1, 2, 3).shouldMatchInOrder(551 { it shouldBe 1 },552 { it shouldBe 2 },553 { it shouldBe 6 }554 )555 }556 }557 "out-of-order elements cause error" {558 shouldThrow<AssertionError> {559 listOf(1, 2, 3) should matchInOrder(560 { it shouldBe 2 },561 { it shouldBe 1 },562 { it shouldBe 3 }563 )564 }565 }566 "work with unsorted collections" {567 val actual = listOf(5, 3, 1, 2, 4, 2)568 withClue("should match 4th, 5th and 6th elements ([.., 2, 4, 2])") {569 actual should matchInOrder(570 { it shouldBe 2 },571 { it shouldBeGreaterThan 3 },572 { it shouldBeInRange 2..2 }573 )574 }575 }576 "negation should work" {577 shouldFail {578 listOf(1, 2, 3, 4).shouldNotMatchInOrder(579 { it shouldBe 2 },580 { it shouldBe 3 },581 )582 }.message shouldBe """583 Expected some assertion to fail but all passed584 """.trimIndent()585 listOf(1, 2, 3, 4).shouldNotMatchInOrder(586 { it shouldBe 2 },587 { it shouldBe 4 }588 )589 }590 }591 "matchInOrderSubset" should {592 "test that a collection matches the assertions in the given order without gaps" {593 listOf(1, 1, 2, 2, 3, 3) should matchInOrderSubset(594 { it shouldBe 1 },595 { it shouldBe 2 },596 { it shouldBe 2 },597 { it shouldBe 3 }598 )599 arrayOf(1, 1, 1).shouldMatchInOrderSubset(600 { it shouldBe 1 }601 )602 }603 "Negation should work" {604 shouldFail {605 listOf(1, 2, 3, 4).shouldNotMatchInOrderSubset(606 { it shouldBe 2 },607 { it shouldBe 4 },608 )609 }.message shouldBe """610 Expected some assertion to fail but all passed611 """.trimIndent()612 arrayOf(1, 2, 3, 4).shouldNotMatchInOrder(613 { it shouldBe 4 },614 { it shouldBe 1 }615 )616 }617 "Non existing element causes error" {618 shouldThrow<AssertionError> {619 listOf(1, 1, 2, 2, 3, 3) should matchInOrderSubset(620 { it shouldBe 1 },621 { it shouldBe 2 },622 { it shouldBe 6 }623 )624 }.message shouldBe """625 Expected a sequence of elements to pass the assertions, possibly with gaps between but failed to match all assertions626 Best result when comparing from index [0], where 2 elements passed, but the following elements failed:627 3 => expected:<6> but was:<2>628 4 => expected:<6> but was:<3>629 5 => expected:<6> but was:<3>630 """.trimIndent()631 }632 "out-of-order elements cause error" {633 shouldThrow<AssertionError> {634 listOf(1, 2, 3) should matchInOrderSubset(635 { it shouldBe 2 },636 { it shouldBe 1 },637 { it shouldBe 3 }638 )639 }640 }641 "gaps should be ok" {642 listOf(1, 1, 2, 2, 3, 3) should matchInOrderSubset(643 { it shouldBe 1 },644 { it shouldBe 2 },645 { it shouldBe 3 }646 )647 }648 "work with unsorted collections" {649 val actual = listOf(5, 3, 1, 2, 4, 2)650 withClue("should match 4th, 5th and 6th elements ([.., 2, 4, 2])") {651 actual should matchInOrderSubset(652 { it shouldBe 2 },653 { it shouldBeGreaterThan 3 },654 { it shouldBeInRange 2..2 }655 )656 }657 }658 }659 "matchEach" should {660 "test that a collection matches the assertions in the given order without gaps" {661 listOf(1, 3, 7) should matchEach(662 { it shouldBe 1 },663 { it shouldBeInRange 2..4 },664 { it shouldBeGreaterThan 2 }665 )666 }667 "Negation should work" {668 shouldFail{669 listOf(1, 2).shouldNotMatchEach(670 { it shouldBe 1 },671 { it shouldBe 2 },672 )673 }.message shouldBe """674 Expected some element to fail its assertion, but all passed.675 """.trimIndent()676 arrayOf(1, 2).shouldNotMatchEach(677 { it shouldBe 2 },678 { it shouldBe 1 }679 )680 }681 "No assertion exists for each element" {682 shouldFail {683 listOf(1, -1, 999) should matchEach(684 { it shouldBe 1 }685 )686 }.message shouldBe """687 Expected each element to pass its assertion, but found issues at indexes: [1, 2]688 1 => Element has no corresponding assertion. Only 1 assertions provided689 2 => Element has no corresponding assertion. Only 1 assertions provided690 """.trimIndent()691 }692 "Too many assertions cause error" {693 shouldFail {694 listOf(1, 3, 7) should matchEach(695 { it shouldBe 1 },696 { it shouldBe 3 },697 { it shouldBe 7 },698 { it shouldBe 7 },699 { it shouldBe 7 },700 )701 }.message shouldBe """702 Expected each element to pass its assertion, but found issues at indexes: [3, 4]703 3 => No actual element for assertion at index 3704 4 => No actual element for assertion at index 4705 """.trimIndent()706 }707 "Non matching element causes error" {708 shouldFail {709 listOf(1, 3, 7) should matchEach(710 { it shouldBe 1 },711 { it shouldBeInRange 2..4 },712 { it shouldBeGreaterThan 7 }713 )714 }.message shouldBe """715 Expected each element to pass its assertion, but found issues at indexes: [2]716 2 => 7 should be > 7717 """.trimIndent()718 }719 "out-of-order elements cause error" {720 shouldThrow<AssertionError> {721 setOf(2, 3, 1) should matchEach(722 { it shouldBe 2 },723 { it shouldBe 1 },724 { it shouldBe 3 }725 )726 }.message shouldBe """727 Expected each element to pass its assertion, but found issues at indexes: [1, 2]728 1 => expected:<1> but was:<3>729 2 => expected:<3> but was:<1>730 """.trimIndent()731 }732 "gaps cause errors" {733 shouldThrow<AssertionError> {734 listOf(1, 1, 2, 2, 3, 3) should matchEach(735 { it shouldBe 1 },736 { it shouldBe 2 },737 { it shouldBe 3 }738 )739 }.message shouldBe """740 Expected each element to pass its assertion, but found issues at indexes: [1, 2, 3, 4, 5]741 1 => expected:<2> but was:<1>742 2 => expected:<3> but was:<2>743 3 => Element has no corresponding assertion. Only 3 assertions provided744 4 => Element has no corresponding assertion. Only 3 assertions provided745 5 => Element has no corresponding assertion. Only 3 assertions provided746 """.trimIndent()747 }748 }749 "existInOrder" should {750 "test that a collection matches the predicates in the given order, duplicates permitted" {751 val col = listOf(1, 1, 2, 2, 3, 3)752 col should existInOrder(753 { it == 1 },754 { it == 2 },755 { it == 3 }756 )757 col should existInOrder({ it == 1 })758 shouldThrow<AssertionError> {759 col should existInOrder(760 { it == 1 },761 { it == 2 },762 { it == 6 }763 )764 }...

Full Screen

Full Screen

Chap5.kt

Source:Chap5.kt Github

copy

Full Screen

1package org.kiworkshop.learningfpinkotlin2import io.kotest.core.spec.style.StringSpec3import io.kotest.matchers.collections.shouldBeEmpty4import io.kotest.matchers.collections.shouldContainExactly5import io.kotest.matchers.ints.shouldBeLessThan6import io.kotest.matchers.longs.shouldBeGreaterThan7import io.kotest.matchers.longs.shouldBeLessThan8import io.kotest.matchers.longs.shouldBeLessThanOrEqual9import io.kotest.matchers.shouldBe10import org.kiworkshop.learningfpinkotlin.FunList.Cons11import org.kiworkshop.learningfpinkotlin.FunList.Nil12import kotlin.math.sqrt13class Chap5 : StringSpec({14 // 연습문제 5-7, takeWhile에서 element가 모두 p를 만족하지 못했을 때 원본 리스트가 아니라 빈 리스트를 내보내야 하는거 아닌가?15 // 142쪽에 IntRange를 FunStream<Int>로 변환하는 코드 작성하기가 꽤 머리아프다.16 // IntRange를 FunList<Int>로 변환하는 코드를 꼭 재귀를 사용해서 구현해보자.17 val list = funListOf(1, 2, 3, 4, 5)18 fun <T> FunList<T>.toList(): List<T> {19 tailrec fun FunList<T>.toList(acc: MutableList<T>): MutableList<T> = when (this) {20 is Nil -> acc21 is Cons -> this.tail.toList(acc.add(this.head).let { acc })22 }23 return this.toList(mutableListOf())24 }25 fun <T> FunStream<T>.toList(): List<T> {26 tailrec fun FunStream<T>.toList(acc: MutableList<T>): MutableList<T> = when (this) {27 is FunStream.Nil -> acc28 is FunStream.Cons -> this.tail().toList(acc.add(this.head()).let { acc })29 }30 return this.toList(mutableListOf())31 }32 "Example 5-1" {33 // when34 val intList: FunList<Int> = Cons(1, Cons(2, Cons(3, Cons(4, Cons(5, Nil)))))35 // then36 intList.toList().shouldContainExactly(1, 2, 3, 4, 5)37 }38 "Example 5-2" {39 // when40 val doubleList: FunList<Double> = Cons(1.0, Cons(2.0, Cons(3.0, Cons(4.0, Cons(5.0, Nil)))))41 // then42 doubleList.toList().shouldContainExactly(1.0, 2.0, 3.0, 4.0, 5.0)43 }44 "Example 5-3" {45 Cons(1, Nil).addHead(2).toList().shouldContainExactly(2, 1)46 Cons(1, Nil).appendTail(2).toList().shouldContainExactly(1, 2)47 Cons(1, Nil).appendTail(2).reverse().toList().shouldContainExactly(2, 1)48 Cons(1, Nil).addHead(2).addHead(3).getTail().toList().shouldContainExactly(2, 1)49 Cons(1, Nil).addHead(2).addHead(3).getHead() shouldBe 350 }51 "Example 5-4" {52 // test filter53 list.filter { it < 3 }.toList().shouldContainExactly(1, 2)54 // test drop55 list.toList().shouldContainExactly(1, 2, 3, 4, 5)56 list.drop(3).toList().shouldContainExactly(4, 5)57 list.drop(10).toList().shouldBeEmpty()58 list.toList().shouldContainExactly(1, 2, 3, 4, 5)59 }60 "Example 5-5" {61 list.toList().shouldContainExactly(1, 2, 3, 4, 5)62 list.dropWhile { it != 3 }.toList().shouldContainExactly(3, 4, 5)63 list.toList().shouldContainExactly(1, 2, 3, 4, 5)64 }65 "Example 5-6" {66 list.take(3).toList().shouldContainExactly(1, 2, 3)67 }68 "Example 5-7" {69 list.takeWhile { it < 3 }.toList().shouldContainExactly(1, 2)70 list.takeWhile { false }.toList().shouldBeEmpty()71 listOf(1, 2, 3, 4, 5).takeWhile { false }.shouldBeEmpty()72 }73 "Example 5-8" {74 list.map { it * 2 }.toList().shouldContainExactly(2, 4, 6, 8, 10)75 list.indexedMap { i, elem -> (i + 1) * 10 + elem }.toList().shouldContainExactly(11, 22, 33, 44, 55)76 }77 "Example 5-9" {78 list.maximumByFoldLeft() shouldBe 579 }80 "Example 5-10" {81 list.filterByFoldLeft { it and 1 == 1 }.toList().shouldContainExactly(1, 3, 5)82 }83 "Example 5-11" {84 list.reverseByFoldRight().toList().shouldContainExactly(5, 4, 3, 2, 1)85 }86 "Example 5-12" {87 list.filterByFoldRight { it and 1 == 1 }.toList().shouldContainExactly(1, 3, 5)88 }89 "Example 5-13" {90 funListOf(1, 2, 3, 4, 5).zip(funListOf(1.0, 2.0)).toList().mapIndexed { index, pair ->91 index.shouldBeLessThan(2)92 pair.first shouldBe (index + 1)93 pair.second shouldBe (index + 1).toDouble()94 }95 }96 data class Entry(val english: String, val numeric: Int)97 "Example 5-14" {98 funListOf(1, 2, 3, 4, 5).zipWith(::Pair, funListOf(1.0, 2.0)).toList().mapIndexed { index, pair ->99 index.shouldBeLessThan(2)100 pair.first shouldBe (index + 1)101 pair.second shouldBe (index + 1).toDouble()102 }103 funListOf(Entry("One", 1), Entry("Two", 2), Entry("Three", 3))104 .associate { Pair(it, it.numeric) }105 .let { map ->106 map[Entry("One", 1)] shouldBe 1107 map[Entry("Two", 2)] shouldBe 2108 map[Entry("Three", 3)] shouldBe 3109 }110 }111 "Example 5-15" {112 funListOf(113 Entry("Three", 30),114 Entry("One", 1),115 Entry("Two", 20),116 Entry("One", 10),117 Entry("Two", 2),118 Entry("Three", 3)119 )120 .groupBy { it.english }121 .let { map ->122 map.getValue("One").toList().shouldContainExactly(Entry("One", 1), Entry("One", 10))123 map.getValue("Two").toList().shouldContainExactly(Entry("Two", 20), Entry("Two", 2))124 map.getValue("Three").toList().shouldContainExactly(Entry("Three", 30), Entry("Three", 3))125 }126 }127 // list와 sequence의 차이, atomic kotlin에서 horizontal과 vertical로 비교한거 공유하자.128 fun testBigIntList(129 bigIntList: List<Int>,130 assertImperativeWay: (Long) -> Unit,131 assertFunctionalWay: (Long) -> Unit,132 assertRealFunctionalWay: (Long) -> Unit133 ) {134 fun imperativeWay(intList: List<Int>): Int {135 for (value in intList) {136 val doubleValue = value * value137 if (doubleValue < 10) {138 return doubleValue139 }140 }141 throw NoSuchElementException("There is no value")142 }143 fun functionalWay(intList: List<Int>): Int = intList.map { n -> n * n }.first { n -> n < 10 }144 fun realFunctionalWay(intList: List<Int>): Int = intList.asSequence().map { n -> n * n }.first { n -> n < 10 }145 fun test(f: (List<Int>) -> Int, assert: (Long) -> Unit) {146 System.currentTimeMillis().let { start ->147 f(bigIntList)148 (System.currentTimeMillis() - start).let {149 println("imperativeWay: $it ms")150 assert(it)151 }152 }153 }154 test(::imperativeWay, assertImperativeWay)155 test(::functionalWay, assertFunctionalWay)156 test(::realFunctionalWay, assertRealFunctionalWay)157 }158 "Example 5-16" {159 println("increasing list")160 testBigIntList(161 bigIntList = (1..10000000).toList(),162 assertImperativeWay = { millis: Long -> millis.shouldBeLessThanOrEqual(1) },163 assertFunctionalWay = { millis: Long -> millis.shouldBeGreaterThan(100) },164 assertRealFunctionalWay = { millis: Long -> millis.shouldBeLessThan(10) },165 )166 println("\ndecreasing list")167 testBigIntList(168 bigIntList = (10000000 downTo 1).toList(),169 assertImperativeWay = { millis: Long -> millis.shouldBeLessThanOrEqual(1) },170 assertFunctionalWay = { millis: Long -> millis.shouldBeGreaterThan(100) }, // 왜 functionalWay만 100ms가 넘지?171 assertRealFunctionalWay = { millis: Long -> millis.shouldBeLessThanOrEqual(1) },172 )173 }174 "Example 5-17" {175 funStreamOf(1, 2, 3).getHead() shouldBe 1176 funStreamOf(1, 2, 3).getTail()177 .toString() shouldBe "Cons(head=() -> T, tail=() -> org.kiworkshop.learningfpinkotlin.FunStream<T>)"178 funStreamOf(1, 2, 3).getTail().toList().shouldContainExactly(2, 3)179 funStreamOf(1, 2, 3).sum() shouldBe 6180 funStreamOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10).sum() shouldBe 55181 }182 "Example 5-18" {183 funStreamOf(1, 2, 3).product() shouldBe 6184 funStreamOf(2, 5).product() shouldBe 10185 }186 "Example 5-19" {187 funStreamOf(1, 2, 3).appendTail(4).toList().shouldContainExactly(1, 2, 3, 4)188 }189 "Example 5-20" {190 funStreamOf(1, 2, 3).filter { it and 1 == 1 }.toList().shouldContainExactly(1, 3)191 }192 "Example 5-21" {193 funStreamOf(1, 2, 3).map { it * 2.0 }.toList().shouldContainExactly(2.0, 4.0, 6.0)194 }195 "performanceTest" {196 fun funListWay(intList: FunList<Int>): Int = intList197 .map { n -> n * n }198 .filter { n -> n < 1000000 }199 .map { n -> n - 2 }200 .filter { n -> n < 1000 }201 .map { n -> n * 10 }202 .getHead()203 fun funStreamWay(intList: FunStream<Int>): Int = intList204 .map { n -> n * n }205 .filter { n -> n < 1000000 }206 .map { n -> n - 2 }207 .filter { n -> n < 1000 }208 .map { n -> n * 10 }209 .getHead()210 fun IntRange.toFunList(): FunList<Int> {211 tailrec fun IntIterator.toFunList(acc: FunList<Int> = Nil): FunList<Int> =212 if (this.hasNext()) {213 toFunList(Cons(this.nextInt(), acc))214 } else {215 acc216 }217 return this.reversed().iterator().toFunList()218 }219 fun IntRange.toFunStream(): FunStream<Int> {220 fun IntIterator.toFunStream(): FunStream<Int> {221 if (!this.hasNext()) {222 return FunStream.Nil223 }224 val next = this.nextInt()225 return if (this.hasNext())226 FunStream.Cons({ next }) { toFunStream() }227 else228 FunStream.Cons({ next }) { FunStream.Nil }229 }230 return this.iterator().toFunStream()231 }232 (1..3).toFunList().toList().shouldContainExactly(1, 2, 3)233 (1..3).toFunStream().toList().shouldContainExactly(1, 2, 3)234 (0 until 0).toFunStream().toList().shouldBeEmpty()235 fun howMuchMillsItTakes(testName: String, runnable: () -> Unit): Long {236 return System.currentTimeMillis().let { start ->237 println(testName)238 runnable()239 val calculationMillis = (System.currentTimeMillis() - start)240 println("$calculationMillis ms")241 calculationMillis242 }243 }244 val bigIntList = (1..10000000).toFunList()245 val bigIntStream = (1..10000000).toFunStream()246// 이 테스트 하나만 돌릴때는 괜찮은데 전체 테스트를 돌리면 메모리가 부족해서 예외가 발생한다.247// howMuchMillsItTakes("funListWay") { funListWay(bigIntList) } shouldBeGreaterThan 1000248 println()249 howMuchMillsItTakes("funStreamWay") { funStreamWay(bigIntStream) } shouldBeLessThan 10250 }251 "Example 5-22" {...

Full Screen

Full Screen

CollectionMatchers.kt

Source:CollectionMatchers.kt Github

copy

Full Screen

1package io.kotest.matchers.collections2import io.kotest.assertions.show.show3import io.kotest.matchers.Matcher4import io.kotest.matchers.MatcherResult5import io.kotest.matchers.neverNullMatcher6fun <T> haveSizeMatcher(size: Int) = object : Matcher<Collection<T>> {7 override fun test(value: Collection<T>) =8 MatcherResult(9 value.size == size,10 { "Collection should have size $size but has size ${value.size}. Values: ${value.show().value}" },11 { "Collection should not have size $size. Values: ${value.show().value}" }12 )13}14fun <T> beEmpty(): Matcher<Collection<T>> = object : Matcher<Collection<T>> {15 override fun test(value: Collection<T>): MatcherResult = MatcherResult(16 value.isEmpty(),17 { "Collection should be empty but contained ${value.show().value}" },18 { "Collection should not be empty" }19 )20}21fun <T> existInOrder(vararg ps: (T) -> Boolean): Matcher<Collection<T>?> = existInOrder(ps.asList())22/**23 * Assert that a collections contains a subsequence that matches the given subsequence of predicates, possibly with24 * values in between.25 */26fun <T> existInOrder(predicates: List<(T) -> Boolean>): Matcher<Collection<T>?> = neverNullMatcher { actual ->27 require(predicates.isNotEmpty()) { "predicates must not be empty" }28 var subsequenceIndex = 029 val actualIterator = actual.iterator()30 while (actualIterator.hasNext() && subsequenceIndex < predicates.size) {31 if (predicates[subsequenceIndex](actualIterator.next())) subsequenceIndex += 132 }33 MatcherResult(34 subsequenceIndex == predicates.size,35 { "${actual.show().value} did not match the predicates ${predicates.show().value} in order" },36 { "${actual.show().value} should not match the predicates ${predicates.show().value} in order" }37 )38}39fun <T> haveSize(size: Int): Matcher<Collection<T>> = haveSizeMatcher(size)40fun <T> singleElement(t: T): Matcher<Collection<T>> = object : Matcher<Collection<T>> {41 override fun test(value: Collection<T>) = MatcherResult(42 value.size == 1 && value.first() == t,43 { "Collection should be a single element of $t but has ${value.size} elements: ${value.show().value}" },44 { "Collection should not be a single element of $t" }45 )46}47fun <T> singleElement(p: (T) -> Boolean): Matcher<Collection<T>> = object : Matcher<Collection<T>> {48 override fun test(value: Collection<T>): MatcherResult {49 val filteredValue: List<T> = value.filter(p)50 return MatcherResult(51 filteredValue.size == 1,52 { "Collection should have a single element by a given predicate but has ${filteredValue.size} elements: ${value.show().value}" },53 { "Collection should not have a single element by a given predicate" }54 )55 }56}57fun <T : Comparable<T>> beSorted(): Matcher<List<T>> = sorted()58fun <T : Comparable<T>> sorted(): Matcher<List<T>> = object : Matcher<List<T>> {59 override fun test(value: List<T>): MatcherResult {60 val failure = value.withIndex().firstOrNull { (i, it) -> i != value.lastIndex && it > value[i + 1] }61 val elementMessage = when (failure) {62 null -> ""63 else -> ". Element ${failure.value} at index ${failure.index} was greater than element ${value[failure.index + 1]}"64 }65 return MatcherResult(66 failure == null,67 { "List ${value.show().value} should be sorted$elementMessage" },68 { "List ${value.show().value} should not be sorted" }69 )70 }71}72fun <T : Comparable<T>> beMonotonicallyIncreasing(): Matcher<List<T>> = monotonicallyIncreasing()73fun <T : Comparable<T>> monotonicallyIncreasing(): Matcher<List<T>> = object : Matcher<List<T>> {74 override fun test(value: List<T>): MatcherResult {75 return testMonotonicallyIncreasingWith(value,76 Comparator { a, b -> a.compareTo(b) })77 }78}79fun <T> beMonotonicallyIncreasingWith(comparator: Comparator<in T>): Matcher<List<T>> =80 monotonicallyIncreasingWith(comparator)81fun <T> monotonicallyIncreasingWith(comparator: Comparator<in T>): Matcher<List<T>> = object : Matcher<List<T>> {82 override fun test(value: List<T>): MatcherResult {83 return testMonotonicallyIncreasingWith(value, comparator)84 }85}86private fun<T> testMonotonicallyIncreasingWith(value: List<T>, comparator: Comparator<in T>): MatcherResult {87 val failure = value.zipWithNext().withIndex().find { (_, pair) -> comparator.compare(pair.first, pair.second) > 0 }88 val snippet = value.show().value89 val elementMessage = when (failure) {90 null -> ""91 else -> ". Element ${failure.value.second} at index ${failure.index + 1} was not monotonically increased from previous element."92 }93 return MatcherResult(94 failure == null,95 { "List [$snippet] should be monotonically increasing$elementMessage" },96 { "List [$snippet] should not be monotonically increasing" }97 )98}99fun <T : Comparable<T>> beMonotonicallyDecreasing(): Matcher<List<T>> = monotonicallyDecreasing()100fun <T : Comparable<T>> monotonicallyDecreasing(): Matcher<List<T>> = object : Matcher<List<T>> {101 override fun test(value: List<T>): MatcherResult {102 return testMonotonicallyDecreasingWith(value,103 Comparator { a, b -> a.compareTo(b) })104 }105}106fun <T> beMonotonicallyDecreasingWith(comparator: Comparator<in T>): Matcher<List<T>> = monotonicallyDecreasingWith(107 comparator)108fun <T> monotonicallyDecreasingWith(comparator: Comparator<in T>): Matcher<List<T>> = object : Matcher<List<T>> {109 override fun test(value: List<T>): MatcherResult {110 return testMonotonicallyDecreasingWith(value, comparator)111 }112}113private fun <T> testMonotonicallyDecreasingWith(value: List<T>, comparator: Comparator<in T>): MatcherResult {114 val failure = value.zipWithNext().withIndex().find { (_, pair) -> comparator.compare(pair.first, pair.second) < 0 }115 val snippet = value.show().value116 val elementMessage = when (failure) {117 null -> ""118 else -> ". Element ${failure.value.second} at index ${failure.index + 1} was not monotonically decreased from previous element."119 }120 return MatcherResult(121 failure == null,122 { "List [$snippet] should be monotonically decreasing$elementMessage" },123 { "List [$snippet] should not be monotonically decreasing" }124 )125}126fun <T : Comparable<T>> beStrictlyIncreasing(): Matcher<List<T>> = strictlyIncreasing()127fun <T : Comparable<T>> strictlyIncreasing(): Matcher<List<T>> = object : Matcher<List<T>> {128 override fun test(value: List<T>): MatcherResult {129 return testStrictlyIncreasingWith(value, Comparator { a, b -> a.compareTo(b) })130 }131}132fun <T> beStrictlyIncreasingWith(comparator: Comparator<in T>): Matcher<List<T>> = strictlyIncreasingWith(133 comparator)134fun <T> strictlyIncreasingWith(comparator: Comparator<in T>): Matcher<List<T>> = object : Matcher<List<T>> {135 override fun test(value: List<T>): MatcherResult {136 return testStrictlyIncreasingWith(value, comparator)137 }138}139private fun <T> testStrictlyIncreasingWith(value: List<T>, comparator: Comparator<in T>): MatcherResult {140 val failure = value.zipWithNext().withIndex().find { (_, pair) -> comparator.compare(pair.first, pair.second) >= 0 }141 val snippet = value.show().value142 val elementMessage = when (failure) {143 null -> ""144 else -> ". Element ${failure.value.second} at index ${failure.index + 1} was not strictly increased from previous element."145 }146 return MatcherResult(147 failure == null,148 { "List [$snippet] should be strictly increasing$elementMessage" },149 { "List [$snippet] should not be strictly increasing" }150 )151}152fun <T : Comparable<T>> beStrictlyDecreasing(): Matcher<List<T>> = strictlyDecreasing()153fun <T : Comparable<T>> strictlyDecreasing(): Matcher<List<T>> = object : Matcher<List<T>> {154 override fun test(value: List<T>): MatcherResult {155 return testStrictlyDecreasingWith(value, Comparator { a, b -> a.compareTo(b) })156 }157}158fun <T> beStrictlyDecreasingWith(comparator: Comparator<in T>): Matcher<List<T>> = strictlyDecreasingWith(159 comparator)160fun <T> strictlyDecreasingWith(comparator: Comparator<in T>): Matcher<List<T>> = object : Matcher<List<T>> {161 override fun test(value: List<T>): MatcherResult {162 return testStrictlyDecreasingWith(value, comparator)163 }164}165private fun <T> testStrictlyDecreasingWith(value: List<T>, comparator: Comparator<in T>): MatcherResult {166 val failure = value.zipWithNext().withIndex().find { (_, pair) -> comparator.compare(pair.first, pair.second) <= 0 }167 val snippet = value.show().value168 val elementMessage = when (failure) {169 null -> ""170 else -> ". Element ${failure.value.second} at index ${failure.index + 1} was not strictly decreased from previous element."171 }172 return MatcherResult(173 failure == null,174 { "List [$snippet] should be strictly decreasing$elementMessage" },175 { "List [$snippet] should not be strictly decreasing" }176 )177}...

Full Screen

Full Screen

increasing.kt

Source:increasing.kt Github

copy

Full Screen

1package io.kotest.matchers.collections2import io.kotest.assertions.print.print3import io.kotest.matchers.Matcher4import io.kotest.matchers.MatcherResult5import io.kotest.matchers.should6import io.kotest.matchers.shouldNot7fun <T : Comparable<T>> Iterable<T>.shouldBeStrictlyIncreasing(): Iterable<T> {8 toList().shouldBeStrictlyIncreasing()9 return this10}11fun <T : Comparable<T>> Array<T>.shouldBeStrictlyIncreasing(): Array<T> {12 asList().shouldBeStrictlyIncreasing()13 return this14}15fun <T : Comparable<T>> List<T>.shouldBeStrictlyIncreasing(): List<T> {16 this should beStrictlyIncreasing()17 return this18}19fun <T : Comparable<T>> Iterable<T>.shouldNotBeStrictlyIncreasing(): Iterable<T> {20 toList().shouldNotBeStrictlyIncreasing()21 return this22}23fun <T : Comparable<T>> Array<T>.shouldNotBeStrictlyIncreasing(): Array<T> {24 asList().shouldNotBeStrictlyIncreasing()25 return this26}27fun <T : Comparable<T>> List<T>.shouldNotBeStrictlyIncreasing(): List<T> {28 this shouldNot beStrictlyIncreasing()29 return this30}31fun <T : Comparable<T>> Iterable<T>.shouldBeMonotonicallyIncreasing(): Iterable<T> {32 toList().shouldBeMonotonicallyIncreasing()33 return this34}35fun <T : Comparable<T>> Array<T>.shouldBeMonotonicallyIncreasing(): Array<T> {36 asList().shouldBeMonotonicallyIncreasing()37 return this38}39fun <T : Comparable<T>> List<T>.shouldBeMonotonicallyIncreasing(): List<T> {40 this should beMonotonicallyIncreasing()41 return this42}43fun <T : Comparable<T>> Iterable<T>.shouldNotBeMonotonicallyIncreasing(): Iterable<T> {44 toList().shouldNotBeMonotonicallyIncreasing()45 return this46}47fun <T : Comparable<T>> Array<T>.shouldNotBeMonotonicallyIncreasing(): Array<T> {48 asList().shouldNotBeMonotonicallyIncreasing()49 return this50}51fun <T : Comparable<T>> List<T>.shouldNotBeMonotonicallyIncreasing(): List<T> {52 this shouldNot beMonotonicallyIncreasing()53 return this54}55fun <T> List<T>.shouldBeMonotonicallyIncreasingWith(comparator: Comparator<in T>): List<T> {56 this should beMonotonicallyIncreasingWith(comparator)57 return this58}59fun <T> Iterable<T>.shouldBeMonotonicallyIncreasingWith(comparator: Comparator<in T>): Iterable<T> {60 toList().shouldBeMonotonicallyIncreasingWith(comparator)61 return this62}63fun <T> Array<T>.shouldBeMonotonicallyIncreasingWith(comparator: Comparator<in T>): Array<T> {64 asList().shouldBeMonotonicallyIncreasingWith(comparator)65 return this66}67fun <T> List<T>.shouldNotBeMonotonicallyIncreasingWith(comparator: Comparator<in T>): List<T> {68 this shouldNot beMonotonicallyIncreasingWith(comparator)69 return this70}71fun <T> Iterable<T>.shouldNotBeMonotonicallyIncreasingWith(comparator: Comparator<in T>): Iterable<T> {72 toList().shouldNotBeMonotonicallyIncreasingWith(comparator)73 return this74}75fun <T> Array<T>.shouldNotBeMonotonicallyIncreasingWith(comparator: Comparator<in T>): Array<T> {76 asList().shouldNotBeMonotonicallyIncreasingWith(comparator)77 return this78}79fun <T> List<T>.shouldBeStrictlyIncreasingWith(comparator: Comparator<in T>) =80 this should beStrictlyIncreasingWith(comparator)81fun <T> Iterable<T>.shouldBeStrictlyIncreasingWith(comparator: Comparator<in T>) =82 toList().shouldBeStrictlyIncreasingWith(comparator)83fun <T> Array<T>.shouldBeStrictlyIncreasingWith(comparator: Comparator<in T>) =84 asList().shouldBeStrictlyIncreasingWith(comparator)85fun <T> List<T>.shouldNotBeStrictlyIncreasingWith(comparator: Comparator<in T>) =86 this shouldNot beStrictlyIncreasingWith(comparator)87fun <T> Iterable<T>.shouldNotBeStrictlyIncreasingWith(comparator: Comparator<in T>) =88 toList().shouldNotBeStrictlyIncreasingWith(comparator)89fun <T> Array<T>.shouldNotBeStrictlyIncreasingWith(comparator: Comparator<in T>) =90 asList().shouldNotBeStrictlyIncreasingWith(comparator)91fun <T : Comparable<T>> beStrictlyIncreasing(): Matcher<List<T>> = strictlyIncreasing()92fun <T : Comparable<T>> strictlyIncreasing(): Matcher<List<T>> = object : Matcher<List<T>> {93 override fun test(value: List<T>): MatcherResult {94 return testStrictlyIncreasingWith(value) { a, b -> a.compareTo(b) }95 }96}97fun <T> beStrictlyIncreasingWith(comparator: Comparator<in T>): Matcher<List<T>> = strictlyIncreasingWith(comparator)98fun <T> strictlyIncreasingWith(comparator: Comparator<in T>): Matcher<List<T>> = object : Matcher<List<T>> {99 override fun test(value: List<T>): MatcherResult {100 return testStrictlyIncreasingWith(value, comparator)101 }102}103private fun <T> testStrictlyIncreasingWith(value: List<T>, comparator: Comparator<in T>): MatcherResult {104 val failure = value.zipWithNext().withIndex().find { (_, pair) -> comparator.compare(pair.first, pair.second) >= 0 }105 val snippet = value.print().value106 val elementMessage = when (failure) {107 null -> ""108 else -> ". Element ${failure.value.second} at index ${failure.index + 1} was not strictly increased from previous element."109 }110 return MatcherResult(111 failure == null,112 { "List [$snippet] should be strictly increasing$elementMessage" },113 { "List [$snippet] should not be strictly increasing" }114 )115}116fun <T : Comparable<T>> beMonotonicallyIncreasing(): Matcher<List<T>> = monotonicallyIncreasing()117fun <T : Comparable<T>> monotonicallyIncreasing(): Matcher<List<T>> = object : Matcher<List<T>> {118 override fun test(value: List<T>): MatcherResult {119 return testMonotonicallyIncreasingWith(value) { a, b -> a.compareTo(b) }120 }121}122fun <T> beMonotonicallyIncreasingWith(comparator: Comparator<in T>): Matcher<List<T>> =123 monotonicallyIncreasingWith(comparator)124fun <T> monotonicallyIncreasingWith(comparator: Comparator<in T>): Matcher<List<T>> = object : Matcher<List<T>> {125 override fun test(value: List<T>): MatcherResult {126 return testMonotonicallyIncreasingWith(value, comparator)127 }128}129private fun <T> testMonotonicallyIncreasingWith(value: List<T>, comparator: Comparator<in T>): MatcherResult {130 val failure = value.zipWithNext().withIndex().find { (_, pair) -> comparator.compare(pair.first, pair.second) > 0 }131 val snippet = value.print().value132 val elementMessage = when (failure) {133 null -> ""134 else -> ". Element ${failure.value.second} at index ${failure.index + 1} was not monotonically increased from previous element."135 }136 return MatcherResult(137 failure == null,138 { "List [$snippet] should be monotonically increasing$elementMessage" },139 { "List [$snippet] should not be monotonically increasing" }140 )141}...

Full Screen

Full Screen

TimeSeriesDBTest.kt

Source:TimeSeriesDBTest.kt Github

copy

Full Screen

1package org.raspikiln.tsdb2import io.kotest.core.spec.style.FunSpec3import io.kotest.matchers.collections.shouldBeMonotonicallyIncreasingWith4import io.kotest.matchers.doubles.shouldBeGreaterThan5import io.kotest.matchers.doubles.shouldBeGreaterThanOrEqual6import io.kotest.matchers.doubles.shouldBeLessThan7import io.kotest.matchers.ints.shouldBeExactly8import io.kotest.matchers.ints.shouldBeLessThan9import io.kotest.matchers.shouldBe10import kotlinx.coroutines.delay11import java.io.File12import java.time.Instant13import java.util.Comparator14import kotlin.random.Random15import kotlin.time.Duration16import kotlin.time.Duration.Companion.hours17import kotlin.time.Duration.Companion.seconds18class TimeSeriesDBTest : FunSpec({19 test("able to write and do things") {20 val db = timeSeriesDb(retention = 10.hours)21 val temperatureA = MetricGenerator(MetricIdentifier(name = "temperatureA"), 0..20)22 val temperatureB = MetricGenerator(MetricIdentifier(name = "temperatureB"), 40..60)23 var metricCount = 024 repeat(2_000) { _ ->25 val metricsAdded = (1..10).random()26 metricCount += metricsAdded27 repeat(metricsAdded) {28 db.write(listOf(temperatureA.next(), temperatureB.next()))29 }30 listOf(temperatureA, temperatureB).forEach { metric ->31 val query = db.query(metric.identifier, Instant.now().minusSeconds(3_000)..Instant.now()).toList()32 query.forEach { metric shouldContain it.value }33 query.shouldBeMonotonicallyIncreasingWith(Comparator.comparing { it.timestamp })34 query.count() shouldBe metricCount35 }36 delay(5)37 }38 }39 test("clear partitions after retention") {40 val db = timeSeriesDb(retention = 10.seconds)41 val metricMeasurement = MetricGenerator(MetricIdentifier(name = "temperatureA"), 0..20)42 repeat(500) {43 db.write(metricMeasurement.next())44 }45 delay(12_000)46 db.write(metricMeasurement.next())47 db.query(48 metricName = metricMeasurement.identifier,49 timestampRange = Instant.now().minusSeconds(20)..Instant.now()50 ).count() shouldBeExactly 151 }52})53data class MetricGenerator(54 val identifier: MetricIdentifier,55 val range: IntRange56) {57 infix fun shouldContain(value: Double) {58 range.first.toDouble() shouldBeLessThan value59 range.last.toDouble() shouldBeGreaterThanOrEqual value60 }61 fun next(): Measurement =62 Measurement(63 metric = identifier,64 datapoint = Datapoint(65 timestamp = Instant.now(),66 value = nextValue()67 )68 )69 private fun nextValue() = Random.Default.nextDouble(range.first.toDouble(), range.last.toDouble())70}71private fun timeSeriesDb(retention: Duration = 10.hours) =72 StandardTimeSeriesDB(options = StandardTimeSeriesDB.Options(73 directory = File("data-test"),74 partitionDuration = 10.seconds,75 partitionCapacity = 1_000,76 retention = retention,77 deleteDelayTime = 0.seconds78 )).apply { purgeAll() }...

Full Screen

Full Screen

DailyBalancesPropJqwikTest.kt

Source:DailyBalancesPropJqwikTest.kt Github

copy

Full Screen

1import io.kotest.matchers.collections.shouldBeStrictlyIncreasingWith2import io.kotest.matchers.collections.shouldContainAll3import io.kotest.matchers.shouldBe4import net.jqwik.api.*5import net.jqwik.api.constraints.NotEmpty6import net.jqwik.api.statistics.Statistics7import net.jqwik.kotlin.api.anyForType8import net.jqwik.kotlin.api.combine9import net.jqwik.time.api.Dates10import java.time.LocalDate11class DailyBalancesPropJqwikTest {12 @Property13 fun testArbitrary(@ForAll("uniqueBalances") list: List<Balance>) {14 Statistics.label("sizes").collect(list.size)15 }16 @Property17 fun `contains all original elements`(@ForAll("uniqueBalances") list: List<Balance>) {18 val result = list.expandToDaily()19 result.shouldContainAll(list)20 }21 @Property22 fun `result is strictly increasing by the balance date`(@ForAll("uniqueBalances") list: List<Balance>) {23 val result = list.expandToDaily()24 result.shouldBeStrictlyIncreasingWith(compareBy { it.date })25 }26 @Property27 fun `returns the whole range`(@ForAll("uniqueBalances") @NotEmpty list: List<Balance>) {...

Full Screen

Full Screen

DailyBalancesPropKotestTest.kt

Source:DailyBalancesPropKotestTest.kt Github

copy

Full Screen

1import io.kotest.core.spec.style.DescribeSpec2import io.kotest.matchers.booleans.shouldBeFalse3import io.kotest.matchers.collections.shouldBeStrictlyIncreasingWith4import io.kotest.matchers.collections.shouldContainAll5import io.kotest.matchers.shouldBe6import io.kotest.property.Arb7import io.kotest.property.PropTestConfig8import io.kotest.property.arbitrary.*9import io.kotest.property.checkAll10import java.time.LocalDate11class DailyBalancesPropKotestTest : DescribeSpec({12 describe("properties") {13 val arbBalance = Arb.bind(Arb.localDate(), Arb.bigDecimal()) { d, a -> Balance(d, a) }14 fun arbUniqueList(minLength: Int = 0) = Arb.list(arbBalance, minLength..100).map { it.distinctBy { it.date } }15 it("contains all original elements") {16 checkAll(PropTestConfig(outputClassifications = true), arbUniqueList()) { list ->17 val result = list.expandToDaily()18 result.shouldContainAll(list)19 }20 }21 it("result is strictly increasing by the balance date") {22 checkAll(arbUniqueList()) { list ->23 val result = list.expandToDaily()24 result.shouldBeStrictlyIncreasingWith(compareBy { it.date })25 }...

Full Screen

Full Screen

LineTest.kt

Source:LineTest.kt Github

copy

Full Screen

1package day052import io.kotest.matchers.collections.shouldContainExactlyInAnyOrder3import org.junit.jupiter.api.Test4internal class LineTest {5 @Test6 fun create__success__horizontalIncreasingNumbersOnly() {7 val definition = LineDefinition(Position(3, 5), Position(5, 5))8 val line = Line(definition)9 line.positions shouldContainExactlyInAnyOrder listOf(Position(3, 5), Position(4, 5), Position(5, 5))10 }11 @Test12 fun create__success__verticalDecreasingX() {13 val definition = LineDefinition(Position(3, 5), Position(3, 3))14 val line = Line(definition)15 line.positions shouldContainExactlyInAnyOrder listOf(Position(3, 3), Position(3, 4), Position(3, 5))16 }...

Full Screen

Full Screen

test

Using AI Code Generation

copy

Full Screen

1class MyTest : FunSpec({2 test("increasing") {3 increasing(1, 2, 3, 4, 5)4 }5})6class MyTest : FunSpec({7 test("increasing") {8 increasing(1, 2, 3, 4, 5)9 }10})11class MyTest : FunSpec({12 test("increasing") {13 increasing(1, 2, 3, 4, 5)14 }15})16class MyTest : FunSpec({17 test("increasing") {18 increasing(1, 2, 3, 4, 5)19 }20})21class MyTest : FunSpec({22 test("increasing") {23 increasing(1, 2, 3

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