@Test public void shouldInitializeCrashView() throws Exception { SherlockDatabaseHelper database = mock(SherlockDatabaseHelper.class); Crash crash = mock(Crash.class); when(crash.getId()).thenReturn(1); AppInfo appInfo = mock(AppInfo.class); when(crash.getAppInfo()).thenReturn(appInfo); when(database.getCrashById(1)).thenReturn(crash); CrashActions actions = mock(CrashActions.class); CrashPresenter presenter = new CrashPresenter(database, actions); presenter.render(1); verify(actions).render(argThat(new CustomTypeSafeMatcher<CrashViewModel>("") { @Override protected boolean matchesSafely(CrashViewModel crashViewModel) { return crashViewModel.getIdentifier() == 1; } })); verify(actions).renderAppInfo(any(AppInfoViewModel.class)); }
public static Matcher<View> withTableLayout(final int tableLayoutId, final int row, final int column) { return new CustomTypeSafeMatcher<View>(format("Table layout with id: {0} at row: {1} and column: {2}", tableLayoutId, row, column)) { @Override protected boolean matchesSafely(View item) { View view = item.getRootView().findViewById(tableLayoutId); if (view == null || !(view instanceof TableLayout)) return false; TableLayout tableLayout = (TableLayout) view; TableRow tableRow = (TableRow) tableLayout.getChildAt(row); View childView = tableRow.getChildAt(column); return childView == item; } }; }
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; } }; }
@NonNull private CustomTypeSafeMatcher<List<HttpCallRecord>> areSortedAccordingToDate() { return new CustomTypeSafeMatcher<List<HttpCallRecord>>("are sorted") { @Override protected boolean matchesSafely(List<HttpCallRecord> list) { for (int index = 0 ; index < list.size() - 1 ; index++) { long firstRecordTime = list.get(index).getDate().getTime(); long secondRecordTime = list.get(index + 1).getDate().getTime(); if (firstRecordTime < secondRecordTime) { return false; } } return true; } }; }
@Test public void shouldReturnBoundsToHighlight() throws Exception { when(responseFormatter.format(anyString())).thenReturn("ABC0124abc"); HttpHeader httpHeader = getJsonContentTypeHeader(); when(httpCallRecord.getRequestHeader("Content-Type")).thenReturn(httpHeader); resolveBackgroundTask(); presenter.init(viewModel, REQUEST_MODE); presenter.searchInBody("abc"); verify(httpCallBodyView).removeOldHighlightedSpans(); verify(httpCallBodyView).highlightBounds(argThat(new CustomTypeSafeMatcher<List<Bound>>("") { @Override protected boolean matchesSafely(List<Bound> item) { Bound firstBound = item.get(0); assertThat(firstBound.getLeft(), is(0)); assertThat(firstBound.getRight(), is(3)); Bound secondBound = item.get(1); assertThat(secondBound.getLeft(), is(7)); assertThat(secondBound.getRight(), is(10)); return true; } })); }
private Matcher<DefaultErrorContractDTO> errorResponseViewMatches(final DefaultErrorContractDTO expectedErrorContract) { return new CustomTypeSafeMatcher<DefaultErrorContractDTO>("a matching ErrorResponseView"){ @Override protected boolean matchesSafely(DefaultErrorContractDTO item) { if (!(item.errors.size() == expectedErrorContract.errors.size())) return false; for (int i = 0; i < item.errors.size(); i++) { DefaultErrorDTO itemError = item.errors.get(i); DefaultErrorDTO expectedError = item.errors.get(i); if (!itemError.code.equals(expectedError.code)) return false; if (!itemError.message.equals(expectedError.message)) return false; } return item.error_id.equals(expectedErrorContract.error_id); } }; }
@Test public void testInjection() throws Exception { // given final int newFieldValue = 1; final String newFiledValueStr = String.valueOf(newFieldValue); final Injector injector = Guice.createInjector(new AbstractModule() { @Override protected void configure() { final ModelParameterTypeListener modelParameterTypeListener = new ModelParameterTypeListener(ImmutableMap.of("field", newFiledValueStr)); bindListener(Matchers.any(), modelParameterTypeListener); } }); // when final TypeParameterOwner instance = injector.getInstance(TypeParameterOwner.class); // then assertThat(instance, new CustomTypeSafeMatcher<TypeParameterOwner>("got it's fields injected") { @Override protected boolean matchesSafely(TypeParameterOwner item) { return item.field == newFieldValue; } }); }
@Test public void testZip3() throws Exception { // given final Tuple3<ImmutableList<String>, ImmutableList<String>, ImmutableList<String>> zipped = Tuple3.of(ImmutableList.of("a"), ImmutableList.of("b"), ImmutableList.of("c")); // when final Iterable<Product3<String, String, String>> zip = Products.zip(zipped); // then assertThat(zip, contains(new CustomTypeSafeMatcher<Product3<String, String, String>>("") { @Override protected boolean matchesSafely(final Product3<String, String, String> item) { return item.first().equals("a") && item.second().equals("b") && item.third().equals("c"); } })); }
/** * Test for nullability. * Checks that all public methods in clases in package * {@code com.jcabi.github }have {@code @NotNull} annotation for return * value and for input arguments(if they are not scalar). * * @throws Exception If some problem inside */ @Test public void checkNullability() throws Exception { MatcherAssert.assertThat( this.classpath.allPublicMethods(), Matchers.everyItem( // @checkstyle LineLength (1 line) new CustomTypeSafeMatcher<Method>("parameter and return value is annotated with @NonNull") { @Override protected boolean matchesSafely(final Method item) { return item.getReturnType().isPrimitive() || "toString".equals(item.getName()) || item.isAnnotationPresent(NotNull.class) && NullabilityTest.allParamsAnnotated(item); } } ) ); }
/** * Test for immutability. * Checks that all classes in package {@code com.jcabi.github } * have {@code @Immutable} annotation. * * @throws Exception If some problem inside */ @Test public void checkImmutability() throws Exception { MatcherAssert.assertThat( Iterables.filter( this.classpath.allTypes(), new Predicate<Class<?>>() { @Override public boolean apply(final Class<?> input) { return !ImmutabilityTest.skip().contains( input.getName() ); } } ), Matchers.everyItem( new CustomTypeSafeMatcher<Class<?>>("annotated type") { @Override protected boolean matchesSafely(final Class<?> item) { return item.isAnnotationPresent(Immutable.class); } } ) ); }
private Matcher<UploadPartRequest> matchUploadPart(final char c) { return new CustomTypeSafeMatcher<UploadPartRequest>("") { @Override protected boolean matchesSafely(UploadPartRequest subject) { try { String read = CharStreams.toString(new InputStreamReader(subject.getInputStream(), Charsets.UTF_8)); for (int i = 0, n = read.length(); i < n; i++) { checkState(read.charAt(i) == c); } return true; } catch (IOException e) { throw new AssertionError(e); } } }; }
/** * Convenience method for wrapping a {@link Predicate} into a matcher. * * @param function the predicate to wrap. * @param <T> The expected input type. * @return a {@link CustomTypeSafeMatcher} that simply wraps the input predicate. */ public static <T> Matcher<T> match(Predicate<T> function) { return new CustomTypeSafeMatcher<T>("Did not match") { @Override protected boolean matchesSafely(T item) { return function.test(item); } }; }
public void testExecuteBulkPipelineDoesNotExist() { CompoundProcessor processor = mock(CompoundProcessor.class); when(store.get("_id")).thenReturn(new Pipeline("_id", "_description", version, processor)); BulkRequest bulkRequest = new BulkRequest(); IndexRequest indexRequest1 = new IndexRequest("_index", "_type", "_id").source(Collections.emptyMap()).setPipeline("_id"); bulkRequest.add(indexRequest1); IndexRequest indexRequest2 = new IndexRequest("_index", "_type", "_id").source(Collections.emptyMap()).setPipeline("does_not_exist"); bulkRequest.add(indexRequest2); @SuppressWarnings("unchecked") BiConsumer<IndexRequest, Exception> failureHandler = mock(BiConsumer.class); @SuppressWarnings("unchecked") Consumer<Exception> completionHandler = mock(Consumer.class); executionService.executeBulkRequest(bulkRequest.requests(), failureHandler, completionHandler); verify(failureHandler, times(1)).accept( argThat(new CustomTypeSafeMatcher<IndexRequest>("failure handler was not called with the expected arguments") { @Override protected boolean matchesSafely(IndexRequest item) { return item == indexRequest2; } }), argThat(new CustomTypeSafeMatcher<IllegalArgumentException>("failure handler was not called with the expected arguments") { @Override protected boolean matchesSafely(IllegalArgumentException iae) { return "pipeline with id [does_not_exist] does not exist".equals(iae.getMessage()); } }) ); verify(completionHandler, times(1)).accept(null); }
@Test public void files() throws FileSystemException { CustomTypeSafeMatcher<Integer> matcher = new CustomTypeSafeMatcher<Integer>("Has at least one item") { @Override protected boolean matchesSafely(Integer item) { return item > 0; } }; MatcherAssert.assertThat(new FileSystemOfPath(RESOURCES).files(), Matchers.hasSize(matcher)); }
public static Matcher<View> withRecyclerView(final int recyclerViewId, final int position) { return new CustomTypeSafeMatcher<View>("") { @Override protected boolean matchesSafely(View item) { RecyclerView view = (RecyclerView) item.getRootView().findViewById(recyclerViewId); return view.getChildAt(position) == item; } }; }
public static Matcher<Bundle> forMailChooserIntent(final String action, final String mimeType, final String extraData, final String fileName) { return new CustomTypeSafeMatcher<Bundle>("Custom matcher for matching mail chooser intent") { @Override protected boolean matchesSafely(Bundle item) { Intent intent = (Intent) item.get(EXTRA_INTENT); Uri uri = intent.getParcelableExtra(EXTRA_STREAM); return action.equals(intent.getAction()) && mimeType.equals(intent.getType()) && intent.getStringExtra(EXTRA_SUBJECT).equalsIgnoreCase(extraData) && uri.getPath().endsWith(fileName); } }; }
public static Matcher<View> withRecyclerView(final int recyclerViewId, final int position) { return new CustomTypeSafeMatcher<View>(format("recycler view with id: {0} at position: {1}", recyclerViewId, position)) { @Override protected boolean matchesSafely(View item) { View view = item.getRootView().findViewById(recyclerViewId); if (view == null || !(view instanceof RecyclerView)) return false; RecyclerView recyclerView = (RecyclerView) view; View childView = recyclerView.findViewHolderForAdapterPosition(position).itemView; return childView == item; } }; }
public static Matcher<View> withListSize(final int size) { return new CustomTypeSafeMatcher<View>(format("recycler view with id: {0} ", size)) { @Override protected boolean matchesSafely(View view) { if (view == null || !(view instanceof RecyclerView)) return false; RecyclerView recyclerView = (RecyclerView) view; return recyclerView.getAdapter().getItemCount() == size; } }; }
@NonNull private CustomTypeSafeMatcher<View> anyView() { return new CustomTypeSafeMatcher<View>("") { @Override protected boolean matchesSafely(View item) { return true; } }; }
private Matcher<? super List<HttpHeaderValue>> containsWithValue(final String value) { return new CustomTypeSafeMatcher<List<HttpHeaderValue>>("contains with value:" + value) { @Override protected boolean matchesSafely(List<HttpHeaderValue> list) { return any(list, new Predicate<HttpHeaderValue>() { @Override public boolean apply(@Nullable HttpHeaderValue httpHeaderValue) { return httpHeaderValue.getValue().equals(value); } }); } }; }
@NonNull private CustomTypeSafeMatcher<List<HttpCallRecord>> hasCallWithUrl(final String url) { return new CustomTypeSafeMatcher<List<HttpCallRecord>>("with url") { @Override protected boolean matchesSafely(List<HttpCallRecord> item) { for (HttpCallRecord httpCall : item) { if (httpCall.getUrl().equals(url)) { return true; } } return false; } }; }
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; } }; }
private Matcher<HttpHeaderViewModel> withHeaderData(final String headerName, final String headerValue) { return new CustomTypeSafeMatcher<HttpHeaderViewModel>("Header with") { @Override protected boolean matchesSafely(HttpHeaderViewModel viewModel) { return viewModel.headerName().equals(headerName) && viewModel.headerValues().equals(headerValue); } }; }
public static CustomTypeSafeMatcher<ResponseFormatter> withConcreteClass(final Class<? extends ResponseFormatter> clazz) { return new CustomTypeSafeMatcher<ResponseFormatter>("Matches exact class " + clazz.getName()) { @Override protected boolean matchesSafely(ResponseFormatter object) { return object.getClass().getName().equals(clazz.getName()); } }; }
@NonNull private CustomTypeSafeMatcher<List<HttpCallRecord>> withSize(final int size) { return new CustomTypeSafeMatcher<List<HttpCallRecord>>("with size") { @Override protected boolean matchesSafely(List<HttpCallRecord> item) { return item.size() == size; } }; }
@Nonnull private static CustomTypeSafeMatcher<PublicOccupationTypeDTO> equalToOccupationType(final OrganisationType organisationType, final OccupationType occupationType) { return new CustomTypeSafeMatcher<PublicOccupationTypeDTO>( String.format("occupationType=%s organisationType=%s", occupationType, organisationType)) { @Override protected boolean matchesSafely(final PublicOccupationTypeDTO o) { return o.getOccupationType() == occupationType && o.getOrganisationType() == organisationType; } }; }
@Nonnull private static CustomTypeSafeMatcher<AddressDTO> equalToAddress(final Address address) { return new CustomTypeSafeMatcher<AddressDTO>("Address does not match") { @Override protected boolean matchesSafely(final AddressDTO o) { return Objects.equals(o.getStreetAddress(), address.getStreetAddress()) && Objects.equals(o.getCity(), address.getCity()) && Objects.equals(o.getPostalCode(), address.getPostalCode()); } }; }
private static <T> Matcher<CompletionStage<T>> completesTo(final Matcher<T> expected) { return new CustomTypeSafeMatcher<CompletionStage<T>>("completes to " + String.valueOf(expected)) { @Override protected boolean matchesSafely(CompletionStage<T> item) { try { final T value = item.toCompletableFuture().get(1, SECONDS); return expected.matches(value); } catch (Exception ex) { return false; } } }; }
private CustomTypeSafeMatcher<LineMessagingException> errorResponseIs(final ErrorResponse errorResponse) { return new CustomTypeSafeMatcher<LineMessagingException>("Error Response") { @Override protected boolean matchesSafely(LineMessagingException item) { assertThat(item.getErrorResponse()) .isEqualTo(errorResponse); return true; } }; }
/** * Test for visibility. * Checks that there are not public classes in package * {@code com.jcabi.github}. * * @throws Exception If some problem inside */ @Test public void checkVisibility() throws Exception { MatcherAssert.assertThat( Iterables.filter( this.classpath.allTypes(), new Predicate<Class<?>>() { @Override public boolean apply(final Class<?> input) { return !( input.isInterface() || SKIP.contains(input.getName()) || (input.getEnclosingClass() != null && input.getName().endsWith("Smart")) ); } } ), Matchers.everyItem( new CustomTypeSafeMatcher<Class<?>>("not public type") { @Override protected boolean matchesSafely(final Class<?> item) { return !Modifier.isPublic(item.getModifiers()); } } ) ); }
public static void assertEqualsWithoutWhiteSpaces(final String expected, String actual) { assertThat(actual, new CustomTypeSafeMatcher<String>(expected) { @Override protected boolean matchesSafely(String item) { return item.replaceAll("\\s", "").equals(expected.replaceAll("\\s", "")); } }); }
public static void assertMatchToExpressionWithoutWhiteSpaces(final String regex, String actual) { assertThat(actual, new CustomTypeSafeMatcher<String>(regex) { @Override protected boolean matchesSafely(String item) { return item.replaceAll("\\s", "").matches(regex.replaceAll("\\s", "")); } }); }
public static void assertContainsWithoutWhiteSpaces(final String subString, String actual) { assertThat(actual, new CustomTypeSafeMatcher<String>(subString) { @Override protected boolean matchesSafely(String item) { return item.replaceAll("\\s", "").contains(subString.replaceAll("\\s", "")); } }); }
/** * Creates a matcher that matches if the examined result set returns the * given collection of rows in some order. * * <p>Closes the result set after reading. * * <p>For example: * <pre>assertThat(statement.executeQuery("select empno from emp"), * returnsUnordered("empno=1234", "empno=100"));</pre> */ public static Matcher<? super ResultSet> returnsUnordered(String... lines) { final List<String> expectedList = Lists.newArrayList(lines); Collections.sort(expectedList); return new CustomTypeSafeMatcher<ResultSet>(Arrays.toString(lines)) { @Override protected void describeMismatchSafely(ResultSet item, Description description) { final Object value = THREAD_ACTUAL.get(); THREAD_ACTUAL.remove(); description.appendText("was ").appendValue(value); } protected boolean matchesSafely(ResultSet resultSet) { final List<String> actualList = Lists.newArrayList(); try { CalciteAssert.toStringList(resultSet, actualList); resultSet.close(); } catch (SQLException e) { throw new RuntimeException(e); } Collections.sort(actualList); THREAD_ACTUAL.set(actualList); final boolean equals = actualList.equals(expectedList); if (!equals) { THREAD_ACTUAL.set(actualList); } return equals; } }; }
/** * Matcher that succeeds for any collection that, when converted to strings * and sorted on those strings, matches the given reference string. * * <p>Use it as an alternative to {@link CoreMatchers#is} if items in your * list might occur in any order. * * <p>For example: * * <blockquote><pre>List<Integer> ints = Arrays.asList(2, 500, 12); * assertThat(ints, sortsAs("[12, 2, 500]");</pre></blockquote> */ static <T> Matcher<Iterable<? extends T>> sortsAs(final String value) { return new CustomTypeSafeMatcher<Iterable<? extends T>>(value) { protected boolean matchesSafely(Iterable<? extends T> item) { final List<String> strings = new ArrayList<>(); for (T t : item) { strings.add(t.toString()); } Collections.sort(strings); return value.equals(strings.toString()); } }; }
public static Matcher<? super Class<?>> isAbstractClass() { return new CustomTypeSafeMatcher<Class<?>>("is abstract class") { @Override protected boolean matchesSafely(Class<?> aClass) { return Modifier.isAbstract(aClass.getModifiers()); } }; }
/** * A matcher matching non-null and non-empty strings * * Example: * <pre>assertThat("this is not an empty string", notEmptyString())</pre> * * @return * matcher for a not empty string */ @Factory public static Matcher<String> notEmptyString() { return new CustomTypeSafeMatcher<String>("not empty") { @Override protected boolean matchesSafely(String s) { return !s.isEmpty(); } }; }
public static Matcher<DockerRule> apiVersionGreater(final RemoteApiVersion version) { return new CustomTypeSafeMatcher<DockerRule>("is greater") { public boolean matchesSafely(DockerRule dockerRule) { return getVersion(dockerRule.getClient()).isGreater(version); } }; }
public static Matcher<DockerRule> isGreaterOrEqual(final RemoteApiVersion version) { return new CustomTypeSafeMatcher<DockerRule>("is greater or equal") { public boolean matchesSafely(DockerRule dockerRule) { return getVersion(dockerRule.getClient()).isGreaterOrEqual(version); } @Override protected void describeMismatchSafely(DockerRule rule, Description mismatchDescription) { mismatchDescription .appendText(" was ") .appendText(getVersion(rule.getClient()).toString()); } }; }