org.hamcrest.BaseMatcher Java Examples

The following examples show how to use org.hamcrest.BaseMatcher. 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: ShellUiTestUtil.java    From dsl-devkit with 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 #2
Source File: SequentialSubscriptionTest.java    From servicetalk with 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 #3
Source File: Matchers.java    From java-technology-stack with 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 #4
Source File: CubeMetaIngesterTest.java    From kylin-on-parquet-v2 with 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 File: DefaultDatabusTest.java    From emodb with 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 #6
Source File: SqlJsonFunctionsTest.java    From Quicksql with 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 #7
Source File: SqlJsonFunctionsTest.java    From Quicksql with 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 #8
Source File: TypeFinderTest.java    From Quicksql with 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 #9
Source File: StashReaderTest.java    From emodb with 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 #10
Source File: CalciteParsesSimpleIdentifiersTest.java    From beam with 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 #11
Source File: SwtWorkbenchBot.java    From dsl-devkit with 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 #12
Source File: Matchers.java    From pushfish-android with 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 #13
Source File: GatewayIntegrationTests.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
@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 #14
Source File: JmesPathRuntimeTest.java    From jmespath-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 #15
Source File: JmesPathRuntimeTest.java    From jmespath-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 #16
Source File: WireMockRestServiceServer.java    From spring-cloud-contract with Apache License 2.0 6 votes vote down vote up
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 #17
Source File: CharacterRuleProviderTest.java    From credhub with 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 #18
Source File: Matchers.java    From pushfish-android with 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 #19
Source File: FlutterWidgetTest.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@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
Source File: FlutterWidgetTest.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@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 File: Matchers.java    From spring4-understanding with 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 #22
Source File: Matchers.java    From pushfish-android with 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 #23
Source File: RestClientCallArgumentMatcher.java    From ods-provisioning-app with Apache License 2.0 6 votes vote down vote up
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 #24
Source File: AdditionalMatchers.java    From ConfigJSR with 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 #25
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 #26
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 #27
Source File: ResourceServerPropertiesTests.java    From spring-security-oauth2-boot with Apache License 2.0 6 votes vote down vote up
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 #28
Source File: Matchers.java    From pushfish-android with 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 #29
Source File: S3ScanWriterTest.java    From emodb with Apache License 2.0 5 votes vote down vote up
private Matcher<PutObjectRequest> putsIntoBucket(final String bucket) {
    return new BaseMatcher<PutObjectRequest>() {
        @Override
        public boolean matches(Object item) {
            PutObjectRequest request = (PutObjectRequest) item;
            return request != null && request.getBucketName().equals(bucket);
        }

        @Override
        public void describeTo(Description description) {
            description.appendText("PutObjectRequest for bucket ").appendText(bucket);
        }
    };
}
 
Example #30
Source File: SolManBackendGetChangeTransportsTest.java    From devops-cm-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testHelp() throws Exception {
    Commands.main(new String[] {
            "-t", "SOLMAN",
            "get-transports",
            "--help"});
    String helpText = IOUtils.toString(result.toByteArray(), "UTF-8");

    assertThat(helpText, new BaseMatcher<String>() {

        String expected = ".*-m,--modifiable-only[\\s]*Returns modifiable transports only.*";
        String actual;

        @Override
        public boolean matches(Object item) {
            if(! (item instanceof String)) {
                return false;
            }

            actual = (String) item;
            return Pattern.compile(expected, Pattern.MULTILINE).matcher(actual).find();
        }

        @Override
        public void describeTo(Description description) {
            description.appendText(String.format("Expected regex '%s' not found in '%s'.", expected, actual));
        }
    });
}