org.hamcrest.Description Java Examples

The following examples show how to use org.hamcrest.Description. 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: ScreengrabTest.java    From ETHWallet 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 #2
Source File: OnlineLayersPreferenceActivityTest.java    From mage-android with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #3
Source File: ViolationMatchers.java    From fullstop with 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 #4
Source File: EventuallyMatcher.java    From spring-cloud-deployer with 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 #5
Source File: SOSActivityTest.java    From BaldPhone with 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 #6
Source File: CustomMatchers.java    From cukes with 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 #7
Source File: ResponseMatcher.java    From cukes with 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 #8
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 #9
Source File: AssertionHelper.java    From ogham with 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 #10
Source File: HttpMatchers.java    From rulz with 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 #11
Source File: DocFragmentRepository_IntegTest.java    From estatio with 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 #12
Source File: ServiceResponseMatchers.java    From konker-platform with 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 #13
Source File: LongListMatchers.java    From soas with 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 #14
Source File: OpenstackPhyInterfaceJsonMatcher.java    From onos with 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 #15
Source File: TaskEvalBehaviorTest.java    From flo with 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 #16
Source File: HasStats.java    From caffeine with 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 #17
Source File: PathMacroManagerTest.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Before
public final void setupApplication() throws Exception {
  // in fact the test accesses extension points so it rather should be converted to a platform one
  assumeNotNull(ApplicationManager.getApplication());

  context = new JUnit4Mockery();
  context.setImposteriser(ClassImposteriser.INSTANCE);
  myApplication = context.mock(ApplicationEx.class, "application");

  context.checking(new Expectations() {
    {
      allowing(myApplication).isUnitTestMode();
      will(returnValue(false));

      // some tests leave invokeLater()'s after them
      allowing(myApplication).invokeLater(with(any(Runnable.class)), with(any(ModalityState.class)));

      allowing(myApplication).runReadAction(with(any(Runnable.class)));
      will(new Action() {
        @Override
        public void describeTo(final Description description) {
          description.appendText("runs runnable");
        }

        @Override
        @javax.annotation.Nullable
        public Object invoke(final Invocation invocation) throws Throwable {
          ((Runnable)invocation.getParameter(0)).run();
          return null;
        }
      });
    }
  });
}
 
Example #18
Source File: AstrixTestUtil.java    From astrix with 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 #19
Source File: MultiMetaServerTest.java    From x-pipe with Apache License 2.0 5 votes vote down vote up
@Test
public void testMultiProxy(){
	
	int serversCount = 10;
	List<MetaServer> servers = new LinkedList<>();
	
	for(int i=0; i < serversCount - 1 ; i++){
		servers.add(mock(MetaServer.class));
	}
	
	MetaServer metaServer = MultiMetaServer.newProxy(mock(MetaServer.class), servers);
	
	final ForwardInfo forwardInfo = new ForwardInfo();
	
	metaServer.clusterDeleted(getClusterId(), forwardInfo);
	
	for(MetaServer mockServer :  servers){
		verify(mockServer).clusterDeleted(eq(getClusterId()),  argThat(new BaseMatcher<ForwardInfo>() {

			@Override
			public boolean matches(Object item) {
				//should be cloned
				if(item == forwardInfo){
					return false;
				}
				return true;
			}
			@Override
			public void describeTo(Description description) {
				
			}
		}));
	}
	
}
 
Example #20
Source File: NavInputFieldMatchers.java    From espresso-cucumber with Apache License 2.0 5 votes vote down vote up
public static Matcher<View> withWarningState() {
    return new BoundedMatcher<View, StockInputField>(StockInputField.class) {
        @Override
        public boolean matchesSafely(final StockInputField inputField) {
            final InputFieldMode inputMode = inputField.getModel().getEnum(Attributes.INPUT_MODE);

            return InputFieldMode.WARN.equals(inputMode);
        }

        @Override
        public void describeTo(final Description description) {
            description.appendText("with warning state");
        }
    };
}
 
Example #21
Source File: MissingAuthorizationMatcher.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean matchesSafely(MissingAuthorization item, Description mismatchDescription) {
  if (StringUtils.equals(missing.getResourceId(), item.getResourceId())
      && StringUtils.equals(missing.getResourceType(), item.getResourceType())
      && StringUtils.equals(missing.getViolatedPermissionName(), item.getViolatedPermissionName())) {
    return true;
  }
  mismatchDescription.appendText("expected missing authorization: ").appendValue(missing).appendValue(" received: ").appendValue(item);
  return false;
}
 
Example #22
Source File: ArtifactsControllerIntegrationTest.java    From gocd with 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 #23
Source File: IntentMatchers.java    From android-test with Apache License 2.0 5 votes vote down vote up
public static Matcher<Intent> anyIntent() {
  return new TypeSafeMatcher<Intent>() {
    @Override
    public void describeTo(Description description) {
      description.appendText("any intent");
    }

    @Override
    public boolean matchesSafely(Intent intent) {
      return true;
    }
  };
}
 
Example #24
Source File: PreferenceMatchers.java    From android-test with 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 #25
Source File: SerializableCoderTest.java    From beam with 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 #26
Source File: Matchers.java    From pushfish-android with 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 #27
Source File: LogRecordMatcher.java    From beam with 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 #28
Source File: OptionalMatchers.java    From java-8-matchers with MIT License 5 votes vote down vote up
/**
 * Matches a non empty OptionalInt with the given content
 *
 * @param content Expected contents of the Optional
 */
public static Matcher<OptionalInt> containsInt(int content) {
    return new TypeSafeMatcher<OptionalInt>() {
        @Override
        protected boolean matchesSafely(OptionalInt item) {
            return item.isPresent() && item.getAsInt() == content;
        }

        @Override
        public void describeTo(Description description) {
            description.appendText(Optional.of(content).toString());
        }
    };
}
 
Example #29
Source File: InParameterJoinMatcher.java    From fdb-record-layer with 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 File: MappingValueCodecTest.java    From onos with 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;
}