{
/**
* @see Matcher#_dont_implement_Matcher___instead_extend_BaseMatcher_()
*/
public final void _dont_implement_Matcher___instead_extend_BaseMatcher_() {
// See Matcher interface for an explanation of this method.
}
public void describeMismatch(Object item, Description description) {
description.appendText("was ").appendValue(item);
}
@Override
public String toString() {
return StringDescription.toString(this);
}
}
libhamcrest-java-1.2/hamcrest-core/src/main/java/org/hamcrest/CustomMatcher.java 0000644 0001750 0001750 00000002164 11123257170 027660 0 ustar moeller moeller package 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;
}
public final void describeTo(Description description) {
description.appendText(fixedDescription);
}
}
libhamcrest-java-1.2/hamcrest-core/src/main/java/org/hamcrest/CustomTypeSafeMatcher.java 0000644 0001750 0001750 00000002321 11123257170 031314 0 ustar moeller moeller package 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 #matchesSafely(T)} 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;
}
public final void describeTo(Description description) {
description.appendText(fixedDescription);
}
}
libhamcrest-java-1.2/hamcrest-core/src/main/java/org/hamcrest/Description.java 0000644 0001750 0001750 00000004354 11123257170 027370 0 ustar moeller moeller package 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 extends SelfDescribing> values);
public static final class NullDescription implements Description {
public Description appendDescriptionOf(SelfDescribing value) {
return this;
}
public Description appendList(String start, String separator,
String end, Iterable extends SelfDescribing> values) {
return this;
}
public Description appendText(String text) {
return this;
}
public Description appendValue(Object value) {
return this;
}
public Description appendValueList(String start, String separator,
String end, T... values) {
return this;
}
public Description appendValueList(String start, String separator,
String end, Iterable values) {
return this;
}
@Override
public String toString() {
return "";
}
}
}
libhamcrest-java-1.2/hamcrest-core/src/main/java/org/hamcrest/DiagnosingMatcher.java 0000644 0001750 0001750 00000000707 11123257170 030471 0 ustar moeller moeller package org.hamcrest;
/**
* TODO(ngd): Document.
*
* @param
*/
public abstract class DiagnosingMatcher extends BaseMatcher {
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.2/hamcrest-core/src/main/java/org/hamcrest/Factory.java 0000644 0001750 0001750 00000000674 11123257170 026515 0 ustar moeller moeller package 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.2/hamcrest-core/src/main/java/org/hamcrest/FeatureMatcher.java 0000644 0001750 0001750 00000003545 11175026440 030006 0 ustar moeller moeller package 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 super U> 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 super U> 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 mismatchDescription) {
final U featureValue = featureValueOf(actual);
if (!subMatcher.matches(featureValue)) {
mismatchDescription.appendText(featureName).appendText(" ");
subMatcher.describeMismatch(featureValue, mismatchDescription);
return false;
}
return true;
};
public final void describeTo(Description description) {
description.appendText(featureDescription).appendText(" ")
.appendDescriptionOf(subMatcher);
}
} libhamcrest-java-1.2/hamcrest-core/src/main/java/org/hamcrest/Matcher.java 0000644 0001750 0001750 00000004304 11123257170 026463 0 ustar moeller moeller /* 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}.
*
* @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.2/hamcrest-core/src/main/java/org/hamcrest/MatcherAssert.java 0000644 0001750 0001750 00000001652 11123257170 027650 0 ustar moeller moeller /* Copyright (c) 2000-2006 hamcrest.org
*/
package org.hamcrest;
public class MatcherAssert {
public static void assertThat(T actual, Matcher super T> matcher) {
assertThat("", actual, matcher);
}
public static void assertThat(String reason, T actual, Matcher super T> 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.2/hamcrest-core/src/main/java/org/hamcrest/SelfDescribing.java 0000644 0001750 0001750 00000000722 11123257170 027763 0 ustar moeller moeller package 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.2/hamcrest-core/src/main/java/org/hamcrest/StringDescription.java 0000644 0001750 0001750 00000002753 11123257170 030560 0 ustar moeller moeller package 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.2/hamcrest-core/src/main/java/org/hamcrest/TypeSafeDiagnosingMatcher.java 0000644 0001750 0001750 00000004462 11123257170 032134 0 ustar moeller moeller package 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);
}
@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.2/hamcrest-core/src/main/java/org/hamcrest/TypeSafeMatcher.java 0000644 0001750 0001750 00000005543 11202570227 030131 0 ustar moeller moeller package 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}.
*/
@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.2/hamcrest-core/src/main/java/org/hamcrest/package.html 0000644 0001750 0001750 00000000332 11123257170 026513 0 ustar moeller moeller
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.2/hamcrest-examples/ 0000755 0001750 0001750 00000000000 10632277411 020075 5 ustar moeller moeller libhamcrest-java-1.2/hamcrest-examples/src/ 0000755 0001750 0001750 00000000000 10632277411 020664 5 ustar moeller moeller libhamcrest-java-1.2/hamcrest-examples/src/main/ 0000755 0001750 0001750 00000000000 10632277411 021610 5 ustar moeller moeller libhamcrest-java-1.2/hamcrest-examples/src/main/java/ 0000755 0001750 0001750 00000000000 10632277411 022531 5 ustar moeller moeller libhamcrest-java-1.2/hamcrest-examples/src/main/java/org/ 0000755 0001750 0001750 00000000000 10632277411 023320 5 ustar moeller moeller libhamcrest-java-1.2/hamcrest-examples/src/main/java/org/hamcrest/ 0000755 0001750 0001750 00000000000 10632277411 025126 5 ustar moeller moeller libhamcrest-java-1.2/hamcrest-examples/src/main/java/org/hamcrest/examples/ 0000755 0001750 0001750 00000000000 10632277411 026744 5 ustar moeller moeller libhamcrest-java-1.2/hamcrest-examples/src/main/java/org/hamcrest/examples/junit3/ 0000755 0001750 0001750 00000000000 11675175275 030175 5 ustar moeller moeller ././@LongLink 0000000 0000000 0000000 00000000155 00000000000 011566 L ustar root root libhamcrest-java-1.2/hamcrest-examples/src/main/java/org/hamcrest/examples/junit3/ExampleWithAssertThat.java libhamcrest-java-1.2/hamcrest-examples/src/main/java/org/hamcrest/examples/junit3/ExampleWithAssertT0000644 0001750 0001750 00000001162 11033250101 033617 0 ustar moeller moeller package 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"));
}
}
././@LongLink 0000000 0000000 0000000 00000000154 00000000000 011565 L ustar root root libhamcrest-java-1.2/hamcrest-examples/src/main/java/org/hamcrest/examples/junit3/ExampleWithEasyMock2.java libhamcrest-java-1.2/hamcrest-examples/src/main/java/org/hamcrest/examples/junit3/ExampleWithEasyMoc0000644 0001750 0001750 00000004451 11033250101 033576 0 ustar moeller moeller package 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"));
}
}
././@LongLink 0000000 0000000 0000000 00000000151 00000000000 011562 L ustar root root libhamcrest-java-1.2/hamcrest-examples/src/main/java/org/hamcrest/examples/junit3/ExampleWithJMock1.java libhamcrest-java-1.2/hamcrest-examples/src/main/java/org/hamcrest/examples/junit3/ExampleWithJMock1.0000644 0001750 0001750 00000004573 11033250101 033405 0 ustar moeller moeller package 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.2/hamcrest-examples/src/main/java/org/hamcrest/examples/junit4/ 0000755 0001750 0001750 00000000000 11675175275 030176 5 ustar moeller moeller ././@LongLink 0000000 0000000 0000000 00000000155 00000000000 011566 L ustar root root libhamcrest-java-1.2/hamcrest-examples/src/main/java/org/hamcrest/examples/junit4/ExampleWithAssertThat.java libhamcrest-java-1.2/hamcrest-examples/src/main/java/org/hamcrest/examples/junit4/ExampleWithAssertT0000644 0001750 0001750 00000003723 11121050350 033627 0 ustar moeller moeller 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 Matcher shouldBe(String string) {
return new TypeSafeMatcher() {
public void describeTo(Description description) {
// TODO Auto-generated method stub
}
@Override
public boolean matchesSafely(ComplicatedClass item) {
// TODO Auto-generated method stub
return false;
}
@Override
public void describeMismatchSafely(ComplicatedClass item, Description mismatchDescription) {
// TODO Auto-generated method stub
}
};
}
}
././@LongLink 0000000 0000000 0000000 00000000154 00000000000 011565 L ustar root root libhamcrest-java-1.2/hamcrest-examples/src/main/java/org/hamcrest/examples/junit4/ExampleWithEasyMock2.java libhamcrest-java-1.2/hamcrest-examples/src/main/java/org/hamcrest/examples/junit4/ExampleWithEasyMoc0000644 0001750 0001750 00000004746 11033250101 033606 0 ustar moeller moeller package 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.2/hamcrest-examples/src/main/java/org/hamcrest/examples/testng/ 0000755 0001750 0001750 00000000000 11675175275 030265 5 ustar moeller moeller ././@LongLink 0000000 0000000 0000000 00000000155 00000000000 011566 L ustar root root libhamcrest-java-1.2/hamcrest-examples/src/main/java/org/hamcrest/examples/testng/ExampleWithAssertThat.java libhamcrest-java-1.2/hamcrest-examples/src/main/java/org/hamcrest/examples/testng/ExampleWithAssertT0000644 0001750 0001750 00000001154 11033250101 033710 0 ustar moeller moeller package 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"));
}
}
././@LongLink 0000000 0000000 0000000 00000000154 00000000000 011565 L ustar root root libhamcrest-java-1.2/hamcrest-examples/src/main/java/org/hamcrest/examples/testng/ExampleWithEasyMock2.java libhamcrest-java-1.2/hamcrest-examples/src/main/java/org/hamcrest/examples/testng/ExampleWithEasyMoc0000644 0001750 0001750 00000004666 11033250101 033676 0 ustar moeller moeller package 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.Configuration;
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;
@Configuration(beforeTestMethod = true)
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.2/hamcrest-generator/ 0000755 0001750 0001750 00000000000 10632277426 020253 5 ustar moeller moeller libhamcrest-java-1.2/hamcrest-generator/src/ 0000755 0001750 0001750 00000000000 10632277426 021042 5 ustar moeller moeller libhamcrest-java-1.2/hamcrest-generator/src/main/ 0000755 0001750 0001750 00000000000 10632277426 021766 5 ustar moeller moeller libhamcrest-java-1.2/hamcrest-generator/src/main/java/ 0000755 0001750 0001750 00000000000 10632277427 022710 5 ustar moeller moeller libhamcrest-java-1.2/hamcrest-generator/src/main/java/org/ 0000755 0001750 0001750 00000000000 10632277427 023477 5 ustar moeller moeller libhamcrest-java-1.2/hamcrest-generator/src/main/java/org/hamcrest/ 0000755 0001750 0001750 00000000000 10632277427 025305 5 ustar moeller moeller libhamcrest-java-1.2/hamcrest-generator/src/main/java/org/hamcrest/generator/ 0000755 0001750 0001750 00000000000 11675175275 027301 5 ustar moeller moeller libhamcrest-java-1.2/hamcrest-generator/src/main/java/org/hamcrest/generator/config/ 0000755 0001750 0001750 00000000000 11675175275 030546 5 ustar moeller moeller ././@LongLink 0000000 0000000 0000000 00000000151 00000000000 011562 L ustar root root libhamcrest-java-1.2/hamcrest-generator/src/main/java/org/hamcrest/generator/config/XmlConfigurator.java libhamcrest-java-1.2/hamcrest-generator/src/main/java/org/hamcrest/generator/config/XmlConfigurator.0000644 0001750 0001750 00000012371 11111332021 033637 0 ustar moeller moeller package 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();
}
}
}
././@LongLink 0000000 0000000 0000000 00000000151 00000000000 011562 L ustar root root libhamcrest-java-1.2/hamcrest-generator/src/main/java/org/hamcrest/generator/EasyMock2FactoryWriter.java libhamcrest-java-1.2/hamcrest-generator/src/main/java/org/hamcrest/generator/EasyMock2FactoryWriter.0000644 0001750 0001750 00000011235 11033250104 033573 0 ustar moeller moeller package 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);
}
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);
}
public void writeFooter() throws IOException {
output.append('}').append(newLine);
}
public void close() throws IOException {
output.close();
}
public void flush() throws IOException {
output.flush();
}
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.2/hamcrest-generator/src/main/java/org/hamcrest/generator/FactoryMethod.java 0000644 0001750 0001750 00000016312 11074021477 032702 0 ustar moeller moeller package 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(...)'
*
* @return
*/
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;
}
@SuppressWarnings({"RedundantIfStatement"})
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
FactoryMethod that = (FactoryMethod) o;
if (exceptions != null ? !exceptions.equals(that.exceptions) : that.exceptions != null) return false;
if (factoryMethod != null ? !factoryMethod.equals(that.factoryMethod) : that.factoryMethod != null)
return false;
if (genericTypeParameters != null ? !genericTypeParameters.equals(that.genericTypeParameters) : that.genericTypeParameters != null)
return false;
if (generifiedType != null ? !generifiedType.equals(that.generifiedType) : that.generifiedType != null)
return false;
if (javaDoc != null ? !javaDoc.equals(that.javaDoc) : that.javaDoc != null) return false;
if (matcherClass != null ? !matcherClass.equals(that.matcherClass) : that.matcherClass != null) return false;
if (parameters != null ? !parameters.equals(that.parameters) : that.parameters != null) return false;
return true;
}
@Override
public int hashCode() {
int result;
result = (matcherClass != null ? matcherClass.hashCode() : 0);
result = 31 * result + (factoryMethod != null ? factoryMethod.hashCode() : 0);
result = 31 * result + (generifiedType != null ? generifiedType.hashCode() : 0);
result = 31 * result + (parameters != null ? parameters.hashCode() : 0);
result = 31 * result + (exceptions != null ? exceptions.hashCode() : 0);
result = 31 * result + (genericTypeParameters != null ? genericTypeParameters.hashCode() : 0);
result = 31 * result + (javaDoc != null ? javaDoc.hashCode() : 0);
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;
}
@SuppressWarnings({"RedundantIfStatement"})
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Parameter parameter = (Parameter) o;
if (name != null ? !name.equals(parameter.name) : parameter.name != null) return false;
if (type != null ? !type.equals(parameter.type) : parameter.type != null) return false;
return true;
}
@Override
public int hashCode() {
int result;
result = (type != null ? type.hashCode() : 0);
result = 31 * result + (name != null ? name.hashCode() : 0);
return result;
}
@Override
public String toString() {
return type + " " + name;
}
}
}
libhamcrest-java-1.2/hamcrest-generator/src/main/java/org/hamcrest/generator/FactoryWriter.java 0000644 0001750 0001750 00000002261 11033250104 032716 0 ustar moeller moeller package 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;
}
././@LongLink 0000000 0000000 0000000 00000000150 00000000000 011561 L ustar root root libhamcrest-java-1.2/hamcrest-generator/src/main/java/org/hamcrest/generator/HamcrestFactoryWriter.java libhamcrest-java-1.2/hamcrest-generator/src/main/java/org/hamcrest/generator/HamcrestFactoryWriter.j0000644 0001750 0001750 00000013703 11111307215 033723 0 ustar moeller moeller package 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);
}
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);
}
public void writeFooter() throws IOException {
output.append('}').append(newLine);
}
public void close() throws IOException {
output.close();
}
public void flush() throws IOException {
output.flush();
}
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.2/hamcrest-generator/src/main/java/org/hamcrest/generator/QDox.java 0000644 0001750 0001750 00000001631 11033250104 030765 0 ustar moeller moeller package 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.2/hamcrest-generator/src/main/java/org/hamcrest/generator/QDoxFactoryReader.java 0000644 0001750 0001750 00000010124 11111332771 033445 0 ustar moeller moeller package 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);
}
public Iterator iterator() {
final Iterator iterator = wrapped.iterator();
return new Iterator() {
public boolean hasNext() {
return iterator.hasNext();
}
public FactoryMethod next() {
return enhance(iterator.next());
}
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()];
for (int i = 0; i < types.length; i++) {
// QDox ignores varargs and generics, so we strip them out to help QDox.
String type = params.get(i).getType();
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);
return methods.length == 1 ? methods[0] : null;
}
/**
* Reconstructs the JavaDoc as a string for a particular method.
*/
private 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();
}
}
././@LongLink 0000000 0000000 0000000 00000000147 00000000000 011567 L ustar root root libhamcrest-java-1.2/hamcrest-generator/src/main/java/org/hamcrest/generator/QuickReferenceWriter.java libhamcrest-java-1.2/hamcrest-generator/src/main/java/org/hamcrest/generator/QuickReferenceWriter.ja0000644 0001750 0001750 00000003553 11033250104 033660 0 ustar moeller moeller package 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;
}
public void writeHeader() throws IOException {
}
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 String removePackageNames(String in) {
// Simplify fully qualified names (allowing for trailing '...').
return in == null ? "" : in.replaceAll("[^<>]*\\.([^\\.])", "$1");
}
public void writeFooter() throws IOException {
}
public void close() throws IOException {
}
public void flush() throws IOException {
}
}
././@LongLink 0000000 0000000 0000000 00000000152 00000000000 011563 L ustar root root libhamcrest-java-1.2/hamcrest-generator/src/main/java/org/hamcrest/generator/ReflectiveFactoryReader.java libhamcrest-java-1.2/hamcrest-generator/src/main/java/org/hamcrest/generator/ReflectiveFactoryReader0000644 0001750 0001750 00000014164 11111331567 033754 0 ustar moeller moeller package org.hamcrest.generator;
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();
}
public Iterator iterator() {
return new Iterator() {
private int currentMethod = -1;
private Method[] allMethods = cls.getMethods();
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.
}
}
public FactoryMethod next() {
if (currentMethod >= 0 && currentMethod < allMethods.length) {
return buildFactoryMethod(allMethods[currentMethod]);
} else {
throw new IllegalStateException("next() called without hasNext() check.");
}
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
/**
* Determine whether a particular method is classified as a matcher factory method.
*