下面列出了java.io.StringBufferInputStream#org.hamcrest.Matcher 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
protected boolean matchesMatchers(Object argument) {
if (argument == null) {
return false;
}
VariableMap argumentMap = (VariableMap) argument;
boolean containSameKeys = matchers.keySet().containsAll(argumentMap.keySet()) &&
argumentMap.keySet().containsAll(matchers.keySet());
if (!containSameKeys) {
return false;
}
for (String key : argumentMap.keySet()) {
Matcher<?> matcher = matchers.get(key);
if (!matcher.matches(argumentMap.getValueTyped(key))) {
return false;
}
}
return true;
}
static private final <K, V> Matcher<Map<K, V>> hasEntry ( final K key, final Matcher<V> valueMatcher )
{
return new CustomTypeSafeMatcher<Map<K, V>> ( "Map with entry: key=" + key + ", value=" + valueMatcher ) {
@Override
protected boolean matchesSafely ( final Map<K, V> item )
{
final Object actualValue = item.get ( key );
if ( valueMatcher.matches ( actualValue ) )
{
return true;
}
return false;
}
};
}
public static Matcher<View> withResourceName(final Matcher<String> resourceNameMatcher) {
return new TypeSafeMatcher<View>() {
@Override
public void describeTo(Description description) {
description.appendText("with resource name: ");
resourceNameMatcher.describeTo(description);
}
@Override
public boolean matchesSafely(View view) {
int id = view.getId();
return id != View.NO_ID && id != 0 && view.getResources() != null
&& resourceNameMatcher.matches(view.getResources().getResourceName(id));
}
};
}
/**
* Returns a {@link Matcher} for an {@link AccessibilityCheckResult} whose source check class has
* a simple name that matches the given matcher for a {@code String}. If a BiMap of class aliases
* is provided, it can also match a class paired with the source check class in the BiMap.
*
* @param classNameMatcher a {@code Matcher} for a {@code String}
* @return a {@code Matcher} for an {@code AccessibilityCheckResult}
*/
static Matcher<AccessibilityCheckResult> matchesCheckNames(
final Matcher<? super String> classNameMatcher,
final @Nullable ImmutableBiMap<?, ?> aliases) {
return new TypeSafeMemberMatcher<AccessibilityCheckResult>(
"source check name", classNameMatcher) {
@Override
public boolean matchesSafely(AccessibilityCheckResult result) {
Class<? extends AccessibilityCheck> checkClass = result.getSourceCheckClass();
if (classNameMatcher.matches(checkClass.getSimpleName())) {
return true;
}
Object alias = getAlias(checkClass, aliases);
return (alias instanceof Class)
&& classNameMatcher.matches(((Class<?>) alias).getSimpleName());
}
};
}
/** Adds tabs to {@link TabLayout} */
public static ViewAction addTabs(final String... tabs) {
return new ViewAction() {
@Override
public Matcher<View> getConstraints() {
return isAssignableFrom(TabLayout.class);
}
@Override
public String getDescription() {
return "TabLayout add tabs";
}
@Override
public void perform(UiController uiController, View view) {
uiController.loopMainThreadUntilIdle();
TabLayout tabLayout = (TabLayout) view;
for (int i = 0; i < tabs.length; i++) {
tabLayout.addTab(tabLayout.newTab().setText(tabs[i]));
}
uiController.loopMainThreadUntilIdle();
}
};
}
private static Void containsJoinedFields(List<Row> expected, Iterable<Row> actual) {
List<Matcher<? super Row>> matchers = Lists.newArrayList();
for (Row row : expected) {
List<Matcher> fieldMatchers = Lists.newArrayList();
Schema schema = row.getSchema();
fieldMatchers.add(
new RowFieldMatcherIterableFieldAnyOrder(row.getSchema(), 0, row.getRow(0)));
for (int i = 1; i < schema.getFieldCount(); ++i) {
assertEquals(TypeName.ITERABLE, schema.getField(i).getType().getTypeName());
fieldMatchers.add(
new RowFieldMatcherIterableFieldAnyOrder(row.getSchema(), i, row.getIterable(i)));
}
matchers.add(allOf(fieldMatchers.toArray(new Matcher[0])));
}
assertThat(actual, containsInAnyOrder(matchers.toArray(new Matcher[0])));
return null;
}
/**
* Returns a matcher that matches {@link Next} instances whose effects match the supplied effect
* matcher.
*
* @param matcher the matcher to apply to the effects
* @param <M> the model type
* @param <F> the effect type
*/
public static <M, F> Matcher<Next<M, F>> hasEffects(Matcher<Iterable<F>> matcher) {
return new TypeSafeDiagnosingMatcher<Next<M, F>>() {
@Override
protected boolean matchesSafely(Next<M, F> item, Description mismatchDescription) {
if (!item.hasEffects()) {
mismatchDescription.appendText("it had no effects");
return false;
} else if (!matcher.matches(item.effects())) {
mismatchDescription.appendText("the effects were ");
matcher.describeMismatch(item.effects(), mismatchDescription);
return false;
}
return true;
}
@Override
public void describeTo(Description description) {
description.appendText("Next with effects ").appendDescriptionOf(matcher);
}
};
}
static Matcher<EventCollector> failureIs(final Matcher<? super Throwable> exceptionMatcher) {
return new TypeSafeMatcher<EventCollector>() {
@Override
public boolean matchesSafely(EventCollector item) {
for (Failure f : item.fFailures) {
return exceptionMatcher.matches(f.getException());
}
return false;
}
public void describeTo(org.hamcrest.Description description) {
description.appendText("failure is ");
exceptionMatcher.describeTo(description);
}
};
}
private Matcher<BounceProxyRecord> hasId(final String bpId) {
return new BaseMatcher<BounceProxyRecord>() {
@Override
public boolean matches(Object item) {
BounceProxyRecord record = (BounceProxyRecord) item;
return record.getInfo().getId().equals(bpId);
}
@Override
public void describeTo(Description description) {
description.appendText("has BounceProxy ID '" + bpId + "'");
}
};
}
/**
* Calls <code>setScrollPosition(position, positionOffset, true)</code> on the <code>TabLayout
* </code>
*/
public static ViewAction setScrollPosition(final int position, final float positionOffset) {
return new ViewAction() {
@Override
public Matcher<View> getConstraints() {
return ViewMatchers.isAssignableFrom(TabLayout.class);
}
@Override
public String getDescription() {
return "setScrollPosition(" + position + ", " + positionOffset + ", true)";
}
@Override
public void perform(UiController uiController, View view) {
TabLayout tabs = (TabLayout) view;
tabs.setScrollPosition(position, positionOffset, true);
uiController.loopMainThreadUntilIdle();
}
};
}
@Test
public void testDocSetUpByEnUs() {
AcceptableLocales locales = AcceptableLocales.getInstance(Locale.EN_US);
JavaAdapterContainer.globalInitialize(locales, new JUnit4Adapter().getName());
new JUnit4Adapter().initialSetAdapter();
new WebDriverAdapter().initialSetAdapter();
AdditionalTestDocs testDocs
= AdapterContainer.globalInstance().getAdditionalTestDocs();
AdditionalMethodTestDoc clickTestDoc
= testDocs.getMethodTestDoc("org.openqa.selenium.WebElement", "click", new ArrayList<String>(0));
assertThat(clickTestDoc.getTestDoc(), is("click {this}"));
AdditionalMethodTestDoc isTestDoc1
= testDocs.getMethodTestDoc("org.hamcrest.CoreMatchers", "is",
Arrays.asList(Object.class.getSimpleName()));
assertThat(isTestDoc1.getCaptureStyle(), is(CaptureStyle.NONE));
assertThat(isTestDoc1.getTestDoc(), is("equals to '{0}'"));
AdditionalMethodTestDoc isTestDoc2
= testDocs.getMethodTestDoc("org.hamcrest.CoreMatchers", "is",
Arrays.asList(Matcher.class.getCanonicalName()));
assertThat(isTestDoc2.getCaptureStyle(), is(CaptureStyle.NONE));
assertThat(isTestDoc2.getTestDoc(), is("{0}"));
}
public static Matcher<Float> floatCloseTo(float value, float range) {
return new BaseMatcher<Float>() {
private Matcher<Double> doubleMatcher = null;
@Override
public boolean matches(Object item) {
if (item instanceof Float) {
return (doubleMatcher = closeTo(value, range)).matches(((Float)item).doubleValue());
}
else {
return (doubleMatcher = closeTo(value, range)).matches(item);
}
}
@Override
public void describeTo(Description description) {
doubleMatcher.describeTo(description);
}
};
}
private static Matcher<? super PropertyContainer> hasProperty(String key, Object value) {
return new TypeSafeDiagnosingMatcher<PropertyContainer>() {
@Override
protected boolean matchesSafely(PropertyContainer item, Description mismatchDescription) {
Object property;
try (Transaction tx = item.getGraphDatabase().beginTx()) {
property = item.getProperty(key, null);
tx.success();
}
if (property == null) {
mismatchDescription.appendText("property ").appendValue(key).appendText(" not present");
return false;
}
if (value instanceof Matcher<?>) {
Matcher<?> matcher = (Matcher<?>) value;
if (!matcher.matches(property)) {
matcher.describeMismatch(property, mismatchDescription);
return false;
}
return true;
}
if (!property.equals(value)) {
mismatchDescription.appendText("property ").appendValue(key).appendText("has value").appendValue(property);
return false;
}
return true;
}
@Override
public void describeTo(Description description) {
description.appendText("entity with property ").appendValue(key).appendText("=").appendValue(value);
}
};
}
/**
* Returns a matcher that matches TextViews whose start drawable is filled with the specified fill
* color.
*/
public static Matcher<View> withStartDrawableFilledWith(
final @ColorInt int fillColor, final int allowedComponentVariance) {
return new BoundedMatcher<View, TextView>(TextView.class) {
private String failedCheckDescription;
@Override
public void describeTo(final Description description) {
description.appendText(failedCheckDescription);
}
@Override
public boolean matchesSafely(final TextView view) {
final Drawable[] compoundDrawables = view.getCompoundDrawables();
final boolean isRtl =
(ViewCompat.getLayoutDirection(view) == ViewCompat.LAYOUT_DIRECTION_RTL);
final Drawable startDrawable = isRtl ? compoundDrawables[2] : compoundDrawables[0];
if (startDrawable == null) {
failedCheckDescription = "no start drawable";
return false;
}
try {
final Rect bounds = startDrawable.getBounds();
TestUtils.assertAllPixelsOfColor(
"",
startDrawable,
bounds.width(),
bounds.height(),
true,
fillColor,
allowedComponentVariance,
true);
} catch (Throwable t) {
failedCheckDescription = t.getMessage();
return false;
}
return true;
}
};
}
private static Matcher<String> indexNameEqualTo(String indexName) {
switch (databaseType) {
case "H2":
return equalTo(indexName.toUpperCase());
case "ORACLE":
return either(equalTo(indexName)).or(equalTo(indexName.toUpperCase()));
default:
return equalTo(indexName);
}
}
/** Causes this data interaction to work within the Root specified by the given root matcher. */
@CheckResult
@CheckReturnValue
public DataInteraction inRoot(Matcher<Root> rootMatcher) {
this.rootMatcher = checkNotNull(rootMatcher);
return this;
}
/**
* Assert the primary value of the named response header with the given
* Hamcrest {@link Matcher}.
*/
public ResultMatcher string(final String name, final Matcher<? super String> matcher) {
return new ResultMatcher() {
@Override
public void match(MvcResult result) {
assertThat("Response header " + name, result.getResponse().getHeader(name), matcher);
}
};
}
@Test
public void testSelectFromKeyColumnUsage() {
execute("create table table1 (id1 integer)");
execute("create table table2 (id2 integer primary key)");
execute("create table table3 (id3 integer, name string, other double, primary key (id3, name))");
ensureYellow();
execute("select * from information_schema.key_column_usage order by table_name, ordinal_position asc");
assertEquals(3L, response.rowCount());
assertThat(response.cols(), arrayContaining(
"column_name",
"constraint_catalog",
"constraint_name",
"constraint_schema",
"ordinal_position",
"table_catalog",
"table_name",
"table_schema"
));
final String defaultSchema = sqlExecutor.getCurrentSchema();
Matcher<Object[][]> resultMatcher = arrayContaining(
new Object[]{"id2", defaultSchema, "table2_pk", defaultSchema, 1, defaultSchema, "table2", defaultSchema},
new Object[]{"id3", defaultSchema, "table3_pk", defaultSchema, 1, defaultSchema, "table3", defaultSchema},
new Object[]{"name", defaultSchema, "table3_pk", defaultSchema, 2, defaultSchema, "table3", defaultSchema}
);
assertThat(response.rows(), resultMatcher);
// check that the constraint name is the same as in table_constraints by joining the two tables
execute("select t1.* from information_schema.key_column_usage t1 " +
"join information_schema.table_constraints t2 " +
"on t1.constraint_name = t2.constraint_name " +
"order by t1.table_name, t1.ordinal_position asc");
assertThat(response.rows(), resultMatcher);
}
/**
* Assert a cookie's comment with a Hamcrest {@link Matcher}.
*/
public ResultMatcher comment(final String name, final Matcher<? super String> matcher) {
return result -> {
Cookie cookie = getCookie(result, name);
assertThat("Response cookie '" + name + "' comment", cookie.getComment(), matcher);
};
}
private static <T> DataInputView readAndThenWriteData(
DataInputView originalDataInput,
TypeSerializer<T> readSerializer,
TypeSerializer<T> writeSerializer,
Matcher<T> testDataMatcher) throws IOException {
T data = readSerializer.deserialize(originalDataInput);
assertThat(data, testDataMatcher);
DataOutputSerializer out = new DataOutputSerializer(INITIAL_OUTPUT_BUFFER_SIZE);
writeSerializer.serialize(data, out);
return new DataInputDeserializer(out.wrapAsByteBuffer());
}
private void validateDiscountRow() {
final Matcher<View> amountDescription = withId(com.mercadopago.android.px.R.id.amount_description);
final Matcher<View> maxCouponAmount = withId(com.mercadopago.android.px.R.id.max_coupon_amount);
final Matcher<View> amountBeforeDiscount =
withId(com.mercadopago.android.px.R.id.amount_before_discount);
final Matcher<View> finalAmount = withId(com.mercadopago.android.px.R.id.final_amount);
onView(amountDescription).check(matches(withEffectiveVisibility(ViewMatchers.Visibility.VISIBLE)));
onView(maxCouponAmount).check(matches(withEffectiveVisibility(ViewMatchers.Visibility.VISIBLE)));
onView(amountBeforeDiscount)
.check(matches(withEffectiveVisibility(ViewMatchers.Visibility.VISIBLE)));
onView(finalAmount).check(matches(withEffectiveVisibility(ViewMatchers.Visibility.VISIBLE)));
onView(amountDescription).check(matches(withText(getAmountDescription())));
}
@SafeVarargs
private static <T extends PropertyContainer> void assertSingle(Iterator<T> iter, Matcher<? super T>... matchers) {
try {
assertTrue("should contain at least one value", iter.hasNext());
assertThat(iter.next(), allOf(matchers));
assertFalse("should contain at most one value", iter.hasNext());
} finally {
if (iter instanceof ResourceIterator<?>) {
((ResourceIterator<?>) iter).close();
}
}
}
@Test
public void testEvictedKeyDoesNotFudgeOlderEvents() {
eventSink.updated("k1", () -> "v0", "v1");
eventSink.created("k2", "v2");
eventSink.evicted("k1", () -> "v0");
eventSink.close();
InOrder inOrder = inOrder(listener);
Matcher<StoreEvent<String, String>> updatedMatcher = eventType(EventType.UPDATED);
inOrder.verify(listener).onEvent(argThat(updatedMatcher));
inOrder.verify(listener).onEvent(argThat(createdMatcher));
inOrder.verify(listener).onEvent(argThat(evictedMatcher));
verifyNoMoreInteractions(listener);
}
private Matcher<? super List<byte[]>> containsAllItems(final List<byte[]> expectedMessages)
{
return new TypeSafeMatcher<List<byte[]>>()
{
@Override
protected boolean matchesSafely(List<byte[]> actualMessages)
{
if (actualMessages.size() != expectedMessages.size())
{
return false;
}
Iterator<byte[]> it1 = expectedMessages.iterator(), it2 = actualMessages.iterator();
for (; it1.hasNext() && it2.hasNext();)
{
byte[] expected = it1.next();
byte[] actual = it2.next();
if (!Arrays.equals(expected, actual))
{
return false;
}
}
return !it1.hasNext() && !it2.hasNext();
}
@Override
public void describeTo(Description description)
{
description.appendText("Expecting list containing ")
.appendValue(expectedMessages.size())
.appendText(" items: ")
.appendValue(expectedMessages);
}
};
}
/**
* Creates a Matcher that matches a {@link RelNode} if its hints string
* representation is equal to the given {@code value}.
*/
public static Matcher<RelNode> hasHints(final String value) {
return compose(Is.is(value),
input -> input instanceof Hintable
? ((Hintable) input).getHints().toString()
: "[]");
}
/**
* Matches an empty OptionalLong.
*/
public static Matcher<OptionalLong> emptyLong() {
return new TypeSafeMatcher<OptionalLong>() {
@Override
protected boolean matchesSafely(OptionalLong item) {
return !item.isPresent();
}
@Override
public void describeTo(Description description) {
description.appendText("An empty OptionalLong");
}
};
}
public MockServer andExpectJsonPath(String jsonPath, Matcher<Object> matcher) {
expectedJsonPaths.put(jsonPath, matcher);
return this;
}
protected AndOrPredicateMatcher(@Nonnull Matcher<Collection<QueryPredicate>> childrenMatchers) {
this.childrenMatchers = childrenMatchers;
}
public static Matcher<RecordQueryPlan> textIndexScan(@Nonnull Matcher<? super RecordQueryTextIndexPlan> planMatcher) {
return new TextIndexMatcher(planMatcher);
}
@Override
public Matcher<View> getConstraints() {
return isDisplayed();
}