org.hamcrest.CustomMatcher Java Examples

The following examples show how to use org.hamcrest.CustomMatcher. 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: HttpMatchers.java    From rulz with Apache License 2.0 6 votes vote down vote up
public static Matcher<Response> other() {
    return new CustomMatcher<Response>("unrecognized family of responses") {

        @Override
        public boolean matches(Object o) {
            return (o instanceof Response)
                    && (((Response) o).getStatusInfo().getFamily() == Response.Status.Family.OTHER);
        }

        @Override
        public void describeMismatch(Object item, Description description) {
            Response response = (Response) item;
            provideDescription(response, description);
        }
    };
}
 
Example #2
Source File: JsonMatcher.java    From pnc with Apache License 2.0 6 votes vote down vote up
public static CustomMatcher<String> containsJsonAttribute(
        String jsonAttribute,
        Consumer<String>... actionWhenMatches) {
    return new CustomMatcher<String>("matchesJson") {
        @Override
        public boolean matches(Object o) {
            String rawJson = String.valueOf(o);
            logger.debug("Evaluating raw JSON: " + rawJson);
            Object value = from(rawJson).get(jsonAttribute);
            logger.debug("Got value from JSon: " + value);
            if (value != null) {
                if (actionWhenMatches != null) {
                    Stream.of(actionWhenMatches).forEach(action -> action.accept(String.valueOf(value)));
                }
                return true;
            }
            return false;
        }
    };
}
 
Example #3
Source File: HttpMatchers.java    From rulz with Apache License 2.0 6 votes vote down vote up
public static Matcher<Response> serverError() {
    final int statusCode = Response.Status.INTERNAL_SERVER_ERROR.getStatusCode();
    return new CustomMatcher<Response>("Internal server error(" + 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 #4
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 #5
Source File: HttpMatchers.java    From rulz with Apache License 2.0 6 votes vote down vote up
public static Matcher<Response> informational() {
    return new CustomMatcher<Response>("1xx (informational) family of responses") {

        @Override
        public boolean matches(Object o) {
            return (o instanceof Response)
                    && (((Response) o).getStatusInfo().getFamily() == Response.Status.Family.INFORMATIONAL);
        }

        @Override
        public void describeMismatch(Object item, Description description) {
            Response response = (Response) item;
            provideDescription(response, description);
        }
    };
}
 
Example #6
Source File: HttpMatchers.java    From rulz with Apache License 2.0 6 votes vote down vote up
public static Matcher<Response> redirection() {
    return new CustomMatcher<Response>("3xx (redirection) family of responses") {

        @Override
        public boolean matches(Object o) {
            return (o instanceof Response)
                    && (((Response) o).getStatusInfo().getFamily() == Response.Status.Family.REDIRECTION);
        }

        @Override
        public void describeMismatch(Object item, Description description) {
            Response response = (Response) item;
            provideDescription(response, description);
        }

    };
}
 
Example #7
Source File: HttpMatchers.java    From rulz with Apache License 2.0 6 votes vote down vote up
public static Matcher<Response> clientError() {
       return new CustomMatcher<Response>("4xx (client error) family of responses") {

        @Override
        public boolean matches(Object o) {
            return (o instanceof Response)
                    && (((Response) o).getStatusInfo().getFamily() == Response.Status.Family.CLIENT_ERROR);
        }

        @Override
        public void describeMismatch(Object item, Description description) {
            Response response = (Response) item;
            provideDescription(response, description);
        }

    };
}
 
Example #8
Source File: HttpMatchers.java    From rulz with Apache License 2.0 6 votes vote down vote up
public static Matcher<Response> successful() {
    return new CustomMatcher<Response>("2xx family of successful responses") {

        @Override
        public boolean matches(Object o) {
            return (o instanceof Response)
                    && (((Response) o).getStatusInfo().getFamily() == Response.Status.Family.SUCCESSFUL);
        }

        @Override
        public void describeMismatch(Object item, Description description) {
            Response response = (Response) item;
            provideDescription(response, description);
        }

    };
}
 
Example #9
Source File: BuildPropertiesTest.java    From template-compiler with Apache License 2.0 5 votes vote down vote up
private Matcher<String> patternMatcher(String regex) {
  return new CustomMatcher<String>("matches pattern") {
    @Override
    public boolean matches(Object item) {
      return (item instanceof String) && ((String)item).matches(regex);
    }
  };
}
 
Example #10
Source File: ElasticsearchIOTestCommon.java    From beam with Apache License 2.0 5 votes vote down vote up
void testWriteWithErrors() throws Exception {
  Write write =
      ElasticsearchIO.write()
          .withConnectionConfiguration(connectionConfiguration)
          .withMaxBatchSize(BATCH_SIZE);
  List<String> input =
      ElasticsearchIOTestUtils.createDocuments(
          numDocs, ElasticsearchIOTestUtils.InjectionMode.INJECT_SOME_INVALID_DOCS);
  expectedException.expect(isA(IOException.class));
  expectedException.expectMessage(
      new CustomMatcher<String>("RegExp matcher") {
        @Override
        public boolean matches(Object o) {
          String message = (String) o;
          // This regexp tests that 2 malformed documents are actually in error
          // and that the message contains their IDs.
          // It also ensures that root reason, root error type,
          // caused by reason and caused by error type are present in message.
          // To avoid flakiness of the test in case of Elasticsearch error message change,
          // only "failed to parse" root reason is matched,
          // the other messages are matched using .+
          return message.matches(
              "(?is).*Error writing to Elasticsearch, some elements could not be inserted"
                  + ".*Document id .+: failed to parse \\(.+\\).*Caused by: .+ \\(.+\\).*"
                  + "Document id .+: failed to parse \\(.+\\).*Caused by: .+ \\(.+\\).*");
        }
      });
  // write bundles size is the runner decision, we cannot force a bundle size,
  // so we test the Writer as a DoFn outside of a runner.
  try (DoFnTester<String, Void> fnTester = DoFnTester.of(new Write.WriteFn(write))) {
    // inserts into Elasticsearch
    fnTester.processBundle(input);
  }
}
 
Example #11
Source File: FlutterWidgetTest.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Contract(pure = true)
@NotNull
private static Matcher<Predicate<DiagnosticsNode>> matches(@NotNull DiagnosticsNode node) {
  return new CustomMatcher<Predicate<DiagnosticsNode>>("Should match: " + node.getDescription()) {
    @Override
    public boolean matches(Object o) {
      //noinspection unchecked
      return ((Predicate<DiagnosticsNode>)o).test(node);
    }
  };
}
 
Example #12
Source File: FlutterWidgetTest.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Contract(pure = true)
@NotNull
private static Matcher<Predicate<DiagnosticsNode>> matches(@NotNull DiagnosticsNode node) {
  return new CustomMatcher<Predicate<DiagnosticsNode>>("Should match: " + node.getDescription()) {
    @Override
    public boolean matches(Object o) {
      //noinspection unchecked
      return ((Predicate<DiagnosticsNode>)o).test(node);
    }
  };
}
 
Example #13
Source File: VersionMatcherRule.java    From intellij-quarkus with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected void starting(Description d) {
  final TargetVersions targetVersions = d.getAnnotation(TargetVersions.class);
  if (targetVersions == null) return;

  myMatcher = new CustomMatcher<String>("Gradle version '" + targetVersions.value() + "'") {
    @Override
    public boolean matches(Object item) {
      return item instanceof String && new VersionMatcher(GradleVersion.version(item.toString())).isVersionMatch(targetVersions);
    }
  };
}
 
Example #14
Source File: JsonSurferTest.java    From JsonSurfer with MIT License 5 votes vote down vote up
@Test
public void testJsonPathFilterEqualBoolean() throws Exception {
    JsonPathListener mockListener = mock(JsonPathListener.class);
    surfer.configBuilder().bind("$.store.book[?(@.marked==true)]", mockListener)
            .buildAndSurf(read("sample_filter.json"));

    verify(mockListener, times(1)).onValue(argThat(new CustomMatcher<Object>("test filter") {
        @Override
        public boolean matches(Object o) {
            return provider.primitive("Moby Dick").equals(provider.resolve(o, "title"));
        }
    }), any(ParsingContext.class));
}
 
Example #15
Source File: JsonSurferTest.java    From JsonSurfer with MIT License 5 votes vote down vote up
@Test
public void testJsonPathFilterEqualNumber() throws Exception {
    JsonPathListener mockListener = mock(JsonPathListener.class);
    surfer.configBuilder().bind("$.store.book[?(@.price==8.95)]", mockListener)
            .buildAndSurf(read("sample_filter.json"));

    verify(mockListener, times(1)).onValue(argThat(new CustomMatcher<Object>("test filter") {
        @Override
        public boolean matches(Object o) {
            return provider.primitive("Sayings of the Century").equals(provider.resolve(o, "title"));
        }
    }), any(ParsingContext.class));
}
 
Example #16
Source File: JsonSurferTest.java    From JsonSurfer with MIT License 5 votes vote down vote up
@Test
public void testJsonPathFilterEqualString1() throws Exception {
    JsonPathListener mockListener = mock(JsonPathListener.class);
    surfer.configBuilder().bind("$.store.book[?(@.description.year=='2010')]", mockListener)
            .buildAndSurf(read("sample_filter.json"));
    verify(mockListener, times(1)).onValue(argThat(new CustomMatcher<Object>("Test filter") {
        @Override
        public boolean matches(Object o) {
            return provider.primitive("Sword of Honour").equals(provider.resolve(o, "title"));
        }
    }), any(ParsingContext.class));
}
 
Example #17
Source File: JsonSurferTest.java    From JsonSurfer with MIT License 5 votes vote down vote up
@Test
public void testJsonPathFilterExistence2() throws Exception {

    JsonPathListener mockListener = mock(JsonPathListener.class);
    surfer.configBuilder().bind("$.store.book[?(@.description)]", mockListener)
            .buildAndSurf(read("sample_filter.json"));

    verify(mockListener, times(1)).onValue(argThat(new CustomMatcher<Object>("test filter") {
        @Override
        public boolean matches(Object o) {
            return provider.primitive("Sword of Honour").equals(provider.resolve(o, "title"));
        }
    }), any(ParsingContext.class));

}
 
Example #18
Source File: JsonSurferTest.java    From JsonSurfer with MIT License 5 votes vote down vote up
@Test
public void testJsonPathFilterMatchRegex() throws Exception {
    JsonPathListener mockListener = mock(JsonPathListener.class);
    surfer.configBuilder().bind("$.store.book[?(@.isbn=~/\\d-\\d\\d\\d-21311-\\d/)]", mockListener)
            .buildAndSurf(read("sample_filter.json"));
    verify(mockListener, times(1)).onValue(argThat(new CustomMatcher<Object>("Test filter") {
        @Override
        public boolean matches(Object o) {
            return provider.primitive("Moby Dick").equals(provider.resolve(o, "title"));
        }
    }), any(ParsingContext.class));
}
 
Example #19
Source File: JsonSurferTest.java    From JsonSurfer with MIT License 5 votes vote down vote up
@Test
public void testJsonPathFilterMatchRegexFlags() throws Exception {
    JsonPathListener mockListener = mock(JsonPathListener.class);
    surfer.configBuilder().bind("$.store.book[?(@.author=~/tolkien/i)]", mockListener) // we assume other flags work too
            .buildAndSurf(read("sample_filter.json"));
    verify(mockListener, times(1)).onValue(argThat(new CustomMatcher<Object>("Test filter") {
        @Override
        public boolean matches(Object o) {
            return provider.primitive("The Lord of the Rings").equals(provider.resolve(o, "title"));
        }
    }), any(ParsingContext.class));
}
 
Example #20
Source File: IgniteCacheQueryH2IndexingLeakTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @param wanted Wanted.
 */
private static <T extends Comparable<? super T>> Matcher<T> greaterOrEqualTo(T wanted) {
    return new CustomMatcher<T>("should be greater or equal to " + wanted) {
        @SuppressWarnings({"unchecked", "rawtypes"})
        @Override public boolean matches(Object item) {
            return wanted != null && item instanceof Comparable && ((Comparable)item).compareTo(wanted) >= 0;
        }
    };
}
 
Example #21
Source File: DubboMonitorTest.java    From dubbo-2.6.5 with Apache License 2.0 5 votes vote down vote up
@Test
public void testSum() {
    URL statistics = new URL("dubbo", "10.20.153.11", 0)
            .addParameter(MonitorService.APPLICATION, "morgan")
            .addParameter(MonitorService.INTERFACE, "MemberService")
            .addParameter(MonitorService.METHOD, "findPerson")
            .addParameter(MonitorService.CONSUMER, "10.20.153.11")
            .addParameter(MonitorService.SUCCESS, 1)
            .addParameter(MonitorService.FAILURE, 0)
            .addParameter(MonitorService.ELAPSED, 3)
            .addParameter(MonitorService.MAX_ELAPSED, 3)
            .addParameter(MonitorService.CONCURRENT, 1)
            .addParameter(MonitorService.MAX_CONCURRENT, 1);
    Invoker invoker = mock(Invoker.class);
    MonitorService monitorService = mock(MonitorService.class);

    given(invoker.getUrl()).willReturn(URL.valueOf("dubbo://127.0.0.1:7070?interval=20"));
    DubboMonitor dubboMonitor = new DubboMonitor(invoker, monitorService);

    dubboMonitor.collect(statistics);
    dubboMonitor.collect(statistics.addParameter(MonitorService.SUCCESS, 3).addParameter(MonitorService.CONCURRENT, 2)
            .addParameter(MonitorService.INPUT, 1).addParameter(MonitorService.OUTPUT, 2));
    dubboMonitor.collect(statistics.addParameter(MonitorService.SUCCESS, 6).addParameter(MonitorService.ELAPSED, 2));

    dubboMonitor.send();

    ArgumentCaptor<URL> summaryCaptor = ArgumentCaptor.forClass(URL.class);
    verify(monitorService, atLeastOnce()).collect(summaryCaptor.capture());

    List<URL> allValues = summaryCaptor.getAllValues();

    assertThat(allValues, not(nullValue()));
    assertThat(allValues, hasItem(new CustomMatcher<URL>("Monitor count should greater than 1") {
        @Override
        public boolean matches(Object item) {
            URL url = (URL) item;
            return Integer.valueOf(url.getParameter(MonitorService.SUCCESS)) > 1;
        }
    }));
}
 
Example #22
Source File: ArtifactsResourceTest.java    From apicurio-registry with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("rawtypes")
    @Test
    public void testListArtifactVersions() throws Exception {
        String artifactContent = resourceToString("openapi-empty.json");
        
        // Create an artifact
        createArtifact("testListArtifactVersions/EmptyAPI", ArtifactType.OPENAPI, artifactContent);

        // Update the artifact 5 times
        for (int idx = 0; idx < 5; idx++) {
            given()
                .when()
                    .contentType(CT_JSON)
                    .header("X-Registry-ArtifactType", ArtifactType.OPENAPI.name())
                    .pathParam("artifactId", "testListArtifactVersions/EmptyAPI")
                    .body(artifactContent.replace("Empty API", "Empty API (Update " + idx + ")"))
                    .put("/artifacts/{artifactId}")
                .then()
                    .statusCode(200)
                    .body("id", equalTo("testListArtifactVersions/EmptyAPI"))
                    .body("type", equalTo(ArtifactType.OPENAPI.name()));
        }
        
        // List the artifact versions
        given()
            .when()
                .pathParam("artifactId", "testListArtifactVersions/EmptyAPI")
                .get("/artifacts/{artifactId}/versions")
            .then()
//                .log().all()
                .statusCode(200)
                // The following custom matcher makes sure that 6 versions are returned
                .body(new CustomMatcher("Unexpected list of artifact versions.") {
                    @Override
                    public boolean matches(Object item) {
                        String val = item.toString();
                        if (val == null) {
                            return false;
                        }
                        if (!val.startsWith("[") || !val.endsWith("]")) {
                            return false;
                        }
                        return val.split(",").length == 6;
                    }
                });
        
        // Try to list artifact versions for an artifact that doesn't exist.
        given()
            .when()
                .pathParam("artifactId", "testListArtifactVersions/MissingAPI")
                .get("/artifacts/{artifactId}/versions")
            .then()
                .statusCode(404);

    }