org.hamcrest.Matcher Java Examples
The following examples show how to use
org.hamcrest.Matcher.
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 check out the related API usage on the sidebar.
Example #1
Source File: InMemoryBounceProxyDirectoryTest.java From joynr with Apache License 2.0 | 6 votes |
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 #2
Source File: EventCollector.java From hamcrest-junit with Eclipse Public License 1.0 | 6 votes |
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 #3
Source File: EqualsVariableMap.java From camunda-bpm-platform with Apache License 2.0 | 6 votes |
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 #4
Source File: AdditionalMatchers.java From ConfigJSR with Apache License 2.0 | 6 votes |
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 #5
Source File: CoGroupTest.java From beam with Apache License 2.0 | 6 votes |
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 #6
Source File: TabLayoutActions.java From material-components-android with Apache License 2.0 | 6 votes |
/** * 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 #7
Source File: NextMatchers.java From mobius with Apache License 2.0 | 6 votes |
/** * 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 File: AdapterContainerTest.java From sahagin-java with Apache License 2.0 | 6 votes |
@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 #9
Source File: InstallableUnitTest.java From packagedrone with Eclipse Public License 1.0 | 6 votes |
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 #10
Source File: TestUtilsActions.java From material-components-android with Apache License 2.0 | 6 votes |
/** 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 #11
Source File: AccessibilityCheckResultBaseUtils.java From Accessibility-Test-Framework-for-Android with Apache License 2.0 | 6 votes |
/** * 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 #12
Source File: MainActivityTest.java From otp-authenticator with MIT License | 6 votes |
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 #13
Source File: HeaderResultMatchers.java From spring4-understanding with Apache License 2.0 | 5 votes |
/** * 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 #14
Source File: TypeSerializerUpgradeTestBase.java From flink with Apache License 2.0 | 5 votes |
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 #15
Source File: OptionalMatchers.java From java-8-matchers with MIT License | 5 votes |
/** * 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 #16
Source File: DataInteraction.java From android-test with Apache License 2.0 | 5 votes |
/** 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
Source File: TestDatabaseMetaDataProvider.java From morf with Apache License 2.0 | 5 votes |
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 #18
Source File: Matchers.java From calcite with Apache License 2.0 | 5 votes |
/** * 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 #19
Source File: TestUtilsMatchers.java From material-components-android with Apache License 2.0 | 5 votes |
/** * 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 #20
Source File: FulltextIndexTest.java From ongdb-lab-apoc with Apache License 2.0 | 5 votes |
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 #21
Source File: InformationSchemaTest.java From crate with Apache License 2.0 | 5 votes |
@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 #22
Source File: FulltextIndexTest.java From ongdb-lab-apoc with Apache License 2.0 | 5 votes |
@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
Source File: FixStreamMessageParserPermutationsTest.java From nanofix with Apache License 2.0 | 5 votes |
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 #24
Source File: CookieResultMatchers.java From spring-analysis-note with MIT License | 5 votes |
/** * 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 #25
Source File: FudgingInvocationScopedEventSinkTest.java From ehcache3 with Apache License 2.0 | 5 votes |
@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 #26
Source File: DiscountValidator.java From px-android with MIT License | 5 votes |
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 #27
Source File: RecyclerViewActions.java From android-test with Apache License 2.0 | 4 votes |
@SuppressWarnings("unchecked") @Override public Matcher<View> getConstraints() { return allOf(isAssignableFrom(RecyclerView.class), isDisplayed()); }
Example #28
Source File: MinionActionManagerTest.java From uyuni with GNU General Public License v2.0 | 4 votes |
/** * Test package install with staging when inside the staging window * @throws Exception when Taskomatic service is down */ public void testPackageInstallWithStagingInsideWindow() throws Exception { user.addPermanentRole(RoleFactory.ORG_ADMIN); UserFactory.save(user); MinionServer minion1 = MinionServerFactoryTest.createTestMinionServer(user); minion1.setOrg(user.getOrg()); Package pkg = PackageTest.createTestPackage(user.getOrg()); List packageIds = new LinkedList(); packageIds.add(pkg.getId().intValue()); user.getOrg().getOrgConfig().setStagingContentEnabled(true); Config.get().setString(SALT_CONTENT_STAGING_WINDOW, "48"); Config.get().setString(SALT_CONTENT_STAGING_ADVANCE, "48"); ZonedDateTime now = ZonedDateTime.now(ZoneId.systemDefault()); ZonedDateTime scheduledActionTime = now.plusHours(24); TaskomaticApi taskomaticMock = mock(TaskomaticApi.class); ActionManager.setTaskomaticApi(taskomaticMock); MinionActionManager.setTaskomaticApi(taskomaticMock); SystemHandler handler = new SystemHandler(taskomaticMock, xmlRpcSystemHelper, systemEntitlementManager, systemManager); context().checking(new Expectations() { { Matcher<Map<Long, ZonedDateTime>> minionMatcher = AllOf.allOf(IsMapContaining.hasKey(minion1.getId())); Matcher<Map<Long, Map<Long, ZonedDateTime>>> actionsMatcher = AllOf.allOf(IsMapContaining.hasEntry(any(Long.class), minionMatcher)); exactly(1).of(taskomaticMock) .scheduleActionExecution(with(any(Action.class))); exactly(1).of(taskomaticMock).scheduleStagingJobs(with(actionsMatcher)); } }); DataResult dr = ActionManager.recentlyScheduledActions(user, null, 30); int preScheduleSize = dr.size(); handler.schedulePackageInstall(user, minion1.getId().intValue(), packageIds, Date.from(scheduledActionTime.toInstant())); dr = ActionManager.recentlyScheduledActions(user, null, 30); assertEquals(1, dr.size() - preScheduleSize); assertEquals("Package Install", ((ScheduledAction)dr.get(0)).getTypeName()); }
Example #29
Source File: VerificationResultMatchersImpl.java From batfish with Apache License 2.0 | 4 votes |
public HasPacketModel(Matcher<? super SortedMap<String, String>> subMatcher) { super(subMatcher, "A VerificationResult with packetModel: ", "packetModel"); }
Example #30
Source File: GarmadonSparkStorageStatusListenerIntegrationTest.java From garmadon with Apache License 2.0 | 4 votes |
private void checkExecutorBroadcastStorage(String name, Matcher<Long> offHeapMatcher, Matcher<Long> memoryMatcher, Matcher<Long> diskMatcher) { ExecutorInfo info = executors.get(name); assertThat("broadcast offheap storage has unexpected value", info.broadcastOffHeap, offHeapMatcher); assertThat("broadcast memory storage has unexpected value", info.broadcastMemory, memoryMatcher); assertThat("broadcast disk storage has unexpected value", info.broadcastDisk, diskMatcher); }