Best Kotest code snippet using io.kotest.matchers.collections.unique.Array.shouldBeUnique
matchers.kt
Source:matchers.kt  
1package io.kotest.matchers.collections2import io.kotest.assertions.show.show3import io.kotest.matchers.Matcher4import io.kotest.matchers.MatcherResult5import io.kotest.matchers.neverNullMatcher6import io.kotest.matchers.should7import io.kotest.matchers.shouldHave8import io.kotest.matchers.shouldNot9import kotlin.jvm.JvmName10fun <T> Iterable<T>.shouldContainOnlyNulls() = toList().shouldContainOnlyNulls()11fun <T> Array<T>.shouldContainOnlyNulls() = asList().shouldContainOnlyNulls()12fun <T> Collection<T>.shouldContainOnlyNulls() = this should containOnlyNulls()13fun <T> Iterable<T>.shouldNotContainOnlyNulls() = toList().shouldNotContainOnlyNulls()14fun <T> Array<T>.shouldNotContainOnlyNulls() = asList().shouldNotContainOnlyNulls()15fun <T> Collection<T>.shouldNotContainOnlyNulls() = this shouldNot containOnlyNulls()16fun <T> containOnlyNulls() = object : Matcher<Collection<T>> {17   override fun test(value: Collection<T>) =18      MatcherResult(19         value.all { it == null },20         "Collection should contain only nulls",21         "Collection should not contain only nulls"22      )23}24fun <T> Iterable<T>.shouldContainNull() = toList().shouldContainNull()25fun <T> Array<T>.shouldContainNull() = asList().shouldContainNull()26fun <T> Collection<T>.shouldContainNull() = this should containNull()27fun <T> Iterable<T>.shouldNotContainNull() = toList().shouldNotContainNull()28fun <T> Array<T>.shouldNotContainNull() = asList().shouldNotContainNull()29fun <T> Collection<T>.shouldNotContainNull() = this shouldNot containNull()30fun <T> containNull() = object : Matcher<Collection<T>> {31   override fun test(value: Collection<T>) =32      MatcherResult(33         value.any { it == null },34         "Collection should contain at least one null",35         "Collection should not contain any nulls"36      )37}38fun <T> Iterable<T>.shouldHaveElementAt(index: Int, element: T) = toList().shouldHaveElementAt(index, element)39fun <T> Array<T>.shouldHaveElementAt(index: Int, element: T) = asList().shouldHaveElementAt(index, element)40fun <T> List<T>.shouldHaveElementAt(index: Int, element: T) = this should haveElementAt(index, element)41fun <T> Iterable<T>.shouldNotHaveElementAt(index: Int, element: T) = toList().shouldNotHaveElementAt(index, element)42fun <T> Array<T>.shouldNotHaveElementAt(index: Int, element: T) = asList().shouldNotHaveElementAt(index, element)43fun <T> List<T>.shouldNotHaveElementAt(index: Int, element: T) = this shouldNot haveElementAt(index, element)44fun <T, L : List<T>> haveElementAt(index: Int, element: T) = object : Matcher<L> {45   override fun test(value: L) =46      MatcherResult(47         value[index] == element,48         { "Collection should contain ${element.show().value} at index $index" },49         { "Collection should not contain ${element.show().value} at index $index" }50      )51}52fun <T> Iterable<T>.shouldContainNoNulls() = toList().shouldContainNoNulls()53fun <T> Array<T>.shouldContainNoNulls() = asList().shouldContainNoNulls()54fun <T> Collection<T>.shouldContainNoNulls() = this should containNoNulls()55fun <T> Iterable<T>.shouldNotContainNoNulls() = toList().shouldNotContainNoNulls()56fun <T> Array<T>.shouldNotContainNoNulls() = asList().shouldNotContainNoNulls()57fun <T> Collection<T>.shouldNotContainNoNulls() = this shouldNot containNoNulls()58fun <T> containNoNulls() = object : Matcher<Collection<T>> {59   override fun test(value: Collection<T>) =60      MatcherResult(61         value.all { it != null },62         { "Collection should not contain nulls" },63         { "Collection should have at least one null" }64      )65}66infix fun <T> Array<T>.shouldNotContainExactlyInAnyOrder(expected: Array<T>) =67   asList().shouldNotContainExactlyInAnyOrder(expected.asList())68infix fun <T, C : Collection<T>> C?.shouldNotContainExactlyInAnyOrder(expected: C) =69   this shouldNot containExactlyInAnyOrder(expected)70fun <T, C : Collection<T>> C?.shouldNotContainExactlyInAnyOrder(vararg expected: T) =71   this shouldNot containExactlyInAnyOrder(*expected)72infix fun <T> Array<T>.shouldContainExactlyInAnyOrder(expected: Array<T>) =73   asList().shouldContainExactlyInAnyOrder(expected.asList())74infix fun <T, C : Collection<T>> C?.shouldContainExactlyInAnyOrder(expected: C) =75   this should containExactlyInAnyOrder(expected)76fun <T, C : Collection<T>> C?.shouldContainExactlyInAnyOrder(vararg expected: T) =77   this should containExactlyInAnyOrder(*expected)78fun <T> containExactlyInAnyOrder(vararg expected: T): Matcher<Collection<T>?> =79   containExactlyInAnyOrder(expected.asList())80/** Assert that a collection contains exactly the given values and nothing else, in any order. */81fun <T, C : Collection<T>> containExactlyInAnyOrder(expected: C): Matcher<C?> = neverNullMatcher { value ->82   val valueGroupedCounts: Map<T, Int> = value.groupBy { it }.mapValues { it.value.size }83   val expectedGroupedCounts: Map<T, Int> = expected.groupBy { it }.mapValues { it.value.size }84   val passed = expectedGroupedCounts.size == valueGroupedCounts.size85      && expectedGroupedCounts.all { valueGroupedCounts[it.key] == it.value }86   MatcherResult(87      passed,88      "Collection should contain ${expected.show().value} in any order, but was ${value.show().value}",89      "Collection should not contain exactly ${expected.show().value} in any order"90   )91}92infix fun <T : Comparable<T>> Iterable<T>.shouldHaveUpperBound(t: T) = toList().shouldHaveUpperBound(t)93infix fun <T : Comparable<T>> Array<T>.shouldHaveUpperBound(t: T) = asList().shouldHaveUpperBound(t)94infix fun <T : Comparable<T>, C : Collection<T>> C.shouldHaveUpperBound(t: T) = this should haveUpperBound(t)95fun <T : Comparable<T>, C : Collection<T>> haveUpperBound(t: T) = object : Matcher<C> {96   override fun test(value: C) = MatcherResult(97      value.all { it <= t },98      "Collection should have upper bound $t",99      "Collection should not have upper bound $t"100   )101}102infix fun <T : Comparable<T>> Iterable<T>.shouldHaveLowerBound(t: T) = toList().shouldHaveLowerBound(t)103infix fun <T : Comparable<T>> Array<T>.shouldHaveLowerBound(t: T) = asList().shouldHaveLowerBound(t)104infix fun <T : Comparable<T>, C : Collection<T>> C.shouldHaveLowerBound(t: T) = this should haveLowerBound(t)105fun <T : Comparable<T>, C : Collection<T>> haveLowerBound(t: T) = object : Matcher<C> {106   override fun test(value: C) = MatcherResult(107      value.all { t <= it },108      "Collection should have lower bound $t",109      "Collection should not have lower bound $t"110   )111}112fun <T> Iterable<T>.shouldBeUnique() = toList().shouldBeUnique()113fun <T> Array<T>.shouldBeUnique() = asList().shouldBeUnique()114fun <T> Collection<T>.shouldBeUnique() = this should beUnique()115fun <T> Iterable<T>.shouldNotBeUnique() = toList().shouldNotBeUnique()116fun <T> Array<T>.shouldNotBeUnique() = asList().shouldNotBeUnique()117fun <T> Collection<T>.shouldNotBeUnique() = this shouldNot beUnique()118fun <T> beUnique() = object : Matcher<Collection<T>> {119   override fun test(value: Collection<T>) = MatcherResult(120      value.toSet().size == value.size,121      "Collection should be Unique",122      "Collection should contain at least one duplicate element"123   )124}125fun <T> Iterable<T>.shouldContainDuplicates() = toList().shouldContainDuplicates()126fun <T> Array<T>.shouldContainDuplicates() = asList().shouldContainDuplicates()127fun <T> Collection<T>.shouldContainDuplicates() = this should containDuplicates()128fun <T> Iterable<T>.shouldNotContainDuplicates() = toList().shouldNotContainDuplicates()129fun <T> Array<T>.shouldNotContainDuplicates() = asList().shouldNotContainDuplicates()130fun <T> Collection<T>.shouldNotContainDuplicates() = this shouldNot containDuplicates()131fun <T> containDuplicates() = object : Matcher<Collection<T>> {132   override fun test(value: Collection<T>) = MatcherResult(133      value.toSet().size < value.size,134      "Collection should contain duplicates",135      "Collection should not contain duplicates"136   )137}138fun <T> beSortedWith(comparator: Comparator<in T>): Matcher<List<T>> = sortedWith(comparator)139fun <T> beSortedWith(cmp: (T, T) -> Int): Matcher<List<T>> = sortedWith(cmp)140fun <T> sortedWith(comparator: Comparator<in T>): Matcher<List<T>> = sortedWith { a, b ->141   comparator.compare(a, b)142}143fun <T> sortedWith(cmp: (T, T) -> Int): Matcher<List<T>> = object : Matcher<List<T>> {144   override fun test(value: List<T>): MatcherResult {145      val failure = value.withIndex().firstOrNull { (i, it) -> i != value.lastIndex && cmp(it, value[i + 1]) > 0 }146      val snippet = value.joinToString(",", limit = 10)147      val elementMessage = when (failure) {148         null -> ""149         else -> ". Element ${failure.value} at index ${failure.index} shouldn't precede element ${value[failure.index + 1]}"150      }151      return MatcherResult(152         failure == null,153         "List [$snippet] should be sorted$elementMessage",154         "List [$snippet] should not be sorted"155      )156   }157}158fun <T : Comparable<T>> Iterable<T>.shouldBeSorted() = toList().shouldBeSorted()159fun <T : Comparable<T>> Array<T>.shouldBeSorted() = asList().shouldBeSorted()160fun <T : Comparable<T>> List<T>.shouldBeSorted() = this should beSorted<T>()161fun <T : Comparable<T>> Iterable<T>.shouldNotBeSorted() = toList().shouldNotBeSorted()162fun <T : Comparable<T>> Array<T>.shouldNotBeSorted() = asList().shouldNotBeSorted()163fun <T : Comparable<T>> List<T>.shouldNotBeSorted() = this shouldNot beSorted<T>()164infix fun <T> Iterable<T>.shouldBeSortedWith(comparator: Comparator<in T>) = toList().shouldBeSortedWith(comparator)165infix fun <T> Array<T>.shouldBeSortedWith(comparator: Comparator<in T>) = asList().shouldBeSortedWith(comparator)166infix fun <T> List<T>.shouldBeSortedWith(comparator: Comparator<in T>) = this should beSortedWith(comparator)167infix fun <T> Iterable<T>.shouldNotBeSortedWith(comparator: Comparator<in T>) = toList().shouldNotBeSortedWith(comparator)168infix fun <T> Array<T>.shouldNotBeSortedWith(comparator: Comparator<in T>) = asList().shouldNotBeSortedWith(comparator)169infix fun <T> List<T>.shouldNotBeSortedWith(comparator: Comparator<in T>) = this shouldNot beSortedWith(comparator)170infix fun <T> Iterable<T>.shouldBeSortedWith(cmp: (T, T) -> Int) = toList().shouldBeSortedWith(cmp)171infix fun <T> Array<T>.shouldBeSortedWith(cmp: (T, T) -> Int) = asList().shouldBeSortedWith(cmp)172infix fun <T> List<T>.shouldBeSortedWith(cmp: (T, T) -> Int) = this should beSortedWith(cmp)173infix fun <T> Iterable<T>.shouldNotBeSortedWith(cmp: (T, T) -> Int) = toList().shouldNotBeSortedWith(cmp)174infix fun <T> Array<T>.shouldNotBeSortedWith(cmp: (T, T) -> Int) = asList().shouldNotBeSortedWith(cmp)175infix fun <T> List<T>.shouldNotBeSortedWith(cmp: (T, T) -> Int) = this shouldNot beSortedWith(cmp)176fun <T : Comparable<T>> Iterable<T>.shouldBeMonotonicallyIncreasing() = toList().shouldBeMonotonicallyIncreasing()177fun <T : Comparable<T>> Array<T>.shouldBeMonotonicallyIncreasing() = asList().shouldBeMonotonicallyIncreasing()178fun <T : Comparable<T>> List<T>.shouldBeMonotonicallyIncreasing() = this should beMonotonicallyIncreasing<T>()179fun <T : Comparable<T>> Iterable<T>.shouldNotBeMonotonicallyIncreasing() = toList().shouldNotBeMonotonicallyIncreasing()180fun <T : Comparable<T>> Array<T>.shouldNotBeMonotonicallyIncreasing() = asList().shouldNotBeMonotonicallyIncreasing()181fun <T : Comparable<T>> List<T>.shouldNotBeMonotonicallyIncreasing() = this shouldNot beMonotonicallyIncreasing<T>()182fun <T> List<T>.shouldBeMonotonicallyIncreasingWith(comparator: Comparator<in T>) =183   this should beMonotonicallyIncreasingWith(comparator)184fun <T> Iterable<T>.shouldBeMonotonicallyIncreasingWith(comparator: Comparator<in T>) =185   toList().shouldBeMonotonicallyIncreasingWith(comparator)186fun <T> Array<T>.shouldBeMonotonicallyIncreasingWith(comparator: Comparator<in T>) =187   asList().shouldBeMonotonicallyIncreasingWith(comparator)188fun <T> List<T>.shouldNotBeMonotonicallyIncreasingWith(comparator: Comparator<in T>) =189   this shouldNot beMonotonicallyIncreasingWith(comparator)190fun <T> Iterable<T>.shouldNotBeMonotonicallyIncreasingWith(comparator: Comparator<in T>) =191   toList().shouldNotBeMonotonicallyIncreasingWith(comparator)192fun <T> Array<T>.shouldNotBeMonotonicallyIncreasingWith(comparator: Comparator<in T>) =193   asList().shouldNotBeMonotonicallyIncreasingWith(comparator)194fun <T : Comparable<T>> Iterable<T>.shouldBeMonotonicallyDecreasing() = toList().shouldBeMonotonicallyDecreasing()195fun <T : Comparable<T>> Array<T>.shouldBeMonotonicallyDecreasing() = asList().shouldBeMonotonicallyDecreasing()196fun <T : Comparable<T>> List<T>.shouldBeMonotonicallyDecreasing() = this should beMonotonicallyDecreasing<T>()197fun <T : Comparable<T>> Iterable<T>.shouldNotBeMonotonicallyDecreasing() = toList().shouldNotBeMonotonicallyDecreasing()198fun <T : Comparable<T>> Array<T>.shouldNotBeMonotonicallyDecreasing() = asList().shouldNotBeMonotonicallyDecreasing()199fun <T : Comparable<T>> List<T>.shouldNotBeMonotonicallyDecreasing() = this shouldNot beMonotonicallyDecreasing<T>()200fun <T> List<T>.shouldBeMonotonicallyDecreasingWith(comparator: Comparator<in T>) =201   this should beMonotonicallyDecreasingWith(comparator)202fun <T> Iterable<T>.shouldBeMonotonicallyDecreasingWith(comparator: Comparator<in T>) =203   toList().shouldBeMonotonicallyDecreasingWith(comparator)204fun <T> Array<T>.shouldBeMonotonicallyDecreasingWith(comparator: Comparator<in T>) =205   asList().shouldBeMonotonicallyDecreasingWith(comparator)206fun <T> List<T>.shouldNotBeMonotonicallyDecreasingWith(comparator: Comparator<in T>) =207   this shouldNot beMonotonicallyDecreasingWith(comparator)208fun <T> Iterable<T>.shouldNotBeMonotonicallyDecreasingWith(comparator: Comparator<in T>) =209   toList().shouldNotBeMonotonicallyDecreasingWith(comparator)210fun <T> Array<T>.shouldNotBeMonotonicallyDecreasingWith(comparator: Comparator<in T>) =211   asList().shouldNotBeMonotonicallyDecreasingWith(comparator)212fun <T : Comparable<T>> Iterable<T>.shouldBeStrictlyIncreasing() = toList().shouldBeStrictlyIncreasing()213fun <T : Comparable<T>> Array<T>.shouldBeStrictlyIncreasing() = asList().shouldBeStrictlyIncreasing()214fun <T : Comparable<T>> List<T>.shouldBeStrictlyIncreasing() = this should beStrictlyIncreasing<T>()215fun <T : Comparable<T>> Iterable<T>.shouldNotBeStrictlyIncreasing() = toList().shouldNotBeStrictlyIncreasing()216fun <T : Comparable<T>> Array<T>.shouldNotBeStrictlyIncreasing() = asList().shouldNotBeStrictlyIncreasing()217fun <T : Comparable<T>> List<T>.shouldNotBeStrictlyIncreasing() = this shouldNot beStrictlyIncreasing<T>()218fun <T> List<T>.shouldBeStrictlyIncreasingWith(comparator: Comparator<in T>) =219   this should beStrictlyIncreasingWith(comparator)220fun <T> Iterable<T>.shouldBeStrictlyIncreasingWith(comparator: Comparator<in T>) =221   toList().shouldBeStrictlyIncreasingWith(comparator)222fun <T> Array<T>.shouldBeStrictlyIncreasingWith(comparator: Comparator<in T>) =223   asList().shouldBeStrictlyIncreasingWith(comparator)224fun <T> List<T>.shouldNotBeStrictlyIncreasingWith(comparator: Comparator<in T>) =225   this shouldNot beStrictlyIncreasingWith(comparator)226fun <T> Iterable<T>.shouldNotBeStrictlyIncreasingWith(comparator: Comparator<in T>) =227   toList().shouldNotBeStrictlyIncreasingWith(comparator)228fun <T> Array<T>.shouldNotBeStrictlyIncreasingWith(comparator: Comparator<in T>) =229   asList().shouldNotBeStrictlyIncreasingWith(comparator)230fun <T : Comparable<T>> Iterable<T>.shouldBeStrictlyDecreasing() = toList().shouldBeStrictlyDecreasing()231fun <T : Comparable<T>> List<T>.shouldBeStrictlyDecreasing() = this should beStrictlyDecreasing<T>()232fun <T : Comparable<T>> Iterable<T>.shouldNotBeStrictlyDecreasing() = toList().shouldNotBeStrictlyDecreasing()233fun <T : Comparable<T>> List<T>.shouldNotBeStrictlyDecreasing() = this shouldNot beStrictlyDecreasing<T>()234fun <T> List<T>.shouldBeStrictlyDecreasingWith(comparator: Comparator<in T>) =235   this should beStrictlyDecreasingWith(comparator)236fun <T> Iterable<T>.shouldBeStrictlyDecreasingWith(comparator: Comparator<in T>) =237   toList().shouldBeStrictlyDecreasingWith(comparator)238fun <T> Array<T>.shouldBeStrictlyDecreasingWith(comparator: Comparator<in T>) =239   asList().shouldBeStrictlyDecreasingWith(comparator)240fun <T> List<T>.shouldNotBeStrictlyDecreasingWith(comparator: Comparator<in T>) =241   this shouldNot beStrictlyDecreasingWith(comparator)242fun <T> Iterable<T>.shouldNotBeStrictlyDecreasingWith(comparator: Comparator<in T>) =243   toList().shouldNotBeStrictlyDecreasingWith(comparator)244fun <T> Array<T>.shouldNotBeStrictlyDecreasingWith(comparator: Comparator<in T>) =245   asList().shouldNotBeStrictlyDecreasingWith(comparator)246infix fun <T> Iterable<T>.shouldHaveSingleElement(t: T) = toList().shouldHaveSingleElement(t)247infix fun <T> Array<T>.shouldHaveSingleElement(t: T) = asList().shouldHaveSingleElement(t)248infix fun <T> Iterable<T>.shouldHaveSingleElement(p: (T) -> Boolean) = toList().shouldHaveSingleElement(p)249infix fun <T> Array<T>.shouldHaveSingleElement(p: (T) -> Boolean) = asList().shouldHaveSingleElement(p)250infix fun <T> Collection<T>.shouldHaveSingleElement(t: T) = this should singleElement(t)251infix fun <T> Collection<T>.shouldHaveSingleElement(p: (T) -> Boolean) = this should singleElement(p)252infix fun <T> Iterable<T>.shouldNotHaveSingleElement(t: T) = toList().shouldNotHaveSingleElement(t)253infix fun <T> Array<T>.shouldNotHaveSingleElement(t: T) = asList().shouldNotHaveSingleElement(t)254infix fun <T> Collection<T>.shouldNotHaveSingleElement(t: T) = this shouldNot singleElement(t)255infix fun <T> Iterable<T>.shouldHaveSize(size: Int) = toList().shouldHaveSize(size)256infix fun <T> Array<T>.shouldHaveSize(size: Int) = asList().shouldHaveSize(size)257infix fun <T> Collection<T>.shouldHaveSize(size: Int) = this should haveSize(size = size)258infix fun <T> Iterable<T>.shouldNotHaveSize(size: Int) = toList().shouldNotHaveSize(size)259infix fun <T> Array<T>.shouldNotHaveSize(size: Int) = asList().shouldNotHaveSize(size)260infix fun <T> Collection<T>.shouldNotHaveSize(size: Int) = this shouldNot haveSize(size)261/**262 * Verifies this collection contains only one element263 *264 * This assertion is an alias to `collection shouldHaveSize 1`. This will pass if the collection have exactly one element265 * (definition of a Singleton Collection)266 *267 * ```268 * listOf(1).shouldBeSingleton()    // Assertion passes269 * listOf(1, 2).shouldBeSingleton() // Assertion fails270 * ```271 *272 * @see [shouldHaveSize]273 * @see [shouldNotBeSingleton]274 * @see [shouldHaveSingleElement]275 */276fun <T> Collection<T>.shouldBeSingleton() = this shouldHaveSize 1277fun <T> Iterable<T>.shouldBeSingleton() = toList().shouldBeSingleton()278fun <T> Array<T>.shouldBeSingleton() = asList().shouldBeSingleton()279inline fun <T> Collection<T>.shouldBeSingleton(fn: (T) -> Unit) {280   this.shouldBeSingleton()281   fn(this.first())282}283inline fun <T> Iterable<T>.shouldBeSingleton(fn: (T) -> Unit) {284   toList().shouldBeSingleton(fn)285}286inline fun <T> Array<T>.shouldBeSingleton(fn: (T) -> Unit) {287   asList().shouldBeSingleton(fn)288}289/**290 * Verifies this collection doesn't contain only one element291 *292 * This assertion is an alias to `collection shouldNotHaveSize 1`. This will pass if the collection doesn't have exactly one element293 * (definition of a Singleton Collection)294 *295 * ```296 * listOf(1, 2).shouldNotBeSingleton()    // Assertion passes297 * listOf<Int>().shouldNotBeSingleton()   // Assertion passes298 * listOf(1).shouldNotBeSingleton()       // Assertion fails299 * ```300 *301 * @see [shouldNotHaveSize]302 * @see [shouldBeSingleton]303 * @see [shouldNotHaveSingleElement]304 */305fun <T> Collection<T>.shouldNotBeSingleton() = this shouldNotHaveSize 1306fun <T> Iterable<T>.shouldNotBeSingleton() = toList().shouldNotBeSingleton()307fun <T> Array<T>.shouldNotBeSingleton() = asList().shouldNotBeSingleton()308infix fun <T, U> Iterable<T>.shouldBeLargerThan(other: Collection<U>) = toList().shouldBeLargerThan(other)309infix fun <T, U> Array<T>.shouldBeLargerThan(other: Collection<U>) = asList().shouldBeLargerThan(other)310infix fun <T, U> Iterable<T>.shouldBeLargerThan(other: Iterable<U>) = toList().shouldBeLargerThan(other.toList())311infix fun <T, U> Array<T>.shouldBeLargerThan(other: Array<U>) = asList().shouldBeLargerThan(other.asList())312infix fun <T, U> Collection<T>.shouldBeLargerThan(other: Collection<U>) = this should beLargerThan(other)313fun <T, U> beLargerThan(other: Collection<U>) = object : Matcher<Collection<T>> {314   override fun test(value: Collection<T>) = MatcherResult(315      value.size > other.size,316      "Collection of size ${value.size} should be larger than collection of size ${other.size}",317      "Collection of size ${value.size} should not be larger than collection of size ${other.size}"318   )319}320infix fun <T, U> Iterable<T>.shouldBeSmallerThan(other: Collection<U>) = toList().shouldBeSmallerThan(other)321infix fun <T, U> Array<T>.shouldBeSmallerThan(other: Collection<U>) = asList().shouldBeSmallerThan(other)322infix fun <T, U> Iterable<T>.shouldBeSmallerThan(other: Iterable<U>) = toList().shouldBeSmallerThan(other.toList())323infix fun <T, U> Array<T>.shouldBeSmallerThan(other: Array<U>) = asList().shouldBeSmallerThan(other.asList())324infix fun <T, U> Collection<T>.shouldBeSmallerThan(other: Collection<U>) = this should beSmallerThan(other)325fun <T, U> beSmallerThan(other: Collection<U>) = object : Matcher<Collection<T>> {326   override fun test(value: Collection<T>) = MatcherResult(327      value.size < other.size,328      "Collection of size ${value.size} should be smaller than collection of size ${other.size}",329      "Collection of size ${value.size} should not be smaller than collection of size ${other.size}"330   )331}332infix fun <T, U> Iterable<T>.shouldBeSameSizeAs(other: Collection<U>) = toList().shouldBeSameSizeAs(other)333infix fun <T, U> Array<T>.shouldBeSameSizeAs(other: Collection<U>) = asList().shouldBeSameSizeAs(other)334infix fun <T, U> Iterable<T>.shouldBeSameSizeAs(other: Iterable<U>) = toList().shouldBeSameSizeAs(other.toList())335infix fun <T, U> Array<T>.shouldBeSameSizeAs(other: Array<U>) = asList().shouldBeSameSizeAs(other.asList())336infix fun <T, U> Collection<T>.shouldBeSameSizeAs(other: Collection<U>) = this should beSameSizeAs(other)337fun <T, U> beSameSizeAs(other: Collection<U>) = object : Matcher<Collection<T>> {338   override fun test(value: Collection<T>) = MatcherResult(339      value.size == other.size,340      "Collection of size ${value.size} should be the same size as collection of size ${other.size}",341      "Collection of size ${value.size} should not be the same size as collection of size ${other.size}"342   )343}344infix fun <T> Iterable<T>.shouldHaveAtLeastSize(n: Int) = toList().shouldHaveAtLeastSize(n)345infix fun <T> Array<T>.shouldHaveAtLeastSize(n: Int) = asList().shouldHaveAtLeastSize(n)346infix fun <T> Collection<T>.shouldHaveAtLeastSize(n: Int) = this shouldHave atLeastSize(n)347fun <T> atLeastSize(n: Int) = object : Matcher<Collection<T>> {348   override fun test(value: Collection<T>) = MatcherResult(349      value.size >= n,350      "Collection should contain at least $n elements",351      "Collection should contain less than $n elements"352   )353}354infix fun <T> Iterable<T>.shouldHaveAtMostSize(n: Int) = toList().shouldHaveAtMostSize(n)355infix fun <T> Array<T>.shouldHaveAtMostSize(n: Int) = asList().shouldHaveAtMostSize(n)356infix fun <T> Collection<T>.shouldHaveAtMostSize(n: Int) = this shouldHave atMostSize(n)357fun <T> atMostSize(n: Int) = object : Matcher<Collection<T>> {358   override fun test(value: Collection<T>) = MatcherResult(359      value.size <= n,360      "Collection should contain at most $n elements",361      "Collection should contain more than $n elements"362   )363}364infix fun <T> Iterable<T>.shouldExist(p: (T) -> Boolean) = toList().shouldExist(p)365infix fun <T> Array<T>.shouldExist(p: (T) -> Boolean) = asList().shouldExist(p)366infix fun <T> Collection<T>.shouldExist(p: (T) -> Boolean) = this should exist(p)367fun <T> exist(p: (T) -> Boolean) = object : Matcher<Collection<T>> {368   override fun test(value: Collection<T>) = MatcherResult(369      value.any { p(it) },370      "Collection should contain an element that matches the predicate $p",371      "Collection should not contain an element that matches the predicate $p"372   )373}374fun <T> Iterable<T>.shouldExistInOrder(vararg ps: (T) -> Boolean) = toList().shouldExistInOrder(ps.toList())375fun <T> Array<T>.shouldExistInOrder(vararg ps: (T) -> Boolean) = asList().shouldExistInOrder(ps.toList())376fun <T> List<T>.shouldExistInOrder(vararg ps: (T) -> Boolean) = this.shouldExistInOrder(ps.toList())377infix fun <T> Iterable<T>.shouldExistInOrder(expected: List<(T) -> Boolean>) = toList().shouldExistInOrder(expected)378infix fun <T> Array<T>.shouldExistInOrder(expected: List<(T) -> Boolean>) = asList().shouldExistInOrder(expected)379infix fun <T> List<T>.shouldExistInOrder(expected: List<(T) -> Boolean>) = this should existInOrder(expected)380infix fun <T> Iterable<T>.shouldNotExistInOrder(expected: Iterable<(T) -> Boolean>) = toList().shouldNotExistInOrder(expected.toList())381infix fun <T> Array<T>.shouldNotExistInOrder(expected: Array<(T) -> Boolean>) = asList().shouldNotExistInOrder(expected.asList())382infix fun <T> Iterable<T>.shouldNotExistInOrder(expected: List<(T) -> Boolean>) = toList().shouldNotExistInOrder(expected)383infix fun <T> Array<T>.shouldNotExistInOrder(expected: List<(T) -> Boolean>) = asList().shouldNotExistInOrder(expected)384infix fun <T> List<T>.shouldNotExistInOrder(expected: List<(T) -> Boolean>) = this shouldNot existInOrder(expected)385fun <T> Iterable<T>.shouldBeEmpty() = toList().shouldBeEmpty()386fun <T> Array<T>.shouldBeEmpty() = asList().shouldBeEmpty()387fun <T> Collection<T>.shouldBeEmpty() = this should beEmpty()388fun <T> Iterable<T>.shouldNotBeEmpty() = toList().shouldNotBeEmpty()389fun <T> Array<T>.shouldNotBeEmpty() = asList().shouldNotBeEmpty()390fun <T> Collection<T>.shouldNotBeEmpty() = this shouldNot beEmpty()391fun <T> Iterable<T>.shouldContainAnyOf(vararg ts: T) = toList().shouldContainAnyOf(ts)392fun <T> Array<T>.shouldContainAnyOf(vararg ts: T) = asList().shouldContainAnyOf(ts)393fun <T> Collection<T>.shouldContainAnyOf(vararg ts: T) = this should containAnyOf(ts.asList())394fun <T> Iterable<T>.shouldNotContainAnyOf(vararg ts: T) = toList().shouldNotContainAnyOf(ts)395fun <T> Array<T>.shouldNotContainAnyOf(vararg ts: T) = asList().shouldNotContainAnyOf(ts)396fun <T> Collection<T>.shouldNotContainAnyOf(vararg ts: T) = this shouldNot containAnyOf(ts.asList())397infix fun <T> Iterable<T>.shouldContainAnyOf(ts: Collection<T>) = toList().shouldContainAnyOf(ts)398infix fun <T> Array<T>.shouldContainAnyOf(ts: Collection<T>) = asList().shouldContainAnyOf(ts)399infix fun <T> Collection<T>.shouldContainAnyOf(ts: Collection<T>) = this should containAnyOf(ts)400infix fun <T> Iterable<T>.shouldNotContainAnyOf(ts: Collection<T>) = toList().shouldNotContainAnyOf(ts)401infix fun <T> Array<T>.shouldNotContainAnyOf(ts: Collection<T>) = asList().shouldNotContainAnyOf(ts)402infix fun <T> Collection<T>.shouldNotContainAnyOf(ts: Collection<T>) = this shouldNot containAnyOf(ts)403fun <T> containAnyOf(ts: Collection<T>) = object : Matcher<Collection<T>> {404   override fun test(value: Collection<T>): MatcherResult {405      if (ts.isEmpty()) throwEmptyCollectionError()406      return MatcherResult(407         ts.any { it in value },408         { "Collection should contain any of ${ts.joinToString(separator = ", ", limit = 10) { it.show().value }}" },409         { "Collection should not contain any of ${ts.joinToString(separator = ", ", limit = 10) { it.show().value }}" }410      )411   }412}413/**414 * Verifies that this instance is in [collection]415 *416 * Assertion to check that this instance is in [collection]. This assertion checks by reference, and not by value,417 * therefore the exact instance must be in [collection], or this will fail.418 *419 * An empty collection will always fail. If you need to check for empty collection, use [Collection.shouldBeEmpty]420 *421 * @see [shouldNotBeOneOf]422 * @see [beOneOf]423 */424infix fun <T> T.shouldBeOneOf(collection: Collection<T>) = this should beOneOf(collection)425/**426 * Verifies that this instance is NOT in [collection]427 *428 * Assertion to check that this instance is not in [collection]. This assertion checks by reference, and not by value,429 * therefore the exact instance must not be in [collection], or this will fail.430 *431 * An empty collection will always fail. If you need to check for empty collection, use [Collection.shouldBeEmpty]432 *433 * @see [shouldBeOneOf]434 * @see [beOneOf]435 */436infix fun <T> T.shouldNotBeOneOf(collection: Collection<T>) = this shouldNot beOneOf(collection)437/**438 * Verifies that this instance is any of [any]439 *440 * Assertion to check that this instance is any of [any]. This assertion checks by reference, and not by value,441 * therefore the exact instance must be in [any], or this will fail.442 *443 * An empty collection will always fail. If you need to check for empty collection, use [Collection.shouldBeEmpty]444 *445 * @see [shouldNotBeOneOf]446 * @see [beOneOf]447 */448fun <T> T.shouldBeOneOf(vararg any: T) = this should beOneOf(any.toList())449/**450 * Verifies that this instance is NOT any of [any]451 *452 * Assertion to check that this instance is not any of [any]. This assertion checks by reference, and not by value,453 * therefore the exact instance must not be in [any], or this will fail.454 *455 * An empty collection will always fail. If you need to check for empty collection, use [Collection.shouldBeEmpty]456 *457 * @see [shouldNotBeOneOf]458 * @see [beOneOf]459 */460fun <T> T.shouldNotBeOneOf(vararg any: T) = this shouldNot beOneOf(any.toList())461/**462 * Matcher that verifies that this instance is in [collection]463 *464 * Assertion to check that this instance is in [collection]. This matcher checks by reference, and not by value,465 * therefore the exact instance must be in [collection], or this will fail.466 *467 * An empty collection will always fail. If you need to check for empty collection, use [Collection.shouldBeEmpty]468 *469 * @see [shouldBeOneOf]470 * @see [shouldNotBeOneOf]471 */472fun <T> beOneOf(collection: Collection<T>) = object : Matcher<T> {473   override fun test(value: T): MatcherResult {474      if (collection.isEmpty()) throwEmptyCollectionError()475      val match = collection.any { it === value }476      return MatcherResult(477         match,478         "Collection should contain the instance of value, but doesn't.",479         "Collection should not contain the instance of value, but does."480      )481   }482}483/**484 * Verifies that this element is in [collection] by comparing value485 *486 * Assertion to check that this element is in [collection]. This assertion checks by value, and not by reference,487 * therefore even if the exact instance is not in [collection] but another instance with same value is present, the488 * test will pass.489 *490 * An empty collection will always fail. If you need to check for empty collection, use [Collection.shouldBeEmpty]491 *492 * @see [shouldNotBeIn]493 * @see [beIn]494 */495infix fun <T> T.shouldBeIn(collection: Collection<T>) = this should beIn(collection)496/**497 * Verifies that this element is NOT any of [collection]498 *499 * Assertion to check that this element is not any of [collection]. This assertion checks by value, and not by reference,500 * therefore any instance with same value must not be in [collection], or this will fail.501 *502 * An empty collection will always fail. If you need to check for empty collection, use [Collection.shouldBeEmpty]503 *504 * @see [shouldNotBeIn]505 * @see [beIn]506 */507infix fun <T> T.shouldNotBeIn(collection: Collection<T>) = this shouldNot beIn(collection.toList())508/**509 * Verifies that this element is any of [any] by comparing value510 *511 * Assertion to check that this element is any of [any]. This assertion checks by value, and not by reference,512 * therefore even if the exact instance is not any of [any] but another instance with same value is present, the513 * test will pass.514 *515 * An empty collection will always fail. If you need to check for empty collection, use [Collection.shouldBeEmpty]516 *517 * @see [shouldNotBeIn]518 * @see [beIn]519 */520fun <T> T.shouldBeIn(vararg any: T) = this should beIn(any.toList())521/**522 * Verifies that this element is NOT any of [any]523 *524 * Assertion to check that this element is not any of [any]. This assertion checks by value, and not by reference,525 * therefore any instance with same value must not be in [any], or this will fail.526 *527 * An empty collection will always fail. If you need to check for empty collection, use [Collection.shouldBeEmpty]528 *529 * @see [shouldNotBeIn]530 * @see [beIn]531 */532fun <T> T.shouldNotBeIn(vararg any: T) = this shouldNot beIn(any.toList())533/**534 * Verifies that this element is in [array] by comparing value535 *536 * Assertion to check that this element is in [array]. This assertion checks by value, and not by reference,537 * therefore even if the exact instance is not in [array] but another instance with same value is present, the538 * test will pass.539 *540 * An empty array will always fail. If you need to check for empty array, use [Array.shouldBeEmpty]541 *542 * @see [shouldNotBeIn]543 * @see [beIn]544 */545@JvmName("shouldBeInArray")546infix fun <T> T.shouldBeIn(array: Array<T>) = this should beIn(array.toList())547/**548 * Verifies that this element is NOT any of [array]549 *550 * Assertion to check that this element is not any of [array]. This assertion checks by value, and not by reference,551 * therefore any instance with same value must not be in [array], or this will fail.552 *553 * An empty array will always fail. If you need to check for empty array, use [Array.shouldBeEmpty]554 *555 * @see [shouldNotBeIn]556 * @see [beIn]557 */558@JvmName("shouldNotBeInArray")559infix fun <T> T.shouldNotBeIn(array: Array<T>) = this shouldNot beIn(array.toList())560/**561 *  Matcher that verifies that this element is in [collection] by comparing value562 *563 * Assertion to check that this element is in [collection]. This assertion checks by value, and not by reference,564 * therefore even if the exact instance is not in [collection] but another instance with same value is present, the565 * test will pass.566 *567 * An empty collection will always fail. If you need to check for empty collection, use [Collection.shouldBeEmpty]568 *569 * @see [shouldBeOneOf]570 * @see [shouldNotBeOneOf]571 */572fun <T> beIn(collection: Collection<T>) = object : Matcher<T> {573   override fun test(value: T): MatcherResult {574      if (collection.isEmpty()) throwEmptyCollectionError()575      val match = value in collection576      return MatcherResult(577         match,578         "Collection should contain ${value.show().value}, but doesn't. Possible values: ${collection.show().value}",579         "Collection should not contain ${value.show().value}, but does. Forbidden values: ${collection.show().value}"580      )581   }582}583private fun throwEmptyCollectionError(): Nothing {584   throw AssertionError("Asserting content on empty collection. Use Collection.shouldBeEmpty() instead.")585}...SequenceMatchersTest.kt
Source:SequenceMatchersTest.kt  
1package com.sksamuel.kotest.matchers.collections2import io.kotest.assertions.throwables.shouldThrow3import io.kotest.assertions.throwables.shouldThrowAny4import io.kotest.core.spec.style.WordSpec5import io.kotest.core.spec.style.scopes.WordSpecTerminalScope6import io.kotest.core.spec.style.scopes.WordSpecShouldContainerScope7import io.kotest.matchers.sequences.shouldBeLargerThan8import io.kotest.matchers.sequences.shouldBeSameCountAs9import io.kotest.matchers.sequences.shouldBeSmallerThan10import io.kotest.matchers.sequences.shouldBeSorted11import io.kotest.matchers.sequences.shouldBeSortedWith12import io.kotest.matchers.sequences.shouldBeUnique13import io.kotest.matchers.sequences.shouldContain14import io.kotest.matchers.sequences.shouldContainAll15import io.kotest.matchers.sequences.shouldContainAllInAnyOrder16import io.kotest.matchers.sequences.shouldContainDuplicates17import io.kotest.matchers.sequences.shouldContainExactly18import io.kotest.matchers.sequences.shouldContainInOrder19import io.kotest.matchers.sequences.shouldContainNoNulls20import io.kotest.matchers.sequences.shouldContainNull21import io.kotest.matchers.sequences.shouldContainOnlyNulls22import io.kotest.matchers.sequences.shouldExist23import io.kotest.matchers.sequences.shouldHaveAtLeastCount24import io.kotest.matchers.sequences.shouldHaveAtMostCount25import io.kotest.matchers.sequences.shouldHaveCount26import io.kotest.matchers.sequences.shouldHaveElementAt27import io.kotest.matchers.sequences.shouldHaveLowerBound28import io.kotest.matchers.sequences.shouldHaveSingleElement29import io.kotest.matchers.sequences.shouldHaveUpperBound30import io.kotest.matchers.sequences.shouldNotBeSorted31import io.kotest.matchers.sequences.shouldNotBeSortedWith32import io.kotest.matchers.sequences.shouldNotBeUnique33import io.kotest.matchers.sequences.shouldNotContain34import io.kotest.matchers.sequences.shouldNotContainAllInAnyOrder35import io.kotest.matchers.sequences.shouldNotContainExactly36import io.kotest.matchers.sequences.shouldNotContainNoNulls37import io.kotest.matchers.sequences.shouldNotContainNull38import io.kotest.matchers.sequences.shouldNotContainOnlyNulls39import io.kotest.matchers.sequences.shouldNotHaveCount40import io.kotest.matchers.sequences.shouldNotHaveElementAt41class SequenceMatchersTest : WordSpec() {42   /* PassFail */43   private suspend fun WordSpecShouldContainerScope.pass(name: String, test: suspend WordSpecTerminalScope.() -> Unit) {44      ("succeed $name")(test)45   }46   private suspend fun WordSpecShouldContainerScope.succeed(name: String, test: suspend WordSpecTerminalScope.() -> Unit) = pass(name, test)47   fun WordSpecShouldContainerScope.fail(msg: String): Nothing = io.kotest.assertions.fail(msg)48   suspend fun WordSpecShouldContainerScope.fail(name: String, test: () -> Any?) {49      ("fail $name") { shouldThrowAny(test) }50   }51   suspend inline fun <reified E : Throwable> WordSpecShouldContainerScope.abort(name: String, crossinline test: () -> Any?) {52      ("abort $name") { shouldThrow<E>(test) }53   }54   suspend inline fun <reified E : Throwable> WordSpecShouldContainerScope.`throw`(name: String, crossinline test: () -> Any?) = abort<E>(55      name,56      test)57   /* sample data */58   val empty = emptySequence<Int>()59   val single = sequenceOf(0)60   val nulls = sequenceOf<Int?>(null, null, null, null)61   val sparse = sequenceOf(null, null, null, 3)62   val countup = (0..10).asSequence()63   val countdown = (10 downTo 0).asSequence()64   val unique = sequenceOf(3, 2, 1)65   val repeating = sequenceOf(1, 2, 3, 1, 2, 3)66   val asc = { a: Int, b: Int -> a - b }67   val desc = { a: Int, b: Int -> b - a }68   /* tests */69   init {70      /* count */71      "have count" should {72         succeed("for empty when 0") {73            empty.shouldHaveCount(0)74         }75         fail("for empty when non-zero") {76            empty.shouldHaveCount(1)77         }78         succeed("for single when 1") {79            single.shouldHaveCount(1)80         }81         fail("for single when 0") {82            single.shouldHaveCount(0)83         }84         "match count() for multiple" {85            sparse.shouldHaveCount(sparse.count())86         }87         fail("to mis-match count() for multiple") {88            sparse.shouldHaveCount(sparse.count() - 1)89         }90      }91      "not have count" should {92         fail("for empty when non-zero") {93            empty.shouldNotHaveCount(0)94         }95         succeed("for empty when non-zero") {96            empty.shouldNotHaveCount(1)97         }98         fail("for single when 1") {99            single.shouldNotHaveCount(1)100         }101         succeed("for single when 0") {102            single.shouldNotHaveCount(0)103         }104         fail("to match count() for multiple") {105            sparse.shouldNotHaveCount(sparse.count())106         }107         "mis-match count() for multiple" {108            sparse.shouldNotHaveCount(sparse.count() - 1)109         }110      }111      "larger than" should {112         fail("for empty") {113            empty.shouldBeLargerThan(single)114         }115         succeed("with empty") {116            single.shouldBeLargerThan(empty)117         }118         fail("for smaller") {119            nulls.shouldBeLargerThan(countup)120         }121         fail("for same count") {122            countup.shouldBeLargerThan(countdown)123         }124         succeed("for larger") {125            countup.shouldBeLargerThan(nulls)126         }127      }128      "smaller than" should {129         succeed("for empty") {130            empty.shouldBeSmallerThan(single)131         }132         fail("with empty") {133            single.shouldBeSmallerThan(empty)134         }135         succeed("for smaller") {136            nulls.shouldBeSmallerThan(countup)137         }138         fail("for same count") {139            countup.shouldBeSmallerThan(countdown)140         }141         fail("for larger") {142            countup.shouldBeSmallerThan(nulls)143         }144      }145      "same count" should {146         fail("for empty with any") {147            empty.shouldBeSameCountAs(single)148         }149         fail("for any with empty") {150            nulls.shouldBeSameCountAs(empty)151         }152         fail("for smaller") {153            nulls.shouldBeSameCountAs(countup)154         }155         succeed("with same count") {156            countup.shouldBeSameCountAs(countdown)157         }158         fail("for larger") {159            countup.shouldBeSmallerThan(nulls)160         }161      }162      "at least count" should {163         succeed("for empty with -1") {164            empty.shouldHaveAtLeastCount(-1)165         }166         succeed("for any with -1") {167            countup.shouldHaveAtLeastCount(-1)168         }169         succeed("for empty with 0") {170            empty.shouldHaveAtLeastCount(0)171         }172         fail("for empty with 1") {173            empty.shouldHaveAtLeastCount(1)174         }175         succeed("for smaller count") {176            single.shouldHaveAtLeastCount(0)177         }178         succeed("for same count") {179            nulls.shouldHaveAtLeastCount(nulls.count())180         }181         fail("for larger count") {182            countup.shouldHaveAtLeastCount(countup.count() + 1)183         }184      }185      "at most count" should {186         fail("for empty with -1") {187            empty.shouldHaveAtMostCount(-1)188         }189         succeed("for empty with 0") {190            empty.shouldHaveAtMostCount(0)191         }192         succeed("for empty with 1") {193            empty.shouldHaveAtMostCount(1)194         }195         fail("for smaller count") {196            countup.shouldHaveAtMostCount(countup.count() - 1)197         }198         succeed("for same count") {199            countup.shouldHaveAtMostCount(countup.count())200         }201         succeed("for larger count") {202            countup.shouldHaveAtMostCount(countup.count() + 1)203         }204      }205      /* contain */206      /** null */207      "contain only nulls" should {208         succeed("for empty") {209            empty.shouldContainOnlyNulls()210         }211         fail("for single") {212            single.shouldContainOnlyNulls()213         }214         succeed("for nulls") {215            nulls.shouldContainOnlyNulls()216         }217         fail("for sparse") {218            sparse.shouldContainOnlyNulls()219         }220      }221      "not contain only nulls" should {222         fail("for empty") {223            empty.shouldNotContainOnlyNulls()224         }225         "fail for single" {226            single.shouldNotContainOnlyNulls()227         }228         fail("for nulls") {229            nulls.shouldNotContainOnlyNulls()230         }231         succeed("for sparse") {232            sparse.shouldNotContainOnlyNulls()233         }234      }235      "contain a null" should {236         fail("for empty") {237            empty.shouldContainNull()238         }239         fail("for non-nulls") {240            single.shouldContainNull()241         }242         succeed("for nulls") {243            nulls.shouldContainNull()244         }245         succeed("for sparse") {246            sparse.shouldContainNull()247         }248      }249      "not contain a null" should {250         succeed("for empty") {251            empty.shouldNotContainNull()252         }253         succeed("for non-nulls") {254            single.shouldNotContainNull()255         }256         fail("for nulls") {257            nulls.shouldNotContainNull()258         }259         fail("for sparse") {260            sparse.shouldNotContainNull()261         }262      }263      "contain no nulls" should {264         succeed("for empty") {265            empty.shouldContainNoNulls()266         }267         succeed("for non-nulls") {268            single.shouldContainNoNulls()269         }270         fail("for nulls") {271            nulls.shouldContainNoNulls()272         }273         fail("for sparse") {274            sparse.shouldContainNoNulls()275         }276      }277      "not contain no nulls" should {278         fail("for empty") {279            empty.shouldNotContainNoNulls()280         }281         fail("for non-nulls") {282            single.shouldNotContainNoNulls()283         }284         succeed("for nulls") {285            nulls.shouldNotContainNoNulls()286         }287         succeed("for sparse") {288            sparse.shouldNotContainNoNulls()289         }290      }291      /** single-value */292      "single element" should {293         fail("for empty") {294            empty.shouldHaveSingleElement(null)295         }296         succeed("for single") {297            single.shouldHaveSingleElement(single.first())298         }299         fail("for multiple") {300            nulls.shouldHaveSingleElement(null)301         }302      }303      "have element at" should {304         abort<IndexOutOfBoundsException>("for empty") {305            empty.shouldHaveElementAt(empty.count(), 0)306         }307         abort<IndexOutOfBoundsException>("when an element after the end is requested") {308            nulls.shouldHaveElementAt(nulls.count(), 0)309         }310         succeed("when the sequence has the element") {311            countup.shouldHaveElementAt(10, 10)312         }313         fail("when the sequence doesn't have the element") {314            countdown.shouldHaveElementAt(10, 10)315         }316      }317      "not have element at" should {318         abort<IndexOutOfBoundsException>("for empty") {319            empty.shouldNotHaveElementAt(empty.count(), 0)320         }321         abort<IndexOutOfBoundsException>("when an element after the end is requested") {322            nulls.shouldNotHaveElementAt(nulls.count(), 0)323         }324         fail("when the sequence has the element") {325            countup.shouldNotHaveElementAt(10, 10)326         }327         succeed("when the sequence doesn't have the element") {328            countdown.shouldNotHaveElementAt(10, 10)329         }330      }331      "contain" should {332         fail("for empty") {333            empty.shouldContain(0)334         }335         succeed("when the sequence contains the value") {336            countup.shouldContain(2)337         }338         fail("when the sequence doesn't contain the value") {339            sparse.shouldContain(2)340         }341      }342      "not contain" should {343         succeed("for empty") {344            empty.shouldNotContain(0)345         }346         fail("when the sequence contains the value") {347            countup.shouldNotContain(2)348         }349         succeed("when the sequence doesn't contain the value") {350            sparse.shouldNotContain(2)351         }352      }353      "exist" should {354         fail("for empty") {355            empty.shouldExist { true }356         }357         succeed("when always true") {358            single.shouldExist { true }359         }360         fail("when always false") {361            countup.shouldExist { false }362         }363         succeed("when matches at least one") {364            countdown.shouldExist { it % 5 == 4 }365         }366         fail("when matches none") {367            countdown.shouldExist { it > 20 }368         }369      }370      /** multiple-value */371      "contain all" should {372         succeed("for empty with empty") {373            empty.shouldContainAll(empty)374         }375         succeed("for empty with empty (variadic)") {376            empty.shouldContainAll()377         }378         fail("for empty with any other") {379            empty.shouldContainAll(single)380         }381         succeed("for any with empty") {382            single.shouldContainAll(empty)383         }384         succeed("for any with empty (variadic)") {385            single.shouldContainAll()386         }387         succeed("for subset of nulls") {388            sparse.shouldContainAll(nulls)389         }390         succeed("for subset of nulls (variadic)") {391            sparse.shouldContainAll(null, null)392         }393         succeed("for subset in order (variadic)") {394            countdown.shouldContainAll(2, 3, 5, 7)395         }396         succeed("for subset not in order (variadic)") {397            countdown.shouldContainAll(2, 5, 3, 7)398         }399         succeed("for same elements") {400            repeating.shouldContainAll(unique)401         }402         succeed("for same elements (variadic)") {403            repeating.shouldContainAll(2, 3, 1)404         }405         succeed("for same elements, repeated") {406            unique.shouldContainAll(repeating)407         }408         succeed("for same elements, repeated (variadic)") {409            unique.shouldContainAll(1, 2, 3, 1, 2, 3)410         }411      }412      "contain exactly empty" should {413         succeed("for empty") {414            empty.shouldContainExactly(sequenceOf<Int>())415         }416         succeed("for empty (variadic)") {417            empty.shouldContainExactly()418         }419         fail("for single") {420            single.shouldContainExactly(empty)421         }422         "fail for single (variadic)" {423            shouldThrowAny {424               single.shouldContainExactly()425            }426         }427         fail("for multiple") {428            nulls.shouldContainExactly(empty)429         }430         fail("for multiple (variadic)") {431            nulls.shouldContainExactly()432         }433      }434      "contain exactly non-empty" should {435         val nonempty = sparse;436         fail("for empty") {437            empty.shouldContainExactly(nonempty)438         }439         fail("for empty (variadic)") {440            empty.shouldContainExactly(*nonempty.toList().toTypedArray())441         }442         succeed("for same") {443            sparse.shouldContainExactly(nonempty)444         }445         succeed("for same (variadic)") {446            sparse.shouldContainExactly(*sparse.toList().toTypedArray())447         }448         fail("for another of different size") {449            countup.shouldContainExactly(nonempty)450         }451         fail("for another of different size (variadic)") {452            countup.shouldContainExactly(*nonempty.toList().toTypedArray())453         }454         fail("for another of same size") {455            nulls.shouldContainExactly(nonempty)456         }457         fail("for another of same size (variadic)") {458            nulls.shouldContainExactly(*nonempty.toList().toTypedArray())459         }460         fail("for same elements but different order") {461            repeating.shouldContainExactly(unique + unique)462         }463         fail("for same elements but different order (variadic)") {464            repeating.shouldContainExactly(1, 1, 2, 2, 3, 3)465         }466      }467      "not contain exactly empty" should {468         fail("for empty") {469            empty.shouldNotContainExactly(sequenceOf<Int>())470         }471         succeed("for single") {472            single.shouldNotContainExactly(empty)473         }474         succeed("for multiple") {475            nulls.shouldNotContainExactly(empty)476         }477      }478      "not contain exactly non-empty" should {479         val nonempty = sparse;480         succeed("for empty") {481            empty.shouldNotContainExactly(nonempty)482         }483         fail("for same") {484            sparse.shouldNotContainExactly(nonempty)485         }486         succeed("for another of different size") {487            countup.shouldNotContainExactly(nonempty)488         }489         succeed("for another of same size") {490            nulls.shouldNotContainExactly(nonempty)491         }492         succeed("for same elements but different order") {493            repeating.shouldNotContainExactly(unique + unique)494         }495         succeed("for same elements but different order (variadic)") {496            repeating.shouldNotContainExactly(1, 1, 2, 2, 3, 3)497         }498         succeed("for single traversable equal sequence") {499            var count1 = 0500            var count2 = 0501            val seq1 = generateSequence { if(count1 < 5) count1++ else null }502            val seq2 = generateSequence { if(count2 < 5) count2++ else null }503            seq1.shouldContainExactly(seq2)504         }505         fail("for single traversable unequal sequence") {506            var count1 = 0507            var count2 = 0508            val seq1 = generateSequence { if(count1 < 5) count1++ else null }509            val seq2 = generateSequence { if(count2 < 6) count2++ else null }510            seq1.shouldContainExactly(seq2)511         }512      }513      "contain in any order" should {514         succeed("for empty with empty") {515            empty.shouldContainAllInAnyOrder(empty)516         }517         fail("for empty with any other") {518            empty.shouldContainAllInAnyOrder(nulls)519         }520         succeed("when elements are same") {521            countdown.shouldContainAllInAnyOrder(countup)522         }523         fail("for overlapping sequence") {524            countup.shouldContainAllInAnyOrder((5..15).asSequence())525         }526         succeed("for subset, same count with nulls") {527            sparse.shouldContainAllInAnyOrder(nulls)528         }529         succeed("for subset, same count") {530            repeating.shouldContainAllInAnyOrder(unique + unique)531         }532         succeed("for subset, same count (variadic)") {533            repeating.shouldContainAllInAnyOrder(1, 1, 2, 2, 3, 3)534         }535         fail("for subset, different count with nulls") {536            sparse.shouldContainAllInAnyOrder(sparse.toSet().asSequence())537         }538         fail("for same, different count") {539            repeating.shouldContainAllInAnyOrder(unique)540         }541      }542      "not contain in any order" should {543         fail("for empty with empty") {544            empty.shouldNotContainAllInAnyOrder(empty)545         }546         succeed("for empty with any other") {547            empty.shouldNotContainAllInAnyOrder(nulls)548         }549         fail("when elements are same") {550            countdown.shouldNotContainAllInAnyOrder(countup)551         }552         succeed("for overlapping sequence") {553            countup.shouldNotContainAllInAnyOrder((5..15).asSequence())554         }555         fail("for subset, same count with nulls") {556            sparse.shouldNotContainAllInAnyOrder(nulls)557         }558         fail("for subset, same count") {559            repeating.shouldNotContainAllInAnyOrder(unique + unique)560         }561         fail("for subset, same count (variadic)") {562            repeating.shouldNotContainAllInAnyOrder(1, 1, 2, 2, 3, 3)563         }564         succeed("for subset, different count with nulls") {565            sparse.shouldNotContainAllInAnyOrder(sparse.toSet().asSequence())566         }567         succeed("for same, different count") {568            repeating.shouldNotContainAllInAnyOrder(unique)569         }570      }571      "contain in order" should {572         "with empty" {573            shouldThrowAny {574               countup.shouldContainInOrder(empty)575            }576         }577         fail("with empty (variadic)") {578            countup.shouldContainInOrder()579         }580         fail("for overlapping sequence") {581            countup.shouldContainInOrder((5..15).asSequence())582         }583         fail("for overlapping sequence (variadic)") {584            countup.shouldContainInOrder(*(5..15).toList().toTypedArray())585         }586         succeed("for subset in order") {587            countup.shouldContainInOrder(sequenceOf(2, 3, 5, 7))588         }589         succeed("for subset in order (variadic)") {590            countup.shouldContainInOrder(2, 3, 5, 7)591         }592         succeed("for subset in order with repeats") {593            repeating.shouldContainInOrder(sequenceOf(1, 3, 1, 2))594         }595         succeed("for subset in order with repeats (variadic)") {596            repeating.shouldContainInOrder(1, 3, 1, 2)597         }598         fail("for subset in order with too many repeats") {599            repeating.shouldContainInOrder(sequenceOf(1, 3, 1, 2, 2))600         }601         fail("for subset in order with too many repeats (variadic)") {602            repeating.shouldContainInOrder(1, 3, 1, 2, 2)603         }604         fail("for subset not in order") {605            countup.shouldContainInOrder(sequenceOf(2, 5, 3, 7))606         }607         fail("for subset not in order (variadic)") {608            countup.shouldContainInOrder(2, 5, 3, 7)609         }610      }611      /** unique */612      "unique" should {613         succeed("for empty") {614            empty.shouldBeUnique()615         }616         succeed("for single") {617            single.shouldBeUnique()618         }619         fail("with repeated nulls") {620            sparse.shouldBeUnique()621         }622         fail("with repeats") {623            repeating.shouldBeUnique()624         }625         succeed("for multiple unique") {626            countup.shouldBeUnique()627         }628      }629      "not unique" should {630         fail("for empty") {631            empty.shouldNotBeUnique()632         }633         fail("for single") {634            single.shouldNotBeUnique()635         }636         succeed("with repeated nulls") {637            sparse.shouldNotBeUnique()638         }639         succeed("with repeats") {640            repeating.shouldNotBeUnique()641         }642         fail("for multiple unique") {643            countup.shouldNotBeUnique()644         }645      }646      "duplicates" should {647         fail("for empty") {648            empty.shouldContainDuplicates()649         }650         fail("for single") {651            single.shouldContainDuplicates()652         }653         succeed("with repeated nulls") {654            sparse.shouldContainDuplicates()655         }656         succeed("with repeats") {657            repeating.shouldNotBeUnique()658         }659         fail("for multiple unique") {660            countup.shouldContainDuplicates()661         }662      }663      /* comparable */664      /** bound */665      "have an upper bound" should {666         succeed("for empty") {667            empty.shouldHaveUpperBound(Int.MIN_VALUE)668         }669         succeed("for single") {670            single.shouldHaveUpperBound(0)671         }672         fail("for single with wrong bound") {673            single.shouldHaveUpperBound(-1)674         }675         succeed("for multiple") {676            countup.shouldHaveUpperBound(countup.maxOrNull() ?: Int.MAX_VALUE)677         }678         fail("for multiple with wrong bound") {679            countup.shouldHaveUpperBound((countup.maxOrNull() ?: Int.MAX_VALUE) - 1)680         }681      }682      "have a lower bound" should {683         succeed("for empty") {684            empty.shouldHaveLowerBound(Int.MAX_VALUE)685         }686         succeed("for single") {687            single.shouldHaveLowerBound(0)688         }689         fail("for single with wrong bound") {690            single.shouldHaveLowerBound(1)691         }692         succeed("for multiple") {693            countup.shouldHaveLowerBound(countup.minOrNull() ?: Int.MIN_VALUE)694         }695         fail("for multiple with wrong bound") {696            countup.shouldHaveLowerBound((countup.minOrNull() ?: Int.MIN_VALUE) + 1)697         }698      }699      /** sort */700      "sorted" should {701         succeed("for empty") {702            empty.shouldBeSorted()703         }704         succeed("for single") {705            single.shouldBeSorted()706         }707         fail("for repeating") {708            repeating.shouldBeSorted()709         }710         succeed("for count-up") {711            countup.shouldBeSorted()712         }713         fail("for count-down") {714            countdown.shouldBeSorted()715         }716      }717      "not sorted" should {718         fail("for empty") {719            empty.shouldNotBeSorted()720         }721         fail("for single") {722            single.shouldNotBeSorted()723         }724         succeed("for repeating") {725            repeating.shouldNotBeSorted()726         }727         fail("for count-up") {728            countup.shouldNotBeSorted()729         }730         succeed("for count-down") {731            countdown.shouldNotBeSorted()732         }733      }734      "sorted ascending" should {735         val dir = asc736         succeed("for empty") {737            empty.shouldBeSortedWith(dir)738         }739         succeed("for single") {740            single.shouldBeSortedWith(dir)741         }742         fail("for repeating") {743            repeating.shouldBeSortedWith(dir)744         }745         succeed("for count-up") {746            countup.shouldBeSortedWith(dir)747         }748         fail("for count-down") {749            countdown.shouldBeSortedWith(dir)750         }751      }752      "sorted descending" should {753         val dir = desc754         succeed("for empty") {755            empty.shouldBeSortedWith(dir)756         }757         succeed("for single") {758            single.shouldBeSortedWith(dir)759         }760         fail("for repeating") {761            repeating.shouldBeSortedWith(dir)762         }763         fail("for count-up") {764            countup.shouldBeSortedWith(dir)765         }766         succeed("for count-down") {767            countdown.shouldBeSortedWith(dir)768         }769      }770      "not sorted ascending" should {771         val dir = asc772         fail("for empty") {773            empty.shouldNotBeSortedWith(dir)774         }775         fail("for single") {776            single.shouldNotBeSortedWith(dir)777         }778         succeed("for repeating") {779            repeating.shouldNotBeSortedWith(dir)780         }781         fail("for count-up") {782            countup.shouldNotBeSortedWith(dir)783         }784         succeed("for count-down") {785            countdown.shouldNotBeSortedWith(dir)786         }787      }788      "not sorted descending" should {789         val dir = desc790         fail("for empty") {791            empty.shouldNotBeSortedWith(dir)792         }793         fail("for single") {794            single.shouldNotBeSortedWith(dir)795         }796         succeed("for repeating") {797            repeating.shouldNotBeSortedWith(dir)798         }799         succeed("for count-up") {800            countup.shouldNotBeSortedWith(dir)801         }802         fail("for count-down") {803            countdown.shouldNotBeSortedWith(dir)804         }805      }806   }807}...MonomialTest.kt
Source:MonomialTest.kt  
1package com.github.shwaka.kohomology.free2import com.github.shwaka.kohomology.dg.degree.DegreeIndeterminate3import com.github.shwaka.kohomology.dg.degree.MultiDegreeGroup4import com.github.shwaka.kohomology.dg.degree.MultiDegreeMorphism5import com.github.shwaka.kohomology.forAll6import com.github.shwaka.kohomology.free.monoid.FreeMonoid7import com.github.shwaka.kohomology.free.monoid.FreeMonoidMorphismByDegreeChange8import com.github.shwaka.kohomology.free.monoid.Indeterminate9import com.github.shwaka.kohomology.free.monoid.Monomial10import com.github.shwaka.kohomology.free.monoid.Signed11import com.github.shwaka.kohomology.free.monoid.Zero12import com.github.shwaka.kohomology.util.PrintConfig13import com.github.shwaka.kohomology.util.PrintType14import com.github.shwaka.kohomology.util.Sign15import io.kotest.assertions.throwables.shouldNotThrowAny16import io.kotest.assertions.throwables.shouldThrow17import io.kotest.core.NamedTag18import io.kotest.core.spec.style.FreeSpec19import io.kotest.inspectors.forAll20import io.kotest.matchers.booleans.shouldBeTrue21import io.kotest.matchers.collections.shouldBeUnique22import io.kotest.matchers.collections.shouldContainExactlyInAnyOrder23import io.kotest.matchers.shouldBe24import io.kotest.property.Arb25import io.kotest.property.arbitrary.negativeInts26import io.kotest.property.arbitrary.positiveInts27import io.kotest.property.checkAll28import io.kotest.property.exhaustive.exhaustive29val monomialTestTag = NamedTag("Monomial")30class MonomialTest : FreeSpec({31    tags(monomialTestTag)32    "indeterminate list with mixed degrees is not allowed" {33        checkAll(Arb.positiveInts(), Arb.negativeInts()) { positiveDegree, negativeDegree ->34            val indeterminateList = listOf(35                Indeterminate("x", positiveDegree),36                Indeterminate("y", negativeDegree)37            )38            shouldThrow<IllegalArgumentException> {39                FreeMonoid(indeterminateList)40            }41        }42    }43    "degree 0 is not allowed" {44        val indeterminateList = listOf(45            Indeterminate("x", 0)46        )47        shouldThrow<IllegalArgumentException> {48            FreeMonoid(indeterminateList)49        }50    }51    "positive degrees should be allowed" {52        val indeterminateList = listOf(53            Indeterminate("x", 1),54            Indeterminate("x", 2),55            Indeterminate("x", 3),56        )57        val monoid = FreeMonoid(indeterminateList)58        shouldNotThrowAny {59            monoid.listElements(0)60        }61    }62    "negative degrees should be allowed" {63        val indeterminateList = listOf(64            Indeterminate("x", -1),65            Indeterminate("x", -2),66            Indeterminate("x", -3),67        )68        val monoid = FreeMonoid(indeterminateList)69        shouldNotThrowAny {70            monoid.listElements(0)71        }72    }73    "two generators of even degrees" {74        val indeterminateList = listOf(75            Indeterminate("x", 2),76            Indeterminate("y", 2),77        )78        val monoid = FreeMonoid(indeterminateList)79        val gen = exhaustive(listOf(Pair(0, 1), Pair(1, 0), Pair(2, 2), Pair(3, 0), Pair(4, 3)))80        checkAll(gen) { (degree, size) ->81            monoid.listElements(degree).size shouldBe size82        }83    }84    "two generators of negative even degrees" {85        val indeterminateList = listOf(86            Indeterminate("x", -2),87            Indeterminate("y", -2),88        )89        val monoid = FreeMonoid(indeterminateList)90        val gen = exhaustive(listOf(Pair(0, 1), Pair(-1, 0), Pair(-2, 2), Pair(-3, 0), Pair(-4, 3)))91        checkAll(gen) { (degree, size) ->92            monoid.listElements(degree).size shouldBe size93        }94    }95    "two generators of odd degrees" {96        val indeterminateList = listOf(97            Indeterminate("x", 1),98            Indeterminate("y", 1),99        )100        val monoid = FreeMonoid(indeterminateList)101        val gen = exhaustive(listOf(Pair(0, 1), Pair(1, 2), Pair(2, 1), Pair(3, 0), Pair(4, 0)))102        checkAll(gen) { (degree, size) ->103            monoid.listElements(degree).size shouldBe size104        }105    }106    "two generators of negative odd degrees" {107        val indeterminateList = listOf(108            Indeterminate("x", -1),109            Indeterminate("y", -1),110        )111        val monoid = FreeMonoid(indeterminateList)112        val gen = exhaustive(listOf(Pair(0, 1), Pair(-1, 2), Pair(-2, 1), Pair(-3, 0), Pair(-4, 0)))113        checkAll(gen) { (degree, size) ->114            monoid.listElements(degree).size shouldBe size115        }116    }117    "polynomial algebra tensor exterior algebra" {118        val indeterminateList = listOf(119            Indeterminate("x", 1),120            Indeterminate("y", 2),121        )122        val monoid = FreeMonoid(indeterminateList)123        val gen = exhaustive(listOf(0, 1, 2, 3, 4))124        checkAll(gen) { degree ->125            monoid.listElements(degree).size shouldBe 1126        }127    }128    "listElements() should return the empty list for a negative degree if the generators are positive" {129        val indeterminateList = listOf(130            Indeterminate("x", 1),131            Indeterminate("y", 2),132        )133        val monoid = FreeMonoid(indeterminateList)134        checkAll(Arb.negativeInts()) { degree ->135            monoid.listElements(degree).isEmpty().shouldBeTrue()136        }137    }138    "listElements() should return the empty list for a positive degree if the generators are negative" {139        val indeterminateList = listOf(140            Indeterminate("x", -1),141            Indeterminate("y", -2),142        )143        val monoid = FreeMonoid(indeterminateList)144        checkAll(Arb.positiveInts()) { degree ->145            monoid.listElements(degree).isEmpty().shouldBeTrue()146        }147    }148    "listDegreesForAugmentedDegree() test" - {149        val degreeGroup = MultiDegreeGroup(150            listOf(151                DegreeIndeterminate("N", 1)152            )153        )154        val (n) = degreeGroup.generatorList155        degreeGroup.context.run {156            val indeterminateList = listOf(157                Indeterminate("a", 2 * n),158                Indeterminate("b", 2 * n),159                Indeterminate("x", 4 * n - 1),160                Indeterminate("y", 4 * n - 1),161                Indeterminate("z", 4 * n - 1),162                Indeterminate("w", 4 * n - 1),163            )164            val monoid = FreeMonoid(degreeGroup, indeterminateList)165            "listDegreesForAugmentedDegree() should return a list with distinct elements" {166                (0 until 20).forAll { degree ->167                    monoid.listDegreesForAugmentedDegree(degree).shouldBeUnique()168                }169            }170            "check results of listDegreesForAugmentedDegree() for specific degrees" {171                monoid.listDegreesForAugmentedDegree(2) shouldBe listOf(2 * n)172                monoid.listDegreesForAugmentedDegree(4) shouldBe listOf(4 * n)173                monoid.listDegreesForAugmentedDegree(6).shouldContainExactlyInAnyOrder(174                    listOf(8 * n - 2, 6 * n)175                )176                monoid.listDegreesForAugmentedDegree(12).shouldContainExactlyInAnyOrder(177                    listOf(16 * n - 4, 14 * n - 2, 12 * n)178                )179            }180        }181    }182    "multiplication test" {183        val indeterminateList = listOf(184            Indeterminate("x", 1),185            Indeterminate("y", 1),186            Indeterminate("z", 2),187        )188        val monoid = FreeMonoid(indeterminateList)189        val x = Monomial(indeterminateList, listOf(1, 0, 0))190        val y = Monomial(indeterminateList, listOf(0, 1, 0))191        val z = Monomial(indeterminateList, listOf(0, 0, 1))192        val xy = Monomial(indeterminateList, listOf(1, 1, 0))193        val xz = Monomial(indeterminateList, listOf(1, 0, 1))194        val yz = Monomial(indeterminateList, listOf(0, 1, 1))195        val xyz = Monomial(indeterminateList, listOf(1, 1, 1))196        val yzz = Monomial(indeterminateList, listOf(0, 1, 2))197        monoid.multiply(x, y) shouldBe Signed(xy, Sign.PLUS)198        monoid.multiply(xy, xz) shouldBe Zero199        monoid.multiply(xz, y) shouldBe Signed(xyz, Sign.PLUS)200        monoid.multiply(y, xz) shouldBe Signed(xyz, Sign.MINUS)201        monoid.multiply(z, yz) shouldBe Signed(yzz, Sign.PLUS)202    }203    "toString() and toTex() test" {204        val printConfigForTex = PrintConfig(PrintType.TEX)205        val indeterminateList = listOf(206            Indeterminate("x", 2),207            Indeterminate("y", 2),208        )209        val unit = Monomial(indeterminateList, listOf(0, 0))210        unit.toString() shouldBe "1"211        unit.toString(printConfigForTex) shouldBe "1"212        val xy2 = Monomial(indeterminateList, listOf(1, 2))213        xy2.toString() shouldBe "xy^2"214        xy2.toString(printConfigForTex) shouldBe "xy^{2}"215    }216    "toString() and toTex() test for indeterminate names with 'tex'" {217        val printConfigForTex = PrintConfig(PrintType.TEX)218        val indeterminateList = listOf(219            Indeterminate("x", "X", 2),220            Indeterminate("y", "Y", 2),221        )222        val x = Monomial(indeterminateList, listOf(1, 0))223        x.toString() shouldBe "x"224        x.toString(printConfigForTex) shouldBe "X"225        val xy = Monomial(indeterminateList, listOf(1, 1))226        xy.toString() shouldBe "xy"227        xy.toString(printConfigForTex) shouldBe "XY"228        val xy2 = Monomial(indeterminateList, listOf(1, 2))229        xy2.toString() shouldBe "xy^2"230        xy2.toString(printConfigForTex) shouldBe "XY^{2}"231    }232    "Indeterminate.convertDegree() test" {233        val degreeGroup = MultiDegreeGroup(234            listOf(235                DegreeIndeterminate("N", 1)236            )237        )238        val (n) = degreeGroup.generatorList239        degreeGroup.context.run {240            val morphism = MultiDegreeMorphism(degreeGroup, degreeGroup, listOf(2 * n))241            val x = Indeterminate("x", 1 + n)242            x.degree shouldBe (1 + n)243            x.convertDegree(morphism).degree shouldBe (1 + 2 * n)244        }245    }246    "FreeMonoidMorphismByDegreeChange test" - {247        val degreeGroup1 = MultiDegreeGroup(248            listOf(249                DegreeIndeterminate("K", 1)250            )251        )252        val (k) = degreeGroup1.generatorList253        val indeterminateList = degreeGroup1.context.run {254            listOf(255                Indeterminate("x", 2 * k),256                Indeterminate("y", 4 * k - 1),257            )258        }259        val monoid1 = FreeMonoid(degreeGroup1, indeterminateList)260        val degreeGroup2 = MultiDegreeGroup(261            listOf(262                DegreeIndeterminate("N", 1),263                DegreeIndeterminate("M", 1),264            )265        )266        val (n, m) = degreeGroup2.generatorList267        val degreeMorphism = degreeGroup2.context.run {268            MultiDegreeMorphism(degreeGroup1, degreeGroup2, listOf(n + m))269        }270        val monoidMorphism = FreeMonoidMorphismByDegreeChange(monoid1, degreeMorphism)271        val monoid2 = monoidMorphism.target272        "x should be mapped to a monomial of degree (2n + 2m)" {273            val x = monoid1.fromExponentList(intArrayOf(1, 0))274            monoidMorphism(x).degree shouldBe degreeGroup2.context.run { 2 * n + 2 * m }275        }276        "y should be mapped to a monomial of degree (4n + 4m - 1)" {277            val y = monoid1.fromExponentList(intArrayOf(0, 1))278            monoidMorphism(y).degree shouldBe degreeGroup2.context.run { 4 * n + 4 * m - 1 }279        }280        "(x^2 y) should be mapped to a monomial of degree (8n + 8m - 1)" {281            val x2y = monoid1.fromExponentList(intArrayOf(2, 1))282            monoidMorphism(x2y).degree shouldBe degreeGroup2.context.run { 8 * n + 8 * m - 1 }283        }284        "FreeMonoidMorphismByDegreeChange should preserve exponentList" {285            val exponentLists = listOf(286                intArrayOf(1, 0),287                intArrayOf(0, 1),288                intArrayOf(1, 1),289                intArrayOf(3, 2),290            )291            exponentLists.forAll { exponentList ->292                monoidMorphism(monoid1.fromExponentList(exponentList)) shouldBe293                    monoid2.fromExponentList(exponentList)294            }295        }296    }297})...ReloadConfigCommandTest.kt
Source:ReloadConfigCommandTest.kt  
1package builtin2import CustomMockPlugin3import be.seeseemelk.mockbukkit.MockBukkit4import be.seeseemelk.mockbukkit.command.ConsoleCommandSenderMock5import de.axelrindle.pocketknife.PocketCommand6import de.axelrindle.pocketknife.PocketConfig7import de.axelrindle.pocketknife.builtin.command.ReloadConfigCommand8import io.kotest.assertions.throwables.shouldThrow9import io.kotest.core.spec.style.StringSpec10import io.kotest.matchers.collections.*11import io.kotest.matchers.should12import io.kotest.matchers.shouldBe13import io.kotest.matchers.shouldNotBe14import io.kotest.matchers.types.beInstanceOf15import io.mockk.every16import io.mockk.mockk17import org.bukkit.command.CommandSender18import java.io.IOException19class ReloadConfigCommandTest : StringSpec({20    val mockedPlugin = MockBukkit.load(CustomMockPlugin::class.java)21    val pocketConfig = PocketConfig(mockedPlugin)22    val sender = ConsoleCommandSenderMock()23    val pluginCommand = mockedPlugin.getCommand("test")!!24    pocketConfig.register("config", mockedPlugin.getResource("/testConfig.yml"))25    pocketConfig.register("anotherConfig", mockedPlugin.getResource("/testConfig.yml"))26    "onPreReload & onReloadAll should be called once" {27        var preCalls = 028        var calls = 029        val command = object : ReloadConfigCommand<CustomMockPlugin>(mockedPlugin, pocketConfig) {30            override fun onEvent(event: Event, sender: CommandSender, info: String?, error: Throwable?) {31                super.onEvent(event, sender, info, error)32                when(event) {33                    Event.PRE_RELOAD -> preCalls++34                    Event.AFTER_RELOAD -> calls++35                    else -> org.junit.jupiter.api.fail("Something unexpected happened! ($event)", error)36                }37            }38        }39        PocketCommand.register(mockedPlugin, command)40        command.onCommand(sender, pluginCommand, pluginCommand.label, emptyArray()) shouldBe true41        preCalls shouldBe 142        calls shouldBe 143    }44    "onPreReload & onReload should be called twice" {45        var preCalls = 046        var calls = 047        val command = object : ReloadConfigCommand<CustomMockPlugin>(mockedPlugin, pocketConfig) {48            override fun onEvent(event: Event, sender: CommandSender, info: String?, error: Throwable?) {49                super.onEvent(event, sender, info, error)50                when(event) {51                    Event.PRE_RELOAD -> preCalls++52                    Event.SINGLE -> {}53                    Event.AFTER_RELOAD -> calls++54                    else -> org.junit.jupiter.api.fail("Something unexpected happened! ($event)", error)55                }56            }57        }58        PocketCommand.register(mockedPlugin, command)59        command.onCommand(sender, pluginCommand, pluginCommand.label, arrayOf("config")) shouldBe true60        command.onCommand(sender, pluginCommand, pluginCommand.label, arrayOf("anotherConfig")) shouldBe true61        preCalls shouldBe 262        calls shouldBe 263    }64    "onInvalid should be called for unknown config names while onPreReload gets also called" {65        var preCalled = false66        val command = object : ReloadConfigCommand<CustomMockPlugin>(mockedPlugin, pocketConfig) {67            override fun onEvent(event: Event, sender: CommandSender, info: String?, error: Throwable?) {68                super.onEvent(event, sender, info, error)69                when(event) {70                    Event.PRE_RELOAD -> preCalled = true71                    Event.INVALID -> {72                        info shouldBe "unknown"73                        error shouldNotBe null74                    }75                    else -> org.junit.jupiter.api.fail("Something unexpected happened! ($event)", error)76                }77            }78        }79        PocketCommand.register(mockedPlugin, command)80        command.onCommand(sender, pluginCommand, pluginCommand.label, arrayOf("unknown")) shouldBe true81        preCalled shouldBe true82    }83    "an exception in onPreReload does not lead to onInvalid being called when reloading s single config file" {84        val command = object : ReloadConfigCommand<CustomMockPlugin>(mockedPlugin, pocketConfig) {85            override fun onEvent(event: Event, sender: CommandSender, info: String?, error: Throwable?) {86                super.onEvent(event, sender, info, error)87                when(event) {88                    Event.PRE_RELOAD -> throw RuntimeException("imagine a severe error here")89                    else -> org.junit.jupiter.api.fail("Something unexpected happened! ($event)", error)90                }91            }92        }93        PocketCommand.register(mockedPlugin, command)94        val thrown = shouldThrow<RuntimeException> {95            command.onCommand(sender, pluginCommand, pluginCommand.label, arrayOf("config"))96        }97        thrown.message shouldBe "imagine a severe error here"98    }99    "an exception in onPreReload does not lead to onInvalid being called when reloading all config files" {100        val command = object : ReloadConfigCommand<CustomMockPlugin>(mockedPlugin, pocketConfig) {101            override fun onEvent(event: Event, sender: CommandSender, info: String?, error: Throwable?) {102                super.onEvent(event, sender, info, error)103                when(event) {104                    Event.PRE_RELOAD -> throw RuntimeException("imagine a severe error here")105                    else -> org.junit.jupiter.api.fail("Something unexpected happened!", error)106                }107            }108        }109        PocketCommand.register(mockedPlugin, command)110        val thrown = shouldThrow<RuntimeException> {111            command.onCommand(sender, pluginCommand, pluginCommand.label, emptyArray())112        }113        thrown.message shouldBe "imagine a severe error here"114    }115    "tabComplete should behave correctly" {116        val command = ReloadConfigCommand(mockedPlugin, pocketConfig)117        PocketCommand.register(mockedPlugin, command)118        command.tabComplete(sender, pluginCommand, emptyArray())119            .shouldHaveSize(2)120            .shouldBeUnique()121            .shouldContainAll("config", "anotherConfig")122        command.tabComplete(sender, pluginCommand, arrayOf("a")) shouldContainExactly arrayListOf("anotherConfig")123        command.tabComplete(sender, pluginCommand, arrayOf("C")) shouldContainExactly arrayListOf("anotherConfig")124        command.tabComplete(sender, pluginCommand, arrayOf("c")) shouldContainExactly arrayListOf("config")125        command.tabComplete(sender, pluginCommand, arrayOf("x")).shouldBeEmpty()126    }127    "reloading all configs must not result in an INVALID event" {128        val configMock = mockk<PocketConfig>()129        val command = object : ReloadConfigCommand<CustomMockPlugin>(mockedPlugin, configMock) {130            override fun onEvent(event: Event, sender: CommandSender, info: String?, error: Throwable?) {131                super.onEvent(event, sender, info, error)132                when(event) {133                    Event.INVALID -> io.kotest.assertions.fail("Event.INVALID must not occur!")134                    Event.ERROR -> {135                        info shouldBe null136                        error should beInstanceOf<IOException>()137                    }138                    else -> {} // ignore139                }140            }141        }142        PocketCommand.register(mockedPlugin, command)143        every { configMock.reloadAll() } throws IOException("imagine an I/O error here")144        command.onCommand(sender, pluginCommand, pluginCommand.label, emptyArray())145    }146    "an unexpected exception while reloading all configs leads to Event.AFTER_RELOAD not being called" {147    }148    "an unexpected exception causes the operation to be aborted" {149        var preCalls = 0150        val command = object : ReloadConfigCommand<CustomMockPlugin>(mockedPlugin, pocketConfig) {151            override fun onEvent(event: Event, sender: CommandSender, info: String?, error: Throwable?) {152                super.onEvent(event, sender, info, error)153                when(event) {154                    Event.PRE_RELOAD -> preCalls++155                    Event.SINGLE -> throw IOException("imagine the file could not be read")156                    Event.ERROR -> {157                        info shouldBe null158                        error should beInstanceOf<IOException>()159                    }160                    else -> org.junit.jupiter.api.fail("Something unexpected happened!", error)161                }162            }163        }164        PocketCommand.register(mockedPlugin, command)165        command.onCommand(sender, pluginCommand, pluginCommand.label, arrayOf("config", "anotherConfig")) shouldBe true166        preCalls shouldBe 1167    }168    "invalid usage returns true" {169        val command = object : ReloadConfigCommand<CustomMockPlugin>(mockedPlugin, pocketConfig) {170            override val canReloadSingle: Boolean = false171        }172        PocketCommand.register(mockedPlugin, command)173        command.onCommand(sender, pluginCommand, pluginCommand.label, arrayOf("config", "anotherConfig")) shouldBe false174        command.onCommand(sender, pluginCommand, pluginCommand.label, emptyArray()) shouldBe true175    }176    "default getUsage implementation respects the canReloadSingle setting" {177        var localCanReloadSingle = true178        val command = object : ReloadConfigCommand<CustomMockPlugin>(mockedPlugin, pocketConfig) {179            override val canReloadSingle: Boolean180                get() = localCanReloadSingle181        }182        PocketCommand.register(mockedPlugin, command)183        command.getUsage() shouldBe "/reload [config]"184        localCanReloadSingle = false185        command.getUsage() shouldBe "/reload"186    }187})...ArchetypeTest.kt
Source:ArchetypeTest.kt  
1package com.mineinabyss.geary.ecs.engine2import com.mineinabyss.geary.components.RelationComponent3import com.mineinabyss.geary.datatypes.GearyType4import com.mineinabyss.geary.datatypes.HOLDS_DATA5import com.mineinabyss.geary.datatypes.Relation6import com.mineinabyss.geary.datatypes.RelationValueId7import com.mineinabyss.geary.engine.archetypes.Archetype8import com.mineinabyss.geary.helpers.GearyTest9import com.mineinabyss.geary.helpers.componentId10import com.mineinabyss.geary.helpers.entity11import com.mineinabyss.geary.helpers.getArchetype12import io.kotest.matchers.collections.shouldBeUnique13import io.kotest.matchers.collections.shouldContainExactly14import io.kotest.matchers.maps.shouldContainKey15import io.kotest.matchers.maps.shouldNotContainKey16import io.kotest.matchers.shouldBe17import kotlinx.coroutines.awaitAll18import kotlinx.coroutines.launch19import kotlinx.coroutines.test.runTest20import org.junit.jupiter.api.Nested21import org.junit.jupiter.api.Test22import kotlin.time.measureTime23internal class ArchetypeTest : GearyTest() {24    //TODO bring this back when we switch to Koin DI25//    @Test26//    fun `ids assigned correctly`() {27//        Engine.rootArchetype.id shouldBe 028//        (Engine.rootArchetype + 1u).id shouldBe 129//        (Engine.rootArchetype + 1u + 2u).id shouldBe 230//        (Engine.rootArchetype + 1u).id shouldBe 131//    }32    @Nested33    inner class MovingBetweenArchetypes {34        @Test35        fun `empty type equals empty archetype`() {36            GearyType().getArchetype() shouldBe engine.rootArchetype37        }38        @Test39        fun `get type equals archetype adding`() {40            engine.rootArchetype + 1u + 2u + 3u - 1u + 1u shouldBe41                    GearyType(listOf(1u, 2u, 3u)).getArchetype()42        }43        @Test44        fun `reach same archetype from different starting positions`() {45            engine.rootArchetype + 1u + 2u + 3u shouldBe engine.rootArchetype + 3u + 2u + 1u46        }47    }48    @Test49    fun matchedRelations() {50        val arc = Archetype(51            engine,52            GearyType(53                listOf(54                    Relation.of(1uL or HOLDS_DATA, 10uL).id,55                    Relation.of(2uL or HOLDS_DATA, 10uL).id,56                )57            ), 058        )59        val relation = RelationValueId(10uL)60        val matched = arc.matchedRelationsFor(listOf(relation))61        matched shouldContainKey relation62        matched[relation]?.map { it.key }.shouldContainExactly(1uL or HOLDS_DATA, 2uL or HOLDS_DATA)63        val wrongRelation = RelationValueId(11uL)64        val matched2 = arc.matchedRelationsFor(listOf(wrongRelation))65        matched2 shouldNotContainKey wrongRelation66    }67    @Test68    fun `getComponents with relations`() {69        entity {70            set("Test")71            setRelation(String::class, 10)72            setRelation(Int::class, 15)73        }.getComponents() shouldContainExactly74                setOf("Test", RelationComponent(componentId<String>(), 10), RelationComponent(componentId<Int>(), 15))75    }76    @Nested77    inner class Async {78        @Test79        fun `add entities concurrently`() = runTest {80            clearEngine()81            val arc = engine.getArchetype(GearyType(ulongArrayOf(componentId<String>() or HOLDS_DATA)))82            concurrentOperation(10000) {83                arc.addEntityWithData(engine.newEntity().getRecord(), arrayOf("Test"))84            }.awaitAll()85            arc.ids.size shouldBe 1000086            arc.ids.shouldBeUnique()87        }88    }89    // The two tests below are pretty beefy and more like benchmarks so they're disabled by default90//    @Test91    fun `set and remove concurrency`() = runTest {92        println(measureTime {93            concurrentOperation(100) {94                val entity = entity()95                repeat(1000) { id ->96                    launch {97//                        entity.withLock {98                        entity.setRelation(id.toULong(), "String")99                        println("Locked for ${entity.id}: $id, size ${engine.archetypeCount}")100//                        }101                    }102                }103            }.awaitAll()104        })105//        entity.getComponents().shouldBeEmpty()106    }107    //    @Test108//    fun `mutliple locks`() {109//        val a = entity()110////        val b = entity()111//        concurrentOperation(10000) {112//            engine.withLock(setOf(a/*, b*/)) {113//                println("Locking")114//                delay(100)115//            }116//        }117//    }118    //    @Test119    fun `concurrent archetype creation`() = runTest {120        clearEngine()121        val iters = 10000122        println(measureTime {123            for (i in 0 until iters) {124//            concurrentOperation(iters) { i ->125                engine.getArchetype(GearyType((0uL..i.toULong()).toList()))126                println("Creating arc $i, total: ${engine.archetypeCount}")127//            }.awaitAll()128            }129        })130        engine.archetypeCount shouldBe iters + 1131    }132}...unique.kt
Source:unique.kt  
1package io.kotest.matchers.collections2import io.kotest.matchers.Matcher3import io.kotest.matchers.MatcherResult4import io.kotest.matchers.should5import io.kotest.matchers.shouldNot6fun <T> Iterable<T>.shouldBeUnique(): Iterable<T> {7   toList().shouldBeUnique()8   return this9}10fun <T> Array<T>.shouldBeUnique(): Array<T> {11   asList().shouldBeUnique()12   return this13}14fun <T> Collection<T>.shouldBeUnique(): Collection<T> {15   this should beUnique()16   return this17}18fun <T> Iterable<T>.shouldNotBeUnique(): Iterable<T> {19   toList().shouldNotBeUnique()20   return this21}22fun <T> Array<T>.shouldNotBeUnique(): Array<T> {23   asList().shouldNotBeUnique()24   return this25}26fun <T> Collection<T>.shouldNotBeUnique(): Collection<T> {27   this shouldNot beUnique()28   return this29}30fun <T> beUnique() = object : Matcher<Collection<T>> {31   override fun test(value: Collection<T>) = MatcherResult(32      value.toSet().size == value.size,33      { "Collection should be Unique" },34      {35         "Collection should contain at least one duplicate element"36      })37}...Array.shouldBeUnique
Using AI Code Generation
1array.shouldBeUnique()2array.shouldBeUnique()3array.shouldNotBeUnique()4array.shouldNotBeUnique()5array.shouldBeUniqueBy { it.id }6array.shouldBeUniqueBy { it.id }7array.shouldNotBeUniqueBy { it.id }8array.shouldNotBeUniqueBy { it.id }9array.shouldBeUniqueBy { it.id }10array.shouldBeUniqueBy { it.id }11array.shouldNotBeUniqueBy { it.id }12array.shouldNotBeUniqueBy { it.id }13array.shouldBeUniqueBy { it.id }14array.shouldBeUniqueBy { it.id }15array.shouldNotBeUniqueBy { it.id }16array.shouldNotBeUniqueBy { it.id }17array.shouldBeUniqueBy { it.id }Array.shouldBeUnique
Using AI Code Generation
1    import io.kotest.matchers.collections.unique.shouldBeUnique2    fun main() {3        val list = listOf(1, 2, 3, 4, 5, 6, 7, 8)4        list.shouldBeUnique()5    }6    import io.kotest.matchers.numerics.positive.shouldBePositive7    fun main() {8        num.shouldBePositive()9    }Array.shouldBeUnique
Using AI Code Generation
1fun main() { val list = listOf(1, 2, 3, 4, 5) list.shouldBeUnique() }2fun main() { val list = listOf(1, 2, 3, 4, 5) list.shouldBeUnique() }3fun main() { val list = listOf(1, 2, 3, 4, 5) list.shouldBeUnique() }4fun main() { val list = listOf(1, 2, 3, 4, 5) list.shouldBeUnique() }5fun main() { val list = listOf(1, 2, 3, 4, 5) list.shouldBeUnique() }6fun main() { val list = listOf(1, 2, 3, 4, 5) list.shouldBeUnique() }7fun main() { val list = listOf(1, 2, 3, 4, 5) list.shouldBeUnique() }8fun main() { val list = listOf(1, 2, 3, 4, 5) list.shouldBeUnique() }9fun main() { val list = listOf(1, 2, 3, 4, 5) list.shouldBeUnique() }10fun main() { val list = listOf(1, 2, 3, 4, 5) list.shouldBeUnique() }11fun main() { val list = listOfArray.shouldBeUnique
Using AI Code Generation
1import io.kotest.matchers.collections.shouldBeUnique2import io.kotest.matchers.collections.shouldBeSorted3import io.kotest.matchers.collections.shouldBeSortedDescending4import io.kotest.matchers.collections.shouldBeSortedWith5import io.kotest.matchers.collections.shouldContain6import io.kotest.matchers.collections.shouldContainAll7import io.kotest.matchers.collections.shouldContainAnyOf8import io.kotest.matchers.collections.shouldContainInOrder9import io.kotest.matchers.collections.shouldContainNoneOf10import io.kotest.matchers.collections.shouldContainOnly11import io.kotest.matchers.collections.shouldContainSame12import io.kotest.matchers.collections.shouldHaveAtArray.shouldBeUnique
Using AI Code Generation
1@DisplayName("Test for unique element in array")2@ValueSource(ints = [1, 2, 3, 4, 5])3fun `test for unique element in array`(value: Int) {4val array = arrayOf(1, 2, 3, 4, 5)5array.shouldBeUnique()6}7}Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
