Java Code Examples for org.hamcrest.Matcher

The following examples show how to use org.hamcrest.Matcher. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: camunda-bpm-platform   Source File: EqualsVariableMap.java    License: Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 2
Source Project: packagedrone   Source File: InstallableUnitTest.java    License: Eclipse Public License 1.0 6 votes vote down vote up
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;
        }
    };
}
 
Example 3
Source Project: otp-authenticator   Source File: MainActivityTest.java    License: MIT License 6 votes vote down vote up
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));
        }
    };
}
 
Example 4
/**
 * 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());
    }
  };
}
 
Example 5
/** 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();
    }
  };
}
 
Example 6
Source Project: beam   Source File: CoGroupTest.java    License: Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 7
Source Project: mobius   Source File: NextMatchers.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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);
    }
  };
}
 
Example 8
Source Project: hamcrest-junit   Source File: EventCollector.java    License: Eclipse Public License 1.0 6 votes vote down vote up
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);
        }
    };
}
 
Example 9
Source Project: joynr   Source File: InMemoryBounceProxyDirectoryTest.java    License: Apache License 2.0 6 votes vote down vote up
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 + "'");
            }

        };
    }
 
Example 10
/**
 * 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();
    }
  };
}
 
Example 11
Source Project: sahagin-java   Source File: AdapterContainerTest.java    License: Apache License 2.0 6 votes vote down vote up
@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}"));
}
 
Example 12
Source Project: ConfigJSR   Source File: AdditionalMatchers.java    License: Apache License 2.0 6 votes vote down vote up
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);
        }
    };
}
 
Example 13
Source Project: ongdb-lab-apoc   Source File: FulltextIndexTest.java    License: Apache License 2.0 5 votes vote down vote up
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);
        }
    };
}
 
Example 14
/**
 * 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;
    }
  };
}
 
Example 15
Source Project: morf   Source File: TestDatabaseMetaDataProvider.java    License: Apache License 2.0 5 votes vote down vote up
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);
  }
}
 
Example 16
Source Project: android-test   Source File: DataInteraction.java    License: Apache License 2.0 5 votes vote down vote up
/** 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;
}
 
Example 17
/**
 * 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);
		}
	};
}
 
Example 18
Source Project: crate   Source File: InformationSchemaTest.java    License: Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 19
Source Project: spring-analysis-note   Source File: CookieResultMatchers.java    License: MIT License 5 votes vote down vote up
/**
 * 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);
	};
}
 
Example 20
Source Project: flink   Source File: TypeSerializerUpgradeTestBase.java    License: Apache License 2.0 5 votes vote down vote up
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());
}
 
Example 21
Source Project: px-android   Source File: DiscountValidator.java    License: MIT License 5 votes vote down vote up
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())));
}
 
Example 22
Source Project: ongdb-lab-apoc   Source File: FulltextIndexTest.java    License: Apache License 2.0 5 votes vote down vote up
@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();
        }
    }
}
 
Example 23
@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);
}
 
Example 24
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);
        }
    };
}
 
Example 25
Source Project: calcite   Source File: Matchers.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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()
          : "[]");
}
 
Example 26
Source Project: java-8-matchers   Source File: OptionalMatchers.java    License: MIT License 5 votes vote down vote up
/**
 * 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");
        }
    };
}
 
Example 27
Source Project: fahrschein   Source File: MockServer.java    License: Apache License 2.0 4 votes vote down vote up
public MockServer andExpectJsonPath(String jsonPath, Matcher<Object> matcher) {
    expectedJsonPaths.put(jsonPath, matcher);
    return this;
}
 
Example 28
Source Project: fdb-record-layer   Source File: AndOrPredicateMatcher.java    License: Apache License 2.0 4 votes vote down vote up
protected AndOrPredicateMatcher(@Nonnull Matcher<Collection<QueryPredicate>> childrenMatchers) {
    this.childrenMatchers = childrenMatchers;
}
 
Example 29
Source Project: fdb-record-layer   Source File: PlanMatchers.java    License: Apache License 2.0 4 votes vote down vote up
public static Matcher<RecordQueryPlan> textIndexScan(@Nonnull Matcher<? super RecordQueryTextIndexPlan> planMatcher) {
    return new TextIndexMatcher(planMatcher);
}
 
Example 30
@Override
public Matcher<View> getConstraints() {
  return isDisplayed();
}