下面列出了java.io.StringBufferInputStream#org.hamcrest.Description 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Creates a matcher against the text stored in R.id.item_content. This text is roughly
* "item: $row_number".
*/
@SuppressWarnings("rawtypes")
public static Matcher<Object> withItemContent(final Matcher<String> itemTextMatcher) {
// use preconditions to fail fast when a test is creating an invalid matcher.
checkNotNull(itemTextMatcher);
return new BoundedMatcher<Object, Map>(Map.class) {
@Override
public boolean matchesSafely(Map map) {
return hasEntry(equalTo("STR"), itemTextMatcher).matches(map);
}
@Override
public void describeTo(Description description) {
description.appendText("with item content: ");
itemTextMatcher.describeTo(description);
}
};
}
@SuppressWarnings("unchecked")
private static <T> Description getDescription(String reason, T actual, Matcher<? super T> matcher, String additionalText) {
if (matcher instanceof CustomDescriptionProvider) {
return ((CustomDescriptionProvider<T>) matcher).describe(reason, actual, additionalText);
}
// @formatter:off
Description description = new StringDescription();
description.appendText(getReason(reason, matcher))
.appendText(additionalText==null ? "" : ("\n"+additionalText))
.appendText("\nExpected: ")
.appendDescriptionOf(matcher)
.appendText("\n but: ");
matcher.describeMismatch(actual, description);
// @formatter:on
return description;
}
private static Matcher<View> childAtPosition(
final Matcher<View> parentMatcher, final int position) {
return new TypeSafeMatcher<View>() {
@Override
public void describeTo(Description description) {
description.appendText("Child at position " + position + " in parent ");
parentMatcher.describeTo(description);
}
@Override
public boolean matchesSafely(View view) {
ViewParent parent = view.getParent();
return parent instanceof ViewGroup && parentMatcher.matches(parent)
&& view.equals(((ViewGroup) parent).getChildAt(position));
}
};
}
public static Matcher<Violation> hasType(final String expectedType) {
return new TypeSafeDiagnosingMatcher<Violation>() {
@Override
protected boolean matchesSafely(final Violation violation, final Description mismatchDescription) {
final String actualType = violation.getViolationType();
if (!Objects.equals(actualType, expectedType)) {
mismatchDescription.appendText("type was ").appendValue(actualType);
return false;
} else {
return true;
}
}
@Override
public void describeTo(final Description description) {
description.appendText("violation of type ").appendValue(expectedType);
}
};
}
/**
* This helps "find" the lists in the activity, since there is more than 1.
*
* @param tag
* @return
*/
private static Matcher<View> withTag(final Object tag) {
return new TypeSafeMatcher<View>() {
@Override
public void describeTo(final Description description) {
description.appendText("has tag equals to: " + tag);
}
@Override
protected boolean matchesSafely(final View view) {
Object viewTag = view.getTag();
if (viewTag == null) {
return tag == null;
}
return viewTag.equals(tag);
}
};
}
@Override
protected boolean matches(Object item, Description mismatchDescription) {
mismatchDescription.appendText(
String.format("failed after %d*%d=%dms:%n", maxAttempts, pause, maxAttempts * pause));
for (int i = 0; i < maxAttempts; i++) {
boolean result = delegate.matches(item);
if (result) {
return true;
}
delegate.describeMismatch(item, mismatchDescription);
mismatchDescription.appendText(", ");
try {
Thread.sleep(pause);
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
}
return false;
}
public static <T> Matcher<Optional<T>> equalToOptional(final T operand) {
return new TypeSafeMatcher<Optional<T>>() {
private Matcher<T> equalTo;
@Override
protected boolean matchesSafely(Optional<T> t) {
if(t.isPresent()) {
equalTo = IsEqual.equalTo(t.get());
return equalTo.matches(operand);
}
return false;
}
@Override
public void describeTo(Description description) {
IsEqual.equalTo(equalTo).describeTo(description);
}
};
}
public static Matcher<Response> noContent() {
final int statusCode = Response.Status.NO_CONTENT.getStatusCode();
return new CustomMatcher<Response>("no content (" + statusCode + ")") {
@Override
public boolean matches(Object o) {
return (o instanceof Response)
&& (((Response) o).getStatus() == statusCode);
}
@Override
public void describeMismatch(Object item, Description description) {
Response response = (Response) item;
provideDescription(response, description);
}
};
}
public static Matcher<ServiceResponse> isResponseOk() {
return new BaseMatcher<ServiceResponse>() {
@Override
protected boolean matchesSafely(ServiceResponse item) {
return item.getStatus().equals(ServiceResponse.Status.OK) &&
item.getResponseMessages().isEmpty();
}
@Override
public void describeTo(Description description) {
description.appendText(
ServiceResponseBuilder.ok().build().toString()
);
}
};
}
@Override
protected boolean matchesSafely(JsonNode jsonNode, Description description) {
// check network name
String jsonNetwork = jsonNode.get(NETWORK).asText();
String network = phyIntf.network();
if (!jsonNetwork.equals(network)) {
description.appendText("network name was " + jsonNetwork);
return false;
}
// check interface name
String jsonIntf = jsonNode.get(INTERFACE).asText();
String intf = phyIntf.intf();
if (!jsonIntf.equals(intf)) {
description.appendText("interface name was " + jsonIntf);
return false;
}
return true;
}
private static Matcher<View> childAtPosition(final Matcher<View> parentMatcher, final int position) {
return new TypeSafeMatcher<View>() {
@Override
public void describeTo(Description description) {
description.appendText("Child at position " + position + " in parent ");
parentMatcher.describeTo(description);
}
@Override
public boolean matchesSafely(View view) {
ViewParent parent = view.getParent();
return parent instanceof ViewGroup && parentMatcher.matches(parent)
&& view.equals(((ViewGroup) parent).getChildAt(position));
}
};
}
public static Matcher<Response> aHeader(final String header, final Matcher<?> matcher) {
return new TypeSafeMatcher<Response>() {
@Override
protected boolean matchesSafely(Response response) {
String actualHeaderValue = response.getHeader(header);
return matcher.matches(actualHeaderValue);
}
@Override
public void describeTo(Description description) {
// description.appendText("has statusCode").appendDescriptionOf(statusCodeMatches);
}
@Override
protected void describeMismatchSafely(Response item, Description mismatchDescription) {
// mismatchDescription.appendText("statusCode<").appendValue(item.statusCode()+"").appendText(">");
}
};
}
@Factory
public static Matcher<Object> isSerializable() {
return new BaseMatcher<Object>() {
public boolean matches(Object o) {
try {
new ObjectOutputStream(new ByteArrayOutputStream()).writeObject(o);
} catch (IOException e) {
throw new RuntimeException(e);
}
return true;
}
public void describeTo(Description description) {
description.appendText("is serializable");
}
};
}
static Matcher<? extends Throwable> causalChainContains(final Class<?> cls) {
return new TypeSafeMatcher<Throwable>() {
@Override
protected boolean matchesSafely(Throwable item) {
final List<Throwable> causalChain = Throwables.getCausalChain(item);
for (Throwable throwable : causalChain) {
if(cls.isAssignableFrom(throwable.getClass())){
return true;
}
}
return false;
}
@Override
public void describeTo(Description description) {
description.appendText("exception with causal chain containing " + cls.getSimpleName());
}
};
}
public static <T> Probe serviceInvocationResult(final Supplier<T> serviceInvocation, final Matcher<? super T> matcher) {
return new Probe() {
private T lastResult;
private Exception lastException;
@Override
public void sample() {
try {
this.lastResult = serviceInvocation.get();
} catch (Exception e) {
this.lastException = e;
}
}
@Override
public boolean isSatisfied() {
return matcher.matches(lastResult);
}
@Override
public void describeFailureTo(Description description) {
description.appendText("Expected serviceInovcation to return:\n");
matcher.describeTo(description);
if (lastException != null) {
description.appendText("\nBut last serviceInvocation threw exception:\n" + lastException.toString());
} else {
description.appendText("\nBut last serviceInvocation returned:\n" + lastResult);
}
}
};
}
private static <T> Matcher<Iterable<? extends T>> containsInOrder(T a, T b) {
Objects.requireNonNull(a);
Objects.requireNonNull(b);
return new TypeSafeMatcher<Iterable<? extends T>>() {
@Override
protected boolean matchesSafely(Iterable<? extends T> ts) {
int ai = -1, bi = -1, i = 0;
for (T t : ts) {
if (a.equals(t)) {
ai = i;
}
if (b.equals(t)) {
bi = i;
}
i++;
}
return ai > -1 && bi > -1 && ai < bi;
}
@Override
public void describeTo(Description description) {
description.appendText("Contains ");
description.appendValue(a);
description.appendText(" before ");
description.appendValue(b);
}
};
}
@Override
public void describeTo(Description description) {
description.appendText("stats: " + type.name() + "=" + count);
if ((desc != null) && (description != desc.getDescription())) {
description.appendText(desc.getDescription().toString());
}
}
@Test
public void testReadExternalRef_RelativeFileFormat_ExceptionThrown(@Injectable final List<AuthorizationValue> auths,
@Mocked IOUtils ioUtils,
@Mocked Files files,
@Injectable final Path parentDirectory,
@Injectable final Path pathToUse
) throws Exception {
final String filePath = "file.json";
File file = tempFolder.newFile(filePath);
final String expectedResult = "really good json";
setupRelativeFileExpectations(parentDirectory, pathToUse, file, filePath);
new StrictExpectations() {{
IOUtils.toString((FileInputStream) any, UTF_8);
times = 1;
result = new IOException();
}};
thrown.expect(new BaseMatcher<IOException>() {
@Override
public void describeTo(Description description) { }
@Override
public boolean matches(Object o) {
return ((Exception)o).getCause().getClass().equals(IOException.class);
}
});
RefUtils.readExternalRef(filePath, RefFormat.RELATIVE, auths, parentDirectory);
}
@Factory
public static <T extends CharSequence> Matcher<T> matchesRegexp(final Pattern pattern) {
return new BaseMatcher<T>() {
public boolean matches(Object o) {
return pattern.matcher((CharSequence) o).matches();
}
public void describeTo(Description description) {
description.appendText("a CharSequence that matches regexp ").appendValue(pattern);
}
};
}
public static Matcher<View> hasCompoundDrawable(final int start, final int top,
final int end, final int bottom) {
return new BoundedMatcher<View, TextView>(TextView.class){
@Override
public void describeTo(Description description) {
final String formatted =
String.format(Locale.getDefault(),
"has Compound Drawable: start=%d, top=%d, end=%d, bottom=%d",
start, top, end, bottom);
description.appendText(formatted);
}
@Override
public boolean matchesSafely(TextView view) {
// We cannot verify the actual drawable, but we can verify one has been set.
final Drawable [] drawables = view.getCompoundDrawables();
if (drawables[0] != null && start == 0) {
return false;
}
if (drawables[1] != null && top == 0) {
return false;
}
if (drawables[2] != null && end == 0) {
return false;
}
if (drawables[3] != null && bottom == 0) {
return false;
}
return true;
}
};
}
@Override
public void describeTo(Description description) {
description
.appendText("a KV(")
.appendValue(keyMatcher)
.appendText(", ")
.appendValue(valueMatcher)
.appendText(")");
}
@Override
protected boolean matchesSafely(T t, Description description) {
boolean result = true;
for (PropertyMatcher<T, ?> pm : matchers) {
if (!pm.matchesSafely(t, description)) { result = false; }
}
return result;
}
public void describeTo(Description description) {
description.appendText("same(");
appendQuoting(description);
description.appendText(wanted.toString());
appendQuoting(description);
description.appendText(")");
}
private TypeSafeMatcher<File> exists() {
return new TypeSafeMatcher<File>() {
@Override
public boolean matchesSafely(File file) {
return file.exists();
}
@Override
public void describeTo(Description description) {
description.appendText("file should exist but does not");
}
};
}
public static Matcher<Preference> isEnabled() {
return new TypeSafeMatcher<Preference>() {
@Override
public void describeTo(Description description) {
description.appendText(" is an enabled preference");
}
@Override
public boolean matchesSafely(Preference pref) {
return pref.isEnabled();
}
};
}
@Test
public void coderWarnsForInterface() throws Exception {
String expectedLogMessage =
"Can't verify serialized elements of type TestInterface "
+ "have well defined equals method.";
// Create the coder multiple times ensuring that we only log once.
SerializableCoder.of(TestInterface.class);
SerializableCoder.of(TestInterface.class);
SerializableCoder.of(TestInterface.class);
expectedLogs.verifyLogRecords(
new TypeSafeMatcher<Iterable<LogRecord>>() {
@Override
public void describeTo(Description description) {
description.appendText(
String.format("single warn log message containing [%s]", expectedLogMessage));
}
@Override
protected boolean matchesSafely(Iterable<LogRecord> item) {
int count = 0;
for (LogRecord logRecord : item) {
if (logRecord.getLevel().equals(Level.WARNING)
&& logRecord.getMessage().contains(expectedLogMessage)) {
count += 1;
}
}
return count == 1;
}
});
}
/**
* A reimplementation of hamcrest's isA() but without the broken generics.
*/
@Factory
public static Matcher<Object> isA(final Class<?> type) {
return new BaseMatcher<Object>() {
public boolean matches(Object item) {
return type.isInstance(item);
}
public void describeTo(Description description) {
description.appendText("instanceof ").appendValue(type);
}
};
}
@Override
public void describeMismatchSafely(LogRecord item, Description description) {
description
.appendText("was log with message \"")
.appendText(item.getMessage())
.appendText("\" at severity ")
.appendValue(item.getLevel());
}
@Override
public void describeTo(Description description) {
description.appendText("In(binding=\"");
bindingMatcher.describeTo(description);
description.appendText("\"; ");
super.describeTo(description);
description.appendText(")");
}
@Override
protected boolean matchesSafely(JsonNode jsonNode, Description description) {
// check mapping treatments
final JsonNode jsonTreatments = jsonNode.get(TREATMENTS);
if (mappingValue.treatments().size() != jsonTreatments.size()) {
description.appendText("mapping treatments array size of " +
Integer.toString(mappingValue.treatments().size()));
return false;
}
for (final MappingTreatment treatment : mappingValue.treatments()) {
boolean treatmentFound = false;
for (int treatmentIdx = 0; treatmentIdx < jsonTreatments.size();
treatmentIdx++) {
final String jsonAddress =
jsonTreatments.get(treatmentIdx).get(ADDRESS)
.get(MappingAddressCodec.IPV4).textValue();
final String address = treatment.address().toString();
if (address.contains(jsonAddress)) {
treatmentFound = true;
}
}
if (!treatmentFound) {
description.appendText("mapping treatment " + treatment.toString());
return false;
}
}
// check mapping action
final JsonNode jsonActionNode = jsonNode.get(MappingValueCodec.ACTION);
assertThat(jsonActionNode, MappingActionJsonMatcher.matchesAction(mappingValue.action()));
return true;
}