Some polishing for test-support module

* Remove `TypeSafeMatcher` in favor of the same class in Hamcrest
* Resolve `serial` warning with `OnFailedToAcquireMutexEvent`
This commit is contained in:
Artem Bilan
2017-10-13 20:38:31 -04:00
parent 1979f91cf5
commit a5d30b9f66
10 changed files with 82 additions and 173 deletions

View File

@@ -26,6 +26,7 @@ import org.springframework.integration.leader.Context;
*
* @since 5.0
*/
@SuppressWarnings("serial")
public class OnFailedToAcquireMutexEvent extends AbstractLeaderEvent {
/**

View File

@@ -16,43 +16,46 @@
package org.springframework.integration.test.matcher;
import java.util.function.Supplier;
import org.hamcrest.Description;
import org.hamcrest.DiagnosingMatcher;
import org.hamcrest.Factory;
import org.springframework.util.ObjectUtils;
/**
* A matcher that evaluates against the result of invoking a function,
* wrapped by the {@link EqualsResultMatcher.Evaluator}
* wrapped by the {@link java.util.function.Supplier}
*
* The goal is to defer the computation until the matcher needs to be actually evaluated.
* Mainly useful in conjunction with retrying matchers such as {@link EventuallyMatcher}
*
* @author Marius Bogoevici
* @author Artem Bilan
*
* @since 4.2
*/
public class EqualsResultMatcher<U> extends DiagnosingMatcher<U> {
private final Evaluator<U> evaluator;
private final Supplier<U> supplier;
public EqualsResultMatcher(Evaluator<U> evaluator) {
this.evaluator = evaluator;
public EqualsResultMatcher(Supplier<U> supplier) {
this.supplier = supplier;
}
@Override
protected boolean matches(Object item, Description mismatchDescription) {
return ObjectUtils.nullSafeEquals(item, evaluator.evaluate());
return ObjectUtils.nullSafeEquals(item, supplier.get());
}
@Override
public void describeTo(Description description) {
}
public interface Evaluator<U> {
U evaluate();
@Factory
public static <U> EqualsResultMatcher<U> equalsResult(Supplier<U> supplier) {
return new EqualsResultMatcher<>(supplier);
}
public static <U> EqualsResultMatcher<U> equalsResult(Evaluator<U> evaluator) {
return new EqualsResultMatcher<U>(evaluator);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2016 the original author or authors.
* Copyright 2013-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,6 +18,7 @@ package org.springframework.integration.test.matcher;
import org.hamcrest.Description;
import org.hamcrest.DiagnosingMatcher;
import org.hamcrest.Factory;
import org.hamcrest.Matcher;
@@ -26,9 +27,9 @@ import org.hamcrest.Matcher;
*
* @param <U> the type the wrapped matcher operates on
*
* (Copied from {@code org.springframework.xd.test.fixtures.EventuallyMatcher})
*
* @author Eric Bottard
* @author Artem Bilan
*
* @since 4.2
*/
public class EventuallyMatcher<U> extends DiagnosingMatcher<U> {
@@ -49,32 +50,36 @@ public class EventuallyMatcher<U> extends DiagnosingMatcher<U> {
this.pause = pause;
}
@Factory
public static <U> Matcher<U> eventually(int nbAttempts, int pause, Matcher<U> delegate) {
return new EventuallyMatcher<U>(delegate, nbAttempts, pause);
return new EventuallyMatcher<>(delegate, nbAttempts, pause);
}
@Factory
public static <U> Matcher<U> eventually(Matcher<U> delegate) {
return new EventuallyMatcher<U>(delegate);
return new EventuallyMatcher<>(delegate);
}
@Override
public void describeTo(Description description) {
description.appendDescriptionOf(delegate).appendText(String.format(", trying at most %d times", nbAttempts));
description.appendDescriptionOf(this.delegate)
.appendText(String.format(", trying at most %d times", this.nbAttempts));
}
@Override
protected boolean matches(Object item, Description mismatchDescription) {
mismatchDescription.appendText(String.format("failed after %d*%d=%dms:%n", nbAttempts, pause, nbAttempts
* pause));
for (int i = 0; i < nbAttempts; i++) {
boolean result = delegate.matches(item);
mismatchDescription.appendText(
String.format("failed after %d*%d=%dms:%n", this.nbAttempts, this.pause, this.nbAttempts * this.pause));
for (int i = 0; i < this.nbAttempts; i++) {
boolean result = this.delegate.matches(item);
if (result) {
return true;
}
delegate.describeMismatch(item, mismatchDescription);
this.delegate.describeMismatch(item, mismatchDescription);
mismatchDescription.appendText(", ");
try {
Thread.sleep(pause);
Thread.sleep(this.pause);
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
@@ -83,4 +88,5 @@ public class EventuallyMatcher<U> extends DiagnosingMatcher<U> {
}
return false;
}
}

View File

@@ -23,6 +23,7 @@ import org.hamcrest.CoreMatchers;
import org.hamcrest.Description;
import org.hamcrest.Factory;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
import org.junit.Assert;
import org.springframework.messaging.Message;
@@ -70,7 +71,7 @@ import org.springframework.messaging.MessageHeaders;
* @author Artem Bilan
*
*/
public class HeaderMatcher extends TypeSafeMatcher<Message<?>> {
public class HeaderMatcher<T> extends TypeSafeMatcher<Message<T>> {
private final Matcher<?> matcher;
@@ -83,7 +84,7 @@ public class HeaderMatcher extends TypeSafeMatcher<Message<?>> {
}
@Override
public boolean matchesSafely(Message<?> item) {
public boolean matchesSafely(Message<T> item) {
return this.matcher.matches(item.getHeaders());
}
@@ -94,73 +95,73 @@ public class HeaderMatcher extends TypeSafeMatcher<Message<?>> {
}
@Factory
public static <T> Matcher<Message<?>> hasHeader(String key, T value) {
return new HeaderMatcher(MapContentMatchers.hasEntry(key, value));
public static <P, V> HeaderMatcher<P> hasHeader(String key, V value) {
return new HeaderMatcher<>(MapContentMatchers.hasEntry(key, value));
}
@Factory
public static <T> Matcher<Message<?>> hasHeader(String key, Matcher<T> valueMatcher) {
return new HeaderMatcher(MapContentMatchers.hasEntry(key, valueMatcher));
public static <P, V> HeaderMatcher<P> hasHeader(String key, Matcher<V> valueMatcher) {
return new HeaderMatcher<>(MapContentMatchers.hasEntry(key, valueMatcher));
}
@Factory
public static Matcher<Message<?>> hasHeaderKey(String key) {
return new HeaderMatcher(MapContentMatchers.hasKey(key));
public static <P> HeaderMatcher<P> hasHeaderKey(String key) {
return new HeaderMatcher<>(MapContentMatchers.hasKey(key));
}
@Factory
public static Matcher<Message<?>> hasAllHeaders(Map<String, ?> entries) {
return new HeaderMatcher(MapContentMatchers.hasAllEntries(entries));
public static <P> HeaderMatcher<P> hasAllHeaders(Map<String, ?> entries) {
return new HeaderMatcher<>(MapContentMatchers.hasAllEntries(entries));
}
@Factory
public static <T> Matcher<Message<?>> hasMessageId(T value) {
return new HeaderMatcher(MapContentMatchers.hasEntry(MessageHeaders.ID, value));
public static <P, V> HeaderMatcher<P> hasMessageId(V value) {
return new HeaderMatcher<>(MapContentMatchers.hasEntry(MessageHeaders.ID, value));
}
@Factory
public static <T> Matcher<Message<?>> hasCorrelationId(T value) {
return new HeaderMatcher(MapContentMatchers.hasEntry("correlationId", value));
public static <P, V> HeaderMatcher<P> hasCorrelationId(V value) {
return new HeaderMatcher<>(MapContentMatchers.hasEntry("correlationId", value));
}
@Factory
public static Matcher<Message<?>> hasSequenceNumber(Integer value) {
public static <P> HeaderMatcher<P> hasSequenceNumber(Integer value) {
return hasSequenceNumber(CoreMatchers.is(value));
}
@Factory
public static Matcher<Message<?>> hasSequenceNumber(Matcher<Integer> matcher) {
return new HeaderMatcher(MapContentMatchers.hasEntry("sequenceNumber", matcher));
public static <P> HeaderMatcher<P> hasSequenceNumber(Matcher<Integer> matcher) {
return new HeaderMatcher<>(MapContentMatchers.hasEntry("sequenceNumber", matcher));
}
@Factory
public static Matcher<Message<?>> hasSequenceSize(Integer value) {
public static <P> HeaderMatcher<P> hasSequenceSize(Integer value) {
return hasSequenceSize(CoreMatchers.is(value));
}
@Factory
public static Matcher<Message<?>> hasSequenceSize(Matcher<Integer> value) {
return new HeaderMatcher(MapContentMatchers.hasEntry("sequenceSize", value));
public static <P> HeaderMatcher<P> hasSequenceSize(Matcher<Integer> value) {
return new HeaderMatcher<>(MapContentMatchers.hasEntry("sequenceSize", value));
}
@Factory
public static Matcher<Message<?>> hasExpirationDate(Date value) {
public static <P> HeaderMatcher<P> hasExpirationDate(Date value) {
return hasExpirationDate(CoreMatchers.is(value.getTime()));
}
@Factory
public static Matcher<Message<?>> hasExpirationDate(Matcher<Long> matcher) {
return new HeaderMatcher(MapContentMatchers.hasEntry("expirationDate", matcher));
public static <P> HeaderMatcher<P> hasExpirationDate(Matcher<Long> matcher) {
return new HeaderMatcher<>(MapContentMatchers.hasEntry("expirationDate", matcher));
}
@Factory
public static Matcher<Message<?>> hasTimestamp(Date value) {
public static <P> HeaderMatcher<P> hasTimestamp(Date value) {
return hasTimestamp(CoreMatchers.is(value.getTime()));
}
@Factory
public static Matcher<Message<?>> hasTimestamp(Matcher<Long> matcher) {
return new HeaderMatcher(MapContentMatchers.hasEntry(MessageHeaders.TIMESTAMP, matcher));
public static <P> HeaderMatcher<P> hasTimestamp(Matcher<Long> matcher) {
return new HeaderMatcher<>(MapContentMatchers.hasEntry(MessageHeaders.TIMESTAMP, matcher));
}
}

View File

@@ -24,6 +24,7 @@ import org.hamcrest.Description;
import org.hamcrest.Factory;
import org.hamcrest.Matcher;
import org.hamcrest.Matchers;
import org.hamcrest.TypeSafeMatcher;
import org.hamcrest.core.AllOf;
/**
@@ -63,8 +64,7 @@ import org.hamcrest.core.AllOf;
* @author Artem Bilan
*
*/
public class MapContentMatchers<T, V> extends
TypeSafeMatcher<Map<? super T, ? super V>> {
public class MapContentMatchers<T, V> extends TypeSafeMatcher<Map<? super T, ? super V>> {
private final T key;

View File

@@ -89,7 +89,7 @@ public class MockitoMessageMatchers {
}
public static <T> Message<?> messageWithHeaderEntry(String key, Matcher<T> valueMatcher) {
return ArgumentMatchers.argThat(new HamcrestArgumentMatcher<>(HeaderMatcher.<T>hasHeader(key, valueMatcher)));
return ArgumentMatchers.argThat(new HamcrestArgumentMatcher<>(HeaderMatcher.hasHeader(key, valueMatcher)));
}
public static Message<?> messageWithHeaderEntries(Map<String, ?> entries) {

View File

@@ -22,7 +22,6 @@ import java.util.Map;
import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
import org.hamcrest.Factory;
import org.hamcrest.Matcher;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
@@ -50,20 +49,20 @@ import org.springframework.messaging.MessageHeaders;
* @author Artem Bilan
*
*/
public class PayloadAndHeaderMatcher extends BaseMatcher<Message<?>> {
public class PayloadAndHeaderMatcher<T> extends BaseMatcher<Message<?>> {
private final Object payload;
private final T payload;
private final Map<String, Object> headers;
private final String[] ignoreKeys;
@Factory
public static Matcher<Message<?>> sameExceptIgnorableHeaders(Message<?> expected, String... ignoreKeys) {
return new PayloadAndHeaderMatcher(expected, ignoreKeys);
public static <P> PayloadAndHeaderMatcher<P> sameExceptIgnorableHeaders(Message<P> expected, String... ignoreKeys) {
return new PayloadAndHeaderMatcher<>(expected, ignoreKeys);
}
private PayloadAndHeaderMatcher(Message<?> expected, String... ignoreKeys) {
private PayloadAndHeaderMatcher(Message<T> expected, String... ignoreKeys) {
this.ignoreKeys = ignoreKeys;
this.payload = expected.getPayload();
this.headers = extractHeadersToAssert(expected);

View File

@@ -19,6 +19,7 @@ package org.springframework.integration.test.matcher;
import org.hamcrest.Description;
import org.hamcrest.Factory;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
import org.hamcrest.core.IsEqual;
import org.junit.Assert;
@@ -54,16 +55,17 @@ import org.springframework.messaging.Message;
*
* @author Alex Peters
* @author Iwein Fuld
* @author Artem Bilan
*
*/
public class PayloadMatcher extends TypeSafeMatcher<Message<?>> {
public class PayloadMatcher<T> extends TypeSafeMatcher<Message<?>> {
private final Matcher<?> matcher;
private final Matcher<T> matcher;
/**
* Create a PayloadMatcher that matches the payload of messages against the given matcher
*/
private PayloadMatcher(Matcher<?> matcher) {
private PayloadMatcher(Matcher<T> matcher) {
super();
this.matcher = matcher;
}
@@ -81,13 +83,13 @@ public class PayloadMatcher extends TypeSafeMatcher<Message<?>> {
}
@Factory
public static <T> Matcher<Message<?>> hasPayload(T payload) {
return new PayloadMatcher(IsEqual.equalTo(payload));
public static <P> PayloadMatcher<P> hasPayload(P payload) {
return new PayloadMatcher<>(IsEqual.equalTo(payload));
}
@Factory
public static <T> Matcher<Message<?>> hasPayload(Matcher<? super T> payloadMatcher) {
return new PayloadMatcher(payloadMatcher);
public static <P> PayloadMatcher<P> hasPayload(Matcher<P> payloadMatcher) {
return new PayloadMatcher<>(payloadMatcher);
}
}

View File

@@ -1,84 +0,0 @@
/*
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.test.matcher;
import java.lang.reflect.Method;
import org.hamcrest.BaseMatcher;
/**
* This class was copied from JUnit to avoid using it from org.junit.internal (causing a backwards compatibility issue).
* If you want to extend this class use a recent version of JUnit, and extend
* <code>org.junit.matchers.TypeSafeMatcher</code>
* <p>
* Convenient base class for Matchers that require a non-null value of a specific type.
* This simply implements the null check, checks the type and then casts.
*
* @author Joe Walnes
*/
abstract class TypeSafeMatcher<T> extends BaseMatcher<T> {
private final Class<?> expectedType;
/**
* Subclasses should implement this. The item will already have been checked for
* the specific type and will never be null.
*
* @param item The item.
* @return true if matches.
*/
public abstract boolean matchesSafely(T item);
protected TypeSafeMatcher() {
expectedType = findExpectedType(getClass());
}
private static Class<?> findExpectedType(Class<?> fromClass) {
for (Class<?> c = fromClass; c != Object.class; c = c.getSuperclass()) {
for (Method method : c.getDeclaredMethods()) {
if (isMatchesSafelyMethod(method)) {
return method.getParameterTypes()[0];
}
}
}
throw new Error("Cannot determine correct type for matchesSafely() method.");
}
private static boolean isMatchesSafelyMethod(Method method) {
return method.getName().equals("matchesSafely")
&& method.getParameterTypes().length == 1
&& !method.isSynthetic();
}
protected TypeSafeMatcher(Class<T> expectedType) {
this.expectedType = expectedType;
}
/**
* Method made final to prevent accidental override.
* If you need to override this, there's no point on extending TypeSafeMatcher.
* Instead, extend the {@link BaseMatcher}.
*/
@Override
@SuppressWarnings({ "unchecked" })
public final boolean matches(Object item) {
return item != null
&& expectedType.isInstance(item)
&& matchesSafely((T) item);
}
}

View File

@@ -47,7 +47,6 @@ import org.springframework.beans.DirectFieldAccessor;
import org.springframework.integration.metadata.MetadataStoreListener;
import org.springframework.integration.metadata.MetadataStoreListenerAdapter;
import org.springframework.integration.support.utils.IntegrationUtils;
import org.springframework.integration.test.matcher.EqualsResultMatcher.Evaluator;
import org.springframework.integration.zookeeper.ZookeeperTestSupport;
/**
@@ -115,22 +114,12 @@ public class ZookeeperMetadataStoreTests extends ZookeeperTestSupport {
assertEquals("Integration",
IntegrationUtils.bytesToString(client.getData().forPath(metadataStore.getPath(testKey)), "UTF-8"));
assertEquals("Integration", metadataStore.get(testKey));
assertThat("Integration", eventually(equalsResult(new Evaluator<String>() {
@Override
public String evaluate() {
return otherMetadataStore.get(testKey);
}
})));
assertThat("Integration", eventually(equalsResult(() -> otherMetadataStore.get(testKey))));
otherMetadataStore.putIfAbsent(testKey2, "Integration-2");
assertEquals("Integration-2",
IntegrationUtils.bytesToString(client.getData().forPath(metadataStore.getPath(testKey2)), "UTF-8"));
assertEquals("Integration-2", otherMetadataStore.get(testKey2));
assertThat("Integration-2", eventually(equalsResult(new Evaluator<String>() {
@Override
public String evaluate() {
return metadataStore.get(testKey2);
}
})));
assertThat("Integration-2", eventually(equalsResult(() -> otherMetadataStore.get(testKey2))));
CloseableUtils.closeQuietly(otherClient);
}
@@ -148,21 +137,11 @@ public class ZookeeperMetadataStoreTests extends ZookeeperTestSupport {
assertEquals("Integration",
IntegrationUtils.bytesToString(client.getData().forPath(metadataStore.getPath(testKey)), "UTF-8"));
assertEquals("Integration", metadataStore.get(testKey));
assertThat("Integration", eventually(equalsResult(new Evaluator<String>() {
@Override
public String evaluate() {
return otherMetadataStore.get(testKey);
}
})));
assertThat("Integration", eventually(equalsResult(() -> otherMetadataStore.get(testKey))));
otherMetadataStore.replace(testKey, "Integration", "Integration-2");
assertEquals("Integration-2",
IntegrationUtils.bytesToString(client.getData().forPath(metadataStore.getPath(testKey)), "UTF-8"));
assertThat("Integration-2", eventually(equalsResult(new Evaluator<String>() {
@Override
public String evaluate() {
return metadataStore.get(testKey);
}
})));
assertThat("Integration-2", eventually(equalsResult(() -> metadataStore.get(testKey))));
assertEquals("Integration-2", otherMetadataStore.get(testKey));
CloseableUtils.closeQuietly(otherClient);
}
@@ -246,6 +225,7 @@ public class ZookeeperMetadataStoreTests extends ZookeeperTestSupport {
assertThat(e.getMessage(), containsString("'listener' must not be null"));
}
metadataStore.addListener(new MetadataStoreListenerAdapter() {
@Override
public void onAdd(String key, String value) {
notifiedChanges.add(Arrays.asList("add", key, value));
@@ -316,6 +296,7 @@ public class ZookeeperMetadataStoreTests extends ZookeeperTestSupport {
barriers.put("remove", new CyclicBarrier(2));
barriers.put("update", new CyclicBarrier(2));
metadataStore.addListener(new MetadataStoreListenerAdapter() {
@Override
public void onAdd(String key, String value) {
notifiedChanges.add(Arrays.asList("add", key, value));