static ViewAction clickNoConstraints() { return new ViewAction() { @Override public Matcher<View> getConstraints() { return isEnabled(); // No constraints, isEnabled and isClickable are checked } @Override public String getDescription() { return "Click a view with no constraints."; } @Override public void perform(UiController uiController, View view) { view.performClick(); } }; }
@Test public void testInvokingAddConsumerCreatesAValidJsonArray() { _jsonObjectBuilder.field( "array" ).arrayValue( ).add( jsonObjectBuilder -> jsonObjectBuilder.field( "solution" ).numberValue( 42 ) ); @SuppressWarnings("unchecked") Matcher<JsonElement> isAJsonArrayWithElements = is( aJsonArrayThat(contains(_aJsonObjectWithTheSolution))); Matcher<JsonElement> isAJsonObjectWithAnArray = is( aJsonObjectWhere("array", isAJsonArrayWithElements)); assertThat(getJsonObject(), isAJsonObjectWithAnArray); }
private static Matcher<View> withIndex(final Matcher<View> matcher, final int index) { return new TypeSafeMatcher<View>() { int currentIndex = 0; @Override public void describeTo(Description description) { description.appendText("with index: "); description.appendValue(index); matcher.describeTo(description); } @Override public boolean matchesSafely(View view) { return matcher.matches(view) && currentIndex++ == index; } }; }
private static ViewAction showControls() { return new ViewAction() { @Override public Matcher<View> getConstraints() { return isAssignableFrom(MovieView.class); } @Override public String getDescription() { return "Show controls of MovieView"; } @Override public void perform(UiController uiController, View view) { uiController.loopMainThreadUntilIdle(); ((MovieView) view).showControls(); uiController.loopMainThreadUntilIdle(); } }; }
public static Matcher<? super HttpResponse> hasContent(final String content, final String charset) { return new BaseMatcher<HttpResponse>() { public boolean matches(Object o) { try { HttpResponse response = (HttpResponse) o; Reader reader = new InputStreamReader(response.getEntity().getContent(), charset); int intValueOfChar; String targetString = ""; while ((intValueOfChar = reader.read()) != -1) { targetString += (char) intValueOfChar; } reader.close(); return targetString.equals(content); } catch (IOException e) { e.printStackTrace(); return false; } } public void describeTo(Description description) { description.appendText(content); } }; }
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)); } }; }
/** * A customized {@link Matcher} for testing that * if one color match the background color of current view. * @param backgroundColor A color int value. * * @return Match or not. */ public static Matcher<View> withBackgroundColor(final int backgroundColor) { return new TypeSafeMatcher<View>() { @Override public boolean matchesSafely(View view) { int color = ((ColorDrawable) view.getBackground().getCurrent()).getColor(); return color == backgroundColor; } @Override public void describeTo(Description description) { description.appendText("with background color value: " + backgroundColor); } }; }
/** * Test if the manual input activity opens. */ @Test public void testGoToManual() { onView(withId(R.id.manual_input_button)).check(matches(allOf( isEnabled(), isClickable()))).perform( new ViewAction() { @Override public Matcher<View> getConstraints() { return isEnabled(); // no constraints, they are checked above } @Override public String getDescription() { return "click manual input button"; } @Override public void perform(UiController uiController, View view) { view.performClick(); } } ); intended(hasComponent(ManualInputActivity.class.getName())); }
public static Matcher<View> hasBackgroundSpanOn(final String text, @ColorRes final int colorResource) { return new CustomTypeSafeMatcher<View>("") { @Override protected boolean matchesSafely(View view) { if (view == null || !(view instanceof TextView)) return false; SpannableString spannableString = (SpannableString) ((TextView) view).getText(); BackgroundColorSpan[] spans = spannableString.getSpans(0, spannableString.length(), BackgroundColorSpan.class); for (BackgroundColorSpan span : spans) { int start = spannableString.getSpanStart(span); int end = spannableString.getSpanEnd(span); CharSequence highlightedString = spannableString.subSequence(start, end); if (text.equals(highlightedString.toString())) { return span.getBackgroundColor() == view.getContext().getResources().getColor(colorResource); } } return false; } }; }
public static Matcher<String> withinSecondsAfter(Seconds seconds, DateTime after) { return new TypeSafeMatcher<String>() { @Override public void describeTo(Description description) { description.appendText(String.format( "a date time within %s seconds after %s", seconds.getSeconds(), after.toString())); } @Override protected boolean matchesSafely(String textRepresentation) { //response representation might vary from request representation DateTime actual = DateTime.parse(textRepresentation); return actual.isAfter(after) && Seconds.secondsBetween(after, actual).isLessThan(seconds); } }; }
public 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)); } }; }
private static Matcher<UsedJourneys> used(Journey journey) { return new TypeSafeMatcher<UsedJourneys>() { @Override public void describeTo(Description description) { description.appendText("used"); description.appendValue(journey); } @Override protected boolean matchesSafely(UsedJourneys journeys) { return journeys.used(journey); } @Override protected void describeMismatchSafely(UsedJourneys item, Description mismatchDescription) { mismatchDescription.appendText("not used"); mismatchDescription.appendValue(journey); } }; }
public static Matcher<View> atPosition(final int position, final Matcher<View> itemMatcher) { return new BoundedMatcher<View, RecyclerView>(RecyclerView.class) { @Override public void describeTo(Description description) { description.appendText("has item at position " + position + ": "); itemMatcher.describeTo(description); } @Override protected boolean matchesSafely(final RecyclerView view) { RecyclerView.ViewHolder viewHolder = view.findViewHolderForAdapterPosition(position); if (viewHolder == null) { return false; } return itemMatcher.matches(viewHolder.itemView); } }; }
public static Matcher<List<AuditLogEntry>> isSameAs( final List<AuditLog> auditLogs) { return new BaseMatcher<List<AuditLogEntry>>() { private int errorPosition; @Override public boolean matches(Object object) { List<AuditLogEntry> auditLogEntries = (List<AuditLogEntry>) object; assertEquals(auditLogEntries.size(), auditLogs.size()); for (int i = 0; i < auditLogEntries.size(); i++) { errorPosition = i; compareAuditLogEntry(auditLogEntries.get(i), auditLogs.get(i)); } return true; } @Override public void describeTo(Description description) { description .appendText("AuditLogEntry is not equal with AuditLog at position " + errorPosition); } }; }
@Order(5) @Test public void view_withCondition_thenAnd_thenNot_doesNotImplementMatcher_implementsMatching() { final Negated.Unfinished.And.Matcher matcher = Cortado.view().withText("test").and().not(); assertThat(matcher).isNotInstanceOf(org.hamcrest.Matcher.class); assertThat(matcher).isInstanceOf(Matching.class); }
private static <K, V> Map<K, Matcher<? super V>> toExpectationMap(Map<? extends K, ? extends V> values) { Map<K, Matcher<? super V>> expectedContents = new HashMap<>(); for (Map.Entry<? extends K, ? extends V> entry : values.entrySet()) { expectedContents.put(entry.getKey(), Matchers.equalTo(entry.getValue())); } return expectedContents; }
public static ViewAction waitForMatch(final Matcher<View> aViewMatcher, final long timeout) { return new ViewAction() { @Override public Matcher<View> getConstraints() { return isRoot(); } @Override public String getDescription() { return "Waiting for view matching " + aViewMatcher; } @Override public void perform(UiController uiController, View view) { uiController.loopMainThreadUntilIdle(); final long startTime = System.currentTimeMillis(); final long endTime = startTime + timeout; do { for (View child : TreeIterables.breadthFirstViewTraversal(view)) { if (aViewMatcher.matches(child)) { // found return; } } uiController.loopMainThreadForAtLeast(50); } while (System.currentTimeMillis() < endTime); //The action has timed out. throw new PerformException.Builder() .withActionDescription(getDescription()) .withViewDescription("") .withCause(new TimeoutException()) .build(); } }; }
@Test public void onTextView_returnsProperViewInteraction() { //given final Cortado.OrAnd.ViewInteraction viewInteraction = Cortado.onTextView().withText("test"); final Matcher<View> expectedEspressoMatcher = Matchers.allOf( ViewMatchers.isAssignableFrom(TextView.class), viewInteraction.getCortado().matchers.get(0)); //when final Matcher<View> rawMatcher = viewInteraction.getCortado().get(); //then Utils.assertThat(rawMatcher).isEqualTo(expectedEspressoMatcher); }
private Matcher<? super HttpCallRecord> hasDate(final Calendar date) { return new CustomTypeSafeMatcher<HttpCallRecord>("has date: " + date) { @Override protected boolean matchesSafely(HttpCallRecord item) { Calendar actualCalendar = Calendar.getInstance(); actualCalendar.setTime(item.getDate()); assertThat(actualCalendar.get(DATE), is(date.get(DATE))); assertThat(actualCalendar.get(DAY_OF_MONTH), is(date.get(DAY_OF_MONTH))); assertThat(actualCalendar.get(YEAR), is(date.get(YEAR))); return true; } }; }
@Factory public static Matcher<String> containsLine(final Matcher<? super String> matcher) { return new BaseMatcher<String>() { public boolean matches(Object o) { String str = (String) o; return containsLine(str, matcher); } public void describeTo(Description description) { description.appendText("a String that contains line that is ").appendDescriptionOf(matcher); } }; }
public static boolean containsLine(String actual, Matcher<? super String> matcher) { BufferedReader reader = new BufferedReader(new StringReader(actual)); String line; try { while ((line = reader.readLine()) != null) { if (matcher.matches(line)) { return true; } } } catch (IOException e) { throw new RuntimeException(e); } return false; }
/** * Returns a matcher that checks if a {@code JsonElement} is a valid JSON * object containing an element. * * @return the matcher that checks if a {@code JsonElement} is a valid JSON * object containing an element */ public static Matcher<JsonElement> aJsonObjectWhere( String key, Matcher<? extends JsonElement> matcher) { Conditions.Builder builder = new Conditions.Builder(); Conditions conditions = builder.where( key, matcher ).build(); return aJsonObjectWith(conditions); }
static private Matcher<OffsetDateTime> after(final OffsetDateTime border) { return new TypeSafeMatcher<OffsetDateTime>() { @Override public void describeTo(Description description) { description.appendText("Timestamp after " + border); } @Override protected boolean matchesSafely(OffsetDateTime item) { return item.isAfter(border); } }; }
private static Matcher<? super Integer> hasFlag(final int flag) { return new TypeSafeMatcher<Integer>() { @Override protected boolean matchesSafely(Integer i) { return (i & flag) == flag; } @Override public void describeTo(Description description) { description.appendText("Flag integer contains " + flag); } }; }
public Matcher<View> atPositionOnView(final int position, final int targetViewId) { return new TypeSafeMatcher<View>() { Resources resources = null; View childView; public void describeTo(Description description) { String idDescription = Integer.toString(recyclerViewId); if (this.resources != null) { try { idDescription = this.resources.getResourceName(recyclerViewId); } catch (Resources.NotFoundException var4) { idDescription = String.format("%s (resource name not found)", recyclerViewId); } } description.appendText("RecyclerView with id: " + idDescription + " at position: " + position); } public boolean matchesSafely(View view) { this.resources = view.getResources(); if (childView == null) { RecyclerView recyclerView = (RecyclerView) view.getRootView().findViewById(recyclerViewId); if (recyclerView != null && recyclerView.getId() == recyclerViewId) { RecyclerView.ViewHolder viewHolder = recyclerView.findViewHolderForAdapterPosition(position); if (viewHolder != null) { childView = viewHolder.itemView; } } else { return false; } } if (targetViewId == -1) { return view == childView; } else { View targetView = childView.findViewById(targetViewId); return view == targetView; } } }; }
public static Matcher<FieldSpec> initializer(Matcher<String> match) { return new FeatureMatcher<FieldSpec, String>(match, "field initializer", "field initializer") { @Override protected String featureValueOf(FieldSpec actual) { return actual.initializer.toString(); } }; }
public static Matcher<List<WebElement>> sorted(final Comparator<String> comparator) { return new TypeSafeMatcher<List<WebElement>>() { @Override protected boolean matchesSafely(final List<WebElement> webElements) { return isWebElementsSortedByText(webElements, comparator); } @Override public void describeTo(Description description) { } }; }
/** * Returns a {@link Matcher} that checks if the field is a JSON Object of * the second embedded. * * @return a matcher for a JSON Object of the second embedded * @review */ public static Matcher<JsonElement> isAJsonObjectWithTheSecondEmbedded() { Conditions.Builder builder = new Conditions.Builder(); Conditions secondEmbeddedContextConditions = builder.where( "embedded", IS_A_TYPE_ID_JSON_OBJECT ).where( "linked", IS_A_TYPE_ID_JSON_OBJECT ).where( "relatedCollection", IS_A_TYPE_ID_JSON_OBJECT ).build(); Conditions secondEmbeddedConditions = builder.where( "@context", is(aJsonObjectWith(secondEmbeddedContextConditions)) ).where( "@id", isALinkTo("localhost/p/second-inner-model/first") ).where( "@type", containsTheTypes("Type") ).where( "binary", isALinkTo("localhost/b/second-inner-model/first/binary") ).where( "boolean", is(aJsonBoolean(false)) ).where( "embedded", isALinkTo("localhost/p/third-inner-model/first") ).where( "link", isALinkTo("community.liferay.com") ).where( "linked", isALinkTo("localhost/p/third-inner-model/second") ).where( "number", is(aJsonInt(equalTo(2017))) ).where( "relatedCollection", isALinkTo("localhost/p/second-inner-model/first/models") ).where( "string", is(aJsonString(equalTo("A string"))) ).build(); return is(aJsonObjectWith(secondEmbeddedConditions)); }
private Matcher<NodeParameters> isNodeParamsFromTxnId(final Long fromTxnId) { return new BaseMatcher<NodeParameters>() { @Override public void describeTo(Description description) { description.appendText(NodeParameters.class.getSimpleName()+"[fromTxId="+fromTxnId+"]"); } @Override public boolean matches(Object item) { if (!(item instanceof NodeParameters)) { return false; } NodeParameters np = (NodeParameters) item; if (fromTxnId == null) { return np.getFromTxnId() == null; } else { return fromTxnId.equals(np.getFromTxnId()); } } }; }
@NonNull public static Matcher<RecyclerView.ViewHolder> withConnectedHost() { return new BoundedMatcher<RecyclerView.ViewHolder, HostListActivity.HostViewHolder>(HostListActivity.HostViewHolder.class) { @Override public boolean matchesSafely(HostListActivity.HostViewHolder holder) { return hasDrawableState(holder.icon, android.R.attr.state_checked); } @Override public void describeTo(Description description) { description.appendText("is connected status"); } }; }
public static Matcher<Class<?>> containsInterceptor(final Class<?> beanClass) { return new BaseMatcher<Class<?>>() { private Class<?> testClass; @Override public boolean matches(Object object) { testClass = (Class<?>) object; Interceptors interceptors = testClass .getAnnotation(Interceptors.class); boolean interceptorSet = false; if (interceptors != null) { for (Class<?> definedInterceptorClass : interceptors .value()) { if (definedInterceptorClass == beanClass) { interceptorSet = true; } } } assertTrue(interceptorSet); return true; } @Override public void describeTo(Description description) { description.appendText("Class " + testClass.getName() + " has no interceptor " + beanClass.getName()); } }; }
static Matcher<Api.Version> isAtLeast(final Api.Version lowerBound) { return new TypeSafeMatcher<Api.Version>() { @Override protected boolean matchesSafely(final Api.Version item) { return item.ordinal() >= lowerBound.ordinal(); } @Override public void describeTo(final Description description) { description.appendText("Version is at least"); description.appendValue(lowerBound); } }; }
private Matcher<Long> greaterThan(final long value) { return new BaseMatcher<Long>() { @Override public void describeTo(Description description) { description.appendText("> " + value); } @Override public boolean matches(Object o) { return ((Long)o) > value; } }; }
/** * Returns a {@link Matcher} that checks if the field is the JSON Object * containing the links of a {@code RootElement} with the provided ID. * * @param id the ID of the {@code RootElement} * @return a matcher for a JSON Object with the links of a {@code * RootElement} with the provided ID * @review */ public static Matcher<JsonElement> isAJsonObjectWithTheLinks(String id) { Conditions.Builder builder = new Conditions.Builder(); Conditions linkConditions = builder.where( "binary1", isALinkTo("localhost/b/model/" + id + "/binary1") ).where( "binary2", isALinkTo("localhost/b/model/" + id + "/binary2") ).where( "embedded2", isALinkTo("localhost/p/first-inner-model/second") ).where( "link1", isALinkTo("www.liferay.com") ).where( "link2", isALinkTo("community.liferay.com") ).where( "linked1", isALinkTo("localhost/p/first-inner-model/third") ).where( "linked2", isALinkTo("localhost/p/first-inner-model/fourth") ).where( "relatedCollection1", isALinkTo("localhost/p/model/" + id + "/models") ).where( "relatedCollection2", isALinkTo("localhost/p/model/" + id + "/models") ).where( "self", isALinkTo("localhost/p/model/" + id) ).build(); return is(aJsonObjectWith(linkConditions)); }
@Test public void view_withCondition_hasProperNegatedFlag() { //given //when Cortado.OrAnd.Matcher matcher = Cortado.view().withText("test"); //then assertThat(matcher.getCortado().negateNextMatcher).isFalse(); }
@Test public void testInvokingBooleanValueCreatesABoolean() { _jsonObjectBuilder.field( "solution" ).booleanValue( true ); Matcher<JsonElement> isAJsonObjectWithTheSolution = is( aJsonObjectWhere("solution", is(aJsonBoolean(true)))); assertThat(getJsonObject(), isAJsonObjectWithTheSolution); }
@Order(3) @Test public void view_withSingleCondition_implementsMatcher_doesNotImplementMatching() { final Cortado.OrAnd.Matcher matcher = Cortado.view().withText("test"); assertThat(matcher).isInstanceOf(org.hamcrest.Matcher.class); assertThat(matcher).isNotInstanceOf(Matching.class); }
@Test public void onButton_returnsProperViewInteraction() { //given final Cortado.OrAnd.ViewInteraction viewInteraction = Cortado.onButton().withText("test"); final Matcher<View> expectedEspressoMatcher = Matchers.allOf( ViewMatchers.isAssignableFrom(Button.class), viewInteraction.getCortado().matchers.get(0)); //when final Matcher<View> rawMatcher = viewInteraction.getCortado().get(); //then Utils.assertThat(rawMatcher).isEqualTo(expectedEspressoMatcher); }