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