Skip to content

Commit 679d14e

Browse files
author
Silvio D'Alessandro
committed
Add support for flat extracting elements from an iterable
1 parent 2cee219 commit 679d14e

File tree

3 files changed

+36
-1
lines changed

3 files changed

+36
-1
lines changed

CHANGELOG.md

+1
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.
88

99
### Added
1010
- Added `first` and `single` assertion for `Iterable`
11+
- Added `flatExtracting` assertion for `Iterable`
1112

1213
## [0.25] 2021-09-12
1314

assertk/src/commonMain/kotlin/assertk/assertions/iterable.kt

+13
Original file line numberDiff line numberDiff line change
@@ -181,6 +181,19 @@ fun <E, R1, R2, R3> Assert<Iterable<E>>.extracting(
181181
actual.map { Triple(f1(it), f2(it), f3(it)) }
182182
}
183183

184+
/**
185+
* Flat extracts a value from each item in the iterable, allowing you to assert on a flattened list of those values.
186+
*
187+
* ```
188+
* assertThat(people)
189+
* .flatExtracting(Person::relatives)
190+
* .contains("Sue", "Bob")
191+
* ```
192+
*/
193+
fun <E, R> Assert<Iterable<E>>.flatExtracting(f1: (E) -> Iterable<R>): Assert<List<R>> = transform { actual ->
194+
actual.flatMap(f1)
195+
}
196+
184197
/**
185198
* Asserts on each item in the iterable, passing if none of the items pass.
186199
* The given lambda will be run for each item.

assertk/src/commonTest/kotlin/test/assertk/assertions/IterableTest.kt

+22-1
Original file line numberDiff line numberDiff line change
@@ -460,6 +460,27 @@ class IterableTest {
460460
}
461461
//region extracting
462462

463+
//region flatExtracting
464+
@Test fun flat_extracting_function_passes() {
465+
val thing = Thing("one", 2, '3', listOf("A", "B"))
466+
assertThat(listOf(thing) as Iterable<Thing>).flatExtracting { it.four }.containsExactly("A", "B")
467+
}
468+
469+
@Test fun flat_extracting_function_fails() {
470+
val thing = Thing("one", 2, '3', listOf("A", "B"))
471+
val error = assertFails {
472+
assertThat(listOf(thing) as Iterable<Thing>).flatExtracting { it.four }.containsExactly("C", "D")
473+
}
474+
assertEquals(
475+
"""expected to contain exactly:<["C", "D"]> but was:<["A", "B"]>
476+
| at index:0 expected:<"C">
477+
| at index:0 unexpected:<"A">
478+
| at index:1 expected:<"D">
479+
| at index:1 unexpected:<"B"> ([Thing(one=one, two=2, three=3, four=[A, B])])""".trimMargin(), error.message
480+
)
481+
}
482+
//region flatExtracting
483+
463484
//region first
464485
@Test fun first_element_present_match_passes() {
465486
assertThat(listOf(1, 2)).first().isEqualTo(1)
@@ -507,5 +528,5 @@ class IterableTest {
507528
}
508529
//endregion
509530

510-
data class Thing(val one: String, val two: Int, val three: Char)
531+
data class Thing(val one: String, val two: Int, val three: Char, val four: List<String> = listOf())
511532
}

0 commit comments

Comments
 (0)