@Before public void init() { audienceManagerService = mock(AudienceManagerService.class); authenticationManager = mock(AuthenticationManager.class); UserDetailsService userDetailsService = mock(UserDetailsService.class); TokenBasedRememberMeServices rememberMeServices = spy(new TokenBasedRememberMeServices("key", userDetailsService)); provider = new AudienceManagerSecurityProvider(audienceManagerService, authenticationManager, rememberMeServices); token.setDetails("id"); doThrow(new BadCredentialsException("Test")).when(authenticationManager).authenticate(any(Authentication.class)); doReturn(token).when(authenticationManager).authenticate(argThat(new BaseMatcher<Authentication>() { @Override public boolean matches(Object item) { return ((Authentication) item).getPrincipal().equals("user"); } @Override public void describeTo(Description description) { description.appendText("Username is user"); } })); }
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)); } }; }
@Factory @Deprecated /** * Please avoid using as the hamcrest way of reporting error wraps a multi-line * text into a single line and makes hard to understand the problem. * Instead, please try to use the spock/groovy assert and {@link #containsLine(String, String)} */ public static Matcher<String> containsLine(final String line) { return new BaseMatcher<String>() { public boolean matches(Object o) { return containsLine(equalTo(line)).matches(o); } public void describeTo(Description description) { description.appendText("a String that contains line ").appendValue(line); } }; }
@Factory public static Matcher<Object> isSerializable() { return new BaseMatcher<Object>() { public boolean matches(Object o) { try { new ObjectOutputStream(new ByteArrayOutputStream()).writeObject(o); } catch (IOException e) { throw new RuntimeException(e); } return true; } public void describeTo(Description description) { description.appendText("is serializable"); } }; }
private BaseMatcher<BindException> getMatcher(String message, String field) { return new BaseMatcher<BindException>() { @Override public void describeTo(Description description) { } @Override public boolean matches(Object item) { BindException ex = (BindException) ((Exception) item).getCause(); ObjectError error = ex.getAllErrors().get(0); boolean messageMatches = message.equals(error.getDefaultMessage()); if (field == null) { return messageMatches; } String fieldErrors = ((FieldError) error).getField(); return messageMatches && fieldErrors.equals(field); } }; }
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; } }; }
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); } }; }
public static Matcher<List<AuditLog>> sortedCreationTimes() { return new BaseMatcher<List<AuditLog>>() { @Override public boolean matches(Object object) { List<AuditLog> auditLogs = (List<AuditLog>) object; for (int i = 0; i < auditLogs.size()-1; i++) { assertTrue(auditLogs.get(i).getCreationTime()<=auditLogs.get(i+1).getCreationTime()); } return true; } @Override public void describeTo(Description description) { description .appendText("AuditLogEntry List not sorted on creation time."); } }; }
public static Matcher<List<AuditLog>> notSortedCreationTimes() { return new BaseMatcher<List<AuditLog>>() { @Override public boolean matches(Object object) { List<AuditLog> auditLogs = (List<AuditLog>) object; for (int i = 0; i < auditLogs.size()-1; i++) { if (auditLogs.get(i).getCreationTime()>auditLogs.get(i+1).getCreationTime()) { return true; } } return false; } @Override public void describeTo(Description description) { description .appendText("AuditLogEntry List sorted on creation time."); } }; }
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"); } }; }
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); } }; }
/** * @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; }
private Matcher<List<Mensa>> equalToMensas(List<Mensa> mensas) { return new BaseMatcher<List<Mensa>>() { @Override @SuppressWarnings("unchecked") public boolean matches(Object item) { List<Mensa> matchTargetList = (List<Mensa>) item; if (matchTargetList.size() != mensas.size()) { return false; } else { for (int i = 0; i < mensas.size(); i++) { Mensa mensa = mensas.get(i); Mensa matchTarget = matchTargetList.get(i); if (!EqualsBuilder.reflectionEquals(mensa, matchTarget, Arrays.asList("updatedAt"))) { return false; } } return true; } } @Override public void describeTo(Description description) { description.appendText("each mensa should be equal except for the update value"); } }; }
public static BaseMatcher<String> captureCreatedRadiator(CreatedRadiator createdRadiator) { return new BaseMatcher<String>() { @Override public boolean matches(Object o) { try { CreatedRadiator cr = new ObjectMapper().readValue((String) o, CreatedRadiator.class); createdRadiator.code = cr.code; createdRadiator.secret = cr.secret; } catch (IOException e) { fail("IOE encountered " + e.getMessage()); } return true; } @Override public void describeTo(Description description) { } }; }
/** * 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<ParseValue> equalTo(final ParseValue parseValue) { return new BaseMatcher<ParseValue>() { @Override public boolean matches(final Object o) { if (parseValue == o) { return true; } if (o == null || parseValue.getClass() != o.getClass()) { return false; } final ParseValue that = (ParseValue) o; return parseValue.offset == that.offset && Objects.equals(parseValue.name, that.name) && Objects.equals(parseValue.definition, that.definition) && Arrays.equals(parseValue.getValue(), that.getValue()); } @Override public void describeTo(final Description description) { description.appendValue(parseValue); } }; }
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()); } }; }
private Matcher<Pageable> matchPageable(int page, int size) { return new BaseMatcher<Pageable>() { @Override public void describeTo(Description description) { description.appendText("Pagable should have pageNumber ").appendValue(page).appendText(" and pageSize ").appendValue(size); } @Override public boolean matches(Object item) { if (item instanceof Pageable) { Pageable p = (Pageable) item; return p.getPageNumber() == page && p.getPageSize() == size; } return false; } }; }
public <T> Matcher<T> equalsRecorded(final String name) { return new BaseMatcher<T>() { @Override public boolean matches(Object o) { return recordedValues.containsKey(name) && recordedValues.get(name).equals(o); } @Override public void describeTo(Description description) { description.appendText("equals value recorded as ").appendValue(name); if (recordedValues.containsKey(name)) { description.appendText(" (").appendValue(recordedValues.get(name)).appendText(")"); } else { description.appendText(" (no value recorded)"); } } }; }
private Matcher<CloudFoundryRawServiceData> matchesContent(final ServicesData expected) { return new BaseMatcher<CloudFoundryRawServiceData>() { @Override @SuppressWarnings("unchecked") public boolean matches(Object actual) { return mapsAreEquivalent((Map<String, ?>) actual, expected); } @Override public void describeMismatch(Object item, Description mismatchDescription) { } @Override public void describeTo(Description description) { } }; }
private void LoginAndVerifyIterationsRequest(String multifactorPassword, final List<KeyValuePair<String, String>> expectedValues) { WebClient webClient = SuccessfullyLogin(multifactorPassword); verify(webClient).uploadValues(eq(IterationsUrl), 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 iterations POST request with expected form data and/or URL"); }
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"); }
@Test public void Parse_PRIK_throws_on_invalid_chunk() { ParserHelper.Chunk chunk = new ParserHelper.Chunk("PRIK", "".getBytes()); thrown.expect(ParseException.class); thrown.expect(new BaseMatcher<ParseException>(){ @Override public void describeTo(Description description) { } @Override public boolean matches(Object item) { ParseException parseException = (ParseException)item; return ParseException.FailureReason.CorruptedBlob.equals(parseException.getReason()); } }); thrown.expectMessage("Failed to decrypt private key"); parserHelper.Parse_PRIK(chunk, TestData.EncryptionKey); }
public static Matcher<byte[]> isActuallyAnExcelFile() { return new BaseMatcher<byte[]>() { @Override public boolean matches(Object o) { final List<String> names = new ArrayList<>(); try (ZipInputStream zipStream = new ZipInputStream(new ByteArrayInputStream((byte[]) o))) { ZipEntry zipEntry; while ((zipEntry = zipStream.getNextEntry()) != null) { names.add(zipEntry.getName()); zipStream.closeEntry(); } } catch (IOException e) { return false; } return hasItems("_rels/.rels", "docProps/app.xml", "xl/styles.xml", "xl/workbook.xml").matches(names); } @Override public void describeTo(Description description) { description.appendText("Given binary data corresponds to an excel file"); } }; }
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); } }; }
private static Matcher<UsageThresholdConfiguration> hasIncreaseOverTimeFrameValue(final double increase, final long timeFrameInMillis) { return new BaseMatcher<UsageThresholdConfiguration>() { @Override public boolean matches(Object obj) { try { final IncreaseOverTimeFrameUsageThresholdConfiguration config = (IncreaseOverTimeFrameUsageThresholdConfiguration) obj; return increase == config.getDelta() && timeFrameInMillis == config.getTimeUnit().toMilliSeconds(config.getTimeFrame()); } catch (ClassCastException ex) { return false; } } @Override public void describeTo(Description description) { description.appendText( String.format("has delta '%.2f' over time-frame '%d' in millis", increase, timeFrameInMillis)); } }; }
/** * Create a matcher that wrapps the specified matcher and tests against the * {@link Throwable#getCause() cause} of an exception. If the item tested * is {@code null} not a {@link Throwable} the wrapped matcher will be called * with a {@code null} item. * * <p>Often useful when working with JUnit {@link ExpectedException} * {@link Rule @Rule}s, for example: * <pre> * thrown.expect(DataAccessException.class); * thrown.except(exceptionCause(isA(SQLException.class))); * </pre> * * @param matcher the matcher to wrap (must not be null) * @return a matcher that tests using the exception cause */ @SuppressWarnings("unchecked") public static <T> Matcher<T> exceptionCause(final Matcher<T> matcher) { return (Matcher<T>) new BaseMatcher<Object>() { @Override public boolean matches(Object item) { Throwable cause = null; if(item != null && item instanceof Throwable) { cause = ((Throwable)item).getCause(); } return matcher.matches(cause); } @Override public void describeTo(Description description) { description.appendText("exception cause ").appendDescriptionOf(matcher); } }; }
/** * Matches all items of provided matcher to source. If any fails this fails. */ public static <T> Matcher<Iterable<T>> allOfThem(final Matcher<T> matcher) { return new BaseMatcher<Iterable<T>>() { @Override public boolean matches(Object item) { if (item instanceof Iterable) { Iterable iterable = ((Iterable) item); for (Object o : iterable){ if (!matcher.matches(o)) return false; } return true; } throw new AssertionError("Iterator types do not match!"); } @Override public void describeTo(Description description) { description.appendText("all items matched "); description.appendDescriptionOf(matcher); } }; }
/** * Matches that at least one item of provided matcher to source. If all fails this fails. */ public static <T> Matcher<Iterable<T>> atLeastOne(final Matcher<T> matcher) { return new BaseMatcher<Iterable<T>>() { @Override public boolean matches(Object item) { if (item instanceof Iterable) { Iterable iterable = ((Iterable) item); for (Object o : iterable){ if (matcher.matches(o)) return true; } return false; } throw new AssertionError("Iterator types do not match!"); } @Override public void describeTo(Description description) { description.appendText("at least one matched "); description.appendDescriptionOf(matcher); } }; }
/** * Returns a custom matcher that retrieves the first matching item only. * * @param matcher matcher that may match more than one item. * @param <T> matcher type. * @return custom matcher which will only trigger for the first item. */ public static <T> Matcher<T> first(final Matcher<T> matcher) { return new BaseMatcher<T>() { private boolean isFirst = true; @Override public boolean matches(Object item) { if (isFirst && matcher.matches(item)) { isFirst = false; return true; } return false; } @Override public void describeTo(Description description) { matcher.describeTo(description); description.appendText("first matching item only"); } }; }
private Matcher<? extends Throwable> deeply(Class<? extends Throwable> expectedCause) { return new BaseMatcher<Throwable>() { @Override public boolean matches(Object argument) { Throwable exception = (Throwable) argument; Throwable cause = exception.getCause(); while (cause != null) { if (expectedCause.isInstance(cause)) return true; cause = cause.getCause(); } return false; } @Override public void describeTo(Description description) { description.appendText(expectedCause.getName()); } }; }
@Test public void testParsePOM_Invalid() { this.exception.expect(RuntimeException.class); this.exception.expectCause(new BaseMatcher<Throwable>() { @Override public boolean matches(Object item) { return item instanceof SAXParseException; } @Override public void describeTo(Description description) { } }); URL url = getClass().getResource(getClass().getSimpleName() + "/pom2.xml"); File f; try { f = new File(url.toURI()); } catch (URISyntaxException e) { f = new File(url.getPath()); } PomUtil.parsePOM(f); Assert.fail("Parser should throw an exception since the document is not well formed!"); }
protected Matcher<T> jsonNumber(final Number e) { return new BaseMatcher<T>() { @Override @SuppressWarnings("unchecked") public boolean matches(final Object n) { T actual = (T) n; T expected = runtime().createNumber(e.doubleValue()); return runtime().typeOf(actual) == JmesPathType.NUMBER && runtime().compare(actual, expected) == 0; } @Override public void describeTo(Description description) { description.appendText("JSON number with value ").appendValue(e); } }; }
protected Matcher<T> jsonArrayOfStrings(final String... strs) { return new BaseMatcher<T>() { @Override @SuppressWarnings("unchecked") public boolean matches(final Object n) { List<T> input = runtime().toList((T) n); if (input.size() != strs.length) { return false; } for (int i = 0; i < strs.length; i++) { if (!runtime().toString(input.get(i)).equals(strs[i])) { return false; } } return true; } @Override public void describeTo(Description description) { description.appendText("JSON array ").appendValue(strs); } }; }
private static <T> Matcher<Collection<T>> containsExactly(final Collection<T> expected) { return new BaseMatcher<Collection<T>>() { @Override public boolean matches(Object o) { return o != null && o instanceof Collection && ImmutableSet.copyOf((Collection) o).equals(ImmutableSet.copyOf(expected)); } @Override public void describeTo(Description description) { description.appendText("contains exactly ").appendValue(expected); } }; }
private Matcher<ListObjectsRequest> listObjectRequest(final String bucket, final String prefix, @Nullable final String marker) { return new BaseMatcher<ListObjectsRequest>() { @Override public boolean matches(Object item) { ListObjectsRequest request = (ListObjectsRequest) item; return request != null && request.getBucketName().equals(bucket) && request.getPrefix().equals(prefix) && Objects.equals(request.getMarker(), marker); } @Override public void describeTo(Description description) { description.appendText("ListObjectRequest[s3://").appendText(bucket).appendText("/").appendText(prefix); if (marker != null) { description.appendText(", marker=").appendText(marker); } description.appendText("]"); } }; }
private static Matcher<MethodInfo> hasInterceptor(final IMethodInterceptor interceptor) { return new BaseMatcher<MethodInfo>() { @Override public void describeTo(Description description) { description.appendText("has interceptor ").appendText(interceptor.toString()); } @Override public boolean matches(Object item) { if (item instanceof MethodInfo) { MethodInfo methodInfo = (MethodInfo) item; return methodInfo.getInterceptors().contains(interceptor); } return false; } }; }
@Test public void testNamedClient_noInstance() throws Exception { exception.expect(ServiceException.class); exception.expectCause(allOf(isA(CacheException.class), new BaseMatcher<CacheException>() { @Override public boolean matches(Object item) { return ((CacheException) item).getMessage().contains("No client with name [dev-custom] could be found."); } @Override public void describeTo(Description description) { } })); Properties props = new Properties(); props.setProperty(Environment.CACHE_REGION_FACTORY, HazelcastCacheRegionFactory.class.getName()); props.setProperty(CacheEnvironment.USE_NATIVE_CLIENT, "true"); props.setProperty(CacheEnvironment.NATIVE_CLIENT_INSTANCE_NAME, "dev-custom"); props.setProperty("hibernate.dialect", "org.hibernate.dialect.HSQLDialect"); Configuration configuration = new Configuration(); configuration.addProperties(props); SessionFactory sf = configuration.buildSessionFactory(); sf.close(); }