Skip to content

Commit

Permalink
shouldExist-more-info (#62)
Browse files Browse the repository at this point in the history
  • Loading branch information
AlexCue987 committed Apr 26, 2024
1 parent b612160 commit a47ad80
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,16 @@ infix fun <T> Iterable<T>.shouldExist(p: (T) -> Boolean) = toList().shouldExist(
infix fun <T> Array<T>.shouldExist(p: (T) -> Boolean) = asList().shouldExist(p)
infix fun <T> Collection<T>.shouldExist(p: (T) -> Boolean) = this should exist(p)
fun <T> exist(p: (T) -> Boolean) = object : Matcher<Collection<T>> {
override fun test(value: Collection<T>) = MatcherResult(
value.any { p(it) },
{ "Collection ${value.print().value} should contain an element that matches the predicate $p" },
{ "Collection ${value.print().value} should not contain an element that matches the predicate $p" }
)
override fun test(value: Collection<T>): MatcherResult {
val matchingElementsIndexes = value.mapIndexedNotNull { index, element ->
if(p(element)) index else null
}
return MatcherResult(
matchingElementsIndexes.isNotEmpty(),
{ "Collection ${value.print().value} should contain an element that matches the predicate $p" },
{ "Collection ${value.print().value} should not contain an element that matches the predicate $p, but elements with the following indexes matched: ${matchingElementsIndexes.print().value}" }
)
}
}

fun <T> Iterable<T>.shouldMatchInOrder(vararg assertions: (T) -> Unit) = toList().shouldMatchInOrder(assertions.toList())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import io.kotest.matchers.collections.containDuplicates
import io.kotest.matchers.collections.containNoNulls
import io.kotest.matchers.collections.containNull
import io.kotest.matchers.collections.containOnlyNulls
import io.kotest.matchers.collections.exist
import io.kotest.matchers.collections.existInOrder
import io.kotest.matchers.collections.haveElementAt
import io.kotest.matchers.collections.haveSize
Expand Down Expand Up @@ -490,6 +491,11 @@ class CollectionMatchersTest : WordSpec() {
val list = listOf(1, 2, 3)
list.shouldExist { it == 2 }
}
"give descriptive message when predicate should not match" {
shouldThrowAny {
listOf(1, 2, 3, 2) shouldNot exist { it == 2}
}.message shouldBe "Collection [1, 2, 3, 2] should not contain an element that matches the predicate (kotlin.Int) -> kotlin.Boolean, but elements with the following indexes matched: [1, 3]"
}
}

"shouldHaveAtLeastSize" should {
Expand Down

0 comments on commit a47ad80

Please sign in to comment.