Java Code Examples for org.hamcrest.Matcher#matches()

The following examples show how to use org.hamcrest.Matcher#matches() . 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 check out the related API usage on the sidebar.
Example 1
Source File: SchemaV4Validator.java    From JustJson with Apache License 2.0 6 votes vote down vote up
@Override
protected boolean doValidate(JsonElement el, StringBuilder sb) {
    //System.out.println("SchemaV4Validator start: " + this.getTitle());
    //check if empty schema
    if(allMatchers == null || allMatchers.isEmpty()) {
        System.out.println("SchemaV4Validator NO MATCHERS end: " + this.getTitle());
        return true;
    }

    Matcher<JsonElement> matcher = allOf(allMatchers);
    //System.out.println("SchemaV4Validator end: " + this.getTitle());
   if(sb!=null) {
       matcher.describeMismatch(el, new StringDescription(sb));
   }
    return matcher.matches(el);
}
 
Example 2
Source File: ComponentHostMatchers.java    From litho with Apache License 2.0 6 votes vote down vote up
/**
 * Matches a view that is a ComponentHost that matches subMatcher.
 *
 * <p>In Espresso tests, when you need to match a View, we recommend using this matcher and nest
 * any of the other matchers in this class along with it. For example <code>
 * componentHost(withText("foobar"))</code> or <code>
 * componentHost(withContentDescription("foobar"))</code>.
 *
 * <p>While it's definitely possible to use Espresso's ViewMatchers directly to match
 * ComponentHosts, using these methods ensure that we can handle weirdness in the view hierarchy
 * that comes from the component stack.
 */
public static Matcher<View> componentHost(final Matcher<? extends ComponentHost> subMatcher) {
  return new BaseMatcher<View>() {
    @Override
    public boolean matches(Object item) {
      if (!(item instanceof ComponentHost)) {
        return false;
      }

      return subMatcher.matches((ComponentHost) item);
    }

    @Override
    public void describeTo(Description description) {
      description.appendText("Expected to be a ComponentHost matching: ");
      subMatcher.describeTo(description);
    }
  };
}
 
Example 3
Source File: MainActivityTest.java    From Android-Developer-Fundamentals-Version-2 with 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 File: RollingAppenderTimeTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testAppender() throws Exception {
    final Logger logger = loggerContextRule.getLogger();
    logger.debug("This is test message number 1");
    Thread.sleep(1500);
    // Trigger the rollover
    for (int i = 0; i < 16; ++i) {
        logger.debug("This is test message number " + i + 1);
    }
    final File dir = new File(DIR);
    assertTrue("Directory not created", dir.exists() && dir.listFiles().length > 0);

    final int MAX_TRIES = 20;
    final Matcher<File[]> hasGzippedFile = hasItemInArray(that(hasName(that(endsWith(".gz")))));
    for (int i = 0; i < MAX_TRIES; i++) {
        final File[] files = dir.listFiles();
        if (hasGzippedFile.matches(files)) {
            return; // test succeeded
        }
        logger.debug("Adding additional event " + i);
        Thread.sleep(100); // Allow time for rollover to complete
    }
    fail("No compressed files found");
}
 
Example 5
Source File: ComponentHostMatchers.java    From litho with Apache License 2.0 6 votes vote down vote up
public static Matcher<ComponentHost> withText(final Matcher<String> textMatcher) {
  return new BaseMatcher<ComponentHost>() {
    @Override
    public boolean matches(Object item) {
      if (!(item instanceof ComponentHost)) {
        return false;
      }

      ComponentHost host = (ComponentHost) item;
      for (CharSequence foundText : host.getTextContent().getTextItems()) {
        if (foundText != null && textMatcher.matches(foundText.toString())) {
          return true;
        }
      }

      return false;
    }

    @Override
    public void describeTo(Description description) {
      description.appendText("ComponentHost should have text that matches: ");
      textMatcher.describeTo(description);
    }
  };
}
 
Example 6
Source File: UriMatchers.java    From android-test with Apache License 2.0 6 votes vote down vote up
public static Matcher<Uri> hasPath(final Matcher<String> pathName) {
  checkNotNull(pathName);

  return new TypeSafeMatcher<Uri>() {

    @Override
    public boolean matchesSafely(Uri uri) {
      return pathName.matches(uri.getPath());
    }

    @Override
    public void describeTo(Description description) {
      description.appendText("has path: ");
      description.appendDescriptionOf(pathName);
    }
  };
}
 
Example 7
Source File: AccessibilityCheckResultBaseUtils.java    From Accessibility-Test-Framework-for-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a {@link Matcher} for an {@link AccessibilityCheckResult} whose source check class has
 * a simple name that matches the given matcher for a {@code String}. If a BiMap of class aliases
 * is provided, it can also match a class paired with the source check class in the BiMap.
 *
 * @param classNameMatcher a {@code Matcher} for a {@code String}
 * @return a {@code Matcher} for an {@code AccessibilityCheckResult}
 */
static Matcher<AccessibilityCheckResult> matchesCheckNames(
    final Matcher<? super String> classNameMatcher,
    final @Nullable ImmutableBiMap<?, ?> aliases) {
  return new TypeSafeMemberMatcher<AccessibilityCheckResult>(
      "source check name", classNameMatcher) {
    @Override
    public boolean matchesSafely(AccessibilityCheckResult result) {
      Class<? extends AccessibilityCheck> checkClass = result.getSourceCheckClass();
      if (classNameMatcher.matches(checkClass.getSimpleName())) {
        return true;
      }
      Object alias = getAlias(checkClass, aliases);
      return (alias instanceof Class)
          && classNameMatcher.matches(((Class<?>) alias).getSimpleName());
    }
  };
}
 
Example 8
Source File: TestFile.java    From pushfish-android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public List<String> linesThat(Matcher<? super String> matcher) {
    try {
        BufferedReader reader = new BufferedReader(new FileReader(this));
        try {
            List<String> lines = new ArrayList<String>();
            String line;
            while ((line = reader.readLine()) != null) {
                if (matcher.matches(line)) {
                    lines.add(line);
                }
            }
            return lines;
        } finally {
            reader.close();
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 9
Source File: HintMatcher.java    From testing-cin with MIT License 6 votes vote down vote up
static Matcher<View> withHint(final Matcher<String> stringMatcher) {
    checkNotNull(stringMatcher);
    return new BoundedMatcher<View, EditText>(EditText.class) {

        @Override
        public boolean matchesSafely(EditText view) {
            final CharSequence hint = view.getHint();
            return hint != null && stringMatcher.matches(hint.toString());
        }

        @Override
        public void describeTo(Description description) {
            description.appendText("with hint: ");
            stringMatcher.describeTo(description);
        }
    };
}
 
Example 10
Source File: ResponseMatcher.java    From cukes with Apache License 2.0 6 votes vote down vote up
public static Matcher<Response> aStatusCode(final Matcher<Integer> statusCodeMatches) {
    return new TypeSafeMatcher<Response>() {

        @Override
        protected boolean matchesSafely(Response response) {
            return statusCodeMatches.matches(response.statusCode());
        }

        @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 11
Source File: DescriptiveSoftAssert.java    From vividus with Apache License 2.0 6 votes vote down vote up
@Override
public <T> boolean assertThat(String businessDescription, String systemDescription, T actual,
        Matcher<? super T> matcher)
{
    boolean isMatches = matcher.matches(actual);
    if (!isMatches)
    {
        String assertionDescription = getAssertionDescriptionString(actual, matcher);
        return recordAssertion(format(businessDescription, assertionDescription),
                format(systemDescription, assertionDescription), isMatches);
    }
    StringDescription description = new StringDescription();
    matcher.describeTo(description);
    String matchedString = description.toString();
    return recordAssertion(businessDescription + StringUtils.SPACE + matchedString,
            systemDescription + StringUtils.SPACE + matchedString, isMatches);
}
 
Example 12
Source File: VerificationModes.java    From android-test with Apache License 2.0 5 votes vote down vote up
@Override
public void verify(Matcher<Intent> matcher, List<VerifiableIntent> recordedIntents) {
  List<VerifiableIntent> unverifiedIntents = new ArrayList<VerifiableIntent>();
  for (VerifiableIntent verifiableIntent : recordedIntents) {
    if (matcher.matches(verifiableIntent.getIntent()) && !verifiableIntent.hasBeenVerified()) {
      unverifiedIntents.add(verifiableIntent);
    }
  }
  if (!unverifiedIntents.isEmpty()) {
    fail(
        String.format(
            "Found unverified intents.\n\nUnverified intents:%s\n\nRecorded intents:%s",
            joinOnDash(unverifiedIntents), joinOnDash(recordedIntents)));
  }
}
 
Example 13
Source File: FanOutRecordsPublisherTest.java    From amazon-kinesis-client with Apache License 2.0 5 votes vote down vote up
private <T> boolean matchAndDescribe(Matcher<T> matcher, T value, String field,
        Description mismatchDescription) {
    if (!matcher.matches(value)) {
        mismatchDescription.appendText(field).appendText(": ");
        matcher.describeMismatch(value, mismatchDescription);
        return false;
    }
    return true;
}
 
Example 14
Source File: AlertActions.java    From vividus with Apache License 2.0 5 votes vote down vote up
@Override
public void processAlert(Matcher<String> matcher, Action action)
{
    Alert alert = switchToAlert(webDriverProvider.get());
    if (alert != null && matcher.matches(alert.getText()))
    {
        action.process(alert, webDriverManager);
    }
}
 
Example 15
Source File: EqualsMap.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
protected boolean matchesMatchers(Object argument) {
  if (argument == null) {
    return false;
  }

  Map<String, Object> argumentMap = (Map<String, Object>) argument;

  boolean containSameKeys = matchers.keySet().containsAll(argumentMap.keySet()) &&
      argumentMap.keySet().containsAll(matchers.keySet());
  if (!containSameKeys) {
    return false;
  }

  for (String key : argumentMap.keySet()) {
    Matcher<?> matcher = matchers.get(key);
    Object value = null;
    if (argumentMap instanceof VariableMap) {
      VariableMap varMap = (VariableMap) argumentMap;
      value = varMap.getValueTyped(key);
    }
    else {
      value = argumentMap.get(key);
    }
    if (!matcher.matches(value)) {
      return false;
    }
  }


  return true;
}
 
Example 16
Source File: SwtBotTreeUtilities.java    From google-cloud-eclipse with Apache License 2.0 5 votes vote down vote up
/**
 * Wait until the given tree item has a matching item, and return the item.
 *
 * @throws TimeoutException if no items appear within the default timeout
 */
public static SWTBotTreeItem getMatchingNode(
    SWTWorkbenchBot bot, SWTBotTreeItem parentItem, Matcher<String> childMatcher) {
  bot.waitUntil(
      new DefaultCondition() {
        @Override
        public String getFailureMessage() {
          return "Child item never appeared";
        }

        @Override
        public boolean test() throws Exception {
          SWTBotTreeItem[] children = parentItem.getItems();
          if (children.length == 1 && "".equals(children[0].getText())) {
            // Work around odd bug seen only on Windows and Linux.
            // https://github.com/GoogleCloudPlatform/google-cloud-eclipse/issues/2569
            parentItem.collapse();
            parentItem.expand();
            children = parentItem.getItems();
          }
          return Iterables.any(parentItem.getNodes(), childMatcher::matches);
        }
      });
  for (SWTBotTreeItem child : parentItem.getItems()) {
    if (childMatcher.matches(child.getText())) {
      return child;
    }
  }
  throw new AssertionError("Child no longer present!");
}
 
Example 17
Source File: ArgumentsComparator.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
private boolean varArgsMatch(InvocationMatcher invocationMatcher, Invocation actual) {
    if (!actual.getMethod().isVarArgs()) {
        //if the method is not vararg forget about it
        return false;
    }

    //we must use raw arguments, not arguments...
    Object[] rawArgs = actual.getRawArguments();
    List<Matcher> matchers = invocationMatcher.getMatchers();

    if (rawArgs.length != matchers.size()) {
        return false;
    }

    for (int i = 0; i < rawArgs.length; i++) {
        Matcher m = matchers.get(i);
        //it's a vararg because it's the last array in the arg list
        if (rawArgs[i] != null && rawArgs[i].getClass().isArray() && i == rawArgs.length-1) {
            Matcher actualMatcher;
            //this is necessary as the framework often decorates matchers
            if (m instanceof MatcherDecorator) {
                actualMatcher = ((MatcherDecorator)m).getActualMatcher();
            } else {
                actualMatcher = m;
            }
            //this is very important to only allow VarargMatchers here. If you're not sure why remove it and run all tests.
            if (!(actualMatcher instanceof VarargMatcher) || !actualMatcher.matches(rawArgs[i])) {
                return false;
            }
        //it's not a vararg (i.e. some ordinary argument before varargs), just do the ordinary check
        } else if (!m.matches(rawArgs[i])){
            return false;
        }
    }

    return true;
}
 
Example 18
Source File: EspressoTestUtils.java    From Equate with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Note that ideal the method below should implement a describeMismatch
 * method (as used by BaseMatcher), but this method is not invoked by
 * ViewAssertions.matches() and it won't get called. This means that I'm not
 * sure how to implement a custom error message.
 */
private static Matcher<View> expressionEquals(final Matcher<String> testString) {
	return new BoundedMatcher<View, EditText>(EditText.class) {
		@Override
		public void describeTo(Description description) {
			description.appendText("with expression text: " + testString);
		}

		@Override
		protected boolean matchesSafely(EditText item) {
			return testString.matches(item.getText().toString());
		}
	};
}
 
Example 19
Source File: VertxMatcherAssert.java    From vertx-rest-client with Apache License 2.0 5 votes vote down vote up
public static <T> void assertThat(TestContext context, String reason,
                                  T actual, Matcher<? super T> matcher) {
    if (!matcher.matches(actual)) {
        Description description = new StringDescription();
        description.appendText(reason)
                .appendText("\nExpected: ")
                .appendDescriptionOf(matcher)
                .appendText("\n     but: ");
        matcher.describeMismatch(actual, description);
        context.fail(description.toString());
    }
}
 
Example 20
Source File: Matchers.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Factory
public static Matcher<Throwable> hasMessage(final Matcher<String> matcher) {
    return new BaseMatcher<Throwable>() {
        public boolean matches(Object o) {
            Throwable t = (Throwable) o;
            return matcher.matches(t.getMessage());
        }

        public void describeTo(Description description) {
            description.appendText("an exception with message that is ").appendDescriptionOf(matcher);
        }
    };
}