Пример #1
0
 @Test
 public void shouldDescribeMismatchOfInvalidJson() {
   Matcher<Object> matcher = isJson(withPathEvaluatedTo(true));
   Description description = new StringDescription();
   matcher.describeMismatch("invalid-json", description);
   assertThat(description.toString(), containsString("\"invalid-json\""));
 }
Пример #2
0
 @Test
 public void shouldDescribeMismatchOfValidJson() {
   Matcher<Object> matcher = isJson(withPathEvaluatedTo(true));
   Description description = new StringDescription();
   matcher.describeMismatch(BOOKS_JSON_STRING, description);
   assertThat(description.toString(), containsString(TestingMatchers.MISMATCHED_TEXT));
 }
 @Test
 public void should_obtain_instanciated_matcher_from_matcher() {
   Matcher<Object> matcher =
       ((BeanFieldMatcher) BeanMatchers.the("firstName", is("Bill"))).getMatcher();
   Person person = new Person("Bill", "Oddie");
   assertThat(matcher.matches(person)).isTrue();
 }
Пример #4
0
  @Override
  protected void describeMismatchSafely(T[] item, Description mismatchDescription) {
    Matches<T> matches = new Matches<>();

    Iterator<Matcher<T>> elementIterator = elements.iterator();
    Iterator<? extends T> itemIterator = asList(item).iterator();
    while (elementIterator.hasNext() && itemIterator.hasNext()) {
      Matcher<T> matcher = elementIterator.next();
      T element = itemIterator.next();
      if (!matcher.matches(element)) {
        matches.mismatch(matcher, element);
      } else {
        matches.match();
      }
    }
    if (elementIterator.hasNext()) {
      int count = count(elementIterator);
      matches.mismatch("missing " + count + " elements");
    }
    if (itemIterator.hasNext()) {
      List<T> items = collect(itemIterator);
      matches.mismatch("found " + items.size() + " elements surplus " + toDescriptionSet(items));
    }

    if (matches.containsMismatches()) {
      mismatchDescription.appendText("mismatching elements ").appendDescriptionOf(matches);
    }
  }
Пример #5
0
 @Override
 public boolean matches(Object item) {
   for (Matcher m : matchers) {
     if (!m.matches(item)) return false;
   }
   return true;
 }
 @Override
 public void describeTo(Description description) {
   description.appendText("a Complex number having ");
   reMatcher.describeTo(description);
   description.appendText(" as real part and ");
   imMatcher.describeTo(description);
   description.appendText(" as imaginary part");
 }
Пример #7
0
 @Test
 public void shouldBeDescriptive() {
   Matcher<Object> matcher = isJson(withPathEvaluatedTo(true));
   Description description = new StringDescription();
   matcher.describeTo(description);
   assertThat(description.toString(), startsWith("is json"));
   assertThat(description.toString(), containsString(TestingMatchers.MATCH_TRUE_TEXT));
 }
Пример #8
0
 private Matcher<T> bestMatcher() {
   for (Matcher<T> matcher : elements) {
     if (matcher.getClass() != IsNull.class) {
       return matcher;
     }
   }
   return equalTo(null);
 }
 @Theory
 @SuppressWarnings({"unchecked", "rawtypes"})
 public void differentMatchersHaveDifferentDescriptions(
     Matcher matcher1, Matcher matcher2, Object value) {
   assumeThat(value, matcher1);
   assumeThat(value, not(matcher2));
   assertThat(matcher1.toString(), not(matcher2.toString()));
 }
Пример #10
0
 @Override
 public void describeMismatch(Object item, Description description) {
   if (!containsAll.matches(item)) {
     containsAll.describeMismatch(item, description);
   }
   if (!containsOnly.matches(item)) {
     containsOnly.describeMismatch(item, description);
   }
 }
Пример #11
0
 /**
  * Returns a current wizard page
  *
  * @return current wizard page
  * @deprecated use getCurrentWizardPage() instead
  */
 public WizardPage getWizardPage() {
   for (WizardPage wizardPage : wizardPageMap.keySet()) {
     Matcher<WizardDialog> matcher = wizardPageMap.get(wizardPage);
     if (matcher.matches(this)) {
       return wizardPage;
     }
   }
   log.warn("No wizard page found in page index '" + currentPage + "'");
   return null;
 }
Пример #12
0
 /** {@inheritDoc} */
 @SuppressWarnings("unchecked")
 public <T> JsonAsserter assertThat(String path, Matcher<T> matcher, String message) {
   T obj = JsonPath.<T>read(jsonObject, path);
   if (!matcher.matches(obj)) {
     throw new AssertionError(
         String.format(
             "JSON Assert Error: %s\nExpected:\n%s\nActual:\n%s",
             message, matcher.toString(), obj));
   }
   return this;
 }
 public void processItems(Iterable<? extends F> iterable) {
   for (F item : iterable) {
     if (nextMatchIx < matchers.size()) {
       Matcher<? super F> matcher = matchers.get(nextMatchIx);
       if (matcher.matches(item)) {
         lastMatchedItem = item;
         nextMatchIx++;
       }
     }
   }
 }
Пример #14
0
  public void testEvaluatesToTrueIfArgumentIsEqualToADoubleValueWithinSomeError() {
    Matcher<Double> p = closeTo(1.0, 0.5);

    assertTrue(p.matches(1.0));
    assertTrue(p.matches(0.5d));
    assertTrue(p.matches(1.5d));

    assertDoesNotMatch("too large", p, 2.0);
    assertMismatchDescription("<2.0> differed by <0.5>", p, 2.0);
    assertDoesNotMatch("number too small", p, 0.0);
    assertMismatchDescription("<0.0> differed by <0.5>", p, 0.0);
  }
Пример #15
0
 @Test
 public void assertThatSmallGraphIsDescribable() {
   Graph graph1 = makeSmallGraph("A");
   Matcher<? super Graph> matcher = deeplyEqualTo(graph1);
   StringDescription description = new StringDescription();
   matcher.describeTo(description);
   assertThat(
       description.toString(),
       allOf(
           startsWith("{" + System.getProperty("line.separator") + "  nodes ["),
           containsString("value is <"),
           containsString("neighbors ["),
           containsString("&Node<A-1>")));
 }
Пример #16
0
  @Override
  public boolean matches(Object item) {
    try {
      if (item == null) {
        return matchingError("Guice injector is null");
      }

      if (!Injector.class.isAssignableFrom(item.getClass())) {
        return matchingError("Object " + item + " is not a Guice Injector");
      }

      T instance = ((Injector) item).getInstance(typeKey);

      if (instance == null) {
        return matchingError("Instance " + typeKey + " is null");
      }

      Class<?> instanceClass = instance.getClass();
      if (!expectedType.isAssignableFrom(instanceClass)) {
        return matchingError(
            "Instance "
                + typeKey
                + " type mismatch: expected "
                + expectedType
                + " but was "
                + ""
                + instanceClass);
      }

      if (!instanceMatcher.matches(instance)) {
        matcherDescription = new StringDescription();
        matcherDescription.appendText(
            "Instance " + typeKey + " does not match " + "expectations: ");
        instanceMatcher.describeMismatch(item, matcherDescription);
        return false;
      } else {
        return true;
      }
    } catch (ConfigurationException | ProvisionException ex) {
      return matchingError(
          "Cannot get instance of "
              + typeKey
              + " from Guice Injector\n"
              + ex.getMessage()
              + "\n\n"
              + "Error stack trace: \n"
              + "-------------------\n"
              + getStackTrace(ex));
    }
  }
Пример #17
0
  private boolean tryExtractPropertyValueFrom(Object bean) {
    ExpressionParser parser = new SpelExpressionParser();
    Expression exp = parser.parseExpression(propertyName);
    beanPropertyValue = exp.getValue(bean);

    return valueMatcher.matches(beanPropertyValue);
  }
Пример #18
0
 /**
  * Allows matching arguments with hamcrest matchers.
  *
  * <p>See examples in javadoc for {@link MockitoHamcrest} class
  *
  * @param matcher decides whether argument matches
  * @return <code>null</code> or default value for primitive (0, false, etc.)
  * @since 2.0
  */
 public static <T> T argThat(Matcher<T> matcher) {
   return (T)
       MOCKING_PROGRESS
           .getArgumentMatcherStorage()
           .reportMatcher(new HamcrestArgumentMatcher(matcher))
           .returnFor(MatcherGenericTypeExtractor.genericTypeOfMatcher(matcher.getClass()));
 }
Пример #19
0
  /**
   * Waits for specified time period for a shell matching specified matcher.
   *
   * @param matcher matcher to match shell
   * @param timePeriod time period to wait for
   * @return shell matching specified matcher
   */
  public Shell getShell(final Matcher<String> matcher, TimePeriod timePeriod) {
    if (!timePeriod.equals(TimePeriod.NONE)) {
      new WaitUntil(new ShellMatchingMatcherIsAvailable(matcher), timePeriod, false);
    }

    Shell[] shells =
        Display.syncExec(
            new ResultRunnable<Shell[]>() {

              @Override
              public Shell[] run() {
                return Display.getDisplay().getShells();
              }
            });

    for (final Shell s : shells) {
      if (matcher.matches(s)) {
        Shell visibleShell =
            Display.syncExec(
                new ResultRunnable<Shell>() {
                  @Override
                  public Shell run() {
                    if (!s.isDisposed() && s.isVisible()) {
                      return s;
                    }
                    return null;
                  }
                });
        if (visibleShell != null) {
          return visibleShell;
        }
      }
    }
    return null;
  }
Пример #20
0
  @Override
  protected boolean matchesSafely(T[] item) {
    if (item.length != elements.size()) {
      return false;
    }

    Iterator<Matcher<T>> elementIterator = elements.iterator();
    Iterator<? extends T> itemIterator = Arrays.asList(item).iterator();
    while (elementIterator.hasNext() && itemIterator.hasNext()) {
      Matcher<T> matcher = elementIterator.next();
      T element = itemIterator.next();
      if (!matcher.matches(element)) {
        return false;
      }
    }
    return true;
  }
Пример #21
0
 @Override
 protected boolean matchesSafely(File item) {
   if (directoryMatcher.matches(item)) {
     return fileMatcher.matches(files(item));
   } else {
     mismatch = directoryMatcher;
     return false;
   }
 }
Пример #22
0
 static void fail(@Nullable Object actualValue, Matcher<?> matcher) {
   Description description =
       new StringDescription()
           .appendText("\nExpected: ")
           .appendDescriptionOf(matcher)
           .appendText("\n     but: ");
   matcher.describeMismatch(actualValue, description);
   AssertionError assertionError = new AssertionError(description.toString());
   assertionError.setStackTrace(ObjectChecker.trimStackTrace(assertionError.getStackTrace()));
   throw assertionError;
 }
 private static <T extends AccessibilityCheckResult> void modifyResultType(
     List<T> results, Matcher<? super T> matcher, AccessibilityCheckResultType newType) {
   if (results == null || matcher == null) {
     return;
   }
   for (T result : results) {
     if (matcher.matches(result)) {
       result.setType(newType);
     }
   }
 }
Пример #24
0
 /**
  * Create Workbench ToolItem matching given toolTip matcher
  *
  * @param matcher
  */
 public WorkbenchToolItem(Matcher<String> toolTipMatcher) {
   ToolBarLookup tl = new ToolBarLookup();
   ToolBar[] workbenchToolBars = tl.getWorkbenchToolBars();
   ToolItem ti = null;
   for (ToolBar t : workbenchToolBars) {
     ti = tl.getToolItem(t, toolTipMatcher);
     if (ti != null) break;
   }
   Thrower.objectIsNull(ti, "ToolItem matching " + toolTipMatcher.toString() + " cannot be found");
   toolItem = ti;
 }
 @Override
 public boolean test() {
   items = table.getItems();
   for (TableItem item : items) {
     if (!item.getSWTWidget().isDisposed() && matcher.matches(item.getText())) {
       item.select();
       return true;
     }
   }
   return false;
 }
Пример #26
0
 @Override
 protected boolean matches(Object item, Description mismatchDescription) {
   FileSink fs = (FileSink) item;
   try {
     String contents = fs.getContents();
     mismatchDescription.appendValue(contents);
     return matcher.matches(contents);
   } catch (IOException e) {
     mismatchDescription.appendText("failed with an IOException: " + e.getMessage());
     return false;
   }
 }
  final String createErrorMessage(final Throwable thrown) {
    final StringBuilder msg = new StringBuilder(128);

    if (hasNullMessage(thrown)) msg.append(beforeNullActual);
    else msg.append(beforeActual).append(getActualMessage(thrown)).append(afterActual);
    msg.append(beforeExpected);

    final Matcher expectedMatcher = getExpectedMatcher();

    if (expectedMatcher != null) {
      final int insertAt = msg.length();
      final String shouldStartWith = expectedMatcherPrefix;
      final boolean[] startsThat = {false};

      expectedMatcher.describeTo(
          new BaseDescription() {
            private int i, upTo = shouldStartWith.length();

            @Override
            protected void append(char c) {
              if (i < upTo && (i == 0 || startsThat[0]))
                startsThat[0] = c == shouldStartWith.charAt(i);
              ++i;
              msg.append(c);
            }

            @Override
            public String toString() {
              return msg.toString();
            }
          });

      if (!startsThat[0]) msg.insert(insertAt, shouldStartWith);

    } else msg.append(getExpectedMessage());

    msg.append(afterExpected);

    return msg.toString();
  }
Пример #28
0
 private static MenuItem show(final Menu menu, final Matcher<?> matcher) {
   if (menu != null) {
     menu.notifyListeners(SWT.Show, new Event());
     MenuItem[] items = menu.getItems();
     for (final MenuItem menuItem : items) {
       if (matcher.matches(menuItem)) {
         return menuItem;
       }
     }
     menu.notifyListeners(SWT.Hide, new Event());
   }
   return null;
 }
 private void assertValues(
     final MimeRulesSource mimeRulesSource,
     final String path,
     final Matcher<? super String> matcher) {
   MimeRule nexusMimeType = mimeRulesSource.getRuleForName(path);
   if (matcher.getClass().equals(nullValue().getClass())) {
     assertThat(nexusMimeType, nullValue());
     return;
   }
   assertThat(nexusMimeType, notNullValue());
   assertThat(nexusMimeType.getMimetypes(), hasSize(1));
   assertThat(nexusMimeType.getMimetypes().get(0), matcher);
 }
 @Override
 public String description() {
   StringBuffer message = new StringBuffer();
   message.append("an item matching ").append(matcher.toString()).append(" in\n");
   for (TableItem item : items) {
     String text = null;
     if (!item.getSWTWidget().isDisposed()) {
       text = item.getText();
     }
     message.append("\t").append(text).append("\n");
   }
   return message.toString();
 }