From: David ‘Bombe’ Roden Date: Wed, 13 Nov 2013 21:15:37 +0000 (+0100) Subject: Add matchers for iterators. X-Git-Url: https://git.pterodactylus.net/?a=commitdiff_plain;h=c54ff0e71fd2e97202ab800b9d3b6e35478f819b;p=Sone.git Add matchers for iterators. --- diff --git a/src/test/java/net/pterodactylus/sone/Matchers.java b/src/test/java/net/pterodactylus/sone/Matchers.java index 4bf7aa5..c08ffb1 100644 --- a/src/test/java/net/pterodactylus/sone/Matchers.java +++ b/src/test/java/net/pterodactylus/sone/Matchers.java @@ -17,8 +17,15 @@ package net.pterodactylus.sone; +import static java.util.Arrays.asList; import static java.util.regex.Pattern.compile; +import java.util.Collection; +import java.util.Iterator; +import java.util.List; + +import com.google.common.base.Objects; +import com.google.common.collect.Lists; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; @@ -44,4 +51,65 @@ public class Matchers { }; } + public static Matcher> contains(T... items) { + return contains(asList(items)); + } + + public static Matcher> contains(final Collection items) { + return new TypeSafeMatcher>() { + @Override + protected boolean matchesSafely(Iterator iterator) { + for (T item : items) { + if (!iterator.hasNext()) { + return false; + } + T nextItem = iterator.next(); + if (!Objects.equal(item, nextItem)) { + return false; + } + } + if (iterator.hasNext()) { + return false; + } + return true; + } + + @Override + public void describeTo(Description description) { + description.appendText("contains ").appendValue(items); + } + }; + } + + public static Matcher> containsInAnyOrder(T... items) { + return containsInAnyOrder(asList(items)); + } + + public static Matcher> containsInAnyOrder(final Collection items) { + return new TypeSafeMatcher>() { + private final List remainingItems = Lists.newArrayList(items); + @Override + protected boolean matchesSafely(Iterator iterator) { + while (iterator.hasNext()) { + T item = iterator.next(); + if (remainingItems.isEmpty()) { + return false; + } + if (!remainingItems.remove(item)) { + return false; + } + } + if (!remainingItems.isEmpty()) { + return false; + } + return true; + } + + @Override + public void describeTo(Description description) { + description.appendText("contains ").appendValue(items); + } + }; + } + }