@Test public void testBadRepo() throws Exception { expectedException.expect(new CustomMatcher<Object>(IllegalArgumentException.class.getName()) { @Override public boolean matches(Object item) { return item instanceof IllegalArgumentException; } }); new GSWagon() { public Repository getRepository() { return new Repository("id", "http://bucket/key"); } }.openConnectionInternal(); }
private void checkRemoveAddress(boolean sniff) { Object[] extraSettings = {TransportClient.CLIENT_TRANSPORT_SNIFF.getKey(), sniff}; try(TestIteration iteration = new TestIteration(extraSettings)) { final TransportClientNodesService service = iteration.transportClientNodesService; assertEquals(iteration.listNodesCount + iteration.sniffNodesCount, service.connectedNodes().size()); final TransportAddress addressToRemove = randomFrom(iteration.listNodeAddresses); service.removeTransportAddress(addressToRemove); assertThat(service.connectedNodes(), everyItem(not(new CustomMatcher<DiscoveryNode>("removed address") { @Override public boolean matches(Object item) { return item instanceof DiscoveryNode && ((DiscoveryNode)item).getAddress().equals(addressToRemove); } }))); assertEquals(iteration.listNodesCount + iteration.sniffNodesCount - 1, service.connectedNodes().size()); } }
@Test public void sendTextMessage() { // Setup ExampleMessage message = ExampleMessage.createOutgoingTextMessage(TEST_CHAT_ID, "Hello world"); final MessageQueries.SendQuery<ExampleMessage> sendQuery = new MessageQueries.SendQuery<>(TEST_CHAT_ID, message); final TestSubscriber<Update<ExampleMessage>> testSubscriber = new TestSubscriber<>(); // Execute mUpdates.subscribe(testSubscriber); mTarget.send(sendQuery).subscribe(); // Assert verify(mMockParseHelper).save(argThat(new CustomMatcher<ParseObject>("") { @Override public boolean matches(Object item) { final ParseObject parseMessage = (ParseObject) item; return parseMessage.getClassName().equals(MessagesTable.NAME); } })); testSubscriber.assertValueCount(2); }
/** * MkIssue can list its labels. * @throws Exception If some problem inside */ @Test public void listsReadOnlyLabels() throws Exception { final Issue issue = this.issue(); final String tag = "test-tag"; issue.repo().labels().create(tag, "c0c0c0"); issue.labels().add(Collections.singletonList(tag)); MatcherAssert.assertThat( new Issue.Smart(issue).roLabels().iterate(), Matchers.<Label>hasItem( new CustomMatcher<Label>("label just created") { @Override public boolean matches(final Object item) { return Label.class.cast(item).name().equals(tag); } } ) ); }
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); } }; }
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); } }; }
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); } }; }
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); } }; }
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); } }; }
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); } }; }
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); } }; }
@Test public void getAppliedMigrations_shouldQueryAndSortByName() throws Exception { ResultSet appliedMigrationResultSet = mock(ResultSet.class); Row row = mock(Row.class); when(session.execute(argThat(new CustomMatcher<Insert>("Get applied migrations") { @Override public boolean matches(Object item) { return "SELECT name,status FROM test.migrations;".equals(item.toString()); } }))).thenReturn(appliedMigrationResultSet); when(appliedMigrationResultSet.all()).thenReturn(Collections.singletonList(row)); when(row.getString(0)).thenReturn("001_initial_migration.cql"); when(row.getString(1)).thenReturn("APPLIED"); assertThat(client.getAppliedMigrations()).containsOnly("001_initial_migration.cql"); }
@Test public void getAppliedMigrations_shouldIgnoreFailedAndIncompleteMigrations() throws Exception { ResultSet appliedMigrationResultSet = mock(ResultSet.class); Row row1 = mock(Row.class); Row row2 = mock(Row.class); when(session.execute(argThat(new CustomMatcher<Insert>("Get applied migrations") { @Override public boolean matches(Object item) { return "SELECT name,status FROM test.migrations;".equals(item.toString()); } }))).thenReturn(appliedMigrationResultSet); when(appliedMigrationResultSet.all()).thenReturn(Arrays.asList(row1, row2)); when(row1.getString(0)).thenReturn("001_initial_migration.cql"); when(row1.getString(1)).thenReturn("APPLIED"); when(row2.getString(0)).thenReturn("002_add_stuff.cql"); when(row2.getString(1)).thenReturn("FAILED"); assertThat(client.getAppliedMigrations()).containsOnly("001_initial_migration.cql"); }
@Test public void customMatcherShouldBeMoreCompact() { //when int numberOfShips = ts.findNumberOfShipsInRangeByCriteria(searchCriteria); //then assertThat(numberOfShips).isZero(); //and verify(ts).findNumberOfShipsInRangeByCriteria(argThat(new HamcrestArgumentMatcher<>( new CustomMatcher<ShipSearchCriteria>("ShipSearchCriteria minimumRange<2000 and numberOfPhasers>2") { @Override public boolean matches(Object item) { ShipSearchCriteria criteria = (ShipSearchCriteria) item; return criteria.getMinimumRange() < 2000 && criteria.getNumberOfPhasers() > 2; } }))); }
@Test public void testGetToken() throws Exception { User user = UserServiceTest.newInstence(); us.save(user); mockMvc .perform( post("/api/token").param("email", user.getEmail()).param("password", user.getPassword()) .accept(MediaType.parseMediaType("application/json;charset=UTF-8"))).andExpect(status().isOk()) .andExpect(content().contentType(MediaType.parseMediaType("application/json;charset=UTF-8"))) .andExpect(jsonPath("$.token").value( // 匿名内部类,自定义Matcher,判断返回的json文的token属性是否是32个字符长的md5密文 new CustomMatcher<String>("长度为32的字符串") { public boolean matches(Object object) { return ((object instanceof String) && !((String) object).isEmpty() && ((String) object) .length() == 32); } })); }
public static Matcher<View> withMessageDirection(final int direction) { return new CustomMatcher<View>("with message direction: ") { @Override public boolean matches(Object item) { if (!(item instanceof AdapterView)) { return false; } Adapter adapter = ((AdapterView) item).getAdapter(); for (int i = 0; i < adapter.getCount(); i++) { Cursor message = (Cursor) adapter.getItem(i); if (message != null && MessageUtils.getMessageDirection(message) == direction) { return true; } } return false; } }; }
public static Matcher<View> withMessageContent(final Context context, final String content) { return new CustomMatcher<View>("with message content: ") { @Override public boolean matches(Object item) { if (!(item instanceof AdapterView)) { return false; } Adapter adapter = ((AdapterView) item).getAdapter(); for (int i = 0; i < adapter.getCount(); i++) { Cursor cursor = (Cursor) adapter.getItem(i); if (cursor != null) { CompositeMessage message = CompositeMessage.fromCursor(context, cursor); TextComponent text = message.getComponent(TextComponent.class); if (text != null && text.getContent().equalsIgnoreCase(content)) { return true; } } } return false; } }; }
/** Test all targets can be extracted from tracker */ @Test public void testThatAllExpectedMmsisAreReturnedByTracker() throws Exception { Set<TargetInfo> targets = aisTrackService.targets(); int[] mmsis = targets.stream().mapToInt(t -> t.getMmsi()).distinct().toArray(); for (int mmsi : mmsis) { assertThat(mmsi, new CustomMatcher<Integer>("Tracked MMSI must in in list of expected MMSI's") { @Override public boolean matches(Object o) { for (int i = 0; i < mmsiInTestData.length; i++) { if (mmsiInTestData[i] == mmsi) return true; } return false; } }); } }
static Matcher<List<Object>> containsBufferFor(MetricValue[]... metricsArgs) { return new CustomMatcher<List<Object>>("Contains buffers for the specicied metrics") { @Override public boolean matches(Object item) { @SuppressWarnings("unchecked") List<String> items = ((List<Object>) item).stream() .map((x) -> ((ByteBuf) x).toString(StandardCharsets.UTF_8)).collect(Collectors.toList()); if (metricsArgs.length != items.size()) { return false; } for (MetricValue[] metrics : metricsArgs) { String payload = Arrays.asList(metrics).stream().map(MetricToBytesEncoder::toString) .collect(Collectors.joining("\n")); if (!items.contains(payload)) { return false; } } return true; } }; }
@Test public void testDeserializationAfterSerialization() throws Exception { testSerialization(); Port port = objectMapper.readValue(serializedPort, Port.class); assertThat(port.getAdminStateUp(), is(equalTo(ADMIN_STATE_UP))); assertThat(port.getDeviceId(), is(equalTo(DEVICE_ID))); assertThat(port.getDeviceOwner(), is(equalTo(DEVICE_OWNER))); assertThat(port.getMacAddress(), is(equalTo(MAC_ADDRESS))); assertThat(port.getName(), is(equalTo(NAME))); assertThat(port.getNetworkId(), is(equalTo(NETWORK_ID))); assertThat(port.getTenantId(), is(equalTo(TENANT_ID))); assertThat(port.getSecurityGroups(), hasItem(equalTo(SEC_GROUP))); assertThat(port.getList(), hasItem(new CustomMatcher<Ip>( "an Ip object with address " + IP_ADDRESS + " and subnet id " + IP_SUBNET_ID) { @Override public boolean matches(Object ip) { return ip instanceof Ip && IP_ADDRESS.equals(((Ip) ip).getAddress()) && IP_SUBNET_ID.equals(((Ip) ip).getSubnetId()); } })); }
@Test public void testDeserializationAfterSerialization() throws Exception { testSerialization(); Subnet subnet = objectMapper.readValue(serializedSubnet, Subnet.class); assertThat(subnet.getCidr(), is(equalTo(CIDR))); assertThat(subnet.getDnsNames(), hasItem(equalTo(DNS_SERVER))); assertThat(subnet.isEnableDHCP(), is(equalTo(ENABLE_DHCP))); assertThat(subnet.getIpversion(), is(equalTo(IP_VERSION))); assertThat(subnet.getGw(), is(equalTo(GATEWAY))); assertThat(subnet.getHostRoutes(), hasItem(equalTo(HOST_ROUTE))); assertThat(subnet.getName(), is(equalTo(NAME))); assertThat(subnet.getNetworkId(), is(equalTo(NETWORK_ID))); assertThat(subnet.getTenantId(), is(equalTo(TENANT_ID))); assertThat(subnet.getList(), hasItem(new CustomMatcher<Pool>( "a Pool object with start " + POOL_START + " and end " + POOL_END) { @Override public boolean matches(Object pool) { return pool instanceof Pool && POOL_START.equals(((Pool) pool).getStart()) && POOL_END.equals(((Pool) pool).getEnd()); } })); }
@Test public void testGetItemNotFound() throws Exception { expectedException.expect(new CustomMatcher<Object>(ResourceDoesNotExistException.class.getName()) { @Override public boolean matches(Object item) { return item instanceof ResourceDoesNotExistException; } }); final HttpClient client = strictMock(HttpClient.class); final Storage storage = createStrictMock(Storage.class); final GSWagon gsWagon = new GSWagon() { @Override void get(Blob blob, File file) throws IOException, TransferFailedException { // noop } }; gsWagon.swapAndCloseConnection(new ConnectionPOJO( storage, BLOB_ID, client )); expect(storage.get(EasyMock.<BlobId>anyObject())).andReturn(null).once(); replay(storage); final File outFile = temporaryFolder.newFile(); gsWagon.get("artifact", outFile); }
@Test public void testBuildStorageFailsWithoutProjectID() { final GSWagon gsWagon = new GSWagon() { public Repository getRepository() { return new Repository("id", "url"); } }; gsWagon.swapAndCloseConnection(connectionPOJO); final String property = gsWagon.getPropertyString(gsWagon.getRepository().getId()); final String pre = System.getProperty(property); try { expectedException.expect(new CustomMatcher<Object>(NullPointerException.class.getName()) { @Override public boolean matches(Object item) { return item instanceof NullPointerException; } }); System.clearProperty(property); gsWagon.swapAndCloseConnection(connectionPOJO); assertNotNull(gsWagon.buildStorage(connectionPOJO.client)); } finally { if (pre != null) { System.setProperty(property, pre); } else { System.clearProperty(property); } } }
@Test public void testBuildPropertyNPE() { expectedException.expect(new CustomMatcher<Object>(NullPointerException.class.getName()) { @Override public boolean matches(Object item) { return item instanceof NullPointerException; } }); gsWagon.getPropertyString(null); }
@Test public void testTranslateNotFound() throws Exception { expectedException.expect(new CustomMatcher(ResourceDoesNotExistException.class.getName()) { @Override public boolean matches(Object o) { return o instanceof ResourceDoesNotExistException; } }); throw GSWagon.translate("foo", new StorageException(404, "bad")); }
@Test public void testTranslateBadAuth401() throws Exception { expectedException.expect(new CustomMatcher(AuthorizationException.class.getName()) { @Override public boolean matches(Object o) { return o instanceof AuthorizationException; } }); throw GSWagon.translate("foo", new StorageException(401, "bad")); }
@Test public void testTranslateBadAuth403() throws Exception { expectedException.expect(new CustomMatcher(AuthorizationException.class.getName()) { @Override public boolean matches(Object o) { return o instanceof AuthorizationException; } }); throw GSWagon.translate("foo", new StorageException(403, "bad")); }
@Test public void testTranslateRetryable() throws Exception { expectedException.expect(new CustomMatcher(TransferFailedException.class.getName()) { @Override public boolean matches(Object o) { return o instanceof TransferFailedException; } }); final StorageException se = new StorageException(429, "foo"); assertTrue(se.isRetryable()); throw GSWagon.translate("foo", se); }
@Test public void testTranslateUnknownType() throws Exception { expectedException.expect(new CustomMatcher(TransferFailedException.class.getName()) { @Override public boolean matches(Object o) { return o instanceof TransferFailedException; } }); final StorageException se = new StorageException(455, "foo"); assertFalse(se.isRetryable()); throw GSWagon.translate("foo", se); }
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); } }
@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); } }; }
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); } }; }
@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)); }
@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)); }
@Test public void acquireLock_shouldReturnTrueIfInsertSucceeds() throws Exception { ResultSet leaseResultSet = mock(ResultSet.class); when(session.execute(argThat(new CustomMatcher<Insert>("Get lease insert statement") { @Override public boolean matches(Object item) { String cql = item.toString(); return cql.startsWith("INSERT INTO test.leases") && cql.contains("VALUES ('migration',"); } }))).thenReturn(leaseResultSet); when(leaseResultSet.wasApplied()).thenReturn(true); assertThat(client.acquireLock()).isTrue(); }
@Test public void acquireLock_shouldReturnFalseIfInsertFails() throws Exception { ResultSet leaseResultSet = mock(ResultSet.class); when(session.execute(argThat(new CustomMatcher<Insert>("Get lease insert statement") { @Override public boolean matches(Object item) { String cql = item.toString(); return cql.startsWith("INSERT INTO test.leases") && cql.contains("VALUES ('migration',"); } }))).thenReturn(leaseResultSet); when(leaseResultSet.wasApplied()).thenReturn(false); assertThat(client.acquireLock()).isFalse(); }
private ContributorCreatedEvent prepareContributorCreatedEventMatcher(final String expectedId, final String expectedCode) { return Mockito.argThat(new CustomMatcher<ContributorCreatedEvent>("ContributorCreatedEvent [contributorId=" + expectedId + " contributorCode=" + expectedCode + "]") { @Override public boolean matches(Object paramObject) { ContributorCreatedEvent e = (ContributorCreatedEvent) paramObject; return e.getContributorId().equals(expectedId) && e.getContributorCode().equals(expectedCode) && e.getContributorData() != null; } }); }
private ContributorMergedEvent prepareContributorMergedEventMatcher(final String expectedFrom, final String expectedTo) { return Mockito.argThat(new CustomMatcher<ContributorMergedEvent>("ContributorMergedEvent [contributorCodeFrom=" + expectedFrom + " contributorCodeTo=" + expectedTo + "]") { @Override public boolean matches(Object paramObject) { ContributorMergedEvent e = (ContributorMergedEvent) paramObject; return e.getContributorCodeFrom().equals(expectedFrom) && e.getContributorCodeTo().equals(expectedTo); } }); }
private ContributorCodeChangedEvent prepareContributorCodeChangedEventMatcher(final String expectedFrom, final String expectedTo) { return Mockito.argThat(new CustomMatcher<ContributorCodeChangedEvent>( "ContributorCodeChangedEvent [contributorCodeFrom=" + expectedFrom + " contributorCodeTo=" + expectedTo + "]") { @Override public boolean matches(Object paramObject) { ContributorCodeChangedEvent e = (ContributorCodeChangedEvent) paramObject; return e.getContributorCodeFrom().equals(expectedFrom) && e.getContributorCodeTo().equals(expectedTo); } }); }