🔀 Merge branch 'release/v82'
[Sone.git] / src / test / kotlin / net / pterodactylus / sone / test / Matchers.kt
index 7fc9428..1f479f6 100644 (file)
@@ -7,6 +7,24 @@ import net.pterodactylus.util.web.*
 import org.hamcrest.*
 import org.hamcrest.Matchers.*
 
+/**
+ * Returns a [hamcrest matcher][Matcher] constructed from the given predicate.
+ */
+fun <T> matches(description: String? = null, predicate: (T) -> Boolean) = object : TypeSafeDiagnosingMatcher<T>() {
+
+       override fun matchesSafely(item: T, mismatchDescription: Description) =
+                       predicate(item).onFalse {
+                               mismatchDescription.appendValue(item).appendText(" did not match predicate")
+                       }
+
+       override fun describeTo(description: Description) {
+               description.appendText("matches predicate ").appendValue(predicate)
+       }
+
+}.let { matcher ->
+       description?.let { describedAs(description, matcher) } ?: matcher
+}
+
 fun hasHeader(name: String, value: String) = object : TypeSafeDiagnosingMatcher<Header>() {
        override fun matchesSafely(item: Header, mismatchDescription: Description) =
                        compare(item.name, { it.equals(name, ignoreCase = true) }) { mismatchDescription.appendText("name is ").appendValue(it) }