DATAGEODE-60 - Add support for JSR-107 JCache API Annotations in Caching-defined Regions.

This commit is contained in:
John Blum
2017-11-17 20:09:06 -08:00
parent a2129dc17b
commit 3f7bad8f0f
16 changed files with 736 additions and 245 deletions

View File

@@ -45,6 +45,7 @@ public class GemfireUtilsTest {
@Test
public void isClientWithClientIsTrue() {
ClientCache mockClient = mock(ClientCache.class);
assertThat(GemfireUtils.isClient(mockClient), is(true));
@@ -54,6 +55,7 @@ public class GemfireUtilsTest {
@Test
public void isClientWithNonClientIsFalse() {
Cache mockCache = mock(Cache.class);
assertThat(GemfireUtils.isClient(mockCache), is(false));
@@ -63,7 +65,9 @@ public class GemfireUtilsTest {
@Test
public void isDurableWithDurableClientIsTrue() {
ClientCache mockClientCache = mock(ClientCache.class);
DistributedSystem mockDistributedSystem = mock(DistributedSystem.class);
Properties gemfireProperties = new Properties();
@@ -83,7 +87,9 @@ public class GemfireUtilsTest {
@Test
public void isDurableWithNonDurableClientIsFalse() {
ClientCache mockClientCache = mock(ClientCache.class);
DistributedSystem mockDistributedSystem = mock(DistributedSystem.class);
Properties gemfireProperties = new Properties();
@@ -103,7 +109,9 @@ public class GemfireUtilsTest {
@Test
public void isDurableWhenDistributedSystemIsNotConnectedIsFalse() {
ClientCache mockClientCache = mock(ClientCache.class);
DistributedSystem mockDistributedSystem = mock(DistributedSystem.class);
when(mockClientCache.getDistributedSystem()).thenReturn(mockDistributedSystem);
@@ -118,6 +126,7 @@ public class GemfireUtilsTest {
@Test
public void isPeerWithPeerIsTrue() {
Cache mockCache = mock(Cache.class);
assertThat(GemfireUtils.isPeer(mockCache), is(true));
@@ -127,11 +136,11 @@ public class GemfireUtilsTest {
@Test
public void isPeerWithNonPeerIsFalse() {
ClientCache mockClientCache = mock(ClientCache.class);
assertThat(GemfireUtils.isPeer(mockClientCache), is(false));
verifyZeroInteractions(mockClientCache);
}
}

View File

@@ -20,11 +20,16 @@ import static org.assertj.core.api.Assertions.assertThat;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.cache.annotation.CacheDefaults;
import javax.cache.annotation.CacheRemoveAll;
import javax.cache.annotation.CacheResult;
import org.apache.geode.cache.GemFireCache;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.ApplicationContext;
@@ -48,44 +53,58 @@ public class EnableCachingDefinedRegionsIntegrationTests {
private ApplicationContext applicationContext;
@Autowired
private CacheableEchoService echoService;
private JCacheEchoService jcacheEchoService;
@Autowired
private SpringCacheableEchoService springEchoService;
@Autowired
private GemFireCache gemfireCache;
@Before
public void setup() {
//System.err.printf("@Cacheable Beans [%s]%n",
// Arrays.toString(applicationContext.getBeanNamesForAnnotation(Cacheable.class)));
assertThat(this.gemfireCache).isNotNull();
//System.err.printf("Cache Regions [%s]%n", this.gemfireCache.rootRegions().stream()
// .map(Region::getFullPath).collect(Collectors.toSet()));
}
@Test
public void cacheRegionsExists() {
assertThat(gemfireCache.getRegion("/Example")).isNotNull();
assertThat(gemfireCache.getRegion("/Echo")).isNotNull();
assertThat(gemfireCache.getRegion("/JCacheOne")).isNotNull();
assertThat(gemfireCache.getRegion("/JCacheTwo")).isNotNull();
assertThat(gemfireCache.getRegion("/SpringOne")).isNotNull();
}
@Test
public void echoServiceOperationsAreSuccessful() {
public void echoServiceCachingWithJCacheIsSuccessful() {
assertThat(echoService.isCacheMiss()).isFalse();
assertThat(echoService.echo("one")).isEqualTo("one");
assertThat(echoService.isCacheMiss()).isTrue();
assertThat(echoService.echo("two")).isEqualTo("two");
assertThat(echoService.isCacheMiss()).isTrue();
assertThat(echoService.echo("one")).isEqualTo("one");
assertThat(echoService.isCacheMiss()).isFalse();
assertThat(echoService.echo("three")).isEqualTo("three");
assertThat(echoService.isCacheMiss()).isTrue();
assertThat(echoService.echo("two")).isEqualTo("two");
assertThat(echoService.isCacheMiss()).isFalse();
assertThat(jcacheEchoService.isCacheMiss()).isFalse();
assertThat(jcacheEchoService.echo("four")).isEqualTo("four");
assertThat(jcacheEchoService.isCacheMiss()).isTrue();
assertThat(jcacheEchoService.echo("five")).isEqualTo("five");
assertThat(jcacheEchoService.isCacheMiss()).isTrue();
assertThat(jcacheEchoService.echo("four")).isEqualTo("four");
assertThat(jcacheEchoService.isCacheMiss()).isFalse();
assertThat(jcacheEchoService.echo("six")).isEqualTo("six");
assertThat(jcacheEchoService.isCacheMiss()).isTrue();
assertThat(jcacheEchoService.echo("five")).isEqualTo("five");
assertThat(jcacheEchoService.isCacheMiss()).isFalse();
}
@Test
public void echoServiceCachingWithSpringIsSuccessful() {
assertThat(springEchoService.isCacheMiss()).isFalse();
assertThat(springEchoService.echo("one")).isEqualTo("one");
assertThat(springEchoService.isCacheMiss()).isTrue();
assertThat(springEchoService.echo("two")).isEqualTo("two");
assertThat(springEchoService.isCacheMiss()).isTrue();
assertThat(springEchoService.echo("one")).isEqualTo("one");
assertThat(springEchoService.isCacheMiss()).isFalse();
assertThat(springEchoService.echo("three")).isEqualTo("three");
assertThat(springEchoService.isCacheMiss()).isTrue();
assertThat(springEchoService.echo("two")).isEqualTo("two");
assertThat(springEchoService.isCacheMiss()).isFalse();
}
@PeerCacheApplication(name = "EnableCachingDefinedRegionsIntegrationTests", logLevel = "warning")
@@ -93,18 +112,28 @@ public class EnableCachingDefinedRegionsIntegrationTests {
static class TestConfiguration {
@Bean
CacheableEchoService echoService() {
return new CacheableEchoService();
JCacheEchoService jcacheEchoService() {
return new JCacheEchoService();
}
@Bean
TestService testService() {
return new CachingTestService();
@Qualifier("Spring")
SpringCacheableEchoService springEchoService() {
return new SpringCacheableEchoService();
}
@Bean
TestService testServiceOne() {
return new SpringCachingTestService();
}
@Bean
TestService testServiceTwo() {
return new Jsr107CachingTestService();
}
}
@Service
static class CacheableEchoService {
static abstract class AbstractCacheableService {
private final AtomicBoolean cacheMiss = new AtomicBoolean(false);
@@ -112,9 +141,27 @@ public class EnableCachingDefinedRegionsIntegrationTests {
return this.cacheMiss.compareAndSet(true, false);
}
public void setCacheMiss() {
this.cacheMiss.set(true);
}
}
@Service
static class JCacheEchoService extends AbstractCacheableService {
@CacheResult(cacheName = "Echo")
public Object echo(String key) {
setCacheMiss();
return key;
}
}
@Service
static class SpringCacheableEchoService extends AbstractCacheableService {
@Cacheable("Echo")
public Object echo(String key) {
this.cacheMiss.set(true);
setCacheMiss();
return key;
}
}
@@ -123,9 +170,19 @@ public class EnableCachingDefinedRegionsIntegrationTests {
Object testMethod(String key);
}
static class CachingTestService implements TestService {
@CacheDefaults(cacheName = "JCacheOne")
@CacheRemoveAll(cacheName = "SpringOne")
static class Jsr107CachingTestService implements TestService {
@CachePut("Example")
@CacheResult(cacheName = "JCacheTwo")
public Object testMethod(String key) {
return null;
}
}
static class SpringCachingTestService implements TestService {
@CachePut("SpringOne")
public Object testMethod(String key) {
return "test";
}

View File

@@ -33,6 +33,11 @@ import java.util.Arrays;
import java.util.Map;
import java.util.Set;
import javax.cache.annotation.CacheDefaults;
import javax.cache.annotation.CacheRemove;
import javax.cache.annotation.CacheRemoveAll;
import javax.cache.annotation.CacheResult;
import org.apache.geode.cache.RegionShortcut;
import org.apache.geode.cache.client.ClientRegionShortcut;
import org.junit.Before;
@@ -88,7 +93,7 @@ public class EnableCachingDefinedRegionsUnitTests {
return mockBeanDefinition;
}
catch (ClassNotFoundException cause) {
throw newRuntimeException(cause, "Mock for class [%s] failed", beanClass.getName());
throw newRuntimeException(cause, "Creating a mock for class [%s] failed", beanClass.getName());
}
}
@@ -111,6 +116,16 @@ public class EnableCachingDefinedRegionsUnitTests {
return mockBeanDefinitionRegistry;
}
@Test
public void annotationTypeIsEnableCachingDefinedRegions() {
assertThat(this.configuration.getAnnotationType()).isEqualTo(EnableCachingDefinedRegions.class);
}
@Test
public void getCacheNameResolverIsConfiguredProperly() {
assertThat(this.configuration.getCacheNameResolver()).isNotNull();
}
@Test
public void setGetAndResolveClientRegionShortcut() {
@@ -319,13 +334,15 @@ public class EnableCachingDefinedRegionsUnitTests {
verify(mockBeanDefinitionRegistry, times(registeredRegionBeanNames.size()))
.registerBeanDefinition(anyString(), any(BeanDefinition.class));
registeredRegionBeanNames.forEach(beanName ->
registeredRegionBeanNames.forEach(beanName -> {
verify(mockBeanDefinitionRegistry, times(1)).containsBeanDefinition(eq(beanName));
verify(mockBeanDefinitionRegistry, times(1))
.registerBeanDefinition(eq(beanName), any(BeanDefinition.class)));
.registerBeanDefinition(eq(beanName), any(BeanDefinition.class));
});
}
@Test
public void cacheableServiceOneTwoThreeRegistersTwentyTwoRegionBeans() {
public void cacheableServiceOneTwoAndThreeRegistersTwentyTwoRegionBeans() {
Map<String, BeanDefinition> registeredBeanDefinitions = MapBuilder.<String, BeanDefinition>newMapBuilder()
.put("cacheableServiceOne", mockBeanDefinition(CacheableServiceOne.class))
@@ -345,45 +362,110 @@ public class EnableCachingDefinedRegionsUnitTests {
verify(mockBeanDefinitionRegistry, times(1)).getBeanDefinitionNames();
verify(mockBeanDefinitionRegistry, times(1))
.getBeanDefinition(eq("cacheableServiceOne"));
verify(mockBeanDefinitionRegistry, times(1))
.getBeanDefinition(eq("cacheableServiceTwo"));
verify(mockBeanDefinitionRegistry, times(1))
.getBeanDefinition(eq("cacheableServiceThree"));
Arrays.asList("cacheableServiceOne", "cacheableServiceTwo", "cacheableServiceThree").forEach(beanName ->
verify(mockBeanDefinitionRegistry, times(1)).getBeanDefinition(eq(beanName)));
verify(mockBeanDefinitionRegistry, times(registeredRegionBeanNames.size()))
.registerBeanDefinition(anyString(), any(BeanDefinition.class));
registeredRegionBeanNames.forEach(beanName ->
registeredRegionBeanNames.forEach(beanName -> {
int wantedNumberOfInvocations = "RegionSix".equals(beanName) || "RegionTwo".equals(beanName) ? 2 : 1;
verify(mockBeanDefinitionRegistry, times(wantedNumberOfInvocations)).containsBeanDefinition(eq(beanName));
verify(mockBeanDefinitionRegistry, times(1))
.registerBeanDefinition(eq(beanName), any(BeanDefinition.class)));
.registerBeanDefinition(eq(beanName), any(BeanDefinition.class));
});
}
@Test
@SuppressWarnings("unchecked")
public void collectCacheNamesForCacheableAndCachePutOnCacheableServiceThreeRegistersRegionFifteenSixteenSeventeen() {
public void cacheableServiceFiveRegistersRegionOneTwoThreeFourFiveSixAndSeven() {
assertThat(this.configuration.collectCacheNames(CacheableServiceThree.class, Cacheable.class, CachePut.class))
.containsExactly("RegionFifteen", "RegionSixteen", "RegionSeventeen");
Map<String, BeanDefinition> registeredBeanDefinitions = MapBuilder.<String, BeanDefinition>newMapBuilder()
.put("cacheableServiceFive", mockBeanDefinition(CacheableServiceFive.class))
.build();
BeanDefinitionRegistry mockBeanDefinitionRegistry = mockBeanDefinitionRegistry(registeredBeanDefinitions);
this.configuration.registerBeanDefinitions(mockBeanDefinitionRegistry);
Set<String> registeredRegionBeanNames =
asSet("RegionOne", "RegionTwo", "RegionThree", "RegionFour", "RegionFive",
"RegionSix", "RegionSeven");
verify(mockBeanDefinitionRegistry, times(1)).getBeanDefinitionNames();
verify(mockBeanDefinitionRegistry, times(1))
.getBeanDefinition(eq("cacheableServiceFive"));
verify(mockBeanDefinitionRegistry, times(registeredRegionBeanNames.size()))
.registerBeanDefinition(anyString(), any(BeanDefinition.class));
registeredRegionBeanNames.forEach(beanName -> {
verify(mockBeanDefinitionRegistry, times(1)).containsBeanDefinition(eq(beanName));
verify(mockBeanDefinitionRegistry, times(1))
.registerBeanDefinition(eq(beanName), any(BeanDefinition.class));
});
}
@Test
@SuppressWarnings("unchecked")
public void collectCacheNamesForCacheableOnCacheableServiceThreeRegistersRegionFifteen() {
public void cacheableServiceSixRegistersRegionOneTwoThreeFourAndFive() {
assertThat(this.configuration.collectCacheNames(CacheableServiceThree.class, Cacheable.class))
.containsExactly("RegionFifteen");
Map<String, BeanDefinition> registeredBeanDefinitions = MapBuilder.<String, BeanDefinition>newMapBuilder()
.put("cacheableServiceSix", mockBeanDefinition(CacheableServiceSix.class))
.build();
BeanDefinitionRegistry mockBeanDefinitionRegistry = mockBeanDefinitionRegistry(registeredBeanDefinitions);
this.configuration.registerBeanDefinitions(mockBeanDefinitionRegistry);
Set<String> registeredRegionBeanNames =
asSet("RegionOne", "RegionTwo", "RegionThree", "RegionFour", "RegionFive");
verify(mockBeanDefinitionRegistry, times(1)).getBeanDefinitionNames();
verify(mockBeanDefinitionRegistry, times(1))
.getBeanDefinition(eq("cacheableServiceSix"));
verify(mockBeanDefinitionRegistry, times(registeredRegionBeanNames.size()))
.registerBeanDefinition(anyString(), any(BeanDefinition.class));
registeredRegionBeanNames.forEach(beanName -> {
verify(mockBeanDefinitionRegistry, times(1)).containsBeanDefinition(eq(beanName));
verify(mockBeanDefinitionRegistry, times(1))
.registerBeanDefinition(eq(beanName), any(BeanDefinition.class));
});
}
@Test
@SuppressWarnings("unchecked")
public void collectCacheNamesForCachePutOnCacheableServiceThreeRegistersRegionSixteenSeventeen() {
public void cacheableServiceSevenRegistersRegionOneThroughEleven() {
assertThat(this.configuration.collectCacheNames(CacheableServiceThree.class, CachePut.class))
.containsExactly("RegionSixteen", "RegionSeventeen");
Map<String, BeanDefinition> registeredBeanDefinitions = MapBuilder.<String, BeanDefinition>newMapBuilder()
.put("cacheableServiceSeven", mockBeanDefinition(CacheableServiceSeven.class))
.build();
BeanDefinitionRegistry mockBeanDefinitionRegistry = mockBeanDefinitionRegistry(registeredBeanDefinitions);
this.configuration.registerBeanDefinitions(mockBeanDefinitionRegistry);
Set<String> registeredRegionBeanNames =
asSet("RegionOne", "RegionTwo", "RegionThree", "RegionFour", "RegionFive", "RegionSix",
"RegionSeven", "RegionEight", "RegionNine", "RegionTen", "RegionEleven");
verify(mockBeanDefinitionRegistry, times(1)).getBeanDefinitionNames();
verify(mockBeanDefinitionRegistry, times(1))
.getBeanDefinition(eq("cacheableServiceSeven"));
verify(mockBeanDefinitionRegistry, times(registeredRegionBeanNames.size()))
.registerBeanDefinition(anyString(), any(BeanDefinition.class));
registeredRegionBeanNames.forEach(beanName -> {
verify(mockBeanDefinitionRegistry, times(1)).containsBeanDefinition(eq(beanName));
verify(mockBeanDefinitionRegistry, times(1))
.registerBeanDefinition(eq(beanName), any(BeanDefinition.class));
});
}
@Service
@@ -450,4 +532,63 @@ public class EnableCachingDefinedRegionsUnitTests {
public void cacheableMethodFive() {}
}
@CacheDefaults(cacheName = "RegionOne")
@CacheRemoveAll(cacheName = "RegionSix")
@CacheResult(cacheName = "RegionSeven")
@SuppressWarnings("unused")
static class CacheableServiceFive {
@javax.cache.annotation.CachePut(cacheName = "RegionTwo")
public void cacheableMethodOne() {}
@CacheRemove(cacheName = "RegionThree")
public void cacheableMethodTwo() {}
@CacheRemoveAll(cacheName = "RegionFour")
public void cacheableMethodThree() {}
@CacheResult(cacheName = "RegionFive")
public void cacheableMethodFour() {}
}
@CacheDefaults(cacheName = "RegionOne")
@javax.cache.annotation.CachePut(cacheName = "RegionOne")
@CacheRemoveAll(cacheName = "RegionFive")
@SuppressWarnings("unused")
static class CacheableServiceSix {
@javax.cache.annotation.CachePut(cacheName = "RegionTwo")
@javax.cache.annotation.CacheResult(cacheName = "RegionOne")
public void cacheableMethodOne() {}
@CacheRemove(cacheName = "RegionThree")
public void cacheableMethodTwo() {}
@CacheRemoveAll(cacheName = "RegionThree")
public void cacheableMethodThree() {}
@CacheResult(cacheName = "RegionFour")
@CacheRemove(cacheName = "RegionFive")
public void cacheableMethodFour() {}
}
@Caching(
cacheable = { @Cacheable({ "RegionSix", "RegionSeven", "RegionEight" }), @Cacheable("RegionNine")},
put = @CachePut("RegionTwo")
)
@CacheDefaults(cacheName = "RegionOne")
static class CacheableServiceSeven extends CacheableServiceSix {
@CachePut("RegionTen")
@CacheRemove(cacheName = "RegionFive")
@CacheResult(cacheName = "RegionEleven")
public void cacheableMethodFive() {}
@Cacheable("RegionThree")
public void cacheableMethodSix() {}
}
}

View File

@@ -24,8 +24,8 @@ import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.springframework.data.gemfire.util.CacheUtils.toRegionPath;
import static org.springframework.data.gemfire.util.CollectionUtils.nullSafeList;
import static org.springframework.data.gemfire.util.RegionUtils.toRegionPath;
import java.util.HashSet;
import java.util.List;
@@ -51,7 +51,6 @@ import org.apache.geode.cache.client.ClientRegionFactory;
import org.apache.geode.cache.client.ClientRegionShortcut;
import org.junit.After;
import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.context.ConfigurableApplicationContext;
@@ -346,14 +345,11 @@ public class EnableEntityDefinedRegionsUnitTests {
}
protected static <K, V> ClientCache mockClientCache() {
ClientCache mockClientCache = mock(ClientCache.class, mockName("ClientCache"));
Answer<ClientRegionFactory<K, V>> createClientRegionFactory = new Answer<ClientRegionFactory<K, V>>() {
@Override @SuppressWarnings("unchecked")
public ClientRegionFactory<K, V> answer(InvocationOnMock invocation) throws Throwable {
return mockClientRegionFactory(invocation.getArgument(0));
}
};
Answer<ClientRegionFactory<K, V>> createClientRegionFactory =
invocation -> mockClientRegionFactory(invocation.getArgument(0));
when(mockClientCache.createClientRegionFactory(any(ClientRegionShortcut.class)))
.thenAnswer(createClientRegionFactory);
@@ -527,7 +523,9 @@ public class EnableEntityDefinedRegionsUnitTests {
}
/* (non-Javadoc) */
@SuppressWarnings("unused")
protected static <T, R> Answer<R> newSetter(Class<T> parameterType, AtomicReference<T> argument, R returnValue) {
return invocation -> {
argument.set(invocation.getArgument(0));
return returnValue;

View File

@@ -44,6 +44,7 @@ import org.junit.rules.ExpectedException;
* Unit tests for {@link CollectionUtils}.
*
* @author John Blum
* @see java.lang.Iterable
* @see java.util.Collection
* @see java.util.Collections
* @see java.util.Enumeration
@@ -63,6 +64,7 @@ public class CollectionUtilsUnitTests {
@Test
public void addAllIterableElementsToList() {
List<Integer> target = new ArrayList<>(Arrays.asList(1, 2, 3));
Set<Integer> source = new HashSet<>(Arrays.asList(1, 2, 3));
@@ -75,6 +77,7 @@ public class CollectionUtilsUnitTests {
@Test
public void addAllIterableElementsToSet() {
Set<Integer> target = new HashSet<>(Arrays.asList(1, 2, 3));
Set<Integer> source = new HashSet<>(Arrays.asList(1, 2, 3, 4, 5));
@@ -87,15 +90,17 @@ public class CollectionUtilsUnitTests {
@Test
public void addIterableToNullCollection() {
exception.expect(IllegalArgumentException.class);
exception.expectCause(is(nullValue(Throwable.class)));
exception.expectMessage("Collection must not be null");
exception.expectMessage("Collection is required");
CollectionUtils.addAll(null, Collections.emptySet());
}
@Test
public void addEmptyIterableToCollection() {
Collection<Integer> target = new ArrayList<>(Arrays.asList(1, 2, 3));
target = CollectionUtils.addAll(target, Collections.emptyList());
@@ -107,6 +112,7 @@ public class CollectionUtilsUnitTests {
@Test
public void addNullIterableToCollection() {
Collection<Integer> target = new ArrayList<>(Arrays.asList(1, 2, 3));
target = CollectionUtils.addAll(target, null);
@@ -118,6 +124,7 @@ public class CollectionUtilsUnitTests {
@Test
public void asSetContainsAllArrayElements() {
Object[] elements = { "a", "b", "c" };
Set<?> set = CollectionUtils.asSet(elements);
@@ -129,6 +136,7 @@ public class CollectionUtilsUnitTests {
@Test
public void asSetContainsUniqueArrayElements() {
Object[] elements = { 1, 2, 1 };
Set<?> set = CollectionUtils.asSet(elements);
@@ -140,6 +148,7 @@ public class CollectionUtilsUnitTests {
@Test(expected = UnsupportedOperationException.class)
public void asSetReturnsUnmodifiableSet() {
Set<Integer> set = CollectionUtils.asSet(1, 2, 3);
assertThat(set).isNotNull();
@@ -176,36 +185,9 @@ public class CollectionUtilsUnitTests {
assertThat(CollectionUtils.containsAny(null, 1)).isFalse();
}
@Test
public void defaultIfEmptyWithNonNullNonEmptyIterableReturnsIterable() {
Iterable<Object> iterable = Collections.singleton(1);
Iterable<Object> defaultIterable = Collections.singleton(2);
assertThat(CollectionUtils.defaultIfEmpty(iterable, defaultIterable)).isSameAs(iterable);
}
@Test
public void defaultIfEmptyWithEmptyIterableReturnsDefault() {
Iterable<Object> iterable = Collections.emptySet();
Iterable<Object> defaultIterable = Collections.singleton(2);
assertThat(CollectionUtils.defaultIfEmpty(iterable, defaultIterable)).isSameAs(defaultIterable);
}
@Test
public void defaultIfEmptyWithNullIterableReturnsDefault() {
Iterable<?> defaultIterable = Collections.singleton(2);
assertThat(CollectionUtils.defaultIfEmpty(null, defaultIterable)).isSameAs(defaultIterable);
}
@Test
public void defaultIfEmptyWithNullIterableAndNullDefaultReturnsNull() {
assertThat(CollectionUtils.defaultIfEmpty((Iterable<?>) null, null)).isNull();
}
@Test
public void emptyIterableReturnsEmptyIterable() {
Iterable<?> iterable = CollectionUtils.emptyIterable();
assertThat(iterable).isNotNull();
@@ -216,6 +198,7 @@ public class CollectionUtilsUnitTests {
@Test
@SuppressWarnings("unchecked")
public void iterableEnumeration() {
Enumeration<String> mockEnumeration = mock(Enumeration.class, "MockEnumeration");
when(mockEnumeration.hasMoreElements()).thenReturn(true).thenReturn(true).thenReturn(true).thenReturn(false);
@@ -241,6 +224,7 @@ public class CollectionUtilsUnitTests {
@Test
@SuppressWarnings("unchecked")
public void iterableIterator() {
Iterator<String> mockIterator = mock(Iterator.class, "MockIterator");
when(mockIterator.hasNext()).thenReturn(true).thenReturn(true).thenReturn(true).thenReturn(false);
@@ -265,6 +249,7 @@ public class CollectionUtilsUnitTests {
@Test
public void nullSafeCollectionWithNonNullCollection() {
Collection<?> mockCollection = mock(Collection.class);
assertThat(CollectionUtils.nullSafeCollection(mockCollection)).isSameAs(mockCollection);
@@ -272,6 +257,7 @@ public class CollectionUtilsUnitTests {
@Test
public void nullSafeCollectionWithNullCollection() {
Collection collection = CollectionUtils.nullSafeCollection(null);
assertThat(collection).isNotNull();
@@ -281,6 +267,7 @@ public class CollectionUtilsUnitTests {
@Test
@SuppressWarnings("unchecked")
public void nullSafeIterableWithNonNullIterable() {
Iterable<Object> mockIterable = mock(Iterable.class);
assertThat(CollectionUtils.nullSafeIterable(mockIterable)).isSameAs(mockIterable);
@@ -288,6 +275,7 @@ public class CollectionUtilsUnitTests {
@Test
public void nullSafeIterableWithNullIterable() {
Iterable<Object> iterable = CollectionUtils.nullSafeIterable(null);
assertThat(iterable).isNotNull();
@@ -295,8 +283,10 @@ public class CollectionUtilsUnitTests {
assertThat(iterable.iterator().hasNext()).isFalse();
}
@SuppressWarnings("all")
@Test(expected = IllegalStateException.class)
public void nullSafeIterableIterator() {
Iterable<Object> iterable = CollectionUtils.nullSafeIterable(null);
assertThat(iterable).isNotNull();
@@ -319,8 +309,40 @@ public class CollectionUtilsUnitTests {
}
}
@Test
public void nullSafeIterableWithNonNullNonEmptyIterableReturnsIterable() {
Iterable<Object> iterable = Collections.singleton(1);
Iterable<Object> defaultIterable = Collections.singleton(2);
assertThat(CollectionUtils.nullSafeIterable(iterable, defaultIterable)).isSameAs(iterable);
}
@Test
public void nullSafeIterableWithEmptyIterableReturnsDefault() {
Iterable<Object> iterable = Collections.emptySet();
Iterable<Object> defaultIterable = Collections.singleton(2);
assertThat(CollectionUtils.nullSafeIterable(iterable, defaultIterable)).isSameAs(defaultIterable);
}
@Test
public void nullSafeIterableWithNullIterableReturnsDefault() {
Iterable<?> defaultIterable = Collections.singleton(2);
assertThat(CollectionUtils.nullSafeIterable(null, defaultIterable)).isSameAs(defaultIterable);
}
@Test
public void nullSafeIterableWithNullIterableAndNullDefaultReturnsNull() {
assertThat(CollectionUtils.nullSafeIterable((Iterable<?>) null, null)).isNull();
}
@Test
public void nullSafeListWithNonNullList() {
List<?> mockList = mock(List.class);
assertThat(CollectionUtils.nullSafeList(mockList)).isSameAs(mockList);
@@ -328,6 +350,7 @@ public class CollectionUtilsUnitTests {
@Test
public void nullSafeListWithNullList() {
List<?> list = CollectionUtils.nullSafeList(null);
assertThat(list).isNotNull();
@@ -336,6 +359,7 @@ public class CollectionUtilsUnitTests {
@Test
public void nullSafeMapWithNonNullMap() {
Map<?, ?> mockMap = mock(Map.class);
assertThat(CollectionUtils.nullSafeMap(mockMap)).isSameAs(mockMap);
@@ -343,6 +367,7 @@ public class CollectionUtilsUnitTests {
@Test
public void nullSafeMapWithNullMap() {
Map<?, ?> map = CollectionUtils.nullSafeMap(null);
assertThat(map).isNotNull();
@@ -351,6 +376,7 @@ public class CollectionUtilsUnitTests {
@Test
public void nullSafeSetWithNonNullSet() {
Set<?> mockSet = mock(Set.class);
assertThat(CollectionUtils.nullSafeSet(mockSet)).isSameAs(mockSet);
@@ -358,6 +384,7 @@ public class CollectionUtilsUnitTests {
@Test
public void nullSafeSetWithNullSet() {
Set<?> set = CollectionUtils.nullSafeSet(null);
assertThat(set).isNotNull();
@@ -366,6 +393,7 @@ public class CollectionUtilsUnitTests {
@Test
public void sortIsSuccessful() {
List<Integer> list = new ArrayList<Integer>(Arrays.asList(2, 3, 1));
List<Integer> sortedList = CollectionUtils.sort(list);
@@ -375,6 +403,7 @@ public class CollectionUtilsUnitTests {
@Test
public void subListFromListWithIndexesReturnsSubList() {
List<Integer> list = Arrays.asList(0, 1, 2, 3);
List<Integer> subList = CollectionUtils.subList(list, 1, 3);
@@ -386,6 +415,7 @@ public class CollectionUtilsUnitTests {
@Test
public void subListFromListWithNoIndexesReturnsEmptyList() {
List<Integer> subList = CollectionUtils.subList(Arrays.asList(0, 1, 2));
assertThat(subList).isNotNull();
@@ -399,9 +429,10 @@ public class CollectionUtilsUnitTests {
@Test
public void subListWithNullSourceListThrowsIllegalArgumentException() {
exception.expect(IllegalArgumentException.class);
exception.expectCause(is(nullValue(Throwable.class)));
exception.expectMessage("List must not be null");
exception.expectMessage("List is required");
CollectionUtils.subList(null, 1, 2, 3);
}

View File

@@ -0,0 +1,77 @@
/*
* Copyright 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.
* 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.data.gemfire.util;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.Test;
/**
* Unit tests for {@link StreamUtils}.
*
* @author John Blum
* @see java.util.stream.Stream
* @see org.junit.Test
* @see org.springframework.data.gemfire.util.StreamUtils
* @since 2.0.0
*/
public class StreamUtilsTests {
@Test
@SuppressWarnings("unchecked")
public void concatNoStreams() {
Stream<Object> stream = StreamUtils.concat();
assertThat(stream).isNotNull();
assertThat(stream.count()).isEqualTo(0);
}
@Test
@SuppressWarnings("unchecked")
public void concatOneStream() {
Stream<Integer> stream = StreamUtils.concat(Stream.of(1, 2, 3));
assertThat(stream).isNotNull();
assertThat(stream.collect(Collectors.toList())).containsExactly(1, 2, 3);
}
@Test
@SuppressWarnings("unchecked")
public void concatTwoStreams() {
Stream<Integer> stream = StreamUtils.concat(Stream.of(1, 2, 3), Stream.of(4, 5, 6));
assertThat(stream).isNotNull();
assertThat(stream.collect(Collectors.toList())).containsExactly(1, 2, 3, 4, 5, 6);
}
@Test
@SuppressWarnings("unchecked")
public void concatThreeStreams() {
Stream<Integer> stream =
StreamUtils.concat(Stream.of(1, 2, 3), Stream.of(4, 5, 6), Stream.of(7, 8, 9));
assertThat(stream).isNotNull();
assertThat(stream.collect(Collectors.toList())).containsExactly(1, 2, 3, 4, 5, 6, 7, 8, 9);
}
}