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)); } }; }
public static <T> Matcher<T> hasFieldWithUserRef(final String fieldName, final User user) { return new BaseMatcher<T>() { @Override public boolean matches(Object o) { Ref<User> userRef = TestSupport.getField(o, fieldName); if (user == null) { return userRef == null; } else { String username = userRef.getKey().getName(); return user.getUsername().equals(username); } } @Override public void describeTo(Description description) { description.appendText(String.format("User with username '%s' on field %s", user, fieldName)); } }; }
@Override protected boolean matchesSafely(RecordedRequest item, Description mismatchDescription) { if (item == null) { mismatchDescription.appendText("was null"); return false; } switch (checkingOption) { default: case METHOD_PATH: return matchesMethodAndPath(item, mismatchDescription); case HEADER: return matchesHeader(item, mismatchDescription); case QUERY_PARAMETER: return matchesQueryParameter(item, mismatchDescription); } }
public static Matcher<ClassSpec> generatesTo(String expectedTestFile) { return new TypeSafeMatcher<ClassSpec>() { @Override protected boolean matchesSafely(ClassSpec spec) { String expectedClass = getExpectedClass(spec, expectedTestFile); String actualClass = generateClass(spec); try { assertThat(actualClass, equalToIgnoringWhiteSpace(expectedClass)); } catch (AssertionError e) { //Unfortunately for string comparisons Hamcrest doesn't really give us a nice diff. On the other hand //IDEs know how to nicely display JUnit's ComparisonFailure - makes debugging tests much easier throw new ComparisonFailure(String.format("Output class does not match expected [test-file: %s]", expectedTestFile), expectedClass, actualClass); } return true; } @Override public void describeTo(Description description) { //Since we bubble an exception this will never actually get called } }; }
/** * @return the graph */ public GWGraph getGraph() { if (graph==null) { List<SWTBotGefEditPart> parts = editor.editParts(new BaseMatcher<EditPart>() { @Override public boolean matches(Object item) { if (item instanceof org.gw4e.eclipse.studio.part.editor.GraphPart) return true; if (item instanceof org.gw4e.eclipse.studio.part.editor.VertexPart) return true; if (item instanceof org.gw4e.eclipse.studio.part.editor.EdgePart) return true; return false; } @Override public void describeTo(Description description) { } }); if (parts==null || parts.size() ==0) { throw new RuntimeException("Empty Graph"); } graph = getGraph (parts.get(0)); } return graph; }
public 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; } }; }
public static org.hamcrest.Matcher<View> childAtPosition( final org.hamcrest.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)); } }; }
@Override protected boolean matchesSafely(JsonNode jsonNode, Description description) { // check node identifier of master String jsonNodeId = jsonNode.get("master").asText(); String nodeId = mastershipTerm.master().id(); if (!jsonNodeId.equals(nodeId)) { description.appendText("master's node id was " + jsonNodeId); return false; } // check term number long jsonTermNumber = jsonNode.get("termNumber").asLong(); long termNumber = mastershipTerm.termNumber(); if (jsonTermNumber != termNumber) { description.appendText("term number was " + jsonTermNumber); return false; } return true; }
/** * Checks if collection has the given number of items. */ public static Matcher<Collection<?>> hasItems(final int numberOfItems) { return new TypeSafeMatcher<Collection<?>>() { @Override public boolean matchesSafely(Collection<?> collection) { if (collection == null || collection.size() != numberOfItems) { return false; } return true; } @Override public void describeTo(Description description) { description.appendText("expected a collection with " + numberOfItems + " items"); } }; }
/** * Matches the contents of a mod vlan pcp instruction. * * @param instructionJson JSON instruction to match * @param description Description object used for recording errors * @return true if contents match, false otherwise */ private boolean matchModVlanPcpInstruction(JsonNode instructionJson, Description description) { ModVlanPcpInstruction instructionToMatch = (ModVlanPcpInstruction) instruction; final String jsonSubtype = instructionJson.get("subtype").textValue(); if (!instructionToMatch.subtype().name().equals(jsonSubtype)) { description.appendText("subtype was " + jsonSubtype); return false; } final String jsonType = instructionJson.get("type").textValue(); if (!instructionToMatch.type().name().equals(jsonType)) { description.appendText("type was " + jsonType); return false; } final short jsonVlanPcp = instructionJson.get("vlanPcp").shortValue(); final short vlanId = instructionToMatch.vlanPcp(); if (jsonVlanPcp != vlanId) { description.appendText("vlan pcp was " + jsonVlanPcp); return false; } return true; }
/** * Matches the contents of a mod MPLS label instruction. * * @param instructionJson JSON instruction to match * @param description Description object used for recording errors * @return true if contents match, false otherwise */ private boolean matchModMplsLabelInstruction(JsonNode instructionJson, Description description) { ModMplsLabelInstruction instructionToMatch = (ModMplsLabelInstruction) instruction; final String jsonSubtype = instructionJson.get("subtype").textValue(); if (!instructionToMatch.subtype().name().equals(jsonSubtype)) { description.appendText("subtype was " + jsonSubtype); return false; } final String jsonType = instructionJson.get("type").textValue(); if (!instructionToMatch.type().name().equals(jsonType)) { description.appendText("type was " + jsonType); return false; } final int jsonLabel = instructionJson.get("label").intValue(); final int label = instructionToMatch.label().toInt(); if (label != jsonLabel) { description.appendText("MPLS label was " + jsonLabel); return false; } return true; }
/** * Checks that the given {@code VideoLibraryModel.Video} is equal to the video data in the given * cursor table at the given {@code index}. */ private Matcher<VideoLibraryModel.Video> equalsVideoDataInCursor(final Object[][] cursorTable, final int index) { return new BaseMatcher<VideoLibraryModel.Video>() { @Override public boolean matches(final Object item) { final VideoLibraryModel.Video video = (VideoLibraryModel.Video) item; return video.getId().equals(cursorTable[VIDEO_ID_COLUMN_INDEX][index]) && video.getYear() == (Integer) cursorTable[VIDEO_YEAR_COLUMN_INDEX][index] && video.getTopic().equals(cursorTable[VIDEO_TOPIC_COLUMN_INDEX][index]) && video.getTitle().equals(cursorTable[VIDEO_TITLE_COLUMN_INDEX][index]) && video.getDesc().equals(cursorTable[VIDEO_DESC_COLUMN_INDEX][index]) && video.getVid().equals(cursorTable[VIDEO_VID_COLUMN_INDEX][index]) && video.getSpeakers().equals( cursorTable[VIDEO_SPEAKER_COLUMN_INDEX][index]) && video.getThumbnailUrl().equals( cursorTable[VIDEO_THUMBNAIL_URL_COLUMN_INDEX][index]); } @Override public void describeTo(final Description description) { description.appendText("The Video does not match the data in table ") .appendValue(cursorTable).appendText(" at index ").appendValue(index); } }; }
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); } }; }
private boolean matchesQueryParameter(RecordedRequest item, Description mismatchDescription) { String path = item.getPath(); boolean hasQuery = path.indexOf("?") > 0; if (!hasQuery) { mismatchDescription.appendText(" query was empty"); return false; } String query = path.substring(path.indexOf("?") + 1, path.length()); String[] parameters = query.split("&"); for (String p : parameters) { if (p.equals(String.format("%s=%s", first, second))) { return true; } } mismatchDescription.appendValueList("Query parameters were {", ", ", "}.", parameters); return false; }
@Override public void describeMismatchSafely( final MimeType item, final Description desc ) { try { desc.appendText("was param ") .appendDescriptionOf( new ParamDescription( this.name, item.params().get(this.name) ) ); } catch (final IOException err) { desc.appendText("was not set"); } }
/** * Checks if array is non-empty. This matcher can be replaced with JUnit 4.8 */ public static Matcher<Object[]> hasItemInArray() { return new TypeSafeMatcher<Object[]>() { @Override public boolean matchesSafely(Object[] arrayToTest) { if (arrayToTest == null || arrayToTest.length == 0) { return false; } return true; } @Override public void describeTo(Description description) { description.appendText("non-empty array"); } }; }
public static Matcher<String> isCorrectTimeStampFormat() { return new BaseMatcher<String>() { @Override public boolean matches(Object object) { String string = (String) object; assertTrue(string .matches("[0-9]{2,}/[0-9]{2,}/[0-9]{4,}_[0-9]{2,}:[0-9]{2,}:[0-9]{2,}\\.[0-9]{3,}")); return true; } @Override public void describeTo(Description description) { description .appendText("Timestamp format is wrong. MM/dd/YYYY_hh:mm:ss.SSS expected"); } }; }
private static Matcher within(double epsilon, double value) { return new BaseMatcher() { @Override public void describeTo(Description description) { description.appendText("within ") .appendText(Double.toString(epsilon)) .appendText(" of ") .appendText(Double.toString(value)); } @Override public boolean matches(Object item) { return item instanceof Double && Math.abs(((Double)item) - value) < epsilon; } }; }
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)); } }; }
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); } }; }
private void LoginAndVerifyLoginRequest(String multifactorPassword, final List<KeyValuePair<String, String>> expectedValues) { WebClient webClient = SuccessfullyLogin(multifactorPassword); verify(webClient).uploadValues(eq(LoginUrl), Matchers.argThat(new BaseMatcher<List<KeyValuePair<String, String>>>() { @Override public boolean matches(Object o) { return AreEqual((List<KeyValuePair<String, String>>)o, expectedValues); } @Override public void describeTo(Description d) { //throw new RuntimeException("TODO"); } })); // "Did not see login POST request with expected form data and/or URL"); }
@Override public void describeTo(Description description) { description.appendText("BugInstance with:\n"); if (bugType != null) { description.appendText("bugType=").appendValue(bugType).appendText(","); } if (className != null) { description.appendText("className=").appendValue(className).appendText(","); } if (methodName != null) { description.appendText("methodName=").appendValue(methodName).appendText(","); } if (fieldName != null) { description.appendText("fieldName=").appendValue(fieldName).appendText(","); } if (lineNumber != null) { description.appendText("lineNumber=").appendValue(lineNumber); } }
private Matcher<Email> equalsMail(Email email) { return new BaseMatcher<Email>() { @Override public boolean matches(Object item) { if(item instanceof Email){ Email other = (Email)item; if(email.getId() == other.getId()){ return true; } } return false; } @Override public void describeTo(Description description) { description.appendText("equalsMail should return email with id ").appendValue(email.getId()); } }; }
@Override public void describeTo(Description description) { if (expectedContents.isEmpty()) { description.appendText("A map"); return; } description.appendText("A map with:"); IndentationControl.indent(); for (Map.Entry<K, Matcher<? super V>> entry : expectedContents.entrySet()) { IndentationControl.newline(description).appendText(entry.getKey().toString()).appendText(": ").appendDescriptionOf(entry.getValue()); } IndentationControl.outdent(); }
@Override protected boolean matchesSafely(JsonNode jsonForwardingObj, Description description) { ObjectiveJsonMatcher.matchesObjective(forwardingObjective).matchesSafely(jsonForwardingObj); // check id int jsonId = jsonForwardingObj.get("id").asInt(); int id = forwardingObjective.id(); if (jsonId != id) { description.appendText("id was " + jsonId); return false; } // check nextId int jsonNextId = jsonForwardingObj.get("nextId").asInt(); int nextId = forwardingObjective.nextId(); if (jsonNextId != nextId) { description.appendText("nextId was " + jsonNextId); return false; } // check flag String jsonFlag = jsonForwardingObj.get("flag").asText(); String flag = forwardingObjective.flag().toString(); if (!jsonFlag.equals(flag)) { description.appendText("flag was " + jsonFlag); return false; } return true; }
public static Matcher<View> withRecyclerViewItems (final int size) { return new TypeSafeMatcher<View>() { @Override public boolean matchesSafely (final View view) { return ((RecyclerView) view).getAdapter().getItemCount () == size; } @Override public void describeTo (final Description description) { description.appendText ("RecycleView should have " + size + " items"); } }; }
/** * Helper class that matches a given toolbar title. * * @param textMatcher The matcher to verify the toolbar title against * @return The matcher that will verify the toolbar title */ private static Matcher<Object> withToolbarTitle(final Matcher<CharSequence> textMatcher) { return new BoundedMatcher<Object, Toolbar>(Toolbar.class) { @Override public boolean matchesSafely(Toolbar toolbar) { return textMatcher.matches(toolbar.getTitle()); } @Override public void describeTo(Description description) { description.appendText("with toolbar title: "); textMatcher.describeTo(description); } }; }
private BaseMatcher<Object> isProxy() { return new BaseMatcher<Object>() { @Override public boolean matches(Object item) { return AopUtils.isAopProxy(item); } @Override public void describeTo(Description description) { } }; }
@Override protected boolean matchesSafely( final Try<T> tTry, final Description description) { if (tTry.isFailure()) { return true; } description.appendText("was a Success"); return false; }
private Matcher<Throwable> causeWithMessageContaining(final String message) { return new TypeSafeMatcher<Throwable>() { @Override protected boolean matchesSafely(Throwable item) { return item.getCause() != null && item.getCause().getCause() != null && item.getCause().getCause().getMessage().contains(message); } @Override public void describeTo(Description description) { description.appendText(String.format("cause with cause with message containing '%s'", message)); } }; }
@Override protected boolean matchesSafely(String item, Description mismatchDescription) { try { if (!date.isEqual(ZonedDateTime.parse(item))) { mismatchDescription.appendText("was ").appendValue(item); return false; } return true; } catch (DateTimeParseException e) { mismatchDescription.appendText("was ").appendValue(item) .appendText(", which could not be parsed as a ZonedDateTime"); return false; } }
@Override protected boolean matchesSafely(Result<S, F> result, Description description) { Boolean matches = result.either( innerMatcher::matches, failure -> false ); if(!matches) { ResultMatchers.describeTo(result, description); } return matches; }
private String containsWarnMsgAboutEmptyVersion() { return BDDMockito.argThat(new TypeSafeMatcher<String>() { @Override protected boolean matchesSafely(String item) { return item.contains("is empty. Will not set it"); } @Override public void describeTo(Description description) { } }); }
private static <M extends Member> Matcher<M> nameMatches(final Matcher<String> nameMatcher) { return new TypeSafeMatcher<M>() { @Override public void describeTo(Description description) { description.appendText("name ").appendDescriptionOf(nameMatcher); } @Override protected boolean matchesSafely(M item) { return nameMatcher.matches(item.getName()); } }; }