Merge branch 'release-0.9.7'
[Sone.git] / src / test / kotlin / net / pterodactylus / sone / test / OneByOneMatcher.kt
1 package net.pterodactylus.sone.test
2
3 import org.hamcrest.Description
4 import org.hamcrest.TypeSafeDiagnosingMatcher
5
6 class OneByOneMatcher<A> : TypeSafeDiagnosingMatcher<A>() {
7         private data class Matcher<in A, out V>(val expected: V, val actual: (A) -> V, val description: String)
8
9         private val matchers = mutableListOf<Matcher<A, *>>()
10
11         fun <V> expect(description: String, expected: V, actual: (A) -> V) {
12                 matchers += Matcher<A, V>(expected, actual, description)
13         }
14
15         override fun describeTo(description: Description) {
16                 matchers.forEachIndexed { index, matcher ->
17                         if (index > 0) {
18                                 description.appendText(", ")
19                         }
20                         description.appendText("${matcher.description} is ").appendValue(matcher.expected)
21                 }
22         }
23
24         override fun matchesSafely(item: A, mismatchDescription: Description) =
25                         matchers.all {
26                                 if (it.expected != it.actual(item)) {
27                                         mismatchDescription.appendText("${it.description} is ").appendValue(it.actual(item))
28                                         false
29                                 } else {
30                                         true
31                                 }
32                         }
33 }