X-Git-Url: https://git.pterodactylus.net/?p=Sone.git;a=blobdiff_plain;f=src%2Ftest%2Fkotlin%2Fnet%2Fpterodactylus%2Fsone%2Ftest%2FMatchers.kt;fp=src%2Ftest%2Fkotlin%2Fnet%2Fpterodactylus%2Fsone%2Ftest%2FMatchers.kt;h=d941c01e44716fc9a74aee3d1cd46a2b6651bba9;hp=644f192c6ad71c3111adf3bb351da2542ac5e2e1;hb=1ccf70bc878f6cdba8affdbe6d34c4a4f811e81a;hpb=d0a369a783e84292bbac793191a8cbf6827f395c diff --git a/src/test/kotlin/net/pterodactylus/sone/test/Matchers.kt b/src/test/kotlin/net/pterodactylus/sone/test/Matchers.kt index 644f192..d941c01 100644 --- a/src/test/kotlin/net/pterodactylus/sone/test/Matchers.kt +++ b/src/test/kotlin/net/pterodactylus/sone/test/Matchers.kt @@ -65,3 +65,58 @@ fun isIdentity(id: String, nickname: String, requestUri: String, contexts: Match .addAttribute("contexts", Identity::getContexts, contexts) .addAttribute("properties", Identity::getProperties, properties) +/** + * [TypeSafeDiagnosingMatcher] implementation that aims to cut down boilerplate on verifying the attributes + * of typical container objects. + */ +class AttributeMatcher(private val objectName: String) : TypeSafeDiagnosingMatcher() { + + private data class AttributeToMatch( + val name: String, + val getter: (T) -> V, + val matcher: Matcher + ) + + private val attributesToMatch = mutableListOf>() + + /** + * Adds an attribute to check for equality, returning `this`. + */ + fun addAttribute(name: String, expected: V, getter: (T) -> V): AttributeMatcher = apply { + attributesToMatch.add(AttributeToMatch(name, getter, describedAs("$name %0", equalTo(expected), expected))) + } + + /** + * Adds an attribute to check with the given [hamcrest matcher][Matcher]. + */ + fun addAttribute(name: String, getter: (T) -> V, matcher: Matcher) = apply { + attributesToMatch.add(AttributeToMatch(name, getter, matcher)) + } + + override fun describeTo(description: Description) { + attributesToMatch.forEachIndexed { index, attributeToMatch -> + if (index == 0) { + description.appendText("$objectName with ") + } else { + description.appendText(", ") + } + attributeToMatch.matcher.describeTo(description) + } + } + + override fun matchesSafely(item: T, mismatchDescription: Description): Boolean = + attributesToMatch.fold(true) { matches, attributeToMatch -> + if (!matches) { + false + } else { + if (!attributeToMatch.matcher.matches(attributeToMatch.getter(item))) { + mismatchDescription.appendText("but ${attributeToMatch.name} ") + attributeToMatch.matcher.describeMismatch(attributeToMatch.getter(item), mismatchDescription) + false + } else { + true + } + } + } + +}