libhamcrest-java-1.3/0000755000175000017500000000000012131006721014112 5ustar ebourgebourglibhamcrest-java-1.3/build.xml0000644000175000017500000004636211774371401015762 0ustar ebourgebourg libhamcrest-java-1.3/hamcrest-integration/0000755000175000017500000000000011753011773020255 5ustar ebourgebourglibhamcrest-java-1.3/hamcrest-integration/src/0000755000175000017500000000000011753011773021044 5ustar ebourgebourglibhamcrest-java-1.3/hamcrest-integration/src/main/0000755000175000017500000000000012131006721021754 5ustar ebourgebourglibhamcrest-java-1.3/hamcrest-integration/src/main/java/0000755000175000017500000000000011753011773022711 5ustar ebourgebourglibhamcrest-java-1.3/hamcrest-integration/src/main/java/org/0000755000175000017500000000000011753011773023500 5ustar ebourgebourglibhamcrest-java-1.3/hamcrest-integration/src/main/java/org/hamcrest/0000755000175000017500000000000012131006721025272 5ustar ebourgebourglibhamcrest-java-1.3/hamcrest-integration/src/main/java/org/hamcrest/JavaLangMatcherAssert.java0000644000175000017500000000064411753011773032326 0ustar ebourgebourgpackage org.hamcrest; /** * Integration method for use with Java's assert keyword. * Example: *
 * assert that("Foo", startsWith("f"));
 * 
* * @author Neil Dunn */ public class JavaLangMatcherAssert { private JavaLangMatcherAssert() {}; public static boolean that(T argument, Matcher matcher) { return matcher.matches(argument); } } libhamcrest-java-1.3/hamcrest-integration/src/main/java/org/hamcrest/EasyMock2Matchers.java0000644000175000017500000000051111753011773031432 0ustar ebourgebourgpackage org.hamcrest; import org.hamcrest.integration.EasyMock2Adapter; import org.hamcrest.core.IsEqual; /** * * @author Joe Walnes */ public class EasyMock2Matchers { public static String equalTo(String string) { EasyMock2Adapter.adapt(IsEqual.equalTo(string)); return null; } } libhamcrest-java-1.3/hamcrest-integration/src/main/java/org/hamcrest/integration/0000755000175000017500000000000012131006721027615 5ustar ebourgebourg././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibhamcrest-java-1.3/hamcrest-integration/src/main/java/org/hamcrest/integration/EasyMock2Adapter.javalibhamcrest-java-1.3/hamcrest-integration/src/main/java/org/hamcrest/integration/EasyMock2Adapter.ja0000644000175000017500000000242711753011773033250 0ustar ebourgebourgpackage org.hamcrest.integration; import org.easymock.IArgumentMatcher; import org.easymock.EasyMock; import org.hamcrest.Matcher; import org.hamcrest.StringDescription; /** * An adapter allowing a Hamcrest {@link org.hamcrest.Matcher} * to act as an EasyMock {@link org.easymock.IArgumentMatcher}. * * @author Joe Walnes */ public class EasyMock2Adapter implements IArgumentMatcher { /** * Convenience factory method that will adapt a * Hamcrest {@link org.hamcrest.Matcher} to act as an * EasyMock {@link org.easymock.IArgumentMatcher} and * report it to EasyMock so it can be kept track of. */ public static IArgumentMatcher adapt(Matcher matcher) { EasyMock2Adapter easyMock2Matcher = new EasyMock2Adapter(matcher); EasyMock.reportMatcher(easyMock2Matcher); return easyMock2Matcher; } private final Matcher hamcrestMatcher; public EasyMock2Adapter(Matcher matcher) { this.hamcrestMatcher = matcher; } @Override public boolean matches(Object argument) { return hamcrestMatcher.matches(argument); } @Override public void appendTo(StringBuffer buffer) { hamcrestMatcher.describeTo(new StringDescription(buffer)); } } libhamcrest-java-1.3/hamcrest-integration/src/main/java/org/hamcrest/integration/JMock1Adapter.java0000644000175000017500000000221311753011773033057 0ustar ebourgebourgpackage org.hamcrest.integration; import org.jmock.core.Constraint; import org.hamcrest.Matcher; import org.hamcrest.StringDescription; /** * An adapter allowing a Hamcrest {@link org.hamcrest.Matcher} * to act as an jMock1 {@link org.jmock.core.Constraint}. * Note, this is not necessary for jMock2 as it supports Hamcrest * out of the box. * * @author Joe Walnes */ public class JMock1Adapter implements Constraint { /** * Convenience factory method that will adapt a * Hamcrest {@link org.hamcrest.Matcher} to act as an * jMock {@link org.jmock.core.Constraint}. */ public static Constraint adapt(Matcher matcher) { return new JMock1Adapter(matcher); } private final Matcher hamcrestMatcher; public JMock1Adapter(Matcher matcher) { this.hamcrestMatcher = matcher; } @Override public boolean eval(Object o) { return hamcrestMatcher.matches(o); } @Override public StringBuffer describeTo(StringBuffer buffer) { hamcrestMatcher.describeTo(new StringDescription(buffer)); return buffer; } } libhamcrest-java-1.3/hamcrest-integration/src/main/java/org/hamcrest/JMock1Matchers.java0000644000175000017500000000046111753011773030725 0ustar ebourgebourgpackage org.hamcrest; import org.hamcrest.integration.JMock1Adapter; import org.hamcrest.core.IsEqual; import org.jmock.core.Constraint; public class JMock1Matchers { public static Constraint equalTo(String string) { return JMock1Adapter.adapt(IsEqual.equalTo(string)); } } libhamcrest-java-1.3/hamcrest-integration/src/main/hamcrest-integration.iml0000644000175000017500000000107211753011773026622 0ustar ebourgebourg libhamcrest-java-1.3/hamcrest-parent-1.3.pom0000644000175000017500000000366411776633002020250 0ustar ebourgebourg 4.0.0 org.hamcrest hamcrest-parent 1.3 pom Hamcrest Maven Parent https://github.com/hamcrest/JavaHamcrest General parent POM for all hamcrest libraries. New BSD License http://www.opensource.org/licenses/bsd-license.php repo https://github.com/hamcrest/JavaHamcrest scm:git:git@github.com:hamcrest/JavaHamcrest.git joe.walnes Joe Walnes Developer nat.pryce Nat Pryce Developer smgfreeman Steve Freeman Developer neildunn Neil Dunn Developer scarytom Tom Denley Developer hamcrest-core hamcrest-generator hamcrest-library hamcrest-integration libhamcrest-java-1.3/hamcrest-all-1.3.pom0000644000175000017500000000121211776633002017512 0ustar ebourgebourg 4.0.0 org.hamcrest hamcrest-parent 1.3 hamcrest-all jar Hamcrest All A self-contained hamcrest jar containing all of the sub-modules in a single artifact. libhamcrest-java-1.3/hamcrest-core/0000755000175000017500000000000011753011773016662 5ustar ebourgebourglibhamcrest-java-1.3/hamcrest-core/src/0000755000175000017500000000000011753011773017451 5ustar ebourgebourglibhamcrest-java-1.3/hamcrest-core/src/main/0000755000175000017500000000000012131006721020361 5ustar ebourgebourglibhamcrest-java-1.3/hamcrest-core/src/main/hamcrest-core.iml0000644000175000017500000000066611753011773023644 0ustar ebourgebourg libhamcrest-java-1.3/hamcrest-core/src/main/java/0000755000175000017500000000000011753011773021316 5ustar ebourgebourglibhamcrest-java-1.3/hamcrest-core/src/main/java/org/0000755000175000017500000000000011753011773022105 5ustar ebourgebourglibhamcrest-java-1.3/hamcrest-core/src/main/java/org/hamcrest/0000755000175000017500000000000012131006721023677 5ustar ebourgebourglibhamcrest-java-1.3/hamcrest-core/src/main/java/org/hamcrest/Condition.java0000644000175000017500000000455311755251100026503 0ustar ebourgebourgpackage org.hamcrest; /** * A Condition implements part of a multi-step match. We sometimes need to write matchers * that have a sequence of steps, where each step depends on the result of the previous * step and we can stop processing as soon as a step fails. These classes provide * infrastructure for writing such a sequence. * * Based on https://github.com/npryce/maybe-java * @author Steve Freeman 2012 http://www.hamcrest.com */ public abstract class Condition { public static final NotMatched NOT_MATCHED = new NotMatched(); public interface Step { Condition apply(I value, Description mismatch); } private Condition() { } public abstract boolean matching(Matcher match, String message); public abstract Condition and(Step mapping); public final boolean matching(Matcher match) { return matching(match, ""); } public final Condition then(Step mapping) { return and(mapping); } @SuppressWarnings("unchecked") public static Condition notMatched() { return (Condition) NOT_MATCHED; } public static Condition matched(final T theValue, final Description mismatch) { return new Matched(theValue, mismatch); } private static final class Matched extends Condition { private final T theValue; private final Description mismatch; private Matched(T theValue, Description mismatch) { this.theValue = theValue; this.mismatch = mismatch; } @Override public boolean matching(Matcher matcher, String message) { if (matcher.matches(theValue)) { return true; } mismatch.appendText(message); matcher.describeMismatch(theValue, mismatch); return false; } @Override public Condition and(Step next) { return next.apply(theValue, mismatch); } } private static final class NotMatched extends Condition { @Override public boolean matching(Matcher match, String message) { return false; } @Override public Condition and(Step mapping) { return notMatched(); } } } libhamcrest-java-1.3/hamcrest-core/src/main/java/org/hamcrest/Matcher.java0000644000175000017500000000450011755733625026151 0ustar ebourgebourg/* Copyright (c) 2000-2006 hamcrest.org */ package org.hamcrest; /** * A matcher over acceptable values. * A matcher is able to describe itself to give feedback when it fails. *

* Matcher implementations should NOT directly implement this interface. * Instead, extend the {@link BaseMatcher} abstract class, * which will ensure that the Matcher API can grow to support * new features and remain compatible with all Matcher implementations. *

* For easy access to common Matcher implementations, use the static factory * methods in {@link CoreMatchers}. *

* N.B. Well designed matchers should be immutable. * * @see CoreMatchers * @see BaseMatcher */ public interface Matcher extends SelfDescribing { /** * Evaluates the matcher for argument item. *

* This method matches against Object, instead of the generic type T. This is * because the caller of the Matcher does not know at runtime what the type is * (because of type erasure with Java generics). It is down to the implementations * to check the correct type. * * @param item the object against which the matcher is evaluated. * @return true if item matches, otherwise false. * * @see BaseMatcher */ boolean matches(Object item); /** * Generate a description of why the matcher has not accepted the item. * The description will be part of a larger description of why a matching * failed, so it should be concise. * This method assumes that matches(item) is false, but * will not check this. * * @param item The item that the Matcher has rejected. * @param mismatchDescription * The description to be built or appended to. */ void describeMismatch(Object item, Description mismatchDescription); /** * This method simply acts a friendly reminder not to implement Matcher directly and * instead extend BaseMatcher. It's easy to ignore JavaDoc, but a bit harder to ignore * compile errors . * * @see Matcher for reasons why. * @see BaseMatcher * @deprecated to make */ @Deprecated void _dont_implement_Matcher___instead_extend_BaseMatcher_(); } libhamcrest-java-1.3/hamcrest-core/src/main/java/org/hamcrest/CustomMatcher.java0000644000175000017500000000224711753011773027341 0ustar ebourgebourgpackage org.hamcrest; /** * Utility class for writing one off matchers. * For example: *

 * Matcher<String> aNonEmptyString = new CustomMatcher<String>("a non empty string") {
 *   public boolean matches(Object object) {
 *     return ((object instanceof String) && !((String) object).isEmpty();
 *   }
 * };
 * 
*

* This class is designed for scenarios where an anonymous inner class * matcher makes sense. It should not be used by API designers implementing * matchers. * * @author Neil Dunn * @see CustomTypeSafeMatcher for a type safe variant of this class that you probably * want to use. * @param The type of object being matched. */ public abstract class CustomMatcher extends BaseMatcher { private final String fixedDescription; public CustomMatcher(String description) { if (description == null) { throw new IllegalArgumentException("Description should be non null!"); } this.fixedDescription = description; } @Override public final void describeTo(Description description) { description.appendText(fixedDescription); } } libhamcrest-java-1.3/hamcrest-core/src/main/java/org/hamcrest/TypeSafeDiagnosingMatcher.java0000644000175000017500000000460511753011773031612 0ustar ebourgebourgpackage org.hamcrest; import org.hamcrest.internal.ReflectiveTypeFinder; /** * Convenient base class for Matchers that require a non-null value of a specific type * and that will report why the received value has been rejected. * This implements the null check, checks the type and then casts. * To use, implement

matchesSafely()
. * * @param * @author Neil Dunn * @author Nat Pryce * @author Steve Freeman */ public abstract class TypeSafeDiagnosingMatcher extends BaseMatcher { private static final ReflectiveTypeFinder TYPE_FINDER = new ReflectiveTypeFinder("matchesSafely", 2, 0); private final Class expectedType; /** * Subclasses should implement this. The item will already have been checked * for the specific type and will never be null. */ protected abstract boolean matchesSafely(T item, Description mismatchDescription); /** * Use this constructor if the subclass that implements matchesSafely * is not the class that binds <T> to a type. * @param expectedType The expectedType of the actual value. */ protected TypeSafeDiagnosingMatcher(Class expectedType) { this.expectedType = expectedType; } /** * Use this constructor if the subclass that implements matchesSafely * is not the class that binds <T> to a type. * @param typeFinder A type finder to extract the type */ protected TypeSafeDiagnosingMatcher(ReflectiveTypeFinder typeFinder) { this.expectedType = typeFinder.findExpectedType(getClass()); } /** * The default constructor for simple sub types */ protected TypeSafeDiagnosingMatcher() { this(TYPE_FINDER); } @Override @SuppressWarnings("unchecked") public final boolean matches(Object item) { return item != null && expectedType.isInstance(item) && matchesSafely((T) item, new Description.NullDescription()); } @SuppressWarnings("unchecked") @Override public final void describeMismatch(Object item, Description mismatchDescription) { if (item == null || !expectedType.isInstance(item)) { super.describeMismatch(item, mismatchDescription); } else { matchesSafely((T) item, mismatchDescription); } } } libhamcrest-java-1.3/hamcrest-core/src/main/java/org/hamcrest/FeatureMatcher.java0000644000175000017500000000360711753011773027463 0ustar ebourgebourgpackage org.hamcrest; import org.hamcrest.internal.ReflectiveTypeFinder; /** * Supporting class for matching a feature of an object. Implement featureValueOf() * in a subclass to pull out the feature to be matched against. * * @param The type of the object to be matched * @param The type of the feature to be matched */ public abstract class FeatureMatcher extends TypeSafeDiagnosingMatcher { private static final ReflectiveTypeFinder TYPE_FINDER = new ReflectiveTypeFinder("featureValueOf", 1, 0); private final Matcher subMatcher; private final String featureDescription; private final String featureName; /** * Constructor * @param subMatcher The matcher to apply to the feature * @param featureDescription Descriptive text to use in describeTo * @param featureName Identifying text for mismatch message */ public FeatureMatcher(Matcher subMatcher, String featureDescription, String featureName) { super(TYPE_FINDER); this.subMatcher = subMatcher; this.featureDescription = featureDescription; this.featureName = featureName; } /** * Implement this to extract the interesting feature. * @param actual the target object * @return the feature to be matched */ protected abstract U featureValueOf(T actual); @Override protected boolean matchesSafely(T actual, Description mismatch) { final U featureValue = featureValueOf(actual); if (!subMatcher.matches(featureValue)) { mismatch.appendText(featureName).appendText(" "); subMatcher.describeMismatch(featureValue, mismatch); return false; } return true; }; @Override public final void describeTo(Description description) { description.appendText(featureDescription).appendText(" ") .appendDescriptionOf(subMatcher); } } libhamcrest-java-1.3/hamcrest-core/src/main/java/org/hamcrest/Description.java0000644000175000017500000000464511753011773027052 0ustar ebourgebourgpackage org.hamcrest; /** * A description of a Matcher. A Matcher will describe itself to a description * which can later be used for reporting. * * @see Matcher#describeTo(Description) */ public interface Description { /** * A description that consumes input but does nothing. */ static final Description NONE = new NullDescription(); /** * Appends some plain text to the description. */ Description appendText(String text); /** * Appends the description of a {@link SelfDescribing} value to this description. */ Description appendDescriptionOf(SelfDescribing value); /** * Appends an arbitary value to the description. */ Description appendValue(Object value); /** * Appends a list of values to the description. */ Description appendValueList(String start, String separator, String end, T... values); /** * Appends a list of values to the description. */ Description appendValueList(String start, String separator, String end, Iterable values); /** * Appends a list of {@link org.hamcrest.SelfDescribing} objects * to the description. */ Description appendList(String start, String separator, String end, Iterable values); public static final class NullDescription implements Description { @Override public Description appendDescriptionOf(SelfDescribing value) { return this; } @Override public Description appendList(String start, String separator, String end, Iterable values) { return this; } @Override public Description appendText(String text) { return this; } @Override public Description appendValue(Object value) { return this; } @Override public Description appendValueList(String start, String separator, String end, T... values) { return this; } @Override public Description appendValueList(String start, String separator, String end, Iterable values) { return this; } @Override public String toString() { return ""; } } } libhamcrest-java-1.3/hamcrest-core/src/main/java/org/hamcrest/TypeSafeMatcher.java0000644000175000017500000000570611753011773027612 0ustar ebourgebourgpackage org.hamcrest; import org.hamcrest.internal.ReflectiveTypeFinder; /** * Convenient base class for Matchers that require a non-null value of a specific type. * This simply implements the null check, checks the type and then casts. * * @author Joe Walnes * @author Steve Freeman * @author Nat Pryce */ public abstract class TypeSafeMatcher extends BaseMatcher { private static final ReflectiveTypeFinder TYPE_FINDER = new ReflectiveTypeFinder("matchesSafely", 1, 0); final private Class expectedType; /** * The default constructor for simple sub types */ protected TypeSafeMatcher() { this(TYPE_FINDER); } /** * Use this constructor if the subclass that implements matchesSafely * is not the class that binds <T> to a type. * @param expectedType The expectedType of the actual value. */ protected TypeSafeMatcher(Class expectedType) { this.expectedType = expectedType; } /** * Use this constructor if the subclass that implements matchesSafely * is not the class that binds <T> to a type. * @param typeFinder A type finder to extract the type */ protected TypeSafeMatcher(ReflectiveTypeFinder typeFinder) { this.expectedType = typeFinder.findExpectedType(getClass()); } /** * Subclasses should implement this. The item will already have been checked for * the specific type and will never be null. */ protected abstract boolean matchesSafely(T item); /** * Subclasses should override this. The item will already have been checked for * the specific type and will never be null. */ protected void describeMismatchSafely(T item, Description mismatchDescription) { super.describeMismatch(item, mismatchDescription); } /** * Methods made final to prevent accidental override. * If you need to override this, there's no point on extending TypeSafeMatcher. * Instead, extend the {@link BaseMatcher}. */ @Override @SuppressWarnings({"unchecked"}) public final boolean matches(Object item) { return item != null && expectedType.isInstance(item) && matchesSafely((T) item); } @SuppressWarnings("unchecked") @Override final public void describeMismatch(Object item, Description description) { if (item == null) { super.describeMismatch(item, description); } else if (! expectedType.isInstance(item)) { description.appendText("was a ") .appendText(item.getClass().getName()) .appendText(" (") .appendValue(item) .appendText(")"); } else { describeMismatchSafely((T)item, description); } } } libhamcrest-java-1.3/hamcrest-core/src/main/java/org/hamcrest/internal/0000755000175000017500000000000012131006721025513 5ustar ebourgebourglibhamcrest-java-1.3/hamcrest-core/src/main/java/org/hamcrest/internal/ReflectiveTypeFinder.java0000644000175000017500000000616011753011773032457 0ustar ebourgebourg/** * The TypeSafe classes, and their descendants, need a mechanism to find out what type has been used as a parameter * for the concrete matcher. Unfortunately, this type is lost during type erasure so we need to use reflection * to get it back, by picking out the type of a known parameter to a known method. * The catch is that, with bridging methods, this type is only visible in the class that actually implements * the expected method, so the ReflectiveTypeFinder needs to be applied to that class or a subtype. * * For example, the abstract TypeSafeDiagnosingMatcher<T> defines an abstract method *
protected abstract boolean matchesSafely(T item, Description mismatchDescription);
* By default it uses new ReflectiveTypeFinder("matchesSafely", 2, 0); to find the * parameterised type. If we create a TypeSafeDiagnosingMatcher<String>, the type * finder will return String.class. * * A FeatureMatcher is an abstract subclass of TypeSafeDiagnosingMatcher. * Although it has a templated implementation of matchesSafely(<T>, Decription);, the * actualy run-time signature of this is matchesSafely(Object, Description);. Instead, * we must find the type by reflecting on the concrete implementation of *
protected abstract U featureValueOf(T actual);
* a method which is declared in FeatureMatcher. * * In short, use this to extract a type from a method in the leaf class of a templated class hierarchy. * * @author Steve Freeman * @author Nat Pryce */ package org.hamcrest.internal; import java.lang.reflect.Method; public class ReflectiveTypeFinder { private final String methodName; private final int expectedNumberOfParameters; private final int typedParameter; public ReflectiveTypeFinder(String methodName, int expectedNumberOfParameters, int typedParameter) { this.methodName = methodName; this.expectedNumberOfParameters = expectedNumberOfParameters; this.typedParameter = typedParameter; } public Class findExpectedType(Class fromClass) { for (Class c = fromClass; c != Object.class; c = c.getSuperclass()) { for (Method method : c.getDeclaredMethods()) { if (canObtainExpectedTypeFrom(method)) { return expectedTypeFrom(method); } } } throw new Error("Cannot determine correct type for " + methodName + "() method."); } /** * @param method The method to examine. * @return true if this method references the relevant type */ protected boolean canObtainExpectedTypeFrom(Method method) { return method.getName().equals(methodName) && method.getParameterTypes().length == expectedNumberOfParameters && !method.isSynthetic(); } /** * @param method The method from which to extract * @return The type we're looking for */ protected Class expectedTypeFrom(Method method) { return method.getParameterTypes()[typedParameter]; } }././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootlibhamcrest-java-1.3/hamcrest-core/src/main/java/org/hamcrest/internal/SelfDescribingValueIterator.javalibhamcrest-java-1.3/hamcrest-core/src/main/java/org/hamcrest/internal/SelfDescribingValueIterator.j0000644000175000017500000000115311753011773033274 0ustar ebourgebourgpackage org.hamcrest.internal; import java.util.Iterator; import org.hamcrest.SelfDescribing; public class SelfDescribingValueIterator implements Iterator { private Iterator values; public SelfDescribingValueIterator(Iterator values) { this.values = values; } @Override public boolean hasNext() { return values.hasNext(); } @Override public SelfDescribing next() { return new SelfDescribingValue(values.next()); } @Override public void remove() { values.remove(); } } libhamcrest-java-1.3/hamcrest-core/src/main/java/org/hamcrest/internal/ArrayIterator.java0000644000175000017500000000142611753011773031165 0ustar ebourgebourgpackage org.hamcrest.internal; import java.lang.reflect.Array; import java.util.Iterator; public class ArrayIterator implements Iterator { private final Object array; private int currentIndex = 0; public ArrayIterator(Object array) { if (!array.getClass().isArray()) { throw new IllegalArgumentException("not an array"); } this.array = array; } @Override public boolean hasNext() { return currentIndex < Array.getLength(array); } @Override public Object next() { return Array.get(array, currentIndex++); } @Override public void remove() { throw new UnsupportedOperationException("cannot remove items from an array"); } } libhamcrest-java-1.3/hamcrest-core/src/main/java/org/hamcrest/internal/SelfDescribingValue.java0000644000175000017500000000062211753011773032252 0ustar ebourgebourgpackage org.hamcrest.internal; import org.hamcrest.Description; import org.hamcrest.SelfDescribing; public class SelfDescribingValue implements SelfDescribing { private T value; public SelfDescribingValue(T value) { this.value = value; } @Override public void describeTo(Description description) { description.appendValue(value); } } libhamcrest-java-1.3/hamcrest-core/src/main/java/org/hamcrest/CustomTypeSafeMatcher.java0000644000175000017500000000242211765134502030774 0ustar ebourgebourgpackage org.hamcrest; /** * Utility class for writing one off matchers. * For example: *
 * Matcher<String> aNonEmptyString = new CustomTypeSafeMatcher<String>("a non empty string") {
 *   public boolean matchesSafely(String string) {
 *     return !string.isEmpty();
 *   }
 *   public void describeMismatchSafely(String string, Description mismatchDescription) {
 *     mismatchDescription.appendText("was empty");
 *   }
 * };
 * 
* This is a variant of {@link CustomMatcher} that first type checks * the argument being matched. By the time {@link TypeSafeMatcher#matchesSafely} is * is called the argument is guaranteed to be non-null and of the correct * type. * * @author Neil Dunn * @param The type of object being matched */ public abstract class CustomTypeSafeMatcher extends TypeSafeMatcher { private final String fixedDescription; public CustomTypeSafeMatcher(String description) { if (description == null) { throw new IllegalArgumentException("Description must be non null!"); } this.fixedDescription = description; } @Override public final void describeTo(Description description) { description.appendText(fixedDescription); } } libhamcrest-java-1.3/hamcrest-core/src/main/java/org/hamcrest/MatcherAssert.java0000644000175000017500000000170711753011773027330 0ustar ebourgebourg/* Copyright (c) 2000-2006 hamcrest.org */ package org.hamcrest; public class MatcherAssert { public static void assertThat(T actual, Matcher matcher) { assertThat("", actual, matcher); } public static void assertThat(String reason, T actual, Matcher matcher) { if (!matcher.matches(actual)) { Description description = new StringDescription(); description.appendText(reason) .appendText("\nExpected: ") .appendDescriptionOf(matcher) .appendText("\n but: "); matcher.describeMismatch(actual, description); throw new AssertionError(description.toString()); } } public static void assertThat(String reason, boolean assertion) { if (!assertion) { throw new AssertionError(reason); } } } libhamcrest-java-1.3/hamcrest-core/src/main/java/org/hamcrest/DiagnosingMatcher.java0000644000175000017500000000100711755732222030143 0ustar ebourgebourgpackage org.hamcrest; /** * TODO(ngd): Document. * * @param */ public abstract class DiagnosingMatcher extends BaseMatcher { @Override public final boolean matches(Object item) { return matches(item, Description.NONE); } @Override public final void describeMismatch(Object item, Description mismatchDescription) { matches(item, mismatchDescription); } protected abstract boolean matches(Object item, Description mismatchDescription); } libhamcrest-java-1.3/hamcrest-core/src/main/java/org/hamcrest/StringDescription.java0000644000175000017500000000305211753011773030230 0ustar ebourgebourgpackage org.hamcrest; import java.io.IOException; /** * A {@link Description} that is stored as a string. */ public class StringDescription extends BaseDescription { private final Appendable out; public StringDescription() { this(new StringBuilder()); } public StringDescription(Appendable out) { this.out = out; } /** * Return the description of a {@link SelfDescribing} object as a String. * * @param selfDescribing * The object to be described. * @return * The description of the object. */ public static String toString(SelfDescribing selfDescribing) { return new StringDescription().appendDescriptionOf(selfDescribing).toString(); } /** * Alias for {@link #toString(SelfDescribing)}. */ public static String asString(SelfDescribing selfDescribing) { return toString(selfDescribing); } @Override protected void append(String str) { try { out.append(str); } catch (IOException e) { throw new RuntimeException("Could not write description", e); } } @Override protected void append(char c) { try { out.append(c); } catch (IOException e) { throw new RuntimeException("Could not write description", e); } } /** * Returns the description as a string. */ @Override public String toString() { return out.toString(); } } libhamcrest-java-1.3/hamcrest-core/src/main/java/org/hamcrest/core/0000755000175000017500000000000012131006721024627 5ustar ebourgebourglibhamcrest-java-1.3/hamcrest-core/src/main/java/org/hamcrest/core/IsCollectionContaining.java0000644000175000017500000001171111756137523032115 0ustar ebourgebourgpackage org.hamcrest.core; import static org.hamcrest.core.AllOf.allOf; import static org.hamcrest.core.IsEqual.equalTo; import java.util.ArrayList; import java.util.List; import org.hamcrest.Description; import org.hamcrest.Factory; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeDiagnosingMatcher; public class IsCollectionContaining extends TypeSafeDiagnosingMatcher> { private final Matcher elementMatcher; public IsCollectionContaining(Matcher elementMatcher) { this.elementMatcher = elementMatcher; } @Override protected boolean matchesSafely(Iterable collection, Description mismatchDescription) { boolean isPastFirst = false; for (Object item : collection) { if (elementMatcher.matches(item)){ return true; } if (isPastFirst) { mismatchDescription.appendText(", "); } elementMatcher.describeMismatch(item, mismatchDescription); isPastFirst = true; } return false; } @Override public void describeTo(Description description) { description .appendText("a collection containing ") .appendDescriptionOf(elementMatcher); } /** * Creates a matcher for {@link Iterable}s that only matches when a single pass over the * examined {@link Iterable} yields at least one item that is matched by the specified * itemMatcher. Whilst matching, the traversal of the examined {@link Iterable} * will stop as soon as a matching item is found. *

* For example: *

assertThat(Arrays.asList("foo", "bar"), hasItem(startsWith("ba")))
* * @param itemMatcher * the matcher to apply to items provided by the examined {@link Iterable} */ @Factory public static Matcher> hasItem(Matcher itemMatcher) { return new IsCollectionContaining(itemMatcher); } /** * Creates a matcher for {@link Iterable}s that only matches when a single pass over the * examined {@link Iterable} yields at least one item that is equal to the specified * item. Whilst matching, the traversal of the examined {@link Iterable} * will stop as soon as a matching item is found. *

* For example: *

assertThat(Arrays.asList("foo", "bar"), hasItem("bar"))
* * @param item * the item to compare against the items provided by the examined {@link Iterable} */ @Factory public static Matcher> hasItem(T item) { // Doesn't forward to hasItem() method so compiler can sort out generics. return new IsCollectionContaining(equalTo(item)); } /** * Creates a matcher for {@link Iterable}s that matches when consecutive passes over the * examined {@link Iterable} yield at least one item that is matched by the corresponding * matcher from the specified itemMatchers. Whilst matching, each traversal of * the examined {@link Iterable} will stop as soon as a matching item is found. *

* For example: *

assertThat(Arrays.asList("foo", "bar", "baz"), hasItems(endsWith("z"), endsWith("o")))
* * @param itemMatchers * the matchers to apply to items provided by the examined {@link Iterable} */ @Factory public static Matcher> hasItems(Matcher... itemMatchers) { List>> all = new ArrayList>>(itemMatchers.length); for (Matcher elementMatcher : itemMatchers) { // Doesn't forward to hasItem() method so compiler can sort out generics. all.add(new IsCollectionContaining(elementMatcher)); } return allOf(all); } /** * Creates a matcher for {@link Iterable}s that matches when consecutive passes over the * examined {@link Iterable} yield at least one item that is equal to the corresponding * item from the specified items. Whilst matching, each traversal of the * examined {@link Iterable} will stop as soon as a matching item is found. *

* For example: *

assertThat(Arrays.asList("foo", "bar", "baz"), hasItems("baz", "foo"))
* * @param items * the items to compare against the items provided by the examined {@link Iterable} */ @Factory public static Matcher> hasItems(T... items) { List>> all = new ArrayList>>(items.length); for (T element : items) { all.add(hasItem(element)); } return allOf(all); } } libhamcrest-java-1.3/hamcrest-core/src/main/java/org/hamcrest/core/ShortcutCombination.java0000644000175000017500000000167211753011773031512 0ustar ebourgebourgpackage org.hamcrest.core; import org.hamcrest.BaseMatcher; import org.hamcrest.Description; import org.hamcrest.Matcher; abstract class ShortcutCombination extends BaseMatcher { private final Iterable> matchers; public ShortcutCombination(Iterable> matchers) { this.matchers = matchers; } @Override public abstract boolean matches(Object o); @Override public abstract void describeTo(Description description); protected boolean matches(Object o, boolean shortcut) { for (Matcher matcher : matchers) { if (matcher.matches(o) == shortcut) { return shortcut; } } return !shortcut; } public void describeTo(Description description, String operator) { description.appendList("(", " " + operator + " ", ")", matchers); } } libhamcrest-java-1.3/hamcrest-core/src/main/java/org/hamcrest/core/StringContains.java0000644000175000017500000000211111756147527030460 0ustar ebourgebourg/* Copyright (c) 2000-2006 hamcrest.org */ package org.hamcrest.core; import org.hamcrest.Factory; import org.hamcrest.Matcher; /** * Tests if the argument is a string that contains a substring. */ public class StringContains extends SubstringMatcher { public StringContains(String substring) { super(substring); } @Override protected boolean evalSubstringOf(String s) { return s.indexOf(substring) >= 0; } @Override protected String relationship() { return "containing"; } /** * Creates a matcher that matches if the examined {@link String} contains the specified * {@link String} anywhere. *

* For example: *

assertThat("myStringOfNote", containsString("ring"))
* * @param substring * the substring that the returned matcher will expect to find within any examined string * */ @Factory public static Matcher containsString(String substring) { return new StringContains(substring); } }libhamcrest-java-1.3/hamcrest-core/src/main/java/org/hamcrest/core/CombinableMatcher.java0000644000175000017500000000514611756134616031060 0ustar ebourgebourgpackage org.hamcrest.core; import org.hamcrest.*; import java.util.ArrayList; public class CombinableMatcher extends TypeSafeDiagnosingMatcher { private final Matcher matcher; public CombinableMatcher(Matcher matcher) { this.matcher = matcher; } @Override protected boolean matchesSafely(T item, Description mismatch) { if (!matcher.matches(item)) { matcher.describeMismatch(item, mismatch); return false; } return true; } @Override public void describeTo(Description description) { description.appendDescriptionOf(matcher); } public CombinableMatcher and(Matcher other) { return new CombinableMatcher(new AllOf(templatedListWith(other))); } public CombinableMatcher or(Matcher other) { return new CombinableMatcher(new AnyOf(templatedListWith(other))); } private ArrayList> templatedListWith(Matcher other) { ArrayList> matchers = new ArrayList>(); matchers.add(matcher); matchers.add(other); return matchers; } /** * Creates a matcher that matches when both of the specified matchers match the examined object. *

* For example: *

assertThat("fab", both(containsString("a")).and(containsString("b")))
*/ @Factory public static CombinableBothMatcher both(Matcher matcher) { return new CombinableBothMatcher(matcher); } public static final class CombinableBothMatcher { private final Matcher first; public CombinableBothMatcher(Matcher matcher) { this.first = matcher; } public CombinableMatcher and(Matcher other) { return new CombinableMatcher(first).and(other); } } /** * Creates a matcher that matches when either of the specified matchers match the examined object. *

* For example: *

assertThat("fan", either(containsString("a")).and(containsString("b")))
*/ @Factory public static CombinableEitherMatcher either(Matcher matcher) { return new CombinableEitherMatcher(matcher); } public static final class CombinableEitherMatcher { private final Matcher first; public CombinableEitherMatcher(Matcher matcher) { this.first = matcher; } public CombinableMatcher or(Matcher other) { return new CombinableMatcher(first).or(other); } } }libhamcrest-java-1.3/hamcrest-core/src/main/java/org/hamcrest/core/IsNull.java0000644000175000017500000000443411756146733026731 0ustar ebourgebourg/* Copyright (c) 2000-2010 hamcrest.org */ package org.hamcrest.core; import static org.hamcrest.core.IsNot.not; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.Factory; import org.hamcrest.BaseMatcher; /** * Is the value null? */ public class IsNull extends BaseMatcher { @Override public boolean matches(Object o) { return o == null; } @Override public void describeTo(Description description) { description.appendText("null"); } /** * Creates a matcher that matches if examined object is null. *

* For example: *

assertThat(cheese, is(nullValue())
* */ @Factory public static Matcher nullValue() { return new IsNull(); } /** * A shortcut to the frequently used not(nullValue()). *

* For example: *

assertThat(cheese, is(notNullValue()))
* instead of: *
assertThat(cheese, is(not(nullValue())))
* */ @Factory public static Matcher notNullValue() { return not(nullValue()); } /** * Creates a matcher that matches if examined object is null. Accepts a * single dummy argument to facilitate type inference. *

* For example: *

assertThat(cheese, is(nullValue(Cheese.class))
* * @param type * dummy parameter used to infer the generic type of the returned matcher */ @Factory public static Matcher nullValue(Class type) { return new IsNull(); } /** * A shortcut to the frequently used not(nullValue(X.class)). Accepts a * single dummy argument to facilitate type inference.. *

* For example: *

assertThat(cheese, is(notNullValue(X.class)))
* instead of: *
assertThat(cheese, is(not(nullValue(X.class))))
* * @param type * dummy parameter used to infer the generic type of the returned matcher * */ @Factory public static Matcher notNullValue(Class type) { return not(nullValue(type)); } } libhamcrest-java-1.3/hamcrest-core/src/main/java/org/hamcrest/core/Is.java0000644000175000017500000000551011756135350026063 0ustar ebourgebourgpackage org.hamcrest.core; import org.hamcrest.BaseMatcher; import org.hamcrest.Description; import org.hamcrest.Factory; import org.hamcrest.Matcher; import static org.hamcrest.core.IsEqual.equalTo; import static org.hamcrest.core.IsInstanceOf.instanceOf; /** * Decorates another Matcher, retaining the behaviour but allowing tests * to be slightly more expressive. * * For example: assertThat(cheese, equalTo(smelly)) * vs. assertThat(cheese, is(equalTo(smelly))) */ public class Is extends BaseMatcher { private final Matcher matcher; public Is(Matcher matcher) { this.matcher = matcher; } @Override public boolean matches(Object arg) { return matcher.matches(arg); } @Override public void describeTo(Description description) { description.appendText("is ").appendDescriptionOf(matcher); } @Override public void describeMismatch(Object item, Description mismatchDescription) { matcher.describeMismatch(item, mismatchDescription); } /** * Decorates another Matcher, retaining its behaviour, but allowing tests * to be slightly more expressive. *

* For example: *

assertThat(cheese, is(equalTo(smelly)))
* instead of: *
assertThat(cheese, equalTo(smelly))
* */ @Factory public static Matcher is(Matcher matcher) { return new Is(matcher); } /** * A shortcut to the frequently used is(equalTo(x)). *

* For example: *

assertThat(cheese, is(smelly))
* instead of: *
assertThat(cheese, is(equalTo(smelly)))
* */ @Factory public static Matcher is(T value) { return is(equalTo(value)); } /** * A shortcut to the frequently used is(instanceOf(SomeClass.class)). *

* For example: *

assertThat(cheese, is(Cheddar.class))
* instead of: *
assertThat(cheese, is(instanceOf(Cheddar.class)))
* * @deprecated use isA(Class type) instead. */ @Factory @Deprecated public static Matcher is(Class type) { final Matcher typeMatcher = instanceOf(type); return is(typeMatcher); } /** * A shortcut to the frequently used is(instanceOf(SomeClass.class)). *

* For example: *

assertThat(cheese, isA(Cheddar.class))
* instead of: *
assertThat(cheese, is(instanceOf(Cheddar.class)))
* */ @Factory public static Matcher isA(Class type) { final Matcher typeMatcher = instanceOf(type); return is(typeMatcher); } } libhamcrest-java-1.3/hamcrest-core/src/main/java/org/hamcrest/core/StringStartsWith.java0000644000175000017500000000206011756147466031023 0ustar ebourgebourg/* Copyright (c) 2000-2006 hamcrest.org */ package org.hamcrest.core; import org.hamcrest.Factory; import org.hamcrest.Matcher; /** * Tests if the argument is a string that contains a substring. */ public class StringStartsWith extends SubstringMatcher { public StringStartsWith(String substring) { super(substring); } @Override protected boolean evalSubstringOf(String s) { return s.startsWith(substring); } @Override protected String relationship() { return "starting with"; } /** * Creates a matcher that matches if the examined {@link String} starts with the specified * {@link String}. *

* For example: *

assertThat("myStringOfNote", startsWith("my"))
* * @param prefix * the substring that the returned matcher will expect at the start of any examined string */ @Factory public static Matcher startsWith(String prefix) { return new StringStartsWith(prefix); } }libhamcrest-java-1.3/hamcrest-core/src/main/java/org/hamcrest/core/AllOf.java0000644000175000017500000001222011756134416026503 0ustar ebourgebourgpackage org.hamcrest.core; import org.hamcrest.Description; import org.hamcrest.DiagnosingMatcher; import org.hamcrest.Factory; import org.hamcrest.Matcher; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Calculates the logical conjunction of multiple matchers. Evaluation is shortcut, so * subsequent matchers are not called if an earlier matcher returns false. */ public class AllOf extends DiagnosingMatcher { private final Iterable> matchers; public AllOf(Iterable> matchers) { this.matchers = matchers; } @Override public boolean matches(Object o, Description mismatch) { for (Matcher matcher : matchers) { if (!matcher.matches(o)) { mismatch.appendDescriptionOf(matcher).appendText(" "); matcher.describeMismatch(o, mismatch); return false; } } return true; } @Override public void describeTo(Description description) { description.appendList("(", " " + "and" + " ", ")", matchers); } /** * Creates a matcher that matches if the examined object matches ALL of the specified matchers. *

* For example: *

assertThat("myValue", allOf(startsWith("my"), containsString("Val")))
*/ @Factory public static Matcher allOf(Iterable> matchers) { return new AllOf(matchers); } /** * Creates a matcher that matches if the examined object matches ALL of the specified matchers. *

* For example: *

assertThat("myValue", allOf(startsWith("my"), containsString("Val")))
*/ @Factory public static Matcher allOf(Matcher... matchers) { return allOf(Arrays.asList(matchers)); } /** * Creates a matcher that matches if the examined object matches ALL of the specified matchers. *

* For example: *

assertThat("myValue", allOf(startsWith("my"), containsString("Val")))
*/ @Factory public static Matcher allOf(Matcher first, Matcher second) { List> matchers = new ArrayList>(2); matchers.add(first); matchers.add(second); return allOf(matchers); } /** * Creates a matcher that matches if the examined object matches ALL of the specified matchers. *

* For example: *

assertThat("myValue", allOf(startsWith("my"), containsString("Val")))
*/ @Factory public static Matcher allOf(Matcher first, Matcher second, Matcher third) { List> matchers = new ArrayList>(3); matchers.add(first); matchers.add(second); matchers.add(third); return allOf(matchers); } /** * Creates a matcher that matches if the examined object matches ALL of the specified matchers. *

* For example: *

assertThat("myValue", allOf(startsWith("my"), containsString("Val")))
*/ @Factory public static Matcher allOf(Matcher first, Matcher second, Matcher third, Matcher fourth) { List> matchers = new ArrayList>(4); matchers.add(first); matchers.add(second); matchers.add(third); matchers.add(fourth); return allOf(matchers); } /** * Creates a matcher that matches if the examined object matches ALL of the specified matchers. *

* For example: *

assertThat("myValue", allOf(startsWith("my"), containsString("Val")))
*/ @Factory public static Matcher allOf(Matcher first, Matcher second, Matcher third, Matcher fourth, Matcher fifth) { List> matchers = new ArrayList>(5); matchers.add(first); matchers.add(second); matchers.add(third); matchers.add(fourth); matchers.add(fifth); return allOf(matchers); } /** * Creates a matcher that matches if the examined object matches ALL of the specified matchers. *

* For example: *

assertThat("myValue", allOf(startsWith("my"), containsString("Val")))
*/ @Factory public static Matcher allOf(Matcher first, Matcher second, Matcher third, Matcher fourth, Matcher fifth, Matcher sixth) { List> matchers = new ArrayList>(6); matchers.add(first); matchers.add(second); matchers.add(third); matchers.add(fourth); matchers.add(fifth); matchers.add(sixth); return allOf(matchers); } } libhamcrest-java-1.3/hamcrest-core/src/main/java/org/hamcrest/core/AnyOf.java0000644000175000017500000001126411756134315026527 0ustar ebourgebourgpackage org.hamcrest.core; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.hamcrest.Description; import org.hamcrest.Factory; import org.hamcrest.Matcher; /** * Calculates the logical disjunction of multiple matchers. Evaluation is shortcut, so * subsequent matchers are not called if an earlier matcher returns true. */ public class AnyOf extends ShortcutCombination { public AnyOf(Iterable> matchers) { super(matchers); } @Override public boolean matches(Object o) { return matches(o, true); } @Override public void describeTo(Description description) { describeTo(description, "or"); } /** * Creates a matcher that matches if the examined object matches ANY of the specified matchers. *

* For example: *

assertThat("myValue", anyOf(startsWith("foo"), containsString("Val")))
*/ @Factory public static AnyOf anyOf(Iterable> matchers) { return new AnyOf(matchers); } /** * Creates a matcher that matches if the examined object matches ANY of the specified matchers. *

* For example: *

assertThat("myValue", anyOf(startsWith("foo"), containsString("Val")))
*/ @Factory public static AnyOf anyOf(Matcher... matchers) { return anyOf(Arrays.asList(matchers)); } /** * Creates a matcher that matches if the examined object matches ANY of the specified matchers. *

* For example: *

assertThat("myValue", anyOf(startsWith("foo"), containsString("Val")))
*/ @Factory public static AnyOf anyOf(Matcher first, Matcher second) { List> matchers = new ArrayList>(); matchers.add(first); matchers.add(second); return anyOf(matchers); } /** * Creates a matcher that matches if the examined object matches ANY of the specified matchers. *

* For example: *

assertThat("myValue", anyOf(startsWith("foo"), containsString("Val")))
*/ @Factory public static AnyOf anyOf(Matcher first, Matcher second, Matcher third) { List> matchers = new ArrayList>(); matchers.add(first); matchers.add(second); matchers.add(third); return anyOf(matchers); } /** * Creates a matcher that matches if the examined object matches ANY of the specified matchers. *

* For example: *

assertThat("myValue", anyOf(startsWith("foo"), containsString("Val")))
*/ @Factory public static AnyOf anyOf(Matcher first, Matcher second, Matcher third, Matcher fourth) { List> matchers = new ArrayList>(); matchers.add(first); matchers.add(second); matchers.add(third); matchers.add(fourth); return anyOf(matchers); } /** * Creates a matcher that matches if the examined object matches ANY of the specified matchers. *

* For example: *

assertThat("myValue", anyOf(startsWith("foo"), containsString("Val")))
*/ @Factory public static AnyOf anyOf(Matcher first, Matcher second, Matcher third, Matcher fourth, Matcher fifth) { List> matchers = new ArrayList>(); matchers.add(first); matchers.add(second); matchers.add(third); matchers.add(fourth); matchers.add(fifth); return anyOf(matchers); } /** * Creates a matcher that matches if the examined object matches ANY of the specified matchers. *

* For example: *

assertThat("myValue", anyOf(startsWith("foo"), containsString("Val")))
*/ @Factory public static AnyOf anyOf(Matcher first, Matcher second, Matcher third, Matcher fourth, Matcher fifth, Matcher sixth) { List> matchers = new ArrayList>(); matchers.add(first); matchers.add(second); matchers.add(third); matchers.add(fourth); matchers.add(fifth); matchers.add(sixth); return anyOf(matchers); } } libhamcrest-java-1.3/hamcrest-core/src/main/java/org/hamcrest/core/IsAnything.java0000644000175000017500000000247411756135564027602 0ustar ebourgebourg/* Copyright (c) 2000-2006 hamcrest.org */ package org.hamcrest.core; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.Factory; import org.hamcrest.BaseMatcher; /** * A matcher that always returns true. */ public class IsAnything extends BaseMatcher { private final String message; public IsAnything() { this("ANYTHING"); } public IsAnything(String message) { this.message = message; } @Override public boolean matches(Object o) { return true; } @Override public void describeTo(Description description) { description.appendText(message); } /** * Creates a matcher that always matches, regardless of the examined object. */ @Factory public static Matcher anything() { return new IsAnything(); } /** * Creates a matcher that always matches, regardless of the examined object, but describes * itself with the specified {@link String}. * * @param description * a meaningful {@link String} used when describing itself */ @Factory public static Matcher anything(String description) { return new IsAnything(description); } } libhamcrest-java-1.3/hamcrest-core/src/main/java/org/hamcrest/core/IsSame.java0000644000175000017500000000270111756133532026670 0ustar ebourgebourg/* Copyright (c) 2000-2006 hamcrest.org */ package org.hamcrest.core; import org.hamcrest.BaseMatcher; import org.hamcrest.Description; import org.hamcrest.Factory; import org.hamcrest.Matcher; /** * Is the value the same object as another value? */ public class IsSame extends BaseMatcher { private final T object; public IsSame(T object) { this.object = object; } @Override public boolean matches(Object arg) { return arg == object; } @Override public void describeTo(Description description) { description.appendText("sameInstance(") .appendValue(object) .appendText(")"); } /** * Creates a matcher that matches only when the examined object is the same instance as * the specified target object. * * @param target * the target instance against which others should be assessed */ @Factory public static Matcher sameInstance(T target) { return new IsSame(target); } /** * Creates a matcher that matches only when the examined object is the same instance as * the specified target object. * * @param target * the target instance against which others should be assessed */ @Factory public static Matcher theInstance(T target) { return new IsSame(target); } } libhamcrest-java-1.3/hamcrest-core/src/main/java/org/hamcrest/core/IsEqual.java0000644000175000017500000000637111756143427027065 0ustar ebourgebourg/* Copyright (c) 2000-2006 hamcrest.org */ package org.hamcrest.core; import org.hamcrest.BaseMatcher; import org.hamcrest.Description; import org.hamcrest.Factory; import org.hamcrest.Matcher; import java.lang.reflect.Array; /** * Is the value equal to another value, as tested by the * {@link java.lang.Object#equals} invokedMethod? */ public class IsEqual extends BaseMatcher { private final Object expectedValue; public IsEqual(T equalArg) { expectedValue = equalArg; } @Override public boolean matches(Object actualValue) { return areEqual(actualValue, expectedValue); } @Override public void describeTo(Description description) { description.appendValue(expectedValue); } private static boolean areEqual(Object actual, Object expected) { if (actual == null) { return expected == null; } if (expected != null && isArray(actual)) { return isArray(expected) && areArraysEqual(actual, expected); } return actual.equals(expected); } private static boolean areArraysEqual(Object actualArray, Object expectedArray) { return areArrayLengthsEqual(actualArray, expectedArray) && areArrayElementsEqual(actualArray, expectedArray); } private static boolean areArrayLengthsEqual(Object actualArray, Object expectedArray) { return Array.getLength(actualArray) == Array.getLength(expectedArray); } private static boolean areArrayElementsEqual(Object actualArray, Object expectedArray) { for (int i = 0; i < Array.getLength(actualArray); i++) { if (!areEqual(Array.get(actualArray, i), Array.get(expectedArray, i))) { return false; } } return true; } private static boolean isArray(Object o) { return o.getClass().isArray(); } /** * Creates a matcher that matches when the examined object is logically equal to the specified * operand, as determined by calling the {@link java.lang.Object#equals} method on * the examined object. * *

If the specified operand is null then the created matcher will only match if * the examined object's equals method returns true when passed a * null (which would be a violation of the equals contract), unless the * examined object itself is null, in which case the matcher will return a positive * match.

* *

The created matcher provides a special behaviour when examining Arrays, whereby * it will match if both the operand and the examined object are arrays of the same length and * contain items that are equal to each other (according to the above rules) in the same * indexes.

*

* For example: *

     * assertThat("foo", equalTo("foo"));
     * assertThat(new String[] {"foo", "bar"}, equalTo(new String[] {"foo", "bar"}));
     * 
* */ @Factory public static Matcher equalTo(T operand) { return new IsEqual(operand); } } libhamcrest-java-1.3/hamcrest-core/src/main/java/org/hamcrest/core/SubstringMatcher.java0000644000175000017500000000220511753011773030771 0ustar ebourgebourgpackage org.hamcrest.core; import org.hamcrest.Description; import org.hamcrest.TypeSafeMatcher; public abstract class SubstringMatcher extends TypeSafeMatcher { // TODO: Replace String with CharSequence to allow for easy interopability between // String, StringBuffer, StringBuilder, CharBuffer, etc (joe). protected final String substring; protected SubstringMatcher(final String substring) { this.substring = substring; } @Override public boolean matchesSafely(String item) { return evalSubstringOf(item); } @Override public void describeMismatchSafely(String item, Description mismatchDescription) { mismatchDescription.appendText("was \"").appendText(item).appendText("\""); } @Override public void describeTo(Description description) { description.appendText("a string ") .appendText(relationship()) .appendText(" ") .appendValue(substring); } protected abstract boolean evalSubstringOf(String string); protected abstract String relationship(); }libhamcrest-java-1.3/hamcrest-core/src/main/java/org/hamcrest/core/StringEndsWith.java0000644000175000017500000000204211756147477030436 0ustar ebourgebourg/* Copyright (c) 2000-2006 hamcrest.org */ package org.hamcrest.core; import org.hamcrest.Factory; import org.hamcrest.Matcher; /** * Tests if the argument is a string that contains a substring. */ public class StringEndsWith extends SubstringMatcher { public StringEndsWith(String substring) { super(substring); } @Override protected boolean evalSubstringOf(String s) { return s.endsWith(substring); } @Override protected String relationship() { return "ending with"; } /** * Creates a matcher that matches if the examined {@link String} ends with the specified * {@link String}. *

* For example: *

assertThat("myStringOfNote", endsWith("Note"))
* * @param suffix * the substring that the returned matcher will expect at the end of any examined string */ @Factory public static Matcher endsWith(String suffix) { return new StringEndsWith(suffix); } } libhamcrest-java-1.3/hamcrest-core/src/main/java/org/hamcrest/core/IsNot.java0000644000175000017500000000320011756146036026541 0ustar ebourgebourg/* Copyright (c) 2000-2009 hamcrest.org */ package org.hamcrest.core; import org.hamcrest.BaseMatcher; import org.hamcrest.Description; import org.hamcrest.Factory; import org.hamcrest.Matcher; import static org.hamcrest.core.IsEqual.equalTo; /** * Calculates the logical negation of a matcher. */ public class IsNot extends BaseMatcher { private final Matcher matcher; public IsNot(Matcher matcher) { this.matcher = matcher; } @Override public boolean matches(Object arg) { return !matcher.matches(arg); } @Override public void describeTo(Description description) { description.appendText("not ").appendDescriptionOf(matcher); } /** * Creates a matcher that wraps an existing matcher, but inverts the logic by which * it will match. *

* For example: *

assertThat(cheese, is(not(equalTo(smelly))))
* * @param matcher * the matcher whose sense should be inverted */ @Factory public static Matcher not(Matcher matcher) { return new IsNot(matcher); } /** * A shortcut to the frequently used not(equalTo(x)). *

* For example: *

assertThat(cheese, is(not(smelly)))
* instead of: *
assertThat(cheese, is(not(equalTo(smelly))))
* * @param value * the value that any examined object should not equal */ @Factory public static Matcher not(T value) { return not(equalTo(value)); } } libhamcrest-java-1.3/hamcrest-core/src/main/java/org/hamcrest/core/Every.java0000644000175000017500000000304411756133457026610 0ustar ebourgebourgpackage org.hamcrest.core; import org.hamcrest.Description; import org.hamcrest.Factory; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeDiagnosingMatcher; public class Every extends TypeSafeDiagnosingMatcher> { private final Matcher matcher; public Every(Matcher matcher) { this.matcher= matcher; } @Override public boolean matchesSafely(Iterable collection, Description mismatchDescription) { for (T t : collection) { if (!matcher.matches(t)) { mismatchDescription.appendText("an item "); matcher.describeMismatch(t, mismatchDescription); return false; } } return true; } @Override public void describeTo(Description description) { description.appendText("every item is ").appendDescriptionOf(matcher); } /** * Creates a matcher for {@link Iterable}s that only matches when a single pass over the * examined {@link Iterable} yields items that are all matched by the specified * itemMatcher. *

* For example: *

assertThat(Arrays.asList("bar", "baz"), everyItem(startsWith("ba")))
* * @param itemMatcher * the matcher to apply to every item provided by the examined {@link Iterable} */ @Factory public static Matcher> everyItem(final Matcher itemMatcher) { return new Every(itemMatcher); } } libhamcrest-java-1.3/hamcrest-core/src/main/java/org/hamcrest/core/IsInstanceOf.java0000644000175000017500000000702211756145125030036 0ustar ebourgebourg/* Copyright (c) 2000-2006 hamcrest.org */ package org.hamcrest.core; import org.hamcrest.Description; import org.hamcrest.DiagnosingMatcher; import org.hamcrest.Factory; import org.hamcrest.Matcher; /** * Tests whether the value is an instance of a class. * Classes of basic types will be converted to the relevant "Object" classes */ public class IsInstanceOf extends DiagnosingMatcher { private final Class expectedClass; private final Class matchableClass; /** * Creates a new instance of IsInstanceOf * * @param expectedClass The predicate evaluates to true for instances of this class * or one of its subclasses. */ public IsInstanceOf(Class expectedClass) { this.expectedClass = expectedClass; this.matchableClass = matchableClass(expectedClass); } private static Class matchableClass(Class expectedClass) { if (boolean.class.equals(expectedClass)) return Boolean.class; if (byte.class.equals(expectedClass)) return Byte.class; if (char.class.equals(expectedClass)) return Character.class; if (double.class.equals(expectedClass)) return Double.class; if (float.class.equals(expectedClass)) return Float.class; if (int.class.equals(expectedClass)) return Integer.class; if (long.class.equals(expectedClass)) return Long.class; if (short.class.equals(expectedClass)) return Short.class; return expectedClass; } @Override protected boolean matches(Object item, Description mismatch) { if (null == item) { mismatch.appendText("null"); return false; } if (!matchableClass.isInstance(item)) { mismatch.appendValue(item).appendText(" is a " + item.getClass().getName()); return false; } return true; } @Override public void describeTo(Description description) { description.appendText("an instance of ").appendText(expectedClass.getName()); } /** * Creates a matcher that matches when the examined object is an instance of the specified type, * as determined by calling the {@link java.lang.Class#isInstance(Object)} method on that type, passing the * the examined object. * *

The created matcher assumes no relationship between specified type and the examined object.

*

* For example: *

assertThat(new Canoe(), instanceOf(Paddlable.class));
* */ @SuppressWarnings("unchecked") @Factory public static Matcher instanceOf(Class type) { return (Matcher) new IsInstanceOf(type); } /** * Creates a matcher that matches when the examined object is an instance of the specified type, * as determined by calling the {@link java.lang.Class#isInstance(Object)} method on that type, passing the * the examined object. * *

The created matcher forces a relationship between specified type and the examined object, and should be * used when it is necessary to make generics conform, for example in the JMock clause * with(any(Thing.class))

*

* For example: *

assertThat(new Canoe(), instanceOf(Canoe.class));
* */ @SuppressWarnings("unchecked") @Factory public static Matcher any(Class type) { return (Matcher) new IsInstanceOf(type); } } libhamcrest-java-1.3/hamcrest-core/src/main/java/org/hamcrest/core/package.html0000644000175000017500000000020111753011773027115 0ustar ebourgebourg

Fundamental matchers of objects and values, and composite matchers.

libhamcrest-java-1.3/hamcrest-core/src/main/java/org/hamcrest/core/DescribedAs.java0000644000175000017500000000467111765132326027667 0ustar ebourgebourg/* Copyright (c) 2000-2006 hamcrest.org */ package org.hamcrest.core; import org.hamcrest.BaseMatcher; import org.hamcrest.Description; import org.hamcrest.Factory; import org.hamcrest.Matcher; import java.util.regex.Pattern; import static java.lang.Integer.parseInt; /** * Provides a custom description to another matcher. */ public class DescribedAs extends BaseMatcher { private final String descriptionTemplate; private final Matcher matcher; private final Object[] values; private final static Pattern ARG_PATTERN = Pattern.compile("%([0-9]+)"); public DescribedAs(String descriptionTemplate, Matcher matcher, Object[] values) { this.descriptionTemplate = descriptionTemplate; this.matcher = matcher; this.values = values.clone(); } @Override public boolean matches(Object o) { return matcher.matches(o); } @Override public void describeTo(Description description) { java.util.regex.Matcher arg = ARG_PATTERN.matcher(descriptionTemplate); int textStart = 0; while (arg.find()) { description.appendText(descriptionTemplate.substring(textStart, arg.start())); description.appendValue(values[parseInt(arg.group(1))]); textStart = arg.end(); } if (textStart < descriptionTemplate.length()) { description.appendText(descriptionTemplate.substring(textStart)); } } @Override public void describeMismatch(Object item, Description description) { matcher.describeMismatch(item, description); } /** * Wraps an existing matcher, overriding its description with that specified. All other functions are * delegated to the decorated matcher, including its mismatch description. *

* For example: *

describedAs("a big decimal equal to %0", equalTo(myBigDecimal), myBigDecimal.toPlainString())
* * @param description * the new description for the wrapped matcher * @param matcher * the matcher to wrap * @param values * optional values to insert into the tokenised description */ @Factory public static Matcher describedAs(String description, Matcher matcher, Object... values) { return new DescribedAs(description, matcher, values); } } libhamcrest-java-1.3/hamcrest-core/src/main/java/org/hamcrest/SelfDescribing.java0000644000175000017500000000074111753011773027443 0ustar ebourgebourgpackage org.hamcrest; /** * The ability of an object to describe itself. */ public interface SelfDescribing { /** * Generates a description of the object. The description may be part of a * a description of a larger object of which this is just a component, so it * should be worded appropriately. * * @param description * The description to be built or appended to. */ void describeTo(Description description); }libhamcrest-java-1.3/hamcrest-core/src/main/java/org/hamcrest/BaseDescription.java0000644000175000017500000001051011761746473027644 0ustar ebourgebourgpackage org.hamcrest; import static java.lang.String.valueOf; import java.util.Arrays; import java.util.Iterator; import org.hamcrest.internal.ArrayIterator; import org.hamcrest.internal.SelfDescribingValueIterator; /** * A {@link Description} that is stored as a string. */ public abstract class BaseDescription implements Description { @Override public Description appendText(String text) { append(text); return this; } @Override public Description appendDescriptionOf(SelfDescribing value) { value.describeTo(this); return this; } @Override public Description appendValue(Object value) { if (value == null) { append("null"); } else if (value instanceof String) { toJavaSyntax((String) value); } else if (value instanceof Character) { append('"'); toJavaSyntax((Character) value); append('"'); } else if (value instanceof Short) { append('<'); append(descriptionOf(value)); append("s>"); } else if (value instanceof Long) { append('<'); append(descriptionOf(value)); append("L>"); } else if (value instanceof Float) { append('<'); append(descriptionOf(value)); append("F>"); } else if (value.getClass().isArray()) { appendValueList("[",", ","]", new ArrayIterator(value)); } else { append('<'); append(descriptionOf(value)); append('>'); } return this; } private String descriptionOf(Object value) { try { return valueOf(value); } catch (Exception e) { return value.getClass().getName() + "@" + Integer.toHexString(value.hashCode()); } } @Override public Description appendValueList(String start, String separator, String end, T... values) { return appendValueList(start, separator, end, Arrays.asList(values)); } @Override public Description appendValueList(String start, String separator, String end, Iterable values) { return appendValueList(start, separator, end, values.iterator()); } private Description appendValueList(String start, String separator, String end, Iterator values) { return appendList(start, separator, end, new SelfDescribingValueIterator(values)); } @Override public Description appendList(String start, String separator, String end, Iterable values) { return appendList(start, separator, end, values.iterator()); } private Description appendList(String start, String separator, String end, Iterator i) { boolean separate = false; append(start); while (i.hasNext()) { if (separate) append(separator); appendDescriptionOf(i.next()); separate = true; } append(end); return this; } /** * Append the String str to the description. * The default implementation passes every character to {@link #append(char)}. * Override in subclasses to provide an efficient implementation. */ protected void append(String str) { for (int i = 0; i < str.length(); i++) { append(str.charAt(i)); } } /** * Append the char c to the description. */ protected abstract void append(char c); private void toJavaSyntax(String unformatted) { append('"'); for (int i = 0; i < unformatted.length(); i++) { toJavaSyntax(unformatted.charAt(i)); } append('"'); } private void toJavaSyntax(char ch) { switch (ch) { case '"': append("\\\""); break; case '\n': append("\\n"); break; case '\r': append("\\r"); break; case '\t': append("\\t"); break; default: append(ch); } } } libhamcrest-java-1.3/hamcrest-core/src/main/java/org/hamcrest/Factory.java0000644000175000017500000000071511753011773026170 0ustar ebourgebourgpackage org.hamcrest; import static java.lang.annotation.ElementType.METHOD; import java.lang.annotation.Retention; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Target; /** * Marks a Hamcrest static factory method so tools recognise them. * A factory method is an equivalent to a named constructor. * * @author Joe Walnes */ @Retention(RUNTIME) @Target({METHOD}) public @interface Factory { } libhamcrest-java-1.3/hamcrest-core/src/main/java/org/hamcrest/package.html0000644000175000017500000000034311753011773026174 0ustar ebourgebourg

The stable API defining Matcher and its associated interfaces and classes. Hamcrest sub-projects define their convenience classes in the org.hamcrest package.

libhamcrest-java-1.3/hamcrest-core/src/main/java/org/hamcrest/BaseMatcher.java0000644000175000017500000000137411755733672026754 0ustar ebourgebourg/* Copyright (c) 2000-2006 hamcrest.org */ package org.hamcrest; /** * BaseClass for all Matcher implementations. * * @see Matcher */ public abstract class BaseMatcher implements Matcher { /** * @see Matcher#_dont_implement_Matcher___instead_extend_BaseMatcher_() */ @Override @Deprecated public final void _dont_implement_Matcher___instead_extend_BaseMatcher_() { // See Matcher interface for an explanation of this method. } @Override public void describeMismatch(Object item, Description description) { description.appendText("was ").appendValue(item); } @Override public String toString() { return StringDescription.toString(this); } } libhamcrest-java-1.3/hamcrest-unit-test/0000755000175000017500000000000011753011773017666 5ustar ebourgebourglibhamcrest-java-1.3/hamcrest-unit-test/src/0000755000175000017500000000000011753011773020455 5ustar ebourgebourglibhamcrest-java-1.3/hamcrest-unit-test/src/main/0000755000175000017500000000000012131006721021365 5ustar ebourgebourglibhamcrest-java-1.3/hamcrest-unit-test/src/main/java/0000755000175000017500000000000011753011773022322 5ustar ebourgebourglibhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/0000755000175000017500000000000011753011773023111 5ustar ebourgebourglibhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/0000755000175000017500000000000012131006721024703 5ustar ebourgebourglibhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/FeatureMatcherTest.java0000644000175000017500000000413711753011773031326 0ustar ebourgebourgpackage org.hamcrest; import static org.hamcrest.AbstractMatcherTest.assertDescription; import static org.hamcrest.AbstractMatcherTest.assertMatches; import static org.hamcrest.AbstractMatcherTest.assertMismatchDescription; import junit.framework.TestCase; import org.hamcrest.core.IsEqual; public class FeatureMatcherTest extends TestCase { private final FeatureMatcher resultMatcher = resultMatcher(); public void testMatchesPartOfAnObject() { assertMatches("feature", resultMatcher, new Thingy("bar")); assertDescription("Thingy with result \"bar\"", resultMatcher); } public void testMismatchesPartOfAnObject() { assertMismatchDescription("result mismatch-description", resultMatcher, new Thingy("foo")); } public void testDoesNotThrowNullPointerException() { assertMismatchDescription("was null", resultMatcher, null); } public void testDoesNotThrowClassCastException() { resultMatcher.matches(new ShouldNotMatch()); StringDescription mismatchDescription = new StringDescription(); resultMatcher.describeMismatch(new ShouldNotMatch(), mismatchDescription); assertEquals("was ", mismatchDescription.toString()); } public static class Match extends IsEqual { public Match(String equalArg) { super(equalArg); } @Override public void describeMismatch(Object item, Description description) { description.appendText("mismatch-description"); } } public static class Thingy { private final String result; public Thingy(String result) { this.result = result; } public String getResult() { return result; } } public static class ShouldNotMatch { @Override public String toString() { return "ShouldNotMatch"; } } private static FeatureMatcher resultMatcher() { return new FeatureMatcher(new Match("bar"), "Thingy with result", "result") { @Override public String featureValueOf(Thingy actual) { return actual.getResult(); } }; } } libhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/TypeSafeMatcherTest.java0000644000175000017500000000255611753011773031456 0ustar ebourgebourgpackage org.hamcrest; import junit.framework.TestCase; public class TypeSafeMatcherTest extends TestCase { private final Matcher matcher = new TypeSafeMatcherSubclass(); public static class TypeSafeMatcherSubclass extends TypeSafeMatcher { @Override public boolean matchesSafely(String item) { return false; } @Override public void describeMismatchSafely(String item, Description mismatchDescription) { mismatchDescription.appendText("The mismatch"); } @Override public void describeTo(Description description) { } } public void testCanDetermineMatcherTypeFromProtectedMatchesSafelyMethod() { assertFalse(matcher.matches(null)); assertFalse(matcher.matches(10)); } public void testDescribesMismatches() { assertMismatchDescription("was null", null); assertMismatchDescription("was a java.lang.Integer (<3>)", new Integer(3)); assertMismatchDescription("The mismatch", "a string"); } private void assertMismatchDescription(String expectedDescription, Object actual) { StringDescription description = new StringDescription(); matcher.describeMismatch(actual, description); assertEquals(expectedDescription, description.toString()); } } libhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/CustomMatcherTest.java0000644000175000017500000000104211753011773031175 0ustar ebourgebourgpackage org.hamcrest; import static org.hamcrest.AbstractMatcherTest.assertDescription; import junit.framework.TestCase; public class CustomMatcherTest extends TestCase { public void testUsesStaticDescription() throws Exception { Matcher matcher = new CustomMatcher("I match strings") { @Override public boolean matches(Object item) { return (item instanceof String); } }; assertDescription("I match strings", matcher); } } libhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/CustomTypeSafeMatcherTest.java0000644000175000017500000000205111753011773032637 0ustar ebourgebourgpackage org.hamcrest; public class CustomTypeSafeMatcherTest extends AbstractMatcherTest { private static final String STATIC_DESCRIPTION = "I match non empty strings"; private Matcher customMatcher; @Override protected void setUp() throws Exception { customMatcher = new CustomTypeSafeMatcher(STATIC_DESCRIPTION) { @Override public boolean matchesSafely(String item) { return false; } @Override public void describeMismatchSafely(String item, Description mismatchDescription) { mismatchDescription.appendText("an " + item); } }; } public void testUsesStaticDescription() throws Exception { assertDescription(STATIC_DESCRIPTION, customMatcher); } public void testReportsMismatch() { assertMismatchDescription("an item", customMatcher, "item"); } @Override protected Matcher createMatcher() { return customMatcher; } } libhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/JavaLangMatcherAssertTest.java0000644000175000017500000000101011753011773032563 0ustar ebourgebourgpackage org.hamcrest; import static org.hamcrest.JavaLangMatcherAssert.that; import static org.hamcrest.core.StringStartsWith.startsWith; import junit.framework.TestCase; public class JavaLangMatcherAssertTest extends TestCase { public void testWouldCauseFailingAssertion() throws Exception { assertEquals(false, that("Foo", startsWith("Bar"))); } public void testWouldCausePassingAssertion() throws Exception { assertEquals(true, that("Foo", startsWith("F"))); } } libhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/BaseDescriptionTest.java0000644000175000017500000000432611761746341031512 0ustar ebourgebourgpackage org.hamcrest; import junit.framework.TestCase; public class BaseDescriptionTest extends TestCase { private final StringBuilder result = new StringBuilder(); private final BaseDescription baseDescription = new BaseDescription() { @Override protected void append(char c) { result.append(c); } }; public void testDescribesAppendedNullValue() { baseDescription.appendValue(null); assertEquals("null", result.toString()); } public void testQuotesAppendedStringValue() { baseDescription.appendValue("foo"); assertEquals("\"foo\"", result.toString()); } public void testQuotesAppendedCharacterValue() { baseDescription.appendValue('f'); assertEquals("\"f\"", result.toString()); } public void testBracketsAppendedShortValue() { baseDescription.appendValue(Short.valueOf("2")); assertEquals("<2s>", result.toString()); } public void testBracketsAppendedLongValue() { baseDescription.appendValue(Long.valueOf("2")); assertEquals("<2L>", result.toString()); } public void testBracketsAppendedFloatValue() { baseDescription.appendValue(Float.valueOf("1.2")); assertEquals("<1.2F>", result.toString()); } public void testDescribesAppendedArrayValue() { baseDescription.appendValue(new String[] {"2", "3"}); assertEquals("[\"2\", \"3\"]", result.toString()); } public void testBracketsAppendedObjectValue() { final Object value = new Object(); baseDescription.appendValue(value); assertEquals("<" + value.toString() + ">", result.toString()); } public void testSafelyDescribesAppendedValueOfObjectWhoseToStringThrowsAnException() { final Object value = new Object() { @Override public String toString() { throw new UnsupportedOperationException(); } }; final String expected = value.getClass().getName() + "@" + Integer.toHexString(value.hashCode()); baseDescription.appendValue(value); assertEquals("<" + expected + ">", result.toString()); } } libhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/number/0000755000175000017500000000000012131006721026173 5ustar ebourgebourg././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/number/OrderingComparisonTest.javalibhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/number/OrderingComparisonTest.jav0000644000175000017500000000553211756010763033363 0ustar ebourgebourg/* Copyright (c) 2000-2009 hamcrest.org */ package org.hamcrest.number; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.Matcher; import java.math.BigDecimal; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsNot.not; import static org.hamcrest.number.OrderingComparison.*; public class OrderingComparisonTest extends AbstractMatcherTest { @Override protected Matcher createMatcher() { return greaterThan(1); } public void testDescription() { assertDescription("a value greater than <1>", greaterThan(1)); assertDescription("a value equal to or greater than <1>", greaterThanOrEqualTo(1)); assertDescription("a value equal to <1>", comparesEqualTo(1)); assertDescription("a value less than or equal to <1>", lessThanOrEqualTo(1)); assertDescription("a value less than <1>", lessThan(1)); } public void testMismatchDescriptions() { assertMismatchDescription("<0> was less than <1>", greaterThan(1), 0); assertMismatchDescription("<1> was equal to <1>", greaterThan(1), 1); assertMismatchDescription("<1> was greater than <0>", lessThan(0), 1); assertMismatchDescription("<2> was equal to <2>", lessThan(2), 2); } public void testComparesObjectsForGreaterThan() { assertThat(2, greaterThan(1)); assertThat(0, not(greaterThan(1))); } public void testComparesObjectsForLessThan() { assertThat(2, lessThan(3)); assertThat(0, lessThan(1)); } public void testComparesObjectsForEquality() { assertThat(3, comparesEqualTo(3)); assertThat("aa", comparesEqualTo("aa")); } public void testAllowsForInclusiveComparisons() { assertThat("less", 1, lessThanOrEqualTo(1)); assertThat("greater", 1, greaterThanOrEqualTo(1)); } public void testSupportsDifferentTypesOfComparableObjects() { assertThat(1.1, greaterThan(1.0)); assertThat("cc", greaterThan("bb")); } public void testComparesBigDecimalsWithDifferentScalesCorrectlyForIssue20() { assertThat(new BigDecimal("10.0"), greaterThanOrEqualTo(new BigDecimal("10"))); assertThat(new BigDecimal(10), greaterThanOrEqualTo(new BigDecimal("10.0"))); assertThat(new BigDecimal("2"), comparesEqualTo(new BigDecimal("2.000"))); } public void testComparesCustomTypesWhoseCompareToReturnsValuesGreaterThatOne() { assertThat(new CustomInt(5), lessThan(new CustomInt(10))); } private static final class CustomInt implements Comparable { private final int value; public CustomInt(int value) { this.value = value; } public int compareTo(CustomInt other) { return value - other.value; } } } libhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/number/BigDecimalCloseToTest.java0000644000175000017500000000331311761743635033173 0ustar ebourgebourgpackage org.hamcrest.number; import static org.hamcrest.number.BigDecimalCloseTo.closeTo; import java.math.BigDecimal; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.Matcher; public class BigDecimalCloseToTest extends AbstractMatcherTest { @Override protected Matcher createMatcher() { BigDecimal irrelevant = new BigDecimal("0.01"); return closeTo(irrelevant, irrelevant); } public void testEvaluatesToTrueIfArgumentIsEqualToABigDecimalWithinSomeError() { Matcher p = closeTo(new BigDecimal("1.0"), new BigDecimal("0.5")); assertTrue(p.matches(new BigDecimal("1.0"))); assertTrue(p.matches(new BigDecimal("0.5"))); assertTrue(p.matches(new BigDecimal("1.5"))); assertDoesNotMatch("too large", p, new BigDecimal("2.0")); assertMismatchDescription("<2.0> differed by <0.5>", p, new BigDecimal("2.0")); assertDoesNotMatch("number too small", p, new BigDecimal("0.0")); assertMismatchDescription("<0.0> differed by <0.5>", p, new BigDecimal("0.0")); } public void testEvaluatesToTrueIfArgumentHasDifferentScale() { Matcher p = closeTo(new BigDecimal("1.0"), new BigDecimal("0.5")); assertTrue(p.matches(new BigDecimal("1.000000"))); assertTrue(p.matches(new BigDecimal("0.500000"))); assertTrue(p.matches(new BigDecimal("1.500000"))); assertDoesNotMatch("too large", p, new BigDecimal("2.000000")); assertMismatchDescription("<2.000000> differed by <0.5>", p, new BigDecimal("2.000000")); assertDoesNotMatch("number too small", p, new BigDecimal("0.000000")); assertMismatchDescription("<0.000000> differed by <0.5>", p, new BigDecimal("0.000000")); } } libhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/number/IsCloseToTest.java0000644000175000017500000000164311753011774031563 0ustar ebourgebourg/* Copyright (c) 2000-2006 hamcrest.org */ package org.hamcrest.number; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.Matcher; import static org.hamcrest.number.IsCloseTo.closeTo; public class IsCloseToTest extends AbstractMatcherTest { @Override protected Matcher createMatcher() { double irrelevant = 0.1; return closeTo(irrelevant, irrelevant); } public void testEvaluatesToTrueIfArgumentIsEqualToADoubleValueWithinSomeError() { Matcher p = closeTo(1.0, 0.5); assertTrue(p.matches(1.0)); assertTrue(p.matches(0.5d)); assertTrue(p.matches(1.5d)); assertDoesNotMatch("too large", p, 2.0); assertMismatchDescription("<2.0> differed by <0.5>", p, 2.0); assertDoesNotMatch("number too small", p, 0.0); assertMismatchDescription("<0.0> differed by <0.5>", p, 0.0); } } libhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/MatcherAssertTest.java0000644000175000017500000000525711753011773031200 0ustar ebourgebourgpackage org.hamcrest; import junit.framework.TestCase; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsEqual.equalTo; public class MatcherAssertTest extends TestCase { public void testIncludesDescriptionOfTestedValueInErrorMessage() { String expected = "expected"; String actual = "actual"; String expectedMessage = "identifier\nExpected: \"expected\"\n but: was \"actual\""; try { assertThat("identifier", actual, equalTo(expected)); } catch (AssertionError e) { assertTrue(e.getMessage().startsWith(expectedMessage)); return; } fail("should have failed"); } public void testDescriptionCanBeElided() { String expected = "expected"; String actual = "actual"; String expectedMessage = "\nExpected: \"expected\"\n but: was \"actual\""; try { assertThat(actual, equalTo(expected)); } catch (AssertionError e) { assertTrue(e.getMessage().startsWith(expectedMessage)); return; } fail("should have failed"); } public void testCanTestBooleanDirectly() { assertThat("success reason message", true); try { assertThat("failing reason message", false); } catch (AssertionError e) { assertEquals("failing reason message", e.getMessage()); return; } fail("should have failed"); } public void testIncludesMismatchDescription() { Matcher matcherWithCustomMismatchDescription = new BaseMatcher() { @Override public boolean matches(Object item) { return false; } @Override public void describeTo(Description description) { description.appendText("Something cool"); } @Override public void describeMismatch(Object item, Description mismatchDescription) { mismatchDescription.appendText("Not cool"); } }; String expectedMessage = "\nExpected: Something cool\n but: Not cool"; try { assertThat("Value", matcherWithCustomMismatchDescription); fail("should have failed"); } catch (AssertionError e) { assertEquals(expectedMessage, e.getMessage()); } } public void testCanAssertSubtypes() { Integer aSub = new Integer(1); Number aSuper = aSub; assertThat(aSub, equalTo(aSuper)); } } libhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/AbstractMatcherTest.java0000644000175000017500000000332211753011773031471 0ustar ebourgebourg/* Copyright (c) 2000-2006 hamcrest.org */ package org.hamcrest; import junit.framework.TestCase; import org.junit.Assert; public abstract class AbstractMatcherTest extends TestCase { /** * Create an instance of the Matcher so some generic safety-net tests can be run on it. */ protected abstract Matcher createMatcher(); public static void assertMatches(String message, Matcher c, T arg) { Assert.assertTrue(message, c.matches(arg)); } public static void assertDoesNotMatch(String message, Matcher c, T arg) { Assert.assertFalse(message, c.matches(arg)); } public static void assertDescription(String expected, Matcher matcher) { Description description = new StringDescription(); description.appendDescriptionOf(matcher); Assert.assertEquals("Expected description", expected, description.toString().trim()); } public static void assertMismatchDescription(String expected, Matcher matcher, T arg) { Assert.assertFalse("Precondtion: Matcher should not match item.", matcher.matches(arg)); Description description = new StringDescription(); matcher.describeMismatch(arg, description); Assert.assertEquals("Expected mismatch description", expected, description.toString().trim()); } public void testIsNullSafe() { // should not throw a NullPointerException createMatcher().matches(null); } public void testCopesWithUnknownTypes() { // should not throw ClassCastException createMatcher().matches(new UnknownType()); } public static class UnknownType { } } libhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/beans/0000755000175000017500000000000012131006721025773 5ustar ebourgebourg././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/beans/SamePropertyValuesAsTest.javalibhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/beans/SamePropertyValuesAsTest.ja0000644000175000017500000000674611753011773033276 0ustar ebourgebourg/* Copyright (c) 2000-2008 hamcrest.org */ package org.hamcrest.beans; import static org.hamcrest.beans.SamePropertyValuesAs.samePropertyValuesAs; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.Matcher; public class SamePropertyValuesAsTest extends AbstractMatcherTest { private static final Value aValue = new Value("expected"); private static final ExampleBean expectedBean = new ExampleBean("same", 1, aValue); private static final ExampleBean actualBean = new ExampleBean("same", 1, aValue); @Override protected Matcher createMatcher() { return samePropertyValuesAs(expectedBean); } public void testReportsMatchWhenAllPropertiesMatch() { assertMatches("matched properties", samePropertyValuesAs(expectedBean), actualBean); } public void testReportsMismatchWhenActualTypeIsNotAssignableToExpectedType() { assertMismatchDescription("is incompatible type: ExampleBean", samePropertyValuesAs((Object)aValue), actualBean); } public void testReportsMisatchOnFirstPropertyDifference() { assertMismatchDescription("string was \"different\"", samePropertyValuesAs(expectedBean), new ExampleBean("different", 1, aValue)); assertMismatchDescription("int was <2>", samePropertyValuesAs(expectedBean), new ExampleBean("same", 2, aValue)); assertMismatchDescription("value was ", samePropertyValuesAs(expectedBean), new ExampleBean("same", 1, new Value("other"))); } public void testMatchesBeansWithInheritanceButNoExtraProperties() { assertMatches("sub type with same properties", samePropertyValuesAs(expectedBean), new SubBeanWithNoExtraProperties("same", 1, aValue)); } public void testRejectsSubTypeThatHasExtraProperties() { assertMismatchDescription("has extra properties called [extra]", samePropertyValuesAs(expectedBean), new SubBeanWithExtraProperty("same", 1, aValue)); } public void testDescribesItself() { assertDescription("same property values as ExampleBean [int: <1>, string: \"same\", value: ]", samePropertyValuesAs(expectedBean)); } public static class Value { public Value(Object value) { this.value = value; } public final Object value; @Override public String toString() { return "Value " + value; } } public static class ExampleBean { private String stringProperty; private int intProperty; private Value valueProperty; public ExampleBean(String stringProperty, int intProperty, Value valueProperty) { this.stringProperty = stringProperty; this.intProperty = intProperty; this.valueProperty = valueProperty; } public String getString() { return stringProperty; } public int getInt() { return intProperty; } public Value getValue() { return valueProperty; } } public static class SubBeanWithNoExtraProperties extends ExampleBean { public SubBeanWithNoExtraProperties(String stringProperty, int intProperty, Value valueProperty) { super(stringProperty, intProperty, valueProperty); } } public static class SubBeanWithExtraProperty extends ExampleBean { public SubBeanWithExtraProperty(String stringProperty, int intProperty, Value valueProperty) { super(stringProperty, intProperty, valueProperty); } public String getExtra() { return "extra"; } } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/beans/HasPropertyWithValueTest.javalibhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/beans/HasPropertyWithValueTest.ja0000644000175000017500000001074711753011773033305 0ustar ebourgebourg/* Copyright (c) 2000-20010 hamcrest.org */ package org.hamcrest.beans; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.beans.HasPropertyWithValue.hasProperty; import static org.hamcrest.core.IsAnything.anything; import static org.hamcrest.core.IsEqual.equalTo; import java.beans.IntrospectionException; import java.beans.PropertyDescriptor; import java.beans.SimpleBeanInfo; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.StringDescription; import org.hamcrest.core.IsEqual; /** * @author Iain McGinniss * @author Nat Pryce * @author Steve Freeman * @since 1.1.0 */ public class HasPropertyWithValueTest extends AbstractMatcherTest { private final BeanWithoutInfo shouldMatch = new BeanWithoutInfo("is expected"); private final BeanWithoutInfo shouldNotMatch = new BeanWithoutInfo("not expected"); private final BeanWithInfo beanWithInfo = new BeanWithInfo("with info"); @Override protected Matcher createMatcher() { return hasProperty("irrelevant", anything()); } public void testMatchesInfolessBeanWithMatchedNamedProperty() { assertMatches("with property", hasProperty("property", equalTo("is expected")), shouldMatch); assertMismatchDescription("property 'property' was \"not expected\"", hasProperty("property", equalTo("is expected")), shouldNotMatch); } public void testMatchesBeanWithInfoWithMatchedNamedProperty() { assertMatches("with bean info", hasProperty("property", equalTo("with info")), beanWithInfo); assertMismatchDescription("property 'property' was \"with info\"", hasProperty("property", equalTo("without info")), beanWithInfo); } public void testDoesNotMatchInfolessBeanWithoutMatchedNamedProperty() { assertMismatchDescription("No property \"nonExistentProperty\"", hasProperty("nonExistentProperty", anything()), shouldNotMatch); } public void testDoesNotMatchWriteOnlyProperty() { assertMismatchDescription("property \"writeOnlyProperty\" is not readable", hasProperty("writeOnlyProperty", anything()), shouldNotMatch); } public void testDescribeTo() { assertDescription("hasProperty(\"property\", )", hasProperty("property", equalTo(true))); } public void testMatchesPropertyAndValue() { assertMatches("property with value", hasProperty( "property", anything()), beanWithInfo); } public void testDoesNotWriteMismatchIfPropertyMatches() { Description description = new StringDescription(); hasProperty( "property", anything()).describeMismatch(beanWithInfo, description); assertEquals("Expected mismatch description", "", description.toString()); } public void testDescribesMissingPropertyMismatch() { assertMismatchDescription("No property \"honk\"", hasProperty( "honk", anything()), shouldNotMatch); } public void testCanAccessAnAnonymousInnerClass() { class X implements IX { @Override public int getTest() { return 1; } } assertThat(new X(), HasPropertyWithValue.hasProperty("test", IsEqual.equalTo(1))); } interface IX { int getTest(); } public static class BeanWithoutInfo { private String property; public BeanWithoutInfo(String property) { this.property = property; } public String getProperty() { return property; } public void setProperty(String property) { this.property = property; } public void setWriteOnlyProperty(@SuppressWarnings("unused") float property) { } @Override public String toString() { return "[Person: " + property + "]"; } } public static class BeanWithInfo { private final String propertyValue; public BeanWithInfo(String propertyValue) { this.propertyValue = propertyValue; } public String property() { return propertyValue; } } public static class BeanWithInfoBeanInfo extends SimpleBeanInfo { @Override public PropertyDescriptor[] getPropertyDescriptors() { try { return new PropertyDescriptor[] { new PropertyDescriptor("property", BeanWithInfo.class, "property", null) }; } catch (IntrospectionException e) { throw new RuntimeException("Introspection exception: " + e.getMessage()); } } } } libhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/beans/HasPropertyTest.java0000644000175000017500000000236711767724174032015 0ustar ebourgebourg/* Copyright (c) 2000-2006 hamcrest.org */ package org.hamcrest.beans; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.beans.HasProperty.hasProperty; import static org.hamcrest.core.IsNot.not; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.Matcher; /** * @author Iain McGinniss * @author Nat Pryce * @author Steve Freeman * @since 1.1.0 */ public class HasPropertyTest extends AbstractMatcherTest { private final HasPropertyWithValueTest.BeanWithoutInfo bean = new HasPropertyWithValueTest.BeanWithoutInfo("a bean"); @Override protected Matcher createMatcher() { return hasProperty("irrelevant"); } public void testReturnsTrueIfPropertyExists() { assertThat(bean, hasProperty("writeOnlyProperty")); } public void testReturnsFalseIfPropertyDoesNotExist() { final Matcher hasProperty = hasProperty("aNonExistentProp"); assertThat(bean, not(hasProperty)); assertMismatchDescription("no \"aNonExistentProp\" in <[Person: a bean]>", hasProperty, bean); } public void testDescribeTo() { assertDescription("hasProperty(\"property\")", hasProperty("property")); } } libhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/collection/0000755000175000017500000000000012131006721027036 5ustar ebourgebourg././@LongLink0000000000000000000000000000016600000000000011570 Lustar rootrootlibhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/collection/IsIterableContainingInAnyOrderTest.javalibhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/collection/IsIterableContainingIn0000644000175000017500000000454111753011774033326 0ustar ebourgebourgpackage org.hamcrest.collection; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.Matcher; import org.hamcrest.collection.IsIterableContainingInOrderTest.WithValue; import java.util.Collections; import static java.util.Arrays.asList; import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder; import static org.hamcrest.collection.IsIterableContainingInOrderTest.make; import static org.hamcrest.collection.IsIterableContainingInOrderTest.value; public class IsIterableContainingInAnyOrderTest extends AbstractMatcherTest { @Override protected Matcher createMatcher() { return containsInAnyOrder(1, 2); } public void testMatchesSingleItemIterable() { assertMatches("single item", containsInAnyOrder(1), asList(1)); } public void testDoesNotMatchEmpty() { assertMismatchDescription("No item matches: <1>, <2> in []", containsInAnyOrder(1, 2), Collections.emptyList()); } public void testMatchesIterableOutOfOrder() { assertMatches("Out of order", containsInAnyOrder(1, 2), asList(2, 1)); } public void testMatchesIterableInOrder() { assertMatches("In order", containsInAnyOrder(1, 2), asList(1, 2)); } public void testDoesNotMatchIfOneOfMultipleElementsMismatches() { assertMismatchDescription("Not matched: <4>", containsInAnyOrder(1, 2, 3), asList(1, 2, 4)); } @SuppressWarnings("unchecked") public void testDoesNotMatchIfThereAreMoreElementsThanMatchers() { Matcher> helpTheCompilerOut = containsInAnyOrder(value(1), value(3)); assertMismatchDescription("Not matched: ", helpTheCompilerOut, asList(make(1), make(2), make(3))); } public void testDoesNotMatchIfThereAreMoreMatchersThanElements() { assertMismatchDescription("No item matches: <4> in [<1>, <2>, <3>]", containsInAnyOrder(1, 2, 3, 4), asList(1, 2, 3)); } public void testHasAReadableDescription() { assertDescription("iterable over [<1>, <2>] in any order", containsInAnyOrder(1, 2)); } public void testDoesNotMatchIfSingleItemMismatches() throws Exception { assertMismatchDescription("Not matched: ", containsInAnyOrder(value(4)), asList(make(3))); } } ././@LongLink0000000000000000000000000000015400000000000011565 Lustar rootrootlibhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/collection/IsCollectionWithSizeTest.javalibhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/collection/IsCollectionWithSizeTe0000644000175000017500000000615511753011774033354 0ustar ebourgebourgpackage org.hamcrest.collection; import static java.util.Arrays.asList; import java.util.ArrayList; import java.util.List; import java.util.Collection; import static org.hamcrest.collection.IsCollectionWithSize.hasSize; import static org.hamcrest.core.IsEqual.equalTo; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.Matcher; import org.hamcrest.MatcherAssert; public class IsCollectionWithSizeTest extends AbstractMatcherTest { @Override protected Matcher createMatcher() { return hasSize(7); } public void testMatchesWhenSizeIsCorrect() { assertMatches("correct size", hasSize(equalTo(2)), asList(null, null)); assertMismatchDescription("collection size was <3>", hasSize(equalTo(2)), asList(null, null, null)); } public void testMatchesCollectionWhenSizeIsCorrectUsingObjectElementType() { Collection list = asList(null, null); assertMatches("correct size", hasSize(equalTo(2)), list); assertMismatchDescription("collection size was <2>", hasSize(equalTo(3)), list); } public void testMatchesCollectionWhenSizeIsCorrectUsingStringElementType() { Collection list = asList("a", "b"); assertMatches("correct size", hasSize(equalTo(2)), list); assertMismatchDescription("collection size was <2>", hasSize(equalTo(3)), list); } public void testMatchesCollectionWhenSizeIsCorrectUsingWildcardElementType() { Collection list = asList("a", "b"); assertMatches("correct size", hasSize(equalTo(2)), list); assertMismatchDescription("collection size was <2>", hasSize(equalTo(3)), list); } public void testMatchesListWhenSizeIsCorrectUsingObjectElementType() { List list = asList(null, null); assertMatches("correct size", hasSize(equalTo(2)), list); assertMismatchDescription("collection size was <2>", hasSize(equalTo(3)), list); } public void testMatchesListWhenSizeIsCorrectUsingStringElementType() { List list = asList("a", "b"); assertMatches("correct size", hasSize(equalTo(2)), list); assertMismatchDescription("collection size was <2>", hasSize(equalTo(3)), list); } public void testMatchesListWhenSizeIsCorrectUsingWildcardElementType() { List list = asList("a", "b"); assertMatches("correct size", hasSize(equalTo(2)), list); assertMismatchDescription("collection size was <2>", hasSize(equalTo(3)), list); } public void testProvidesConvenientShortcutForHasSizeEqualTo() { assertMatches("correct size", hasSize(2), asList(null, null)); assertMismatchDescription("collection size was <3>", hasSize(2), asList(null, null, null)); } public void testHasAReadableDescription() { assertDescription("a collection with size <3>", hasSize(equalTo(3))); } public void testCompilesWithATypedCollection() { // To prove Issue 43 ArrayList arrayList = new ArrayList(); MatcherAssert.assertThat(arrayList, hasSize(0)); } } ././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootlibhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/collection/IsArrayContainingInOrderTest.javalibhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/collection/IsArrayContainingInOrd0000644000175000017500000000322411753011773033316 0ustar ebourgebourgpackage org.hamcrest.collection; import static org.hamcrest.collection.IsArrayContainingInOrder.arrayContaining; import static org.hamcrest.core.IsEqual.equalTo; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.Matcher; public class IsArrayContainingInOrderTest extends AbstractMatcherTest { @SuppressWarnings("unchecked") @Override protected Matcher createMatcher() { return arrayContaining(equalTo(1), equalTo(2)); } @SuppressWarnings("unchecked") public void testHasAReadableDescription() { assertDescription("[<1>, <2>]", arrayContaining(equalTo(1), equalTo(2))); } public void testMatchesItemsInOrder() { assertMatches("in order", arrayContaining(1, 2, 3), new Integer[] {1, 2, 3}); assertMatches("single", arrayContaining(1), new Integer[] {1}); } @SuppressWarnings("unchecked") public void testAppliesMatchersInOrder() { assertMatches("in order", arrayContaining(equalTo(1), equalTo(2), equalTo(3)), new Integer[] {1, 2, 3}); assertMatches("single", arrayContaining(equalTo(1)), new Integer[] {1}); } public void testMismatchesItemsInOrder() { Matcher matcher = arrayContaining(1, 2, 3); assertMismatchDescription("was null", matcher, null); assertMismatchDescription("No item matched: <1>", matcher, new Integer[] {}); assertMismatchDescription("No item matched: <2>", matcher, new Integer[] {1}); assertMismatchDescription("item 0: was <4>", matcher, new Integer[] {4,3,2,1}); assertMismatchDescription("item 2: was <4>", matcher, new Integer[] {1,2, 4}); } } libhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/collection/IsArrayTest.java0000644000175000017500000000304111753011774032126 0ustar ebourgebourgpackage org.hamcrest.collection; import static org.hamcrest.collection.IsArray.array; import static org.hamcrest.core.IsEqual.equalTo; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.Matcher; @SuppressWarnings("unchecked") public class IsArrayTest extends AbstractMatcherTest { @Override protected Matcher createMatcher() { return array(equalTo("irrelevant")); } public void testMatchesAnArrayThatMatchesAllTheElementMatchers() { assertMatches("should match array with matching elements", array(equalTo("a"), equalTo("b"), equalTo("c")), new String[]{"a", "b", "c"}); } public void testDoesNotMatchAnArrayWhenElementsDoNotMatch() { assertDoesNotMatch("should not match array with different elements", array(equalTo("a"), equalTo("b")), new String[]{"b", "c"}); } public void testDoesNotMatchAnArrayOfDifferentSize() { assertDoesNotMatch("should not match larger array", array(equalTo("a"), equalTo("b")), new String[]{"a", "b", "c"}); assertDoesNotMatch("should not match smaller array", array(equalTo("a"), equalTo("b")), new String[]{"a"}); } public void testDoesNotMatchNull() { assertDoesNotMatch("should not match null", array(equalTo("a")), null); } public void testHasAReadableDescription() { assertDescription("[\"a\", \"b\"]", array(equalTo("a"), equalTo("b"))); } } ././@LongLink0000000000000000000000000000016300000000000011565 Lustar rootrootlibhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/collection/IsIterableContainingInOrderTest.javalibhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/collection/IsIterableContainingIn0000644000175000017500000000543211753011774033326 0ustar ebourgebourgpackage org.hamcrest.collection; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.FeatureMatcher; import org.hamcrest.Matcher; import java.util.ArrayList; import java.util.List; import static java.util.Arrays.asList; import static org.hamcrest.collection.IsIterableContainingInOrder.contains; import static org.hamcrest.core.IsEqual.equalTo; @SuppressWarnings("unchecked") public class IsIterableContainingInOrderTest extends AbstractMatcherTest { // temporary hack until the Java type system works private final Matcher> contains123 = contains(value(1), value(2), value(3)); @Override protected Matcher createMatcher() { return contains(1, 2); } public void testMatchingSingleItemIterable() throws Exception { assertMatches("Single item iterable", contains(1), asList(1)); } public void testMatchingMultipleItemIterable() throws Exception { assertMatches("Multiple item iterable", contains(1, 2, 3), asList(1, 2, 3)); } public void testDoesNotMatchWithMoreElementsThanExpected() throws Exception { assertMismatchDescription("Not matched: <4>", contains(1, 2, 3), asList(1, 2, 3, 4)); } public void testDoesNotMatchWithFewerElementsThanExpected() throws Exception { List valueList = asList(make(1), make(2)); assertMismatchDescription("No item matched: value with <3>", contains123, valueList); } public void testDoesNotMatchIfSingleItemMismatches() throws Exception { assertMismatchDescription("item 0: value was <3>", contains(value(4)), asList(make(3))); } public void testDoesNotMatchIfOneOfMultipleItemsMismatch() throws Exception { assertMismatchDescription("item 2: value was <4>", contains123, asList(make(1), make(2), make(4))); } public void testDoesNotMatchEmptyIterable() throws Exception { assertMismatchDescription("No item matched: value with <4>", contains(value(4)), new ArrayList()); } public void testHasAReadableDescription() { assertDescription("iterable containing [<1>, <2>]", contains(1, 2)); } public static class WithValue { private final int value; public WithValue(int value) { this.value = value; } public int getValue() { return value; } @Override public String toString() { return "WithValue " + value; } } public static WithValue make(int value) { return new WithValue(value); } public static Matcher value(int value) { return new FeatureMatcher(equalTo(value), "value with", "value") { @Override protected Integer featureValueOf(WithValue actual) { return actual.getValue(); } }; } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/collection/IsArrayWithSizeTest.javalibhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/collection/IsArrayWithSizeTest.ja0000644000175000017500000000253611753011774033276 0ustar ebourgebourgpackage org.hamcrest.collection; import static org.hamcrest.collection.IsArrayWithSize.arrayWithSize; import static org.hamcrest.collection.IsArrayWithSize.emptyArray; import static org.hamcrest.core.IsEqual.equalTo; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.Matcher; public class IsArrayWithSizeTest extends AbstractMatcherTest { @Override protected Matcher createMatcher() { return arrayWithSize(equalTo(2)); } public void testMatchesWhenSizeIsCorrect() { assertMatches("correct size", arrayWithSize(equalTo(3)), new Object[] {1, 2, 3}); assertDoesNotMatch("incorrect size", arrayWithSize(equalTo(2)), new Object[] {1, 2, 3}); } public void testProvidesConvenientShortcutForArrayWithSizeEqualTo() { assertMatches("correct size", arrayWithSize(3), new Object[] {1, 2, 3}); assertDoesNotMatch("incorrect size", arrayWithSize(2), new Object[] {1, 2, 3}); } public void testEmptyArray() { assertMatches("correct size", emptyArray(), new Object[] {}); assertDoesNotMatch("incorrect size", emptyArray(), new Object[] {1}); } public void testHasAReadableDescription() { assertDescription("an array with size <3>", arrayWithSize(equalTo(3))); assertDescription("an empty array", emptyArray()); } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/collection/IsMapContainingTest.javalibhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/collection/IsMapContainingTest.ja0000644000175000017500000000423511753011774033256 0ustar ebourgebourgpackage org.hamcrest.collection; import static org.hamcrest.collection.IsMapContaining.hasEntry; import static org.hamcrest.core.IsAnything.anything; import static org.hamcrest.core.IsEqual.equalTo; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.Matcher; import java.util.Map; import java.util.TreeMap; public class IsMapContainingTest extends AbstractMatcherTest { @Override protected Matcher createMatcher() { return IsMapContaining.hasEntry("irrelevant", "irrelevant"); } public void testMatchesMapContainingMatchingKeyAndValue() { Map map = new TreeMap(); map.put("a", 1); map.put("b", 2); assertMatches("matcherA", hasEntry(equalTo("a"), equalTo(1)), map); assertMatches("matcherB", hasEntry(equalTo("b"), equalTo(2)), map); assertMismatchDescription("map was [, ]", hasEntry(equalTo("c"), equalTo(3)), map); } // no longer compiles. SF // public void testMatchesMapContainingMatchingKeyAndValueWithoutGenerics() { // Map map = new HashMap(); // map.put("a", 1); // map.put("b", 2); // // assertMatches("matcherA", hasEntry(equalTo("a"), equalTo(1)), map); // assertMatches("matcherB", hasEntry(equalTo("b"), equalTo(2)), map); // assertDoesNotMatch("matcherC", hasEntry(equalTo("c"), equalTo(3)), map); // } // public void testDoesNotMatchNull() { assertMismatchDescription("was null", hasEntry(anything(), anything()), null); } public void testHasReadableDescription() { assertDescription("map containing [\"a\"-><2>]", hasEntry(equalTo("a"), (equalTo(2)))); } // Remaining code no longer compiles, thanks to generics. I think that's a good thing, but // I still need to investigate how this behaves with code that doesn't use generics. // I expect ClassCastExceptions will be thrown. // -Joe. // public void testDoesNotMatchAnObjectThatIsNotAMap() { // assertDoesNotMatch("should not matches a string", // mapContaining(ANYTHING, ANYTHING), "not a map"); // } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootlibhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/collection/IsEmptyCollectionTest.javalibhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/collection/IsEmptyCollectionTest.0000644000175000017500000000253111767720656033336 0ustar ebourgebourgpackage org.hamcrest.collection; import java.util.ArrayList; import java.util.Collection; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.Matcher; import static java.util.Arrays.asList; import static org.hamcrest.collection.IsEmptyCollection.empty; import static org.hamcrest.core.Is.is; public class IsEmptyCollectionTest extends AbstractMatcherTest { @Override protected Matcher> createMatcher() { return empty(); } public void testMatchesAnEmptyCollection() { assertMatches("empty collection", createMatcher(), emptyCollection()); } public void testDoesNotMatchACollectionWithAnItem() { assertMismatchDescription("<[one, three]>", is(createMatcher()), collectionOfValues()); } public void testHasAReadableDescription() { assertDescription("an empty collection", createMatcher()); } public void testCompiles() { needs(IsEmptyCollection.emptyCollectionOf(String.class)); } private void needs(@SuppressWarnings("unused") Matcher> bar) { } private static Collection collectionOfValues() { return new ArrayList(asList("one", "three")); } private static Collection emptyCollection() { return new ArrayList(); } }././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootlibhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/collection/IsMapContainingKeyTest.javalibhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/collection/IsMapContainingKeyTest0000644000175000017500000000510011753011774033326 0ustar ebourgebourgpackage org.hamcrest.collection; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.Matcher; import java.util.HashMap; import java.util.Map; import java.util.TreeMap; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.collection.IsMapContaining.hasKey; public class IsMapContainingKeyTest extends AbstractMatcherTest { @Override protected Matcher createMatcher() { return hasKey("foo"); } public void testMatchesSingletonMapContainingKey() { Map map = new HashMap(); map.put("a", 1); assertMatches("Matches single key", hasKey("a"), map); } public void testMatchesMapContainingKey() { Map map = new HashMap(); map.put("a", 1); map.put("b", 2); map.put("c", 3); assertMatches("Matches a", hasKey("a"), map); assertMatches("Matches c", hasKey("c"), map); } // No longer compiles // public void testMatchesMapContainingKeyWithNoGenerics() { // Map map = new HashMap(); // map.put("a", 1); // map.put("b", 2); // map.put("c", 3); // // assertMatches("Matches a", hasKey("a"), map); // assertMatches("Matches c", hasKey("c"), map); // } public void testMatchesMapContainingKeyWithIntegerKeys() throws Exception { Map map = new HashMap(); map.put(1, "A"); map.put(2, "B"); assertThat(map, hasKey(Integer.valueOf(1))); } public void testMatchesMapContainingKeyWithNumberKeys() throws Exception { Map map = new HashMap(); map.put(1, "A"); map.put(2, "B"); assertThat(map, hasKey((Number)1)); // TODO: work out the correct sprinkling of wildcards to get this to work! // assertThat(map, hasKey(1)); } public void testHasReadableDescription() { assertDescription("map containing [\"a\"->ANYTHING]", hasKey("a")); } public void testDoesNotMatchEmptyMap() { assertMismatchDescription("map was []", hasKey("Foo"), new HashMap()); } public void testDoesNotMatchMapMissingKey() { Map map = new TreeMap(); map.put("a", 1); map.put("b", 2); map.put("c", 3); assertMismatchDescription("map was [, , ]", hasKey("d"), map); } } ././@LongLink0000000000000000000000000000016300000000000011565 Lustar rootrootlibhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/collection/IsArrayContainingInAnyOrderTest.javalibhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/collection/IsArrayContainingInAny0000644000175000017500000000377611753011773033335 0ustar ebourgebourgpackage org.hamcrest.collection; import static org.hamcrest.collection.IsArrayContainingInAnyOrder.arrayContainingInAnyOrder; import static org.hamcrest.core.IsEqual.equalTo; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.Matcher; public class IsArrayContainingInAnyOrderTest extends AbstractMatcherTest { @SuppressWarnings("unchecked") @Override protected Matcher createMatcher() { return arrayContainingInAnyOrder(equalTo(1), equalTo(2)); } @SuppressWarnings("unchecked") public void testHasAReadableDescription() { assertDescription("[<1>, <2>] in any order", arrayContainingInAnyOrder(equalTo(1), equalTo(2))); assertDescription("[<1>, <2>] in any order", arrayContainingInAnyOrder(1, 2)); } public void testMatchesItemsInAnyOrder() { assertMatches("in order", arrayContainingInAnyOrder(1, 2, 3), new Integer[] {1, 2, 3}); assertMatches("out of order", arrayContainingInAnyOrder(1, 2, 3), new Integer[] {3, 2, 1}); assertMatches("single", arrayContainingInAnyOrder(1), new Integer[] {1}); } @SuppressWarnings("unchecked") public void testAppliesMatchersInAnyOrder() { assertMatches("in order", arrayContainingInAnyOrder(equalTo(1), equalTo(2), equalTo(3)), new Integer[] {1, 2, 3}); assertMatches("out of order", arrayContainingInAnyOrder(equalTo(1), equalTo(2), equalTo(3)), new Integer[] {3, 2, 1}); assertMatches("single", arrayContainingInAnyOrder(equalTo(1)), new Integer[] {1}); } public void testMismatchesItemsInAnyOrder() { Matcher matcher = arrayContainingInAnyOrder(1, 2, 3); assertMismatchDescription("was null", matcher, null); assertMismatchDescription("No item matches: <1>, <2>, <3> in []", matcher, new Integer[] {}); assertMismatchDescription("No item matches: <2>, <3> in [<1>]", matcher, new Integer[] {1}); assertMismatchDescription("Not matched: <4>", matcher, new Integer[] {4,3,2,1}); } } libhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/collection/IsInTest.java0000644000175000017500000000251611753011774031424 0ustar ebourgebourgpackage org.hamcrest.collection; import java.util.Arrays; import java.util.Collection; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.Matcher; import org.hamcrest.StringDescription; public class IsInTest extends AbstractMatcherTest { String[] elements = {"a", "b", "c"}; @Override protected Matcher createMatcher() { return new IsIn(elements); } public void testReturnsTrueIfArgumentIsInCollection() { Collection collection = Arrays.asList(elements); Matcher isIn = new IsIn(collection); assertMatches("a", isIn, "a"); assertMatches("b", isIn, "b"); assertMatches("c", isIn, "c"); assertDoesNotMatch("d", isIn, "d"); } public void testReturnsTrueIfArgumentIsInArray() { Matcher isIn = new IsIn(elements); assertMatches("a", isIn, "a"); assertMatches("b", isIn, "b"); assertMatches("c", isIn, "c"); assertDoesNotMatch("d", isIn, "d"); } public void testHasReadableDescription() { Matcher isIn = new IsIn(elements); assertEquals("description", "one of {\"a\", \"b\", \"c\"}", StringDescription.toString(isIn)); } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/collection/IsEmptyIterableTest.javalibhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/collection/IsEmptyIterableTest.ja0000644000175000017500000000244711767720520033301 0ustar ebourgebourgpackage org.hamcrest.collection; import java.util.ArrayList; import java.util.Collection; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.Matcher; import static java.util.Arrays.asList; import static org.hamcrest.collection.IsEmptyIterable.emptyIterable; public class IsEmptyIterableTest extends AbstractMatcherTest { @Override protected Matcher> createMatcher() { return emptyIterable(); } public void testMatchesAnEmptyIterable() { assertMatches("empty iterable", createMatcher(), emptyCollection()); } public void testDoesNotMatchAnIterableWithItems() { assertDoesNotMatch("iterable with an item", createMatcher(), collectionOfValues()); } public void testHasAReadableDescription() { assertDescription("an empty iterable", createMatcher()); } public void testCompiles() { needs(IsEmptyIterable.emptyIterableOf(String.class)); } private void needs(@SuppressWarnings("unused") Matcher> bar) { } private static Collection collectionOfValues() { return new ArrayList(asList("one", "three")); } private static Collection emptyCollection() { return new ArrayList(); } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootlibhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/collection/IsIterableWithSizeTest.javalibhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/collection/IsIterableWithSizeTest0000644000175000017500000000233311753011774033351 0ustar ebourgebourgpackage org.hamcrest.collection; import static org.hamcrest.collection.IsIterableWithSize.iterableWithSize; import java.util.Arrays; import java.util.Collections; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.Matcher; public class IsIterableWithSizeTest extends AbstractMatcherTest { @Override protected Matcher createMatcher() { return iterableWithSize(7); } public void testMatchesEmptyIterable() throws Exception { assertMatches("Empty iterable", iterableWithSize(0), Collections.emptyList()); } public void testMatchingSingleItemIterable() throws Exception { assertMatches("Single item iterable", iterableWithSize(1), Arrays.asList(1)); } public void testMatchingMultipleItemIterable() throws Exception { assertMatches("Multiple item iterable", iterableWithSize(3), Arrays.asList(1, 2, 3)); } public void testDoesNotMatchIncorrectSize() throws Exception { assertDoesNotMatch("Incorrect size", iterableWithSize(3), Arrays.asList(1)); } public void testHasAReadableDescription() { assertDescription("an iterable with size <4>", iterableWithSize(4)); } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootlibhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/collection/IsArrayContainingTest.javalibhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/collection/IsArrayContainingTest.0000644000175000017500000000610211753011774033277 0ustar ebourgebourgpackage org.hamcrest.collection; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.Matcher; import static org.hamcrest.collection.IsArrayContaining.hasItemInArray; public class IsArrayContainingTest extends AbstractMatcherTest { @Override protected Matcher createMatcher() { return hasItemInArray("irrelevant"); } public void testMatchesAnArrayThatContainsAnElementMatchingTheGivenMatcher() { assertMatches("should matches array that contains 'a'", hasItemInArray("a"), new String[]{"a", "b", "c"}); } public void testDoesNotMatchAnArrayThatDoesntContainAnElementMatchingTheGivenMatcher() { assertDoesNotMatch("should not matches array that doesn't contain 'a'", hasItemInArray("a"), new String[]{"b", "c"}); assertDoesNotMatch("should not matches empty array", hasItemInArray("a"), new String[0]); } public void testDoesNotMatchNull() { assertDoesNotMatch("should not matches null", hasItemInArray("a"), null); } public void testHasAReadableDescription() { assertDescription("an array containing \"a\"", hasItemInArray("a")); } // Remaining code no longer compiles, thanks to generics. I think that's a good thing, but // I still need to investigate how this behaves with code that doesn't use generics. // I expect ClassCastExceptions will be thrown. // -Joe. // public void testDoesNotMatchObjectThatIsNotAnArray() { // assertDoesNotMatch("should not matches empty list", // arrayContaining("a"), "not a collection"); // } // public void testMatchesPrimitiveArrayElements() { // assertMatches("boolean", arrayContaining(true), new boolean[]{true, false}); // assertDoesNotMatch("boolean", arrayContaining(false), new boolean[]{false}); // // assertMatches("byte", arrayContaining((byte) 1), new byte[]{1, 2, 3}); // assertDoesNotMatch("byte", arrayContaining((byte) 0), new byte[]{1, 2, 3}); // // assertMatches("char", arrayContaining('a'), new char[]{'a', 'b', 'c'}); // assertDoesNotMatch("char", arrayContaining('z'), new char[]{'a', 'b', 'c'}); // // assertMatches("short", arrayContaining((short) 1), new short[]{1, 2, 3}); // assertDoesNotMatch("short", arrayContaining((short) 0), new short[]{1, 2, 3}); // // assertMatches("int", arrayContaining(1), new int[]{1, 2, 3}); // assertDoesNotMatch("int", arrayContaining(0), new int[]{1, 2, 3}); // // assertMatches("long", arrayContaining(1L), new long[]{1, 2, 3}); // assertDoesNotMatch("long", arrayContaining(0L), new long[]{1, 2, 3}); // // assertMatches("float", arrayContaining(1f), new float[]{1f, 2f, 3f}); // assertDoesNotMatch("float", arrayContaining(0f), new float[]{1f, 2f, 3f}); // // assertMatches("double", arrayContaining(1.0), new double[]{1.0, 2.0, 3.0}); // assertDoesNotMatch("double", arrayContaining(0.0), new double[]{1.0, 2.0, 3.0}); // } } ././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootlibhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/collection/IsCollectionContainingTest.javalibhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/collection/IsCollectionContaining0000644000175000017500000001017411753011774033402 0ustar ebourgebourgpackage org.hamcrest.collection; import static java.util.Arrays.asList; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsCollectionContaining.hasItem; import static org.hamcrest.core.IsCollectionContaining.hasItems; import static org.hamcrest.core.IsEqual.equalTo; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeDiagnosingMatcher; import org.hamcrest.core.IsCollectionContaining; import org.hamcrest.core.IsEqual; public class IsCollectionContainingTest extends AbstractMatcherTest { @Override protected Matcher createMatcher() { return hasItem(equalTo("irrelevant")); } public void testMatchesACollectionThatContainsAnElementMatchingTheGivenMatcher() { Matcher> itemMatcher = hasItem(equalTo("a")); assertMatches("should match list that contains 'a'", itemMatcher, asList("a", "b", "c")); } public void testDoesNotMatchCollectionThatDoesntContainAnElementMatchingTheGivenMatcher() { final Matcher> matcher1 = hasItem(mismatchable("a")); assertMismatchDescription("mismatched: b, mismatched: c", matcher1, asList("b", "c")); final Matcher> matcher2 = hasItem(equalTo("a")); assertMismatchDescription("", matcher2, new ArrayList()); } public void testDoesNotMatchNull() { assertDoesNotMatch("should not matches null", hasItem(equalTo("a")), null); } public void testHasAReadableDescription() { assertDescription("a collection containing \"a\"", hasItem(equalTo("a"))); } public void testCanMatchItemWhenCollectionHoldsSuperclass() // Issue 24 { final Set s = new HashSet(); s.add(Integer.valueOf(2)); assertThat(s, new IsCollectionContaining(new IsEqual(Integer.valueOf(2)))); assertThat(s, IsCollectionContaining.hasItem(Integer.valueOf(2))); } @SuppressWarnings("unchecked") public void testMatchesAllItemsInCollection() { final Matcher> matcher1 = hasItems(equalTo("a"), equalTo("b"), equalTo("c")); assertMatches("should match list containing all items", matcher1, asList("a", "b", "c")); final Matcher> matcher2 = hasItems("a", "b", "c"); assertMatches("should match list containing all items (without matchers)", matcher2, asList("a", "b", "c")); final Matcher> matcher3 = hasItems(equalTo("a"), equalTo("b"), equalTo("c")); assertMatches("should match list containing all items in any order", matcher3, asList("c", "b", "a")); final Matcher> matcher4 = hasItems(equalTo("a"), equalTo("b"), equalTo("c")); assertMatches("should match list containing all items plus others", matcher4, asList("e", "c", "b", "a", "d")); final Matcher> matcher5 = hasItems(equalTo("a"), equalTo("b"), equalTo("c")); assertDoesNotMatch("should not match list unless it contains all items", matcher5, asList("e", "c", "b", "d")); // 'a' missing } private static Matcher mismatchable(final String string) { return new TypeSafeDiagnosingMatcher() { @Override protected boolean matchesSafely(String item, Description mismatchDescription) { if (string.equals(item)) return true; mismatchDescription.appendText("mismatched: " + item); return false; } @Override public void describeTo(Description description) { description.appendText("mismatchable: " + string); } }; } } ././@LongLink0000000000000000000000000000015400000000000011565 Lustar rootrootlibhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/collection/IsMapContainingValueTest.javalibhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/collection/IsMapContainingValueTe0000644000175000017500000000262111753011774033310 0ustar ebourgebourgpackage org.hamcrest.collection; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.Matcher; import java.util.HashMap; import java.util.Map; import java.util.TreeMap; import static org.hamcrest.collection.IsMapContaining.hasValue; public class IsMapContainingValueTest extends AbstractMatcherTest { @Override protected Matcher createMatcher() { return hasValue("foo"); } public void testHasReadableDescription() { assertDescription("map containing [ANYTHING->\"a\"]", hasValue("a")); } public void testDoesNotMatchEmptyMap() { Map map = new HashMap(); assertMismatchDescription("map was []", hasValue(1), map); } public void testMatchesSingletonMapContainingValue() { Map map = new HashMap(); map.put("a", 1); assertMatches("Singleton map", hasValue(1), map); } public void testMatchesMapContainingValue() { Map map = new TreeMap(); map.put("a", 1); map.put("b", 2); map.put("c", 3); assertMatches("hasValue 1", hasValue(1), map); assertMatches("hasValue 3", hasValue(3), map); assertMismatchDescription("map was [, , ]", hasValue(4), map); } } libhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/integration/0000755000175000017500000000000012131006721027226 5ustar ebourgebourg././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/integration/JMock1AdapterTest.javalibhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/integration/JMock1AdapterTest.jav0000644000175000017500000000252711753011774033200 0ustar ebourgebourgpackage org.hamcrest.integration; import junit.framework.TestCase; import org.hamcrest.BaseMatcher; import org.hamcrest.Description; import static org.hamcrest.core.IsEqual.equalTo; import org.jmock.core.Constraint; public class JMock1AdapterTest extends TestCase { public static interface InterfaceToMock { void doStuff(String name, int number); } public void testAdaptsHamcrestMatcherToJMockConstraint() { Constraint jMockConstraint = new JMock1Adapter(equalTo("expected")); assertTrue("Should have matched", jMockConstraint.eval("expected")); assertFalse("Should not have matched", jMockConstraint.eval("unexpected")); } public void testDelegatesDescriptionToUnderlyingMatcher() { Constraint jMockConstraint = new JMock1Adapter(new BaseMatcher() { @Override public boolean matches(Object o) { return false; } @Override public void describeTo(Description description) { description.appendText("is like "); description.appendValue("cheese"); } }); StringBuffer buffer = new StringBuffer(); buffer = jMockConstraint.describeTo(buffer); assertEquals("is like \"cheese\"", buffer.toString()); } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootlibhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/integration/EasyMock2AdapterTest.javalibhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/integration/EasyMock2AdapterTest.0000644000175000017500000000256411753011774033211 0ustar ebourgebourgpackage org.hamcrest.integration; import junit.framework.TestCase; import org.easymock.IArgumentMatcher; import org.hamcrest.BaseMatcher; import org.hamcrest.Description; import static org.hamcrest.core.IsEqual.equalTo; public class EasyMock2AdapterTest extends TestCase { public static interface InterfaceToMock { void doStuff(String name, int number); } public void testAdaptsHamcrestMatcherToEasyMockArgumentsMatcher() { IArgumentMatcher easyMockMatcher = new EasyMock2Adapter(equalTo("expected")); assertTrue("Should have matched", easyMockMatcher.matches("expected")); assertFalse("Should not have matched", easyMockMatcher.matches("unexpected")); } public void testDelegatesDescriptionToUnderlyingMatcher() { IArgumentMatcher easyMockMatcher = new EasyMock2Adapter(new BaseMatcher() { @Override public boolean matches(Object o) { return false; } @Override public void describeTo(Description description) { description.appendText("is like "); description.appendValue("cheese"); } }); StringBuffer buffer = new StringBuffer(); easyMockMatcher.appendTo(buffer); assertEquals("is like \"cheese\"", buffer.toString()); } } libhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/BaseMatcherTest.java0000644000175000017500000000120211753011773030573 0ustar ebourgebourgpackage org.hamcrest; import junit.framework.TestCase; public class BaseMatcherTest extends TestCase { public void testDescribesItselfWithToStringMethod() { Matcher someMatcher = new BaseMatcher() { @Override public boolean matches(Object item) { throw new UnsupportedOperationException(); } @Override public void describeTo(Description description) { description.appendText("SOME DESCRIPTION"); } }; assertEquals("SOME DESCRIPTION", someMatcher.toString()); } } libhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/core/0000755000175000017500000000000012131006721025633 5ustar ebourgebourglibhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/core/IsSameTest.java0000644000175000017500000000253711756124063030542 0ustar ebourgebourg/* Copyright (c) 2000-2006 hamcrest.org */ package org.hamcrest.core; import static org.hamcrest.core.IsSame.theInstance; import static org.hamcrest.core.IsSame.sameInstance; import static org.hamcrest.core.IsNot.not; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.Matcher; import static org.hamcrest.MatcherAssert.assertThat; public class IsSameTest extends AbstractMatcherTest { @Override protected Matcher createMatcher() { return sameInstance("irrelevant"); } public void testEvaluatesToTrueIfArgumentIsReferenceToASpecifiedObject() { Object o1 = new Object(); Object o2 = new Object(); assertThat(o1, sameInstance(o1)); assertThat(o2, not(sameInstance(o1))); } public void testAlternativeFactoryMethodAlsoMatchesOnlyIfArgumentIsReferenceToASpecifiedObject() { Object o1 = new Object(); Object o2 = new Object(); assertThat(o1, theInstance(o1)); assertThat(o2, not(theInstance(o1))); } public void testReturnsReadableDescriptionFromToString() { assertDescription("sameInstance(\"ARG\")", sameInstance("ARG")); } public void testReturnsReadableDescriptionFromToStringWhenInitialisedWithNull() { assertDescription("sameInstance(null)", sameInstance(null)); } } libhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/core/SampleSubClass.java0000644000175000017500000000025111753011774031372 0ustar ebourgebourgpackage org.hamcrest.core; public class SampleSubClass extends SampleBaseClass { public SampleSubClass(String value) { super(value); } } libhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/core/DescribedAsTest.java0000644000175000017500000000336111753011774031526 0ustar ebourgebourg/* Copyright (c) 2000-2006 hamcrest.org */ package org.hamcrest.core; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.Matcher; import org.hamcrest.StringDescription; import static org.hamcrest.core.DescribedAs.describedAs; import static org.hamcrest.core.IsAnything.anything; import static org.hamcrest.core.IsEqual.equalTo; import static org.hamcrest.core.IsNot.not; public class DescribedAsTest extends AbstractMatcherTest { @Override protected Matcher createMatcher() { return describedAs("irrelevant", anything()); } public void testOverridesDescriptionOfOtherMatcherWithThatPassedToConstructor() { Matcher m1 = describedAs("m1 description", anything()); Matcher m2 = describedAs("m2 description", not(anything())); assertDescription("m1 description", m1); assertDescription("m2 description", m2); } public void testAppendsValuesToDescription() { Matcher m = describedAs("value 1 = %0, value 2 = %1", anything(), 33, 97); assertDescription("value 1 = <33>, value 2 = <97>", m); } public void testDelegatesMatchingToAnotherMatcher() { Matcher m1 = describedAs("irrelevant", anything()); Matcher m2 = describedAs("irrelevant", not(anything())); assertTrue(m1.matches(new Object())); assertFalse(m2.matches("hi")); } public void testDelegatesMismatchDescriptionToAnotherMatcher() { Matcher m1 = describedAs("irrelevant", equalTo(2)); StringDescription description = new StringDescription(); m1.describeMismatch(1, description); assertEquals("was <1>", description.toString()); } } libhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/core/IsInstanceOfTest.java0000644000175000017500000000373011753011774031703 0ustar ebourgebourg/* Copyright (c) 2000-2010 hamcrest.org */ package org.hamcrest.core; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.Matcher; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsInstanceOf.*; import static org.hamcrest.core.IsNot.not; public class IsInstanceOfTest extends AbstractMatcherTest { @Override protected Matcher createMatcher() { return instanceOf(Number.class); } public void testEvaluatesToTrueIfArgumentIsInstanceOfASpecificClass() { assertThat(1, instanceOf(Number.class)); assertThat(1.0, instanceOf(Number.class)); assertThat(null, not(instanceOf(Number.class))); assertThat(new Object(), not(instanceOf(Number.class))); } public void testHasAReadableDescription() { assertDescription("an instance of java.lang.Number", instanceOf(Number.class)); } public void testDecribesActualClassInMismatchMessage() { assertMismatchDescription("\"some text\" is a java.lang.String", instanceOf(Number.class), "some text"); } public void testMatchesPrimitiveTypes() { assertThat(true, any(boolean.class)); assertThat((byte)1, any(byte.class)); assertThat('x', any(char.class)); assertThat(5.0, any(double.class)); assertThat(5.0f, any(float.class)); assertThat(2, any(int.class)); assertThat(4L, any(long.class)); assertThat((short)1, any(short.class)); } public void testInstanceOfRequiresACastToReturnTheCorrectTypeForUseInJMock() { @SuppressWarnings("unused") Integer anInteger = (Integer)with(instanceOf(Integer.class)); } public void testAnyWillReturnTheCorrectTypeForUseInJMock() { @SuppressWarnings("unused") Integer anInteger = with(any(Integer.class)); } private static T with(@SuppressWarnings("unused") Matcher matcher) { return null; } } libhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/core/IsEqualTest.java0000644000175000017500000000711411753011774030721 0ustar ebourgebourg/* Copyright (c) 2000-2006 hamcrest.org */ package org.hamcrest.core; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.Matcher; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsEqual.equalTo; import static org.hamcrest.core.IsNot.not; public class IsEqualTest extends AbstractMatcherTest { @Override protected Matcher createMatcher() { return equalTo("irrelevant"); } public void testComparesObjectsUsingEqualsMethod() { assertThat("hi", equalTo("hi")); assertThat("bye", not(equalTo("hi"))); assertThat(1, equalTo(1)); assertThat(1, not(equalTo(2))); } public void testCanCompareNullValues() { assertThat(null, equalTo(null)); assertThat(null, not(equalTo("hi"))); assertThat("hi", not(equalTo(null))); } public void testHonoursIsEqualImplementationEvenWithNullValues() { Object alwaysEqual = new Object() { @Override public boolean equals(Object obj) { return true; } }; Object neverEqual = new Object() { @Override public boolean equals(Object obj) { return false; } }; assertThat(alwaysEqual, equalTo(null)); assertThat(neverEqual, not(equalTo(null))); } public void testComparesTheElementsOfAnObjectArray() { String[] s1 = {"a", "b"}; String[] s2 = {"a", "b"}; String[] s3 = {"c", "d"}; String[] s4 = {"a", "b", "c", "d"}; assertThat(s1, equalTo(s1)); assertThat(s2, equalTo(s1)); assertThat(s3, not(equalTo(s1))); assertThat(s4, not(equalTo(s1))); } public void testComparesArraysToNull() { assertThat(new String[]{"a", "b"}, not(equalTo(null))); assertThat(null, not(equalTo(new String[]{"a", "b"}))); } public void testComparesTheElementsOfAnArrayOfPrimitiveTypes() { int[] i1 = new int[]{1, 2}; int[] i2 = new int[]{1, 2}; int[] i3 = new int[]{3, 4}; int[] i4 = new int[]{1, 2, 3, 4}; assertThat(i1, equalTo(i1)); assertThat(i2, equalTo(i1)); assertThat(i3, not(equalTo(i1))); assertThat(i4, not(equalTo(i1))); } public void testRecursivelyTestsElementsOfArrays() { int[][] i1 = new int[][]{{1, 2}, {3, 4}}; int[][] i2 = new int[][]{{1, 2}, {3, 4}}; int[][] i3 = new int[][]{{5, 6}, {7, 8}}; int[][] i4 = new int[][]{{1, 2, 3, 4}, {3, 4}}; assertThat(i1, equalTo(i1)); assertThat(i2, equalTo(i1)); assertThat(i3, not(equalTo(i1))); assertThat(i4, not(equalTo(i1))); } public void testIncludesTheResultOfCallingToStringOnItsArgumentInTheDescription() { final String argumentDescription = "ARGUMENT DESCRIPTION"; Object argument = new Object() { @Override public String toString() { return argumentDescription; } }; assertDescription("<" + argumentDescription + ">", equalTo(argument)); } public void testReturnsAnObviousDescriptionIfCreatedWithANestedMatcherByMistake() { Matcher innerMatcher = equalTo("NestedMatcher"); assertDescription("<" + innerMatcher.toString() + ">", equalTo(innerMatcher)); } public void testReturnsGoodDescriptionIfCreatedWithNullReference() { assertDescription("null", equalTo(null)); } } libhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/core/CombinableTest.java0000644000175000017500000000401611753461214031405 0ustar ebourgebourgpackage org.hamcrest.core; import org.junit.Assert; import org.junit.Test; import static org.hamcrest.AbstractMatcherTest.assertMismatchDescription; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.CombinableMatcher.both; import static org.hamcrest.core.IsEqual.equalTo; import static org.hamcrest.core.IsNot.not; import static org.hamcrest.core.IsNull.notNullValue; import static org.hamcrest.number.OrderingComparison.greaterThan; import static org.junit.Assert.assertEquals; public class CombinableTest { private static final CombinableMatcher EITHER_3_OR_4 = CombinableMatcher.either(equalTo(3)).or(equalTo(4)); private static final CombinableMatcher NOT_3_AND_NOT_4 = CombinableMatcher.both(not(equalTo(3))).and(not(equalTo(4))); @Test public void bothAcceptsAndRejects() { assertThat(2, NOT_3_AND_NOT_4); assertThat(3, not(NOT_3_AND_NOT_4)); } @Test public void acceptsAndRejectsThreeAnds() { CombinableMatcher tripleAnd = NOT_3_AND_NOT_4.and(equalTo(2)); assertThat(2, tripleAnd); assertThat(3, not(tripleAnd)); } @Test public void bothDescribesItself() { assertEquals("(not <3> and not <4>)", NOT_3_AND_NOT_4.toString()); assertMismatchDescription("not <3> was <3>", NOT_3_AND_NOT_4, 3); } @Test public void eitherAcceptsAndRejects() { assertThat(3, EITHER_3_OR_4); assertThat(6, not(EITHER_3_OR_4)); } @Test public void acceptsAndRejectsThreeOrs() { final CombinableMatcher orTriple = EITHER_3_OR_4.or(greaterThan(10)); assertThat(11, orTriple); assertThat(9, not(orTriple)); } @Test public void eitherDescribesItself() { Assert.assertEquals("(<3> or <4>)", EITHER_3_OR_4.toString()); assertMismatchDescription("was <6>", EITHER_3_OR_4, 6); } @Test public void picksUpTypeFromLeftHandSideOfExpression() { assertThat("yellow", both(equalTo("yellow")).and(notNullValue())); } } libhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/core/AllOfTest.java0000644000175000017500000000434411767715345030367 0ustar ebourgebourg/* Copyright (c) 2000-2010 hamcrest.org */ package org.hamcrest.core; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.Matcher; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.AllOf.allOf; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsEqual.equalTo; import static org.hamcrest.core.IsNot.not; import static org.hamcrest.core.IsNull.notNullValue; import static org.hamcrest.core.StringStartsWith.startsWith; public class AllOfTest extends AbstractMatcherTest { @Override @SuppressWarnings("unchecked") protected Matcher createMatcher() { return allOf(IsEqual.equalTo("irrelevant")); } public void testEvaluatesToTheTheLogicalConjunctionOfTwoOtherMatchers() { assertThat("good", allOf(equalTo("good"), startsWith("good"))); assertThat("good", not(allOf(equalTo("bad"), equalTo("good")))); assertThat("good", not(allOf(equalTo("good"), equalTo("bad")))); assertThat("good", not(allOf(equalTo("bad"), equalTo("bad")))); } public void testEvaluatesToTheTheLogicalConjunctionOfManyOtherMatchers() { assertThat("good", allOf(equalTo("good"), equalTo("good"), equalTo("good"), equalTo("good"), equalTo("good"))); assertThat("good", not(allOf(equalTo("good"), equalTo("good"), equalTo("bad"), equalTo("good"), equalTo("good")))); } public void testSupportsMixedTypes() { final Matcher all = allOf( equalTo(new SampleBaseClass("bad")), is(notNullValue()), equalTo(new SampleBaseClass("good")), equalTo(new SampleSubClass("ugly"))); final Matcher negated = not(all); assertThat(new SampleSubClass("good"), negated); } public void testHasAReadableDescription() { assertDescription("(\"good\" and \"bad\" and \"ugly\")", allOf(equalTo("good"), equalTo("bad"), equalTo("ugly"))); } public void testMismatchDescriptionDescribesFirstFailingMatch() { assertMismatchDescription("\"good\" was \"bad\"", allOf(equalTo("bad"), equalTo("good")), "bad"); } } libhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/core/SampleBaseClass.java0000644000175000017500000000075211753011774031521 0ustar ebourgebourgpackage org.hamcrest.core; public class SampleBaseClass { String value; public SampleBaseClass(String value) { this.value = value; } @Override public String toString() { return value; } @Override public boolean equals(Object obj) { return obj instanceof SampleBaseClass && value.equals(((SampleBaseClass) obj).value); } @Override public int hashCode() { return value.hashCode(); } } libhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/core/IsNotTest.java0000644000175000017500000000220611756236430030410 0ustar ebourgebourg/* Copyright (c) 2000-2009 hamcrest.org */ package org.hamcrest.core; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.Matcher; import static org.hamcrest.core.IsEqual.equalTo; import static org.hamcrest.core.IsNot.not; import static org.hamcrest.number.OrderingComparison.greaterThan; public class IsNotTest extends AbstractMatcherTest { @Override protected Matcher createMatcher() { return not("something"); } public void testEvaluatesToTheTheLogicalNegationOfAnotherMatcher() { assertMatches("should match", not(equalTo("A")), "B"); assertDoesNotMatch("should not match", not(equalTo("B")), "B"); } public void testProvidesConvenientShortcutForNotEqualTo() { assertMatches("should match", not("A"), "B"); assertMatches("should match", not("B"), "A"); assertDoesNotMatch("should not match", not("A"), "A"); assertDoesNotMatch("should not match", not("B"), "B"); } public void testUsesDescriptionOfNegatedMatcherWithPrefix() { assertDescription("not a value greater than <2>", not(greaterThan(2))); assertDescription("not \"A\"", not("A")); } } libhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/core/EveryTest.java0000644000175000017500000000227211755732710030452 0ustar ebourgebourgpackage org.hamcrest.core; import org.hamcrest.StringDescription; import org.junit.Test; import java.util.ArrayList; import static java.util.Arrays.asList; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsNot.not; import static org.hamcrest.core.StringContains.containsString; import static org.junit.Assert.assertEquals; public class EveryTest { @Test public void isTrueWhenEveryValueMatches() { assertThat(asList("AaA", "BaB", "CaC"), Every.everyItem(containsString("a"))); assertThat(asList("AbA", "BbB", "CbC"), not(Every.everyItem(containsString("a")))); } @Test public void isAlwaysTrueForEmptyLists() { assertThat(new ArrayList(), Every.everyItem(containsString("a"))); } @Test public void describesItself() { final Every each= new Every(containsString("a")); assertEquals("every item is a string containing \"a\"", each.toString()); StringDescription description = new StringDescription(); each.matchesSafely(asList("BbB"), description); assertEquals("an item was \"BbB\"", description.toString()); } } libhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/core/IsNullTest.java0000644000175000017500000000225711753011774030567 0ustar ebourgebourg/* Copyright (c) 2000-20010 hamcrest.org */ package org.hamcrest.core; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsNot.not; import static org.hamcrest.core.IsNull.notNullValue; import static org.hamcrest.core.IsNull.nullValue; import java.math.BigDecimal; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.Matcher; public class IsNullTest extends AbstractMatcherTest { private static final BigDecimal ANY_NON_NULL_ARGUMENT = new BigDecimal(66); @Override protected Matcher createMatcher() { return nullValue(); } public void testEvaluatesToTrueIfArgumentIsNull() { assertThat(null, nullValue()); assertThat(ANY_NON_NULL_ARGUMENT, not(nullValue())); assertThat(ANY_NON_NULL_ARGUMENT, notNullValue()); assertThat(null, not(notNullValue())); } public void testSupportsStaticTyping() { requiresStringMatcher(nullValue(String.class)); requiresStringMatcher(notNullValue(String.class)); } private void requiresStringMatcher(@SuppressWarnings("unused") Matcher arg) { // no-op } } libhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/core/IsTest.java0000644000175000017500000000272611753011774027735 0ustar ebourgebourgpackage org.hamcrest.core; import static org.hamcrest.core.IsEqual.equalTo; import static org.hamcrest.core.Is.is; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.Matcher; public class IsTest extends AbstractMatcherTest { @Override protected Matcher createMatcher() { return is("something"); } public void testJustMatchesTheSameWayTheUnderylingMatcherDoes() { assertMatches("should match", is(equalTo(true)), true); assertMatches("should match", is(equalTo(false)), false); assertDoesNotMatch("should not match", is(equalTo(true)), false); assertDoesNotMatch("should not match", is(equalTo(false)), true); } public void testGeneratesIsPrefixInDescription() { assertDescription("is ", is(equalTo(true))); } public void testProvidesConvenientShortcutForIsEqualTo() { assertMatches("should match", is("A"), "A"); assertMatches("should match", is("B"), "B"); assertDoesNotMatch("should not match", is("A"), "B"); assertDoesNotMatch("should not match", is("B"), "A"); assertDescription("is \"A\"", is("A")); } public void testProvidesConvenientShortcutForIsInstanceOf() { assertTrue("should match", is(String.class).matches("A")); assertFalse("should not match", is(Integer.class).matches(new Object())); assertFalse("should not match", is(Integer.class).matches(null)); } } libhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/core/AnyOfTest.java0000644000175000017500000000350611767715320030376 0ustar ebourgebourg/* Copyright (c) 2000-2010 hamcrest.org */ package org.hamcrest.core; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.AnyOf.anyOf; import static org.hamcrest.core.IsEqual.equalTo; import static org.hamcrest.core.IsNot.not; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.Matcher; public class AnyOfTest extends AbstractMatcherTest { @Override @SuppressWarnings("unchecked") protected Matcher createMatcher() { return anyOf(IsEqual.equalTo("irrelevant")); } public void testEvaluatesToTheTheLogicalDisjunctionOfTwoOtherMatchers() { assertThat("good", anyOf(equalTo("bad"), equalTo("good"))); assertThat("good", anyOf(equalTo("good"), equalTo("good"))); assertThat("good", anyOf(equalTo("good"), equalTo("bad"))); assertThat("good", not(anyOf(equalTo("bad"), equalTo("bad")))); } public void testEvaluatesToTheTheLogicalDisjunctionOfManyOtherMatchers() { assertThat("good", anyOf(equalTo("bad"), equalTo("good"), equalTo("bad"), equalTo("bad"), equalTo("bad"))); assertThat("good", not(anyOf(equalTo("bad"), equalTo("bad"), equalTo("bad"), equalTo("bad"), equalTo("bad")))); } @SuppressWarnings("unchecked") public void testSupportsMixedTypes() { final Matcher combined = anyOf( equalTo(new SampleBaseClass("bad")), equalTo(new SampleBaseClass("good")), equalTo(new SampleSubClass("ugly")) ); assertThat(new SampleSubClass("good"), combined); } public void testHasAReadableDescription() { assertDescription("(\"good\" or \"bad\" or \"ugly\")", anyOf(equalTo("good"), equalTo("bad"), equalTo("ugly"))); } } libhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/core/IsAnythingTest.java0000644000175000017500000000156211753011774031434 0ustar ebourgebourg/* Copyright (c) 2000-2010 hamcrest.org */ package org.hamcrest.core; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsAnything.anything; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.Matcher; public class IsAnythingTest extends AbstractMatcherTest { @Override protected Matcher createMatcher() { return anything(); } public void testAlwaysEvaluatesToTrue() { assertThat(null, anything()); assertThat(new Object(), anything()); assertThat("hi", anything()); } public void testHasUsefulDefaultDescription() { assertDescription("ANYTHING", anything()); } public void testCanOverrideDescription() { String description = "description"; assertDescription(description, anything(description)); } } libhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/xml/0000755000175000017500000000000012131006721025503 5ustar ebourgebourglibhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/xml/HasXPathTest.java0000644000175000017500000001226211755732767030724 0ustar ebourgebourgpackage org.hamcrest.xml; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsEqual.equalTo; import static org.hamcrest.core.IsNot.not; import static org.hamcrest.core.StringContains.containsString; import static org.hamcrest.xml.HasXPath.hasXPath; import java.io.ByteArrayInputStream; import java.util.HashSet; import java.util.Iterator; import javax.xml.namespace.NamespaceContext; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.Matcher; import org.w3c.dom.Document; /** * @author Joe Walnes */ public class HasXPathTest extends AbstractMatcherTest { private Document xml; private NamespaceContext ns; @Override protected void setUp() throws Exception { super.setUp(); xml = parse("" + "\n" + " Edam\n" + " Cheddar\n" + " Caravane\n" + " \n" + " " + "\n" ); ns = new NamespaceContext() { @Override public String getNamespaceURI(String prefix) { return ("cheese".equals(prefix) ? "http://cheese.com" : null); } @Override public String getPrefix(String namespaceURI) { return ("http://cheese.com".equals(namespaceURI) ? "cheese" : null); } @Override public Iterator getPrefixes(String namespaceURI) { HashSet prefixes = new HashSet(); String prefix = getPrefix(namespaceURI); if (prefix != null) { prefixes.add(prefix); } return prefixes.iterator(); } }; } @Override protected Matcher createMatcher() { return hasXPath("//irrelevant"); } public void testAppliesMatcherToXPathInDocument() throws Exception { assertThat(xml, hasXPath("/root/something[2]/cheese", equalTo("Cheddar"))); assertThat(xml, hasXPath("//something[1]/cheese", containsString("dam"))); assertThat(xml, hasXPath("//something[2]/cheese", not(containsString("dam")))); assertThat(xml, hasXPath("/root/@type", equalTo("food"))); assertThat(xml, hasXPath("//something[@id='b']/cheese", equalTo("Cheddar"))); assertThat(xml, hasXPath("//something[@id='b']/cheese")); } public void testMatchesEmptyElement() throws Exception { assertThat(xml, hasXPath("//emptySomething")); } public void testMatchesEmptyElementInNamespace() throws Exception { assertThat(xml, hasXPath("//cheese:emptySomething", ns)); } public void testFailsIfNodeIsMissing() throws Exception { assertThat(xml, not(hasXPath("/root/something[3]/cheese", ns, equalTo("Cheddar")))); assertThat(xml, not(hasXPath("//something[@id='c']/cheese", ns))); } public void testFailsIfNodeIsMissingInNamespace() throws Exception { assertThat(xml, not(hasXPath("//cheese:foreignSomething", equalTo("Badger")))); assertThat(xml, not(hasXPath("//cheese:foreignSomething"))); } public void testMatchesWithNamespace() throws Exception { assertThat(xml, hasXPath("//cheese:foreignSomething", ns)); assertThat(xml, hasXPath("//cheese:foreignSomething/@milk", ns, equalTo("camel"))); assertThat(xml, hasXPath("//cheese:foreignSomething/text()", ns, equalTo("Caravane"))); } public void testThrowsIllegalArgumentExceptionIfGivenIllegalExpression() { try { hasXPath("\\g:dfgd::DSgf/root/something[2]/cheese", equalTo("blah")); fail("Expected exception"); } catch (IllegalArgumentException expectedException) { // expected exception } } public void testDescribesItself() throws Exception { assertDescription("an XML document with XPath /some/path \"Cheddar\"", hasXPath("/some/path", equalTo("Cheddar"))); assertDescription("an XML document with XPath /some/path", hasXPath("/some/path")); } public void testDescribesMissingNodeMismatch() { assertMismatchDescription("xpath returned no results.", hasXPath("//honky"), xml); } public void testDescribesIncorrectNodeValueMismatch() { assertMismatchDescription("was \"Edam\"", hasXPath("//something[1]/cheese", equalTo("parmesan")), xml); } private static Document parse(String xml) throws Exception { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); return documentBuilder.parse(new ByteArrayInputStream(xml.getBytes())); } } libhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/object/0000755000175000017500000000000012131006721026151 5ustar ebourgebourglibhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/object/HasToStringTest.java0000644000175000017500000000347511755732744032120 0ustar ebourgebourgpackage org.hamcrest.object; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsEqual.equalTo; import static org.hamcrest.core.IsNot.not; import static org.hamcrest.object.HasToString.hasToString; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.Matcher; import org.hamcrest.StringDescription; public class HasToStringTest extends AbstractMatcherTest { private static final String TO_STRING_RESULT = "toString result"; private static final Object ARG = new Object() { @Override public String toString() { return TO_STRING_RESULT; } }; @Override protected Matcher createMatcher() { return hasToString(equalTo("irrelevant")); } public void testPassesResultOfToStringToNestedMatcher() { assertThat(ARG, hasToString(equalTo(TO_STRING_RESULT))); assertThat(ARG, not(hasToString(equalTo("OTHER STRING")))); } public void testProvidesConvenientShortcutForHasToStringEqualTo() { assertThat(ARG, hasToString(TO_STRING_RESULT)); assertThat(ARG, not(hasToString("OTHER STRING"))); } public void testHasReadableDescription() { Matcher toStringMatcher = equalTo(TO_STRING_RESULT); Matcher> matcher = hasToString(toStringMatcher); assertEquals("with toString() " + descriptionOf(toStringMatcher), descriptionOf(matcher)); } public void testMismatchContainsToStringValue() { String expectedMismatchString = "toString() was \"Cheese\""; assertMismatchDescription(expectedMismatchString, hasToString(TO_STRING_RESULT), "Cheese"); } private static String descriptionOf(Matcher matcher) { return StringDescription.asString(matcher); } } libhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/object/IsCompatibleTypeTest.java0000644000175000017500000000344611753011774033115 0ustar ebourgebourgpackage org.hamcrest.object; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.Matcher; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.object.IsCompatibleType.typeCompatibleWith; public class IsCompatibleTypeTest extends AbstractMatcherTest { public static class BaseClass { } public static class ExtendedClass extends BaseClass { } public interface BaseInterface { } public interface ExtendedInterface extends BaseInterface { } public static class ClassImplementingBaseInterface implements BaseInterface { } @Override protected Matcher createMatcher() { return typeCompatibleWith(BaseClass.class); } public void testMatchesSameClass() { assertThat(BaseClass.class, typeCompatibleWith(BaseClass.class)); } public void testMatchesSameInterface() { assertThat(BaseInterface.class, typeCompatibleWith(BaseInterface.class)); } public void testMatchesExtendedClass() { assertThat(ExtendedClass.class, typeCompatibleWith(BaseClass.class)); } public void testMatchesClassImplementingInterface() { assertThat(ClassImplementingBaseInterface.class, typeCompatibleWith(BaseInterface.class)); } public void testMatchesExtendedInterface() { assertThat(ExtendedInterface.class, typeCompatibleWith(BaseInterface.class)); } // public void testDoesNotMatchIncompatibleTypes() { // assertThat(BaseClass.class, not(compatibleType(ExtendedClass.class))); // assertThat(Integer.class, not(compatibleType(String.class))); // } public void testHasReadableDescription() { assertDescription("type < java.lang.Runnable", typeCompatibleWith(Runnable.class)); } } libhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/object/IsEventFromTest.java0000644000175000017500000000355311753011774032100 0ustar ebourgebourg/* Copyright (c) 2000-2006 hamcrest.org */ package org.hamcrest.object; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.object.IsEventFrom.eventFrom; import java.util.EventObject; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.Matcher; public class IsEventFromTest extends AbstractMatcherTest { @Override protected Matcher createMatcher() { return eventFrom(null); } public void testEvaluatesToTrueIfArgumentIsAnEventObjectFiredByASpecifiedSource() { Object o = "Source"; EventObject ev = new EventObject(o); EventObject ev2 = new EventObject("source 2"); Matcher isEventMatcher = eventFrom(o); assertThat(ev, isEventMatcher); assertMismatchDescription("source was \"source 2\"", isEventMatcher, ev2); } private static class DerivedEvent extends EventObject { private static final long serialVersionUID = 1L; public DerivedEvent(Object source) { super(source); } } public void testCanTestForSpecificEventClasses() { Object o = new Object(); DerivedEvent goodEv = new DerivedEvent(o); DerivedEvent wrongSource = new DerivedEvent("wrong source"); EventObject wrongType = new EventObject(o); EventObject wrongSourceAndType = new EventObject(new Object()); Matcher isEventMatcher = IsEventFrom.eventFrom(DerivedEvent.class, o); assertThat(goodEv, isEventMatcher); assertMismatchDescription("source was \"wrong source\"", isEventMatcher, wrongSource); assertMismatchDescription("item type was java.util.EventObject", isEventMatcher, wrongType); assertMismatchDescription("item type was java.util.EventObject", isEventMatcher, wrongSourceAndType); } } libhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/generator/0000755000175000017500000000000012131006721026671 5ustar ebourgebourg././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootlibhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/generator/EasyMock2FactoryWriterTest.javalibhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/generator/EasyMock2FactoryWriterT0000644000175000017500000001405111753011774033300 0ustar ebourgebourgpackage org.hamcrest.generator; import junit.framework.TestCase; import java.io.StringWriter; import java.io.IOException; public class EasyMock2FactoryWriterTest extends TestCase { private FactoryWriter factoryWriter; private StringWriter output = new StringWriter(); @Override protected void setUp() throws Exception { super.setUp(); factoryWriter = new EasyMock2FactoryWriter(output, "com.blah", "EasyMatchers"); } public void testWritesMethodDelegationMethodWrappedInAdapter() throws IOException { FactoryMethod method = new FactoryMethod("com.example.MyMatcher", "anyObject", "unusedReturnType"); factoryWriter.writeMethod(method.getName(), method); assertEquals("" + " public static java.lang.Object anyObject() {\n" + " org.hamcrest.integration.EasyMockAdapter.adapt(\n" + " com.example.MyMatcher.anyObject());\n" + " return null;\n" + " }\n" + "\n", output.toString()); } public void testWritesReturnType() throws IOException { FactoryMethod method = new FactoryMethod("com.example.MyMatcher", "anyString", "unusedReturnType"); method.setGenerifiedType("String"); factoryWriter.writeMethod(method.getName(), method); assertEquals("" + " public static String anyString() {\n" + " org.hamcrest.integration.EasyMockAdapter.adapt(\n" + " com.example.MyMatcher.anyString());\n" + " return null;\n" + " }\n" + "\n", output.toString()); } public void testWritesAdvancedGenerifiedMatcherType() throws IOException { FactoryMethod method = new FactoryMethod("com.example.MyMatcher", "weirdThing", "unusedReturnType"); method.setGenerifiedType("java.util.Map,?>"); factoryWriter.writeMethod(method.getName(), method); assertEquals("" + " public static java.util.Map,?> weirdThing() {\n" + " org.hamcrest.integration.EasyMockAdapter.adapt(\n" + " com.example.MyMatcher.weirdThing());\n" + " return null;\n" + " }\n" + "\n", output.toString()); } public void testWritesParameters() throws IOException { FactoryMethod method = new FactoryMethod("com.example.MyMatcher", "between", "unusedReturnType"); method.addParameter("int[]", "lower"); method.addParameter("com.blah.Cheesable...", "upper"); factoryWriter.writeMethod(method.getName(), method); assertEquals("" + " public static java.lang.Object between(int[] lower, com.blah.Cheesable... upper) {\n" + " org.hamcrest.integration.EasyMockAdapter.adapt(\n" + " com.example.MyMatcher.between(lower, upper));\n" + " return null;\n" + " }\n" + "\n", output.toString()); } public void testWritesExceptions() throws IOException { FactoryMethod method = new FactoryMethod("com.example.MyMatcher", "tricky", "unusedReturnType"); method.addException("java.io.IOException"); method.addException("com.foo.CheeselessException"); factoryWriter.writeMethod(method.getName(), method); assertEquals("" + " public static java.lang.Object tricky() throws java.io.IOException, com.foo.CheeselessException {\n" + " org.hamcrest.integration.EasyMockAdapter.adapt(\n" + " com.example.MyMatcher.tricky());\n" + " return null;\n" + " }\n" + "\n", output.toString()); } // // public void testWritesGenericTypeParameters() throws IOException { // FactoryMethod method = new FactoryMethod("com.example.MyMatcher", "tricky"); // method.addGenericTypeParameter("T"); // method.addGenericTypeParameter("V extends String & Cheese"); // method.addParameter("T", "t"); // method.addParameter("List", "v"); // // factoryWriter.writeMethod(method.getName(), method); // assertEquals("" + // " public static org.hamcrest.Matcher tricky(T t, List v) {\n" + // " return com.example.MyMatcher.tricky(t, v);\n" + // " }\n" + // "\n", // output.toString()); // } // // public void testWritesJavaDoc() throws IOException { // FactoryMethod method = new FactoryMethod("com.example.MyMatcher", "needsDoc"); // method.setJavaDoc("This is a complicated method.\nIt needs docs.\n\n@see MoreStuff"); // // factoryWriter.writeMethod(method.getName(), method); // assertEquals("" + // " /**\n" + // " * This is a complicated method.\n" + // " * It needs docs.\n" + // " * \n" + // " * @see MoreStuff\n" + // " */\n" + // " public static org.hamcrest.Matcher needsDoc() {\n" + // " return com.example.MyMatcher.needsDoc();\n" + // " }\n" + // "\n", // output.toString()); // } // // public void testWritesMethodWithNameOverriden() throws IOException { // FactoryMethod method = new FactoryMethod("com.example.MyMatcher", "eq"); // // factoryWriter.writeMethod("anotherName", method); // assertEquals("" + // " public static org.hamcrest.Matcher anotherName() {\n" + // " return com.example.MyMatcher.eq();\n" + // " }\n" + // "\n", // output.toString()); // } // primitives // arrays? // and/or/not/etc } libhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/generator/config/0000755000175000017500000000000012131006721030136 5ustar ebourgebourg././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootlibhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/generator/config/XmlConfiguratorTest.javalibhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/generator/config/XmlConfiguratorT0000644000175000017500000000703411767324754033363 0ustar ebourgebourgpackage org.hamcrest.generator.config; import junit.framework.TestCase; import org.hamcrest.Factory; import org.hamcrest.Matcher; import org.hamcrest.core.CombinableMatcher; import org.hamcrest.generator.FactoryMethod; import org.hamcrest.generator.FactoryWriter; import org.hamcrest.generator.SugarConfiguration; import org.xml.sax.InputSource; import java.io.StringReader; import java.util.ArrayList; import java.util.List; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsCollectionContaining.hasItem; public class XmlConfiguratorTest extends TestCase { private MockSugarConfiguration sugarConfiguration; private XmlConfigurator config; @Override protected void setUp() throws Exception { super.setUp(); sugarConfiguration = new MockSugarConfiguration(); config = new XmlConfigurator(sugarConfiguration, getClass().getClassLoader()); } public void testAddsMatcherFactoryMethodsToConfiguration() throws Exception { config.load(createXml("" + "" + " " + " " + "")); assertThat(sugarConfiguration.factoryMethods(), hasItem(new FactoryMethod(SomeMatcher.class.getName().replace('$', '.'), "matcher1", "org.hamcrest.Matcher"))); assertThat(sugarConfiguration.factoryMethods(), hasItem(new FactoryMethod(SomeMatcher.class.getName().replace('$', '.'), "matcher2", "org.hamcrest.Matcher"))); assertThat(sugarConfiguration.factoryMethods(), hasItem(new FactoryMethod(AnotherMatcher.class.getName().replace('$', '.'), "matcher3", "org.hamcrest.CombinableMatcher"))); } private static InputSource createXml(String xml) { return new InputSource(new StringReader(xml)); } // Sample Matchers @SuppressWarnings("rawtypes") public static class SomeMatcher { @Factory public static Matcher matcher1() { return null; } @Factory public static Matcher matcher2() { return null; } } @SuppressWarnings("rawtypes") public static class AnotherMatcher { @Factory public static CombinableMatcher matcher3() { return null; } } /** * Simple 'record and check' style mock. Not using a mocking library to avoid * cyclical dependency between mocking library and hamcrest. */ private static class MockSugarConfiguration implements SugarConfiguration { private final List seenFactoryMethods = new ArrayList(); private final List seenFactoryWriters = new ArrayList(); @Override public void addWriter(FactoryWriter factoryWriter) { seenFactoryWriters.add(factoryWriter); } @Override public void addFactoryMethod(FactoryMethod method) { seenFactoryMethods.add(method); } @Override public void addFactoryMethods(Iterable methods) { for (FactoryMethod method : methods) { addFactoryMethod(method); } } public List factoryMethods() { return seenFactoryMethods; } } } ././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootlibhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/generator/ReflectiveFactoryReaderTest.javalibhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/generator/ReflectiveFactoryReader0000644000175000017500000002157111767324470033407 0ustar ebourgebourgpackage org.hamcrest.generator; import junit.framework.TestCase; import org.hamcrest.BaseMatcher; import org.hamcrest.Factory; import org.hamcrest.Matcher; import java.io.IOException; import java.util.Collection; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; @SuppressWarnings("unused") public class ReflectiveFactoryReaderTest extends TestCase { public static class SimpleSetOfMatchers { @Factory public static Matcher firstMethod() { return null; } @Factory public static Matcher secondMethod() { return null; } } public void testIteratesOverFactoryMethods() { Iterable reader = new ReflectiveFactoryReader(SimpleSetOfMatchers.class); Iterator methods = reader.iterator(); assertTrue("Expected first method", methods.hasNext()); FactoryMethod firstMethod = methods.next(); assertEquals("firstMethod", firstMethod.getName()); assertEquals(SimpleSetOfMatchers.class.getName().replace('$', '.'), firstMethod.getMatcherClass()); assertTrue("Expected second method", methods.hasNext()); FactoryMethod secondMethod = methods.next(); assertEquals("secondMethod", secondMethod.getName()); assertEquals(SimpleSetOfMatchers.class.getName().replace('$', '.'), secondMethod.getMatcherClass()); assertFalse("Expected no more methods", methods.hasNext()); } public static class MatchersWithDodgySignatures { @Factory public Matcher notStatic() { return null; } @Factory static Matcher notPublic() { return null; } public static Matcher noAnnotation() { return null; } @Factory public static Matcher goodMethod() { return null; } @Factory public static String anotherGoodMethod() { return null; } @Factory public static void wrongReturnType() { } } public void testOnlyReadsPublicStaticAnnotatedMethodsThatReturnNonVoid() { Iterable reader = new ReflectiveFactoryReader(MatchersWithDodgySignatures.class); Iterator methods = reader.iterator(); assertTrue("Expected first method", methods.hasNext()); assertEquals("goodMethod", methods.next().getName()); assertTrue("Expected second method", methods.hasNext()); assertEquals("anotherGoodMethod", methods.next().getName()); assertFalse("Expected no more methods", methods.hasNext()); } public static class GenerifiedMatchers { @Factory public static Matcher> generifiedType() { return null; } @SuppressWarnings("rawtypes") @Factory public static Matcher noGenerifiedType() { return null; } @Factory public static Matcher, Factory>> crazyType() { return null; } } public void testReadsFullyQualifiedGenericType() { FactoryMethod method = readMethod(GenerifiedMatchers.class, "generifiedType"); assertEquals("java.util.Comparator", method.getGenerifiedType()); } public void testReadsNullGenerifiedTypeIfNotPresent() { FactoryMethod method = readMethod(GenerifiedMatchers.class, "noGenerifiedType"); assertNull(method.getGenerifiedType()); } public void testReadsGenericsInGenericType() { FactoryMethod method = readMethod(GenerifiedMatchers.class, "crazyType"); assertEquals( "java.util.Map, org.hamcrest.Factory>", method.getGenerifiedType()); } public static class ParamterizedMatchers { @Factory public static Matcher withParam(String someString, int[] numbers, Collection things) { return null; } @Factory public static Matcher withArray(String[] array) { return null; } @Factory public static Matcher withVarArgs(String... things) { return null; } @Factory public static Matcher withGenerifiedParam(Collection> things, Set[] x) { return null; } } public void testReadsParameterTypes() { FactoryMethod method = readMethod(ParamterizedMatchers.class, "withParam"); List params = method.getParameters(); assertEquals(3, params.size()); assertEquals("java.lang.String", params.get(0).getType()); assertEquals("int[]", params.get(1).getType()); assertEquals("java.util.Collection", params.get(2).getType()); } public void testReadsArrayAndVarArgParameterTypes() { FactoryMethod arrayMethod = readMethod(ParamterizedMatchers.class, "withArray"); assertEquals("java.lang.String[]", arrayMethod.getParameters().get(0).getType()); FactoryMethod varArgsMethod = readMethod(ParamterizedMatchers.class, "withVarArgs"); assertEquals("java.lang.String...", varArgsMethod.getParameters().get(0).getType()); } public void testReadsGenerifiedParameterTypes() { FactoryMethod method = readMethod(ParamterizedMatchers.class, "withGenerifiedParam"); assertEquals("java.util.Collection>", method.getParameters().get(0).getType()); assertEquals("java.util.Set[]", method.getParameters().get(1).getType()); } public void testCannotReadParameterNamesSoMakesThemUpInstead() { FactoryMethod method = readMethod(ParamterizedMatchers.class, "withParam"); List params = method.getParameters(); assertEquals("param1", params.get(0).getName()); assertEquals("param2", params.get(1).getName()); assertEquals("param3", params.get(2).getName()); } public static class ExceptionalMatchers { @Factory public static Matcher withExceptions() throws Error, IOException, RuntimeException { return null; } } public void testReadsExceptions() { FactoryMethod method = readMethod(ExceptionalMatchers.class, "withExceptions"); List exceptions = method.getExceptions(); assertEquals(3, exceptions.size()); assertEquals("java.lang.Error", exceptions.get(0)); assertEquals("java.io.IOException", exceptions.get(1)); assertEquals("java.lang.RuntimeException", exceptions.get(2)); } public static class WithJavaDoc { /** * Look at me! * * @return something */ @Factory public static Matcher documented() { return null; } } public void testCannotReadJavaDoc() { // JavaDoc information is not available through reflection alone. FactoryMethod method = readMethod(WithJavaDoc.class, "documented"); assertEquals(null, method.getJavaDoc()); } public static class G { @Factory public static & Comparable> Matcher> x(Set t, V v) { return null; } } public void testReadsGenericTypeParameters() { FactoryMethod method = readMethod(G.class, "x"); assertEquals("T", method.getGenericTypeParameters().get(0)); assertEquals("V extends java.util.List & java.lang.Comparable", method.getGenericTypeParameters().get(1)); assertEquals("java.util.Map", method.getGenerifiedType()); assertEquals("java.util.Set", method.getParameters().get(0).getType()); assertEquals("V", method.getParameters().get(1).getType()); } public static class SubclassOfMatcher { @Factory public static BaseMatcher subclassMethod() { return null; } } public void testCatchesSubclasses() { assertNotNull(readMethod(SubclassOfMatcher.class, "subclassMethod")); } private static FactoryMethod readMethod(Class cls, String methodName) { for (FactoryMethod method : new ReflectiveFactoryReader(cls)) { if (method.getName().equals(methodName)) { return method; } } return null; } }././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootlibhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/generator/QuickReferenceWriterTest.javalibhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/generator/QuickReferenceWriterTes0000644000175000017500000000420411753011774033375 0ustar ebourgebourgpackage org.hamcrest.generator; import junit.framework.TestCase; import java.io.PrintStream; import java.io.ByteArrayOutputStream; import java.io.IOException; public class QuickReferenceWriterTest extends TestCase { private ByteArrayOutputStream actualBuffer; private ByteArrayOutputStream expectedBuffer; private PrintStream expected; private QuickReferenceWriter writer; @Override protected void setUp() throws Exception { super.setUp(); actualBuffer = new ByteArrayOutputStream(); writer = new QuickReferenceWriter(new PrintStream(actualBuffer)); expectedBuffer = new ByteArrayOutputStream(); expected = new PrintStream(expectedBuffer); } public void testWritesSimplifiedSummaryOfMatchers() throws IOException { FactoryMethod namedMethod = new FactoryMethod("SomeClass", "someMethod", "unusedReturnType"); namedMethod.addParameter("Cheese", "a"); namedMethod.addParameter("int", "b"); namedMethod.setGenerifiedType("String"); writer.writeMethod("namedMethod", namedMethod); FactoryMethod anotherMethod = new FactoryMethod("SomeClass", "anotherMethod", "unusedReturnType"); anotherMethod.setGenerifiedType("int"); writer.writeMethod("anotherMethod", anotherMethod); expected.println(" [String] namedMethod(Cheese a, int b)"); expected.println(" [int] anotherMethod()"); verify(); } public void testRemovesPackageNames() throws IOException { FactoryMethod namedMethod = new FactoryMethod("SomeClass", "someMethod", "unusedReturnType"); namedMethod.addParameter("com.blah.Foo", "a"); namedMethod.addParameter("com.foo.Cheese", "b"); namedMethod.setGenerifiedType("java.lang.Cheese"); writer.writeMethod("namedMethod", namedMethod); expected.println(" [Cheese] namedMethod(Foo a, Cheese b)"); verify(); } private void verify() { assertEquals(new String(expectedBuffer.toByteArray()), new String(actualBuffer.toByteArray())); } } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootlibhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/generator/QDoxFactoryReaderTest.javalibhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/generator/QDoxFactoryReaderTest.j0000644000175000017500000000777411756153700033265 0ustar ebourgebourgpackage org.hamcrest.generator; import junit.framework.TestCase; import java.io.StringReader; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class QDoxFactoryReaderTest extends TestCase { public void testExtractsOriginalParameterNamesFromSource() { FactoryMethod method = new FactoryMethod("org.SomeClass", "someMethod", "unusedReturnType"); method.addParameter("java.lang.String", "badParamName"); String input = "" + "package org;\n" + "class SomeClass {\n" + " Matcher someMethod(String realParamName) { ... } \n" + "}\n"; FactoryMethod factoryMethod = wrapUsingQDoxedSource(method, "org.SomeClass", input); assertEquals("java.lang.String", factoryMethod.getParameters().get(0).getType()); assertEquals("realParamName", factoryMethod.getParameters().get(0).getName()); } public void testExtractsOriginalGenericParameterNamesFromSource() { FactoryMethod method = new FactoryMethod("org.SomeClass", "someMethod", "unusedReturnType"); method.addParameter("java.util.Collection", "badParamName"); String input = "" + "package org;\n" + "class SomeClass {\n" + " Matcher someMethod(java.util.Collection realParamName) { ... } \n" + "}\n"; FactoryMethod factoryMethod = wrapUsingQDoxedSource(method, "org.SomeClass", input); assertEquals("java.util.Collection", factoryMethod.getParameters().get(0).getType()); assertEquals("realParamName", factoryMethod.getParameters().get(0).getName()); } public void testExtractsOriginalVarArgParameterNamesFromSource() { FactoryMethod method = new FactoryMethod("org.SomeClass", "someMethod", "unusedReturnType"); method.addParameter("java.lang.String...", "badParamName"); String input = "" + "package org;\n" + "class SomeClass {\n" + " Matcher someMethod(java.lang.String... realParamName) { ... } \n" + "}\n"; FactoryMethod factoryMethod = wrapUsingQDoxedSource(method, "org.SomeClass", input); assertEquals("java.lang.String...", factoryMethod.getParameters().get(0).getType()); assertEquals("realParamName", factoryMethod.getParameters().get(0).getName()); } public void testExtractsOriginalJavaDocFromSource() { FactoryMethod method = new FactoryMethod("org.SomeClass", "someMethod", "unusedReturnType"); String input = "" + "package org;\n" + "class SomeClass {\n" + " /**\n" + " * This class does something.\n" + " *\n" + " * @return stuff.\n" + " */\n" + " Matcher someMethod() { ... } \n" + "}\n"; FactoryMethod factoryMethod = wrapUsingQDoxedSource(method, "org.SomeClass", input); assertEquals("This class does something.\n\n@return stuff.\n", factoryMethod.getJavaDoc()); } private static FactoryMethod wrapUsingQDoxedSource(FactoryMethod originalMethod, String className, String input) { List originalMethods = new ArrayList(); originalMethods.add(originalMethod); QDox qdox = new QDox(); qdox.addSource(new StringReader(input)); QDoxFactoryReader qDoxFactoryReader = new QDoxFactoryReader( originalMethods, qdox, className); return getFirstFactoryMethod(qDoxFactoryReader); } private static FactoryMethod getFirstFactoryMethod(QDoxFactoryReader qDoxFactoryReader) { Iterator iterator = qDoxFactoryReader.iterator(); iterator.hasNext(); return iterator.next(); } } ././@LongLink0000000000000000000000000000015400000000000011565 Lustar rootrootlibhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/generator/HamcrestFactoryWriterTest.javalibhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/generator/HamcrestFactoryWriterTe0000644000175000017500000001510011753011774033412 0ustar ebourgebourgpackage org.hamcrest.generator; import java.io.IOException; import java.io.StringWriter; import junit.framework.TestCase; public class HamcrestFactoryWriterTest extends TestCase { private FactoryWriter factoryWriter; private StringWriter output = new StringWriter(); @Override protected void setUp() throws Exception { super.setUp(); factoryWriter = new HamcrestFactoryWriter(null, null, output); } public void testWritesMethodDelegationMethod() throws IOException { FactoryMethod method = new FactoryMethod("com.example.MyMatcher", "anyObject", "matcher.ReturnType"); factoryWriter.writeMethod(method.getName(), method); assertEquals("" + " public static matcher.ReturnType anyObject() {\n" + " return com.example.MyMatcher.anyObject();\n" + " }\n" + "\n", output.toString()); } public void testWritesCompleteJavaSource() throws IOException { factoryWriter = new HamcrestFactoryWriter("com.some.package", "SomeClass", output); factoryWriter.writeHeader(); factoryWriter.writeMethod("method1", new FactoryMethod("com.example.MyMatcher", "method1", "matcher.ReturnType")); factoryWriter.writeMethod("method2", new FactoryMethod("com.example.MyMatcher", "method2", "matcher.ReturnType")); factoryWriter.writeFooter(); assertEquals("" + "// Generated source.\n" + "package com.some.package;\n" + "\n" + "public class SomeClass {\n" + "\n" + " public static matcher.ReturnType method1() {\n" + " return com.example.MyMatcher.method1();\n" + " }\n" + "\n" + " public static matcher.ReturnType method2() {\n" + " return com.example.MyMatcher.method2();\n" + " }\n" + "\n" + "}\n", output.toString()); } public void testWritesGenerifiedMatcherType() throws IOException { FactoryMethod method = new FactoryMethod("com.example.MyMatcher", "anyString", "matcher.ReturnType"); method.setGenerifiedType("String"); factoryWriter.writeMethod(method.getName(), method); assertEquals("" + " public static matcher.ReturnType anyString() {\n" + " return com.example.MyMatcher.anyString();\n" + " }\n" + "\n", output.toString()); } public void testWritesAdvancedGenerifiedMatcherType() throws IOException { FactoryMethod method = new FactoryMethod("com.example.MyMatcher", "weirdThing", "matcher.ReturnType"); method.setGenerifiedType("java.util.Map,?>"); factoryWriter.writeMethod(method.getName(), method); assertEquals("" + " public static matcher.ReturnType,?>> weirdThing() {\n" + " return com.example.MyMatcher.weirdThing();\n" + " }\n" + "\n", output.toString()); } public void testWritesParameters() throws IOException { FactoryMethod method = new FactoryMethod("com.example.MyMatcher", "between", "matcher.ReturnType"); method.addParameter("int[]", "lower"); method.addParameter("com.blah.Cheesable...", "upper"); factoryWriter.writeMethod(method.getName(), method); assertEquals("" + " public static matcher.ReturnType between(int[] lower, com.blah.Cheesable... upper) {\n" + " return com.example.MyMatcher.between(lower, upper);\n" + " }\n" + "\n", output.toString()); } public void testWritesExceptions() throws IOException { FactoryMethod method = new FactoryMethod("com.example.MyMatcher", "tricky", "matcher.ReturnType"); method.addException("java.io.IOException"); method.addException("com.foo.CheeselessException"); factoryWriter.writeMethod(method.getName(), method); assertEquals("" + " public static matcher.ReturnType tricky() throws java.io.IOException, com.foo.CheeselessException {\n" + " return com.example.MyMatcher.tricky();\n" + " }\n" + "\n", output.toString()); } public void testWritesGenericTypeParameters() throws IOException { FactoryMethod method = new FactoryMethod("com.example.MyMatcher", "tricky", "matcher.ReturnType"); method.addGenericTypeParameter("T"); method.addGenericTypeParameter("V extends String & Cheese"); method.addParameter("T", "t"); method.addParameter("List", "v"); factoryWriter.writeMethod(method.getName(), method); assertEquals("" + " public static matcher.ReturnType tricky(T t, List v) {\n" + " return com.example.MyMatcher.tricky(t, v);\n" + " }\n" + "\n", output.toString()); } public void testWritesJavaDoc() throws IOException { FactoryMethod method = new FactoryMethod("com.example.MyMatcher", "needsDoc", "matcher.ReturnType"); method.setJavaDoc("This is a complicated method.\nIt needs docs.\n\n@see MoreStuff"); factoryWriter.writeMethod(method.getName(), method); assertEquals("" + " /**\n" + " * This is a complicated method.\n" + " * It needs docs.\n" + " * \n" + " * @see MoreStuff\n" + " */\n" + " public static matcher.ReturnType needsDoc() {\n" + " return com.example.MyMatcher.needsDoc();\n" + " }\n" + "\n", output.toString()); } public void testWritesMethodWithNameOverriden() throws IOException { FactoryMethod method = new FactoryMethod("com.example.MyMatcher", "eq", "matcher.ReturnType"); factoryWriter.writeMethod("anotherName", method); assertEquals("" + " public static matcher.ReturnType anotherName() {\n" + " return com.example.MyMatcher.eq();\n" + " }\n" + "\n", output.toString()); } } libhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/text/0000755000175000017500000000000012131006721025667 5ustar ebourgebourglibhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/text/StringEndsWithTest.java0000644000175000017500000000324311753011774032325 0ustar ebourgebourg/* Copyright (c) 2000-2006 hamcrest.org */ package org.hamcrest.text; import static org.hamcrest.core.StringEndsWith.endsWith; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.Matcher; public class StringEndsWithTest extends AbstractMatcherTest { static final String EXCERPT = "EXCERPT"; Matcher stringEndsWith = endsWith(EXCERPT); @Override protected Matcher createMatcher() { return stringEndsWith; } public void testEvaluatesToTrueIfArgumentContainsSpecifiedSubstring() { assertFalse("should be false if excerpt at beginning", stringEndsWith.matches(EXCERPT + "END")); assertTrue("should be true if excerpt at end", stringEndsWith.matches("START" + EXCERPT)); assertFalse("should be false if excerpt in middle", stringEndsWith.matches("START" + EXCERPT + "END")); assertTrue("should be true if excerpt is at end and repeated", stringEndsWith.matches(EXCERPT + EXCERPT)); assertFalse("should be false if excerpt is not in string", stringEndsWith.matches("Something else")); assertFalse("should be false if part of excerpt is at end of string", stringEndsWith.matches(EXCERPT.substring(0, EXCERPT.length() - 2))); } public void testEvaluatesToTrueIfArgumentIsEqualToSubstring() { assertTrue("should be true if excerpt is entire string", stringEndsWith.matches(EXCERPT)); } public void testHasAReadableDescription() { assertDescription("a string ending with \"EXCERPT\"", stringEndsWith); } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/text/StringContainsInOrderTest.javalibhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/text/StringContainsInOrderTest.ja0000644000175000017500000000175111753011774033314 0ustar ebourgebourgpackage org.hamcrest.text; import static java.util.Arrays.asList; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.Matcher; public class StringContainsInOrderTest extends AbstractMatcherTest { StringContainsInOrder m = new StringContainsInOrder(asList("a", "b", "c")); @Override protected Matcher createMatcher() { return m; } public void testMatchesOnlyIfStringContainsGivenSubstringsInTheSameOrder() { assertMatches("substrings in order", m, "abc"); assertMatches("substrings separated", m, "1a2b3c4"); assertDoesNotMatch("substrings out of order", m, "cab"); assertDoesNotMatch("no substrings in string", m, "xyz"); assertDoesNotMatch("substring missing", m, "ac"); assertDoesNotMatch("empty string", m, ""); } public void testHasAReadableDescription() { assertDescription("a string containing \"a\", \"b\", \"c\" in order", m); } } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootlibhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/text/IsEqualIgnoringWhiteSpaceTest.javalibhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/text/IsEqualIgnoringWhiteSpaceTes0000644000175000017500000000335011753011774033321 0ustar ebourgebourg/* Copyright (c) 2000-2006 hamcrest.org */ package org.hamcrest.text; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsNot.not; import static org.hamcrest.text.IsEqualIgnoringWhiteSpace.equalToIgnoringWhiteSpace; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.Matcher; public class IsEqualIgnoringWhiteSpaceTest extends AbstractMatcherTest { private final Matcher matcher = equalToIgnoringWhiteSpace("Hello World how\n are we? "); @Override protected Matcher createMatcher() { return matcher; } public void testPassesIfWordsAreSameButWhitespaceDiffers() { assertThat("Hello World how are we?", matcher); assertThat(" Hello World how are \n\n\twe?", matcher); } public void testFailsIfTextOtherThanWhitespaceDiffers() { assertThat("Hello PLANET how are we?", not(matcher)); assertThat("Hello World how are we", not(matcher)); } public void testFailsIfWhitespaceIsAddedOrRemovedInMidWord() { assertThat("HelloWorld how are we?", not(matcher)); assertThat("Hello Wo rld how are we?", not(matcher)); } public void testFailsIfMatchingAgainstNull() { assertThat(null, not(matcher)); } public void testRequiresNonNullStringToBeConstructed() { try { new IsEqualIgnoringWhiteSpace(null); fail("Expected exception"); } catch (IllegalArgumentException goodException) { // expected! } } public void testHasAReadableDescription() { assertDescription("equalToIgnoringWhiteSpace(\"Hello World how\\n are we? \")", matcher); } } libhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/text/IsEqualIgnoringCaseTest.java0000644000175000017500000000307111753011774033244 0ustar ebourgebourg/* Copyright (c) 2000-2006 hamcrest.org */ package org.hamcrest.text; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.Matcher; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsNot.not; import static org.hamcrest.text.IsEqualIgnoringCase.equalToIgnoringCase; public class IsEqualIgnoringCaseTest extends AbstractMatcherTest { @Override protected Matcher createMatcher() { return equalToIgnoringCase("irrelevant"); } public void testIgnoresCaseOfCharsInString() { assertThat("HELLO", equalToIgnoringCase("heLLo")); assertThat("hello", equalToIgnoringCase("heLLo")); assertThat("HelLo", equalToIgnoringCase("heLLo")); assertThat("bye", not(equalToIgnoringCase("heLLo"))); } public void testFailsIfAdditionalWhitespaceIsPresent() { assertThat("heLLo ", not(equalToIgnoringCase("heLLo"))); assertThat(" heLLo", not(equalToIgnoringCase("heLLo"))); } public void testFailsIfMatchingAgainstNull() { assertThat(null, not(equalToIgnoringCase("heLLo"))); } public void testRequiresNonNullStringToBeConstructed() { try { equalToIgnoringCase(null); fail("Expected exception"); } catch (IllegalArgumentException goodException) { // expected! } } public void testDescribesItselfAsCaseInsensitive() { assertDescription("equalToIgnoringCase(\"heLLo\")", equalToIgnoringCase("heLLo")); } } libhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/text/StringContainsTest.java0000644000175000017500000000321011753011774032350 0ustar ebourgebourg/* Copyright (c) 2000-2006 hamcrest.org */ package org.hamcrest.text; import static org.hamcrest.core.StringContains.containsString; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.Matcher; public class StringContainsTest extends AbstractMatcherTest { static final String EXCERPT = "EXCERPT"; Matcher stringContains = containsString(EXCERPT); @Override protected Matcher createMatcher() { return stringContains; } public void testEvaluatesToTrueIfArgumentContainsSpecifiedSubstring() { assertTrue("should be true if excerpt at beginning", stringContains.matches(EXCERPT + "END")); assertTrue("should be true if excerpt at end", stringContains.matches("START" + EXCERPT)); assertTrue("should be true if excerpt in middle", stringContains.matches("START" + EXCERPT + "END")); assertTrue("should be true if excerpt is repeated", stringContains.matches(EXCERPT + EXCERPT)); assertFalse("should not be true if excerpt is not in string", stringContains.matches("Something else")); assertFalse("should not be true if part of excerpt is in string", stringContains.matches(EXCERPT.substring(1))); } public void testEvaluatesToTrueIfArgumentIsEqualToSubstring() { assertTrue("should be true if excerpt is entire string", stringContains.matches(EXCERPT)); } public void testHasAReadableDescription() { assertDescription("a string containing \"EXCERPT\"", stringContains); } } libhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/text/IsEmptyStringTest.java0000644000175000017500000000221511753011774032170 0ustar ebourgebourgpackage org.hamcrest.text; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsNot.not; import static org.hamcrest.text.IsEmptyString.isEmptyOrNullString; import static org.hamcrest.text.IsEmptyString.isEmptyString; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.Matcher; public class IsEmptyStringTest extends AbstractMatcherTest { @Override protected Matcher createMatcher() { return isEmptyOrNullString(); } public void testEmptyOrNullIsNull() { assertThat(null, isEmptyOrNullString()); } public void testEmptyIsNotNull() { assertThat(null, not(isEmptyString())); } public void testMatchesEmptyString() { assertMatches("empty string", isEmptyString(), ""); assertMatches("empty string", isEmptyOrNullString(), ""); } public void testDoesNotMatchNonEmptyString() { assertDoesNotMatch("non empty string", isEmptyString(), "a"); } public void testHasAReadableDescription() { assertDescription("an empty string", isEmptyString()); assertDescription("(null or an empty string)", isEmptyOrNullString()); } } libhamcrest-java-1.3/hamcrest-unit-test/src/main/java/org/hamcrest/text/StringStartsWithTest.java0000644000175000017500000000326311753011774032716 0ustar ebourgebourg/* Copyright (c) 2000-2006 hamcrest.org */ package org.hamcrest.text; import static org.hamcrest.core.StringStartsWith.startsWith; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.Matcher; public class StringStartsWithTest extends AbstractMatcherTest { static final String EXCERPT = "EXCERPT"; Matcher stringStartsWith = startsWith(EXCERPT); @Override protected Matcher createMatcher() { return stringStartsWith; } public void testEvaluatesToTrueIfArgumentContainsSpecifiedSubstring() { assertTrue("should be true if excerpt at beginning", stringStartsWith.matches(EXCERPT + "END")); assertFalse("should be false if excerpt at end", stringStartsWith.matches("START" + EXCERPT)); assertFalse("should be false if excerpt in middle", stringStartsWith.matches("START" + EXCERPT + "END")); assertTrue("should be true if excerpt is at beginning and repeated", stringStartsWith.matches(EXCERPT + EXCERPT)); assertFalse("should be false if excerpt is not in string", stringStartsWith.matches("Something else")); assertFalse("should be false if part of excerpt is at start of string", stringStartsWith.matches(EXCERPT.substring(1))); } public void testEvaluatesToTrueIfArgumentIsEqualToSubstring() { assertTrue("should be true if excerpt is entire string", stringStartsWith.matches(EXCERPT)); } public void testHasAReadableDescription() { assertDescription("a string starting with \"EXCERPT\"", stringStartsWith); } } libhamcrest-java-1.3/hamcrest-unit-test/src/main/hamcrest-unit-tests.iml0000644000175000017500000000152411753011773026031 0ustar ebourgebourg libhamcrest-java-1.3/hamcrest-generator/0000755000175000017500000000000011753011773017720 5ustar ebourgebourglibhamcrest-java-1.3/hamcrest-generator/src/0000755000175000017500000000000011753011773020507 5ustar ebourgebourglibhamcrest-java-1.3/hamcrest-generator/src/main/0000755000175000017500000000000012131006721021417 5ustar ebourgebourglibhamcrest-java-1.3/hamcrest-generator/src/main/java/0000755000175000017500000000000011753011773022354 5ustar ebourgebourglibhamcrest-java-1.3/hamcrest-generator/src/main/java/org/0000755000175000017500000000000011753011773023143 5ustar ebourgebourglibhamcrest-java-1.3/hamcrest-generator/src/main/java/org/hamcrest/0000755000175000017500000000000011753011773024751 5ustar ebourgebourglibhamcrest-java-1.3/hamcrest-generator/src/main/java/org/hamcrest/generator/0000755000175000017500000000000012131006721026723 5ustar ebourgebourglibhamcrest-java-1.3/hamcrest-generator/src/main/java/org/hamcrest/generator/SugarGenerator.java0000644000175000017500000000751211753011773032537 0ustar ebourgebourgpackage org.hamcrest.generator; import java.io.Closeable; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * API for syntactic sugar and wrapper code generation framework. *

Generally, Matcher factory methods are defined all over the place, which makes it * really hard to remember which methods need to be imported and doesn't allow you * to easily browse a list of all of them. *

This generates one uber matcher factory that delegates to all the respective classes. *

Additionally, this allows the uber-classes to do things like wrap matchers in adapters * (e.g. to make them EasyMock friendly) or even generate wrappers in other languages * (such as JRuby or Jython). *

You need to add at least one writer and at least one factory method for this to be * any help. *

Usage

*
 * SugarGenerator sugarGenerator = new SugarGenerator();
 * try {
 *   // Write out sugar as standard Hamcrest factories.
 *   sugarGenerator.addWriter(
 *     new HamcrestFactoryWriter("com.some.package", "MyMatcherClass", new FileWriter(...)));
 *   // Also write out sugar as EasyMock compatible factories.
 *   sugarGenerator.addWriter(
 *     new EasyMockFactoryWriter("com.some.package", "MyEasyMatcherClass", new FileWriter(...)));
 *   // Add a load of Matcher factories to the generated sugar. The factory methods
 *   // are read via reflection.
 *   sugarGenerator.addFactoryMethods(new ReflectiveFactoryReader(IsIn.class));
 *   sugarGenerator.addFactoryMethods(new ReflectiveFactoryReader(IsSame.class));
 *   sugarGenerator.addFactoryMethods(new ReflectiveFactoryReader(IsNot.class));
 *   // Generate everything!
 *   sugarGenerator.generate();
 * } finally {
 *   // Clean up... close all streams.
 *   sugarGenerator.close();
 * }
* * @author Joe Walnes * @see FactoryWriter * @see HamcrestFactoryWriter * @see ReflectiveFactoryReader */ public class SugarGenerator implements Closeable, SugarConfiguration { private final List factoryWriters = new ArrayList(); private final List factoryMethods = new ArrayList(); /** * Add a writer of factories. */ @Override public void addWriter(FactoryWriter factoryWriter) { factoryWriters.add(factoryWriter); } /** * Add a FactoryMethod that will be generated in the sugar. * * @see ReflectiveFactoryReader * @see FactoryMethod */ @Override public void addFactoryMethod(FactoryMethod method) { factoryMethods.add(method); } /** * Convient way to add multiple FactoryMethods. * * @see #addFactoryMethod(FactoryMethod) */ @Override public void addFactoryMethods(Iterable methods) { for (FactoryMethod method : methods) { addFactoryMethod(method); } } /** * Generate all the factory methods using all the writers. * * This should always happen AFTER adding factory methods and writers. */ public void generate() throws IOException { for (FactoryWriter factoryWriter : factoryWriters) { factoryWriter.writeHeader(); for (FactoryMethod factoryMethod : factoryMethods) { factoryWriter.writeMethod(factoryMethod.getName(), factoryMethod); } factoryWriter.writeFooter(); factoryWriter.flush(); } } /** * Close all underlying streams. Calling this means you don't have to explicitly * keep track of all the File streams and close them. */ @Override public void close() throws IOException { for (FactoryWriter factoryWriter : factoryWriters) { factoryWriter.close(); } } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootlibhamcrest-java-1.3/hamcrest-generator/src/main/java/org/hamcrest/generator/ReflectiveFactoryReader.javalibhamcrest-java-1.3/hamcrest-generator/src/main/java/org/hamcrest/generator/ReflectiveFactoryReader0000644000175000017500000001534511767324353033443 0ustar ebourgebourgpackage org.hamcrest.generator; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import static java.lang.reflect.Modifier.isPublic; import static java.lang.reflect.Modifier.isStatic; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.util.Iterator; /** * Reads a list of Hamcrest factory methods from a class, using standard Java reflection. *

Usage

*
 * for (FactoryMethod method : new ReflectiveFactoryReader(MyMatchers.class)) {
 *   ...
 * }
 * 
*

All methods matching signature '@Factory public static Matcher blah(blah)' will be * treated as factory methods. To change this behavior, override {@link #isFactoryMethod(Method)}. *

Caveat: Reflection is hassle-free, but unfortunately cannot expose method parameter names or JavaDoc * comments, making the sugar slightly more obscure. * * @author Joe Walnes * @see SugarGenerator * @see FactoryMethod */ public class ReflectiveFactoryReader implements Iterable { private final Class cls; private final ClassLoader classLoader; public ReflectiveFactoryReader(Class cls) { this.cls = cls; this.classLoader = cls.getClassLoader(); } @Override public Iterator iterator() { return new Iterator() { private int currentMethod = -1; private Method[] allMethods = cls.getMethods(); @Override public boolean hasNext() { while (true) { currentMethod++; if (currentMethod >= allMethods.length) { return false; } else if (isFactoryMethod(allMethods[currentMethod])) { return true; } // else carry on looping and try the next one. } } @Override public FactoryMethod next() { if (outsideArrayBounds()) { throw new IllegalStateException("next() called without hasNext() check."); } return buildFactoryMethod(allMethods[currentMethod]); } @Override public void remove() { throw new UnsupportedOperationException(); } private boolean outsideArrayBounds() { return currentMethod < 0 || allMethods.length <= currentMethod; } }; } /** * Determine whether a particular method is classified as a matcher factory method. *

*

The rules for determining this are: * 1. The method must be public static. * 2. It must have a return type of org.hamcrest.Matcher (or something that extends this). * 3. It must be marked with the org.hamcrest.Factory annotation. *

*

To use another set of rules, override this method. */ protected boolean isFactoryMethod(Method javaMethod) { return isStatic(javaMethod.getModifiers()) && isPublic(javaMethod.getModifiers()) && hasFactoryAnnotation(javaMethod) && !Void.TYPE.equals(javaMethod.getReturnType()); } @SuppressWarnings("unchecked") private boolean hasFactoryAnnotation(Method javaMethod) { // We dynamically load the Factory class, to avoid a compile time // dependency on org.hamcrest.Factory. This gets around // a circular bootstrap issue (because generator is required to // compile core). try { final Class factoryClass = classLoader.loadClass("org.hamcrest.Factory"); if (!Annotation.class.isAssignableFrom(factoryClass)) { throw new RuntimeException("Not an annotation class: " + factoryClass.getCanonicalName()); } return javaMethod.getAnnotation((Class)factoryClass) != null; } catch (ClassNotFoundException e) { throw new RuntimeException("Cannot load hamcrest core", e); } } private static FactoryMethod buildFactoryMethod(Method javaMethod) { FactoryMethod result = new FactoryMethod( classToString(javaMethod.getDeclaringClass()), javaMethod.getName(), classToString(javaMethod.getReturnType())); for (TypeVariable typeVariable : javaMethod.getTypeParameters()) { boolean hasBound = false; StringBuilder s = new StringBuilder(typeVariable.getName()); for (Type bound : typeVariable.getBounds()) { if (bound != Object.class) { if (hasBound) { s.append(" & "); } else { s.append(" extends "); hasBound = true; } s.append(typeToString(bound)); } } result.addGenericTypeParameter(s.toString()); } Type returnType = javaMethod.getGenericReturnType(); if (returnType instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) returnType; Type generifiedType = parameterizedType.getActualTypeArguments()[0]; result.setGenerifiedType(typeToString(generifiedType)); } int paramNumber = 0; for (Type paramType : javaMethod.getGenericParameterTypes()) { String type = typeToString(paramType); // Special case for var args methods.... String[] -> String... if (javaMethod.isVarArgs() && paramNumber == javaMethod.getParameterTypes().length - 1) { type = type.replaceFirst("\\[\\]$", "..."); } result.addParameter(type, "param" + (++paramNumber)); } for (Class exception : javaMethod.getExceptionTypes()) { result.addException(typeToString(exception)); } return result; } /* * Get String representation of Type (e.g. java.lang.String or Map<Stuff,? extends Cheese>). *

* Annoyingly this method wouldn't be needed if java.lang.reflect.Type.toString() behaved consistently * across implementations. Rock on Liskov. */ private static String typeToString(Type type) { return type instanceof Class ? classToString((Class) type): type.toString(); } private static String classToString(Class cls) { final String name = cls.isArray() ? cls.getComponentType().getName() + "[]" : cls.getName(); return name.replace('$', '.'); } }libhamcrest-java-1.3/hamcrest-generator/src/main/java/org/hamcrest/generator/QDox.java0000644000175000017500000000167111753011773030462 0ustar ebourgebourgpackage org.hamcrest.generator; import com.thoughtworks.qdox.JavaDocBuilder; import com.thoughtworks.qdox.model.JavaClass; import java.io.File; import java.io.Reader; /** * Wraps QDox library. This is because to ease distribution, QDox is bundled into * hamcrest-generator.jar and has its package renamed to ensure there is no conflict * (using Jar Jar Links). This wrapper class removes all traces of QDox from Hamcrest's * public API, so there aren't any compatibility problems. * * @author Joe Walnes */ public class QDox { private final JavaDocBuilder javaDocBuilder = new JavaDocBuilder(); public void addSourceTree(File sourceDir) { javaDocBuilder.addSourceTree(sourceDir); } public void addSource(Reader reader) { javaDocBuilder.addSource(reader); } JavaClass getClassByName(String className) { return javaDocBuilder.getClassByName(className); } } libhamcrest-java-1.3/hamcrest-generator/src/main/java/org/hamcrest/generator/QDoxFactoryReader.java0000644000175000017500000001060311756154507033136 0ustar ebourgebourgpackage org.hamcrest.generator; import com.thoughtworks.qdox.model.DocletTag; import com.thoughtworks.qdox.model.JavaClass; import com.thoughtworks.qdox.model.JavaMethod; import com.thoughtworks.qdox.model.JavaParameter; import com.thoughtworks.qdox.model.Type; import java.util.Iterator; import java.util.List; import java.util.regex.Pattern; /** * Wraps an existing sequence of FactoryMethods, and attempts to pull in * parameter names and JavaDoc (which aren't available using reflection) using * QDox. * * @see QDox * @author Joe Walnes */ public class QDoxFactoryReader implements Iterable { private final Iterable wrapped; private final JavaClass classSource; private static final Pattern GENERIC_REGEX = Pattern.compile("<.*>"); private static final Pattern VARARGS_REGEX = Pattern.compile("...", Pattern.LITERAL); public QDoxFactoryReader(Iterable wrapped, QDox qdox, String className) { this.wrapped = wrapped; this.classSource = qdox.getClassByName(className); } @Override public Iterator iterator() { final Iterator iterator = wrapped.iterator(); return new Iterator() { @Override public boolean hasNext() { return iterator.hasNext(); } @Override public FactoryMethod next() { return enhance(iterator.next()); } @Override public void remove() { iterator.remove(); } }; } private FactoryMethod enhance(FactoryMethod factoryMethod) { JavaMethod methodSource = findMethodInSource(factoryMethod); if (methodSource != null) { factoryMethod.setJavaDoc(createJavaDocComment(methodSource)); JavaParameter[] parametersFromSource = methodSource.getParameters(); List parametersFromReflection = factoryMethod.getParameters(); if (parametersFromReflection.size() == parametersFromSource.length) { for (int i = 0; i < parametersFromSource.length; i++) { parametersFromReflection.get(i).setName( parametersFromSource[i].getName()); } } } return factoryMethod; } /** * Attempts to locate the source code for a specific method, by cross-referencing * the signature returned by reflection with the list of methods parsed by QDox. */ private JavaMethod findMethodInSource(FactoryMethod factoryMethod) { // Note, this doesn't always work - it struggles with some kinds of generics. // This seems to cover most cases though. List params = factoryMethod.getParameters(); Type[] types = new Type[params.size()]; boolean varArgs = false; for (int i = 0; i < types.length; i++) { String type = params.get(i).getType(); varArgs = VARARGS_REGEX.matcher(type).find(); // QDox ignores varargs and generics, so we strip them out to help QDox. type = GENERIC_REGEX.matcher(type).replaceAll(""); type = VARARGS_REGEX.matcher(type).replaceAll(""); types[i] = new Type(type); } JavaMethod[] methods = classSource.getMethodsBySignature(factoryMethod.getName(), types, false, varArgs); return methods.length == 1 ? methods[0] : null; } /** * Reconstructs the JavaDoc as a string for a particular method. */ private static String createJavaDocComment(JavaMethod methodSource) { String comment = methodSource.getComment(); DocletTag[] tags = methodSource.getTags(); if ((comment == null || comment.trim().length() == 0) && tags.length == 0) { return null; } StringBuilder result = new StringBuilder(); result.append(comment); result.append("\n\n"); for (DocletTag tag : tags) { result.append('@').append(tag.getName()) .append(' ').append(tag.getValue()) .append('\n'); } return result.toString(); } } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootlibhamcrest-java-1.3/hamcrest-generator/src/main/java/org/hamcrest/generator/HamcrestFactoryWriter.javalibhamcrest-java-1.3/hamcrest-generator/src/main/java/org/hamcrest/generator/HamcrestFactoryWriter.j0000644000175000017500000001430011753011773033403 0ustar ebourgebourgpackage org.hamcrest.generator; import java.io.IOException; import java.io.PrintWriter; import java.io.Writer; import java.util.StringTokenizer; /** * {@link FactoryWriter} that outputs Java code which simply delegates all * Hamcrest factory methods to factory methods elsewhere. This is useful for * grouping lots of matcher classes into one class, so you only have to look * in one place for matchers. * * @author Joe Walnes * @see FactoryWriter */ public class HamcrestFactoryWriter implements FactoryWriter { private final PrintWriter output; private final String javaPackageName; private final String javaClassName; private String indentationString = " "; private String newLine = "\n"; private int indentation = 1; public HamcrestFactoryWriter(String javaPackageName, String javaClassName, Writer output) { this.javaPackageName = javaPackageName; this.javaClassName = javaClassName; this.output = new PrintWriter(output); } @Override public void writeHeader() throws IOException { output.append("// Generated source.").append(newLine) .append("package ").append(javaPackageName).append(';').append(newLine).append(newLine); output.append("public class ").append(javaClassName).append(" {").append(newLine).append(newLine); } @Override public void writeFooter() throws IOException { output.append('}').append(newLine); } @Override public void close() throws IOException { output.close(); } @Override public void flush() throws IOException { output.flush(); } @Override public void writeMethod(String generatedMethodName, FactoryMethod factoryMethodToDelegateTo) throws IOException { writeJavaDoc(factoryMethodToDelegateTo); indent(); output.append("public static "); writeGenericTypeParameters(factoryMethodToDelegateTo); output.append(factoryMethodToDelegateTo.getReturnType()); if (factoryMethodToDelegateTo.getGenerifiedType() != null) { output.append('<').append(factoryMethodToDelegateTo.getGenerifiedType()).append('>'); } output.append(' ').append(generatedMethodName); writeParameters(factoryMethodToDelegateTo); writeExceptions(factoryMethodToDelegateTo); output.append(" {").append(newLine); indentation++; writeMethodBody(factoryMethodToDelegateTo); indentation--; indent(); output.append('}').append(newLine).append(newLine); } private void writeGenericTypeParameters(FactoryMethod factoryMethod) { if (!factoryMethod.getGenericTypeParameters().isEmpty()) { output.append('<'); boolean seenFirst = false; for (String type : factoryMethod.getGenericTypeParameters()) { if (seenFirst) { output.append(", "); } else { seenFirst = true; } output.append(type); } output.append("> "); } } private void writeMethodBody(FactoryMethod factoryMethod) { indent(); output.append("return ").append(factoryMethod.getMatcherClass()); output.append('.'); // lets write the generic types if (!factoryMethod.getGenericTypeParameters().isEmpty()) { output.append('<'); boolean seenFirst = false; for (String type : factoryMethod.getGenericTypeParameters()) { if (seenFirst) { output.append(","); } else { seenFirst = true; } // lets only print the first word of the type // so if its 'T extends Cheese' we just print T //output.append(type); StringTokenizer iter = new StringTokenizer(type); iter.hasMoreElements(); output.append(iter.nextToken()); } output.append(">"); } output.append(factoryMethod.getName()); output.append('('); boolean seenFirst = false; for (FactoryMethod.Parameter parameter : factoryMethod.getParameters()) { if (seenFirst) { output.append(", "); } else { seenFirst = true; } output.append(parameter.getName()); } output.append(')'); output.append(';').append(newLine); } private void writeExceptions(FactoryMethod factoryMethod) { boolean seenFirst = false; for (String exception : factoryMethod.getExceptions()) { if (seenFirst) { output.append(", "); } else { output.append(" throws "); seenFirst = true; } output.append(exception); } } private void writeParameters(FactoryMethod factoryMethod) { output.append('('); boolean seenFirst = false; for (FactoryMethod.Parameter parameter : factoryMethod.getParameters()) { if (seenFirst) { output.append(", "); } else { seenFirst = true; } output.append(parameter.getType()).append(' ').append(parameter.getName()); } output.append(')'); } private void writeJavaDoc(FactoryMethod factoryMethod) { if (factoryMethod.getJavaDoc() != null) { String[] lines = factoryMethod.getJavaDoc().split("\n"); if (lines.length > 0) { indent(); output.append("/**").append(newLine); for (String line : lines) { indent(); output.append(" * ").append(line).append(newLine); } indent(); output.append(" */").append(newLine); } } } private void indent() { for (int i = 0; i < indentation; i++) { output.append(indentationString); } } } libhamcrest-java-1.3/hamcrest-generator/src/main/java/org/hamcrest/generator/config/0000755000175000017500000000000012131006721030170 5ustar ebourgebourg././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootlibhamcrest-java-1.3/hamcrest-generator/src/main/java/org/hamcrest/generator/config/XmlConfigurator.javalibhamcrest-java-1.3/hamcrest-generator/src/main/java/org/hamcrest/generator/config/XmlConfigurator.0000644000175000017500000001257011753011773033335 0ustar ebourgebourgpackage org.hamcrest.generator.config; import org.hamcrest.generator.HamcrestFactoryWriter; import org.hamcrest.generator.QDoxFactoryReader; import org.hamcrest.generator.QuickReferenceWriter; import org.hamcrest.generator.ReflectiveFactoryReader; import org.hamcrest.generator.SugarConfiguration; import org.hamcrest.generator.SugarGenerator; import org.hamcrest.generator.QDox; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import java.io.File; import java.io.FileWriter; import java.io.IOException; public class XmlConfigurator { private final SugarConfiguration sugarConfiguration; private final ClassLoader classLoader; private final SAXParserFactory saxParserFactory; private final QDox qdox; public XmlConfigurator(SugarConfiguration sugarConfiguration, ClassLoader classLoader) { this.sugarConfiguration = sugarConfiguration; this.classLoader = classLoader; saxParserFactory = SAXParserFactory.newInstance(); saxParserFactory.setNamespaceAware(true); qdox = new QDox(); } public void addSourceDir(File sourceDir) { qdox.addSourceTree(sourceDir); } public void load(InputSource inputSource) throws ParserConfigurationException, SAXException, IOException { SAXParser saxParser = saxParserFactory.newSAXParser(); saxParser.parse(inputSource, new DefaultHandler() { @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (localName.equals("factory")) { String className = attributes.getValue("class"); try { addClass(className); } catch (ClassNotFoundException e) { throw new SAXException("Cannot find Matcher class : " + className); } } } }); } private void addClass(String className) throws ClassNotFoundException { Class cls = classLoader.loadClass(className); sugarConfiguration.addFactoryMethods( new QDoxFactoryReader(new ReflectiveFactoryReader(cls), qdox, className)); } public static void main(String[] args) throws Exception { if (args.length != 4) { System.err.println("Args: config-file source-dir generated-class output-dir"); System.err.println(""); System.err.println(" config-file : Path to config file listing matchers to generate sugar for."); System.err.println(" e.g. path/to/matchers.xml"); System.err.println(""); System.err.println(" source-dir : Path to Java source containing matchers to generate sugar for."); System.err.println(" May contain multiple paths, separated by commas."); System.err.println(" e.g. src/java,src/more-java"); System.err.println(""); System.err.println("generated-class : Full name of class to generate."); System.err.println(" e.g. org.myproject.MyMatchers"); System.err.println(""); System.err.println(" output-dir : Where to output generated code (package subdirs will be"); System.err.println(" automatically created)."); System.err.println(" e.g. build/generated-code"); System.exit(-1); } String configFile = args[0]; String srcDirs = args[1]; String fullClassName = args[2]; File outputDir = new File(args[3]); String fileName = fullClassName.replace('.', File.separatorChar) + ".java"; int dotIndex = fullClassName.lastIndexOf("."); String packageName = dotIndex == -1 ? "" : fullClassName.substring(0, dotIndex); String shortClassName = fullClassName.substring(dotIndex + 1); if (!outputDir.isDirectory()) { System.err.println("Output directory not found : " + outputDir.getAbsolutePath()); System.exit(-1); } File outputFile = new File(outputDir, fileName); outputFile.getParentFile().mkdirs(); SugarGenerator sugarGenerator = new SugarGenerator(); try { sugarGenerator.addWriter(new HamcrestFactoryWriter( packageName, shortClassName, new FileWriter(outputFile))); sugarGenerator.addWriter(new QuickReferenceWriter(System.out)); XmlConfigurator xmlConfigurator = new XmlConfigurator(sugarGenerator, XmlConfigurator.class.getClassLoader()); if (srcDirs.trim().length() > 0) { for (String srcDir : srcDirs.split(",")) { xmlConfigurator.addSourceDir(new File(srcDir)); } } xmlConfigurator.load(new InputSource(configFile)); System.out.println("Generating " + fullClassName); sugarGenerator.generate(); } finally { sugarGenerator.close(); } } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootlibhamcrest-java-1.3/hamcrest-generator/src/main/java/org/hamcrest/generator/EasyMock2FactoryWriter.javalibhamcrest-java-1.3/hamcrest-generator/src/main/java/org/hamcrest/generator/EasyMock2FactoryWriter.0000644000175000017500000001156711753011773033274 0ustar ebourgebourgpackage org.hamcrest.generator; import java.io.PrintWriter; import java.io.Writer; import java.io.IOException; /** * {@link FactoryWriter} that outputs Java code which simply delegates all * factory methods to factory methods elsewhere. This is useful for grouping * lots of matcher classes into one class, so you know where to look to find * matchers. * * @author Joe Walnes * @see FactoryWriter */ public class EasyMock2FactoryWriter implements FactoryWriter { private final PrintWriter output; private final String javaPackageName; private final String javaClassName; private String indentationString = " "; private String newLine = "\n"; private int indentation = 1; public EasyMock2FactoryWriter(Writer output, String javaPackageName, String javaClassName) { this.javaPackageName = javaPackageName; this.javaClassName = javaClassName; this.output = new PrintWriter(output); } @Override public void writeHeader() throws IOException { output.append("package ").append(javaPackageName).append(';').append(newLine).append(newLine); output.append("public class ").append(javaClassName).append(" {").append(newLine).append(newLine); } @Override public void writeFooter() throws IOException { output.append('}').append(newLine); } @Override public void close() throws IOException { output.close(); } @Override public void flush() throws IOException { output.flush(); } @Override public void writeMethod(String generatedMethodName, FactoryMethod factoryMethodToDelegateTo) throws IOException { writeJavaDoc(factoryMethodToDelegateTo); indent(); output.append("public static "); //writeGenericTypeParameters(factoryMethodToDelegateTo); String returnType = factoryMethodToDelegateTo.getGenerifiedType(); if (returnType == null) { returnType = "java.lang.Object"; } output.append(returnType); output.append(' ').append(generatedMethodName); writeParameters(factoryMethodToDelegateTo); writeExceptions(factoryMethodToDelegateTo); output.append(" {").append(newLine); indentation++; writeMethodBody(factoryMethodToDelegateTo); indentation--; indent(); output.append('}').append(newLine).append(newLine); } private void writeMethodBody(FactoryMethod factoryMethod) { indent(); output.append("org.hamcrest.integration.EasyMockAdapter.adapt(").append(newLine); indentation++; indent(); output.append(factoryMethod.getMatcherClass()); output.append('.').append(factoryMethod.getName()); output.append('('); boolean seenFirst = false; for (FactoryMethod.Parameter parameter : factoryMethod.getParameters()) { if (seenFirst) { output.append(", "); } else { seenFirst = true; } output.append(parameter.getName()); } output.append("));").append(newLine); indentation--; indent(); output.append("return null;").append(newLine); } private void writeExceptions(FactoryMethod factoryMethod) { boolean seenFirst = false; for (String exception : factoryMethod.getExceptions()) { if (seenFirst) { output.append(", "); } else { output.append(" throws "); seenFirst = true; } output.append(exception); } } private void writeParameters(FactoryMethod factoryMethod) { output.append('('); boolean seenFirst = false; for (FactoryMethod.Parameter parameter : factoryMethod.getParameters()) { if (seenFirst) { output.append(", "); } else { seenFirst = true; } output.append(parameter.getType()).append(' ').append(parameter.getName()); } output.append(')'); } private void writeJavaDoc(FactoryMethod factoryMethod) { if (factoryMethod.getJavaDoc() != null) { String[] lines = factoryMethod.getJavaDoc().split("\n"); if (lines.length > 0) { indent(); output.append("/**").append(newLine); for (String line : lines) { indent(); output.append(" * ").append(line).append(newLine); } indent(); output.append(" */").append(newLine); } } } private void indent() { for (int i = 0; i < indentation; i++) { output.append(indentationString); } } } libhamcrest-java-1.3/hamcrest-generator/src/main/java/org/hamcrest/generator/FactoryWriter.java0000644000175000017500000000234211753011773032407 0ustar ebourgebourgpackage org.hamcrest.generator; import java.io.Closeable; import java.io.Flushable; import java.io.IOException; /** * Writes syntactic sugar code for factories. *

Implementations of this could include vanilla factory methods for * Hamcrest matchers, wrapped factories for other libraries or factories * in other languages (jython, jruby, groovy, etc). *

Usage:

*
 * writer.writeHeader(...);
 * 

* writer.writeMethod(...); * writer.writeMethod(...); * writer.writeMethod(...); * ... * writer.writeFooter(...); * writer.close(); *

* * @author Joe Walnes * @see FactoryMethod * @see SugarGenerator * @see HamcrestFactoryWriter */ public interface FactoryWriter extends Closeable, Flushable { /** * Write the code header. */ void writeHeader() throws IOException; /** * Writes code that delegates to a method. * * @param generatedMethodName * @param factoryMethodToDelegateTo */ void writeMethod(String generatedMethodName, FactoryMethod factoryMethodToDelegateTo) throws IOException; /** * Write any necessary code to finish the output. */ void writeFooter() throws IOException; } libhamcrest-java-1.3/hamcrest-generator/src/main/java/org/hamcrest/generator/SugarConfiguration.java0000644000175000017500000000036311753011773033415 0ustar ebourgebourgpackage org.hamcrest.generator; public interface SugarConfiguration { void addWriter(FactoryWriter factoryWriter); void addFactoryMethod(FactoryMethod method); void addFactoryMethods(Iterable methods); } libhamcrest-java-1.3/hamcrest-generator/src/main/java/org/hamcrest/generator/FactoryMethod.java0000644000175000017500000001775711765131155032373 0ustar ebourgebourgpackage org.hamcrest.generator; import java.util.ArrayList; import static java.util.Collections.unmodifiableList; import java.util.List; /** * Represents a Matcher Factory method. *

*

This class uses Strings to represent things instead of java.lang.reflect equivalents, * allowing methods to be defined from sources other than reflection of classes in the * classpath. * * @author Joe Walnes * @see SugarGenerator */ public class FactoryMethod { private final String matcherClass; private final String factoryMethod; private final String returnType; private String generifiedType; private List parameters = new ArrayList(); private List exceptions = new ArrayList(); private List genericTypeParameters = new ArrayList(); private String javaDoc; public FactoryMethod(String matcherClass, String factoryMethod, String returnType) { this.matcherClass = matcherClass; this.factoryMethod = factoryMethod; this.returnType = returnType; } /** * Original class this factory method came from. */ public String getMatcherClass() { return matcherClass; } /** * @return The fully qualified name of the type returned by the method. This should be a * subclass of org.hamcrest.Matcher. */ public String getReturnType() { return returnType; } /** * Original name of factory method. */ public String getName() { return factoryMethod; } public void setGenerifiedType(String generifiedType) { this.generifiedType = generifiedType; } /** * Generified type of matcher. * ie. 'public Matcher<THISBIT> blah(...)' */ public String getGenerifiedType() { return generifiedType; } public void addParameter(String type, String name) { parameters.add(new Parameter(type, name)); } /** * List of Parameters passed to factory method. * ie. 'public Matcher<...&ht;> blah(THIS, AND, THAT)' */ public List getParameters() { return unmodifiableList(parameters); } public void addException(String exception) { exceptions.add(exception); } /** * List of exceptions thrown by factory method. * ie. 'public Matcher<...> blah(...) throws THIS, THAT' */ public List getExceptions() { return unmodifiableList(exceptions); } public void addGenericTypeParameter(String genericTypeParameter) { genericTypeParameters.add(genericTypeParameter); } /** * List of generic type parameters for factory method definition. * ie. 'public <THIS,THAT> Matcher<...> blah(...)' */ public List getGenericTypeParameters() { return unmodifiableList(genericTypeParameters); } public void setJavaDoc(String javaDoc) { this.javaDoc = javaDoc; } /** * JavaDoc definition of factory method. * Excludes surrounding comment markers. * Note that using standard Java reflection it is not possible to obtain this, * however source code parsers can read this. */ public String getJavaDoc() { return javaDoc; } // Generated in Eclipse... // n.b. Doesn't include returnType @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; FactoryMethod other = (FactoryMethod) obj; if (exceptions == null) { if (other.exceptions != null) return false; } else if (!exceptions.equals(other.exceptions)) return false; if (factoryMethod == null) { if (other.factoryMethod != null) return false; } else if (!factoryMethod.equals(other.factoryMethod)) return false; if (genericTypeParameters == null) { if (other.genericTypeParameters != null) return false; } else if (!genericTypeParameters.equals(other.genericTypeParameters)) return false; if (generifiedType == null) { if (other.generifiedType != null) return false; } else if (!generifiedType.equals(other.generifiedType)) return false; if (javaDoc == null) { if (other.javaDoc != null) return false; } else if (!javaDoc.equals(other.javaDoc)) return false; if (matcherClass == null) { if (other.matcherClass != null) return false; } else if (!matcherClass.equals(other.matcherClass)) return false; if (parameters == null) { if (other.parameters != null) return false; } else if (!parameters.equals(other.parameters)) return false; return true; } // Generated in Eclipse... @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((exceptions == null) ? 0 : exceptions.hashCode()); result = prime * result + ((factoryMethod == null) ? 0 : factoryMethod.hashCode()); result = prime * result + ((genericTypeParameters == null) ? 0 : genericTypeParameters.hashCode()); result = prime * result + ((generifiedType == null) ? 0 : generifiedType.hashCode()); result = prime * result + ((javaDoc == null) ? 0 : javaDoc.hashCode()); result = prime * result + ((matcherClass == null) ? 0 : matcherClass.hashCode()); result = prime * result + ((parameters == null) ? 0 : parameters.hashCode()); return result; } @Override public String toString() { return "{FactoryMethod: \n" + " matcherClass = " + matcherClass + "\n" + " factoryMethod = " + factoryMethod + "\n" + " generifiedType = " + generifiedType + "\n" + " parameters = " + parameters + "\n" + " exceptions = " + exceptions + "\n" + " genericTypeParameters = " + genericTypeParameters + "\n" + " javaDoc = " + javaDoc + "\n" + "}"; } /** * Represents a parameter passed to a factory method. * * @see FactoryMethod */ public static class Parameter { private final String type; private String name; public Parameter(String type, String name) { this.type = type; this.name = name; } /** * Type of parameter, including any generic declarations. */ public String getType() { return type; } /** * Name of parameter, if it can be obtained. If it cannot * be obtained, a sensible default will returned instead. */ public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return type + " " + name; } // Generated in Eclipse... @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + ((type == null) ? 0 : type.hashCode()); return result; } // Generated in Eclipse... @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Parameter other = (Parameter) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; if (type == null) { if (other.type != null) return false; } else if (!type.equals(other.type)) return false; return true; } } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibhamcrest-java-1.3/hamcrest-generator/src/main/java/org/hamcrest/generator/QuickReferenceWriter.javalibhamcrest-java-1.3/hamcrest-generator/src/main/java/org/hamcrest/generator/QuickReferenceWriter.ja0000644000175000017500000000400011753011773033335 0ustar ebourgebourgpackage org.hamcrest.generator; import java.io.IOException; import java.io.PrintStream; /** * Dumps a quick list of factory methods. Designed to be read by users, as a cheatsheet. * * @author Joe Walnes */ public class QuickReferenceWriter implements FactoryWriter { private final PrintStream out; private int columnPosition = 14; public QuickReferenceWriter(PrintStream out) { this.out = out; } public QuickReferenceWriter() { this(System.out); } public void setColumnPosition(int columnPosition) { this.columnPosition = columnPosition; } @Override public void writeHeader() throws IOException { } @Override public void writeMethod(String generatedMethodName, FactoryMethod factoryMethod) throws IOException { String actsOn = removePackageNames(factoryMethod.getGenerifiedType()); for (int i = actsOn.length(); i < columnPosition; i++) { out.append(' '); } out.append('[').append(actsOn).append("] "); out.append(generatedMethodName); out.append('('); boolean seenFirst = false; for (FactoryMethod.Parameter parameter : factoryMethod.getParameters()) { if (seenFirst) { out.append(", "); } else { seenFirst = true; } out.append(removePackageNames(parameter.getType())); out.append(' '); out.append(parameter.getName()); } out.append(')'); out.println(); } private static String removePackageNames(String in) { // Simplify fully qualified names (allowing for trailing '...'). return in == null ? "" : in.replaceAll("[^<>]*\\.([^\\.])", "$1"); } @Override public void writeFooter() throws IOException { } @Override public void close() throws IOException { } @Override public void flush() throws IOException { } } libhamcrest-java-1.3/hamcrest-generator/src/main/hamcrest-generator.iml0000644000175000017500000000117111753011773025730 0ustar ebourgebourg libhamcrest-java-1.3/hamcrest-library/0000755000175000017500000000000011753011773017376 5ustar ebourgebourglibhamcrest-java-1.3/hamcrest-library/src/0000755000175000017500000000000011753011773020165 5ustar ebourgebourglibhamcrest-java-1.3/hamcrest-library/src/main/0000755000175000017500000000000012131006721021075 5ustar ebourgebourglibhamcrest-java-1.3/hamcrest-library/src/main/java/0000755000175000017500000000000011753011773022032 5ustar ebourgebourglibhamcrest-java-1.3/hamcrest-library/src/main/java/org/0000755000175000017500000000000011753011773022621 5ustar ebourgebourglibhamcrest-java-1.3/hamcrest-library/src/main/java/org/hamcrest/0000755000175000017500000000000011753011773024427 5ustar ebourgebourglibhamcrest-java-1.3/hamcrest-library/src/main/java/org/hamcrest/number/0000755000175000017500000000000012131006721025703 5ustar ebourgebourglibhamcrest-java-1.3/hamcrest-library/src/main/java/org/hamcrest/number/IsCloseTo.java0000644000175000017500000000356111756210507030432 0ustar ebourgebourg/* Copyright (c) 2000-2006 hamcrest.org */ package org.hamcrest.number; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.Factory; import org.hamcrest.TypeSafeMatcher; /** * Is the value a number equal to a value within some range of * acceptable error? */ public class IsCloseTo extends TypeSafeMatcher { private final double delta; private final double value; public IsCloseTo(double value, double error) { this.delta = error; this.value = value; } @Override public boolean matchesSafely(Double item) { return actualDelta(item) <= 0.0; } @Override public void describeMismatchSafely(Double item, Description mismatchDescription) { mismatchDescription.appendValue(item) .appendText(" differed by ") .appendValue(actualDelta(item)); } @Override public void describeTo(Description description) { description.appendText("a numeric value within ") .appendValue(delta) .appendText(" of ") .appendValue(value); } private double actualDelta(Double item) { return (Math.abs((item - value)) - delta); } /** * Creates a matcher of {@link Double}s that matches when an examined double is equal * to the specified operand, within a range of +/- error. *

* For example: *

assertThat(1.03, is(closeTo(1.0, 0.03)))
* * @param operand * the expected value of matching doubles * @param error * the delta (+/-) within which matches will be allowed */ @Factory public static Matcher closeTo(double operand, double error) { return new IsCloseTo(operand, error); } } libhamcrest-java-1.3/hamcrest-library/src/main/java/org/hamcrest/number/OrderingComparison.java0000644000175000017500000001222411756203335032367 0ustar ebourgebourg/* Copyright (c) 2000-2009 hamcrest.org */ package org.hamcrest.number; import org.hamcrest.Description; import org.hamcrest.Factory; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; import static java.lang.Integer.signum; public class OrderingComparison> extends TypeSafeMatcher { private static final int LESS_THAN = -1; private static final int GREATER_THAN = 1; private static final int EQUAL = 0; private final T expected; private final int minCompare, maxCompare; private static final String[] comparisonDescriptions = { "less than", "equal to", "greater than" }; private OrderingComparison(T expected, int minCompare, int maxCompare) { this.expected = expected; this.minCompare = minCompare; this.maxCompare = maxCompare; } @Override public boolean matchesSafely(T actual) { int compare = signum(actual.compareTo(expected)); return minCompare <= compare && compare <= maxCompare; } @Override public void describeMismatchSafely(T actual, Description mismatchDescription) { mismatchDescription.appendValue(actual).appendText(" was ") .appendText(asText(actual.compareTo(expected))) .appendText(" ").appendValue(expected); } @Override public void describeTo(Description description) { description.appendText("a value ").appendText(asText(minCompare)); if (minCompare != maxCompare) { description.appendText(" or ").appendText(asText(maxCompare)); } description.appendText(" ").appendValue(expected); } private static String asText(int comparison) { return comparisonDescriptions[signum(comparison) + 1]; } /** * Creates a matcher of {@link Comparable} object that matches when the examined object is * equal to the specified value, as reported by the compareTo method of the * examined object. *

* For example: *

assertThat(1, comparesEqualTo(1))
* * @param value * the value which, when passed to the compareTo method of the examined object, should return zero * */ @Factory public static > Matcher comparesEqualTo(T value) { return new OrderingComparison(value, EQUAL, EQUAL); } /** * Creates a matcher of {@link Comparable} object that matches when the examined object is * greater than the specified value, as reported by the compareTo method of the * examined object. *

* For example: *

assertThat(2, greaterThan(1))
* * @param value * the value which, when passed to the compareTo method of the examined object, should return greater * than zero * */ @Factory public static > Matcher greaterThan(T value) { return new OrderingComparison(value, GREATER_THAN, GREATER_THAN); } /** * Creates a matcher of {@link Comparable} object that matches when the examined object is * greater than or equal to the specified value, as reported by the compareTo method * of the examined object. *

* For example: *

assertThat(1, greaterThanOrEqualTo(1))
* * @param value * the value which, when passed to the compareTo method of the examined object, should return greater * than or equal to zero * */ @Factory public static > Matcher greaterThanOrEqualTo(T value) { return new OrderingComparison(value, EQUAL, GREATER_THAN); } /** * Creates a matcher of {@link Comparable} object that matches when the examined object is * less than the specified value, as reported by the compareTo method of the * examined object. *

* For example: *

assertThat(1, lessThan(2))
* * @param value * the value which, when passed to the compareTo method of the examined object, should return less * than zero * */ @Factory public static > Matcher lessThan(T value) { return new OrderingComparison(value, LESS_THAN, LESS_THAN); } /** * Creates a matcher of {@link Comparable} object that matches when the examined object is * less than or equal to the specified value, as reported by the compareTo method * of the examined object. *

* For example: *

assertThat(1, lessThanOrEqualTo(1))
* * @param value * the value which, when passed to the compareTo method of the examined object, should return less * than or equal to zero * */ @Factory public static > Matcher lessThanOrEqualTo(T value) { return new OrderingComparison(value, LESS_THAN, EQUAL); } } libhamcrest-java-1.3/hamcrest-library/src/main/java/org/hamcrest/number/BigDecimalCloseTo.java0000644000175000017500000000407311765134013032033 0ustar ebourgebourgpackage org.hamcrest.number; import java.math.BigDecimal; import java.math.MathContext; import org.hamcrest.Description; import org.hamcrest.Factory; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; public class BigDecimalCloseTo extends TypeSafeMatcher { private final BigDecimal delta; private final BigDecimal value; public BigDecimalCloseTo(BigDecimal value, BigDecimal error) { this.delta = error; this.value = value; } @Override public boolean matchesSafely(BigDecimal item) { return actualDelta(item).compareTo(BigDecimal.ZERO) <= 0; } @Override public void describeMismatchSafely(BigDecimal item, Description mismatchDescription) { mismatchDescription.appendValue(item) .appendText(" differed by ") .appendValue(actualDelta(item)); } @Override public void describeTo(Description description) { description.appendText("a numeric value within ") .appendValue(delta) .appendText(" of ") .appendValue(value); } private BigDecimal actualDelta(BigDecimal item) { return item.subtract(value, MathContext.DECIMAL128).abs().subtract(delta, MathContext.DECIMAL128).stripTrailingZeros(); } /** * Creates a matcher of {@link java.math.BigDecimal}s that matches when an examined BigDecimal is equal * to the specified operand, within a range of +/- error. The comparison for equality * is done by BigDecimals {@link java.math.BigDecimal#compareTo(java.math.BigDecimal)} method. *

* For example: *

assertThat(new BigDecimal("1.03"), is(closeTo(new BigDecimal("1.0"), new BigDecimal("0.03"))))
* * @param operand * the expected value of matching BigDecimals * @param error * the delta (+/-) within which matches will be allowed */ @Factory public static Matcher closeTo(BigDecimal operand, BigDecimal error) { return new BigDecimalCloseTo(operand, error); } } libhamcrest-java-1.3/hamcrest-library/src/main/java/org/hamcrest/number/package.html0000644000175000017500000000015011753011773030174 0ustar ebourgebourg

Matchers that perform numeric comparisons.

libhamcrest-java-1.3/hamcrest-library/src/main/java/org/hamcrest/beans/0000755000175000017500000000000012131006721025503 5ustar ebourgebourglibhamcrest-java-1.3/hamcrest-library/src/main/java/org/hamcrest/beans/SamePropertyValuesAs.java0000644000175000017500000001234011756163656032473 0ustar ebourgebourgpackage org.hamcrest.beans; import org.hamcrest.*; import java.beans.PropertyDescriptor; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import static org.hamcrest.beans.PropertyUtil.NO_ARGUMENTS; import static org.hamcrest.beans.PropertyUtil.propertyDescriptorsFor; import static org.hamcrest.core.IsEqual.equalTo; public class SamePropertyValuesAs extends TypeSafeDiagnosingMatcher { private final T expectedBean; private final Set propertyNames; private final List propertyMatchers; public SamePropertyValuesAs(T expectedBean) { PropertyDescriptor[] descriptors = propertyDescriptorsFor(expectedBean, Object.class); this.expectedBean = expectedBean; this.propertyNames = propertyNamesFrom(descriptors); this.propertyMatchers = propertyMatchersFor(expectedBean, descriptors); } @Override public boolean matchesSafely(T bean, Description mismatch) { return isCompatibleType(bean, mismatch) && hasNoExtraProperties(bean, mismatch) && hasMatchingValues(bean, mismatch); } @Override public void describeTo(Description description) { description.appendText("same property values as " + expectedBean.getClass().getSimpleName()) .appendList(" [", ", ", "]", propertyMatchers); } private boolean isCompatibleType(T item, Description mismatchDescription) { if (!expectedBean.getClass().isAssignableFrom(item.getClass())) { mismatchDescription.appendText("is incompatible type: " + item.getClass().getSimpleName()); return false; } return true; } private boolean hasNoExtraProperties(T item, Description mismatchDescription) { Set actualPropertyNames = propertyNamesFrom(propertyDescriptorsFor(item, Object.class)); actualPropertyNames.removeAll(propertyNames); if (!actualPropertyNames.isEmpty()) { mismatchDescription.appendText("has extra properties called " + actualPropertyNames); return false; } return true; } private boolean hasMatchingValues(T item, Description mismatchDescription) { for (PropertyMatcher propertyMatcher : propertyMatchers) { if (!propertyMatcher.matches(item)) { propertyMatcher.describeMismatch(item, mismatchDescription); return false; } } return true; } private static List propertyMatchersFor(T bean, PropertyDescriptor[] descriptors) { List result = new ArrayList(descriptors.length); for (PropertyDescriptor propertyDescriptor : descriptors) { result.add(new PropertyMatcher(propertyDescriptor, bean)); } return result; } private static Set propertyNamesFrom(PropertyDescriptor[] descriptors) { HashSet result = new HashSet(); for (PropertyDescriptor propertyDescriptor : descriptors) { result.add(propertyDescriptor.getDisplayName()); } return result; } public static class PropertyMatcher extends DiagnosingMatcher { private final Method readMethod; private final Matcher matcher; private final String propertyName; public PropertyMatcher(PropertyDescriptor descriptor, Object expectedObject) { this.propertyName = descriptor.getDisplayName(); this.readMethod = descriptor.getReadMethod(); this.matcher = equalTo(readProperty(readMethod, expectedObject)); } @Override public boolean matches(Object actual, Description mismatch) { final Object actualValue = readProperty(readMethod, actual); if (!matcher.matches(actualValue)) { mismatch.appendText(propertyName + " "); matcher.describeMismatch(actualValue, mismatch); return false; } return true; } @Override public void describeTo(Description description) { description.appendText(propertyName + ": ").appendDescriptionOf(matcher); } } private static Object readProperty(Method method, Object target) { try { return method.invoke(target, NO_ARGUMENTS); } catch (Exception e) { throw new IllegalArgumentException("Could not invoke " + method + " on " + target, e); } } /** * Creates a matcher that matches when the examined object has values for all of * its JavaBean properties that are equal to the corresponding values of the * specified bean. *

* For example: *

assertThat(myBean, samePropertyValuesAs(myExpectedBean))
* * @param expectedBean * the bean against which examined beans are compared */ @Factory public static Matcher samePropertyValuesAs(T expectedBean) { return new SamePropertyValuesAs(expectedBean); } } libhamcrest-java-1.3/hamcrest-library/src/main/java/org/hamcrest/beans/PropertyUtil.java0000644000175000017500000000374311753011773031053 0ustar ebourgebourg/* Copyright (c) 2000-2006 hamcrest.org */ package org.hamcrest.beans; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; /** * Utility class for accessing properties on JavaBean objects. *

* See http://java.sun.com/products/javabeans/docs/index.html for * more information on JavaBeans. * * @author Iain McGinniss * @author Steve Freeman * @since 1.1.0 */ public class PropertyUtil { /** * Returns the description of the property with the provided * name on the provided object's interface. * * @return the descriptor of the property, or null if the property does not exist. * @throws IllegalArgumentException if there's a introspection failure */ public static PropertyDescriptor getPropertyDescriptor(String propertyName, Object fromObj) throws IllegalArgumentException { for (PropertyDescriptor property : propertyDescriptorsFor(fromObj, null)) { if (property.getName().equals(propertyName)) { return property; } } return null; } /** * Returns all the property descriptors for the class associated with the given object * * @param fromObj Use the class of this object * @param stopClass Don't include any properties from this ancestor class upwards. * @return Property descriptors * @throws IllegalArgumentException if there's a introspection failure */ public static PropertyDescriptor[] propertyDescriptorsFor(Object fromObj, Class stopClass) throws IllegalArgumentException { try { return Introspector.getBeanInfo(fromObj.getClass(), stopClass).getPropertyDescriptors(); } catch (IntrospectionException e) { throw new IllegalArgumentException("Could not get property descriptors for " + fromObj.getClass(), e); } } public static final Object[] NO_ARGUMENTS = new Object[0]; } libhamcrest-java-1.3/hamcrest-library/src/main/java/org/hamcrest/beans/package.html0000644000175000017500000000016011753011773027775 0ustar ebourgebourg

Matchers of Java Bean properties and their values.

libhamcrest-java-1.3/hamcrest-library/src/main/java/org/hamcrest/beans/HasProperty.java0000644000175000017500000000343711756163660030657 0ustar ebourgebourg/* Copyright (c) 2000-2006 hamcrest.org */ package org.hamcrest.beans; import org.hamcrest.Description; import org.hamcrest.Factory; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; /** * A Matcher that checks that an object has a JavaBean property * with the specified name. If an error occurs during introspection * of the object then this is treated as a mismatch. * * @author Iain McGinniss * @author Nat Pryce * @author Steve Freeman */ public class HasProperty extends TypeSafeMatcher { private final String propertyName; public HasProperty(String propertyName) { this.propertyName = propertyName; } @Override public boolean matchesSafely(T obj) { try { return PropertyUtil.getPropertyDescriptor(propertyName, obj) != null; } catch (IllegalArgumentException e) { return false; } } @Override public void describeMismatchSafely(T item, Description mismatchDescription) { mismatchDescription.appendText("no ").appendValue(propertyName).appendText(" in ").appendValue(item); } @Override public void describeTo(Description description) { description.appendText("hasProperty(").appendValue(propertyName).appendText(")"); } /** * Creates a matcher that matches when the examined object has a JavaBean property * with the specified name. *

* For example: *

assertThat(myBean, hasProperty("foo"))
* * @param propertyName * the name of the JavaBean property that examined beans should possess */ @Factory public static Matcher hasProperty(String propertyName) { return new HasProperty(propertyName); } } libhamcrest-java-1.3/hamcrest-library/src/main/java/org/hamcrest/beans/HasPropertyWithValue.java0000644000175000017500000001402211756163420032472 0ustar ebourgebourg/* Copyright (c) 2000-2006 hamcrest.org */ package org.hamcrest.beans; import java.beans.PropertyDescriptor; import java.lang.reflect.Method; import org.hamcrest.Condition; import org.hamcrest.Description; import org.hamcrest.Factory; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeDiagnosingMatcher; import static org.hamcrest.Condition.matched; import static org.hamcrest.Condition.notMatched; import static org.hamcrest.beans.PropertyUtil.NO_ARGUMENTS; /** * Matcher that asserts that a JavaBean property on an argument passed to the * mock object meets the provided matcher. This is useful for when objects * are created within code under test and passed to a mock object, and you wish * to assert that the created object has certain properties. *

*

Example Usage

* Consider the situation where we have a class representing a person, which * follows the basic JavaBean convention of having get() and possibly set() * methods for it's properties: *
 * public class Person {
 *   private String name;
 *   public Person(String person) {
 *     this.person = person;
 *   }
 *   public String getName() {
 *     return name;
 *   }
 * }
* * And that these person objects are generated within a piece of code under test * (a class named PersonGenerator). This object is sent to one of our mock objects * which overrides the PersonGenerationListener interface: *
 * public interface PersonGenerationListener {
 *   public void personGenerated(Person person);
 * }
* * In order to check that the code under test generates a person with name * "Iain" we would do the following: *
 * Mock personGenListenerMock = mock(PersonGenerationListener.class);
 * personGenListenerMock.expects(once()).method("personGenerated").with(and(isA(Person.class), hasProperty("Name", eq("Iain")));
 * PersonGenerationListener listener = (PersonGenerationListener)personGenListenerMock.proxy();
* * If an exception is thrown by the getter method for a property, the property * does not exist, is not readable, or a reflection related exception is thrown * when trying to invoke it then this is treated as an evaluation failure and * the matches method will return false. *

* This matcher class will also work with JavaBean objects that have explicit * bean descriptions via an associated BeanInfo description class. See the * JavaBeans specification for more information: *

* http://java.sun.com/products/javabeans/docs/index.html * * @author Iain McGinniss * @author Nat Pryce * @author Steve Freeman */ public class HasPropertyWithValue extends TypeSafeDiagnosingMatcher { private static final Condition.Step WITH_READ_METHOD = withReadMethod(); private final String propertyName; private final Matcher valueMatcher; public HasPropertyWithValue(String propertyName, Matcher valueMatcher) { this.propertyName = propertyName; this.valueMatcher = nastyGenericsWorkaround(valueMatcher); } @Override public boolean matchesSafely(T bean, Description mismatch) { return propertyOn(bean, mismatch) .and(WITH_READ_METHOD) .and(withPropertyValue(bean)) .matching(valueMatcher, "property '" + propertyName + "' "); } @Override public void describeTo(Description description) { description.appendText("hasProperty(").appendValue(propertyName).appendText(", ") .appendDescriptionOf(valueMatcher).appendText(")"); } private Condition propertyOn(T bean, Description mismatch) { PropertyDescriptor property = PropertyUtil.getPropertyDescriptor(propertyName, bean); if (property == null) { mismatch.appendText("No property \"" + propertyName + "\""); return notMatched(); } return matched(property, mismatch); } private Condition.Step withPropertyValue(final T bean) { return new Condition.Step() { @Override public Condition apply(Method readMethod, Description mismatch) { try { return matched(readMethod.invoke(bean, NO_ARGUMENTS), mismatch); } catch (Exception e) { mismatch.appendText(e.getMessage()); return notMatched(); } } }; } @SuppressWarnings("unchecked") private static Matcher nastyGenericsWorkaround(Matcher valueMatcher) { return (Matcher) valueMatcher; } private static Condition.Step withReadMethod() { return new Condition.Step() { @Override public Condition apply(PropertyDescriptor property, Description mismatch) { final Method readMethod = property.getReadMethod(); if (null == readMethod) { mismatch.appendText("property \"" + property.getName() + "\" is not readable"); return notMatched(); } return matched(readMethod, mismatch); } }; } /** * Creates a matcher that matches when the examined object has a JavaBean property * with the specified name whose value satisfies the specified matcher. *

* For example: *

assertThat(myBean, hasProperty("foo", equalTo("bar"))
* * @param propertyName * the name of the JavaBean property that examined beans should possess * @param valueMatcher * a matcher for the value of the specified property of the examined bean */ @Factory public static Matcher hasProperty(String propertyName, Matcher valueMatcher) { return new HasPropertyWithValue(propertyName, valueMatcher); } } libhamcrest-java-1.3/hamcrest-library/src/main/java/org/hamcrest/collection/0000755000175000017500000000000012131006721026546 5ustar ebourgebourg././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibhamcrest-java-1.3/hamcrest-library/src/main/java/org/hamcrest/collection/IsCollectionWithSize.javalibhamcrest-java-1.3/hamcrest-library/src/main/java/org/hamcrest/collection/IsCollectionWithSize.jav0000644000175000017500000000353711765133375033360 0ustar ebourgebourgpackage org.hamcrest.collection; import org.hamcrest.Factory; import org.hamcrest.FeatureMatcher; import org.hamcrest.Matcher; import java.util.Collection; import static org.hamcrest.core.IsEqual.equalTo; /** * Matches if collection size satisfies a nested matcher. */ public class IsCollectionWithSize extends FeatureMatcher, Integer> { public IsCollectionWithSize(Matcher sizeMatcher) { super(sizeMatcher, "a collection with size", "collection size"); } @Override protected Integer featureValueOf(Collection actual) { return actual.size(); } /** * Creates a matcher for {@link java.util.Collection}s that matches when the size() method returns * a value that satisfies the specified matcher. *

* For example: *

assertThat(Arrays.asList("foo", "bar"), hasSize(equalTo(2)))
* * @param sizeMatcher * a matcher for the size of an examined {@link java.util.Collection} */ @Factory public static Matcher> hasSize(Matcher sizeMatcher) { return new IsCollectionWithSize(sizeMatcher); } /** * Creates a matcher for {@link java.util.Collection}s that matches when the size() method returns * a value equal to the specified size. *

* For example: *

assertThat(Arrays.asList("foo", "bar"), hasSize(2))
* * @param size * the expected size of an examined {@link java.util.Collection} */ @Factory public static Matcher> hasSize(int size) { Matcher matcher = equalTo(size); return IsCollectionWithSize.hasSize(matcher); } } libhamcrest-java-1.3/hamcrest-library/src/main/java/org/hamcrest/collection/IsIterableWithSize.java0000644000175000017500000000364411756176053033154 0ustar ebourgebourgpackage org.hamcrest.collection; import static org.hamcrest.core.IsEqual.equalTo; import java.util.Iterator; import org.hamcrest.Factory; import org.hamcrest.FeatureMatcher; import org.hamcrest.Matcher; public class IsIterableWithSize extends FeatureMatcher, Integer> { public IsIterableWithSize(Matcher sizeMatcher) { super(sizeMatcher, "an iterable with size", "iterable size"); } @Override protected Integer featureValueOf(Iterable actual) { int size = 0; for (Iterator iterator = actual.iterator(); iterator.hasNext(); iterator.next()) { size++; } return size; } /** * Creates a matcher for {@link Iterable}s that matches when a single pass over the * examined {@link Iterable} yields an item count that satisfies the specified * matcher. *

* For example: *

assertThat(Arrays.asList("foo", "bar"), iterableWithSize(equalTo(2)))
* * @param sizeMatcher * a matcher for the number of items that should be yielded by an examined {@link Iterable} */ @Factory public static Matcher> iterableWithSize(Matcher sizeMatcher) { return new IsIterableWithSize(sizeMatcher); } /** * Creates a matcher for {@link Iterable}s that matches when a single pass over the * examined {@link Iterable} yields an item count that is equal to the specified * size argument. *

* For example: *

assertThat(Arrays.asList("foo", "bar"), iterableWithSize(2))
* * @param size * the number of items that should be yielded by an examined {@link Iterable} */ @Factory public static Matcher> iterableWithSize(int size) { return iterableWithSize(equalTo(size)); } } libhamcrest-java-1.3/hamcrest-library/src/main/java/org/hamcrest/collection/IsIn.java0000644000175000017500000000417611756210405030273 0ustar ebourgebourgpackage org.hamcrest.collection; import org.hamcrest.BaseMatcher; import org.hamcrest.Description; import org.hamcrest.Factory; import org.hamcrest.Matcher; import java.util.Arrays; import java.util.Collection; public class IsIn extends BaseMatcher { private final Collection collection; public IsIn(Collection collection) { this.collection = collection; } public IsIn(T[] elements) { collection = Arrays.asList(elements); } @Override public boolean matches(Object o) { return collection.contains(o); } @Override public void describeTo(Description buffer) { buffer.appendText("one of "); buffer.appendValueList("{", ", ", "}", collection); } /** * Creates a matcher that matches when the examined object is found within the * specified collection. *

* For example: *

assertThat("foo", isIn(Arrays.asList("bar", "foo")))
* * @param collection * the collection in which matching items must be found * */ @Factory public static Matcher isIn(Collection collection) { return new IsIn(collection); } /** * Creates a matcher that matches when the examined object is found within the * specified array. *

* For example: *

assertThat("foo", isIn(new String[]{"bar", "foo"}))
* * @param elements * the array in which matching items must be found * */ @Factory public static Matcher isIn(T[] elements) { return new IsIn(elements); } /** * Creates a matcher that matches when the examined object is equal to one of the * specified elements. *

* For example: *

assertThat("foo", isIn("bar", "foo"))
* * @param elements * the elements amongst which matching items will be found * */ @Factory public static Matcher isOneOf(T... elements) { return isIn(elements); } } ././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootlibhamcrest-java-1.3/hamcrest-library/src/main/java/org/hamcrest/collection/IsIterableContainingInAnyOrder.javalibhamcrest-java-1.3/hamcrest-library/src/main/java/org/hamcrest/collection/IsIterableContainingInAn0000644000175000017500000001567011756210443033317 0ustar ebourgebourgpackage org.hamcrest.collection; import org.hamcrest.Description; import org.hamcrest.Factory; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeDiagnosingMatcher; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import static java.util.Arrays.asList; import static org.hamcrest.core.IsEqual.equalTo; public class IsIterableContainingInAnyOrder extends TypeSafeDiagnosingMatcher> { private final Collection> matchers; public IsIterableContainingInAnyOrder(Collection> matchers) { this.matchers = matchers; } @Override protected boolean matchesSafely(Iterable items, Description mismatchDescription) { Matching matching = new Matching(matchers, mismatchDescription); for (T item : items) { if (! matching.matches(item)) { return false; } } return matching.isFinished(items); } @Override public void describeTo(Description description) { description.appendText("iterable over ") .appendList("[", ", ", "]", matchers) .appendText(" in any order"); } private static class Matching { private final Collection> matchers; private final Description mismatchDescription; public Matching(Collection> matchers, Description mismatchDescription) { this.matchers = new ArrayList>(matchers); this.mismatchDescription = mismatchDescription; } public boolean matches(S item) { return isNotSurplus(item) && isMatched(item); } public boolean isFinished(Iterable items) { if (matchers.isEmpty()) { return true; } mismatchDescription .appendText("No item matches: ").appendList("", ", ", "", matchers) .appendText(" in ").appendValueList("[", ", ", "]", items); return false; } private boolean isNotSurplus(S item) { if (matchers.isEmpty()) { mismatchDescription.appendText("Not matched: ").appendValue(item); return false; } return true; } private boolean isMatched(S item) { for (Matcher matcher : matchers) { if (matcher.matches(item)) { matchers.remove(matcher); return true; } } mismatchDescription.appendText("Not matched: ").appendValue(item); return false; } } /** * Creates a matcher for {@link Iterable}s that matches when a single pass over the * examined {@link Iterable} yields a single item that satisfies the specified matcher. * For a positive match, the examined iterable must only yield one item. *

* For example: *

assertThat(Arrays.asList("foo"), containsInAnyOrder(equalTo("foo")))
* * @deprecated use contains(Matcher itemMatcher) instead * * @param itemMatcher * the matcher that must be satisfied by the single item provided by an * examined {@link Iterable} */ @SuppressWarnings("unchecked") @Deprecated @Factory public static Matcher> containsInAnyOrder(final Matcher itemMatcher) { return containsInAnyOrder(new ArrayList>(asList(itemMatcher))); } /** * Creates an order agnostic matcher for {@link Iterable}s that matches when a single pass over * the examined {@link Iterable} yields a series of items, each satisfying one matcher anywhere * in the specified matchers. For a positive match, the examined iterable must be of the same * length as the number of specified matchers. *

* N.B. each of the specified matchers will only be used once during a given examination, so be * careful when specifying matchers that may be satisfied by more than one entry in an examined * iterable. *

* For example: *

assertThat(Arrays.asList("foo", "bar"), containsInAnyOrder(equalTo("bar"), equalTo("foo")))
* * @param itemMatchers * a list of matchers, each of which must be satisfied by an item provided by an examined {@link Iterable} */ @Factory public static Matcher> containsInAnyOrder(Matcher... itemMatchers) { return containsInAnyOrder(Arrays.asList(itemMatchers)); } /** * Creates an order agnostic matcher for {@link Iterable}s that matches when a single pass over * the examined {@link Iterable} yields a series of items, each logically equal to one item * anywhere in the specified items. For a positive match, the examined iterable * must be of the same length as the number of specified items. *

* N.B. each of the specified items will only be used once during a given examination, so be * careful when specifying items that may be equal to more than one entry in an examined * iterable. *

* For example: *

assertThat(Arrays.asList("foo", "bar"), containsInAnyOrder("bar", "foo"))
* * @param items * the items that must equal the items provided by an examined {@link Iterable} in any order */ @Factory public static Matcher> containsInAnyOrder(T... items) { List> matchers = new ArrayList>(); for (T item : items) { matchers.add(equalTo(item)); } return new IsIterableContainingInAnyOrder(matchers); } /** * Creates an order agnostic matcher for {@link Iterable}s that matches when a single pass over * the examined {@link Iterable} yields a series of items, each satisfying one matcher anywhere * in the specified collection of matchers. For a positive match, the examined iterable * must be of the same length as the specified collection of matchers. *

* N.B. each matcher in the specified collection will only be used once during a given * examination, so be careful when specifying matchers that may be satisfied by more than * one entry in an examined iterable. *

* For example: *

assertThat(Arrays.asList("foo", "bar"), containsInAnyOrder(Arrays.asList(equalTo("bar"), equalTo("foo"))))
* * @param itemMatchers * a list of matchers, each of which must be satisfied by an item provided by an examined {@link Iterable} */ @Factory public static Matcher> containsInAnyOrder(Collection> itemMatchers) { return new IsIterableContainingInAnyOrder(itemMatchers); } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootlibhamcrest-java-1.3/hamcrest-library/src/main/java/org/hamcrest/collection/IsArrayContainingInOrder.javalibhamcrest-java-1.3/hamcrest-library/src/main/java/org/hamcrest/collection/IsArrayContainingInOrder0000644000175000017500000000664411756201705033365 0ustar ebourgebourgpackage org.hamcrest.collection; import org.hamcrest.Description; import org.hamcrest.Factory; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; import java.util.ArrayList; import java.util.Collection; import java.util.List; import static java.util.Arrays.asList; import static org.hamcrest.core.IsEqual.equalTo; public class IsArrayContainingInOrder extends TypeSafeMatcher { private final Collection> matchers; private final IsIterableContainingInOrder iterableMatcher; public IsArrayContainingInOrder(List> matchers) { this.iterableMatcher = new IsIterableContainingInOrder(matchers); this.matchers = matchers; } @Override public boolean matchesSafely(E[] item) { return iterableMatcher.matches(asList(item)); } @Override public void describeMismatchSafely(E[] item, Description mismatchDescription) { iterableMatcher.describeMismatch(asList(item), mismatchDescription); } @Override public void describeTo(Description description) { description.appendList("[", ", ", "]", matchers); } /** * Creates a matcher for arrays that matcheswhen each item in the examined array is * logically equal to the corresponding item in the specified items. For a positive match, * the examined array must be of the same length as the number of specified items. *

* For example: *

assertThat(new String[]{"foo", "bar"}, contains("foo", "bar"))
* * @param items * the items that must equal the items within an examined array */ @Factory public static Matcher arrayContaining(E... items) { List> matchers = new ArrayList>(); for (E item : items) { matchers.add(equalTo(item)); } return arrayContaining(matchers); } /** * Creates a matcher for arrays that matches when each item in the examined array satisfies the * corresponding matcher in the specified matchers. For a positive match, the examined array * must be of the same length as the number of specified matchers. *

* For example: *

assertThat(new String[]{"foo", "bar"}, contains(equalTo("foo"), equalTo("bar")))
* * @param itemMatchers * the matchers that must be satisfied by the items in the examined array */ @Factory public static Matcher arrayContaining(Matcher... itemMatchers) { return arrayContaining(asList(itemMatchers)); } /** * Creates a matcher for arrays that matches when each item in the examined array satisfies the * corresponding matcher in the specified list of matchers. For a positive match, the examined array * must be of the same length as the specified list of matchers. *

* For example: *

assertThat(new String[]{"foo", "bar"}, contains(Arrays.asList(equalTo("foo"), equalTo("bar"))))
* * @param itemMatchers * a list of matchers, each of which must be satisfied by the corresponding item in an examined array */ @Factory public static Matcher arrayContaining(List> itemMatchers) { return new IsArrayContainingInOrder(itemMatchers); } } libhamcrest-java-1.3/hamcrest-library/src/main/java/org/hamcrest/collection/IsArray.java0000644000175000017500000000604111756164634031010 0ustar ebourgebourgpackage org.hamcrest.collection; import java.util.Arrays; import org.hamcrest.Description; import org.hamcrest.Factory; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; /** * Matcher for array whose elements satisfy a sequence of matchers. * The array size must equal the number of element matchers. */ public class IsArray extends TypeSafeMatcher { private final Matcher[] elementMatchers; public IsArray(Matcher[] elementMatchers) { this.elementMatchers = elementMatchers.clone(); } @Override public boolean matchesSafely(T[] array) { if (array.length != elementMatchers.length) return false; for (int i = 0; i < array.length; i++) { if (!elementMatchers[i].matches(array[i])) return false; } return true; } @Override public void describeMismatchSafely(T[] actual, Description mismatchDescription) { if (actual.length != elementMatchers.length) { mismatchDescription.appendText("array length was " + actual.length); return; } for (int i = 0; i < actual.length; i++) { if (!elementMatchers[i].matches(actual[i])) { mismatchDescription.appendText("element " + i + " was ").appendValue(actual[i]); return; } } } @Override public void describeTo(Description description) { description.appendList(descriptionStart(), descriptionSeparator(), descriptionEnd(), Arrays.asList(elementMatchers)); } /** * Returns the string that starts the description. * * Can be overridden in subclasses to customise how the matcher is * described. */ protected String descriptionStart() { return "["; } /** * Returns the string that separates the elements in the description. * * Can be overridden in subclasses to customise how the matcher is * described. */ protected String descriptionSeparator() { return ", "; } /** * Returns the string that ends the description. * * Can be overridden in subclasses to customise how the matcher is * described. */ protected String descriptionEnd() { return "]"; } /** * Creates a matcher that matches arrays whose elements are satisfied by the specified matchers. Matches * positively only if the number of matchers specified is equal to the length of the examined array and * each matcher[i] is satisfied by array[i]. *

* For example: *

assertThat(new Integer[]{1,2,3}, is(array(equalTo(1), equalTo(2), equalTo(3))))
* * @param elementMatchers * the matchers that the elements of examined arrays should satisfy */ @Factory public static IsArray array(Matcher... elementMatchers) { return new IsArray(elementMatchers); } } libhamcrest-java-1.3/hamcrest-library/src/main/java/org/hamcrest/collection/IsArrayContaining.java0000644000175000017500000000463311756165721033025 0ustar ebourgebourgpackage org.hamcrest.collection; import java.util.Arrays; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.Factory; import org.hamcrest.TypeSafeMatcher; import static org.hamcrest.core.IsEqual.equalTo; /** * Matches if an array contains an item satisfying a nested matcher. */ public class IsArrayContaining extends TypeSafeMatcher { private final Matcher elementMatcher; public IsArrayContaining(Matcher elementMatcher) { this.elementMatcher = elementMatcher; } @Override public boolean matchesSafely(T[] array) { for (T item : array) { if (elementMatcher.matches(item)) { return true; } } return false; } @Override public void describeMismatchSafely(T[] item, Description mismatchDescription) { super.describeMismatch(Arrays.asList(item), mismatchDescription); }; @Override public void describeTo(Description description) { description .appendText("an array containing ") .appendDescriptionOf(elementMatcher); } /** * Creates a matcher for arrays that matches when the examined array contains at least one item * that is matched by the specified elementMatcher. Whilst matching, the traversal * of the examined array will stop as soon as a matching element is found. *

* For example: *

assertThat(new String[] {"foo", "bar"}, hasItemInArray(startsWith("ba")))
* * @param elementMatcher * the matcher to apply to elements in examined arrays */ @Factory public static Matcher hasItemInArray(Matcher elementMatcher) { return new IsArrayContaining(elementMatcher); } /** * A shortcut to the frequently used hasItemInArray(equalTo(x)). *

* For example: *

assertThat(hasItemInArray(x))
* instead of: *
assertThat(hasItemInArray(equalTo(x)))
* * @param element * the element that should be present in examined arrays */ @Factory public static Matcher hasItemInArray(T element) { Matcher matcher = equalTo(element); return IsArrayContaining.hasItemInArray(matcher); } } ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootlibhamcrest-java-1.3/hamcrest-library/src/main/java/org/hamcrest/collection/IsArrayContainingInAnyOrder.javalibhamcrest-java-1.3/hamcrest-library/src/main/java/org/hamcrest/collection/IsArrayContainingInAnyOr0000644000175000017500000001052411756201065033331 0ustar ebourgebourgpackage org.hamcrest.collection; import static org.hamcrest.core.IsEqual.equalTo; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import org.hamcrest.Description; import org.hamcrest.Factory; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; public class IsArrayContainingInAnyOrder extends TypeSafeMatcher { private final IsIterableContainingInAnyOrder iterableMatcher; private final Collection> matchers; public IsArrayContainingInAnyOrder(Collection> matchers) { this.iterableMatcher = new IsIterableContainingInAnyOrder(matchers); this.matchers = matchers; } @Override public boolean matchesSafely(E[] item) { return iterableMatcher.matches(Arrays.asList(item)); } @Override public void describeMismatchSafely(E[] item, Description mismatchDescription) { iterableMatcher.describeMismatch(Arrays.asList(item), mismatchDescription); }; @Override public void describeTo(Description description) { description.appendList("[", ", ", "]", matchers) .appendText(" in any order"); } /** * Creates an order agnostic matcher for arrays that matches when each item in the * examined array satisfies one matcher anywhere in the specified matchers. * For a positive match, the examined array must be of the same length as the number of * specified matchers. *

* N.B. each of the specified matchers will only be used once during a given examination, so be * careful when specifying matchers that may be satisfied by more than one entry in an examined * array. *

* For example: *

assertThat(new String[]{"foo", "bar"}, arrayContainingInAnyOrder(equalTo("bar"), equalTo("foo")))
* * @param itemMatchers * a list of matchers, each of which must be satisfied by an entry in an examined array */ @Factory public static Matcher arrayContainingInAnyOrder(Matcher... itemMatchers) { return arrayContainingInAnyOrder(Arrays.asList(itemMatchers)); } /** * Creates an order agnostic matcher for arrays that matches when each item in the * examined array satisfies one matcher anywhere in the specified collection of matchers. * For a positive match, the examined array must be of the same length as the specified collection * of matchers. *

* N.B. each matcher in the specified collection will only be used once during a given * examination, so be careful when specifying matchers that may be satisfied by more than * one entry in an examined array. *

* For example: *

assertThat(new String[]{"foo", "bar"}, arrayContainingInAnyOrder(Arrays.asList(equalTo("bar"), equalTo("foo"))))
* * @param itemMatchers * a list of matchers, each of which must be satisfied by an item provided by an examined array */ @Factory public static Matcher arrayContainingInAnyOrder(Collection> itemMatchers) { return new IsArrayContainingInAnyOrder(itemMatchers); } /** * Creates an order agnostic matcher for arrays that matches when each item in the * examined array is logically equal to one item anywhere in the specified items. * For a positive match, the examined array must be of the same length as the number of * specified items. *

* N.B. each of the specified items will only be used once during a given examination, so be * careful when specifying items that may be equal to more than one entry in an examined * array. *

* For example: *

assertThat(new String[]{"foo", "bar"}, containsInAnyOrder("bar", "foo"))
* * @param items * the items that must equal the entries of an examined array, in any order */ @Factory public static Matcher arrayContainingInAnyOrder(E... items) { List> matchers = new ArrayList>(); for (E item : items) { matchers.add(equalTo(item)); } return new IsArrayContainingInAnyOrder(matchers); } } libhamcrest-java-1.3/hamcrest-library/src/main/java/org/hamcrest/collection/IsArrayWithSize.java0000644000175000017500000000403011756176547032501 0ustar ebourgebourgpackage org.hamcrest.collection; import org.hamcrest.Factory; import org.hamcrest.FeatureMatcher; import org.hamcrest.Matcher; import static org.hamcrest.core.DescribedAs.describedAs; import static org.hamcrest.core.IsEqual.equalTo; /** * Matches if array size satisfies a nested matcher. */ public class IsArrayWithSize extends FeatureMatcher { public IsArrayWithSize(Matcher sizeMatcher) { super(sizeMatcher, "an array with size","array size"); } @Override protected Integer featureValueOf(E[] actual) { return actual.length; } /** * Creates a matcher for arrays that matches when the length of the array * satisfies the specified matcher. *

* For example: *

assertThat(new String[]{"foo", "bar"}, arrayWithSize(equalTo(2)))
* * @param sizeMatcher * a matcher for the length of an examined array */ @Factory public static Matcher arrayWithSize(Matcher sizeMatcher) { return new IsArrayWithSize(sizeMatcher); } /** * Creates a matcher for arrays that matches when the length of the array * equals the specified size. *

* For example: *

assertThat(new String[]{"foo", "bar"}, arrayWithSize(2))
* * @param size * the length that an examined array must have for a positive match */ @Factory public static Matcher arrayWithSize(int size) { return arrayWithSize(equalTo(size)); } /** * Creates a matcher for arrays that matches when the length of the array * is zero. *

* For example: *

assertThat(new String[0], emptyArray())
* */ @Factory public static Matcher emptyArray() { Matcher isEmpty = arrayWithSize(0); return describedAs("an empty array", isEmpty); } } libhamcrest-java-1.3/hamcrest-library/src/main/java/org/hamcrest/collection/IsMapContaining.java0000644000175000017500000001266111765133611032455 0ustar ebourgebourgpackage org.hamcrest.collection; import org.hamcrest.Description; import org.hamcrest.Factory; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; import java.util.Map; import java.util.Map.Entry; import static org.hamcrest.core.IsAnything.anything; import static org.hamcrest.core.IsEqual.equalTo; public class IsMapContaining extends TypeSafeMatcher> { private final Matcher keyMatcher; private final Matcher valueMatcher; public IsMapContaining(Matcher keyMatcher, Matcher valueMatcher) { this.keyMatcher = keyMatcher; this.valueMatcher = valueMatcher; } @Override public boolean matchesSafely(Map map) { for (Entry entry : map.entrySet()) { if (keyMatcher.matches(entry.getKey()) && valueMatcher.matches(entry.getValue())) { return true; } } return false; } @Override public void describeMismatchSafely(Map map, Description mismatchDescription) { mismatchDescription.appendText("map was ").appendValueList("[", ", ", "]", map.entrySet()); } @Override public void describeTo(Description description) { description.appendText("map containing [") .appendDescriptionOf(keyMatcher) .appendText("->") .appendDescriptionOf(valueMatcher) .appendText("]"); } /** * Creates a matcher for {@link java.util.Map}s matching when the examined {@link java.util.Map} contains * at least one entry whose key satisfies the specified keyMatcher and whose * value satisfies the specified valueMatcher. *

* For example: *

assertThat(myMap, hasEntry(equalTo("bar"), equalTo("foo")))
* * @param keyMatcher * the key matcher that, in combination with the valueMatcher, must be satisfied by at least one entry * @param valueMatcher * the value matcher that, in combination with the keyMatcher, must be satisfied by at least one entry */ @Factory public static Matcher> hasEntry(Matcher keyMatcher, Matcher valueMatcher) { return new IsMapContaining(keyMatcher, valueMatcher); } /** * Creates a matcher for {@link java.util.Map}s matching when the examined {@link java.util.Map} contains * at least one entry whose key equals the specified key and whose value equals the * specified value. *

* For example: *

assertThat(myMap, hasEntry("bar", "foo"))
* * @param key * the key that, in combination with the value, must be describe at least one entry * @param value * the value that, in combination with the key, must be describe at least one entry */ @Factory public static Matcher> hasEntry(K key, V value) { return new IsMapContaining(equalTo(key), equalTo(value)); } /** * Creates a matcher for {@link java.util.Map}s matching when the examined {@link java.util.Map} contains * at least one key that satisfies the specified matcher. *

* For example: *

assertThat(myMap, hasKey(equalTo("bar")))
* * @param keyMatcher * the matcher that must be satisfied by at least one key */ @Factory public static Matcher> hasKey(Matcher keyMatcher) { return new IsMapContaining(keyMatcher, anything()); } /** * Creates a matcher for {@link java.util.Map}s matching when the examined {@link java.util.Map} contains * at least one key that is equal to the specified key. *

* For example: *

assertThat(myMap, hasKey("bar"))
* * @param key * the key that satisfying maps must contain */ @Factory public static Matcher> hasKey(K key) { return new IsMapContaining(equalTo(key), anything()); } /** * Creates a matcher for {@link java.util.Map}s matching when the examined {@link java.util.Map} contains * at least one value that satisfies the specified valueMatcher. *

* For example: *

assertThat(myMap, hasValue(equalTo("foo")))
* * @param valueMatcher * the matcher that must be satisfied by at least one value */ @Factory public static Matcher> hasValue(Matcher valueMatcher) { return new IsMapContaining(anything(), valueMatcher); } /** * Creates a matcher for {@link java.util.Map}s matching when the examined {@link java.util.Map} contains * at least one value that is equal to the specified value. *

* For example: *

assertThat(myMap, hasValue("foo"))
* * @param value * the value that satisfying maps must contain */ @Factory public static Matcher> hasValue(V value) { return new IsMapContaining(anything(), equalTo(value)); } } libhamcrest-java-1.3/hamcrest-library/src/main/java/org/hamcrest/collection/IsEmptyIterable.java0000644000175000017500000000326111767721152032475 0ustar ebourgebourgpackage org.hamcrest.collection; import org.hamcrest.Description; import org.hamcrest.Factory; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; /** * Tests if collection is empty. */ public class IsEmptyIterable extends TypeSafeMatcher> { @Override public boolean matchesSafely(Iterable iterable) { return !iterable.iterator().hasNext(); } @Override public void describeMismatchSafely(Iterable iter, Description mismatchDescription) { mismatchDescription.appendValueList("[", ",", "]", iter); } @Override public void describeTo(Description description) { description.appendText("an empty iterable"); } /** * Creates a matcher for {@link Iterable}s matching examined iterables that yield no items. *

* For example: *

assertThat(new ArrayList<String>(), is(emptyIterable()))
* */ @Factory public static Matcher> emptyIterable() { return new IsEmptyIterable(); } /** * Creates a matcher for {@link Iterable}s matching examined iterables that yield no items. *

* For example: *

assertThat(new ArrayList<String>(), is(emptyIterableOf(String.class)))
* * @param type * the type of the iterable's content */ @Factory public static Matcher> emptyIterableOf(Class type) { @SuppressWarnings({ "rawtypes", "unchecked" }) final Matcher> result = (Matcher)emptyIterable(); return result; } } ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootlibhamcrest-java-1.3/hamcrest-library/src/main/java/org/hamcrest/collection/IsIterableContainingInOrder.javalibhamcrest-java-1.3/hamcrest-library/src/main/java/org/hamcrest/collection/IsIterableContainingInOr0000644000175000017500000001433111756170275033342 0ustar ebourgebourgpackage org.hamcrest.collection; import org.hamcrest.Description; import org.hamcrest.Factory; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeDiagnosingMatcher; import java.util.ArrayList; import java.util.List; import static java.util.Arrays.asList; import static org.hamcrest.core.IsEqual.equalTo; public class IsIterableContainingInOrder extends TypeSafeDiagnosingMatcher> { private final List> matchers; public IsIterableContainingInOrder(List> matchers) { this.matchers = matchers; } @Override protected boolean matchesSafely(Iterable iterable, Description mismatchDescription) { MatchSeries matchSeries = new MatchSeries(matchers, mismatchDescription); for (E item : iterable) { if (!matchSeries.matches(item)) { return false; } } return matchSeries.isFinished(); } @Override public void describeTo(Description description) { description.appendText("iterable containing ").appendList("[", ", ", "]", matchers); } private static class MatchSeries { public final List> matchers; private final Description mismatchDescription; public int nextMatchIx = 0; public MatchSeries(List> matchers, Description mismatchDescription) { this.mismatchDescription = mismatchDescription; if (matchers.isEmpty()) { throw new IllegalArgumentException("Should specify at least one expected element"); } this.matchers = matchers; } public boolean matches(F item) { return isNotSurplus(item) && isMatched(item); } public boolean isFinished() { if (nextMatchIx < matchers.size()) { mismatchDescription.appendText("No item matched: ").appendDescriptionOf(matchers.get(nextMatchIx)); return false; } return true; } private boolean isMatched(F item) { Matcher matcher = matchers.get(nextMatchIx); if (!matcher.matches(item)) { describeMismatch(matcher, item); return false; } nextMatchIx++; return true; } private boolean isNotSurplus(F item) { if (matchers.size() <= nextMatchIx) { mismatchDescription.appendText("Not matched: ").appendValue(item); return false; } return true; } private void describeMismatch(Matcher matcher, F item) { mismatchDescription.appendText("item " + nextMatchIx + ": "); matcher.describeMismatch(item, mismatchDescription); } } /** * Creates a matcher for {@link Iterable}s that matches when a single pass over the * examined {@link Iterable} yields a series of items, each logically equal to the * corresponding item in the specified items. For a positive match, the examined iterable * must be of the same length as the number of specified items. *

* For example: *

assertThat(Arrays.asList("foo", "bar"), contains("foo", "bar"))
* * @param items * the items that must equal the items provided by an examined {@link Iterable} */ @Factory public static Matcher> contains(E... items) { List> matchers = new ArrayList>(); for (E item : items) { matchers.add(equalTo(item)); } return contains(matchers); } /** * Creates a matcher for {@link Iterable}s that matches when a single pass over the * examined {@link Iterable} yields a single item that satisfies the specified matcher. * For a positive match, the examined iterable must only yield one item. *

* For example: *

assertThat(Arrays.asList("foo"), contains(equalTo("foo")))
* * @param itemMatcher * the matcher that must be satisfied by the single item provided by an * examined {@link Iterable} */ @SuppressWarnings("unchecked") @Factory public static Matcher> contains(final Matcher itemMatcher) { return contains(new ArrayList>(asList(itemMatcher))); } /** * Creates a matcher for {@link Iterable}s that matches when a single pass over the * examined {@link Iterable} yields a series of items, each satisfying the corresponding * matcher in the specified matchers. For a positive match, the examined iterable * must be of the same length as the number of specified matchers. *

* For example: *

assertThat(Arrays.asList("foo", "bar"), contains(equalTo("foo"), equalTo("bar")))
* * @param itemMatchers * the matchers that must be satisfied by the items provided by an examined {@link Iterable} */ @Factory public static Matcher> contains(Matcher... itemMatchers) { return contains(asList(itemMatchers)); } /** * Creates a matcher for {@link Iterable}s that matches when a single pass over the * examined {@link Iterable} yields a series of items, each satisfying the corresponding * matcher in the specified list of matchers. For a positive match, the examined iterable * must be of the same length as the specified list of matchers. *

* For example: *

assertThat(Arrays.asList("foo", "bar"), contains(Arrays.asList(equalTo("foo"), equalTo("bar"))))
* * @param itemMatchers * a list of matchers, each of which must be satisfied by the corresponding item provided by * an examined {@link Iterable} */ @Factory public static Matcher> contains(List> itemMatchers) { return new IsIterableContainingInOrder(itemMatchers); } } libhamcrest-java-1.3/hamcrest-library/src/main/java/org/hamcrest/collection/package.html0000644000175000017500000000014111753011773031037 0ustar ebourgebourg

Matchers of arrays and collections.

libhamcrest-java-1.3/hamcrest-library/src/main/java/org/hamcrest/collection/IsEmptyCollection.java0000644000175000017500000000344611767721120033041 0ustar ebourgebourgpackage org.hamcrest.collection; import java.util.Collection; import org.hamcrest.Description; import org.hamcrest.Factory; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; /** * Tests if collection is empty. */ public class IsEmptyCollection extends TypeSafeMatcher> { @Override public boolean matchesSafely(Collection item) { return item.isEmpty(); } @Override public void describeMismatchSafely(Collection item, Description mismatchDescription) { mismatchDescription.appendValue(item); } @Override public void describeTo(Description description) { description.appendText("an empty collection"); } /** * Creates a matcher for {@link java.util.Collection}s matching examined collections whose isEmpty * method returns true. *

* For example: *

assertThat(new ArrayList<String>(), is(empty()))
* */ @Factory public static Matcher> empty() { return new IsEmptyCollection(); } /** * Creates a matcher for {@link java.util.Collection}s matching examined collections whose isEmpty * method returns true. *

* For example: *

assertThat(new ArrayList<String>(), is(emptyCollectionOf(String.class)))
* * @param type * the type of the collection's content */ @Factory public static Matcher> emptyCollectionOf(Class type) { @SuppressWarnings({ "rawtypes", "unchecked" }) final Matcher> result = (Matcher)empty(); return result; } } libhamcrest-java-1.3/hamcrest-library/src/main/java/org/hamcrest/xml/0000755000175000017500000000000012131006721025213 5ustar ebourgebourglibhamcrest-java-1.3/hamcrest-library/src/main/java/org/hamcrest/xml/HasXPath.java0000644000175000017500000001530211765133740027555 0ustar ebourgebourgpackage org.hamcrest.xml; import org.hamcrest.*; import org.hamcrest.core.IsAnything; import org.w3c.dom.Node; import javax.xml.namespace.NamespaceContext; import javax.xml.namespace.QName; import javax.xml.xpath.*; import static javax.xml.xpath.XPathConstants.STRING; import static org.hamcrest.Condition.matched; import static org.hamcrest.Condition.notMatched; /** * Applies a Matcher to a given XML Node in an existing XML Node tree, specified by an XPath expression. * * @author Joe Walnes * @author Steve Freeman */ public class HasXPath extends TypeSafeDiagnosingMatcher { public static final NamespaceContext NO_NAMESPACE_CONTEXT = null; private static final IsAnything WITH_ANY_CONTENT = new IsAnything(""); private static final Condition.Step NODE_EXISTS = nodeExists(); private final Matcher valueMatcher; private final XPathExpression compiledXPath; private final String xpathString; private final QName evaluationMode; /** * @param xPathExpression XPath expression. * @param valueMatcher Matcher to use at given XPath. * May be null to specify that the XPath must exist but the value is irrelevant. */ public HasXPath(String xPathExpression, Matcher valueMatcher) { this(xPathExpression, NO_NAMESPACE_CONTEXT, valueMatcher); } /** * @param xPathExpression XPath expression. * @param namespaceContext Resolves XML namespace prefixes in the XPath expression * @param valueMatcher Matcher to use at given XPath. * May be null to specify that the XPath must exist but the value is irrelevant. */ public HasXPath(String xPathExpression, NamespaceContext namespaceContext, Matcher valueMatcher) { this(xPathExpression, namespaceContext, valueMatcher, STRING); } private HasXPath(String xPathExpression, NamespaceContext namespaceContext, Matcher valueMatcher, QName mode) { this.compiledXPath = compiledXPath(xPathExpression, namespaceContext); this.xpathString = xPathExpression; this.valueMatcher = valueMatcher; this.evaluationMode = mode; } @Override public boolean matchesSafely(Node item, Description mismatch) { return evaluated(item, mismatch) .and(NODE_EXISTS) .matching(valueMatcher); } @Override public void describeTo(Description description) { description.appendText("an XML document with XPath ").appendText(xpathString); if (valueMatcher != null) { description.appendText(" ").appendDescriptionOf(valueMatcher); } } private Condition evaluated(Node item, Description mismatch) { try { return matched(compiledXPath.evaluate(item, evaluationMode), mismatch); } catch (XPathExpressionException e) { mismatch.appendText(e.getMessage()); } return notMatched(); } private static Condition.Step nodeExists() { return new Condition.Step() { @Override public Condition apply(Object value, Description mismatch) { if (value == null) { mismatch.appendText("xpath returned no results."); return notMatched(); } return matched(String.valueOf(value), mismatch); } }; } private static XPathExpression compiledXPath(String xPathExpression, NamespaceContext namespaceContext) { try { final XPath xPath = XPathFactory.newInstance().newXPath(); if (namespaceContext != null) { xPath.setNamespaceContext(namespaceContext); } return xPath.compile(xPathExpression); } catch (XPathExpressionException e) { throw new IllegalArgumentException("Invalid XPath : " + xPathExpression, e); } } /** * Creates a matcher of {@link org.w3c.dom.Node}s that matches when the examined node has a value at the * specified xPath that satisfies the specified valueMatcher. *

* For example: *

assertThat(xml, hasXPath("/root/something[2]/cheese", equalTo("Cheddar")))
* * @param xPath * the target xpath * @param valueMatcher * matcher for the value at the specified xpath */ @Factory public static Matcher hasXPath(String xPath, Matcher valueMatcher) { return hasXPath(xPath, NO_NAMESPACE_CONTEXT, valueMatcher); } /** * Creates a matcher of {@link org.w3c.dom.Node}s that matches when the examined node has a value at the * specified xPath, within the specified namespaceContext, that satisfies * the specified valueMatcher. *

* For example: *

assertThat(xml, hasXPath("/root/something[2]/cheese", myNs, equalTo("Cheddar")))
* * @param xPath * the target xpath * @param namespaceContext * the namespace for matching nodes * @param valueMatcher * matcher for the value at the specified xpath */ @Factory public static Matcher hasXPath(String xPath, NamespaceContext namespaceContext, Matcher valueMatcher) { return new HasXPath(xPath, namespaceContext, valueMatcher, STRING); } /** * Creates a matcher of {@link org.w3c.dom.Node}s that matches when the examined node contains a node * at the specified xPath, with any content. *

* For example: *

assertThat(xml, hasXPath("/root/something[2]/cheese"))
* * @param xPath * the target xpath */ @Factory public static Matcher hasXPath(String xPath) { return hasXPath(xPath, NO_NAMESPACE_CONTEXT); } /** * Creates a matcher of {@link org.w3c.dom.Node}s that matches when the examined node contains a node * at the specified xPath within the specified namespace context, with any content. *

* For example: *

assertThat(xml, hasXPath("/root/something[2]/cheese", myNs))
* * @param xPath * the target xpath * @param namespaceContext * the namespace for matching nodes */ @Factory public static Matcher hasXPath(String xPath, NamespaceContext namespaceContext) { return new HasXPath(xPath, namespaceContext, WITH_ANY_CONTENT, XPathConstants.NODE); } } libhamcrest-java-1.3/hamcrest-library/src/main/java/org/hamcrest/xml/package.html0000644000175000017500000000013011753011773027502 0ustar ebourgebourg

Matchers of XML documents.

libhamcrest-java-1.3/hamcrest-library/src/main/java/org/hamcrest/object/0000755000175000017500000000000012131006721025661 5ustar ebourgebourglibhamcrest-java-1.3/hamcrest-library/src/main/java/org/hamcrest/object/IsCompatibleType.java0000644000175000017500000000244311756210543031757 0ustar ebourgebourgpackage org.hamcrest.object; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.Factory; import org.hamcrest.TypeSafeMatcher; public class IsCompatibleType extends TypeSafeMatcher> { private final Class type; public IsCompatibleType(Class type) { this.type = type; } @Override public boolean matchesSafely(Class cls) { return type.isAssignableFrom(cls); } @Override public void describeMismatchSafely(Class cls, Description mismatchDescription) { mismatchDescription.appendValue(cls.getName()); } @Override public void describeTo(Description description) { description.appendText("type < ").appendText(type.getName()); } /** * Creates a matcher of {@link Class} that matches when the specified baseType is * assignable from the examined class. *

* For example: *

assertThat(Integer.class, typeCompatibleWith(Number.class))
* * @param baseType * the base class to examine classes against */ @Factory public static Matcher> typeCompatibleWith(Class baseType) { return new IsCompatibleType(baseType); } } libhamcrest-java-1.3/hamcrest-library/src/main/java/org/hamcrest/object/IsEventFrom.java0000644000175000017500000000477711765133457030767 0ustar ebourgebourg/* Copyright (c) 2000-2006 hamcrest.org */ package org.hamcrest.object; import java.util.EventObject; import org.hamcrest.Description; import org.hamcrest.Factory; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeDiagnosingMatcher; /** * Tests if the value is an event announced by a specific object. */ public class IsEventFrom extends TypeSafeDiagnosingMatcher { private final Class eventClass; private final Object source; public IsEventFrom(Class eventClass, Object source) { this.eventClass = eventClass; this.source = source; } @Override public boolean matchesSafely(EventObject item, Description mismatchDescription) { if (!eventClass.isInstance(item)) { mismatchDescription.appendText("item type was " + item.getClass().getName()); return false; } if (!eventHasSameSource(item)) { mismatchDescription.appendText("source was ").appendValue(item.getSource()); return false; } return true; } private boolean eventHasSameSource(EventObject ev) { return ev.getSource() == source; } @Override public void describeTo(Description description) { description.appendText("an event of type ") .appendText(eventClass.getName()) .appendText(" from ") .appendValue(source); } /** * Creates a matcher of {@link java.util.EventObject} that matches any object * derived from eventClass announced by source. *

* For example: *
assertThat(myEvent, is(eventFrom(PropertyChangeEvent.class, myBean)))
* * @param eventClass * the class of the event to match on * @param source * the source of the event */ @Factory public static Matcher eventFrom(Class eventClass, Object source) { return new IsEventFrom(eventClass, source); } /** * Creates a matcher of {@link java.util.EventObject} that matches any EventObject * announced by source. *

* For example: *
assertThat(myEvent, is(eventFrom(myBean)))
* * @param source * the source of the event */ @Factory public static Matcher eventFrom(Object source) { return eventFrom(EventObject.class, source); } } libhamcrest-java-1.3/hamcrest-library/src/main/java/org/hamcrest/object/HasToString.java0000644000175000017500000000300411756203741030743 0ustar ebourgebourgpackage org.hamcrest.object; import org.hamcrest.Factory; import org.hamcrest.FeatureMatcher; import org.hamcrest.Matcher; import static org.hamcrest.core.IsEqual.equalTo; public class HasToString extends FeatureMatcher { public HasToString(Matcher toStringMatcher) { super(toStringMatcher, "with toString()", "toString()"); } @Override protected String featureValueOf(T actual) { return String.valueOf(actual); } /** * Creates a matcher that matches any examined object whose toString method * returns a value that satisfies the specified matcher. *

* For example: *

assertThat(true, hasToString(equalTo("TRUE")))
* * @param toStringMatcher * the matcher used to verify the toString result */ @Factory public static Matcher hasToString(Matcher toStringMatcher) { return new HasToString(toStringMatcher); } /** * Creates a matcher that matches any examined object whose toString method * returns a value equalTo the specified string. *

* For example: *

assertThat(true, hasToString("TRUE"))
* * @param expectedToString * the expected toString result */ @Factory public static Matcher hasToString(String expectedToString) { return new HasToString(equalTo(expectedToString)); } } libhamcrest-java-1.3/hamcrest-library/src/main/java/org/hamcrest/object/package.html0000644000175000017500000000015011753011773030152 0ustar ebourgebourg

Matchers that inspect objects and classes.

libhamcrest-java-1.3/hamcrest-library/src/main/java/org/hamcrest/text/0000755000175000017500000000000012131006721025377 5ustar ebourgebourglibhamcrest-java-1.3/hamcrest-library/src/main/java/org/hamcrest/text/IsEmptyString.java0000644000175000017500000000302411756205244031037 0ustar ebourgebourg package org.hamcrest.text; import static org.hamcrest.core.AnyOf.anyOf; import static org.hamcrest.core.IsNull.nullValue; import org.hamcrest.BaseMatcher; import org.hamcrest.Description; import org.hamcrest.Factory; import org.hamcrest.Matcher; /** * Matches empty Strings (and null). */ public final class IsEmptyString extends BaseMatcher { private static final IsEmptyString INSTANCE = new IsEmptyString(); @SuppressWarnings("unchecked") private static final Matcher NULL_OR_EMPTY_INSTANCE = anyOf(nullValue(), INSTANCE); @Override public boolean matches(Object item) { return item != null && item instanceof String && ((String) item).equals(""); } @Override public void describeTo(Description description) { description.appendText("an empty string"); } /** * Creates a matcher of {@link String} that matches when the examined string has zero length. *

* For example: *

assertThat("", isEmptyString())
* */ @Factory public static Matcher isEmptyString() { return INSTANCE; } /** * Creates a matcher of {@link String} that matches when the examined string is null, or * has zero length. *

* For example: *

assertThat(((String)null), isEmptyString())
* */ @Factory public static Matcher isEmptyOrNullString() { return NULL_OR_EMPTY_INSTANCE; } } libhamcrest-java-1.3/hamcrest-library/src/main/java/org/hamcrest/text/IsEqualIgnoringWhiteSpace.java0000644000175000017500000000561311756206317033303 0ustar ebourgebourg/* Copyright (c) 2000-2006 hamcrest.org */ package org.hamcrest.text; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.Factory; import org.hamcrest.TypeSafeMatcher; import static java.lang.Character.isWhitespace; /** * Tests if a string is equal to another string, ignoring any changes in whitespace. */ public class IsEqualIgnoringWhiteSpace extends TypeSafeMatcher { // TODO: Replace String with CharSequence to allow for easy interopability between // String, StringBuffer, StringBuilder, CharBuffer, etc (joe). private final String string; public IsEqualIgnoringWhiteSpace(String string) { if (string == null) { throw new IllegalArgumentException("Non-null value required by IsEqualIgnoringCase()"); } this.string = string; } @Override public boolean matchesSafely(String item) { return stripSpace(string).equalsIgnoreCase(stripSpace(item)); } @Override public void describeMismatchSafely(String item, Description mismatchDescription) { mismatchDescription.appendText("was ").appendText(stripSpace(item)); } @Override public void describeTo(Description description) { description.appendText("equalToIgnoringWhiteSpace(") .appendValue(string) .appendText(")"); } public String stripSpace(String toBeStripped) { final StringBuilder result = new StringBuilder(); boolean lastWasSpace = true; for (int i = 0; i < toBeStripped.length(); i++) { char c = toBeStripped.charAt(i); if (isWhitespace(c)) { if (!lastWasSpace) { result.append(' '); } lastWasSpace = true; } else { result.append(c); lastWasSpace = false; } } return result.toString().trim(); } /** * Creates a matcher of {@link String} that matches when the examined string is equal to * the specified expectedString, when whitespace differences are (mostly) ignored. To be * exact, the following whitespace rules are applied: *
    *
  • all leading and trailing whitespace of both the expectedString and the examined string are ignored
  • *
  • any remaining whitespace, appearing within either string, is collapsed to a single space before comparison
  • *
*

* For example: *

assertThat("   my\tfoo  bar ", equalToIgnoringWhiteSpace(" my  foo bar"))
* * @param expectedString * the expected value of matched strings */ @Factory public static Matcher equalToIgnoringWhiteSpace(String expectedString) { return new IsEqualIgnoringWhiteSpace(expectedString); } } libhamcrest-java-1.3/hamcrest-library/src/main/java/org/hamcrest/text/StringContainsInOrder.java0000644000175000017500000000340211756206707032513 0ustar ebourgebourgpackage org.hamcrest.text; import org.hamcrest.Description; import org.hamcrest.Factory; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; public class StringContainsInOrder extends TypeSafeMatcher { private final Iterable substrings; public StringContainsInOrder(Iterable substrings) { this.substrings = substrings; } @Override public boolean matchesSafely(String s) { int fromIndex = 0; for (String substring : substrings) { fromIndex = s.indexOf(substring, fromIndex); if (fromIndex == -1) { return false; } } return true; } @Override public void describeMismatchSafely(String item, Description mismatchDescription) { mismatchDescription.appendText("was \"").appendText(item).appendText("\""); } @Override public void describeTo(Description description) { description.appendText("a string containing ") .appendValueList("", ", ", "", substrings) .appendText(" in order"); } /** * Creates a matcher of {@link String} that matches when the examined string contains all of * the specified substrings, regardless of the order of their appearance. *

* For example: *

assertThat("myfoobarbaz", stringContainsInOrder(Arrays.asList("bar", "foo")))
* * @param substrings * the substrings that must be contained within matching strings */ @Factory public static Matcher stringContainsInOrder(Iterable substrings) { return new StringContainsInOrder(substrings); } } libhamcrest-java-1.3/hamcrest-library/src/main/java/org/hamcrest/text/IsEqualIgnoringCase.java0000644000175000017500000000343511756205451032120 0ustar ebourgebourg/* Copyright (c) 2000-2006 hamcrest.org */ package org.hamcrest.text; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.Factory; import org.hamcrest.TypeSafeMatcher; /** * Tests if a string is equal to another string, regardless of the case. */ public class IsEqualIgnoringCase extends TypeSafeMatcher { // TODO: Replace String with CharSequence to allow for easy interopability between // String, StringBuffer, StringBuilder, CharBuffer, etc (joe). private final String string; public IsEqualIgnoringCase(String string) { if (string == null) { throw new IllegalArgumentException("Non-null value required by IsEqualIgnoringCase()"); } this.string = string; } @Override public boolean matchesSafely(String item) { return string.equalsIgnoreCase(item); } @Override public void describeMismatchSafely(String item, Description mismatchDescription) { mismatchDescription.appendText("was ").appendText(item); } @Override public void describeTo(Description description) { description.appendText("equalToIgnoringCase(") .appendValue(string) .appendText(")"); } /** * Creates a matcher of {@link String} that matches when the examined string is equal to * the specified expectedString, ignoring case. *

* For example: *

assertThat("Foo", equalToIgnoringCase("FOO"))
* * @param expectedString * the expected value of matched strings */ @Factory public static Matcher equalToIgnoringCase(String expectedString) { return new IsEqualIgnoringCase(expectedString); } } libhamcrest-java-1.3/hamcrest-library/src/main/java/org/hamcrest/text/package.html0000644000175000017500000000014511753011773027674 0ustar ebourgebourg

Matchers that perform text comparisons.

libhamcrest-java-1.3/hamcrest-library/src/main/hamcrest-library.iml0000644000175000017500000000107111753011773025063 0ustar ebourgebourg libhamcrest-java-1.3/README.txt0000644000175000017500000000503711753011773015631 0ustar ebourgebourg ************ ************************* Hamcrest ************************* ************ --[ What is Hamcrest? ]------------------------------------- Hamcrest is a library of matchers, which can be combined in to create flexible expressions of intent in tests. --[ Binaries ]----------------------------------------------- Depending on how you intend to use Hamcrest, you should use different Jars. * [hamcrest-core.jar] This is the core API to be used by third-party framework providers. This includes the a foundation set of matcher implementations for common operations. This API is stable and will rarely change. You will need this library as a minimum. * [hamcrest-library.jar] The ever-growing library of Matcher implementations. This will grow between releases. * [hamcrest-generator.jar] A tool to allow many Matcher implementations to be combined into a single class so users don't have to remember many classes/packages to import. Generates code. * [hamcrest-integration.jar] Provides integration between Hamcrest and other testing tools, including JUnit (3 and 4), TestNG, jMock and EasyMock. Alternatively, if you don't care: * [hamcrest-all.jar] Includes all of the above. For convenience, all the Jars also include source code. --[ Dependencies ]------------------------------------------- All libraries in the 'lib' directory are used at build time, or are optional extras used for tighter integration with third party libraries. ALL OF THE DEPENDENCIES ARE OPTIONAL. --[ Documentation ]------------------------------------------ Documentation can be found at: http://hamcrest.org/ --[ Source ]------------------------------------------------- The complete source for Hamcrest is bundled. This includes: * Matcher core classes [src/core] * Matcher libary [src/library] * Matcher integrations [src/integration] * Syntactic sugar generator [src/generator] * Unit tests [src/unit-test] * Ant build file [build.xml] * Dependencies [lib] To build, please read BUILDING.txt ------------------------------------------------------------- Developers: - Joe Walnes - Nat Pryce - Steve Freeman Contributors: - Robert Chatley - Tom White - Neil Dunn - Dan North - Magne Rasmussen - David Saff Also, thanks to everyone who has worked on DynaMock, nMock, jMock, EasyMock and MiniMock! These libraries inspired Hamcrest. libhamcrest-java-1.3/hamcrest-examples/0000755000175000017500000000000011753011773017550 5ustar ebourgebourglibhamcrest-java-1.3/hamcrest-examples/src/0000755000175000017500000000000011753011773020337 5ustar ebourgebourglibhamcrest-java-1.3/hamcrest-examples/src/main/0000755000175000017500000000000012131006721021247 5ustar ebourgebourglibhamcrest-java-1.3/hamcrest-examples/src/main/java/0000755000175000017500000000000011753011773022204 5ustar ebourgebourglibhamcrest-java-1.3/hamcrest-examples/src/main/java/org/0000755000175000017500000000000011753011773022773 5ustar ebourgebourglibhamcrest-java-1.3/hamcrest-examples/src/main/java/org/hamcrest/0000755000175000017500000000000011753011773024601 5ustar ebourgebourglibhamcrest-java-1.3/hamcrest-examples/src/main/java/org/hamcrest/examples/0000755000175000017500000000000011753011773026417 5ustar ebourgebourglibhamcrest-java-1.3/hamcrest-examples/src/main/java/org/hamcrest/examples/testng/0000755000175000017500000000000012131006721027707 5ustar ebourgebourg././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootlibhamcrest-java-1.3/hamcrest-examples/src/main/java/org/hamcrest/examples/testng/ExampleWithAssertThat.javalibhamcrest-java-1.3/hamcrest-examples/src/main/java/org/hamcrest/examples/testng/ExampleWithAssertT0000644000175000017500000000120611753011773033402 0ustar ebourgebourgpackage org.hamcrest.examples.testng; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import org.testng.annotations.Test; /** * Demonstrates how Hamcrest matchers can be used with assertThat() * using TestNG. * * @author Joe Walnes */ @Test public class ExampleWithAssertThat { @Test public void usingAssertThat() { assertThat("xx", is("xx")); assertThat("yy", is(not("xx"))); assertThat("i like cheese", containsString("cheese")); } } ././@LongLink0000000000000000000000000000015400000000000011565 Lustar rootrootlibhamcrest-java-1.3/hamcrest-examples/src/main/java/org/hamcrest/examples/testng/ExampleWithEasyMock2.javalibhamcrest-java-1.3/hamcrest-examples/src/main/java/org/hamcrest/examples/testng/ExampleWithEasyMoc0000644000175000017500000000476411755775262033405 0ustar ebourgebourgpackage org.hamcrest.examples.testng; import static org.easymock.EasyMock.createMock; import static org.easymock.EasyMock.eq; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; import static org.hamcrest.EasyMock2Matchers.equalTo; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; /** * Demonstrates how Hamcrest matchers can be used from EasyMock with * TestNG. * * @author Joe Walnes */ @Test public class ExampleWithEasyMock2 { /* EasyMock (2) specific notes: * * Important terminology: * What EasyMock2 calls 'IArgumentMatcher', Hamcrest calls 'Matchers'. * * This functionality is available for EasyMock 2.x but NOT EasyMock 1.x. * * The class does not need to extend anything. * * The additional Hamcrest Matchers can be used by using a static import: * import static org.hamcrest.EasyMockMatchers.*; * * This provides the Hamcrest library of Matchers through an interface * that will provide an adapter to EasyMock IArgumentMatchers and report * them to EasyMock as it needs to keep track of them. */ /** * A sample interface that will be mocked. */ public static interface AnInterface { void doStuff(String string); } private AnInterface mock; @BeforeMethod public void setUpMock() { mock = createMock(AnInterface.class); } /** * This examples shows using a mock with a standard EasyMock2 matcher. * Hamcrest is not used here. */ @Test public void usingAnEasyMockMatcher() { mock.doStuff(eq("i like cheese and stuff")); replay(mock); mock.doStuff("i like cheese and stuff"); verify(mock); } /** * This examples shows using a mock with a Hamcrest matcher, adapted * to jMock. */ @Test public void usingAHamcrestMatcher() { mock.doStuff(equalTo("xx")); replay(mock); mock.doStuff("xx"); verify(mock); } /** * This examples shows using the standard jMock assertThat() method * with both jMock Constraints and Hamcrest Matchers. */ @Test public void usingAssertThat() { // TODO(joe): This is a bit tricker with EasyMock. //assertThat("xx", isTwoXs()); //assertThat("yy", not(isTwoXs())); //assertThat("i like cheese", startsWith("i like")); } } libhamcrest-java-1.3/hamcrest-examples/src/main/java/org/hamcrest/examples/junit4/0000755000175000017500000000000012131006721027620 5ustar ebourgebourg././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootlibhamcrest-java-1.3/hamcrest-examples/src/main/java/org/hamcrest/examples/junit4/ExampleWithAssertThat.javalibhamcrest-java-1.3/hamcrest-examples/src/main/java/org/hamcrest/examples/junit4/ExampleWithAssertT0000644000175000017500000000374511753011773033325 0ustar ebourgebourg/* Copyright (c) 2000-2010 hamcrest.org */ package org.hamcrest.examples.junit4; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; import org.junit.Test; /** * Demonstrates how HamCrest matchers can be used with assertThat() * using JUnit 4.x. * * @author Joe Walnes */ public class ExampleWithAssertThat { @Test public void usingAssertThat() { assertThat("xx", is("xx")); assertThat("yy", is(not("xx"))); assertThat("i like cheese", containsString("cheese")); } /** * Allow JUnit 4 test to be run under JUnit 3. */ public static junit.framework.Test suite() { return new junit.framework.JUnit4TestAdapter(ExampleWithAssertThat.class); } public static class ComplicatedClass { private int firstNumber = 23; private int secondNumber = 45; private String someText = "This is useful text"; public String whichOne(boolean first) { return someText + (first ? firstNumber : secondNumber); } } @Test public void showMismatch() { ComplicatedClass complicated = new ComplicatedClass(); assertThat(complicated, shouldBe("the wrong thing")); } private static Matcher shouldBe(final String string) { return new TypeSafeMatcher() { @Override public void describeTo(Description description) { } // no op @Override public boolean matchesSafely(ComplicatedClass item) { return false; } @Override public void describeMismatchSafely(ComplicatedClass item, Description mismatchDescription) { mismatchDescription.appendText(string); } }; } } ././@LongLink0000000000000000000000000000015400000000000011565 Lustar rootrootlibhamcrest-java-1.3/hamcrest-examples/src/main/java/org/hamcrest/examples/junit4/ExampleWithEasyMock2.javalibhamcrest-java-1.3/hamcrest-examples/src/main/java/org/hamcrest/examples/junit4/ExampleWithEasyMoc0000644000175000017500000000507611753011773033277 0ustar ebourgebourgpackage org.hamcrest.examples.junit4; import static org.easymock.EasyMock.createMock; import static org.easymock.EasyMock.eq; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; import static org.hamcrest.EasyMock2Matchers.equalTo; import org.junit.Test; /** * Demonstrates how HamCrest matchers can be used from EasyMock with * JUnit 4.x. * * @author Joe Walnes */ public class ExampleWithEasyMock2 { /* EasyMock (2) specific notes: * * Important terminology: * What EasyMock2 calls 'IArgumentMatcher', Hamcrest calls 'Matchers'. * * This functionality is available for EasyMock 2.x but NOT EasyMock 1.x. * * The class does not need to extend anything. * * The additional Hamcrest Matchers can be used by using a static import: * import static org.hamcrest.EasyMockMatchers.*; * * This provides the Hamcrest library of Matchers through an interface * that will provide an adapter to EasyMock IArgumentMatchers and report * them to EasyMock as it needs to keep track of them. */ /** * A sample interface that will be mocked. */ public static interface AnInterface { void doStuff(String string); } private AnInterface mock = createMock(AnInterface.class); /** * This examples shows using a mock with a standard EasyMock2 matcher. * Hamcrest is not used here. */ @Test public void usingAnEasyMockMatcher() { mock.doStuff(eq("i like cheese and stuff")); replay(mock); mock.doStuff("i like cheese and stuff"); verify(mock); } /** * This examples shows using a mock with a Hamcrest matcher, adapted * to jMock. */ @Test public void usingAHamcrestMatcher() { mock.doStuff(equalTo("xx")); replay(mock); mock.doStuff("xx"); verify(mock); } /** * This examples shows using the standard jMock assertThat() method * with both jMock Constraints and Hamcrest Matchers. */ @Test public void usingAssertThat() { // TODO(joe): This is a bit tricker with EasyMock. //assertThat("xx", isTwoXs()); //assertThat("yy", not(isTwoXs())); //assertThat("i like cheese", startsWith("i like")); } /** * Allow JUnit 4 test to be run under JUnit 3. */ public static junit.framework.Test suite() { return new junit.framework.JUnit4TestAdapter(ExampleWithEasyMock2.class); } } libhamcrest-java-1.3/hamcrest-examples/src/main/java/org/hamcrest/examples/junit3/0000755000175000017500000000000012131006721027617 5ustar ebourgebourg././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootlibhamcrest-java-1.3/hamcrest-examples/src/main/java/org/hamcrest/examples/junit3/ExampleWithAssertThat.javalibhamcrest-java-1.3/hamcrest-examples/src/main/java/org/hamcrest/examples/junit3/ExampleWithAssertT0000644000175000017500000000121111753011773033306 0ustar ebourgebourgpackage org.hamcrest.examples.junit3; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import junit.framework.TestCase; /** * Demonstrates how Hamcrest matchers can be used with assertThat() * using JUnit 3.8.x. * * @author Joe Walnes */ public class ExampleWithAssertThat extends TestCase { public void testUsingAssertThat() { assertThat("xx", is("xx")); assertThat("yy", is(not("xx"))); assertThat("i like cheese", containsString("cheese")); } } ././@LongLink0000000000000000000000000000015400000000000011565 Lustar rootrootlibhamcrest-java-1.3/hamcrest-examples/src/main/java/org/hamcrest/examples/junit3/ExampleWithEasyMock2.javalibhamcrest-java-1.3/hamcrest-examples/src/main/java/org/hamcrest/examples/junit3/ExampleWithEasyMoc0000644000175000017500000000456711753011773033302 0ustar ebourgebourgpackage org.hamcrest.examples.junit3; import static org.easymock.EasyMock.createMock; import static org.easymock.EasyMock.eq; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; import static org.hamcrest.EasyMock2Matchers.equalTo; import junit.framework.TestCase; /** * Demonstrates how HamCrest matchers can be used from EasyMock with * JUnit 3.x. * * @author Joe Walnes */ public class ExampleWithEasyMock2 extends TestCase { /* EasyMock (2) specific notes: * * Important terminology: * What EasyMock2 calls 'IArgumentMatcher', Hamcrest calls 'Matchers'. * * This functionality is available for EasyMock 2.x but NOT EasyMock 1.x. * * The class extends the standard JUnit TestCase. * * The additional Hamcrest Matchers can be used by using a static import: * import static org.hamcrest.EasyMockMatchers.*; * * This provides the Hamcrest library of Matchers through an interface * that will provide an adapter to EasyMock IArgumentMatchers and report * them to EasyMock as it needs to keep track of them. */ /** * A sample interface that will be mocked. */ public static interface AnInterface { void doStuff(String string); } private AnInterface mock = createMock(AnInterface.class); /** * This examples shows using a mock with a standard EasyMock2 matcher. * Hamcrest is not used here. */ public void testUsingAnEasyMockMatcher() { mock.doStuff(eq("i like cheese and stuff")); replay(mock); mock.doStuff("i like cheese and stuff"); verify(mock); } /** * This examples shows using a mock with a Hamcrest matcher, adapted * to jMock. */ public void testUsingAHamcrestMatcher() { mock.doStuff(equalTo("xx")); replay(mock); mock.doStuff("xx"); verify(mock); } /** * This examples shows using the standard jMock assertThat() method * with both jMock Constraints and Hamcrest Matchers. */ public void testUsingAssertThat() { // TODO(joe): This is a bit tricker with EasyMock. //assertThat("xx", equal("xx")); //assertThat("yy", not(equal("xx"))); //assertThat("i like cheese", startsWith("i like")); } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootlibhamcrest-java-1.3/hamcrest-examples/src/main/java/org/hamcrest/examples/junit3/ExampleWithJMock1.javalibhamcrest-java-1.3/hamcrest-examples/src/main/java/org/hamcrest/examples/junit3/ExampleWithJMock1.0000644000175000017500000000471211753011773033074 0ustar ebourgebourgpackage org.hamcrest.examples.junit3; import static org.hamcrest.JMock1Matchers.equalTo; import org.jmock.Mock; import org.jmock.MockObjectTestCase; /** * Demonstrates how HamCrest matchers can be used from jMock with JUnit 3.8.x. * * @author Joe Walnes */ public class ExampleWithJMock1 extends MockObjectTestCase { /* jMock specific notes: * * Important terminology: * What jMock calls 'Constraints', Hamcrest calls 'Matchers'. * * Note: This is only valid for jMock1. jMock2 supports Hamcrest out * of the box. * * The class extends org.jmock.MockObjectTestCase as usual. * This provides: * - The mock() methods and syntactic sugar for setting up mocks. * - Auto verification of mocks. * - jMock's implementation of assertThat(). * - jMock's standard Constraints. * * The additional Hamcrest Matchers can be used by using a static import: * import static org.hamcrest.JMockMatchers.*; * * This provides the Hamcrest library of Matchers through an interface * that will provide an adapter to JMock Constraints. */ /** * A sample interface to be mocked. */ public static interface AnInterface { void doStuff(String string); } private Mock mock = mock(AnInterface.class); private AnInterface anInterface = (AnInterface) mock.proxy(); /** * This examples shows using a mock with a standard jMock constraint. * Hamcrest is not used here. */ public void testUsingAJMockConstraint() { mock.expects(atLeastOnce()).method("doStuff") .with(stringContains("cheese")); anInterface.doStuff("i like cheese and stuff"); } /** * This examples shows using a mock with a Hamcrest matcher, adapted * to jMock. */ public void testUsingAHamcrestMatcher() { mock.expects(atLeastOnce()).method("doStuff") .with(equalTo("xx")); anInterface.doStuff("xx"); } /** * This examples shows using the standard jMock assertThat() method * with both jMock Constraints and Hamcrest Matchers. */ public void testUsingAssertThat() { assertThat("i like cheese", stringContains("cheese")); // jMock Constraint. assertThat("xx", equalTo("xx")); // Hamcrest Matcher. assertThat("yy", not(equalTo("xx"))); // Mixture of both. } } libhamcrest-java-1.3/hamcrest-examples/src/main/hamcrest-examples.iml0000644000175000017500000000110011753011773025400 0ustar ebourgebourg libhamcrest-java-1.3/hamcrest-core-1.3.pom0000644000175000017500000000137611776633002017705 0ustar ebourgebourg 4.0.0 org.hamcrest hamcrest-parent 1.3 hamcrest-core jar Hamcrest Core This is the core API of hamcrest matcher framework to be used by third-party framework providers. This includes the a foundation set of matcher implementations for common operations. libhamcrest-java-1.3/hamcrest-generator-1.3.pom0000644000175000017500000000132211776633002020732 0ustar ebourgebourg 4.0.0 org.hamcrest hamcrest-parent 1.3 hamcrest-generator Hamcrest generator A tool to allow many Matcher implementations to be combined into a single class so users don't have to remember many classes/packages to import. Generates code. libhamcrest-java-1.3/CHANGES.txt0000644000175000017500000000614211776632430015746 0ustar ebourgebourg== Version 1.3: Not yet released == * Introduce Condition class to ease the implementation of multi-step matches * Upgrade qdox (included in the generator) to the latest stable version * Correct inadvertent deprecation of the Is.isA factory method * Fix issue 179 - AllOf does not output mismatch description * Fix issue 177 - Introduced closeTo matcher for BigDecimals * Fix issue 152 - Factory classes missing from matchers.xml * Fix issue 144 - OrderingComparison doesn't describe mismatch of comparables that return values other than (-1,0,1) * Fix issue 134 - DescribedAs does not delegate describeMismatch * Fix issue 106 - deprecation warning when writing custom matchers * Fix issue 101 - Added theInstance alias for sameInstance factory method == Version 1.3 RC2: Released October 22 2010 == * Added FeatureMatcher * distinguish between instanceOf() and any() == Version 1.2: Released May 16 2009 == * Added mismatch reporting * Added WithSamePropertyValuesAs matcher * Moved any() from IsAnything to IsInstanceOf. It now checks the type of the matched object * Moved MatcherAssert from integration to core * Tightened up generics. * Added IsMapContainingKey and IsMapContainingValue matchers to resolve a generics bug in hasKey and hasValue static factories previously declared in IsMapContaining (ngd) * Added IsCollectionOnlyContaining and IsArrayOnlyContaining which matches collections (and arrays) where all match a given matcher. E.g onlyContains(3,4,5) or onlyContains(lessThan(9)) * text module moved to separate project, hamcrest-text-patterns * added more colection matchers: xContainingInAnyOrder, xContainingInOrder, xWithSize * new text Matcher: IsEmptyString * hamcrest generator uses method return type == Version 1.1: Released Jun 30 2007 == * Hamcrest Generator now includes JavaDoc and parameter names in generated code by using QDox to parse the source code. * Created hamcrest-core.jar (and removed hamcrest-api.jar). Moved core set of matchers (and, eq, not, etc) to this package to make it more practical for external libraries to embed Hamcrest. * Created CoreMatchers (static import sugar) in hamcrest-core.jar. * StringBuilder can use any Appendable (not just StringBuffer). * Added sensible toString() method to BaseMatcher. * Created StringDescription.asString() alias (because toString() caused issues with static imports). * Relaxed isInstanceOf() matcher generic type so it can be used on any kind of object. e.g. assertThat(someUnknownObject, isInstanceOf(String.class)); * Added any(Class), null(Class) and notNull(Class) matchers, which returns Matcher. Helpful when the compiler struggles with type inference. * Modified anyOf() and allOf() to accept mixed-types. * TypeSafeMatcher.matchesSafely() is now public. * Generator recognizes @Factory methods that return subclass of Matcher. (Fix by David Saff) == Version 1.0: Released Dec 15 2006 == Initial release. * Support for namespaces in HasXPath * Bug fix for matching empty elements with HasXPath libhamcrest-java-1.3/BUILDING.txt0000644000175000017500000000360111753011773016064 0ustar ebourgebourg ********************** ********************* Building Hamcrest ********************* ********************** --[ Build requirements ]------------------------------------- * JDK 1.5 Note: that this is a buildtime dependency for 1.5 specific features. However the final built jars should run on 1.4 and 1.3 JVMs with some features unavailable. * Ant 1.6 or greater To enable testing support, ensure junit.jar exists in ANT_HOME/lib. --[ Building from the command line ]------------------------- Execute the default ant target: ant This will do a full clean build, run all tests and (if successful) package up a distribution. The resulting builds reside in the 'build' directory. For a list of finer grained build operations: ant -projecthelp The default version number used in the build is 'SNAPSHOT'. To override this, you can pass a property to ant: ant -Dversion=MY.OTHER.VERSION --[ Building from the IDE ]---------------------------------- It is possible to compile and test the source directly from popular IDEs, without resorting to the command line. Steps: - Run 'ant library'. This generates additional Java coded necessary to compile. - Create a new project. - Add the following directories as source directories: hamcrest-core/src/main/java hamcrest-library/src/main/java hamcrest-generator/src/main/java hamcrest-integration/src/main/java build/temp/hamcrest-core/generated-code build/temp/hamcrest-library/generated-code - Add hamcrest-unit-test/src/main/java as a test directory. If this is unsupported by the IDE, add it as another source directory. - Include all jars in the lib directory in the classpath. - Compile as usual in the IDE. - If supported, run all tests under org.hamcrest from the IDEs JUnit runner. libhamcrest-java-1.3/hamcrest-integration-1.3.pom0000644000175000017500000000236011776633002021272 0ustar ebourgebourg 4.0.0 org.hamcrest hamcrest-parent 1.3 hamcrest-integration jar Hamcrest Integration Provides integration between Hamcrest and other testing tools, including JUnit (3 and 4), TestNG, jMock and EasyMock. org.hamcrest hamcrest-library 1.3 jmock jmock 1.1.0 true org.easymock easymock 2.2 true libhamcrest-java-1.3/matchers.xml0000644000175000017500000000525711761747007016474 0ustar ebourgebourg libhamcrest-java-1.3/LICENSE.txt0000644000175000017500000000274511753011773015761 0ustar ebourgebourgBSD License Copyright (c) 2000-2006, www.hamcrest.org All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of Hamcrest nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. libhamcrest-java-1.3/hamcrest-library-1.3.pom0000644000175000017500000000146411776633002020417 0ustar ebourgebourg 4.0.0 org.hamcrest hamcrest-parent 1.3 hamcrest-library jar Hamcrest library Hamcrest library of matcher implementations. org.hamcrest hamcrest-core 1.3 libhamcrest-java-1.3/core-matchers.xml0000644000175000017500000000157311753011773017412 0ustar ebourgebourg libhamcrest-java-1.3/lib/0000755000175000017500000000000011755766440014706 5ustar ebourgebourg