org.hamcrest.CustomTypeSafeMatcher Java Examples

The following examples show how to use org.hamcrest.CustomTypeSafeMatcher. 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: InjectPropMatcherGenerationTest.java    From litho with Apache License 2.0 6 votes vote down vote up
@Test
public void testInjectPropMatching() {
  final ComponentContext c = mComponentsRule.getContext();
  final MyInjectProp component =
      new MyInjectProp(c.getAndroidContext()).create(c).normalString("normal string").build();
  // Faking some DI mechanism doing its thing.
  component.injectedString = "injected string";
  component.injectedKettle = new MyInjectPropSpec.Kettle(92f);
  component.injectedComponent = Text.create(c).text("injected text").build();

  final Condition<InspectableComponent> matcher =
      TestMyInjectProp.matcher(c)
          .normalString("normal string")
          .injectedString("injected string")
          .injectedKettle(
              new CustomTypeSafeMatcher<MyInjectPropSpec.Kettle>("matches temperature") {
                @Override
                protected boolean matchesSafely(MyInjectPropSpec.Kettle item) {
                  return Math.abs(item.temperatureCelsius - 92f) < 0.1;
                }
              })
          .injectedComponent(TestText.matcher(c).text("injected text").build())
          .build();

  assertThat(c, component).has(deepSubComponentWith(c, matcher));
}
 
Example #2
Source File: AuthenticatingHttpConnectorTest.java    From helios with Apache License 2.0 6 votes vote down vote up
private CustomTypeSafeMatcher<URI> matchesAnyEndpoint(final String path) {
  return new CustomTypeSafeMatcher<URI>("A URI matching one of the endpoints in " + endpoints) {
    @Override
    protected boolean matchesSafely(final URI item) {
      for (final Endpoint endpoint : endpoints) {
        final InetAddress ip = endpoint.getIp();
        final URI uri = endpoint.getUri();

        if (item.getScheme().equals(uri.getScheme())
            && item.getHost().equals(ip.getHostAddress())
            && item.getPath().equals(path)) {
          return true;
        }
      }
      return false;
    }
  };
}
 
Example #3
Source File: CrashPresenterTest.java    From Sherlock with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldInitializeCrashView() throws Exception {
  SherlockDatabaseHelper database = mock(SherlockDatabaseHelper.class);
  Crash crash = mock(Crash.class);
  when(crash.getId()).thenReturn(1);
  AppInfo appInfo = mock(AppInfo.class);
  when(crash.getAppInfo()).thenReturn(appInfo);
  when(database.getCrashById(1)).thenReturn(crash);
  CrashActions actions = mock(CrashActions.class);
  CrashPresenter presenter = new CrashPresenter(database, actions);

  presenter.render(1);

  verify(actions).render(argThat(new CustomTypeSafeMatcher<CrashViewModel>("") {
    @Override
    protected boolean matchesSafely(CrashViewModel crashViewModel) {
      return crashViewModel.getIdentifier() == 1;
    }
  }));
  verify(actions).renderAppInfo(any(AppInfoViewModel.class));
}
 
Example #4
Source File: UnhandledExceptionHandlerBaseTest.java    From backstopper with Apache License 2.0 6 votes vote down vote up
private Matcher<DefaultErrorContractDTO> errorResponseViewMatches(final DefaultErrorContractDTO expectedErrorContract) {
    return new CustomTypeSafeMatcher<DefaultErrorContractDTO>("a matching ErrorResponseView"){
        @Override
        protected boolean matchesSafely(DefaultErrorContractDTO item) {
            if (!(item.errors.size() == expectedErrorContract.errors.size()))
                return false;

            for (int i = 0; i < item.errors.size(); i++) {
                DefaultErrorDTO itemError = item.errors.get(i);
                DefaultErrorDTO expectedError = item.errors.get(i);
                if (!itemError.code.equals(expectedError.code))
                    return false;
                if (!itemError.message.equals(expectedError.message))
                    return false;
            }

            return item.error_id.equals(expectedErrorContract.error_id);
        }
    };
}
 
Example #5
Source File: InstallableUnitTest.java    From packagedrone with Eclipse Public License 1.0 6 votes vote down vote up
static private final Matcher<InstallableUnit> hasProvided ( final String namespace, final String name, final String version )
{
    return new CustomTypeSafeMatcher<InstallableUnit> ( "IU with 'provided'-element [namespace=" + namespace + ", name=" + name + ", version=" + version + " ]" ) {

        @Override
        protected boolean matchesSafely ( final InstallableUnit item )
        {
            final List<Entry<String>> provides = item.getProvides ();
            for ( final Entry<String> provide : provides )
            {
                if ( Objects.equals ( provide.getNamespace (), namespace ) && Objects.equals ( provide.getKey (), name ) && Objects.equals ( provide.getValue (), version ) )
                {
                    return true;
                }
            }
            return false;
        }
    };
}
 
Example #6
Source File: InstallableUnitTest.java    From packagedrone with Eclipse Public License 1.0 6 votes vote down vote up
static private final Matcher<InstallableUnit> hasRequired ( final String namespace, final String name, final String versionRange, final boolean isOptional, final Boolean greedy, final String filter )
{
    return new CustomTypeSafeMatcher<InstallableUnit> ( "IU with 'required'-element [namespace= " + namespace + ", name= " + name + ", versionRange= " + versionRange + " ]" ) {

        @Override
        protected boolean matchesSafely ( final InstallableUnit item )
        {
            final List<Entry<org.eclipse.packagedrone.repo.aspect.common.p2.InstallableUnit.Requirement>> requires = item.getRequires ();
            for ( final Entry<org.eclipse.packagedrone.repo.aspect.common.p2.InstallableUnit.Requirement> require : requires )
            {

                if ( Objects.equals ( require.getNamespace (), namespace ) && Objects.equals ( require.getKey (), name ) )
                {
                    final org.eclipse.packagedrone.repo.aspect.common.p2.InstallableUnit.Requirement value = require.getValue ();
                    if ( Objects.equals ( value.getRange (), VersionRange.valueOf ( versionRange ) ) && Objects.equals ( value.getFilter (), filter ) && Objects.equals ( value.getGreedy (), greedy ) )
                    {
                        return true;
                    }
                }
            }
            return false;
        }
    };
}
 
Example #7
Source File: InstallableUnitTest.java    From packagedrone with Eclipse Public License 1.0 6 votes vote down vote up
static private final <K, V> Matcher<Map<K, V>> hasEntry ( final K key, final Matcher<V> valueMatcher )
{
    return new CustomTypeSafeMatcher<Map<K, V>> ( "Map with entry: key=" + key + ", value=" + valueMatcher ) {

        @Override
        protected boolean matchesSafely ( final Map<K, V> item )
        {
            final Object actualValue = item.get ( key );
            if ( valueMatcher.matches ( actualValue ) )
            {
                return true;
            }
            return false;
        }
    };
}
 
Example #8
Source File: JobHistoryTest.java    From helios with Apache License 2.0 6 votes vote down vote up
private static Matcher<TaskStatusEvent> hasState(final State... possibleStates) {
  final String description =
      "TaskStatusEvent with status.state in " + Arrays.toString(possibleStates);

  return new CustomTypeSafeMatcher<TaskStatusEvent>(description) {
    @Override
    protected boolean matchesSafely(final TaskStatusEvent event) {
      final State actual = event.getStatus().getState();
      for (final State state : possibleStates) {
        if (state == actual) {
          return true;
        }
      }
      return false;
    }
  };
}
 
Example #9
Source File: HealthCheckTest.java    From helios with Apache License 2.0 6 votes vote down vote up
private static Matcher<Version> execCompatibleDockerVersion() {
  return new CustomTypeSafeMatcher<Version>("apiVersion >= 1.18") {
    @Override
    protected boolean matchesSafely(final Version version) {
      try {
        final Iterator<String> versionParts =
            Splitter.on('.').split(version.apiVersion()).iterator();
        final int apiVersionMajor = Integer.parseInt(versionParts.next());
        final int apiVersionMinor = Integer.parseInt(versionParts.next());
        return apiVersionMajor == 1 && apiVersionMinor >= 18;
      } catch (Exception e) {
        return false;
      }
    }
  };
}
 
Example #10
Source File: JobsResourceTest.java    From helios with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateJobWithNoRolloutOptions() throws Exception {
  final JobId jobId = JobId.parse("foobar:1");
  final Job job = Job.newBuilder()
      .setName("foobar")
      .setVersion("1")
      .setImage("busybox:latest")
      .setCreatingUser("user1")
      .setCreated(0L)
      .build();

  final CreateJobResponse jobResponse = resource.post(job, "user1");
  assertThat(jobResponse,
      new CustomTypeSafeMatcher<CreateJobResponse>("CreateJobResponse that is OK") {
        @Override
        protected boolean matchesSafely(final CreateJobResponse response) {
          return response.getStatus() == OK
                 && response.getErrors().isEmpty()
                 && response.getId().contains(jobId.toString());
        }
      }
  );

  verify(model).addJob(job);
}
 
Example #11
Source File: RepeatActionUntilViewStateIntegrationTest.java    From android-test with Apache License 2.0 6 votes vote down vote up
@Test
public void performingActionOnViewWithUnreachableViewStateFailsAfterGivenNoOfAttempts() {
  final int maxAttempts = 2;
  expectedException.expect(
      new CustomTypeSafeMatcher<PerformException>(
          "PerformException " + "with expected cause and action description") {
        @Override
        protected boolean matchesSafely(PerformException performException) {

          return performException
                  .getCause()
                  .getMessage()
                  .equals("Failed to achieve view state " + "after " + maxAttempts + " attempts")
              && performException
                  .getActionDescription()
                  .equals("fast swipe until: has descendant: with text: is \"Position #200\"");
        }
      });
  onView(withId(R.id.vertical_pager))
      .check(matches(hasDescendant(withText("Position #0"))))
      .perform(repeatedlyUntil(swipeUp(), hasDescendant(withText("Position #200")), maxAttempts));
}
 
Example #12
Source File: TestMetaTableMetrics.java    From hbase with Apache License 2.0 6 votes vote down vote up
private Matcher<Map<String, Double>> containsPositiveJmxAttributesFor(final String regexp) {
  return new CustomTypeSafeMatcher<Map<String, Double>>(
      "failed to find all the 5 positive JMX attributes for: " + regexp) {

    @Override
    protected boolean matchesSafely(final Map<String, Double> values) {
      for (String key : values.keySet()) {
        for (String metricsNamePostfix : METRICS_ATTRIBUTE_NAME_POSTFIXES) {
          if (key.matches(regexp + metricsNamePostfix) && values.get(key) > 0) {
            return true;
          }
        }
      }
      return false;
    }
  };
}
 
Example #13
Source File: JobCreateCommandTest.java    From helios with Apache License 2.0 5 votes vote down vote up
private CustomTypeSafeMatcher<Job> matchesName(final String name) {
  return new CustomTypeSafeMatcher<Job>("A Job with name " + name) {
    @Override
    protected boolean matchesSafely(final Job item) {
      return item.getId().getName().equals(name);
    }
  };
}
 
Example #14
Source File: FastForwardReporterTest.java    From helios with Apache License 2.0 5 votes vote down vote up
private static Matcher<Metric> hasValue(double value) {
  return new CustomTypeSafeMatcher<Metric>("a metric with value=" + value) {
    @Override
    protected boolean matchesSafely(final Metric item) {
      return item.getValue() == value;
    }
  };
}
 
Example #15
Source File: JobsResourceTest.java    From helios with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateJobWithPartialRolloutOptions() throws Exception {
  final JobId jobId = JobId.parse("foobar:1");
  final Job job = Job.newBuilder()
      .setName("foobar")
      .setVersion("1")
      .setImage("busybox:latest")
      .setRolloutOptions(RolloutOptions.newBuilder()
          .setTimeout(null)
          .setParallelism(2)
          .setMigrate(null)
          .setOverlap(true)
          .setToken(null)
          .setIgnoreFailures(null)
          .build())
      .setCreatingUser("user1")
      .setCreated(0L)
      .build();

  final CreateJobResponse jobResponse = resource.post(job, "user1");
  assertThat(jobResponse,
      new CustomTypeSafeMatcher<CreateJobResponse>("CreateJobResponse that is OK") {
        @Override
        protected boolean matchesSafely(final CreateJobResponse response) {
          return response.getStatus() == OK
                 && response.getErrors().isEmpty()
                 && response.getId().contains(jobId.toString());
        }
      }
  );

  verify(model).addJob(job);
}
 
Example #16
Source File: HostsResourceTest.java    From helios with Apache License 2.0 5 votes vote down vote up
private static Matcher<WebApplicationException> hasStatus(final Response.Status status) {
  final int statusCode = status.getStatusCode();
  final String msg = "WebApplicationException with response.statusCode=" + statusCode;
  return new CustomTypeSafeMatcher<WebApplicationException>(msg) {
    @Override
    protected boolean matchesSafely(final WebApplicationException item) {
      return item.getResponse() != null && item.getResponse().getStatus() == statusCode;
    }
  };
}
 
Example #17
Source File: JobHistoryReaperTest.java    From helios with Apache License 2.0 5 votes vote down vote up
private CustomTypeSafeMatcher<JobId> matchesName(final String name) {
  return new CustomTypeSafeMatcher<JobId>("A JobId with name " + name) {
    @Override
    protected boolean matchesSafely(final JobId item) {
      return item.getName().equals(name);
    }
  };
}
 
Example #18
Source File: FastForwardReporterTest.java    From helios with Apache License 2.0 5 votes vote down vote up
private static Matcher<Metric> hasKey(String key) {
  return new CustomTypeSafeMatcher<Metric>("a metric with key=" + key) {
    @Override
    protected boolean matchesSafely(final Metric item) {
      return item.getKey().equals(key);
    }
  };
}
 
Example #19
Source File: FluentMatcher.java    From simulacron with Apache License 2.0 5 votes vote down vote up
/**
 * Convenience method for wrapping a {@link Predicate} into a matcher.
 *
 * @param function the predicate to wrap.
 * @param <T> The expected input type.
 * @return a {@link CustomTypeSafeMatcher} that simply wraps the input predicate.
 */
public static <T> Matcher<T> match(Predicate<T> function) {
  return new CustomTypeSafeMatcher<T>("Did not match") {

    @Override
    protected boolean matchesSafely(T item) {
      return function.test(item);
    }
  };
}
 
Example #20
Source File: JobCreateCommandTest.java    From helios with Apache License 2.0 5 votes vote down vote up
private Matcher<Job> hasCapabilities(final Set<String> added, final Set<String> dropped) {
  final String description =
      "Job with addCapabilities=" + added + " and droppedCapabilities=" + dropped;

  return new CustomTypeSafeMatcher<Job>(description) {
    @Override
    protected boolean matchesSafely(final Job actual) {
      return Objects.equals(added, actual.getAddCapabilities())
             && Objects.equals(dropped, actual.getDropCapabilities());
    }
  };
}
 
Example #21
Source File: JobCreateCommandTest.java    From helios with Apache License 2.0 5 votes vote down vote up
private Matcher<Job> hasLabels(final Map<String, String> labels) {
  final String description = "Job with labels=" + labels;

  return new CustomTypeSafeMatcher<Job>(description) {
    @Override
    protected boolean matchesSafely(final Job actual) {
      return Objects.equals(labels, actual.getLabels());
    }
  };
}
 
Example #22
Source File: JobCreateCommandTest.java    From helios with Apache License 2.0 5 votes vote down vote up
private Matcher<Job> hasRuntime(final String runtime) {
  final String description = "Job with runtime=" + runtime;

  return new CustomTypeSafeMatcher<Job>(description) {
    @Override
    protected boolean matchesSafely(final Job actual) {
      return Objects.equals(runtime, actual.getRuntime());
    }
  };
}
 
Example #23
Source File: Matchers.java    From calcite with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a matcher that matches if the examined result set returns the
 * given collection of rows in some order.
 *
 * <p>Closes the result set after reading.
 *
 * <p>For example:
 * <pre>assertThat(statement.executeQuery("select empno from emp"),
 *   returnsUnordered("empno=1234", "empno=100"));</pre>
 */
public static Matcher<? super ResultSet> returnsUnordered(String... lines) {
  final List<String> expectedList = Lists.newArrayList(lines);
  Collections.sort(expectedList);

  return new CustomTypeSafeMatcher<ResultSet>(Arrays.toString(lines)) {
    @Override protected void describeMismatchSafely(ResultSet item,
        Description description) {
      final Object value = THREAD_ACTUAL.get();
      THREAD_ACTUAL.remove();
      description.appendText("was ").appendValue(value);
    }

    protected boolean matchesSafely(ResultSet resultSet) {
      final List<String> actualList = new ArrayList<>();
      try {
        CalciteAssert.toStringList(resultSet, actualList);
        resultSet.close();
      } catch (SQLException e) {
        throw TestUtil.rethrow(e);
      }
      Collections.sort(actualList);

      THREAD_ACTUAL.set(actualList);
      final boolean equals = actualList.equals(expectedList);
      if (!equals) {
        THREAD_ACTUAL.set(actualList);
      }
      return equals;
    }
  };
}
 
Example #24
Source File: Matchers.java    From calcite with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a matcher that matches if the examined value is between bounds:
 * <code>min &le; value &le; max</code>.
 *
 * @param <T> value type
 * @param min Lower bound
 * @param max Upper bound
 */
public static <T extends Comparable<T>> Matcher<T> between(T min, T max) {
  return new CustomTypeSafeMatcher<T>("between " + min + " and " + max) {
    protected boolean matchesSafely(T item) {
      return min.compareTo(item) <= 0
          && item.compareTo(max) <= 0;
    }
  };
}
 
Example #25
Source File: DockerMatchers.java    From docker-java with Apache License 2.0 5 votes vote down vote up
public static Matcher<DockerRule> apiVersionGreater(final RemoteApiVersion version) {
    return new CustomTypeSafeMatcher<DockerRule>("is greater") {
        public boolean matchesSafely(DockerRule dockerRule) {
            return getVersion(dockerRule.getClient()).isGreater(version);
        }
    };
}
 
Example #26
Source File: DockerMatchers.java    From docker-java with Apache License 2.0 5 votes vote down vote up
public static Matcher<DockerRule> isGreaterOrEqual(final RemoteApiVersion version) {
    return new CustomTypeSafeMatcher<DockerRule>("is greater or equal") {
        public boolean matchesSafely(DockerRule dockerRule) {
            return getVersion(dockerRule.getClient()).isGreaterOrEqual(version);
        }

        @Override
        protected void describeMismatchSafely(DockerRule rule, Description mismatchDescription) {
            mismatchDescription
                    .appendText(" was ")
                    .appendText(getVersion(rule.getClient()).toString());
        }
    };
}
 
Example #27
Source File: CxxPrecompiledHeaderRuleTest.java    From buck with Apache License 2.0 5 votes vote down vote up
/** Stolen from {@link PrecompiledHeaderIntegrationTest} */
private static Matcher<BuckBuildLog> reportedTargetSuccessType(
    BuildTarget target, BuildRuleSuccessType successType) {
  return new CustomTypeSafeMatcher<BuckBuildLog>(
      "target: " + target + " with result: " + successType) {

    @Override
    protected boolean matchesSafely(BuckBuildLog buckBuildLog) {
      return buckBuildLog.getLogEntry(target).getSuccessType().equals(Optional.of(successType));
    }
  };
}
 
Example #28
Source File: Executables.java    From credentials-binding-plugin with MIT License 5 votes vote down vote up
public static Matcher<String> executable() {
    return new CustomTypeSafeMatcher<String>("executable") {
        @Override
        protected boolean matchesSafely(String item) {
            try {
                return new ProcessBuilder(LOCATOR, item).start().waitFor() == 0;
            } catch (InterruptedException | IOException e) {
                return false;
            }
        }
    };
}
 
Example #29
Source File: AdManagerSessionTest.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
private Matcher<ValidationException> createTriggerMatcher(final Matcher<String> matcher) {
  return new CustomTypeSafeMatcher<ValidationException>("Trigger") {
    @Override
    protected boolean matchesSafely(ValidationException ve) {
      return matcher.matches(ve.getTrigger());
    }
  };
}
 
Example #30
Source File: AdWordsSessionTest.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
private Matcher<ValidationException> createTriggerMatcher(final Matcher<String> matcher) {
  return new CustomTypeSafeMatcher<ValidationException>("Trigger") {
    @Override
    protected boolean matchesSafely(ValidationException ve) {
      return matcher.matches(ve.getTrigger());
    }
  };
}