2 * Sone - Matchers.java - Copyright © 2013 David Roden
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 package net.pterodactylus.sone;
20 import static java.util.Arrays.asList;
21 import static java.util.regex.Pattern.compile;
23 import java.util.Collection;
24 import java.util.Iterator;
25 import java.util.List;
27 import com.google.common.base.Objects;
28 import com.google.common.collect.Lists;
29 import org.hamcrest.Description;
30 import org.hamcrest.Matcher;
31 import org.hamcrest.TypeSafeMatcher;
34 * Matchers used throughout the tests.
36 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
38 public class Matchers {
40 public static Matcher<String> matches(final String regex) {
41 return new TypeSafeMatcher<String>() {
43 protected boolean matchesSafely(String item) {
44 return compile(regex).matcher(item).find();
48 public void describeTo(Description description) {
49 description.appendText("matches: ").appendValue(regex);
54 public static <T> Matcher<Iterator<T>> contains(T... items) {
55 return contains(asList(items));
58 public static <T> Matcher<Iterator<T>> contains(final Collection<T> items) {
59 return new TypeSafeMatcher<Iterator<T>>() {
61 protected boolean matchesSafely(Iterator<T> iterator) {
62 for (T item : items) {
63 if (!iterator.hasNext()) {
66 T nextItem = iterator.next();
67 if (!Objects.equal(item, nextItem)) {
71 if (iterator.hasNext()) {
78 public void describeTo(Description description) {
79 description.appendText("contains ").appendValue(items);
84 public static <T> Matcher<Iterator<T>> containsInAnyOrder(T... items) {
85 return containsInAnyOrder(asList(items));
88 public static <T> Matcher<Iterator<T>> containsInAnyOrder(final Collection<T> items) {
89 return new TypeSafeMatcher<Iterator<T>>() {
90 private final List<T> remainingItems = Lists.newArrayList(items);
92 protected boolean matchesSafely(Iterator<T> iterator) {
93 while (iterator.hasNext()) {
94 T item = iterator.next();
95 if (remainingItems.isEmpty()) {
98 if (!remainingItems.remove(item)) {
102 if (!remainingItems.isEmpty()) {
109 public void describeTo(Description description) {
110 description.appendText("contains ").appendValue(items);