Skip to content

Commit

Permalink
withFirst(predicate) mapping
Browse files Browse the repository at this point in the history
  • Loading branch information
robfletcher committed May 11, 2020
1 parent 2660321 commit 8502303
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
14 changes: 14 additions & 0 deletions strikt-core/src/main/kotlin/strikt/assertions/Iterable.kt
Original file line number Diff line number Diff line change
Expand Up @@ -68,10 +68,24 @@ fun <T : Collection<E>, E> Builder<T>.single(): Builder<E> =
* iterable that matches [predicate].
*
* @see Iterable.first
* @throws strikt.internal.opentest4j.MappingFailed if no elements match [predicate].
*/
infix fun <T : Iterable<E>, E> Builder<T>.first(predicate: (E) -> Boolean): Builder<E> =
get("first matching element %s") { first(predicate) }

/**
* Runs a group of assertions on the first element in the subject iterable that
* matches [predicate].
*
* @see Iterable.first
* @throws strikt.internal.opentest4j.MappingFailed if no elements match [predicate].
*/
fun <T : Iterable<E>, E> Builder<T>.withFirst(
predicate: (E) -> Boolean,
block: Builder<E>.() -> Unit
): Builder<T> =
with("first matching element %s", { first(predicate) }, block)

/**
* Maps this assertion to an assertion over the last element in the subject
* iterable.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import dev.minutest.rootContext
import org.junit.jupiter.api.assertThrows
import org.opentest4j.MultipleFailuresError
import strikt.api.expectThat
import strikt.internal.opentest4j.MappingFailed

internal object IterableAssertions : JUnit5Minutests {

Expand Down Expand Up @@ -816,6 +817,34 @@ internal object IterableAssertions : JUnit5Minutests {
}
}

context("withFirst(predicate) function") {
listOf("catflap", "rubberplant", "marzipan")
.permute()
.forEach { subject ->
test("runs assertions on the first element of a ${subject.javaClass.simpleName} that matches the predicate") {
expectThat(subject).withFirst({ it.startsWith('r') }) {
isEqualTo("rubberplant")
}
}

test("fails if the nested assertions fail on the first element of a ${subject.javaClass.simpleName} that matches the predicate") {
assertThrows<MultipleFailuresError> {
expectThat(subject).withFirst({ it.startsWith('r') }) {
isEqualTo("catflap")
}
}
}

test("fails if nothing in a ${subject.javaClass.simpleName} matches the predicate") {
assertThrows<MappingFailed> {
expectThat(subject).withFirst({ it.startsWith('z') }) {
isEqualTo("catflap")
}
}
}
}
}

context("withLast function") {
listOf("catflap", "rubberplant", "marzipan")
.permute()
Expand Down

0 comments on commit 8502303

Please sign in to comment.