🚧 Add matcher for empty maps
[Sone.git] / src / test / kotlin / net / pterodactylus / sone / test / Matchers.kt
1 package net.pterodactylus.sone.test
2
3 import net.pterodactylus.sone.utils.*
4 import net.pterodactylus.util.web.*
5 import org.hamcrest.*
6 import org.hamcrest.Matchers.*
7
8 fun hasHeader(name: String, value: String) = object : TypeSafeDiagnosingMatcher<Header>() {
9         override fun matchesSafely(item: Header, mismatchDescription: Description) =
10                         compare(item.name, { it.equals(name, ignoreCase = true) }) { mismatchDescription.appendText("name is ").appendValue(it) }
11                                         ?: compare(item.hasValue(value), { it }) { mismatchDescription.appendText("does not have value ").appendValue(value) }
12                                         ?: true
13
14         override fun describeTo(description: Description) {
15                 description.appendText("name is ").appendValue(name)
16                                 .appendText(", value is ").appendValue(value)
17         }
18 }
19
20 fun <T : Any> compare(value: T, comparison: (T) -> Boolean, onError: (T) -> Unit) =
21                 false.takeUnless { comparison(value) }
22                                 ?.also { onError(value) }
23
24 fun <K, V> isEmptyMap() = object : TypeSafeDiagnosingMatcher<Map<K, V>>() {
25         override fun describeTo(description: Description) {
26                 description.appendText("empty map")
27         }
28
29         override fun matchesSafely(item: Map<K, V>, mismatchDescription: Description) =
30                         item.isEmpty().onFalse {
31                                 mismatchDescription.appendText("was ").appendValue(item)
32                         }
33 }
34