Java Code Examples for org.hamcrest.Description

The following examples show how to use org.hamcrest.Description. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: soas   Source File: LongListMatchers.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creates a matcher against the text stored in R.id.item_content. This text is roughly
 * "item: $row_number".
 */
@SuppressWarnings("rawtypes")
public static Matcher<Object> withItemContent(final Matcher<String> itemTextMatcher) {
  // use preconditions to fail fast when a test is creating an invalid matcher.
  checkNotNull(itemTextMatcher);
  return new BoundedMatcher<Object, Map>(Map.class) {
    @Override
    public boolean matchesSafely(Map map) {
      return hasEntry(equalTo("STR"), itemTextMatcher).matches(map);
    }

    @Override
    public void describeTo(Description description) {
      description.appendText("with item content: ");
      itemTextMatcher.describeTo(description);
    }
  };
}
 
Example 2
Source Project: ogham   Source File: AssertionHelper.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private static <T> Description getDescription(String reason, T actual, Matcher<? super T> matcher, String additionalText) {
	if (matcher instanceof CustomDescriptionProvider) {
		return ((CustomDescriptionProvider<T>) matcher).describe(reason, actual, additionalText);
	}
	// @formatter:off
	Description description = new StringDescription();
	description.appendText(getReason(reason, matcher))
				.appendText(additionalText==null ? "" : ("\n"+additionalText))
				.appendText("\nExpected: ")
				.appendDescriptionOf(matcher)
				.appendText("\n     but: ");
	matcher.describeMismatch(actual, description);
	// @formatter:on
	return description;
}
 
Example 3
Source Project: ETHWallet   Source File: ScreengrabTest.java    License: GNU General Public License v3.0 6 votes vote down vote up
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));
        }
    };
}
 
Example 4
Source Project: fullstop   Source File: ViolationMatchers.java    License: Apache License 2.0 6 votes vote down vote up
public static Matcher<Violation> hasType(final String expectedType) {
    return new TypeSafeDiagnosingMatcher<Violation>() {
        @Override
        protected boolean matchesSafely(final Violation violation, final Description mismatchDescription) {
            final String actualType = violation.getViolationType();
            if (!Objects.equals(actualType, expectedType)) {
                mismatchDescription.appendText("type was ").appendValue(actualType);
                return false;
            } else {
                return true;
            }
        }

        @Override
        public void describeTo(final Description description) {
            description.appendText("violation of type ").appendValue(expectedType);
        }
    };
}
 
Example 5
/**
 * This helps "find" the lists in the activity, since there is more than 1.
 *
 * @param tag
 * @return
 */
private static Matcher<View> withTag(final Object tag) {
    return new TypeSafeMatcher<View>() {

        @Override
        public void describeTo(final Description description) {
            description.appendText("has tag equals to: " + tag);
        }

        @Override
        protected boolean matchesSafely(final View view) {
            Object viewTag = view.getTag();
            if (viewTag == null) {
                return tag == null;
            }

            return viewTag.equals(tag);
        }
    };
}
 
Example 6
Source Project: spring-cloud-deployer   Source File: EventuallyMatcher.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected boolean matches(Object item, Description mismatchDescription) {
	mismatchDescription.appendText(
			String.format("failed after %d*%d=%dms:%n", maxAttempts, pause, maxAttempts * pause));
	for (int i = 0; i < maxAttempts; i++) {
		boolean result = delegate.matches(item);
		if (result) {
			return true;
		}
		delegate.describeMismatch(item, mismatchDescription);
		mismatchDescription.appendText(", ");
		try {
			Thread.sleep(pause);
		}
		catch (InterruptedException e) {
			Thread.currentThread().interrupt();
			break;
		}
	}
	return false;
}
 
Example 7
Source Project: cukes   Source File: CustomMatchers.java    License: Apache License 2.0 6 votes vote down vote up
public static <T> Matcher<Optional<T>> equalToOptional(final T operand) {
    return new TypeSafeMatcher<Optional<T>>() {

        private Matcher<T> equalTo;

        @Override
        protected boolean matchesSafely(Optional<T> t) {
            if(t.isPresent()) {
                equalTo = IsEqual.equalTo(t.get());
                return equalTo.matches(operand);
            }
            return false;
        }

        @Override
        public void describeTo(Description description) {
            IsEqual.equalTo(equalTo).describeTo(description);
        }
    };
}
 
Example 8
Source Project: rulz   Source File: HttpMatchers.java    License: Apache License 2.0 6 votes vote down vote up
public static Matcher<Response> noContent() {
    final int statusCode = Response.Status.NO_CONTENT.getStatusCode();
    return new CustomMatcher<Response>("no content (" + statusCode + ")") {

        @Override
        public boolean matches(Object o) {
            return (o instanceof Response)
                    && (((Response) o).getStatus() == statusCode);
        }

        @Override
        public void describeMismatch(Object item, Description description) {
            Response response = (Response) item;
            provideDescription(response, description);
        }

    };
}
 
Example 9
Source Project: konker-platform   Source File: ServiceResponseMatchers.java    License: Apache License 2.0 6 votes vote down vote up
public static Matcher<ServiceResponse> isResponseOk() {
    return new BaseMatcher<ServiceResponse>() {
        @Override
        protected boolean matchesSafely(ServiceResponse item) {
            return item.getStatus().equals(ServiceResponse.Status.OK) &&
                   item.getResponseMessages().isEmpty();
        }

        @Override
        public void describeTo(Description description) {
            description.appendText(
                ServiceResponseBuilder.ok().build().toString()
            );
        }
    };
}
 
Example 10
Source Project: onos   Source File: OpenstackPhyInterfaceJsonMatcher.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected boolean matchesSafely(JsonNode jsonNode, Description description) {

    // check network name
    String jsonNetwork = jsonNode.get(NETWORK).asText();
    String network = phyIntf.network();
    if (!jsonNetwork.equals(network)) {
        description.appendText("network name was " + jsonNetwork);
        return false;
    }

    // check interface name
    String jsonIntf = jsonNode.get(INTERFACE).asText();
    String intf = phyIntf.intf();
    if (!jsonIntf.equals(intf)) {
        description.appendText("interface name was " + jsonIntf);
        return false;
    }

    return true;
}
 
Example 11
Source Project: BaldPhone   Source File: SOSActivityTest.java    License: Apache License 2.0 6 votes vote down vote up
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));
        }
    };
}
 
Example 12
Source Project: cukes   Source File: ResponseMatcher.java    License: Apache License 2.0 6 votes vote down vote up
public static Matcher<Response> aHeader(final String header, final Matcher<?> matcher) {
        return new TypeSafeMatcher<Response>() {

            @Override
            protected boolean matchesSafely(Response response) {
                String actualHeaderValue = response.getHeader(header);
                return matcher.matches(actualHeaderValue);
            }

            @Override
            public void describeTo(Description description) {
//                description.appendText("has statusCode").appendDescriptionOf(statusCodeMatches);
            }

            @Override
            protected void describeMismatchSafely(Response item, Description mismatchDescription) {
//                mismatchDescription.appendText("statusCode<").appendValue(item.statusCode()+"").appendText(">");
            }
        };
    }
 
Example 13
Source Project: pushfish-android   Source File: Matchers.java    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
@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");
        }
    };
}
 
Example 14
Source Project: estatio   Source File: DocFragmentRepository_IntegTest.java    License: Apache License 2.0 6 votes vote down vote up
static Matcher<? extends Throwable> causalChainContains(final Class<?> cls) {
    return new TypeSafeMatcher<Throwable>() {
        @Override
        protected boolean matchesSafely(Throwable item) {
            final List<Throwable> causalChain = Throwables.getCausalChain(item);
            for (Throwable throwable : causalChain) {
                if(cls.isAssignableFrom(throwable.getClass())){
                    return true;
                }
            }
            return false;
        }

        @Override
        public void describeTo(Description description) {
            description.appendText("exception with causal chain containing " + cls.getSimpleName());
        }
    };
}
 
Example 15
Source Project: astrix   Source File: AstrixTestUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static <T> Probe serviceInvocationResult(final Supplier<T> serviceInvocation, final Matcher<? super T> matcher) {
	return new Probe() {
		
		private T lastResult;
		private Exception lastException;

		@Override
		public void sample() {
			try {
				this.lastResult = serviceInvocation.get();
			} catch (Exception e) {
				this.lastException = e;
			}
		}
		
		@Override
		public boolean isSatisfied() {
			return matcher.matches(lastResult);
		}
		
		@Override
		public void describeFailureTo(Description description) {
			description.appendText("Expected serviceInovcation to return:\n");
			matcher.describeTo(description);
			if (lastException != null) {
				description.appendText("\nBut last serviceInvocation threw exception:\n" + lastException.toString());
			} else {
				description.appendText("\nBut last serviceInvocation returned:\n" + lastResult);
			}
		}
	};
}
 
Example 16
Source Project: flo   Source File: TaskEvalBehaviorTest.java    License: Apache License 2.0 5 votes vote down vote up
private static <T> Matcher<Iterable<? extends T>> containsInOrder(T a, T b) {
  Objects.requireNonNull(a);
  Objects.requireNonNull(b);
  return new TypeSafeMatcher<Iterable<? extends T>>() {

    @Override
    protected boolean matchesSafely(Iterable<? extends T> ts) {
      int ai = -1, bi = -1, i = 0;
      for (T t : ts) {
        if (a.equals(t)) {
          ai = i;
        }
        if (b.equals(t)) {
          bi = i;
        }
        i++;
      }

      return ai > -1 && bi > -1 && ai < bi;
    }

    @Override
    public void describeTo(Description description) {
      description.appendText("Contains ");
      description.appendValue(a);
      description.appendText(" before ");
      description.appendValue(b);
    }
  };
}
 
Example 17
Source Project: caffeine   Source File: HasStats.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void describeTo(Description description) {
  description.appendText("stats: " + type.name() + "=" + count);
  if ((desc != null) && (description != desc.getDescription())) {
    description.appendText(desc.getDescription().toString());
  }
}
 
Example 18
Source Project: swagger-parser   Source File: RefUtilsTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testReadExternalRef_RelativeFileFormat_ExceptionThrown(@Injectable final List<AuthorizationValue> auths,
                                                                   @Mocked IOUtils ioUtils,
                                                                   @Mocked Files files,
                                                                   @Injectable final Path parentDirectory,
                                                                   @Injectable final Path pathToUse
) throws Exception {
    final String filePath = "file.json";
    File file = tempFolder.newFile(filePath);
    final String expectedResult = "really good json";

    setupRelativeFileExpectations(parentDirectory, pathToUse, file, filePath);

    new StrictExpectations() {{
        IOUtils.toString((FileInputStream) any, UTF_8);
        times = 1;
        result = new IOException();
    }};

    thrown.expect(new BaseMatcher<IOException>() {
        @Override
        public void describeTo(Description description) { }
        @Override
        public boolean matches(Object o) {
            return ((Exception)o).getCause().getClass().equals(IOException.class);
        }
    });
    RefUtils.readExternalRef(filePath, RefFormat.RELATIVE, auths, parentDirectory);
}
 
Example 19
Source Project: pushfish-android   Source File: Matchers.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Factory
public static <T extends CharSequence> Matcher<T> matchesRegexp(final Pattern pattern) {
    return new BaseMatcher<T>() {
        public boolean matches(Object o) {
            return pattern.matcher((CharSequence) o).matches();
        }

        public void describeTo(Description description) {
            description.appendText("a CharSequence that matches regexp ").appendValue(pattern);
        }
    };
}
 
Example 20
Source Project: twitter-kit-android   Source File: TweetAsserts.java    License: Apache License 2.0 5 votes vote down vote up
public static Matcher<View> hasCompoundDrawable(final int start, final int top,
                                                     final int end, final int bottom) {
    return new BoundedMatcher<View, TextView>(TextView.class){
        @Override
        public void describeTo(Description description) {
            final String formatted =
                    String.format(Locale.getDefault(),
                            "has Compound Drawable: start=%d, top=%d, end=%d, bottom=%d",
                            start, top, end, bottom);
            description.appendText(formatted);
        }

        @Override
        public boolean matchesSafely(TextView view) {
            // We cannot verify the actual drawable, but we can verify one has been set.
            final Drawable [] drawables = view.getCompoundDrawables();
            if (drawables[0] != null && start == 0) {
                return false;
            }
            if (drawables[1] != null && top == 0) {
                return false;
            }
            if (drawables[2] != null && end == 0) {
                return false;
            }
            if (drawables[3] != null && bottom == 0) {
                return false;
            }

            return true;
        }
    };
}
 
Example 21
Source Project: beam   Source File: TestUtils.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void describeTo(Description description) {
  description
      .appendText("a KV(")
      .appendValue(keyMatcher)
      .appendText(", ")
      .appendValue(valueMatcher)
      .appendText(")");
}
 
Example 22
Source Project: octarine   Source File: AnInstance.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected boolean matchesSafely(T t, Description description) {
    boolean result = true;
    for (PropertyMatcher<T, ?> pm : matchers) {
        if (!pm.matchesSafely(t, description)) { result = false; }
    }
    return result;
}
 
Example 23
Source Project: astor   Source File: Same.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void describeTo(Description description) {
    description.appendText("same(");
    appendQuoting(description);
    description.appendText(wanted.toString());
    appendQuoting(description);
    description.appendText(")");
}
 
Example 24
Source Project: gocd   Source File: ArtifactsControllerIntegrationTest.java    License: Apache License 2.0 5 votes vote down vote up
private TypeSafeMatcher<File> exists() {
    return new TypeSafeMatcher<File>() {
        @Override
        public boolean matchesSafely(File file) {
            return file.exists();
        }

        @Override
        public void describeTo(Description description) {
            description.appendText("file should exist but does not");
        }
    };
}
 
Example 25
Source Project: android-test   Source File: PreferenceMatchers.java    License: Apache License 2.0 5 votes vote down vote up
public static Matcher<Preference> isEnabled() {
  return new TypeSafeMatcher<Preference>() {
    @Override
    public void describeTo(Description description) {
      description.appendText(" is an enabled preference");
    }

    @Override
    public boolean matchesSafely(Preference pref) {
      return pref.isEnabled();
    }
  };
}
 
Example 26
Source Project: beam   Source File: SerializableCoderTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void coderWarnsForInterface() throws Exception {
  String expectedLogMessage =
      "Can't verify serialized elements of type TestInterface "
          + "have well defined equals method.";
  // Create the coder multiple times ensuring that we only log once.
  SerializableCoder.of(TestInterface.class);
  SerializableCoder.of(TestInterface.class);
  SerializableCoder.of(TestInterface.class);
  expectedLogs.verifyLogRecords(
      new TypeSafeMatcher<Iterable<LogRecord>>() {
        @Override
        public void describeTo(Description description) {
          description.appendText(
              String.format("single warn log message containing [%s]", expectedLogMessage));
        }

        @Override
        protected boolean matchesSafely(Iterable<LogRecord> item) {
          int count = 0;
          for (LogRecord logRecord : item) {
            if (logRecord.getLevel().equals(Level.WARNING)
                && logRecord.getMessage().contains(expectedLogMessage)) {
              count += 1;
            }
          }
          return count == 1;
        }
      });
}
 
Example 27
Source Project: pushfish-android   Source File: Matchers.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * A reimplementation of hamcrest's isA() but without the broken generics.
 */
@Factory
public static Matcher<Object> isA(final Class<?> type) {
    return new BaseMatcher<Object>() {
        public boolean matches(Object item) {
            return type.isInstance(item);
        }

        public void describeTo(Description description) {
            description.appendText("instanceof ").appendValue(type);
        }
    };
}
 
Example 28
Source Project: beam   Source File: LogRecordMatcher.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void describeMismatchSafely(LogRecord item, Description description) {
  description
      .appendText("was log with message \"")
      .appendText(item.getMessage())
      .appendText("\" at severity ")
      .appendValue(item.getLevel());
}
 
Example 29
Source Project: fdb-record-layer   Source File: InParameterJoinMatcher.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void describeTo(Description description) {
    description.appendText("In(binding=\"");
    bindingMatcher.describeTo(description);
    description.appendText("\"; ");
    super.describeTo(description);
    description.appendText(")");
}
 
Example 30
Source Project: onos   Source File: MappingValueCodecTest.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected boolean matchesSafely(JsonNode jsonNode, Description description) {

    // check mapping treatments
    final JsonNode jsonTreatments = jsonNode.get(TREATMENTS);
    if (mappingValue.treatments().size() != jsonTreatments.size()) {
        description.appendText("mapping treatments array size of " +
                Integer.toString(mappingValue.treatments().size()));
        return false;
    }

    for (final MappingTreatment treatment : mappingValue.treatments()) {
        boolean treatmentFound = false;
        for (int treatmentIdx = 0; treatmentIdx < jsonTreatments.size();
                treatmentIdx++) {
            final String jsonAddress =
                    jsonTreatments.get(treatmentIdx).get(ADDRESS)
                            .get(MappingAddressCodec.IPV4).textValue();
            final String address = treatment.address().toString();
            if (address.contains(jsonAddress)) {
                treatmentFound = true;
            }
        }

        if (!treatmentFound) {
            description.appendText("mapping treatment " + treatment.toString());
            return false;
        }
    }

    // check mapping action
    final JsonNode jsonActionNode = jsonNode.get(MappingValueCodec.ACTION);

    assertThat(jsonActionNode, MappingActionJsonMatcher.matchesAction(mappingValue.action()));

    return true;
}