Search in sources :

Example 46 with TypeSafeMatcher

use of org.hamcrest.TypeSafeMatcher in project mod-circulation-storage by folio-org.

the class JsonMatchers method hasSameProperties.

/**
 * Checks whether the object being asserted has the same values for properties
 * as expectedProperties has.
 *
 * This is equivalent of {@code expectedProperties.map().containsAll(actual.map())}.
 *
 * @param expectedProperties - expected properties and values to be present.
 * @return true only if all the properties from expectedProperties are present
 * and has the same value in actual object.
 */
public static Matcher<JsonObject> hasSameProperties(JsonObject expectedProperties) {
    return new TypeSafeMatcher<JsonObject>() {

        @Override
        protected boolean matchesSafely(JsonObject actual) {
            if (actual == null || actual.size() < expectedProperties.size()) {
                return false;
            }
            for (Map.Entry<String, Object> expectedProperty : expectedProperties) {
                final String propertyKey = expectedProperty.getKey();
                final Object expectedValue = expectedProperty.getValue();
                final Object actualValue = actual.getValue(propertyKey);
                if (!Objects.equals(expectedValue, actualValue)) {
                    return false;
                }
            }
            return true;
        }

        @Override
        public void describeTo(Description description) {
            description.appendText("Json object has following properties").appendValue(expectedProperties.toString());
        }
    };
}
Also used : TypeSafeMatcher(org.hamcrest.TypeSafeMatcher) Description(org.hamcrest.Description) JsonObject(io.vertx.core.json.JsonObject) JsonObject(io.vertx.core.json.JsonObject) Map(java.util.Map)

Example 47 with TypeSafeMatcher

use of org.hamcrest.TypeSafeMatcher in project openhab-addons by openhab.

the class ModbusPollerThingHandlerTest method testPollUnregistrationOnDispose.

@Test
public void testPollUnregistrationOnDispose() throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException {
    PollTask pollTask = Mockito.mock(PollTask.class);
    doReturn(pollTask).when(comms).registerRegularPoll(notNull(), eq(150l), eq(0L), notNull(), notNull());
    Configuration pollerConfig = new Configuration();
    pollerConfig.put("refresh", 150L);
    pollerConfig.put("start", 5);
    pollerConfig.put("length", 13);
    pollerConfig.put("type", "coil");
    poller = createPollerThingBuilder("poller").withConfiguration(pollerConfig).withBridge(endpoint.getUID()).build();
    addThing(poller);
    verifyEndpointBasicInitInteraction();
    // verify registration
    final AtomicReference<ModbusReadCallback> callbackRef = new AtomicReference<>();
    verify(mockedModbusManager).newModbusCommunicationInterface(argThat(new TypeSafeMatcher<ModbusSlaveEndpoint>() {

        @Override
        public void describeTo(Description description) {
            description.appendText("correct endpoint");
        }

        @Override
        protected boolean matchesSafely(ModbusSlaveEndpoint endpoint) {
            return checkEndpoint(endpoint);
        }
    }), any());
    verify(comms).registerRegularPoll(argThat(new TypeSafeMatcher<ModbusReadRequestBlueprint>() {

        @Override
        public void describeTo(Description description) {
        }

        @Override
        protected boolean matchesSafely(ModbusReadRequestBlueprint request) {
            return checkRequest(request, ModbusReadFunctionCode.READ_COILS);
        }
    }), eq(150l), eq(0L), argThat(new TypeSafeMatcher<ModbusReadCallback>() {

        @Override
        public void describeTo(Description description) {
        }

        @Override
        protected boolean matchesSafely(ModbusReadCallback callback) {
            callbackRef.set(callback);
            return true;
        }
    }), notNull());
    verifyNoMoreInteractions(mockedModbusManager);
    // reset call counts for easy assertions
    reset(mockedModbusManager);
    // remove the thing
    disposeThing(poller);
    // 1) should first unregister poll task
    verify(comms).unregisterRegularPoll(eq(pollTask));
    verifyNoMoreInteractions(mockedModbusManager);
}
Also used : PollTask(org.openhab.core.io.transport.modbus.PollTask) TypeSafeMatcher(org.hamcrest.TypeSafeMatcher) Description(org.hamcrest.Description) Configuration(org.openhab.core.config.core.Configuration) ModbusSlaveEndpoint(org.openhab.core.io.transport.modbus.endpoint.ModbusSlaveEndpoint) ModbusReadRequestBlueprint(org.openhab.core.io.transport.modbus.ModbusReadRequestBlueprint) ModbusReadCallback(org.openhab.core.io.transport.modbus.ModbusReadCallback) AtomicReference(java.util.concurrent.atomic.AtomicReference) Test(org.junit.jupiter.api.Test)

Example 48 with TypeSafeMatcher

use of org.hamcrest.TypeSafeMatcher in project openhab-addons by openhab.

the class ModbusPollerThingHandlerTest method testPollingGeneric.

public void testPollingGeneric(String type, ModbusReadFunctionCode expectedFunctionCode) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException {
    PollTask pollTask = Mockito.mock(PollTask.class);
    doReturn(pollTask).when(comms).registerRegularPoll(notNull(), eq(150l), eq(0L), notNull(), notNull());
    Configuration pollerConfig = new Configuration();
    pollerConfig.put("refresh", 150L);
    pollerConfig.put("start", 5);
    pollerConfig.put("length", 13);
    pollerConfig.put("type", type);
    poller = createPollerThingBuilder("poller").withConfiguration(pollerConfig).withBridge(endpoint.getUID()).build();
    addThing(poller);
    assertThat(poller.getStatusInfo().toString(), poller.getStatus(), is(equalTo(ThingStatus.ONLINE)));
    verifyEndpointBasicInitInteraction();
    verify(mockedModbusManager).newModbusCommunicationInterface(argThat(new TypeSafeMatcher<ModbusSlaveEndpoint>() {

        @Override
        public void describeTo(Description description) {
            description.appendText("correct endpoint (");
        }

        @Override
        protected boolean matchesSafely(ModbusSlaveEndpoint endpoint) {
            return checkEndpoint(endpoint);
        }
    }), any());
    verify(comms).registerRegularPoll(argThat(new TypeSafeMatcher<ModbusReadRequestBlueprint>() {

        @Override
        public void describeTo(Description description) {
            description.appendText("correct request");
        }

        @Override
        protected boolean matchesSafely(ModbusReadRequestBlueprint request) {
            return checkRequest(request, expectedFunctionCode);
        }
    }), eq(150l), eq(0L), notNull(), notNull());
    verifyNoMoreInteractions(mockedModbusManager);
}
Also used : PollTask(org.openhab.core.io.transport.modbus.PollTask) TypeSafeMatcher(org.hamcrest.TypeSafeMatcher) Description(org.hamcrest.Description) Configuration(org.openhab.core.config.core.Configuration) ModbusSlaveEndpoint(org.openhab.core.io.transport.modbus.endpoint.ModbusSlaveEndpoint) ModbusReadRequestBlueprint(org.openhab.core.io.transport.modbus.ModbusReadRequestBlueprint)

Example 49 with TypeSafeMatcher

use of org.hamcrest.TypeSafeMatcher in project fdb-record-layer by FoundationDB.

the class FDBRecordStoreIndexTest method markManyDisabled.

@Test
public void markManyDisabled() throws Exception {
    final Index[] indexes = new Index[100];
    for (int i = 0; i < indexes.length; i++) {
        indexes[i] = new Index(String.format("index-%d", i), "str_value_indexed");
    }
    final RecordMetaDataHook hook = metaData -> {
        final RecordTypeBuilder recordType = metaData.getRecordType("MySimpleRecord");
        for (int i = 0; i < indexes.length; i++) {
            metaData.addIndex(recordType, indexes[i]);
        }
    };
    // Such timing problems take several tries to show up.
    for (int j = 0; j < 10; j++) {
        try (FDBRecordContext context = openContext()) {
            openSimpleRecordStore(context, hook);
            List<CompletableFuture<Boolean>> futures = new ArrayList<>();
            List<Index> shouldBeDisabled = new ArrayList<>();
            // Expected contract: only use isIndexXXX and markIndexXXX and wait for all futures when done.
            for (int i = 0; i < indexes.length; i++) {
                if ((i % 2 == 0) || (i == 99 && recordStore.isIndexDisabled(indexes[i]))) {
                    futures.add(recordStore.markIndexDisabled(indexes[i]));
                    shouldBeDisabled.add(indexes[i]);
                }
            }
            AsyncUtil.whenAll(futures).join();
            for (Index index : shouldBeDisabled) {
                assertThat(index, new TypeSafeMatcher<Index>() {

                    @Override
                    protected boolean matchesSafely(Index item) {
                        return recordStore.isIndexDisabled(index);
                    }

                    @Override
                    public void describeTo(Description description) {
                        description.appendText("a disabled index");
                    }
                });
            }
        }
    }
}
Also used : BeforeEach(org.junit.jupiter.api.BeforeEach) Arrays(java.util.Arrays) LogMessageKeys(com.apple.foundationdb.record.logging.LogMessageKeys) MetaDataException(com.apple.foundationdb.record.metadata.MetaDataException) IndexScanType(com.apple.foundationdb.record.IndexScanType) Pair(org.apache.commons.lang3.tuple.Pair) FDBError(com.apple.foundationdb.FDBError) RecordCoreException(com.apple.foundationdb.record.RecordCoreException) RecordIndexUniquenessViolation(com.apple.foundationdb.record.RecordIndexUniquenessViolation) Expressions.concat(com.apple.foundationdb.record.metadata.Key.Expressions.concat) GroupingKeyExpression(com.apple.foundationdb.record.metadata.expressions.GroupingKeyExpression) Tag(org.junit.jupiter.api.Tag) Query(com.apple.foundationdb.record.query.expressions.Query) KeyExpression(com.apple.foundationdb.record.metadata.expressions.KeyExpression) IndexOptions(com.apple.foundationdb.record.metadata.IndexOptions) Set(java.util.Set) FanType(com.apple.foundationdb.record.metadata.expressions.KeyExpression.FanType) TupleRange(com.apple.foundationdb.record.TupleRange) Matchers.instanceOf(org.hamcrest.Matchers.instanceOf) RecordMetaDataProvider(com.apple.foundationdb.record.RecordMetaDataProvider) RecordStoreState(com.apple.foundationdb.record.RecordStoreState) TupleHelpers(com.apple.foundationdb.tuple.TupleHelpers) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) InvalidIndexEntry(com.apple.foundationdb.record.provider.foundationdb.indexes.InvalidIndexEntry) AutoContinuingCursor(com.apple.foundationdb.record.cursors.AutoContinuingCursor) Matchers.is(org.hamcrest.Matchers.is) Assertions.assertThrows(org.junit.jupiter.api.Assertions.assertThrows) Assertions.fail(org.junit.jupiter.api.Assertions.fail) FunctionNames(com.apple.foundationdb.record.FunctionNames) RecordMetaData(com.apple.foundationdb.record.RecordMetaData) Assertions.assertNotNull(org.junit.jupiter.api.Assertions.assertNotNull) IndexAggregateFunction(com.apple.foundationdb.record.metadata.IndexAggregateFunction) Assertions.assertNull(org.junit.jupiter.api.Assertions.assertNull) AsyncUtil(com.apple.foundationdb.async.AsyncUtil) ArrayList(java.util.ArrayList) Strings(com.google.common.base.Strings) CloseableAsyncIterator(com.apple.foundationdb.async.CloseableAsyncIterator) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) FDBRecordStoreBase.indexEntryKey(com.apple.foundationdb.record.provider.foundationdb.FDBRecordStoreBase.indexEntryKey) Nullable(javax.annotation.Nullable) Matchers.greaterThanOrEqualTo(org.hamcrest.Matchers.greaterThanOrEqualTo) IsolationLevel(com.apple.foundationdb.record.IsolationLevel) Tags(com.apple.test.Tags) TestRecords1EvolvedProto(com.apple.foundationdb.record.TestRecords1EvolvedProto) ExecutionException(java.util.concurrent.ExecutionException) Assertions.assertArrayEquals(org.junit.jupiter.api.Assertions.assertArrayEquals) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) Index(com.apple.foundationdb.record.metadata.Index) FDBException(com.apple.foundationdb.FDBException) ThenKeyExpression(com.apple.foundationdb.record.metadata.expressions.ThenKeyExpression) IndexEntry(com.apple.foundationdb.record.IndexEntry) StoreTimer(com.apple.foundationdb.record.provider.common.StoreTimer) LoggerFactory(org.slf4j.LoggerFactory) Assertions.assertNotEquals(org.junit.jupiter.api.Assertions.assertNotEquals) Random(java.util.Random) Tuple(com.apple.foundationdb.tuple.Tuple) Range(com.apple.foundationdb.Range) Assertions.assertFalse(org.junit.jupiter.api.Assertions.assertFalse) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Expressions.concatenateFields(com.apple.foundationdb.record.metadata.Key.Expressions.concatenateFields) ImmutableSet(com.google.common.collect.ImmutableSet) TestRecords1Proto(com.apple.foundationdb.record.TestRecords1Proto) ImmutableMap(com.google.common.collect.ImmutableMap) Matchers.lessThanOrEqualTo(org.hamcrest.Matchers.lessThanOrEqualTo) Collection(java.util.Collection) CompletionException(java.util.concurrent.CompletionException) IndexQueryabilityFilter(com.apple.foundationdb.record.query.IndexQueryabilityFilter) TypeSafeMatcher(org.hamcrest.TypeSafeMatcher) Collectors(java.util.stream.Collectors) Test(org.junit.jupiter.api.Test) List(java.util.List) EvaluationContext(com.apple.foundationdb.record.EvaluationContext) Matchers.equalTo(org.hamcrest.Matchers.equalTo) IndexTypes(com.apple.foundationdb.record.metadata.IndexTypes) Optional(java.util.Optional) TestNoIndexesProto(com.apple.foundationdb.record.TestNoIndexesProto) LazyCursor(com.apple.foundationdb.record.cursors.LazyCursor) EnumSource(org.junit.jupiter.params.provider.EnumSource) CompletableFuture(java.util.concurrent.CompletableFuture) Iterators(com.google.common.collect.Iterators) Key(com.apple.foundationdb.record.metadata.Key) FieldKeyExpression(com.apple.foundationdb.record.metadata.expressions.FieldKeyExpression) HashSet(java.util.HashSet) ExecuteProperties(com.apple.foundationdb.record.ExecuteProperties) ScanProperties(com.apple.foundationdb.record.ScanProperties) RecordCursorIterator(com.apple.foundationdb.record.RecordCursorIterator) BooleanSource(com.apple.test.BooleanSource) Nonnull(javax.annotation.Nonnull) Expressions.field(com.apple.foundationdb.record.metadata.Key.Expressions.field) EmptyKeyExpression(com.apple.foundationdb.record.metadata.expressions.EmptyKeyExpression) Matchers.hasEntry(org.hamcrest.Matchers.hasEntry) Description(org.hamcrest.Description) Matchers.oneOf(org.hamcrest.Matchers.oneOf) Logger(org.slf4j.Logger) RecordMetaDataBuilder(com.apple.foundationdb.record.RecordMetaDataBuilder) RecordTypeBuilder(com.apple.foundationdb.record.metadata.RecordTypeBuilder) IndexState(com.apple.foundationdb.record.IndexState) TestRecordsIndexFilteringProto(com.apple.foundationdb.record.TestRecordsIndexFilteringProto) Message(com.google.protobuf.Message) Collections(java.util.Collections) Description(org.hamcrest.Description) ArrayList(java.util.ArrayList) Index(com.apple.foundationdb.record.metadata.Index) RecordTypeBuilder(com.apple.foundationdb.record.metadata.RecordTypeBuilder) CompletableFuture(java.util.concurrent.CompletableFuture) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) Test(org.junit.jupiter.api.Test)

Example 50 with TypeSafeMatcher

use of org.hamcrest.TypeSafeMatcher in project mod-inventory by folio-org.

the class ResponseMatchers method hasValidationError.

public static Matcher<Response> hasValidationError(String expectedMessage, String expectedKey, String expectedValue) {
    return new TypeSafeMatcher<Response>() {

        @Override
        protected boolean matchesSafely(Response response) {
            if (response.getStatusCode() != 422) {
                return false;
            }
            if (!response.getContentType().startsWith(ContentType.APPLICATION_JSON)) {
                return false;
            }
            try {
                JsonArray errors = response.getJson().getJsonArray("errors");
                if (errors != null && errors.size() == 1) {
                    JsonObject error = errors.getJsonObject(0);
                    JsonArray parameters = error.getJsonArray("parameters");
                    if (parameters != null && parameters.size() == 1) {
                        String message = error.getString("message");
                        String key = parameters.getJsonObject(0).getString("key");
                        String value = parameters.getJsonObject(0).getString("value");
                        return Objects.equals(expectedMessage, message) && Objects.equals(expectedKey, key) && Objects.equals(expectedValue, value);
                    }
                }
                return false;
            } catch (DecodeException ex) {
                return false;
            }
        }

        @Override
        public void describeTo(Description description) {
            description.appendText("Response has 422 status and 'message' - ").appendValue(expectedMessage).appendText(", 'key' - ").appendValue(expectedKey).appendText(" and 'value' - ").appendValue(expectedValue);
        }

        @Override
        protected void describeMismatchSafely(Response response, Description mismatchDescription) {
            mismatchDescription.appendText("Status: ").appendValue(response.getStatusCode()).appendText(", body: ");
            if (response.getContentType().startsWith(ContentType.APPLICATION_JSON)) {
                mismatchDescription.appendValue(response.getJson());
            } else {
                mismatchDescription.appendValue(response.getBody());
            }
        }
    };
}
Also used : Response(org.folio.inventory.support.http.client.Response) JsonArray(io.vertx.core.json.JsonArray) TypeSafeMatcher(org.hamcrest.TypeSafeMatcher) Description(org.hamcrest.Description) JsonObject(io.vertx.core.json.JsonObject) DecodeException(io.vertx.core.json.DecodeException)

Aggregations

TypeSafeMatcher (org.hamcrest.TypeSafeMatcher)124 Description (org.hamcrest.Description)121 View (android.view.View)62 ViewParent (android.view.ViewParent)43 ViewGroup (android.view.ViewGroup)40 Espresso.onView (android.support.test.espresso.Espresso.onView)26 Espresso.onView (androidx.test.espresso.Espresso.onView)11 TextView (android.widget.TextView)10 Resources (android.content.res.Resources)9 Test (org.junit.Test)9 ViewMatchers.withContentDescription (android.support.test.espresso.matcher.ViewMatchers.withContentDescription)8 RecyclerView (androidx.recyclerview.widget.RecyclerView)7 ArrayList (java.util.ArrayList)6 JsonNode (org.codehaus.jackson.JsonNode)6 JsonParseException (org.neo4j.server.rest.domain.JsonParseException)6 HTTP (org.neo4j.test.server.HTTP)6 ViewMatchers.withContentDescription (androidx.test.espresso.matcher.ViewMatchers.withContentDescription)5 List (java.util.List)5 StringDescription (org.hamcrest.StringDescription)5 AdapterView (android.widget.AdapterView)4