Java Code Examples for org.hamcrest.BaseMatcher

The following examples show how to use org.hamcrest.BaseMatcher. 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 check out the related API usage on the sidebar.
Example 1
Source Project: Quicksql   Source File: TypeFinderTest.java    License: MIT License 6 votes vote down vote up
private void assertTypeContains(List<Type> expectedTypes, List<Node> nodes) {
  final HashSet<Type> types = new HashSet<>();
  final EnumerableRelImplementor.TypeFinder typeFinder =
      new EnumerableRelImplementor.TypeFinder(types);
  for (Node node : nodes) {
    node.accept(typeFinder);
  }
  Assert.assertThat(types, new BaseMatcher<HashSet<Type>>() {
    @Override public boolean matches(Object o) {
      final Set<Type> actual = (HashSet<Type>) o;
      return actual.containsAll(expectedTypes);
    }

    @Override public void describeTo(Description description) {
      description.appendText("Expected a set of types containing all of: ")
          .appendText(Objects.toString(expectedTypes));
    }
  });
}
 
Example 2
Source Project: Quicksql   Source File: SqlJsonFunctionsTest.java    License: MIT License 6 votes vote down vote up
private Matcher<? super Throwable> errorMatches(Throwable expected) {
  return new BaseMatcher<Throwable>() {
    @Override public boolean matches(Object item) {
      if (!(item instanceof Throwable)) {
        return false;
      }
      Throwable error = (Throwable) item;
      return expected != null
          && Objects.equals(error.getClass(), expected.getClass())
          && Objects.equals(error.getMessage(), expected.getMessage());
    }

    @Override public void describeTo(Description description) {
      description.appendText("is ").appendText(expected.toString());
    }
  };
}
 
Example 3
Source Project: Quicksql   Source File: SqlJsonFunctionsTest.java    License: MIT License 6 votes vote down vote up
@Nonnull private BaseMatcher<JsonFunctions.JsonPathContext> contextMatches(
    JsonFunctions.JsonPathContext expected) {
  return new BaseMatcher<JsonFunctions.JsonPathContext>() {
    @Override public boolean matches(Object item) {
      if (!(item instanceof JsonFunctions.JsonPathContext)) {
        return false;
      }
      JsonFunctions.JsonPathContext context = (JsonFunctions.JsonPathContext) item;
      if (Objects.equals(context.mode, expected.mode)
          && Objects.equals(context.obj, expected.obj)) {
        if (context.exc == null && expected.exc == null) {
          return true;
        }
        return context.exc != null && expected.exc != null
            && Objects.equals(context.exc.getClass(), expected.exc.getClass())
            && Objects.equals(context.exc.getMessage(), expected.exc.getMessage());
      }
      return false;
    }

    @Override public void describeTo(Description description) {
      description.appendText("is ").appendText(expected.toString());
    }
  };
}
 
Example 4
Source Project: kylin-on-parquet-v2   Source File: CubeMetaIngesterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testBadIngest() {
    thrown.expect(RuntimeException.class);

    //should not break at table duplicate check, should fail at model duplicate check
    thrown.expectCause(new BaseMatcher<Throwable>() {
        @Override
        public boolean matches(Object item) {
            if (item instanceof IllegalStateException) {
                if (((IllegalStateException) item).getMessage().equals("Already exist a model called test_kylin_inner_join_model_desc")) {
                    return true;
                }
            }
            return false;
        }

        @Override
        public void describeTo(Description description) {
        }
    });

    String srcPath = this.getClass().getResource("/cloned_cube_meta.zip").getPath();
    CubeMetaIngester.main(new String[] { "-project", "default", "-srcPath", srcPath });
}
 
Example 5
Source Project: java-technology-stack   Source File: Matchers.java    License: MIT License 6 votes vote down vote up
/**
 * 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);
		}
	};
}
 
Example 6
Source Project: servicetalk   Source File: SequentialSubscriptionTest.java    License: Apache License 2.0 6 votes vote down vote up
private static Matcher<? super CountingSubscription> matchValueOrCancelled(
        Matcher<? super Long> valueMatcher) {
    return new BaseMatcher<CountingSubscription>() {
        @Override
        public void describeTo(final Description description) {
            valueMatcher.describeTo(description);
            description.appendText(" or not cancelled.");
        }

        @Override
        public boolean matches(final Object o) {
            if (!(o instanceof CountingSubscription)) {
                return false;
            }
            CountingSubscription s = (CountingSubscription) o;
            return valueMatcher.matches(s.requestedReceived()) || s.isCancelled();
        }
    };
}
 
Example 7
Source Project: dsl-devkit   Source File: SwtWorkbenchBot.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Returns the first {@link SWTBotLabel} with the given text, or {@code null} if none was found.
 *
 * @param text
 *          the label text
 * @return the first {@link SWTBotLabel} with the given text, or {@code null} if none was found
 */
public SWTBotLabel getLabel(final String text) {
  List<Label> labels = finder.findControls(new BaseMatcher<Label>() {
    @Override
    public boolean matches(final Object item) {
      return item instanceof Label && ((Label) item).getText().equals(text);
    }

    @Override
    public void describeTo(final Description description) {}
  });
  if (labels.isEmpty()) {
    return null;
  } else {
    return new SWTBotLabel(labels.get(0));
  }
}
 
Example 8
Source Project: pushfish-android   Source File: Matchers.java    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
@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);
        }
    };
}
 
Example 9
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 10
Source Project: pushfish-android   Source File: Matchers.java    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
@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);
        }
    };
}
 
Example 11
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 12
public String toString() {
  if (invalidMatcherList.isEmpty()) {
    String validMatchers =
        featureMatcherList.stream()
            .map(Pair::getLeft)
            .map(BaseMatcher::toString)
            .collect(Collectors.joining(","));

    return "All matchers suceeded: " + validMatchers;
  }

  Description description = new StringDescription();
  // result.append("A ClientCall with the following properties:");
  for (Pair<FeatureMatcher, Object> pair : invalidMatcherList) {
    FeatureMatcher invalidMatcher = pair.getLeft();

    description.appendText("Expecting '");
    invalidMatcher.describeTo(description);
    description.appendText("', but got values:").appendValue(pair.getRight());
  }

  return description.toString();
}
 
Example 13
Source Project: litho   Source File: ComponentHostMatchers.java    License: 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 14
Source Project: litho   Source File: ComponentHostMatchers.java    License: 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 15
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);
		}

	};
}
 
Example 16
Source Project: dsl-devkit   Source File: ShellUiTestUtil.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Tests if a shell with a specific type of data contained (e.g. Window).
 * 
 * @param bot
 *          to use
 * @param clazz
 *          class of data contained to check for
 */
@SuppressWarnings("rawtypes")
public static void assertShellWithDataTypeVisible(final SWTWorkbenchBot bot, final Class clazz) {
  bot.waitUntil(Conditions.waitForShell(new BaseMatcher<Shell>() {
    @SuppressWarnings("unchecked")
    public boolean matches(final Object item) {
      return UIThreadRunnable.syncExec(new Result<Boolean>() {
        public Boolean run() {
          if (item instanceof Shell) {
            Object shellData = ((Shell) item).getData();
            if (shellData != null) {
              return clazz.isAssignableFrom(shellData.getClass());
            }
          }
          return false;
        }
      });
    }

    public void describeTo(final Description description) {
      description.appendText("Shell for " + clazz.getName());
    }
  }));
}
 
Example 17
Source Project: ConfigJSR   Source File: AdditionalMatchers.java    License: Apache License 2.0 6 votes vote down vote up
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);
        }
    };
}
 
Example 18
Source Project: spring4-understanding   Source File: Matchers.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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);
		}
	};
}
 
Example 19
@Contract(pure = true)
@NotNull
private static Matcher<FlutterWidget> hasCategories(@Nullable String... category) {
  final List<String> expected = category != null ? Arrays.asList(category) : Collections.emptyList();
  return new BaseMatcher<FlutterWidget>() {
    @Override
    public boolean matches(final Object item) {
      final List<String> categories = ((FlutterWidget)item).getCategories();
      return categories != null && categories.containsAll(expected);
    }

    @Override
    public void describeTo(final Description description) {
      description.appendText("getCategories should return ").appendValue(category);
    }
  };
}
 
Example 20
@Contract(pure = true)
@NotNull
private static Matcher<FlutterWidget> hasCategories(@Nullable String... category) {
  final List<String> expected = category != null ? Arrays.asList(category) : Collections.emptyList();
  return new BaseMatcher<FlutterWidget>() {
    @Override
    public boolean matches(final Object item) {
      final List<String> categories = ((FlutterWidget)item).getCategories();
      return categories != null && categories.containsAll(expected);
    }

    @Override
    public void describeTo(final Description description) {
      description.appendText("getCategories should return ").appendValue(category);
    }
  };
}
 
Example 21
Source Project: credhub   Source File: CharacterRuleProviderTest.java    License: Apache License 2.0 6 votes vote down vote up
private Matcher<CharacterRule> usesCharacters(final CharacterData characterData) {
  return new BaseMatcher<CharacterRule>() {

    @Override
    public boolean matches(final Object item) {
      final CharacterRule rule = (CharacterRule) item;
      return rule.getValidCharacters().equals(characterData.getCharacters());
    }

    @Override
    public void describeTo(final Description description) {
      description.appendText("getValidCharacters() should equal")
        .appendValue(characterData.getCharacters());
    }
  };
}
 
Example 22
private void requestHeaders(ResponseActions expect, RequestPattern request) {
	if (request.getHeaders() != null) {
		for (final String header : request.getHeaders().keySet()) {
			final MultiValuePattern pattern = request.getHeaders().get(header);
			expect.andExpect(header(header, new BaseMatcher<String>() {

				@Override
				public boolean matches(Object item) {
					return pattern.match(
							new MultiValue(header, Arrays.asList((String) item)))
							.isExactMatch();
				}

				@Override
				public void describeTo(Description description) {
					description
							.appendText("should match header: " + header + " with ")
							.appendText(pattern.getExpected());
				}
			}));
		}
	}
}
 
Example 23
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);
    }
  };
}
 
Example 24
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);
    }
  };
}
 
Example 25
@Test
public void loadBalancerFilterNoClientWorks() {
	testClient.get().uri("/get").header("Host", "www.loadbalancerclientempty.org")
			.exchange().expectStatus().value(new BaseMatcher<Integer>() {
				@Override
				public boolean matches(Object item) {
					if (Integer.class.isInstance(item)) {
						Integer toMatch = (Integer) item;
						return toMatch.intValue() == 503;
					}
					return false;
				}

				@Override
				public void describeTo(Description description) {
					description.appendText("Expected 503");
				}
			});
}
 
Example 26
Source Project: emodb   Source File: DefaultDatabusTest.java    License: Apache License 2.0 6 votes vote down vote up
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);

        }
    };
}
 
Example 27
Source Project: emodb   Source File: StashReaderTest.java    License: Apache License 2.0 6 votes vote down vote up
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("]");
        }
    };
}
 
Example 28
Source Project: beam   Source File: CalciteParsesSimpleIdentifiersTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Asserts that the specified field alias is parsed as expected.
 *
 * <p>SQL parser un-escapes the qouted identifiers, for example.
 */
private Matcher<PCollection<Row>> parsedAs(String expected) {
  return new BaseMatcher<PCollection<Row>>() {
    @Override
    public boolean matches(Object actual) {
      PCollection<Row> result = (PCollection<Row>) actual;
      PAssert.thatSingleton(result).satisfies(assertFieldNameIs(expected));
      pipeline.run();
      return true;
    }

    @Override
    public void describeTo(Description description) {
      description.appendText("field alias matches");
    }
  };
}
 
Example 29
Source Project: kafka-helmsman   Source File: BurrowTest.java    License: MIT License 5 votes vote down vote up
private Request expectPath(String path) {
  return argThat(new BaseMatcher<Request>() {
    @Override
    public void describeTo(Description description) {
      description.appendText("Requested URL does not match expected: " + path);
    }

    @Override
    public boolean matches(Object o) {
      Request request = (Request) o;
      return request.url().encodedPath().equals(path);
    }
  });
}
 
Example 30
Source Project: FRC-2019-Public   Source File: MotionProfileGeneratorTest.java    License: MIT License 5 votes vote down vote up
public static Matcher<Double> epsilonEqualTo(final double b, final double epsilon) {
    return new BaseMatcher<Double>() {
        @Override
        public boolean matches(Object a) {
            return Util.epsilonEquals((Double) a, b, epsilon);
        }

        @Override
        public void describeTo(Description description) {
            description.appendText("Should be within +/- ").appendValue(epsilon).appendText(" of ")
                    .appendValue(b);
        }
    };
}