DATAGEODE-100 - Avoid Pool Already Exists Exception on Spring container initialization.

This commit is contained in:
John Blum
2018-04-14 13:17:18 -07:00
parent 28ff99e15b
commit 1fd41c9b3a
95 changed files with 2922 additions and 2837 deletions

View File

@@ -23,11 +23,10 @@ import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.junit4.SpringRunner;
/**
* The AutoRegionLookupIntegrationTests class is a test suite of test cases testing the contract and functionality
* of Spring Data GemFire's new auto Region lookup feature.
* Integration tests to test the contract and functionality of Spring Data GemFire's Auto Region Lookup functionality.
*
* @author John Blum
* @see org.junit.Test
@@ -36,7 +35,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
* @see org.springframework.test.context.junit4.SpringJUnit4ClassRunner
* @since 1.5.0
*/
@RunWith(SpringJUnit4ClassRunner.class)
@RunWith(SpringRunner.class)
@ContextConfiguration
@SuppressWarnings("unused")
public class AutoRegionLookupIntegrationTests {
@@ -54,5 +53,4 @@ public class AutoRegionLookupIntegrationTests {
assertTrue(applicationContext.containsBean("/NativeReplicateParent/NativeReplicateChild"));
assertTrue(applicationContext.containsBean("/NativeReplicateParent/NativeReplicateChild/NativeReplicateGrandchild"));
}
}

View File

@@ -29,11 +29,11 @@ import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.junit4.SpringRunner;
/**
* The AutoRegionLookupWithAutowiringIntegrationTests class is a test suite class testing the behavior of
* Spring Data GemFire's auto Region lookup functionality when combined with Spring's component auto-wiring capabilities.
* Integration tests to test the behavior of Spring Data GemFire's Auto Region Lookup functionality
* when combined with Spring's component auto-wiring capabilities.
*
* @author John Blum
* @see org.junit.Test
@@ -42,7 +42,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
* @see org.springframework.test.context.junit4.SpringJUnit4ClassRunner
* @since 1.5.0
*/
@RunWith(SpringJUnit4ClassRunner.class)
@RunWith(SpringRunner.class)
@ContextConfiguration
@SuppressWarnings("unused")
public class AutoRegionLookupWithAutowiringIntegrationTests {
@@ -50,24 +50,24 @@ public class AutoRegionLookupWithAutowiringIntegrationTests {
@Autowired
private TestComponent testComponent;
protected static void assertRegionMetaData(final Region<?, ?> region,
final String expectedName, final DataPolicy expectedDataPolicy) {
private static void assertRegionMetaData(Region<?, ?> region, String expectedName, DataPolicy expectedDataPolicy) {
assertRegionMetaData(region, expectedName, Region.SEPARATOR + expectedName, expectedDataPolicy);
}
protected static void assertRegionMetaData(final Region<?, ?> region, final String expectedName,
final String expectedFullPath, final DataPolicy expectedDataPolicy) {
private static void assertRegionMetaData(Region<?, ?> region, String expectedName, String expectedFullPath,
DataPolicy expectedDataPolicy) {
assertNotNull(String.format("Region (%1$s) was not properly configured and initialized!", expectedName), region);
assertEquals(expectedName, region.getName());
assertEquals(expectedFullPath, region.getFullPath());
assertNotNull(String.format("Region (%1$s) must have RegionAttributes defined!", expectedName),
region.getAttributes());
assertNotNull(String.format("Region (%1$s) must have RegionAttributes defined!", expectedName), region.getAttributes());
assertEquals(expectedDataPolicy, region.getAttributes().getDataPolicy());
assertFalse(region.getAttributes().getDataPolicy().withPersistence());
}
@Test
public void testAutowiredNativeRegions() {
assertRegionMetaData(testComponent.nativePartitionedRegion, "NativePartitionedRegion", DataPolicy.PARTITION);
assertRegionMetaData(testComponent.nativeReplicateParent, "NativeReplicateParent", DataPolicy.REPLICATE);
assertRegionMetaData(testComponent.nativeReplicateChild, "NativeReplicateChild",
@@ -92,5 +92,4 @@ public class AutoRegionLookupWithAutowiringIntegrationTests {
Region<?, ?> nativeReplicateGrandchild;
}
}

View File

@@ -24,11 +24,11 @@ import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.junit4.SpringRunner;
/**
* The AutoRegionLookupWithComponentScanningIntegrationTests class is a test suite class testing the behavior of
* Spring Data GemFire's auto Region lookup behavior with Spring component scanning functionality.
* Integration tests to test the behavior of Spring Data GemFire's Auto Region Lookup behavior
* with Spring component scanning functionality.
*
* @author John Blum
* @see org.junit.Test
@@ -37,19 +37,19 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
* @see org.springframework.test.context.junit4.SpringJUnit4ClassRunner
* @since 1.5.0
*/
@RunWith(SpringJUnit4ClassRunner.class)
@RunWith(SpringRunner.class)
@ContextConfiguration
@SuppressWarnings("unused")
public class AutoRegionLookupWithComponentScanningIntegrationTests {
@Autowired
private ApplicationContext context;
private ApplicationContext applicationContext;
@Test
public void testAutowiredNativeRegions() {
assertTrue("The 'autoRegionLookupDao' Spring bean DAO was not properly configured an initialized!",
context.containsBean("autoRegionLookupDao"));
assertNotNull(context.getBean("autoRegionLookupDao", AutoRegionLookupDao.class));
}
assertTrue("The 'autoRegionLookupDao' Spring bean DAO was not properly configured an initialized!",
this.applicationContext.containsBean("autoRegionLookupDao"));
assertNotNull(this.applicationContext.getBean("autoRegionLookupDao", AutoRegionLookupDao.class));
}
}

View File

@@ -16,10 +16,12 @@
package org.springframework.data.gemfire;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.springframework.data.gemfire.util.RuntimeExceptionFactory.newRuntimeException;
import java.io.File;
import java.io.IOException;
@@ -45,8 +47,8 @@ import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.gemfire.fork.LocatorProcess;
import org.springframework.data.gemfire.process.ProcessExecutor;
import org.springframework.data.gemfire.process.ProcessWrapper;
import org.springframework.data.gemfire.test.support.ClientServerIntegrationTestsSupport;
import org.springframework.data.gemfire.test.support.FileUtils;
import org.springframework.data.gemfire.test.support.ThreadUtils;
import org.springframework.data.gemfire.test.support.ThrowableUtils;
@@ -69,7 +71,7 @@ import org.springframework.util.StringUtils;
* @since 1.5.0
*/
@SuppressWarnings("unused")
public class CacheClusterConfigurationIntegrationTest {
public class CacheClusterConfigurationIntegrationTest extends ClientServerIntegrationTestsSupport {
private static File locatorWorkingDirectory;
@@ -77,11 +79,14 @@ public class CacheClusterConfigurationIntegrationTest {
private static List<String> locatorProcessOutput = Collections.synchronizedList(new ArrayList<String>());
private static final String LOG_LEVEL = "error";
@Rule
public TestRule watchman = new TestWatcher() {
@Override
protected void failed(Throwable throwable, Description description) {
System.err.println(String.format("Test '%1$s' failed...", description.getDisplayName()));
System.err.printf("Test [%s] failed...%n", description.getDisplayName());
System.err.println(ThrowableUtils.toString(throwable));
System.err.println("Locator process log file contents were...");
System.err.println(getLocatorProcessOutput(description));
@@ -89,36 +94,42 @@ public class CacheClusterConfigurationIntegrationTest {
@Override
protected void finished(Description description) {
if (Boolean.valueOf(System.getProperty("spring.gemfire.fork.clean", Boolean.TRUE.toString()))) {
try {
FileUtils.write(new File(locatorWorkingDirectory.getParent(),
String.format("%1$s-clusterconfiglocator.log", description.getMethodName())),
String.format("%s-clusterconfiglocator.log", description.getMethodName())),
getLocatorProcessOutput(description));
}
catch (IOException e) {
throw new RuntimeException("Failed the write the contents of the Locator process log to a file!", e);
catch (IOException cause) {
throw newRuntimeException(cause, "Failed the write the contents of the Locator process log to a file");
}
}
}
private String getLocatorProcessOutput(Description description) {
try {
String locatorProcessOutputString = StringUtils.collectionToDelimitedString(locatorProcessOutput,
FileUtils.LINE_SEPARATOR, String.format("[%1$s] - ", description.getMethodName()), "");
locatorProcessOutputString = (StringUtils.hasText(locatorProcessOutputString) ?
locatorProcessOutputString : locatorProcess.readLogFile());
locatorProcessOutputString = StringUtils.hasText(locatorProcessOutputString)
? locatorProcessOutputString : locatorProcess.readLogFile();
return locatorProcessOutputString;
}
catch (IOException e) {
throw new RuntimeException("Failed to read the contents of the Locator process log file!", e);
catch (IOException cause) {
throw newRuntimeException(cause, "Failed to read the contents of the Locator process log file");
}
}
};
@BeforeClass
public static void testSuiteSetup() throws IOException {
@SuppressWarnings("all")
public static void startLocator() throws IOException {
int availablePort = findAvailablePort();
String locatorName = "ClusterConfigLocator";
locatorWorkingDirectory = new File(System.getProperty("user.dir"), locatorName.toLowerCase());
@@ -130,12 +141,12 @@ public class CacheClusterConfigurationIntegrationTest {
List<String> arguments = new ArrayList<>();
arguments.add("-Dgemfire.name=" + locatorName);
arguments.add("-Dgemfire.mcast-port=0");
arguments.add("-Dgemfire.log-level=error");
arguments.add("-Dspring.data.gemfire.enable-cluster-configuration=true");
arguments.add("-Dspring.data.gemfire.load-cluster-configuration=true");
arguments.add(String.format("-Dgemfire.log-level=%s", LOG_LEVEL));
arguments.add(String.format("-Dspring.data.gemfire.locator.port=%d", availablePort));
locatorProcess = ProcessExecutor.launch(locatorWorkingDirectory, LocatorProcess.class,
locatorProcess = run(locatorWorkingDirectory, LocatorProcess.class,
arguments.toArray(new String[arguments.size()]));
locatorProcess.register(input -> locatorProcessOutput.add(input));
@@ -144,66 +155,84 @@ public class CacheClusterConfigurationIntegrationTest {
waitForLocatorStart(TimeUnit.SECONDS.toMillis(30));
System.out.println("Cluster Configuration Locator should be running!");
System.setProperty("spring.data.gemfire.locator.port", String.valueOf(availablePort));
}
private static void waitForLocatorStart(final long milliseconds) {
ThreadUtils.timedWait(milliseconds, 500, new ThreadUtils.WaitCondition() {
File pidControlFile = new File(locatorWorkingDirectory, LocatorProcess.getLocatorProcessControlFilename());
@Override public boolean waiting() {
@Override
public boolean waiting() {
return !pidControlFile.isFile();
}
});
}
@AfterClass
public static void testSuiteTearDown() {
public static void stopLocator() {
locatorProcess.shutdown();
System.clearProperty("spring.data.gemfire.locator.port");
if (Boolean.valueOf(System.getProperty("spring.gemfire.fork.clean", Boolean.TRUE.toString()))) {
FileSystemUtils.deleteRecursively(locatorWorkingDirectory);
}
}
protected Region assertRegion(final Region actualRegion, final String expectedRegionName) {
private Region assertRegion(Region actualRegion, String expectedRegionName) {
return assertRegion(actualRegion, expectedRegionName, Region.SEPARATOR+expectedRegionName);
}
protected Region assertRegion(final Region actualRegion, final String expectedRegionName, final String expectedRegionFullPath) {
assertNotNull(String.format("The '%1$s' was not properly configured and initialized!", expectedRegionName), actualRegion);
private Region assertRegion(Region actualRegion, String expectedRegionName, String expectedRegionFullPath) {
assertNotNull(String.format("The [%s] was not properly configured and initialized!",
expectedRegionName), actualRegion);
assertEquals(expectedRegionName, actualRegion.getName());
assertEquals(expectedRegionFullPath, actualRegion.getFullPath());
return actualRegion;
}
protected Region assertRegionAttributes(final Region actualRegion, final DataPolicy expectedDataPolicy, final Scope expectedScope) {
private Region assertRegionAttributes(Region actualRegion, DataPolicy expectedDataPolicy, Scope expectedScope) {
assertNotNull(actualRegion);
assertNotNull(actualRegion.getAttributes());
assertEquals(expectedDataPolicy, actualRegion.getAttributes().getDataPolicy());
assertEquals(expectedScope, actualRegion.getAttributes().getScope());
return actualRegion;
}
protected String getLocation(final String configLocation) {
private String getLocation(String configLocation) {
String baseLocation = getClass().getPackage().getName().replace('.', File.separatorChar);
return baseLocation.concat(File.separator).concat(configLocation);
}
protected Region getRegion(ConfigurableApplicationContext applicationContext, String regionBeanName) {
private Region getRegion(ConfigurableApplicationContext applicationContext, String regionBeanName) {
return applicationContext.getBean(regionBeanName, Region.class);
}
protected ConfigurableApplicationContext newApplicationContext(String... configLocations) {
private ConfigurableApplicationContext newApplicationContext(String... configLocations) {
ConfigurableApplicationContext applicationContext = new ClassPathXmlApplicationContext(configLocations);
applicationContext.registerShutdownHook();
return applicationContext;
}
@Test
@Ignore
// TODO re-enable the test once the GemFire Cluster Configuration Service race condition has been properly fixed!
public void clusterConfigurationTest() {
ConfigurableApplicationContext applicationContext = newApplicationContext(
getLocation("cacheUsingClusterConfigurationIntegrationTest.xml"));
ConfigurableApplicationContext applicationContext =
newApplicationContext(getLocation("cacheUsingClusterConfigurationIntegrationTest.xml"));
assertRegionAttributes(assertRegion(getRegion(applicationContext, "ClusterConfigRegion"), "ClusterConfigRegion"),
DataPolicy.PARTITION, Scope.DISTRIBUTED_NO_ACK);
@@ -223,17 +252,20 @@ public class CacheClusterConfigurationIntegrationTest {
@Test
public void localConfigurationTest() {
try {
newApplicationContext(getLocation("cacheUsingLocalOnlyConfigurationIntegrationTest.xml"));
newApplicationContext(getLocation("cacheUsingLocalConfigurationIntegrationTest.xml"));
fail("Loading the 'cacheUsingLocalOnlyConfigurationIntegrationTest.xml' Spring ApplicationContext"
+ " configuration file should have resulted in an Exception due to the Region lookup on"
+ " 'ClusterConfigRegion' when GemFire Cluster Configuration is disabled!");
}
catch (BeanCreationException expected) {
assertTrue(expected.getCause() instanceof BeanInitializationException);
assertTrue(expected.getCause().getMessage().matches(
"Region \\[ClusterConfigRegion\\] in Cache \\[.*\\] not found"));
assertThat(expected).hasCauseInstanceOf(BeanInitializationException.class);
assertTrue(String.format("Message was [%s]", expected.getMessage()), expected.getCause().getMessage()
.matches("Region \\[ClusterConfigRegion\\] in Cache \\[.*\\] not found"));
}
}
}

View File

@@ -32,8 +32,10 @@ import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Matchers.same;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
@@ -56,10 +58,9 @@ import org.apache.geode.cache.util.GatewayConflictResolver;
import org.apache.geode.distributed.DistributedMember;
import org.apache.geode.distributed.DistributedSystem;
import org.apache.geode.pdx.PdxSerializer;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.mockito.InOrder;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.beans.factory.BeanFactory;
@@ -94,34 +95,27 @@ public class CacheFactoryBeanTest {
@Mock
private Cache mockCache;
@Rule
public ExpectedException exception = ExpectedException.none();
@Test
public void afterPropertiesSet() throws Exception {
final AtomicBoolean postProcessBeforeCacheInitializationCalled = new AtomicBoolean(false);
final Properties gemfireProperties = new Properties();
public void afterPropertiesSetAppliesCacheConfigurersAndThenInitializesBeanFactoryLocator() throws Exception {
CacheFactoryBean cacheFactoryBean = new CacheFactoryBean() {
CacheFactoryBean cacheFactoryBean = spy(new CacheFactoryBean());
@Override
protected void postProcessBeforeCacheInitialization(Properties actualGemfireProperties) {
assertThat(actualGemfireProperties, is(sameInstance(gemfireProperties)));
postProcessBeforeCacheInitializationCalled.set(true);
}
};
cacheFactoryBean.setProperties(gemfireProperties);
cacheFactoryBean.afterPropertiesSet();
assertThat(postProcessBeforeCacheInitializationCalled.get(), is(true));
InOrder orderVerifier = inOrder(cacheFactoryBean);
orderVerifier.verify(cacheFactoryBean, times(1)).applyCacheConfigurers();
orderVerifier.verify(cacheFactoryBean, times(1)).initBeanFactoryLocator();
}
@Test
public void postProcessBeforeCacheInitializationUsingDefaults() {
Properties gemfireProperties = new Properties();
public void applyingCacheConfigurersDisablesAutoReconnectAndDoesNotUseClusterConfigurationByDefault() {
new CacheFactoryBean().postProcessBeforeCacheInitialization(gemfireProperties);
CacheFactoryBean cacheFactoryBean = new CacheFactoryBean();
cacheFactoryBean.applyCacheConfigurers();
Properties gemfireProperties = cacheFactoryBean.getProperties();
assertThat(gemfireProperties.size(), is(equalTo(2)));
assertThat(gemfireProperties.containsKey("disable-auto-reconnect"), is(true));
@@ -131,13 +125,15 @@ public class CacheFactoryBeanTest {
}
@Test
public void postProcessBeforeCacheInitializationWithAutoReconnectAndClusterConfigurationDisabled() {
Properties gemfireProperties = new Properties();
public void applyCacheConfigurersWithAutoReconnectAndClusterConfigurationDisabled() {
CacheFactoryBean cacheFactoryBean = new CacheFactoryBean();
cacheFactoryBean.setEnableAutoReconnect(false);
cacheFactoryBean.setUseClusterConfiguration(false);
cacheFactoryBean.postProcessBeforeCacheInitialization(gemfireProperties);
cacheFactoryBean.applyCacheConfigurers();
Properties gemfireProperties = cacheFactoryBean.getProperties();
assertThat(gemfireProperties.size(), is(equalTo(2)));
assertThat(gemfireProperties.containsKey("disable-auto-reconnect"), is(true));
@@ -147,13 +143,15 @@ public class CacheFactoryBeanTest {
}
@Test
public void postProcessBeforeCacheInitializationWithAutoReconnectAndClusterConfigurationEnabled() {
Properties gemfireProperties = new Properties();
public void applyCacheConfigurersWithAutoReconnectAndClusterConfigurationEnabled() {
CacheFactoryBean cacheFactoryBean = new CacheFactoryBean();
cacheFactoryBean.setEnableAutoReconnect(true);
cacheFactoryBean.setUseClusterConfiguration(true);
cacheFactoryBean.postProcessBeforeCacheInitialization(gemfireProperties);
cacheFactoryBean.applyCacheConfigurers();
Properties gemfireProperties = cacheFactoryBean.getProperties();
assertThat(gemfireProperties.size(), is(equalTo(2)));
assertThat(gemfireProperties.containsKey("disable-auto-reconnect"), is(true));
@@ -163,13 +161,15 @@ public class CacheFactoryBeanTest {
}
@Test
public void postProcessBeforeCacheInitializationWithAutoReconnectDisabledAndClusterConfigurationEnabled() {
Properties gemfireProperties = new Properties();
public void applyCacheConfigurersWithAutoReconnectDisabledAndClusterConfigurationEnabled() {
CacheFactoryBean cacheFactoryBean = new CacheFactoryBean();
cacheFactoryBean.setEnableAutoReconnect(false);
cacheFactoryBean.setUseClusterConfiguration(true);
cacheFactoryBean.postProcessBeforeCacheInitialization(gemfireProperties);
cacheFactoryBean.applyCacheConfigurers();
Properties gemfireProperties = cacheFactoryBean.getProperties();
assertThat(gemfireProperties.size(), is(equalTo(2)));
assertThat(gemfireProperties.containsKey("disable-auto-reconnect"), is(true));
@@ -179,10 +179,29 @@ public class CacheFactoryBeanTest {
}
@Test
public void getObjectCallsInit() throws Exception {
final Cache mockCache = mock(Cache.class);
public void applyCacheConfigurersWithAutoReconnectEnabledAndClusterConfigurationDisabled() {
final AtomicBoolean initCalled = new AtomicBoolean(false);
CacheFactoryBean cacheFactoryBean = new CacheFactoryBean();
cacheFactoryBean.setEnableAutoReconnect(true);
cacheFactoryBean.setUseClusterConfiguration(false);
cacheFactoryBean.applyCacheConfigurers();
Properties gemfireProperties = cacheFactoryBean.getProperties();
assertThat(gemfireProperties.size(), is(equalTo(2)));
assertThat(gemfireProperties.containsKey("disable-auto-reconnect"), is(true));
assertThat(gemfireProperties.containsKey("use-cluster-configuration"), is(true));
assertThat(gemfireProperties.getProperty("disable-auto-reconnect"), is(equalTo("false")));
assertThat(gemfireProperties.getProperty("use-cluster-configuration"), is(equalTo("false")));
}
@Test
public void getObjectCallsInit() throws Exception {
AtomicBoolean initCalled = new AtomicBoolean(false);
Cache mockCache = mock(Cache.class);
CacheFactoryBean cacheFactoryBean = new CacheFactoryBean() {
@Override Cache init() {
@@ -199,6 +218,7 @@ public class CacheFactoryBeanTest {
@Test
public void getObjectReturnsExistingCache() throws Exception {
Cache mockCache = mock(Cache.class);
CacheFactoryBean cacheFactoryBean = new CacheFactoryBean();
@@ -323,9 +343,11 @@ public class CacheFactoryBeanTest {
@Test
public void resolveCacheCallsFetchCacheReturnsMock() {
final Cache mockCache = mock(Cache.class);
Cache mockCache = mock(Cache.class);
CacheFactoryBean cacheFactoryBean = new CacheFactoryBean() {
@Override @SuppressWarnings("unchecked ")
protected <T extends GemFireCache> T fetchCache() {
return (T) mockCache;
@@ -339,8 +361,9 @@ public class CacheFactoryBeanTest {
@Test
public void resolveCacheCreatesCacheWhenFetchCacheThrowsCacheClosedException() {
final Cache mockCache = mock(Cache.class);
final CacheFactory mockCacheFactory = mock(CacheFactory.class);
Cache mockCache = mock(Cache.class);
CacheFactory mockCacheFactory = mock(CacheFactory.class);
when(mockCacheFactory.create()).thenReturn(mockCache);
@@ -364,6 +387,7 @@ public class CacheFactoryBeanTest {
@Test
public void fetchExistingCache() throws Exception {
Cache mockCache = mock(Cache.class);
CacheFactoryBean cacheFactoryBean = new CacheFactoryBean();
@@ -378,7 +402,9 @@ public class CacheFactoryBeanTest {
@Test
public void resolveProperties() {
Properties gemfireProperties = new Properties();
CacheFactoryBean cacheFactoryBean = new CacheFactoryBean();
cacheFactoryBean.setProperties(gemfireProperties);
@@ -388,6 +414,7 @@ public class CacheFactoryBeanTest {
@Test
public void resolvePropertiesWhenNull() {
CacheFactoryBean cacheFactoryBean = new CacheFactoryBean();
cacheFactoryBean.setProperties(null);
@@ -400,7 +427,9 @@ public class CacheFactoryBeanTest {
@Test
public void createFactory() {
Properties gemfireProperties = new Properties();
Object cacheFactoryReference = new CacheFactoryBean().createFactory(gemfireProperties);
assertThat(cacheFactoryReference, is(instanceOf(CacheFactory.class)));
@@ -416,9 +445,10 @@ public class CacheFactoryBeanTest {
@Test
public void prepareFactoryWithUnspecifiedPdxOptions() {
CacheFactory mockCacheFactory = mock(CacheFactory.class);
assertThat(new CacheFactoryBean().prepareFactory(mockCacheFactory), is(sameInstance(mockCacheFactory)));
assertThat(new CacheFactoryBean().configureFactory(mockCacheFactory), is(sameInstance(mockCacheFactory)));
verify(mockCacheFactory, never()).setPdxDiskStore(any(String.class));
verify(mockCacheFactory, never()).setPdxIgnoreUnreadFields(any(Boolean.class));
@@ -429,6 +459,7 @@ public class CacheFactoryBeanTest {
@Test
public void prepareFactoryWithSpecificPdxOptions() {
CacheFactoryBean cacheFactoryBean = new CacheFactoryBean();
cacheFactoryBean.setPdxSerializer(mock(PdxSerializer.class));
@@ -437,7 +468,7 @@ public class CacheFactoryBeanTest {
CacheFactory mockCacheFactory = mock(CacheFactory.class);
assertThat(cacheFactoryBean.prepareFactory(mockCacheFactory), is(sameInstance(mockCacheFactory)));
assertThat(cacheFactoryBean.configureFactory(mockCacheFactory), is(sameInstance(mockCacheFactory)));
verify(mockCacheFactory, never()).setPdxDiskStore(any(String.class));
verify(mockCacheFactory, times(1)).setPdxIgnoreUnreadFields(eq(false));
@@ -448,6 +479,7 @@ public class CacheFactoryBeanTest {
@Test
public void prepareFactoryWithAllPdxOptions() {
CacheFactoryBean cacheFactoryBean = new CacheFactoryBean();
cacheFactoryBean.setPdxDiskStoreName("testPdxDiskStoreName");
@@ -458,7 +490,7 @@ public class CacheFactoryBeanTest {
CacheFactory mockCacheFactory = mock(CacheFactory.class);
assertThat(cacheFactoryBean.prepareFactory(mockCacheFactory), is(sameInstance(mockCacheFactory)));
assertThat(cacheFactoryBean.configureFactory(mockCacheFactory), is(sameInstance(mockCacheFactory)));
verify(mockCacheFactory, times(1)).setPdxDiskStore(eq("testPdxDiskStoreName"));
verify(mockCacheFactory, times(1)).setPdxIgnoreUnreadFields(eq(false));
@@ -468,24 +500,8 @@ public class CacheFactoryBeanTest {
}
@Test
public void createCacheWithExistingCache() throws Exception {
CacheFactory mockCacheFactory = mock(CacheFactory.class);
CacheFactoryBean cacheFactoryBean = new CacheFactoryBean();
public void createCacheWithCacheFactory() {
cacheFactoryBean.setCache(mockCache);
assertThat(cacheFactoryBean.getCache(), is(sameInstance(mockCache)));
Cache actualCache = cacheFactoryBean.createCache(mockCacheFactory);
assertThat(actualCache, is(sameInstance(mockCache)));
verify(mockCacheFactory, never()).create();
verifyZeroInteractions(mockCache);
}
@Test
public void createCacheWithNoExistingCache() {
CacheFactory mockCacheFactory = mock(CacheFactory.class);
when(mockCacheFactory.create()).thenReturn(mockCache);
@@ -502,6 +518,7 @@ public class CacheFactoryBeanTest {
@Test(expected = IllegalArgumentException.class)
public void postProcessCacheWithInvalidCriticalHeapPercentage() throws Exception {
try {
CacheFactoryBean cacheFactoryBean = new CacheFactoryBean();
@@ -521,6 +538,7 @@ public class CacheFactoryBeanTest {
@Test(expected = IllegalArgumentException.class)
public void postProcessCacheWithInvalidCriticalOffHeapPercentage() throws Exception {
try {
CacheFactoryBean cacheFactoryBean = new CacheFactoryBean();
@@ -540,6 +558,7 @@ public class CacheFactoryBeanTest {
@Test(expected = IllegalArgumentException.class)
public void postProcessCacheWithInvalidEvictionHeapPercentage() throws Exception {
try {
CacheFactoryBean cacheFactoryBean = new CacheFactoryBean();
@@ -559,6 +578,7 @@ public class CacheFactoryBeanTest {
@Test(expected = IllegalArgumentException.class)
public void postProcessCacheWithInvalidEvictionOffHeapPercentage() throws Exception {
try {
CacheFactoryBean cacheFactoryBean = new CacheFactoryBean();
@@ -584,6 +604,7 @@ public class CacheFactoryBeanTest {
@Test
public void getObjectTypeWithExistingCache() {
Cache mockCache = mock(Cache.class);
CacheFactoryBean cacheFactoryBean = new CacheFactoryBean();
@@ -600,8 +621,10 @@ public class CacheFactoryBeanTest {
@Test
@SuppressWarnings("unchecked")
public void destroy() throws Exception {
final AtomicBoolean fetchCacheCalled = new AtomicBoolean(false);
final Cache mockCache = mock(Cache.class, "GemFireCache");
AtomicBoolean fetchCacheCalled = new AtomicBoolean(false);
Cache mockCache = mock(Cache.class, "GemFireCache");
GemfireBeanFactoryLocator mockGemfireBeanFactoryLocator = mock(GemfireBeanFactoryLocator.class);
@@ -631,7 +654,8 @@ public class CacheFactoryBeanTest {
@Test
@SuppressWarnings("unchecked")
public void destroyWhenCacheIsNull() throws Exception {
final AtomicBoolean fetchCacheCalled = new AtomicBoolean(false);
AtomicBoolean fetchCacheCalled = new AtomicBoolean(false);
CacheFactoryBean cacheFactoryBean = new CacheFactoryBean() {
@Override protected <T extends GemFireCache> T fetchCache() {
@@ -650,8 +674,10 @@ public class CacheFactoryBeanTest {
@Test
@SuppressWarnings("unchecked")
public void destroyWhenCacheClosedIsTrue() throws Exception {
final AtomicBoolean fetchCacheCalled = new AtomicBoolean(false);
final Cache mockCache = mock(Cache.class, "GemFireCache");
AtomicBoolean fetchCacheCalled = new AtomicBoolean(false);
Cache mockCache = mock(Cache.class, "GemFireCache");
CacheFactoryBean cacheFactoryBean = new CacheFactoryBean() {
@Override @SuppressWarnings("unchecked") protected <T extends GemFireCache> T fetchCache() {
@@ -672,6 +698,7 @@ public class CacheFactoryBeanTest {
@Test
public void closeCache() {
GemFireCache mockCache = mock(GemFireCache.class, "testCloseCache.MockCache");
new CacheFactoryBean().close(mockCache);

View File

@@ -25,7 +25,7 @@ import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.junit4.SpringRunner;
/**
* Integration test trying various basic configurations of GemFire through
@@ -36,21 +36,29 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
* @author Costin Leau
* @author John Blum
*/
@RunWith(SpringJUnit4ClassRunner.class)
@RunWith(SpringRunner.class)
@ContextConfiguration(locations = "basic-cache.xml")
public class CacheIntegrationTest {
@Autowired ApplicationContext ctx;
@Autowired
ApplicationContext applicationContext;
Cache cache;
@After
public void tearDown() {
GemfireUtils.close(this.cache);
}
@Test
public void testBasicCache() throws Exception {
cache = ctx.getBean("default-cache",Cache.class);
cache = applicationContext.getBean("default-cache",Cache.class);
}
@Test
public void testCacheWithProps() throws Exception {
cache = ctx.getBean("cache-with-props", Cache.class);
cache = applicationContext.getBean("cache-with-props", Cache.class);
// the name property seems to be ignored
assertEquals("cache-with-props", cache.getDistributedSystem().getName());
assertEquals("cache-with-props", cache.getName());
@@ -58,18 +66,15 @@ public class CacheIntegrationTest {
@Test
public void testNamedCache() throws Exception {
cache = ctx.getBean("named-cache", Cache.class);
cache = applicationContext.getBean("named-cache", Cache.class);
assertEquals("named-cache", cache.getDistributedSystem().getName());
assertEquals("named-cache", cache.getName());
}
@Test
public void testCacheWithXml() throws Exception {
ctx.getBean("cache-with-xml", Cache.class);
}
@After
public void tearDown() {
if (cache!=null) cache.close();
applicationContext.getBean("cache-with-xml", Cache.class);
}
}

View File

@@ -196,7 +196,7 @@ public class LookupRegionFactoryBeanTest {
factoryBean.afterPropertiesSet();
}
catch (IllegalStateException expected) {
assertEquals("Statistics for Region '/Example' must be enabled to change Entry & Region TTL/TTI Expiration settings",
assertEquals("Statistics for Region [/Example] must be enabled to change Entry & Region TTL/TTI Expiration settings",
expected.getMessage());
throw expected;
}

View File

@@ -51,7 +51,7 @@ import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.StringUtils;
/**
@@ -67,7 +67,7 @@ import org.springframework.util.StringUtils;
* @see org.springframework.test.context.junit4.SpringJUnit4ClassRunner
* @since 1.7.0
*/
@RunWith(SpringJUnit4ClassRunner.class)
@RunWith(SpringRunner.class)
@ContextConfiguration
@SuppressWarnings("unused")
public class LookupRegionMutationIntegrationTest {
@@ -75,7 +75,8 @@ public class LookupRegionMutationIntegrationTest {
@Resource(name = "Example")
private Region<?, ?> example;
protected void assertCacheListeners(CacheListener[] cacheListeners, Collection<String> expectedCacheListenerNames) {
private void assertCacheListeners(CacheListener[] cacheListeners, Collection<String> expectedCacheListenerNames) {
if (!expectedCacheListenerNames.isEmpty()) {
assertNotNull("CacheListeners must not be null!", cacheListeners);
assertEquals(expectedCacheListenerNames.size(), cacheListeners.length);
@@ -83,38 +84,44 @@ public class LookupRegionMutationIntegrationTest {
}
}
protected void assertEvictionAttributes(EvictionAttributes evictionAttributes, EvictionAction expectedAction, EvictionAlgorithm expectedAlgorithm, int expectedMaximum) {
private void assertEvictionAttributes(EvictionAttributes evictionAttributes, EvictionAction expectedAction,
EvictionAlgorithm expectedAlgorithm, int expectedMaximum) {
assertNotNull("EvictionAttributes must not be null!", evictionAttributes);
assertEquals(expectedAction, evictionAttributes.getAction());
assertEquals(expectedAlgorithm, evictionAttributes.getAlgorithm());
assertEquals(expectedMaximum, evictionAttributes.getMaximum());
}
protected void assertExpirationAttributes(ExpirationAttributes expirationAttributes,
private void assertExpirationAttributes(ExpirationAttributes expirationAttributes,
String description, int expectedTimeout, ExpirationAction expectedAction) {
assertNotNull(String.format("ExpirationAttributes for '%1$s' must not be null!", description), expirationAttributes);
assertEquals(expectedAction, expirationAttributes.getAction());
assertEquals(expectedTimeout, expirationAttributes.getTimeout());
}
protected void assertGatewaySenders(Region<?, ?> region, List<String> expectedGatewaySenderIds) {
private void assertGatewaySenders(Region<?, ?> region, List<String> expectedGatewaySenderIds) {
assertNotNull(region.getAttributes());
assertNotNull(region.getAttributes().getGatewaySenderIds());
assertEquals(expectedGatewaySenderIds.size(), region.getAttributes().getGatewaySenderIds().size());
assertTrue(expectedGatewaySenderIds.containsAll(region.getAttributes().getGatewaySenderIds()));
}
protected void assertGemFireComponent(Object gemfireComponent, String expectedName) {
private void assertGemFireComponent(Object gemfireComponent, String expectedName) {
assertNotNull("The GemFire component must not be null!", gemfireComponent);
assertEquals(expectedName, gemfireComponent.toString());
}
protected void assertRegionAttributes(Region<?, ?> region, String expectedName, DataPolicy expectedDataPolicy) {
private void assertRegionAttributes(Region<?, ?> region, String expectedName, DataPolicy expectedDataPolicy) {
assertRegionAttributes(region, expectedName, String.format("%1$s%2$s", Region.SEPARATOR, expectedName),
expectedDataPolicy);
}
protected void assertRegionAttributes(Region<?, ?> region, String expectedName, String expectedFullPath,
private void assertRegionAttributes(Region<?, ?> region, String expectedName, String expectedFullPath,
DataPolicy expectedDataPolicy) {
assertNotNull(String.format("'%1$s' Region was not properly initialized!", region));
@@ -124,7 +131,8 @@ public class LookupRegionMutationIntegrationTest {
assertEquals(expectedDataPolicy, region.getAttributes().getDataPolicy());
}
protected Collection<String> toStrings(Object[] objects) {
private Collection<String> toStrings(Object[] objects) {
List<String> cacheListenerNames = new ArrayList<String>(objects.length);
for (Object object : objects) {
@@ -136,6 +144,7 @@ public class LookupRegionMutationIntegrationTest {
@Test
public void testRegionConfiguration() {
assertRegionAttributes(example, "Example", DataPolicy.REPLICATE);
assertEquals(13, example.getAttributes().getInitialCapacity());
assertEquals(0.85f, example.getAttributes().getLoadFactor(), 0.0f);
@@ -249,11 +258,12 @@ public class LookupRegionMutationIntegrationTest {
public static final class TestCustomExpiry<K, V> extends AbstractNameable implements CustomExpiry<K, V> {
@Override public ExpirationAttributes getExpiry(Region.Entry<K, V> entry) {
@Override
public ExpirationAttributes getExpiry(Region.Entry<K, V> entry) {
throw new UnsupportedOperationException("Not Implemented!");
}
@Override public void close() { }
@Override
public void close() { }
}
}

View File

@@ -26,7 +26,7 @@ import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.junit4.SpringRunner;
/**
* The LookupSubRegionTest class is a test suite of test cases testing the contract and functionality of Region lookups
@@ -41,15 +41,16 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
* @since 1.3.3
* @since 7.0.1 (GemFire)
*/
@RunWith(SpringRunner.class)
@ContextConfiguration("lookupSubRegion.xml")
@RunWith(SpringJUnit4ClassRunner.class)
@SuppressWarnings("unused")
public class LookupSubRegionTest {
@Autowired
private ApplicationContext context;
private ApplicationContext applicationContext;
private void assertRegionExists(final String expectedRegionName, final String expectedRegionPath, final Region region) {
protected void assertRegionExists(final String expectedRegionName, final String expectedRegionPath, final Region region) {
assertNotNull(String.format("The Region with name (%1$s) at path (%2$s) was null!",
expectedRegionName, expectedRegionPath), region);
assertEquals(String.format("Expected Region name of %1$s; but was %2$s!", expectedRegionName, region.getName()),
@@ -60,37 +61,38 @@ public class LookupSubRegionTest {
@Test
public void testDirectLookup() {
Region accounts = context.getBean("/Customers/Accounts", Region.class);
Region accounts = applicationContext.getBean("/Customers/Accounts", Region.class);
assertRegionExists("Accounts", "/Customers/Accounts", accounts);
assertFalse(context.containsBean("Customers/Accounts"));
assertFalse(context.containsBean("/Customers"));
assertFalse(context.containsBean("Customers"));
assertFalse(applicationContext.containsBean("Customers/Accounts"));
assertFalse(applicationContext.containsBean("/Customers"));
assertFalse(applicationContext.containsBean("Customers"));
Region items = context.getBean("Customers/Accounts/Orders/Items", Region.class);
Region items = applicationContext.getBean("Customers/Accounts/Orders/Items", Region.class);
assertRegionExists("Items", "/Customers/Accounts/Orders/Items", items);
assertFalse(context.containsBean("/Customers/Accounts/Orders/Items"));
assertFalse(context.containsBean("/Customers/Accounts/Orders"));
assertFalse(context.containsBean("Customers/Accounts/Orders"));
assertFalse(applicationContext.containsBean("/Customers/Accounts/Orders/Items"));
assertFalse(applicationContext.containsBean("/Customers/Accounts/Orders"));
assertFalse(applicationContext.containsBean("Customers/Accounts/Orders"));
}
@Test
public void testNestedLookup() {
Region parent = context.getBean("Parent", Region.class);
Region parent = applicationContext.getBean("Parent", Region.class);
assertRegionExists("Parent", "/Parent", parent);
assertFalse(context.containsBean("/Parent"));
assertFalse(applicationContext.containsBean("/Parent"));
Region child = context.getBean("/Parent/Child", Region.class);
Region child = applicationContext.getBean("/Parent/Child", Region.class);
assertRegionExists("Child", "/Parent/Child", child);
assertFalse(context.containsBean("Parent/Child"));
assertFalse(applicationContext.containsBean("Parent/Child"));
Region grandchild = context.getBean("/Parent/Child/Grandchild", Region.class);
Region grandchild = applicationContext.getBean("/Parent/Child/Grandchild", Region.class);
assertRegionExists("Grandchild", "/Parent/Child/Grandchild", grandchild);
assertFalse(context.containsBean("Parent/Child/Grandchild"));
assertFalse(applicationContext.containsBean("Parent/Child/Grandchild"));
}
}

View File

@@ -169,7 +169,7 @@ public class PartitionedRegionFactoryBeanTest {
factoryBean.resolveDataPolicy(mockRegionFactory, true, "PARTITION");
}
catch (IllegalArgumentException e) {
assertEquals("Data Policy [PARTITION] is invalid when persistent is true.", e.getMessage());
assertEquals("Data Policy [PARTITION] is not valid when persistent is true", e.getMessage());
throw e;
}
finally {
@@ -195,7 +195,7 @@ public class PartitionedRegionFactoryBeanTest {
factoryBean.resolveDataPolicy(mockRegionFactory, false, "PERSISTENT_PARTITION");
}
catch (IllegalArgumentException e) {
assertEquals("Data Policy [PERSISTENT_PARTITION] is invalid when persistent is false.", e.getMessage());
assertEquals("Data Policy [PERSISTENT_PARTITION] is not valid when persistent is false", e.getMessage());
throw e;
}
finally {

View File

@@ -125,7 +125,7 @@ public class RegionFactoryBeanTest extends AbstractRegionFactoryBeanTests {
@Override
public void verify() {
assertNotNull(this.exception);
assertEquals("Data Policy [PERSISTENT_REPLICATE] is invalid when persistent is false.",
assertEquals("Data Policy [PERSISTENT_REPLICATE] is not valid when persistent is false",
exception.getMessage());
}
};
@@ -170,53 +170,6 @@ public class RegionFactoryBeanTest extends AbstractRegionFactoryBeanTests {
return new TestRegionFactory();
}
@Test
public void testAssertDataPolicyAndPersistentAttributesAreCompatible() {
RegionFactoryBean<?, ?> factoryBean = new TestRegionFactoryBean<>();
factoryBean.setPersistent(null);
factoryBean.assertDataPolicyAndPersistentAttributesAreCompatible(DataPolicy.PARTITION);
factoryBean.assertDataPolicyAndPersistentAttributesAreCompatible(DataPolicy.REPLICATE);
factoryBean.assertDataPolicyAndPersistentAttributesAreCompatible(DataPolicy.PERSISTENT_PARTITION);
factoryBean.assertDataPolicyAndPersistentAttributesAreCompatible(DataPolicy.PERSISTENT_REPLICATE);
factoryBean.setPersistent(false);
factoryBean.assertDataPolicyAndPersistentAttributesAreCompatible(DataPolicy.PARTITION);
factoryBean.assertDataPolicyAndPersistentAttributesAreCompatible(DataPolicy.REPLICATE);
factoryBean.setPersistent(true);
factoryBean.assertDataPolicyAndPersistentAttributesAreCompatible(DataPolicy.PERSISTENT_PARTITION);
factoryBean.assertDataPolicyAndPersistentAttributesAreCompatible(DataPolicy.PERSISTENT_REPLICATE);
}
@Test(expected = IllegalArgumentException.class)
public void testAssertNonPersistentDataPolicyWithPersistentAttribute() {
try {
RegionFactoryBean<?, ?> factoryBean = new TestRegionFactoryBean<>();
factoryBean.setPersistent(true);
factoryBean.assertDataPolicyAndPersistentAttributesAreCompatible(DataPolicy.REPLICATE);
}
catch (IllegalArgumentException expected) {
assertEquals("Data Policy [REPLICATE] is invalid when persistent is true.", expected.getMessage());
throw expected;
}
}
@Test(expected = IllegalArgumentException.class)
public void testAssertPersistentDataPolicyWithNonPersistentAttribute() {
try {
RegionFactoryBean<?, ?> factoryBean = new TestRegionFactoryBean<>();
factoryBean.setPersistent(false);
factoryBean.assertDataPolicyAndPersistentAttributesAreCompatible(DataPolicy.PERSISTENT_PARTITION);
}
catch (IllegalArgumentException expected) {
assertEquals("Data Policy [PERSISTENT_PARTITION] is invalid when persistent is false.",
expected.getMessage());
throw expected;
}
}
@Test
public void testIsPersistent() {
@@ -233,26 +186,6 @@ public class RegionFactoryBeanTest extends AbstractRegionFactoryBeanTests {
assertTrue(factoryBean.isPersistent());
}
@Test
public void testIsPersistentUnspecified() {
RegionFactoryBean<?, ?> factoryBean = new TestRegionFactoryBean<>();
assertTrue(factoryBean.isPersistentUnspecified());
factoryBean.setPersistent(false);
assertFalse(factoryBean.isPersistentUnspecified());
factoryBean.setPersistent(true);
assertFalse(factoryBean.isPersistentUnspecified());
factoryBean.setPersistent(null);
assertTrue(factoryBean.isPersistentUnspecified());
}
@Test
public void testIsNotPersistent() {
@@ -761,7 +694,7 @@ public class RegionFactoryBeanTest extends AbstractRegionFactoryBeanTests {
factoryBean.resolveDataPolicy(mockRegionFactory, true, " ");
}
catch (IllegalArgumentException expected) {
assertEquals("Data Policy [ ] is invalid.", expected.getMessage());
assertEquals("Data Policy [ ] is invalid", expected.getMessage());
throw expected;
}
finally {
@@ -781,7 +714,7 @@ public class RegionFactoryBeanTest extends AbstractRegionFactoryBeanTests {
factoryBean.resolveDataPolicy(mockRegionFactory, true, "");
}
catch (IllegalArgumentException expected) {
assertEquals("Data Policy [] is invalid.", expected.getMessage());
assertEquals("Data Policy [] is invalid", expected.getMessage());
throw expected;
}
finally {
@@ -801,7 +734,7 @@ public class RegionFactoryBeanTest extends AbstractRegionFactoryBeanTests {
factoryBean.resolveDataPolicy(mockRegionFactory, true, "CSV");
}
catch (IllegalArgumentException expected) {
assertEquals("Data Policy [CSV] is invalid.", expected.getMessage());
assertEquals("Data Policy [CSV] is invalid", expected.getMessage());
throw expected;
}
finally {
@@ -842,7 +775,7 @@ public class RegionFactoryBeanTest extends AbstractRegionFactoryBeanTests {
factoryBean.resolveDataPolicy(mockRegionFactory, true, "EMPTY");
}
catch (IllegalArgumentException expected) {
assertEquals("Data Policy [EMPTY] is invalid when persistent is true.", expected.getMessage());
assertEquals("Data Policy [EMPTY] is not valid when persistent is true", expected.getMessage());
throw expected;
}
finally {
@@ -883,7 +816,7 @@ public class RegionFactoryBeanTest extends AbstractRegionFactoryBeanTests {
factoryBean.resolveDataPolicy(mockRegionFactory, false, "PERSISTENT_PARTITION");
}
catch (IllegalArgumentException expected) {
assertEquals("Data Policy [PERSISTENT_PARTITION] is invalid when persistent is false.", expected.getMessage());
assertEquals("Data Policy [PERSISTENT_PARTITION] is not valid when persistent is false", expected.getMessage());
throw expected;
}
finally {
@@ -906,7 +839,7 @@ public class RegionFactoryBeanTest extends AbstractRegionFactoryBeanTests {
"Setting the 'persistent' attribute to TRUE and 'Data Policy' to PARTITION should have thrown an IllegalArgumentException!");
}
catch (IllegalArgumentException expected) {
assertEquals("Data Policy [PARTITION] is invalid when persistent is true.", expected.getMessage());
assertEquals("Data Policy [PARTITION] is not valid when persistent is true", expected.getMessage());
throw expected;
}
finally {
@@ -992,7 +925,7 @@ public class RegionFactoryBeanTest extends AbstractRegionFactoryBeanTests {
factoryBean.resolveDataPolicy(mockRegionFactory, false, (String) null);
}
catch (IllegalArgumentException expected) {
assertEquals("Data Policy [PERSISTENT_PARTITION] is invalid when persistent is false.", expected.getMessage());
assertEquals("Data Policy [PERSISTENT_PARTITION] is not valid when persistent is false", expected.getMessage());
throw expected;
}
finally {
@@ -1014,7 +947,7 @@ public class RegionFactoryBeanTest extends AbstractRegionFactoryBeanTests {
factoryBean.resolveDataPolicy(mockRegionFactory, true, (String) null);
}
catch (IllegalArgumentException expected) {
assertEquals("Data Policy [PARTITION] is invalid when persistent is true.", expected.getMessage());
assertEquals("Data Policy [PARTITION] is not valid when persistent is true", expected.getMessage());
throw expected;
}
finally {
@@ -1092,7 +1025,7 @@ public class RegionFactoryBeanTest extends AbstractRegionFactoryBeanTests {
fail("Setting the 'persistent' attribute to FALSE and 'Data Policy' to PERSISTENT_REPLICATE should have thrown an IllegalArgumentException!");
}
catch (IllegalArgumentException expected) {
assertEquals("Data Policy [PERSISTENT_REPLICATE] is invalid when persistent is false.", expected.getMessage());
assertEquals("Data Policy [PERSISTENT_REPLICATE] is not valid when persistent is false", expected.getMessage());
throw expected;
}
finally {
@@ -1114,7 +1047,7 @@ public class RegionFactoryBeanTest extends AbstractRegionFactoryBeanTests {
fail("Setting the 'persistent' attribute to TRUE and 'Data Policy' to REPLICATE should have thrown an IllegalArgumentException!");
}
catch (IllegalArgumentException expected) {
assertEquals("Data Policy [REPLICATE] is invalid when persistent is true.", expected.getMessage());
assertEquals("Data Policy [REPLICATE] is not valid when persistent is true", expected.getMessage());
throw expected;
}
finally {

View File

@@ -22,6 +22,8 @@ import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.Optional;
import org.apache.geode.cache.DataPolicy;
import org.apache.geode.cache.Region;
import org.apache.geode.cache.RegionExistsException;
@@ -44,9 +46,11 @@ import org.springframework.data.gemfire.fork.SpringContainerProcess;
* @since 1.4.0
* @link https://jira.spring.io/browse/SGF-204
*/
// TODO: slow test; can this test use mocks?
public class RegionLookupIntegrationTests {
protected void assertNoRegionLookup(final String configLocation) {
private void assertNoRegionLookup(String configLocation) {
ConfigurableApplicationContext applicationContext = null;
try {
@@ -54,8 +58,9 @@ public class RegionLookupIntegrationTests {
fail("Spring ApplicationContext should have thrown a BeanCreationException caused by a RegionExistsException!");
}
catch (BeanCreationException expected) {
//expected.printStackTrace(System.err);
assertTrue(expected.getMessage(), expected.getCause() instanceof RegionExistsException);
throw (RegionExistsException) expected.getCause();
}
finally {
@@ -63,18 +68,17 @@ public class RegionLookupIntegrationTests {
}
}
protected void closeApplicationContext(final ConfigurableApplicationContext applicationContext) {
if (applicationContext != null) {
applicationContext.close();
}
private ConfigurableApplicationContext createApplicationContext(String configLocation) {
return new ClassPathXmlApplicationContext(configLocation);
}
protected ConfigurableApplicationContext createApplicationContext(final String configLocation) {
return new ClassPathXmlApplicationContext(configLocation);
private void closeApplicationContext(ConfigurableApplicationContext applicationContext) {
Optional.ofNullable(applicationContext).ifPresent(ConfigurableApplicationContext::close);
}
@Test
public void testAllowRegionBeanDefinitionOverrides() {
ConfigurableApplicationContext applicationContext = null;
try {
@@ -142,6 +146,7 @@ public class RegionLookupIntegrationTests {
@Test
public void testEnableRegionLookups() {
ConfigurableApplicationContext applicationContext = null;
try {
@@ -225,6 +230,7 @@ public class RegionLookupIntegrationTests {
@Test
public void testEnableClientRegionLookups() {
ConfigurableApplicationContext applicationContext = null;
try {
@@ -257,5 +263,4 @@ public class RegionLookupIntegrationTests {
closeApplicationContext(applicationContext);
}
}
}

View File

@@ -168,7 +168,7 @@ public class ReplicatedRegionFactoryBeanTest {
factoryBean.resolveDataPolicy(mockRegionFactory, true, "empty");
}
catch (IllegalArgumentException e) {
assertEquals("Data Policy [EMPTY] is invalid when persistent is true.", e.getMessage());
assertEquals("Data Policy [EMPTY] is not valid when persistent is true", e.getMessage());
throw e;
}
finally {
@@ -202,7 +202,7 @@ public class ReplicatedRegionFactoryBeanTest {
factoryBean.resolveDataPolicy(mockRegionFactory, true, "REPLICATE");
}
catch (IllegalArgumentException e) {
assertEquals("Data Policy [REPLICATE] is invalid when persistent is true.", e.getMessage());
assertEquals("Data Policy [REPLICATE] is not valid when persistent is true", e.getMessage());
throw e;
}
finally {
@@ -228,7 +228,7 @@ public class ReplicatedRegionFactoryBeanTest {
factoryBean.resolveDataPolicy(mockRegionFactory, false, "PERSISTENT_REPLICATE");
}
catch (IllegalArgumentException e) {
assertEquals("Data Policy [PERSISTENT_REPLICATE] is invalid when persistent is false.", e.getMessage());
assertEquals("Data Policy [PERSISTENT_REPLICATE] is not valid when persistent is false", e.getMessage());
throw e;
}
finally {

View File

@@ -32,6 +32,7 @@ import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
@@ -40,7 +41,6 @@ import static org.mockito.Mockito.when;
import java.net.InetSocketAddress;
import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
import java.util.Optional;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicBoolean;
@@ -52,14 +52,10 @@ import org.apache.geode.cache.client.ClientCacheFactory;
import org.apache.geode.cache.client.Pool;
import org.apache.geode.distributed.DistributedSystem;
import org.apache.geode.pdx.PdxSerializer;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.data.gemfire.GemfireUtils;
import org.springframework.data.gemfire.config.xml.GemfireConstants;
import org.springframework.data.gemfire.support.ConnectionEndpoint;
import org.springframework.data.gemfire.util.ArrayUtils;
import org.springframework.data.gemfire.util.DistributedSystemUtils;
@@ -84,17 +80,16 @@ import org.springframework.data.gemfire.util.DistributedSystemUtils;
*/
public class ClientCacheFactoryBeanTest {
@Rule
public ExpectedException exception = ExpectedException.none();
private Properties createProperties(String key, String value) {
return addProperty(null, key, value);
}
@SuppressWarnings("all")
private Properties addProperty(Properties properties, String key, String value) {
properties = Optional.ofNullable(properties).orElseGet(Properties::new);
properties.setProperty(key, value);
return properties;
}
@@ -267,19 +262,19 @@ public class ClientCacheFactoryBeanTest {
ClientCacheFactoryBean clientCacheFactoryBean = new ClientCacheFactoryBean() {
@Override
ClientCacheFactory initializePdx(ClientCacheFactory clientCacheFactory) {
ClientCacheFactory configurePdx(ClientCacheFactory clientCacheFactory) {
initializePdxCalled.set(true);
return clientCacheFactory;
}
@Override
ClientCacheFactory initializePool(final ClientCacheFactory clientCacheFactory) {
ClientCacheFactory configurePool(final ClientCacheFactory clientCacheFactory) {
initializePoolCalled.set(true);
return clientCacheFactory;
}
};
assertThat(clientCacheFactoryBean.prepareFactory(mockClientCacheFactory),
assertThat(clientCacheFactoryBean.configureFactory(mockClientCacheFactory),
is(sameInstance(mockClientCacheFactory)));
assertThat(initializePdxCalled.get(), is(true));
assertThat(initializePoolCalled.get(), is(true));
@@ -306,7 +301,7 @@ public class ClientCacheFactoryBeanTest {
ClientCacheFactory mockClientCacheFactory = mock(ClientCacheFactory.class);
assertThat(clientCacheFactoryBean.initializePdx(mockClientCacheFactory),
assertThat(clientCacheFactoryBean.configurePdx(mockClientCacheFactory),
is(sameInstance(mockClientCacheFactory)));
verify(mockClientCacheFactory, times(1)).setPdxSerializer(eq(mockPdxSerializer));
@@ -332,7 +327,7 @@ public class ClientCacheFactoryBeanTest {
ClientCacheFactory mockClientCacheFactory = mock(ClientCacheFactory.class);
assertThat(clientCacheFactoryBean.initializePdx(mockClientCacheFactory),
assertThat(clientCacheFactoryBean.configurePdx(mockClientCacheFactory),
is(sameInstance(mockClientCacheFactory)));
verify(mockClientCacheFactory, never()).setPdxDiskStore(anyString());
@@ -355,7 +350,7 @@ public class ClientCacheFactoryBeanTest {
ClientCacheFactory mockClientCacheFactory = mock(ClientCacheFactory.class);
assertThat(clientCacheFactoryBean.initializePdx(mockClientCacheFactory),
assertThat(clientCacheFactoryBean.configurePdx(mockClientCacheFactory),
is(sameInstance(mockClientCacheFactory)));
verifyZeroInteractions(mockClientCacheFactory);
@@ -419,7 +414,7 @@ public class ClientCacheFactoryBeanTest {
ClientCacheFactory mockClientCacheFactory = mock(ClientCacheFactory.class);
assertThat(clientCacheFactoryBean.initializePool(mockClientCacheFactory),
assertThat(clientCacheFactoryBean.configurePool(mockClientCacheFactory),
is(sameInstance(mockClientCacheFactory)));
verify(mockPool, times(1)).getFreeConnectionTimeout();
@@ -523,7 +518,7 @@ public class ClientCacheFactoryBeanTest {
ClientCacheFactory mockClientCacheFactory = mock(ClientCacheFactory.class);
assertThat(clientCacheFactoryBean.initializePool(mockClientCacheFactory),
assertThat(clientCacheFactoryBean.configurePool(mockClientCacheFactory),
is(sameInstance(mockClientCacheFactory)));
verifyZeroInteractions(mockPool);
@@ -622,7 +617,7 @@ public class ClientCacheFactoryBeanTest {
ClientCacheFactory mockClientCacheFactory = mock(ClientCacheFactory.class);
assertThat(clientCacheFactoryBean.initializePool(mockClientCacheFactory),
assertThat(clientCacheFactoryBean.configurePool(mockClientCacheFactory),
is(sameInstance(mockClientCacheFactory)));
verify(mockPool, times(1)).getFreeConnectionTimeout();
@@ -687,7 +682,7 @@ public class ClientCacheFactoryBeanTest {
ClientCacheFactory mockClientCacheFactory = mock(ClientCacheFactory.class);
assertThat(clientCacheFactoryBean.initializePool(mockClientCacheFactory),
assertThat(clientCacheFactoryBean.configurePool(mockClientCacheFactory),
is(sameInstance(mockClientCacheFactory)));
verify(mockPool, never()).getLocators();
@@ -715,7 +710,7 @@ public class ClientCacheFactoryBeanTest {
ClientCacheFactory mockClientCacheFactory = mock(ClientCacheFactory.class);
assertThat(clientCacheFactoryBean.initializePool(mockClientCacheFactory),
assertThat(clientCacheFactoryBean.configurePool(mockClientCacheFactory),
is(sameInstance(mockClientCacheFactory)));
verify(mockPool, never()).getLocators();
@@ -742,7 +737,7 @@ public class ClientCacheFactoryBeanTest {
ClientCacheFactory mockClientCacheFactory = mock(ClientCacheFactory.class);
assertThat(clientCacheFactoryBean.initializePool(mockClientCacheFactory),
assertThat(clientCacheFactoryBean.configurePool(mockClientCacheFactory),
is(sameInstance(mockClientCacheFactory)));
verify(mockPool, times(1)).getLocators();
@@ -769,7 +764,7 @@ public class ClientCacheFactoryBeanTest {
ClientCacheFactory mockClientCacheFactory = mock(ClientCacheFactory.class);
assertThat(clientCacheFactoryBean.initializePool(mockClientCacheFactory),
assertThat(clientCacheFactoryBean.configurePool(mockClientCacheFactory),
is(sameInstance(mockClientCacheFactory)));
verify(mockPool, never()).getLocators();
@@ -793,7 +788,7 @@ public class ClientCacheFactoryBeanTest {
ClientCacheFactory mockClientCacheFactory = mock(ClientCacheFactory.class);
assertThat(clientCacheFactoryBean.initializePool(mockClientCacheFactory),
assertThat(clientCacheFactoryBean.configurePool(mockClientCacheFactory),
is(sameInstance(mockClientCacheFactory)));
verify(mockClientCacheFactory, never()).addPoolLocator(anyString(), anyInt());
@@ -819,31 +814,29 @@ public class ClientCacheFactoryBeanTest {
}
@Test
public void resolvePoolByReturningProvidedPool() {
public void resolvePoolReturnsConfiguredPool() {
Pool mockPool = mock(Pool.class);
ClientCacheFactoryBean clientCacheFactoryBean = new ClientCacheFactoryBean();
ClientCacheFactoryBean clientCacheFactoryBean = spy(new ClientCacheFactoryBean());
clientCacheFactoryBean.setPool(mockPool);
assertThat(clientCacheFactoryBean.getPool(), is(sameInstance(mockPool)));
assertThat(clientCacheFactoryBean.resolvePool(), is(equalTo(mockPool)));
verify(clientCacheFactoryBean, never()).getPoolName();
verifyZeroInteractions(mockPool);
}
@Test
public void resolvesPoolByName() {
public void resolvesPoolReturnsNamedPool() {
Pool mockPool = mock(Pool.class);
ClientCacheFactoryBean clientCacheFactoryBean = new ClientCacheFactoryBean() {
@Override Pool findPool(String name) {
assertThat(name, is(equalTo("TestPool")));
return mockPool;
}
};
ClientCacheFactoryBean clientCacheFactoryBean = spy(new ClientCacheFactoryBean());
when(clientCacheFactoryBean.findPool(eq("TestPool"))).thenReturn(mockPool);
clientCacheFactoryBean.setPoolName("TestPool");
@@ -851,150 +844,59 @@ public class ClientCacheFactoryBeanTest {
assertThat(clientCacheFactoryBean.getPoolName(), is(equalTo("TestPool")));
assertThat(clientCacheFactoryBean.resolvePool(), is(equalTo(mockPool)));
verify(clientCacheFactoryBean, times(1)).findPool(eq("TestPool"));
verifyZeroInteractions(mockPool);
}
@Test
public void resolvesPoolByDefaultName() {
Pool mockPool = mock(Pool.class);
ClientCacheFactoryBean clientCacheFactoryBean = new ClientCacheFactoryBean() {
@Override Pool findPool(String name) {
assertThat(name, is(equalTo(GemfireConstants.DEFAULT_GEMFIRE_POOL_NAME)));
return mockPool;
}
};
assertThat(clientCacheFactoryBean.getPool(), is(nullValue()));
assertThat(clientCacheFactoryBean.getPoolName(), is(nullValue()));
assertThat(clientCacheFactoryBean.resolvePool(), is(equalTo(mockPool)));
verifyZeroInteractions(mockPool);
}
@Test
public void resolvesNamedPoolFromBeanFactory() {
ListableBeanFactory mockBeanFactory = mock(ListableBeanFactory.class);
Pool mockPool = mock(Pool.class);
PoolFactoryBean mockPoolFactoryBean = mock(PoolFactoryBean.class);
Map<String, PoolFactoryBean> beans = Collections.singletonMap("&TestPool", mockPoolFactoryBean);
when(mockBeanFactory.getBeansOfType(eq(PoolFactoryBean.class), eq(false), eq(false))).thenReturn(beans);
when(mockPoolFactoryBean.getPool()).thenReturn(mockPool);
ClientCacheFactoryBean clientCacheFactoryBean = new ClientCacheFactoryBean();
clientCacheFactoryBean.setBeanFactory(mockBeanFactory);
clientCacheFactoryBean.setPoolName("TestPool");
assertThat(clientCacheFactoryBean.getBeanFactory(), is(equalTo(mockBeanFactory)));
assertThat(clientCacheFactoryBean.getPool(), is(nullValue()));
assertThat(clientCacheFactoryBean.getPoolName(), is(equalTo("TestPool")));
assertThat(clientCacheFactoryBean.resolvePool(), is(equalTo(mockPool)));
verify(mockBeanFactory, times(1)).getBeansOfType(eq(PoolFactoryBean.class), eq(false), eq(false));
verify(mockPoolFactoryBean, times(1)).getPool();
verifyZeroInteractions(mockPool);
}
@Test
public void resolvesUnnamedPoolFromBeanFactory() {
ListableBeanFactory mockBeanFactory = mock(ListableBeanFactory.class);
Pool mockPool = mock(Pool.class);
PoolFactoryBean mockPoolFactoryBean = mock(PoolFactoryBean.class);
Map<String, PoolFactoryBean> beans = Collections.singletonMap("&gemfirePool", mockPoolFactoryBean);
when(mockBeanFactory.getBeansOfType(eq(PoolFactoryBean.class), eq(false), eq(false))).thenReturn(beans);
when(mockPoolFactoryBean.getPool()).thenReturn(mockPool);
ClientCacheFactoryBean clientCacheFactoryBean = new ClientCacheFactoryBean();
clientCacheFactoryBean.setBeanFactory(mockBeanFactory);
assertThat(clientCacheFactoryBean.getBeanFactory(), is(equalTo(mockBeanFactory)));
assertThat(clientCacheFactoryBean.getPool(), is(nullValue()));
assertThat(clientCacheFactoryBean.getPoolName(), is(nullValue()));
assertThat(clientCacheFactoryBean.resolvePool(), is(equalTo(mockPool)));
verify(mockBeanFactory, times(1)).getBeansOfType(eq(PoolFactoryBean.class), eq(false), eq(false));
verify(mockPoolFactoryBean, times(1)).getPool();
verifyZeroInteractions(mockPool);
}
@Test
public void resolvePoolReturnsNullWhenNoBeansOfTypePoolFactoryBeanExists() {
ListableBeanFactory mockBeanFactory = mock(ListableBeanFactory.class);
Map<String, PoolFactoryBean> beans = Collections.emptyMap();
when(mockBeanFactory.getBeansOfType(eq(PoolFactoryBean.class), eq(false), eq(false))).thenReturn(beans);
ClientCacheFactoryBean clientCacheFactoryBean = new ClientCacheFactoryBean();
clientCacheFactoryBean.setBeanFactory(mockBeanFactory);
assertThat(clientCacheFactoryBean.getBeanFactory(), is(equalTo(mockBeanFactory)));
assertThat(clientCacheFactoryBean.getPool(), is(nullValue()));
assertThat(clientCacheFactoryBean.getPoolName(), is(nullValue()));
assertThat(clientCacheFactoryBean.resolvePool(), is(nullValue()));
verify(mockBeanFactory, times(1)).getBeansOfType(eq(PoolFactoryBean.class), eq(false), eq(false));
}
@Test
public void resolvePoolReturnsNullWhenNoBeansOfTypePoolFactoryBeanExistsWithPoolName() {
ListableBeanFactory mockBeanFactory = mock(ListableBeanFactory.class);
Pool mockPool = mock(Pool.class);
PoolFactoryBean mockPoolFactoryBean = mock(PoolFactoryBean.class);
Map<String, PoolFactoryBean> beans = Collections.singletonMap("&swimPool", mockPoolFactoryBean);
when(mockBeanFactory.getBeansOfType(eq(PoolFactoryBean.class), eq(false), eq(false))).thenReturn(beans);
when(mockPoolFactoryBean.getPool()).thenReturn(mockPool);
ClientCacheFactoryBean clientCacheFactoryBean = new ClientCacheFactoryBean();
clientCacheFactoryBean.setBeanFactory(mockBeanFactory);
clientCacheFactoryBean.setPoolName("TestPool");
assertThat(clientCacheFactoryBean.getBeanFactory(), is(equalTo(mockBeanFactory)));
assertThat(clientCacheFactoryBean.getPool(), is(nullValue()));
assertThat(clientCacheFactoryBean.getPoolName(), is(equalTo("TestPool")));
assertThat(clientCacheFactoryBean.resolvePool(), is(nullValue()));
verify(mockBeanFactory, times(1)).getBeansOfType(eq(PoolFactoryBean.class), eq(false), eq(false));
verify(mockPoolFactoryBean, never()).getPool();
verifyZeroInteractions(mockPool);
}
@Test
public void resolvePoolReturnsNullWhenBeanFactoryIsNotAListableBeanFactory() {
public void resolvesPoolReturnsNamedPoolFromBeanFactory() {
BeanFactory mockBeanFactory = mock(BeanFactory.class);
Pool mockPool = mock(Pool.class);
PoolFactoryBean mockPoolFactoryBean = mock(PoolFactoryBean.class);
when(mockBeanFactory.containsBean(eq("TestPool"))).thenReturn(true);
when(mockBeanFactory.getBean(eq("&TestPool"), eq(PoolFactoryBean.class))).thenReturn(mockPoolFactoryBean);
when(mockPoolFactoryBean.getPool()).thenReturn(mockPool);
ClientCacheFactoryBean clientCacheFactoryBean = new ClientCacheFactoryBean();
clientCacheFactoryBean.setBeanFactory(mockBeanFactory);
clientCacheFactoryBean.setPoolName("TestPool");
assertThat(clientCacheFactoryBean.getBeanFactory(), is(equalTo(mockBeanFactory)));
assertThat(clientCacheFactoryBean.getPool(), is(nullValue()));
assertThat(clientCacheFactoryBean.getPoolName(), is(nullValue()));
assertThat(clientCacheFactoryBean.resolvePool(), is(nullValue()));
assertThat(clientCacheFactoryBean.getPoolName(), is(equalTo("TestPool")));
assertThat(clientCacheFactoryBean.resolvePool(), is(equalTo(mockPool)));
verifyZeroInteractions(mockBeanFactory);
verify(mockBeanFactory, times(1)).containsBean(eq("TestPool"));
verify(mockBeanFactory, times(1))
.getBean(eq("&TestPool"), eq(PoolFactoryBean.class));
verify(mockPoolFactoryBean, times(1)).getPool();
verifyZeroInteractions(mockPool);
}
@Test
public void resolvePoolWhenBeanFactoryHasNoPoolBeansReturnsNull() {
BeanFactory mockBeanFactory = mock(BeanFactory.class);
when(mockBeanFactory.containsBean(anyString())).thenReturn(false);
ClientCacheFactoryBean clientCacheFactoryBean = new ClientCacheFactoryBean();
clientCacheFactoryBean.setBeanFactory(mockBeanFactory);
clientCacheFactoryBean.setPoolName("TestPool");
assertThat(clientCacheFactoryBean.getBeanFactory(), is(equalTo(mockBeanFactory)));
assertThat(clientCacheFactoryBean.getPool(), is(nullValue()));
assertThat(clientCacheFactoryBean.getPoolName(), is(equalTo("TestPool")));
assertThat(clientCacheFactoryBean.resolvePool(), is(nullValue(Pool.class)));
verify(mockBeanFactory, times(1)).containsBean(eq("TestPool"));
verify(mockBeanFactory, never()).getBean(anyString(), eq(PoolFactoryBean.class));
}
@Test

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.gemfire.client;
import static org.assertj.core.api.Assertions.assertThat;
@@ -20,13 +21,11 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
@@ -51,10 +50,8 @@ import org.apache.geode.compression.Compressor;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InOrder;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.core.io.Resource;
import org.springframework.data.gemfire.TestUtils;
import org.springframework.data.gemfire.util.ArrayUtils;
@@ -79,32 +76,36 @@ public class ClientRegionFactoryBeanTest {
@Before
public void setup() {
factoryBean = spy(new ClientRegionFactoryBean<>());
this.factoryBean = spy(new ClientRegionFactoryBean<>());
}
@After
public void tearDown() throws Exception {
factoryBean.destroy();
factoryBean = null;
this.factoryBean.destroy();
this.factoryBean = null;
}
@Test
@SuppressWarnings({ "deprecation", "unchecked" })
public void createRegionUsingDefaultShortcut() throws Exception {
String testRegionName = "TestRegion";
BeanFactory mockBeanFactory = mock(BeanFactory.class);
ClientCache mockClientCache = mock(ClientCache.class);
ClientRegionFactory mockClientRegionFactory = mock(ClientRegionFactory.class);
Pool mockPool = mock(Pool.class);
Region mockRegion = mock(Region.class);
RegionAttributes mockRegionAttributes = mock(RegionAttributes.class);
when(mockBeanFactory.getBean(eq("TestPoolTwo"), eq(Pool.class))).thenReturn(mockPool);
when(mockClientCache.createClientRegionFactory(eq(ClientRegionShortcut.LOCAL)))
.thenReturn(mockClientRegionFactory);
when(mockClientRegionFactory.create(eq(testRegionName))).thenReturn(mockRegion);
when(mockClientRegionFactory.create(eq("TestRegion"))).thenReturn(mockRegion);
when(mockPool.getName()).thenReturn("TestPoolTwo");
when(mockRegionAttributes.getCloningEnabled()).thenReturn(false);
when(mockRegionAttributes.getCompressor()).thenReturn(mock(Compressor.class));
when(mockRegionAttributes.getConcurrencyChecksEnabled()).thenReturn(true);
@@ -125,19 +126,6 @@ public class ClientRegionFactoryBeanTest {
when(mockRegionAttributes.getStatisticsEnabled()).thenReturn(true);
when(mockRegionAttributes.getValueConstraint()).thenReturn(Number.class);
BeanFactory mockBeanFactory = mock(BeanFactory.class);
Pool mockPool = mock(Pool.class);
Resource mockSnapshot = mock(Resource.class, "Snapshot");
when(mockBeanFactory.containsBean(eq("TestPoolOne"))).thenReturn(false);
when(mockBeanFactory.containsBean(eq("TestPoolTwo"))).thenReturn(true);
when(mockBeanFactory.isTypeMatch(eq("TestPoolTwo"), eq(Pool.class))).thenReturn(true);
when(mockBeanFactory.getBean(eq("TestPoolTwo"))).thenReturn(mockPool);
when(mockPool.getName()).thenReturn("TestPoolTwo");
when(mockSnapshot.getInputStream()).thenReturn(mock(InputStream.class));
EvictionAttributes evictionAttributes = EvictionAttributes.createLRUEntryAttributes();
factoryBean.setAttributes(mockRegionAttributes);
@@ -146,12 +134,11 @@ public class ClientRegionFactoryBeanTest {
factoryBean.setEvictionAttributes(evictionAttributes);
factoryBean.setPersistent(false);
factoryBean.setPoolName("TestPoolTwo");
factoryBean.setSnapshot(mockSnapshot);
factoryBean.setShortcut(null);
Region actualRegion = factoryBean.createRegion(mockClientCache, testRegionName);
Region actualRegion = factoryBean.createRegion(mockClientCache, "TestRegion");
assertSame(mockRegion, actualRegion);
assertThat(actualRegion).isEqualTo(mockRegion);
verify(mockClientCache, times(1)).createClientRegionFactory(eq(ClientRegionShortcut.LOCAL));
verify(mockClientRegionFactory, times(1)).setCloningEnabled(eq(false));
@@ -161,6 +148,7 @@ public class ClientRegionFactoryBeanTest {
verify(mockClientRegionFactory, times(1)).setCustomEntryIdleTimeout(null);
verify(mockClientRegionFactory, times(1)).setCustomEntryTimeToLive(null);
verify(mockClientRegionFactory, times(1)).setDiskStoreName(eq("TestDiskStoreOne"));
verify(mockClientRegionFactory, times(1)).setDiskStoreName(eq("TestDiskStoreTwo"));
verify(mockClientRegionFactory, times(1)).setDiskSynchronous(eq(false));
verify(mockClientRegionFactory, times(1)).setEntryIdleTimeout(any(ExpirationAttributes.class));
verify(mockClientRegionFactory, times(1)).setEntryTimeToLive(any(ExpirationAttributes.class));
@@ -169,13 +157,12 @@ public class ClientRegionFactoryBeanTest {
verify(mockClientRegionFactory, times(1)).setKeyConstraint(eq(Long.class));
verify(mockClientRegionFactory, times(1)).setLoadFactor(eq(0.75f));
verify(mockClientRegionFactory, never()).setPoolName(eq("TestPoolOne"));
verify(mockClientRegionFactory, times(1)).setPoolName(eq("TestPoolTwo"));
verify(mockClientRegionFactory, times(1)).setRegionIdleTimeout(any(ExpirationAttributes.class));
verify(mockClientRegionFactory, times(1)).setRegionTimeToLive(any(ExpirationAttributes.class));
verify(mockClientRegionFactory, times(1)).setStatisticsEnabled(eq(true));
verify(mockClientRegionFactory, times(1)).setValueConstraint(eq(Number.class));
verify(mockClientRegionFactory, times(1)).setDiskStoreName(eq("TestDiskStoreTwo"));
verify(mockClientRegionFactory, times(1)).setPoolName(eq("TestPoolTwo"));
verify(mockClientRegionFactory, times(1)).create(eq(testRegionName));
verify(mockClientRegionFactory, times(1)).create(eq("TestRegion"));
verify(mockRegion, never()).loadSnapshot(any(InputStream.class));
}
@@ -183,34 +170,37 @@ public class ClientRegionFactoryBeanTest {
@SuppressWarnings({ "deprecation", "unchecked" })
public void createRegionUsingDefaultPersistentShortcut() throws Exception {
BeanFactory mockBeanFactory = mock(BeanFactory.class);
ClientCache mockClientCache = mock(ClientCache.class);
ClientRegionFactory<Object, Object> mockClientRegionFactory = mock(ClientRegionFactory.class);
Pool mockPool = mock(Pool.class);
Region<Object, Object> mockRegion = mock(Region.class);
RegionAttributes<Object, Object> mockRegionAttributes = mock(RegionAttributes.class);
when(mockBeanFactory.getBean(anyString(), eq(Pool.class))).thenReturn(mockPool);
when(mockClientCache.createClientRegionFactory(eq(ClientRegionShortcut.LOCAL_PERSISTENT)))
.thenReturn(mockClientRegionFactory);
when(mockClientRegionFactory.create(eq("TestRegion"))).thenReturn(mockRegion);
when(mockRegionAttributes.getPoolName()).thenReturn("TestPool");
BeanFactory mockBeanFactory = mock(BeanFactory.class);
when(mockBeanFactory.containsBean(eq("TestPool"))).thenReturn(true);
when(mockBeanFactory.isTypeMatch(eq("TestPool"), eq(Pool.class))).thenReturn(false);
factoryBean.setAttributes(mockRegionAttributes);
factoryBean.setBeanFactory(mockBeanFactory);
factoryBean.setPersistent(true);
factoryBean.setPoolName("TestPool");
Region<Object, Object> actualRegion = factoryBean.createRegion(mockClientCache, "TestRegion");
assertSame(mockRegion, actualRegion);
assertThat(actualRegion).isEqualTo(mockRegion);
verify(mockBeanFactory, times(1)).getBean(eq("TestPool"), eq(Pool.class));
verify(mockClientCache, times(1)).createClientRegionFactory(eq(ClientRegionShortcut.LOCAL_PERSISTENT));
verify(mockClientRegionFactory, times(1)).setPoolName(eq("TestPool"));
verify(mockClientRegionFactory, times(1)).create(eq("TestRegion"));
verify(mockBeanFactory, times(1)).containsBean(eq("TestPool"));
verify(mockBeanFactory, never()).getBean(eq("TestPool"));
verify(mockRegionAttributes, times(1)).getPoolName();
verify(mockRegion, never()).loadSnapshot(any(InputStream.class));
}
@@ -235,7 +225,7 @@ public class ClientRegionFactoryBeanTest {
Region<Object, Object> actualRegion = factoryBean.createRegion(mockClientCache, "TestRegion");
assertSame(mockRegion, actualRegion);
assertThat(actualRegion).isEqualTo(mockRegion);
verifyZeroInteractions(mockBeanFactory);
verify(mockClientCache, times(1))
@@ -245,7 +235,7 @@ public class ClientRegionFactoryBeanTest {
@Test
@SuppressWarnings("unchecked")
public void createRegionWithSubRegionCreation() throws Exception {
public void createRegionAsSubRegion() throws Exception {
BeanFactory mockBeanFactory = mock(BeanFactory.class);
@@ -266,7 +256,7 @@ public class ClientRegionFactoryBeanTest {
Region<Object, Object> actualRegion = factoryBean.createRegion(mockClientCache, "TestSubRegion");
assertSame(mockSubRegion, actualRegion);
assertThat(actualRegion).isEqualTo(mockSubRegion);
verifyZeroInteractions(mockBeanFactory);
verify(mockClientCache, times(1))
@@ -277,108 +267,142 @@ public class ClientRegionFactoryBeanTest {
@Test
@SuppressWarnings("unchecked")
public void configurePoolFromRegionAttributesAndEagerlyInitializesPool() {
public void createClientRegionFactoryFromClientCache() {
ClientCache mockClientCache = mock(ClientCache.class);
ClientRegionFactory mockClientRegionFactory = mock(ClientRegionFactory.class);
when(mockClientCache.createClientRegionFactory(any(ClientRegionShortcut.class)))
.thenReturn(mockClientRegionFactory);
assertThat(factoryBean.createClientRegionFactory(mockClientCache, ClientRegionShortcut.CACHING_PROXY))
.isEqualTo(mockClientRegionFactory);
verify(mockClientCache, times(1))
.createClientRegionFactory(eq(ClientRegionShortcut.CACHING_PROXY));
}
@Test
@SuppressWarnings("unchecked")
public void configurePoolFromClientRegionFactoryBeanAndEagerlyInitializePool() {
BeanFactory mockBeanFactory = mock(BeanFactory.class);
ClientRegionFactory<Object, Object> mockClientRegionFactory = mock(ClientRegionFactory.class);
Pool mockPool = mock(Pool.class);
when(mockBeanFactory.getBean(eq("MockPool"), eq(Pool.class))).thenReturn(mockPool);
factoryBean.setBeanFactory(mockBeanFactory);
factoryBean.setPoolName("MockPool");
factoryBean.configure(mockClientRegionFactory);
verify(mockBeanFactory, times(1)).getBean(eq("MockPool"), eq(Pool.class));
verify(mockClientRegionFactory, times(1)).setPoolName(eq("MockPool"));
}
@Test
@SuppressWarnings("unchecked")
public void configurePoolFromClientRegionFactoryBeanEvenWhenRegionAttributesPoolNameIsSet() {
BeanFactory mockBeanFactory = mock(BeanFactory.class);
ClientRegionFactory<Object, Object> mockClientRegionFactory = mock(ClientRegionFactory.class);
Pool mockPool = mock(Pool.class);
RegionAttributes<Object, Object> mockRegionAttributes = mock(RegionAttributes.class);
when(mockBeanFactory.containsBean(eq("TestPool"))).thenReturn(true);
when(mockBeanFactory.isTypeMatch(eq("TestPool"), eq(Pool.class))).thenReturn(true);
when(mockBeanFactory.getBean(anyString(), eq(Pool.class))).thenReturn(mockPool);
when(mockRegionAttributes.getPoolName()).thenReturn("TestPool");
factoryBean.setAttributes(mockRegionAttributes);
factoryBean.setBeanFactory(mockBeanFactory);
factoryBean.setPoolName("MockPool");
factoryBean.configure(mockClientRegionFactory);
verify(mockBeanFactory, times(1)).getBean(eq("MockPool"), eq(Pool.class));
verify(mockBeanFactory, never()).getBean(eq("TestPool"), eq(Pool.class));
verify(mockClientRegionFactory, times(1)).setPoolName(eq("MockPool"));
verify(mockRegionAttributes, times(1)).getPoolName();
}
@Test
@SuppressWarnings("unchecked")
public void configurePoolFromRegionAttributesAndEagerlyInitializePool() {
BeanFactory mockBeanFactory = mock(BeanFactory.class);
ClientRegionFactory<Object, Object> mockClientRegionFactory = mock(ClientRegionFactory.class);
Pool mockPool = mock(Pool.class);
RegionAttributes<Object, Object> mockRegionAttributes = mock(RegionAttributes.class);
when(mockBeanFactory.getBean(eq("TestPool"), eq(Pool.class))).thenReturn(mockPool);
when(mockRegionAttributes.getPoolName()).thenReturn("TestPool");
factoryBean.setAttributes(mockRegionAttributes);
factoryBean.setBeanFactory(mockBeanFactory);
factoryBean.configure(mockClientRegionFactory);
verify(mockBeanFactory, times(1)).containsBean(eq("TestPool"));
verify(mockBeanFactory, times(1)).isTypeMatch(eq("TestPool"), eq(Pool.class));
verify(mockBeanFactory, times(1)).getBean(eq("TestPool"), eq(Pool.class));
verify(mockClientRegionFactory, times(1)).setPoolName(eq("TestPool"));
verify(mockRegionAttributes, times(1)).getPoolName();
}
@Test
@Test(expected = IllegalArgumentException.class)
@SuppressWarnings("unchecked")
public void configurePoolFromRegionAttributesThrowsExceptionWhileEagerlyInitializingPool() {
public void configurePoolThrowsExceptionWhileEagerlyInitializingPool() {
BeanFactory mockBeanFactory = mock(BeanFactory.class);
ClientRegionFactory<Object, Object> mockClientRegionFactory = mock(ClientRegionFactory.class);
RegionAttributes<Object, Object> mockRegionAttributes = mock(RegionAttributes.class);
when(mockBeanFactory.getBean(anyString(), eq(Pool.class))).thenThrow(new BeanCreationException("test"));
when(mockBeanFactory.containsBean(eq("TestPool"))).thenReturn(true);
when(mockBeanFactory.isTypeMatch(eq("TestPool"), eq(Pool.class))).thenReturn(true);
when(mockBeanFactory.getBean(eq("TestPool"), eq(Pool.class)))
.thenThrow(new BeanCreationException("TEST"));
when(mockRegionAttributes.getPoolName()).thenReturn("TestPool");
factoryBean.setAttributes(mockRegionAttributes);
factoryBean.setBeanFactory(mockBeanFactory);
factoryBean.configure(mockClientRegionFactory);
factoryBean.setPoolName("MockPool");
verify(mockBeanFactory, times(1)).containsBean(eq("TestPool"));
verify(mockBeanFactory, times(1)).isTypeMatch(eq("TestPool"), eq(Pool.class));
verify(mockBeanFactory, times(1)).getBean(eq("TestPool"), eq(Pool.class));
verify(mockClientRegionFactory, times(1)).setPoolName(eq("TestPool"));
verify(mockRegionAttributes, times(1)).getPoolName();
try {
factoryBean.configure(mockClientRegionFactory);
}
catch (IllegalArgumentException expected) {
assertThat(expected).hasMessage("[MockPool] is not resolvable as a Pool in the application context");
assertThat(expected).hasNoCause();
throw expected;
}
finally {
verify(mockBeanFactory, times(1)).getBean(eq("MockPool"), eq(Pool.class));
verify(mockClientRegionFactory, never()).setPoolName(eq("MockPool"));
}
}
@Test
@SuppressWarnings("unchecked")
public void configurePoolFromRegionAttributesDoesNotEagerlyInitializePoolWhenNotPoolTypeMatch() {
public void doesNotConfigurePoolWhenClientRegionFactoryBeanPoolIsDefaultPool() {
BeanFactory mockBeanFactory = mock(BeanFactory.class);
ClientRegionFactory<Object, Object> mockClientRegionFactory = mock(ClientRegionFactory.class);
RegionAttributes<Object, Object> mockRegionAttributes = mock(RegionAttributes.class);
when(mockBeanFactory.containsBean(eq("TestPool"))).thenReturn(true);
when(mockBeanFactory.isTypeMatch(eq("TestPool"), eq(Pool.class))).thenReturn(false);
when(mockRegionAttributes.getPoolName()).thenReturn("TestPool");
factoryBean.setAttributes(mockRegionAttributes);
factoryBean.setBeanFactory(mockBeanFactory);
factoryBean.setPoolName(ClientRegionFactoryBean.DEFAULT_POOL_NAME);
factoryBean.configure(mockClientRegionFactory);
verify(mockBeanFactory, times(1)).containsBean(eq("TestPool"));
verify(mockBeanFactory, times(1)).isTypeMatch(eq("TestPool"), eq(Pool.class));
verify(mockBeanFactory, never()).getBean(anyString(), eq(Pool.class));
verify(mockClientRegionFactory, times(1)).setPoolName(eq("TestPool"));
verify(mockRegionAttributes, times(1)).getPoolName();
}
assertThat(factoryBean.getPoolName().orElse(null)).isEqualTo(ClientRegionFactoryBean.DEFAULT_POOL_NAME);
@Test
@SuppressWarnings("unchecked")
public void doesNotConfigurePoolFromRegionAttributesWhenPoolIsUnresolvable() {
BeanFactory mockBeanFactory = mock(BeanFactory.class);
ClientRegionFactory<Object, Object> mockClientRegionFactory = mock(ClientRegionFactory.class);
RegionAttributes<Object, Object> mockRegionAttributes = mock(RegionAttributes.class);
when(mockBeanFactory.containsBean(anyString())).thenReturn(false);
when(mockRegionAttributes.getPoolName()).thenReturn("TestPool");
factoryBean.setAttributes(mockRegionAttributes);
factoryBean.setBeanFactory(mockBeanFactory);
factoryBean.configure(mockClientRegionFactory);
verify(mockBeanFactory, times(1)).containsBean(eq("TestPool"));
verify(mockBeanFactory, never()).isTypeMatch(anyString(), eq(Pool.class));
verify(mockBeanFactory, never()).getBean(anyString(), eq(Pool.class));
verify(mockClientRegionFactory, never()).setPoolName(anyString());
verify(mockRegionAttributes, times(1)).getPoolName();
}
@Test
@SuppressWarnings("unchecked")
public void doesNotConfigurePoolFromRegionAttributesWhenPoolIsDefaultPool() {
public void doesNotConfigurePoolWhenRegionAttributesPoolIsDefaultPool() {
BeanFactory mockBeanFactory = mock(BeanFactory.class);
@@ -392,9 +416,8 @@ public class ClientRegionFactoryBeanTest {
factoryBean.setBeanFactory(mockBeanFactory);
factoryBean.configure(mockClientRegionFactory);
verify(factoryBean, never()).isPoolResolvable(anyString());
verify(mockBeanFactory, never()).containsBean(anyString());
verify(mockBeanFactory, never()).isTypeMatch(anyString(), eq(Pool.class));
assertThat(factoryBean.getPoolName().orElse(null)).isNull();
verify(mockBeanFactory, never()).getBean(anyString(), eq(Pool.class));
verify(mockClientRegionFactory, never()).setPoolName(anyString());
verify(mockRegionAttributes, times(1)).getPoolName();
@@ -402,7 +425,7 @@ public class ClientRegionFactoryBeanTest {
@Test
@SuppressWarnings("unchecked")
public void doesNotConfigurePoolFromRegionAttributesWhenPoolIsEmpty() {
public void doesNotConfigurePoolWhenDeclaredPoolIsEmpty() {
BeanFactory mockBeanFactory = mock(BeanFactory.class);
@@ -414,12 +437,11 @@ public class ClientRegionFactoryBeanTest {
factoryBean.setAttributes(mockRegionAttributes);
factoryBean.setBeanFactory(mockBeanFactory);
factoryBean.setPoolName("");
factoryBean.configure(mockClientRegionFactory);
verify(factoryBean, never()).isNotDefaultPool(anyString());
verify(factoryBean, never()).isPoolResolvable(anyString());
verify(mockBeanFactory, never()).containsBean(anyString());
verify(mockBeanFactory, never()).isTypeMatch(anyString(), eq(Pool.class));
assertThat(factoryBean.getPoolName().orElse(null)).isEqualTo("");
verify(mockBeanFactory, never()).getBean(anyString(), eq(Pool.class));
verify(mockClientRegionFactory, never()).setPoolName(anyString());
verify(mockRegionAttributes, times(1)).getPoolName();
@@ -427,7 +449,7 @@ public class ClientRegionFactoryBeanTest {
@Test
@SuppressWarnings("unchecked")
public void doesNotConfigurePoolFromRegionAttributesWhenPoolIsNull() {
public void doesNotConfigurePoolWhenDeclaredPoolIsNull() {
BeanFactory mockBeanFactory = mock(BeanFactory.class);
@@ -438,190 +460,15 @@ public class ClientRegionFactoryBeanTest {
when(mockRegionAttributes.getPoolName()).thenReturn(null);
factoryBean.setAttributes(mockRegionAttributes);
factoryBean.setBeanFactory(mockBeanFactory);
factoryBean.configure(mockClientRegionFactory);
verify(factoryBean, never()).isNotDefaultPool(anyString());
verify(factoryBean, never()).isPoolResolvable(anyString());
verify(mockBeanFactory, never()).containsBean(anyString());
verify(mockBeanFactory, never()).isTypeMatch(anyString(), eq(Pool.class));
verify(mockBeanFactory, never()).getBean(anyString(), eq(Pool.class));
verify(mockClientRegionFactory, never()).setPoolName(anyString());
verify(mockRegionAttributes, times(1)).getPoolName();
}
@Test
@SuppressWarnings("unchecked")
public void configurePoolFromClientRegionFactoryBeanAndEagerlyInitializesPool() {
BeanFactory mockBeanFactory = mock(BeanFactory.class);
ClientRegionFactory<Object, Object> mockClientRegionFactory = mock(ClientRegionFactory.class);
when(mockBeanFactory.containsBean(eq("MockPool"))).thenReturn(true);
when(mockBeanFactory.isTypeMatch(eq("MockPool"), eq(Pool.class))).thenReturn(true);
factoryBean.setBeanFactory(mockBeanFactory);
factoryBean.setPoolName("MockPool");
factoryBean.configure(mockClientRegionFactory);
verify(mockBeanFactory, times(1)).containsBean(eq("MockPool"));
verify(mockBeanFactory, times(1)).isTypeMatch(eq("MockPool"), eq(Pool.class));
verify(mockBeanFactory, times(1)).getBean(eq("MockPool"), eq(Pool.class));
verify(mockClientRegionFactory, times(1)).setPoolName(eq("MockPool"));
}
@Test
@SuppressWarnings("unchecked")
public void configurePoolFromClientRegionFactoryBeanThrowsExceptionWhileEagerlyInitializingPool() {
BeanFactory mockBeanFactory = mock(BeanFactory.class);
ClientRegionFactory<Object, Object> mockClientRegionFactory = mock(ClientRegionFactory.class);
when(mockBeanFactory.containsBean(eq("MockPool"))).thenReturn(true);
when(mockBeanFactory.isTypeMatch(eq("MockPool"), eq(Pool.class))).thenReturn(true);
when(mockBeanFactory.getBean(eq("MockPool"), eq(Pool.class))).thenThrow(new BeanCreationException("TEST"));
factoryBean.setBeanFactory(mockBeanFactory);
factoryBean.setPoolName("MockPool");
factoryBean.configure(mockClientRegionFactory);
verify(mockBeanFactory, times(1)).containsBean(eq("MockPool"));
verify(mockBeanFactory, times(1)).isTypeMatch(eq("MockPool"), eq(Pool.class));
verify(mockBeanFactory, times(1)).getBean(eq("MockPool"), eq(Pool.class));
verify(mockClientRegionFactory, times(1)).setPoolName(eq("MockPool"));
}
@Test
@SuppressWarnings("unchecked")
public void configurePoolFromClientRegionFactoryBeanDoesNotEagerlyInitializePoolWhenNotPoolTypeMatch() {
BeanFactory mockBeanFactory = mock(BeanFactory.class);
ClientRegionFactory<Object, Object> mockClientRegionFactory = mock(ClientRegionFactory.class);
when(mockBeanFactory.containsBean(eq("MockPool"))).thenReturn(true);
when(mockBeanFactory.isTypeMatch(anyString(), eq(Pool.class))).thenReturn(false);
factoryBean.setBeanFactory(mockBeanFactory);
factoryBean.setPoolName("MockPool");
factoryBean.configure(mockClientRegionFactory);
verify(mockBeanFactory, times(1)).containsBean(eq("MockPool"));
verify(mockBeanFactory, times(1)).isTypeMatch(eq("MockPool"), eq(Pool.class));
verify(mockBeanFactory, never()).getBean(anyString(), eq(Pool.class));
verify(mockClientRegionFactory, times(1)).setPoolName(eq("MockPool"));
}
@Test
@SuppressWarnings("unchecked")
public void configuresPoolFromClientRegionFactoryBeanEvenWhenRegionAttributesPoolNameIsSet() {
BeanFactory mockBeanFactory = mock(BeanFactory.class);
ClientRegionFactory<Object, Object> mockClientRegionFactory = mock(ClientRegionFactory.class);
RegionAttributes<Object, Object> mockRegionAttributes = mock(RegionAttributes.class);
when(mockBeanFactory.containsBean(anyString())).thenReturn(true);
when(mockBeanFactory.isTypeMatch(anyString(), eq(Pool.class))).thenReturn(true);
when(mockRegionAttributes.getPoolName()).thenReturn("TestPool");
factoryBean.setAttributes(mockRegionAttributes);
factoryBean.setBeanFactory(mockBeanFactory);
factoryBean.setPoolName("MockPool");
factoryBean.configure(mockClientRegionFactory);
InOrder inOrderVerifier = inOrder(mockBeanFactory, mockClientRegionFactory);
inOrderVerifier.verify(mockBeanFactory, times(1)).containsBean(eq("TestPool"));
inOrderVerifier.verify(mockBeanFactory, times(1)).isTypeMatch(eq("TestPool"), eq(Pool.class));
inOrderVerifier.verify(mockBeanFactory, times(1)).getBean(eq("TestPool"), eq(Pool.class));
inOrderVerifier.verify(mockClientRegionFactory, times(1)).setPoolName(eq("TestPool"));
inOrderVerifier.verify(mockBeanFactory, times(1)).containsBean(eq("MockPool"));
inOrderVerifier.verify(mockBeanFactory, times(1)).isTypeMatch(eq("MockPool"), eq(Pool.class));
inOrderVerifier.verify(mockBeanFactory, times(1)).getBean(eq("MockPool"), eq(Pool.class));
inOrderVerifier.verify(mockClientRegionFactory, times(1)).setPoolName(eq("MockPool"));
}
@Test
@SuppressWarnings("unchecked")
public void doesNotConfigurePoolFromClientRegionFactoryBeanWhenPoolIsUnresolvable() {
BeanFactory mockBeanFactory = mock(BeanFactory.class);
ClientRegionFactory<Object, Object> mockClientRegionFactory = mock(ClientRegionFactory.class);
when(mockBeanFactory.containsBean(anyString())).thenReturn(false);
factoryBean.setBeanFactory(mockBeanFactory);
factoryBean.setPoolName("MockPool");
factoryBean.configure(mockClientRegionFactory);
verify(mockBeanFactory, times(1)).containsBean(eq("MockPool"));
verify(mockBeanFactory, never()).isTypeMatch(anyString(), eq(Pool.class));
verify(mockBeanFactory, never()).getBean(anyString(), eq(Pool.class));
verify(mockClientRegionFactory, never()).setPoolName(anyString());
}
@Test
@SuppressWarnings("unchecked")
public void doesNotConfigurePoolFromClientRegionFactoryBeanWhenPoolIsDefaultPool() {
BeanFactory mockBeanFactory = mock(BeanFactory.class);
ClientRegionFactory<Object, Object> mockClientRegionFactory = mock(ClientRegionFactory.class);
factoryBean.setBeanFactory(mockBeanFactory);
factoryBean.setPoolName(ClientRegionFactoryBean.DEFAULT_POOL_NAME);
factoryBean.configure(mockClientRegionFactory);
verify(factoryBean, never()).isPoolResolvable(anyString());
verify(mockBeanFactory, never()).containsBean(anyString());
verify(mockBeanFactory, never()).isTypeMatch(anyString(), eq(Pool.class));
verify(mockBeanFactory, never()).getBean(anyString(), eq(Pool.class));
verify(mockClientRegionFactory, never()).setPoolName(anyString());
}
@Test
@SuppressWarnings("unchecked")
public void doesNotConfigurePoolFromClientRegionFactoryBeanWhenPoolIsEmpty() {
BeanFactory mockBeanFactory = mock(BeanFactory.class);
ClientRegionFactory<Object, Object> mockClientRegionFactory = mock(ClientRegionFactory.class);
factoryBean.setBeanFactory(mockBeanFactory);
factoryBean.setPoolName("");
factoryBean.configure(mockClientRegionFactory);
verify(factoryBean, never()).isNotDefaultPool(anyString());
verify(factoryBean, never()).isPoolResolvable(anyString());
verify(mockBeanFactory, never()).containsBean(anyString());
verify(mockBeanFactory, never()).isTypeMatch(anyString(), eq(Pool.class));
verify(mockBeanFactory, never()).getBean(anyString(), eq(Pool.class));
verify(mockClientRegionFactory, never()).setPoolName(anyString());
}
@Test
@SuppressWarnings("unchecked")
public void doesNotConfigurePoolFromClientRegionFactoryBeanWhenPoolIsNull() {
BeanFactory mockBeanFactory = mock(BeanFactory.class);
ClientRegionFactory<Object, Object> mockClientRegionFactory = mock(ClientRegionFactory.class);
factoryBean.setBeanFactory(mockBeanFactory);
factoryBean.setPoolName(null);
factoryBean.configure(mockClientRegionFactory);
verify(factoryBean, never()).isNotDefaultPool(anyString());
verify(factoryBean, never()).isPoolResolvable(anyString());
verify(mockBeanFactory, never()).containsBean(anyString());
verify(mockBeanFactory, never()).isTypeMatch(anyString(), eq(Pool.class));
assertThat(factoryBean.getPoolName().orElse(null)).isNull();
verify(mockBeanFactory, never()).getBean(anyString(), eq(Pool.class));
verify(mockClientRegionFactory, never()).setPoolName(anyString());
verify(mockRegionAttributes, times(1)).getPoolName();
}
@Test
@@ -666,22 +513,6 @@ public class ClientRegionFactoryBeanTest {
assertTrue(factoryBean.isPersistent());
}
@Test
public void isPersistentUnspecifiedIsCorrect() {
assertTrue(factoryBean.isPersistentUnspecified());
factoryBean.setPersistent(true);
assertTrue(factoryBean.isPersistent());
assertFalse(factoryBean.isPersistentUnspecified());
factoryBean.setPersistent(false);
assertTrue(factoryBean.isNotPersistent());
assertFalse(factoryBean.isPersistentUnspecified());
}
@Test
public void isNotPersistentIsCorrect() {

View File

@@ -60,7 +60,7 @@ import org.springframework.data.gemfire.test.support.ThreadUtils;
import org.springframework.data.gemfire.util.DistributedSystemUtils;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.Assert;
import org.springframework.util.SocketUtils;
@@ -82,7 +82,7 @@ import org.springframework.util.SocketUtils;
* @see org.apache.geode.cache.util.CacheListenerAdapter
* @since 1.6.3
*/
@RunWith(SpringJUnit4ClassRunner.class)
@RunWith(SpringRunner.class)
@ContextConfiguration
@SuppressWarnings("all")
public class DurableClientCacheIntegrationTest extends AbstractGemFireClientServerIntegrationTest {
@@ -117,30 +117,30 @@ public class DurableClientCacheIntegrationTest extends AbstractGemFireClientServ
private Region<String, Integer> example;
@BeforeClass
public static void setupGemFireServer() throws IOException {
public static void startGemFireServer() throws IOException {
serverPort = setSystemProperty(CACHE_SERVER_PORT_SYSTEM_PROPERTY, SocketUtils.findAvailableTcpPort());
serverProcess = startGemFireServer(DurableClientCacheIntegrationTest.class);
}
@AfterClass
public static void tearDownGemFireServer() {
serverProcess = stopGemFireServer(serverProcess);
public static void stopGemFireServer() {
stopGemFireServer(serverProcess);
clearSystemProperties(DurableClientCacheIntegrationTest.class);
}
protected static boolean isAfterDirtiesContext() {
private static boolean isAfterDirtiesContext() {
return DIRTIES_CONTEXT.get();
}
protected static boolean isBeforeDirtiesContext() {
private static boolean isBeforeDirtiesContext() {
return !isAfterDirtiesContext();
}
protected boolean dirtiesContext() {
private boolean dirtiesContext() {
return !DIRTIES_CONTEXT.getAndSet(true);
}
protected <T> T valueBeforeAndAfterDirtiesContext(T before, T after) {
private <T> T valueBeforeAndAfterDirtiesContext(T before, T after) {
return (isBeforeDirtiesContext() ? before : after);
}
@@ -161,6 +161,7 @@ public class DurableClientCacheIntegrationTest extends AbstractGemFireClientServ
@After
public void tearDown() {
if (dirtiesContext()) {
closeApplicationContext();
runClientCacheProducer();
@@ -171,6 +172,7 @@ public class DurableClientCacheIntegrationTest extends AbstractGemFireClientServ
}
protected void closeApplicationContext() {
applicationContext.close();
assertThat(applicationContext.isRunning(), is(false));
@@ -178,6 +180,7 @@ public class DurableClientCacheIntegrationTest extends AbstractGemFireClientServ
}
protected void runClientCacheProducer() {
try {
ClientCache gemfireClientCache = new ClientCacheFactory()
.addPoolServer(SERVER_HOST, serverPort)
@@ -197,17 +200,17 @@ public class DurableClientCacheIntegrationTest extends AbstractGemFireClientServ
}
}
protected void setSystemProperties() {
private void setSystemProperties() {
System.setProperty(CLIENT_CACHE_INTERESTS_RESULT_POLICY_SYSTEM_PROPERTY, InterestResultPolicyType.NONE.name());
System.setProperty(DURABLE_CLIENT_TIMEOUT_SYSTEM_PROPERTY, "600");
}
protected void assertRegion(Region<?, ?> region, String expectedName, DataPolicy expectedDataPolicy) {
private void assertRegion(Region<?, ?> region, String expectedName, DataPolicy expectedDataPolicy) {
assertRegion(region, expectedName, String.format("%1$s%2$s", Region.SEPARATOR, expectedName),
expectedDataPolicy);
}
protected void assertRegion(Region<?, ?> region, String expectedName, String expectedPath,
private void assertRegion(Region<?, ?> region, String expectedName, String expectedPath,
DataPolicy expectedDataPolicy) {
assertThat(region, is(notNullValue()));
@@ -217,7 +220,8 @@ public class DurableClientCacheIntegrationTest extends AbstractGemFireClientServ
assertThat(region.getAttributes().getDataPolicy(), is(equalTo(expectedDataPolicy)));
}
protected void assertRegionValues(Region<?, ?> region, Object... values) {
private void assertRegionValues(Region<?, ?> region, Object... values) {
assertThat(region.size(), is(equalTo(values.length)));
for (Object value : values) {
@@ -225,7 +229,7 @@ public class DurableClientCacheIntegrationTest extends AbstractGemFireClientServ
}
}
protected void waitForRegionEntryEvents() {
private void waitForRegionEntryEvents() {
ThreadUtils.timedWait(TimeUnit.SECONDS.toMillis(5), TimeUnit.MILLISECONDS.toMillis(500),
new ThreadUtils.WaitCondition() {
@Override public boolean waiting() {
@@ -238,6 +242,7 @@ public class DurableClientCacheIntegrationTest extends AbstractGemFireClientServ
@Test
@DirtiesContext
public void durableClientGetsInitializedWithDataOnServer() {
assumeTrue(isBeforeDirtiesContext());
assertRegionValues(example, 1, 2, 3);
assertThat(regionCacheListenerEventValues.isEmpty(), is(true));
@@ -245,6 +250,7 @@ public class DurableClientCacheIntegrationTest extends AbstractGemFireClientServ
@Test
public void durableClientGetsUpdatesFromServerWhileClientWasOffline() {
assumeTrue(isAfterDirtiesContext());
assertThat(example.isEmpty(), is(true));
@@ -264,7 +270,9 @@ public class DurableClientCacheIntegrationTest extends AbstractGemFireClientServ
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof Pool && "gemfireServerPool".equals(beanName)) {
Pool gemfireServerPool = (Pool) bean;
if (isBeforeDirtiesContext()) {

View File

@@ -16,18 +16,12 @@
package org.springframework.data.gemfire.client;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.CoreMatchers.sameInstance;
import static org.junit.Assert.assertThat;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;
@@ -39,14 +33,13 @@ import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.data.gemfire.GemfireUtils;
import org.springframework.data.gemfire.fork.ServerProcess;
import org.springframework.data.gemfire.process.ProcessExecutor;
import org.springframework.data.gemfire.process.ProcessWrapper;
import org.springframework.data.gemfire.test.support.ClientServerIntegrationTestsSupport;
import org.springframework.data.gemfire.test.support.FileSystemUtils;
import org.springframework.data.gemfire.test.support.ThreadUtils;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.util.Assert;
import org.springframework.test.context.junit4.SpringRunner;
/**
* The GemFireDataSourceIntegrationTest class is a test suite of test cases testing the contract and functionality
@@ -64,12 +57,57 @@ import org.springframework.util.Assert;
* @see org.apache.geode.cache.client.ClientCache
* @since 1.7.0
*/
@RunWith(SpringJUnit4ClassRunner.class)
@RunWith(SpringRunner.class)
@ContextConfiguration
@SuppressWarnings({ "rawtypes", "unused"})
public class GemFireDataSourceIntegrationTest {
public class GemFireDataSourceIntegrationTest extends ClientServerIntegrationTestsSupport {
private static ProcessWrapper serverProcess;
private static final String GEMFIRE_LOG_LEVEL = "error";
private static ProcessWrapper gemfireServer;
@BeforeClass
public static void startGemFireServer() throws IOException {
int availablePort = findAvailablePort();
String serverName = GemFireDataSourceIntegrationTest.class.getSimpleName().concat("Server");
File serverWorkingDirectory = new File(FileSystemUtils.WORKING_DIRECTORY, serverName.toLowerCase());
List<String> arguments = new ArrayList<>();
arguments.add(String.format("-Dgemfire.name=%s", serverName));
arguments.add(String.format("-Dgemfire.log-level=%s", GEMFIRE_LOG_LEVEL));
arguments.add(String.format("-Dspring.data.gemfire.cache.server.port=%d", availablePort));
arguments.add(GemFireDataSourceIntegrationTest.class.getName()
.replace(".", "/").concat("-server-context.xml"));
gemfireServer = run(serverWorkingDirectory, ServerProcess.class,
arguments.toArray(new String[arguments.size()]));
waitForServerToStart(DEFAULT_HOSTNAME, availablePort);
configureGemFireClient(availablePort);
}
private static void configureGemFireClient(int availablePort) {
System.setProperty("gemfire.log-level", "error");
System.setProperty("spring.data.gemfire.cache.server.port", String.valueOf(availablePort));
}
@AfterClass
public static void stopGemFireServer() {
stop(gemfireServer);
System.clearProperty("gemfire.log-level");
System.clearProperty("spring.data.gemfire.cache.server.port");
if (Boolean.valueOf(System.getProperty("spring.gemfire.fork.clean", Boolean.TRUE.toString()))) {
org.springframework.util.FileSystemUtils.deleteRecursively(gemfireServer.getWorkingDirectory());
}
}
@Autowired
private ApplicationContext applicationContext;
@@ -86,64 +124,23 @@ public class GemFireDataSourceIntegrationTest {
@Resource(name = "ServerOnlyRegion")
private Region serverOnlyRegion;
@BeforeClass
public static void setupBeforeClass() throws IOException {
System.setProperty("gemfire.log-level", "warning");
@SuppressWarnings("unchecked")
private void assertRegion(Region actualRegion, String expectedRegionName) {
String serverName = "GemFireDataSourceSpringBasedServer";
File serverWorkingDirectory = new File(FileSystemUtils.WORKING_DIRECTORY, serverName.toLowerCase());
Assert.isTrue(serverWorkingDirectory.isDirectory() || serverWorkingDirectory.mkdirs());
List<String> arguments = new ArrayList<String>();
arguments.add(String.format("-Dgemfire.name=%1$s", serverName));
arguments.add(GemFireDataSourceIntegrationTest.class.getName().replace(".", "/").concat("-server-context.xml"));
serverProcess = ProcessExecutor.launch(serverWorkingDirectory, ServerProcess.class,
arguments.toArray(new String[arguments.size()]));
waitForProcessStart(TimeUnit.SECONDS.toMillis(20), serverProcess, ServerProcess.getServerProcessControlFilename());
System.out.println("Spring configured/bootstrapped GemFire Cache Server Process for ClientCache DataSource Test should be running...");
}
private static void waitForProcessStart(final long milliseconds, final ProcessWrapper process, final String processControlFilename) {
ThreadUtils.timedWait(milliseconds, TimeUnit.MILLISECONDS.toMillis(500), new ThreadUtils.WaitCondition() {
private File processControlFile = new File(process.getWorkingDirectory(), processControlFilename);
@Override public boolean waiting() {
return !processControlFile.isFile();
}
});
}
@AfterClass
public static void tearDown() {
serverProcess.shutdown();
if (Boolean.valueOf(System.getProperty("spring.gemfire.fork.clean", Boolean.TRUE.toString()))) {
org.springframework.util.FileSystemUtils.deleteRecursively(serverProcess.getWorkingDirectory());
}
}
protected void assertRegion(Region actualRegion, String expectedRegionName) {
assertThat(actualRegion, is(not(nullValue())));
assertThat(actualRegion.getName(), is(equalTo(expectedRegionName)));
assertThat(actualRegion.getFullPath(), is(equalTo(String.format("%1$s%2$s",
Region.SEPARATOR, expectedRegionName))));
assertThat(gemfireClientCache.getRegion(actualRegion.getFullPath()), is(sameInstance(actualRegion)));
assertThat(applicationContext.containsBean(expectedRegionName), is(true));
assertThat(applicationContext.getBean(expectedRegionName, Region.class), is(sameInstance(actualRegion)));
assertThat(actualRegion).isNotNull();
assertThat(actualRegion.getName()).isEqualTo(expectedRegionName);
assertThat(actualRegion.getFullPath()).isEqualTo(GemfireUtils.toRegionPath(expectedRegionName));
assertThat(gemfireClientCache.getRegion(actualRegion.getFullPath())).isSameAs(actualRegion);
assertThat(applicationContext.containsBean(expectedRegionName)).isTrue();
assertThat(applicationContext.getBean(expectedRegionName, Region.class)).isSameAs(actualRegion);
}
@Test
@SuppressWarnings("unchecked")
public void clientProxyRegionBeansExist() {
assertRegion(clientOnlyRegion, "ClientOnlyRegion");
assertRegion(clientServerRegion, "ClientServerRegion");
assertRegion(serverOnlyRegion, "ServerOnlyRegion");
}
}

View File

@@ -28,6 +28,7 @@ import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.data.gemfire.GemfireUtils;
import org.springframework.data.gemfire.fork.ServerProcess;
import org.springframework.data.gemfire.process.ProcessWrapper;
import org.springframework.data.gemfire.repository.sample.Person;
@@ -44,6 +45,7 @@ import org.springframework.test.context.junit4.SpringRunner;
*/
@RunWith(SpringRunner.class)
@ContextConfiguration
// TODO: merge with o.s.d.g.client.GemfireDataSoruceIntegrationTest
public class GemFireDataSourceIntegrationTests extends ClientServerIntegrationTestsSupport {
private static ProcessWrapper gemfireServer;
@@ -53,6 +55,7 @@ public class GemFireDataSourceIntegrationTests extends ClientServerIntegrationTe
@BeforeClass
public static void startGemFireServer() throws Exception {
int availablePort = findAvailablePort();
gemfireServer = run(ServerProcess.class,
@@ -70,11 +73,12 @@ public class GemFireDataSourceIntegrationTests extends ClientServerIntegrationTe
stop(gemfireServer);
}
protected void assertRegion(Region<?, ?> region, String name, DataPolicy dataPolicy) {
assertRegion(region, name, String.format("%1$s%2$s", Region.SEPARATOR, "simple"), dataPolicy);
private void assertRegion(Region<?, ?> region, String name, DataPolicy dataPolicy) {
assertRegion(region, name, GemfireUtils.toRegionPath("simple"), dataPolicy);
}
protected void assertRegion(Region<?, ?> region, String name, String fullPath, DataPolicy dataPolicy) {
private void assertRegion(Region<?, ?> region, String name, String fullPath, DataPolicy dataPolicy) {
assertThat(region).isNotNull();
assertThat(region.getName()).isEqualTo(name);
assertThat(region.getFullPath()).isEqualTo(fullPath);
@@ -84,33 +88,36 @@ public class GemFireDataSourceIntegrationTests extends ClientServerIntegrationTe
@Test
public void gemfireServerDataSourceCreated() {
Pool pool = applicationContext.getBean("gemfirePool", Pool.class);
Pool pool = this.applicationContext.getBean("gemfirePool", Pool.class);
assertThat(pool).isNotNull();
assertThat(pool.getSubscriptionEnabled()).isTrue();
List<String> regionList = Arrays.asList(applicationContext.getBeanNamesForType(Region.class));
List<String> regionList = Arrays.asList(this.applicationContext.getBeanNamesForType(Region.class));
assertThat(regionList).hasSize(3);
assertThat(regionList.contains("r1")).isTrue();
assertThat(regionList.contains("r2")).isTrue();
assertThat(regionList.contains("simple")).isTrue();
Region<?, ?> simple = applicationContext.getBean("simple", Region.class);
Region<?, ?> simple = this.applicationContext.getBean("simple", Region.class);
assertRegion(simple, "simple", DataPolicy.EMPTY);
}
@Test
public void repositoryCreatedAndFunctional() {
Person daveMathews = new Person(1L, "Dave", "Mathews");
PersonRepository repository = applicationContext.getBean(PersonRepository.class);
PersonRepository repository = this.applicationContext.getBean(PersonRepository.class);
assertThat(repository.save(daveMathews)).isSameAs(daveMathews);
Optional<Person> result = repository.findById(1L);
assertThat(result.isPresent()).isTrue();
assertThat(result.get().getFirstname()).isEqualTo("Dave");
assertThat(result.map(Person::getFirstname).orElse(null)).isEqualTo("Dave");
}
}

View File

@@ -16,13 +16,6 @@
package org.springframework.data.gemfire.client;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.CoreMatchers.sameInstance;
import static org.junit.Assert.assertThat;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
@@ -35,6 +28,7 @@ import javax.annotation.Resource;
import org.apache.geode.cache.Region;
import org.apache.geode.cache.client.ClientCache;
import org.apache.geode.distributed.ServerLauncher;
import org.assertj.core.api.Assertions;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
@@ -42,6 +36,7 @@ import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.gemfire.GemfireUtils;
import org.springframework.data.gemfire.fork.GemFireBasedServerProcess;
import org.springframework.data.gemfire.process.ProcessExecutor;
import org.springframework.data.gemfire.process.ProcessWrapper;
@@ -67,9 +62,12 @@ import org.springframework.util.StringUtils;
@RunWith(SpringRunner.class)
@ContextConfiguration
@SuppressWarnings({ "rawtypes", "unused"})
// TODO: slow test!
public class GemFireDataSourceUsingNonSpringConfiguredGemFireServerIntegrationTest {
private static ProcessWrapper serverProcess;
private static final String GEMFIRE_LOG_LEVEL = "error";
private static ProcessWrapper gemfireServer;
@Autowired
private ApplicationContext applicationContext;
@@ -87,9 +85,9 @@ public class GemFireDataSourceUsingNonSpringConfiguredGemFireServerIntegrationTe
private Region anotherServerRegion;
@BeforeClass
public static void setupBeforeClass() throws IOException {
public static void startGemFireServer() throws IOException {
System.setProperty("gemfire.log-level", "error");
System.setProperty("gemfire.log-level", GEMFIRE_LOG_LEVEL);
String serverName = "GemFireDataSourceGemFireBasedServer";
@@ -102,20 +100,16 @@ public class GemFireDataSourceUsingNonSpringConfiguredGemFireServerIntegrationTe
Assert.isTrue(new File(serverWorkingDirectory, "cache.xml").isFile(), String.format(
"Expected a cache.xml file to exist in directory (%1$s)!", serverWorkingDirectory));
List<String> arguments = new ArrayList<String>(5);
List<String> arguments = new ArrayList<>(5);
arguments.add(ServerLauncher.Command.START.getName());
arguments.add(String.format("-Dgemfire.name=%1$s", serverName));
arguments.add(String.format("-Dgemfire.mcast-port=%1$s", "0"));
arguments.add(String.format("-Dgemfire.log-level=%1$s", "warning"));
//arguments.add(String.format("-Dgemfire.cache-xml-file=%1$s", "gemfire-datasource-integration-test-cache.xml"));
arguments.add(String.format("-Dgemfire.log-level=%1$s", "error"));
serverProcess = ProcessExecutor.launch(serverWorkingDirectory, customClasspath(), ServerLauncher.class,
gemfireServer = ProcessExecutor.launch(serverWorkingDirectory, customClasspath(), ServerLauncher.class,
arguments.toArray(new String[arguments.size()]));
waitForProcessStart(TimeUnit.SECONDS.toMillis(20), serverProcess, GemFireBasedServerProcess.getServerProcessControlFilename());
System.out.println("GemFire-based Cache Server Process for ClientCache DataSource Test should be running and connected...");
waitForProcessStart(TimeUnit.SECONDS.toMillis(20), gemfireServer, GemFireBasedServerProcess.getServerProcessControlFilename());
}
private static void writeAsCacheXmlFileToDirectory(String classpathResource, File serverWorkingDirectory) throws IOException {
@@ -150,24 +144,24 @@ public class GemFireDataSourceUsingNonSpringConfiguredGemFireServerIntegrationTe
}
@AfterClass
public static void tearDown() {
public static void stopGemFireServer() {
serverProcess.shutdown();
gemfireServer.shutdown();
if (Boolean.valueOf(System.getProperty("spring.gemfire.fork.clean", Boolean.TRUE.toString()))) {
org.springframework.util.FileSystemUtils.deleteRecursively(serverProcess.getWorkingDirectory());
org.springframework.util.FileSystemUtils.deleteRecursively(gemfireServer.getWorkingDirectory());
}
}
protected void assertRegion(Region actualRegion, String expectedRegionName) {
@SuppressWarnings("unchecked")
private void assertRegion(Region actualRegion, String expectedRegionName) {
assertThat(actualRegion, is(not(nullValue())));
assertThat(actualRegion.getName(), is(equalTo(expectedRegionName)));
assertThat(actualRegion.getFullPath(), is(equalTo(String.format("%1$s%2$s",
Region.SEPARATOR, expectedRegionName))));
assertThat(gemfireClientCache.getRegion(actualRegion.getFullPath()), is(sameInstance(actualRegion)));
assertThat(applicationContext.containsBean(expectedRegionName), is(true));
assertThat(applicationContext.getBean(expectedRegionName, Region.class), is(sameInstance(actualRegion)));
Assertions.assertThat(actualRegion).isNotNull();
Assertions.assertThat(actualRegion.getName()).isEqualTo(expectedRegionName);
Assertions.assertThat(actualRegion.getFullPath()).isEqualTo(GemfireUtils.toRegionPath(expectedRegionName));
Assertions.assertThat(gemfireClientCache.getRegion(actualRegion.getFullPath())).isSameAs(actualRegion);
Assertions.assertThat(applicationContext.containsBean(expectedRegionName)).isTrue();
Assertions.assertThat(applicationContext.getBean(expectedRegionName, Region.class)).isSameAs(actualRegion);
}
@Test

View File

@@ -16,19 +16,31 @@
package org.springframework.data.gemfire.client;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.mockito.ArgumentMatchers.*;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.CoreMatchers.sameInstance;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.same;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import org.apache.geode.cache.DataPolicy;
import org.apache.geode.cache.Region;
@@ -43,45 +55,52 @@ import org.apache.geode.management.internal.cli.functions.GetRegionsFunction;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.junit.MockitoJUnitRunner;
import org.mockito.stubbing.Answer;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.data.gemfire.client.function.ListRegionsOnServerFunction;
import org.springframework.data.gemfire.util.RegionUtils;
/**
* The GemfireDataSourcePostProcessor class is a test suite of test cases testing the contract and functionality
* of the GemfireDataSourcePostProcessor class, which is responsible for creating client PROXY Regions
* for all data Regions on servers in a GemFire cluster, providing the ListRegion
* Unit tests for {@link GemfireDataSourcePostProcessor}.
*
* @author John Blum
* @see org.junit.Test
* @see org.mockito.Mockito
* @see org.springframework.beans.factory.config.ConfigurableListableBeanFactory
* @see org.springframework.data.gemfire.client.GemfireDataSourcePostProcessor
* @see org.apache.geode.cache.Region
* @see org.apache.geode.cache.client.ClientCache
* @see org.apache.geode.cache.client.ClientRegionFactory
* @see org.springframework.beans.factory.config.ConfigurableListableBeanFactory
* @see org.springframework.data.gemfire.client.GemfireDataSourcePostProcessor
* @see org.springframework.data.gemfire.client.function.ListRegionsOnServerFunction
* @since 1.7.0
*/
@RunWith(MockitoJUnitRunner.class)
public class GemfireDataSourcePostProcessorTest {
@Rule
public ExpectedException expectedException = ExpectedException.none();
@Mock
private ClientCache mockClientCache;
protected RegionInformation newRegionInformation(Region<?, ?> region) {
@Rule
public ExpectedException exception = ExpectedException.none();
private RegionInformation newRegionInformation(Region<?, ?> region) {
return new RegionInformation(region, false);
}
@SuppressWarnings("unchecked")
protected Region<Object, Object> mockRegion(String name) {
private Region<Object, Object> mockRegion(String name) {
Region<Object, Object> mockRegion = mock(Region.class, name);
RegionAttributes<Object, Object> mockRegionAttributes = mock(RegionAttributes.class,
String.format("%1$s-RegionAttributes", name));
RegionAttributes<Object, Object> mockRegionAttributes =
mock(RegionAttributes.class, String.format("%1$s-RegionAttributes", name));
when(mockRegion.getFullPath()).thenReturn(String.format("%1$s%2$s", Region.SEPARATOR, name));
when(mockRegion.getName()).thenReturn(name);
when(mockRegion.getParentRegion()).thenReturn(null);
when(mockRegion.getFullPath()).thenReturn(RegionUtils.toRegionPath(name));
when(mockRegion.getAttributes()).thenReturn(mockRegionAttributes);
when(mockRegionAttributes.getDataPolicy()).thenReturn(DataPolicy.PARTITION);
when(mockRegionAttributes.getScope()).thenReturn(Scope.DISTRIBUTED_ACK);
@@ -89,26 +108,20 @@ public class GemfireDataSourcePostProcessorTest {
return mockRegion;
}
protected <T> List<T> asList(Iterable<T> iterable) {
List<T> list = new ArrayList<T>();
if (iterable != null) {
for (T element : iterable) {
list.add(element);
}
}
return list;
}
@Test
public void postProcessBeanFactoryCallsCreateClientRegionProxiesWithRegionNames() {
final AtomicBoolean createClientRegionProxiesCalled = new AtomicBoolean(false);
final ConfigurableListableBeanFactory mockBeanFactory = mock(ConfigurableListableBeanFactory.class, "MockSpringBeanFactory");
final List<String> testRegionNames = Collections.singletonList("Test");
GemfireDataSourcePostProcessor postProcessor = new GemfireDataSourcePostProcessor(null) {
@Override Iterable<String> regionNames() {
AtomicBoolean createClientRegionProxiesCalled = new AtomicBoolean(false);
ConfigurableListableBeanFactory mockBeanFactory =
mock(ConfigurableListableBeanFactory.class, "MockSpringBeanFactory");
List<String> testRegionNames = Collections.singletonList("Test");
GemfireDataSourcePostProcessor postProcessor = new GemfireDataSourcePostProcessor(this.mockClientCache) {
@Override
Iterable<String> regionNames() {
return testRegionNames;
}
@@ -126,10 +139,13 @@ public class GemfireDataSourcePostProcessorTest {
@Test
public void regionNamesWithListRegionsOnServerFunction() {
final List<String> expectedRegionNames = Arrays.asList("ExampleOne", "ExampleTwo");
GemfireDataSourcePostProcessor postProcessor = new GemfireDataSourcePostProcessor(null) {
@Override @SuppressWarnings("unchecked") <T> T execute(Function gemfireFunction, Object... arguments) {
List<String> expectedRegionNames = Arrays.asList("ExampleOne", "ExampleTwo");
GemfireDataSourcePostProcessor postProcessor = new GemfireDataSourcePostProcessor(this.mockClientCache) {
@Override @SuppressWarnings("unchecked")
<T> T execute(Function gemfireFunction, Object... arguments) {
assertThat(gemfireFunction, is(instanceOf(ListRegionsOnServerFunction.class)));
return (T) expectedRegionNames;
}
@@ -141,11 +157,16 @@ public class GemfireDataSourcePostProcessorTest {
}
@Test
@SuppressWarnings("unchecked")
public void regionNamesWithGetRegionsFunction() {
final List<String> expectedRegionNames = Arrays.asList("ExampleOne", "ExampleTwo");
GemfireDataSourcePostProcessor postProcessor = new GemfireDataSourcePostProcessor(null) {
@Override @SuppressWarnings("unchecked") <T> T execute(Function gemfireFunction, Object... arguments) {
List<String> expectedRegionNames = Arrays.asList("ExampleOne", "ExampleTwo");
GemfireDataSourcePostProcessor postProcessor = new GemfireDataSourcePostProcessor(this.mockClientCache) {
@Override @SuppressWarnings("unchecked")
<T> T execute(Function gemfireFunction, Object... arguments) {
if (gemfireFunction instanceof ListRegionsOnServerFunction) {
throw new RuntimeException("fail");
}
@@ -154,20 +175,25 @@ public class GemfireDataSourcePostProcessorTest {
newRegionInformation(mockRegion(expectedRegionNames.get(1)))).toArray();
}
throw new IllegalArgumentException(String.format("GemFire Function (%1$s) with ID (%2$s) not registered",
throw new IllegalArgumentException(String.format("GemFire Function [%1$s] with ID [%2$s] not registered",
gemfireFunction.getClass().getName(), gemfireFunction.getId()));
}
};
Iterable<String> actualRegionNames = postProcessor.regionNames();
List<String> actualRegionNames =
StreamSupport.stream(postProcessor.regionNames().spliterator(), false).collect(Collectors.toList());
assertThat(asList(actualRegionNames).containsAll(expectedRegionNames), is(true));
assertThat(actualRegionNames.containsAll(expectedRegionNames), is(true));
}
@Test
public void regionNamesWithGetRegionsFunctionReturningNoResults() {
GemfireDataSourcePostProcessor postProcessor = new GemfireDataSourcePostProcessor(null) {
@Override @SuppressWarnings("unchecked") <T> T execute(Function gemfireFunction, Object... arguments) {
GemfireDataSourcePostProcessor postProcessor = new GemfireDataSourcePostProcessor(this.mockClientCache) {
@Override @SuppressWarnings("unchecked") <T> T
execute(Function gemfireFunction, Object... arguments) {
if (gemfireFunction instanceof ListRegionsOnServerFunction) {
throw new RuntimeException("fail");
}
@@ -189,15 +215,19 @@ public class GemfireDataSourcePostProcessorTest {
@Test
public void regionNamesWithGetRegionsFunctionThrowingException() {
final AtomicBoolean logMethodCalled = new AtomicBoolean(false);
GemfireDataSourcePostProcessor postProcessor = new GemfireDataSourcePostProcessor(null) {
@Override @SuppressWarnings("unchecked") <T> T execute(Function gemfireFunction, Object... arguments) {
AtomicBoolean logMethodCalled = new AtomicBoolean(false);
GemfireDataSourcePostProcessor postProcessor = new GemfireDataSourcePostProcessor(this.mockClientCache) {
@Override @SuppressWarnings("unchecked") <T> T
execute(Function gemfireFunction, Object... arguments) {
throw new IllegalArgumentException(String.format("GemFire Function (%1$s) with ID (%2$s) not registered",
gemfireFunction.getClass().getName(), gemfireFunction.getId()));
}
@Override void log(final String message, final Object... arguments) {
@Override
void log(final String message, final Object... arguments) {
assertThat(message.startsWith("Failed to determine the Regions available on the Server:"), is(true));
logMethodCalled.compareAndSet(false, true);
}
@@ -213,35 +243,40 @@ public class GemfireDataSourcePostProcessorTest {
@Test
public void containsRegionInformationIsTrue() {
assertThat(new GemfireDataSourcePostProcessor(null).containsRegionInformation(
new Object[] { newRegionInformation(mockRegion("Example")) }), is(true));
assertThat(new GemfireDataSourcePostProcessor(this.mockClientCache)
.containsRegionInformation(new Object[] { newRegionInformation(mockRegion("Example")) }),
is(true));
}
@Test
public void containsRegionInformationWithListOfRegionInformationIsFalse() {
assertThat(new GemfireDataSourcePostProcessor(null).containsRegionInformation(
Arrays.asList(newRegionInformation(mockRegion("Example")))), is(false));
assertThat(new GemfireDataSourcePostProcessor(this.mockClientCache)
.containsRegionInformation(Collections.singletonList(newRegionInformation(mockRegion("Example")))),
is(false));
}
@Test
public void containsRegionInformationWithNonEmptyArrayContainingNonRegionInformationIsFalse() {
assertThat(new GemfireDataSourcePostProcessor(null).containsRegionInformation(new Object[] { "test" }),
is(false));
assertThat(new GemfireDataSourcePostProcessor(this.mockClientCache)
.containsRegionInformation(new Object[] { "test" }), is(false));
}
@Test
public void containsRegionInformationWithEmptyArrayIsFalse() {
assertThat(new GemfireDataSourcePostProcessor(null).containsRegionInformation(new Object[0]), is(false));
assertThat(new GemfireDataSourcePostProcessor(this.mockClientCache)
.containsRegionInformation(new Object[0]), is(false));
}
@Test
public void containsRegionInformationWithNullIsFalse() {
assertThat(new GemfireDataSourcePostProcessor(null).containsRegionInformation(null), is(false));
assertThat(new GemfireDataSourcePostProcessor(this.mockClientCache).containsRegionInformation(null),
is(false));
}
@Test
@SuppressWarnings("unchecked")
public void createClientRegionProxies() {
ClientCache mockClientCache = mock(ClientCache.class, "MockGemFireClientCache");
ClientRegionFactory mockClientRegionFactory = mock(ClientRegionFactory.class, "MockGemFireClientRegionFactory");
@@ -283,6 +318,7 @@ public class GemfireDataSourcePostProcessorTest {
@Test
@SuppressWarnings("unchecked")
public void createClientRegionProxiesWhenRegionBeanExists() {
ClientCache mockClientCache = mock(ClientCache.class, "MockGemFireClientCache");
ClientRegionFactory mockClientRegionFactory = mock(ClientRegionFactory.class, "MockGemFireClientRegionFactory");
@@ -299,43 +335,10 @@ public class GemfireDataSourcePostProcessorTest {
GemfireDataSourcePostProcessor postProcessor = new GemfireDataSourcePostProcessor(mockClientCache);
postProcessor.createClientRegionProxies(mockBeanFactory, Arrays.asList("Example"));
postProcessor.createClientRegionProxies(mockBeanFactory, Collections.singletonList("Example"));
verify(mockClientCache, times(1)).createClientRegionFactory(eq(ClientRegionShortcut.PROXY));
verify(mockClientRegionFactory, never()).create(any(String.class));
verify(mockBeanFactory, never()).registerSingleton(any(String.class), any(Region.class));
}
@Test
@SuppressWarnings("unchecked")
public void createClientRegionProxiesWhenBeanOfDifferentTypeWithSameNameAsRegionIsRegistered() {
ClientCache mockClientCache = mock(ClientCache.class, "MockGemFireClientCache");
ClientRegionFactory mockClientRegionFactory = mock(ClientRegionFactory.class, "MockGemFireClientRegionFactory");
when(mockClientCache.createClientRegionFactory(eq(ClientRegionShortcut.PROXY))).thenReturn(
mockClientRegionFactory);
ConfigurableListableBeanFactory mockBeanFactory = mock(ConfigurableListableBeanFactory.class, "MockSpringBeanFactory");
when(mockBeanFactory.containsBean(any(String.class))).thenReturn(true);
when(mockBeanFactory.getBean(any(String.class))).thenReturn(new Object());
GemfireDataSourcePostProcessor postProcessor = new GemfireDataSourcePostProcessor(mockClientCache);
try {
expectedException.expect(IllegalArgumentException.class);
expectedException.expectCause(is(nullValue(Throwable.class)));
expectedException.expectMessage(is(equalTo(String.format(
"Cannot create a client PROXY Region bean named '%1$s'. A bean with this name of type '%2$s' already exists.",
"Example", Object.class.getName()))));
postProcessor.createClientRegionProxies(mockBeanFactory, Arrays.asList("Example"));
}
finally {
verify(mockClientCache, times(1)).createClientRegionFactory(eq(ClientRegionShortcut.PROXY));
verify(mockClientRegionFactory, never()).create(any(String.class));
verify(mockBeanFactory, never()).registerSingleton(any(String.class), any(Region.class));
}
}
}

View File

@@ -68,11 +68,11 @@ public class PoolFactoryBeanTest {
@Rule
public ExpectedException exception = ExpectedException.none();
protected ConnectionEndpoint newConnectionEndpoint(String host, int port) {
private ConnectionEndpoint newConnectionEndpoint(String host, int port) {
return new ConnectionEndpoint(host, port);
}
protected InetSocketAddress newSocketAddress(String host, int port) {
private InetSocketAddress newSocketAddress(String host, int port) {
return new InetSocketAddress(host, port);
}
@@ -89,10 +89,14 @@ public class PoolFactoryBeanTest {
when(mockPoolFactory.create(eq("GemFirePool"))).thenReturn(mockPool);
PoolFactoryBean poolFactoryBean = new PoolFactoryBean() {
@Override protected PoolFactory createPoolFactory() {
@Override
protected PoolFactory createPoolFactory() {
return mockPoolFactory;
}
@Override boolean isDistributedSystemPresent() {
@Override
boolean isClientCachePresent() {
return false;
}
};
@@ -229,7 +233,7 @@ public class PoolFactoryBeanTest {
PoolFactoryBean poolFactoryBean = new PoolFactoryBean();
ReflectionUtils.setField(PoolFactoryBean.class.getDeclaredField("springBasedPool"), poolFactoryBean, false);
ReflectionUtils.setField(PoolFactoryBean.class.getDeclaredField("springManagedPool"), poolFactoryBean, false);
poolFactoryBean.setPool(mockPool);
poolFactoryBean.destroy();
@@ -287,7 +291,7 @@ public class PoolFactoryBeanTest {
assertThat(poolFactoryBean.getLocators().size(), is(equalTo(1)));
assertThat(poolFactoryBean.getLocators().findOne("localhost"), is(equalTo(localhost)));
poolFactoryBean.setLocators(Collections.<ConnectionEndpoint>emptyList());
poolFactoryBean.setLocators(Collections.emptyList());
assertThat(poolFactoryBean.getLocators(), is(notNullValue()));
assertThat(poolFactoryBean.getLocators().isEmpty(), is(true));
@@ -323,7 +327,7 @@ public class PoolFactoryBeanTest {
assertThat(poolFactoryBean.getServers().size(), is(equalTo(1)));
assertThat(poolFactoryBean.getServers().findOne("localhost"), is(equalTo(localhost)));
poolFactoryBean.setServers(Collections.<ConnectionEndpoint>emptyList());
poolFactoryBean.setServers(Collections.emptyList());
assertThat(poolFactoryBean.getServers(), is(notNullValue()));
assertThat(poolFactoryBean.getServers().isEmpty(), is(true));
@@ -444,7 +448,7 @@ public class PoolFactoryBeanTest {
exception.expect(IllegalStateException.class);
exception.expectCause(is(nullValue(Throwable.class)));
exception.expectMessage("The Pool has not been initialized");
exception.expectMessage("Pool [null] has not been initialized");
new PoolFactoryBean().getPool().getPendingEventCount();
}
@@ -476,7 +480,7 @@ public class PoolFactoryBeanTest {
exception.expect(IllegalStateException.class);
exception.expectCause(is(nullValue(Throwable.class)));
exception.expectMessage("The Pool has not been initialized");
exception.expectMessage("Pool [null] has not been initialized");
new PoolFactoryBean().getPool().getQueryService();
}
@@ -511,7 +515,9 @@ public class PoolFactoryBeanTest {
AtomicBoolean destroyCalled = new AtomicBoolean(false);
PoolFactoryBean poolFactoryBean = new PoolFactoryBean() {
@Override public void destroy() throws Exception {
@Override
public void destroy() throws Exception {
destroyCalled.set(true);
throw new IllegalStateException("test");
}
@@ -559,7 +565,7 @@ public class PoolFactoryBeanTest {
exception.expect(IllegalStateException.class);
exception.expectCause(is(nullValue(Throwable.class)));
exception.expectMessage("The Pool has not been initialized");
exception.expectMessage("Pool [null] has not been initialized");
pool.releaseThreadLocalConnection();
}

View File

@@ -237,7 +237,7 @@ public class SpELExpressionConfiguredPoolsIntegrationTests {
}
@Override
boolean isDistributedSystemPresent() {
boolean isClientCachePresent() {
return true;
}
}

View File

@@ -32,6 +32,7 @@ import static org.mockito.Mockito.when;
import java.net.InetSocketAddress;
import java.util.Collections;
import java.util.List;
import java.util.function.Supplier;
import org.apache.geode.cache.client.Pool;
import org.apache.geode.cache.query.QueryService;
@@ -72,7 +73,7 @@ public class DefaultableDelegatingPoolAdapterTest {
private QueryService mockQueryService;
@Mock
private DefaultableDelegatingPoolAdapter.ValueProvider mockValueProvider;
private Supplier mockSupplier;
private static InetSocketAddress newSocketAddress(String host, int port) {
return new InetSocketAddress(host, port);
@@ -125,7 +126,7 @@ public class DefaultableDelegatingPoolAdapterTest {
exception.expect(IllegalArgumentException.class);
exception.expectCause(is(nullValue(Throwable.class)));
exception.expectMessage("'delegate' must not be null");
exception.expectMessage("Pool delegate must not be null");
DefaultableDelegatingPoolAdapter.from(null);
}
@@ -154,10 +155,10 @@ public class DefaultableDelegatingPoolAdapterTest {
this.poolAdapter = this.poolAdapter.preferDefault();
assertThat(this.poolAdapter.prefersDefault(), is(true));
assertThat(this.poolAdapter.defaultIfNull("default", this.mockValueProvider),
assertThat(this.poolAdapter.defaultIfNull("default", this.mockSupplier),
is(equalTo("default")));
verifyZeroInteractions(this.mockValueProvider);
verifyZeroInteractions(this.mockSupplier);
}
@Test
@@ -166,13 +167,13 @@ public class DefaultableDelegatingPoolAdapterTest {
this.poolAdapter = this.poolAdapter.preferDefault();
when(this.mockValueProvider.getValue()).thenReturn("pool");
when(this.mockSupplier.get()).thenReturn("pool");
assertThat(this.poolAdapter.prefersDefault(), is(true));
assertThat(this.poolAdapter.defaultIfNull(null, this.mockValueProvider),
assertThat(this.poolAdapter.defaultIfNull(null, this.mockSupplier),
is(equalTo("pool")));
verify(this.mockValueProvider, times(1)).getValue();
verify(this.mockSupplier, times(1)).get();
}
@Test
@@ -181,13 +182,13 @@ public class DefaultableDelegatingPoolAdapterTest {
this.poolAdapter = this.poolAdapter.preferPool();
when(mockValueProvider.getValue()).thenReturn("pool");
when(mockSupplier.get()).thenReturn("pool");
assertThat(this.poolAdapter.prefersPool(), is(true));
assertThat(this.poolAdapter.defaultIfNull("default", this.mockValueProvider),
assertThat(this.poolAdapter.defaultIfNull("default", this.mockSupplier),
is(equalTo("pool")));
verify(this.mockValueProvider, times(1)).getValue();
verify(this.mockSupplier, times(1)).get();
}
@Test
@@ -196,13 +197,13 @@ public class DefaultableDelegatingPoolAdapterTest {
this.poolAdapter = this.poolAdapter.preferPool();
when(this.mockValueProvider.getValue()).thenReturn(null);
when(this.mockSupplier.get()).thenReturn(null);
assertThat(this.poolAdapter.prefersPool(), is(true));
assertThat(this.poolAdapter.defaultIfNull("default", this.mockValueProvider),
assertThat(this.poolAdapter.defaultIfNull("default", this.mockSupplier),
is(equalTo("default")));
verify(this.mockValueProvider, times(1)).getValue();
verify(this.mockSupplier, times(1)).get();
}
@Test
@@ -214,9 +215,9 @@ public class DefaultableDelegatingPoolAdapterTest {
List<Object> defaultList = Collections.singletonList("default");
assertThat(this.poolAdapter.prefersDefault(), is(true));
assertThat((List<Object>) this.poolAdapter.defaultIfEmpty(defaultList, this.mockValueProvider), is(equalTo(defaultList)));
assertThat((List<Object>) this.poolAdapter.defaultIfEmpty(defaultList, this.mockSupplier), is(equalTo(defaultList)));
verifyZeroInteractions(this.mockValueProvider);
verifyZeroInteractions(this.mockSupplier);
}
@Test
@@ -227,12 +228,12 @@ public class DefaultableDelegatingPoolAdapterTest {
List<Object> poolList = Collections.singletonList("pool");
when(this.mockValueProvider.getValue()).thenReturn(poolList);
when(this.mockSupplier.get()).thenReturn(poolList);
assertThat(this.poolAdapter.prefersDefault(), is(true));
assertThat((List<Object>) this.poolAdapter.defaultIfEmpty(null, this.mockValueProvider), is(equalTo(poolList)));
assertThat((List<Object>) this.poolAdapter.defaultIfEmpty(null, this.mockSupplier), is(equalTo(poolList)));
verify(this.mockValueProvider, times(1)).getValue();
verify(this.mockSupplier, times(1)).get();
}
@Test
@@ -243,13 +244,13 @@ public class DefaultableDelegatingPoolAdapterTest {
List<Object> poolList = Collections.singletonList("pool");
when(this.mockValueProvider.getValue()).thenReturn(poolList);
when(this.mockSupplier.get()).thenReturn(poolList);
assertThat(this.poolAdapter.prefersDefault(), is(true));
assertThat((List<Object>) this.poolAdapter.defaultIfEmpty(Collections.emptyList(), this.mockValueProvider),
assertThat((List<Object>) this.poolAdapter.defaultIfEmpty(Collections.emptyList(), this.mockSupplier),
is(equalTo(poolList)));
verify(this.mockValueProvider, times(1)).getValue();
verify(this.mockSupplier, times(1)).get();
}
@Test
@@ -260,13 +261,13 @@ public class DefaultableDelegatingPoolAdapterTest {
List<Object> poolList = Collections.singletonList("pool");
when(this.mockValueProvider.getValue()).thenReturn(poolList);
when(this.mockSupplier.get()).thenReturn(poolList);
assertThat(this.poolAdapter.prefersPool(), is(true));
assertThat((List<Object>) this.poolAdapter.defaultIfEmpty(Collections.<Object>singletonList("default"), this.mockValueProvider),
assertThat((List<Object>) this.poolAdapter.defaultIfEmpty(Collections.<Object>singletonList("default"), this.mockSupplier),
is(equalTo(poolList)));
verify(this.mockValueProvider, times(1)).getValue();
verify(this.mockSupplier, times(1)).get();
}
@Test
@@ -275,15 +276,15 @@ public class DefaultableDelegatingPoolAdapterTest {
this.poolAdapter = this.poolAdapter.preferPool();
when(this.mockValueProvider.getValue()).thenReturn(null);
when(this.mockSupplier.get()).thenReturn(null);
List<Object> defaultList = Collections.singletonList("default");
assertThat(this.poolAdapter.prefersPool(), is(true));
assertThat((List<Object>) this.poolAdapter.defaultIfEmpty(defaultList, this.mockValueProvider),
assertThat((List<Object>) this.poolAdapter.defaultIfEmpty(defaultList, this.mockSupplier),
is(equalTo(defaultList)));
verify(this.mockValueProvider, times(1)).getValue();
verify(this.mockSupplier, times(1)).get();
}
@Test
@@ -292,15 +293,15 @@ public class DefaultableDelegatingPoolAdapterTest {
assertThat(this.poolAdapter.preferPool(), is(sameInstance(this.poolAdapter)));
when(this.mockValueProvider.getValue()).thenReturn(Collections.emptyList());
when(this.mockSupplier.get()).thenReturn(Collections.emptyList());
List<Object> defaultList = Collections.singletonList("default");
assertThat(this.poolAdapter.prefersPool(), is(true));
assertThat((List<Object>) this.poolAdapter.defaultIfEmpty(defaultList, this.mockValueProvider),
assertThat((List<Object>) this.poolAdapter.defaultIfEmpty(defaultList, this.mockSupplier),
is(equalTo(defaultList)));
verify(this.mockValueProvider, times(1)).getValue();
verify(this.mockSupplier, times(1)).get();
}
@Test

View File

@@ -16,13 +16,10 @@
package org.springframework.data.gemfire.config.xml;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.springframework.data.gemfire.support.GemfireBeanFactoryLocator.newBeanFactoryLocator;
@@ -42,7 +39,6 @@ import org.springframework.data.gemfire.TestUtils;
import org.springframework.data.gemfire.client.ClientCacheFactoryBean;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.util.ReflectionTestUtils;
/**
* Unit tests for {@link CacheParser}.
@@ -68,26 +64,30 @@ public class CacheNamespaceTest{
public void testNoNamedCache() throws Exception {
assertTrue(applicationContext.containsBean("gemfireCache"));
assertTrue(applicationContext.containsBean("gemfire-cache")); // assert alias is registered
assertTrue(applicationContext.containsBean("gemfire-cache"));
CacheFactoryBean cacheFactoryBean = applicationContext.getBean("&gemfireCache", CacheFactoryBean.class);
assertNull(cacheFactoryBean.getCacheXml());
Properties gemfireProperties = cacheFactoryBean.getProperties();
assertNotNull(gemfireProperties);
assertFalse(cacheFactoryBean.getEnableAutoReconnect());
assertTrue(gemfireProperties.containsKey("disable-auto-reconnect"));
assertTrue(Boolean.parseBoolean(gemfireProperties.getProperty("disable-auto-reconnect")));
assertFalse(cacheFactoryBean.getUseClusterConfiguration());
assertTrue(gemfireProperties.containsKey("use-cluster-configuration"));
assertFalse(Boolean.parseBoolean(gemfireProperties.getProperty("use-cluster-configuration")));
Cache gemfireCache = applicationContext.getBean("gemfireCache", Cache.class);
assertNotNull(gemfireCache);
assertNotNull(gemfireCache.getDistributedSystem());
assertNotNull(gemfireCache.getDistributedSystem().getProperties());
assertNotNull(gemfireCache.getDistributedSystem().getProperties().containsKey("disable-auto-reconnect"));
assertTrue(Boolean.parseBoolean(gemfireCache.getDistributedSystem().getProperties()
.getProperty("disable-auto-reconnect")));
CacheFactoryBean cacheFactoryBean = applicationContext.getBean("&gemfireCache", CacheFactoryBean.class);
assertNull(TestUtils.readField("cacheXml", cacheFactoryBean));
Properties gemfireProperties = cacheFactoryBean.getProperties();
assertNotNull(gemfireProperties);
assertTrue(gemfireProperties.containsKey("disable-auto-reconnect"));
assertTrue(Boolean.parseBoolean(gemfireProperties.getProperty("disable-auto-reconnect")));
assertFalse(cacheFactoryBean.getEnableAutoReconnect());
}
@Test
@@ -95,39 +95,60 @@ public class CacheNamespaceTest{
assertTrue(applicationContext.containsBean("cache-with-name"));
CacheFactoryBean cacheFactoryBean =
applicationContext.getBean("&cache-with-name", CacheFactoryBean.class);
assertNull(cacheFactoryBean.getCacheXml());
Properties gemfireProperties = cacheFactoryBean.getProperties();
assertNotNull(gemfireProperties);
assertFalse(cacheFactoryBean.getEnableAutoReconnect());
assertTrue(gemfireProperties.containsKey("disable-auto-reconnect"));
assertTrue(Boolean.parseBoolean(gemfireProperties.getProperty("disable-auto-reconnect")));
assertFalse(cacheFactoryBean.getUseClusterConfiguration());
assertTrue(gemfireProperties.containsKey("use-cluster-configuration"));
assertFalse(Boolean.parseBoolean(gemfireProperties.getProperty("use-cluster-configuration")));
Cache gemfireCache = applicationContext.getBean("gemfireCache", Cache.class);
assertTrue(Boolean.parseBoolean(gemfireCache.getDistributedSystem().getProperties()
.getProperty("disable-auto-reconnect")));
CacheFactoryBean cacheFactoryBean = applicationContext.getBean("&cache-with-name", CacheFactoryBean.class);
assertNull(TestUtils.readField("cacheXml", cacheFactoryBean));
Properties gemfireProperties = cacheFactoryBean.getProperties();
assertNotNull(gemfireProperties);
assertTrue(gemfireProperties.containsKey("disable-auto-reconnect"));
assertTrue(Boolean.parseBoolean(gemfireProperties.getProperty("disable-auto-reconnect")));
assertFalse(cacheFactoryBean.getEnableAutoReconnect());
assertFalse(Boolean.parseBoolean(gemfireCache.getDistributedSystem().getProperties()
.getProperty("use-cluster-configuration")));
}
@Test
public void testCacheWithXmlAndProperties() throws Exception {
public void testCacheWithAutoReconnectDisabled() throws Exception {
assertTrue(applicationContext.containsBean("cache-with-xml-and-props"));
assertTrue(applicationContext.containsBean("cache-with-auto-reconnect-disabled"));
CacheFactoryBean cacheFactoryBean = applicationContext.getBean("&cache-with-xml-and-props", CacheFactoryBean.class);
CacheFactoryBean cacheFactoryBean =
applicationContext.getBean("&cache-with-auto-reconnect-disabled", CacheFactoryBean.class);
Resource cacheXmlResource = TestUtils.readField("cacheXml", cacheFactoryBean);
assertFalse(cacheFactoryBean.getEnableAutoReconnect());
assertEquals("gemfire-cache.xml", cacheXmlResource.getFilename());
assertTrue(applicationContext.containsBean("gemfireProperties"));
assertEquals(applicationContext.getBean("gemfireProperties"), TestUtils.readField("properties", cacheFactoryBean));
assertEquals(Boolean.TRUE, TestUtils.readField("pdxReadSerialized", cacheFactoryBean));
assertEquals(Boolean.FALSE, TestUtils.readField("pdxIgnoreUnreadFields", cacheFactoryBean));
assertEquals(Boolean.TRUE, TestUtils.readField("pdxPersistent", cacheFactoryBean));
Cache gemfireCache = applicationContext.getBean("cache-with-auto-reconnect-disabled", Cache.class);
assertTrue(Boolean.parseBoolean(gemfireCache.getDistributedSystem().getProperties()
.getProperty("disable-auto-reconnect")));
}
@Test
public void testCacheWithAutoReconnectEnabled() throws Exception {
assertTrue(applicationContext.containsBean("cache-with-auto-reconnect-enabled"));
CacheFactoryBean cacheFactoryBean =
applicationContext.getBean("&cache-with-auto-reconnect-enabled", CacheFactoryBean.class);
assertTrue(cacheFactoryBean.getEnableAutoReconnect());
Cache gemfireCache = applicationContext.getBean("cache-with-auto-reconnect-enabled", Cache.class);
assertFalse(Boolean.parseBoolean(gemfireCache.getDistributedSystem().getProperties()
.getProperty("disable-auto-reconnect")));
}
@Test
@@ -138,36 +159,68 @@ public class CacheNamespaceTest{
assertTrue(cache.getGatewayConflictResolver() instanceof TestGatewayConflictResolver);
}
@Test
public void testCacheWithAutoReconnectDisabled() throws Exception {
@Test(expected = IllegalStateException.class)
public void testCacheWithNoBeanFactoryLocator() throws Exception {
assertTrue(applicationContext.containsBean("cache-with-auto-reconnect-disabled"));
Cache gemfireCache = applicationContext.getBean("cache-with-auto-reconnect-disabled", Cache.class);
assertTrue(Boolean.parseBoolean(gemfireCache.getDistributedSystem().getProperties()
.getProperty("disable-auto-reconnect")));
assertTrue(applicationContext.containsBean("cache-with-no-bean-factory-locator"));
CacheFactoryBean cacheFactoryBean =
applicationContext.getBean("&cache-with-auto-reconnect-disabled", CacheFactoryBean.class);
applicationContext.getBean("&cache-with-no-bean-factory-locator", CacheFactoryBean.class);
assertFalse(cacheFactoryBean.getEnableAutoReconnect());
assertNull(cacheFactoryBean.getBeanFactoryLocator());
newBeanFactoryLocator().useBeanFactory("cache-with-no-bean-factory-locator");
}
@Test
public void testCacheWithAutoReconnectEnabled() throws Exception {
public void testCacheWithUseClusterConfigurationDisabled() {
assertTrue(applicationContext.containsBean("cache-with-auto-reconnect-enabled"));
Cache gemfireCache = applicationContext.getBean("cache-with-auto-reconnect-enabled", Cache.class);
assertFalse(Boolean.parseBoolean(gemfireCache.getDistributedSystem().getProperties()
.getProperty("disable-auto-reconnect")));
assertTrue(applicationContext.containsBean("cache-with-use-cluster-configuration-disabled"));
CacheFactoryBean cacheFactoryBean =
applicationContext.getBean("&cache-with-auto-reconnect-enabled", CacheFactoryBean.class);
applicationContext.getBean("&cache-with-use-cluster-configuration-disabled", CacheFactoryBean.class);
assertTrue(cacheFactoryBean.getEnableAutoReconnect());
assertFalse(cacheFactoryBean.getEnableAutoReconnect());
Cache gemfireCache =
applicationContext.getBean("cache-with-use-cluster-configuration-disabled", Cache.class);
assertFalse(Boolean.parseBoolean(gemfireCache.getDistributedSystem().getProperties()
.getProperty("use-cluster-configuration")));
}
@Test
public void testCacheWithUseClusterConfigurationEnabled() {
assertTrue(applicationContext.containsBean("cache-with-use-cluster-configuration-enabled"));
CacheFactoryBean cacheFactoryBean =
applicationContext.getBean("&cache-with-use-cluster-configuration-enabled", CacheFactoryBean.class);
assertTrue(cacheFactoryBean.getUseClusterConfiguration());
Cache gemfireCache =
applicationContext.getBean("cache-with-use-cluster-configuration-enabled", Cache.class);
assertTrue(Boolean.parseBoolean(gemfireCache.getDistributedSystem().getProperties()
.getProperty("use-cluster-configuration")));
}
@Test
public void testCacheWithXmlAndProperties() throws Exception {
assertTrue(applicationContext.containsBean("cache-with-xml-and-props"));
CacheFactoryBean cacheFactoryBean = applicationContext.getBean("&cache-with-xml-and-props", CacheFactoryBean.class);
Resource cacheXmlResource = cacheFactoryBean.getCacheXml();
assertEquals("gemfire-cache.xml", cacheXmlResource.getFilename());
assertTrue(applicationContext.containsBean("gemfireProperties"));
assertEquals(applicationContext.getBean("gemfireProperties"), TestUtils.readField("properties", cacheFactoryBean));
assertEquals(Boolean.TRUE, TestUtils.readField("pdxReadSerialized", cacheFactoryBean));
assertEquals(Boolean.FALSE, TestUtils.readField("pdxIgnoreUnreadFields", cacheFactoryBean));
assertEquals(Boolean.TRUE, TestUtils.readField("pdxPersistent", cacheFactoryBean));
}
@Test
@@ -175,7 +228,8 @@ public class CacheNamespaceTest{
assertTrue(applicationContext.containsBean("heap-tuned-cache"));
CacheFactoryBean cacheFactoryBean = applicationContext.getBean("&heap-tuned-cache", CacheFactoryBean.class);
CacheFactoryBean cacheFactoryBean =
applicationContext.getBean("&heap-tuned-cache", CacheFactoryBean.class);
Float criticalHeapPercentage = cacheFactoryBean.getCriticalHeapPercentage();
Float evictionHeapPercentage = cacheFactoryBean.getEvictionHeapPercentage();
@@ -189,7 +243,8 @@ public class CacheNamespaceTest{
assertTrue(applicationContext.containsBean("off-heap-tuned-cache"));
CacheFactoryBean cacheFactoryBean = applicationContext.getBean("&off-heap-tuned-cache", CacheFactoryBean.class);
CacheFactoryBean cacheFactoryBean =
applicationContext.getBean("&off-heap-tuned-cache", CacheFactoryBean.class);
Float criticalOffHeapPercentage = cacheFactoryBean.getCriticalOffHeapPercentage();
Float evictionOffHeapPercentage = cacheFactoryBean.getEvictionOffHeapPercentage();
@@ -198,33 +253,16 @@ public class CacheNamespaceTest{
assertEquals(50.0f, evictionOffHeapPercentage, 0.0001);
}
@Test(expected = IllegalStateException.class)
public void testNoBeanFactoryLocator() throws Exception {
assertTrue(applicationContext.containsBean("no-bean-factory-locator-cache"));
CacheFactoryBean cacheFactoryBean =
applicationContext.getBean("&no-bean-factory-locator-cache", CacheFactoryBean.class);
assertThat(ReflectionTestUtils.getField(cacheFactoryBean, "beanFactoryLocator"), is(nullValue()));
newBeanFactoryLocator().useBeanFactory("no-bean-factory-locator-cache");
}
@Test
public void namedClientCacheWithNoProperties() throws Exception {
public void namedClientCacheWithNoPropertiesAndNoCacheXml() throws Exception {
assertTrue(applicationContext.containsBean("client-cache-with-name"));
ClientCacheFactoryBean clientCacheFactoryBean =
applicationContext.getBean("&client-cache-with-name", ClientCacheFactoryBean.class);
assertNull(TestUtils.readField("cacheXml", clientCacheFactoryBean));
Properties gemfireProperties = clientCacheFactoryBean.getProperties();
assertNotNull(gemfireProperties);
assertTrue(gemfireProperties.isEmpty());
assertNull(clientCacheFactoryBean.getCacheXml());
assertNull(clientCacheFactoryBean.getProperties());
}
@Test
@@ -235,14 +273,11 @@ public class CacheNamespaceTest{
ClientCacheFactoryBean clientCacheFactoryBean =
applicationContext.getBean("&client-cache-with-xml", ClientCacheFactoryBean.class);
Resource cacheXmlResource = TestUtils.readField("cacheXml", clientCacheFactoryBean);
Resource cacheXmlResource = clientCacheFactoryBean.getCacheXml();
assertEquals("gemfire-client-cache.xml", cacheXmlResource.getFilename());
Properties gemfireProperties = clientCacheFactoryBean.getProperties();
assertNotNull(gemfireProperties);
assertTrue(gemfireProperties.isEmpty());
assertNull(clientCacheFactoryBean.getProperties());
}
public static class TestGatewayConflictResolver implements GatewayConflictResolver {

View File

@@ -23,17 +23,12 @@ import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.data.gemfire.util.ArrayUtils.nullSafeArray;
import java.io.File;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.geode.cache.CacheListener;
import org.apache.geode.cache.CacheLoader;
@@ -47,16 +42,12 @@ import org.apache.geode.cache.InterestResultPolicy;
import org.apache.geode.cache.LoaderHelper;
import org.apache.geode.cache.Region;
import org.apache.geode.cache.RegionAttributes;
import org.apache.geode.cache.client.ClientCache;
import org.apache.geode.cache.client.ClientRegionFactory;
import org.apache.geode.cache.client.ClientRegionShortcut;
import org.apache.geode.cache.util.CacheWriterAdapter;
import org.apache.geode.compression.Compressor;
import org.junit.AfterClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.data.gemfire.SimpleCacheListener;
@@ -64,6 +55,7 @@ import org.springframework.data.gemfire.SimpleObjectSizer;
import org.springframework.data.gemfire.TestUtils;
import org.springframework.data.gemfire.client.ClientRegionFactoryBean;
import org.springframework.data.gemfire.client.Interest;
import org.springframework.data.gemfire.test.mock.context.GemFireMockObjectsApplicationContextInitializer;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.util.ObjectUtils;
@@ -80,7 +72,7 @@ import org.springframework.util.ObjectUtils;
* @see org.springframework.data.gemfire.config.xml.ClientRegionParser
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="client-ns.xml")
@ContextConfiguration(locations="client-ns.xml", initializers = GemFireMockObjectsApplicationContextInitializer.class)
@SuppressWarnings("unused")
public class ClientRegionNamespaceTest {
@@ -95,6 +87,7 @@ public class ClientRegionNamespaceTest {
@Test
public void testBeanNames() throws Exception {
assertTrue(applicationContext.containsBean("SimpleRegion"));
assertTrue(applicationContext.containsBean("Publisher"));
assertTrue(applicationContext.containsBean("ComplexRegion"));
@@ -105,6 +98,7 @@ public class ClientRegionNamespaceTest {
@Test
public void testSimpleClientRegion() throws Exception {
assertTrue(applicationContext.containsBean("simple"));
Region<?, ?> simple = applicationContext.getBean("simple", Region.class);
@@ -119,6 +113,7 @@ public class ClientRegionNamespaceTest {
@Test
@SuppressWarnings("rawtypes")
public void testPublishingClientRegion() throws Exception {
assertTrue(applicationContext.containsBean("empty"));
ClientRegionFactoryBean emptyClientRegionFactoryBean = applicationContext
@@ -134,6 +129,7 @@ public class ClientRegionNamespaceTest {
@Test
@SuppressWarnings("rawtypes")
public void testComplexClientRegion() throws Exception {
assertTrue(applicationContext.containsBean("complex"));
ClientRegionFactoryBean complexClientRegionFactoryBean = applicationContext
@@ -161,6 +157,7 @@ public class ClientRegionNamespaceTest {
@Test
@SuppressWarnings({ "deprecation", "rawtypes" })
public void testPersistentClientRegion() throws Exception {
assertTrue(applicationContext.containsBean("persistent"));
Region persistent = applicationContext.getBean("persistent", Region.class);
@@ -179,6 +176,7 @@ public class ClientRegionNamespaceTest {
@Test
@SuppressWarnings("rawtypes")
public void testOverflowClientRegion() throws Exception {
assertTrue(applicationContext.containsBean("overflow"));
ClientRegionFactoryBean overflowClientRegionFactoryBean = applicationContext
@@ -204,6 +202,7 @@ public class ClientRegionNamespaceTest {
@Test
public void testClientRegionWithCacheLoaderAndCacheWriter() throws Exception {
assertTrue(applicationContext.containsBean("loadWithWrite"));
ClientRegionFactoryBean factory = applicationContext.getBean("&loadWithWrite", ClientRegionFactoryBean.class);
@@ -217,6 +216,7 @@ public class ClientRegionNamespaceTest {
@Test
public void testCompressedReplicateRegion() {
assertTrue(applicationContext.containsBean("Compressed"));
Region<?, ?> compressed = applicationContext.getBean("Compressed", Region.class);
@@ -276,7 +276,7 @@ public class ClientRegionNamespaceTest {
assertInterest(true, false, InterestResultPolicy.KEYS, getInterestWithKey(".*", interests));
assertInterest(true, false, InterestResultPolicy.KEYS_VALUES, getInterestWithKey("keyPrefix.*", interests));
Region mockClientRegion = MockCacheFactoryBean.MOCK_REGION_REF.get();
Region mockClientRegion = applicationContext.getBean("client-with-interests", Region.class);
assertNotNull(mockClientRegion);
@@ -287,15 +287,17 @@ public class ClientRegionNamespaceTest {
eq(InterestResultPolicy.KEYS_VALUES), eq(true), eq(false));
}
protected void assertInterest(final boolean expectedDurable, final boolean expectedReceiveValues,
final InterestResultPolicy expectedPolicy, final Interest actualInterest) {
private void assertInterest(boolean expectedDurable, boolean expectedReceiveValues,
InterestResultPolicy expectedPolicy, Interest actualInterest) {
assertNotNull(actualInterest);
assertEquals(expectedDurable, actualInterest.isDurable());
assertEquals(expectedReceiveValues, actualInterest.isReceiveValues());
assertEquals(expectedPolicy, actualInterest.getPolicy());
}
protected Interest getInterestWithKey(final String key, final Interest... interests) {
private Interest getInterestWithKey(final String key, final Interest... interests) {
for (Interest interest : interests) {
if (interest.getKey().equals(key)) {
return interest;
@@ -305,43 +307,6 @@ public class ClientRegionNamespaceTest {
return null;
}
static final class MockCacheFactoryBean implements FactoryBean<ClientCache>, InitializingBean {
static final AtomicReference<Region> MOCK_REGION_REF = new AtomicReference<Region>(null);
private ClientCache mockClientCache;
@Override
@SuppressWarnings("unchecked")
public void afterPropertiesSet() throws Exception {
this.mockClientCache = mock(ClientCache.class,
ClientRegionNamespaceTest.class.getSimpleName().concat(".MockClientCache"));
ClientRegionFactory mockClientRegionFactory = mock(ClientRegionFactory.class,
ClientRegionNamespaceTest.class.getSimpleName().concat("MockClientRegionFactory"));
when(this.mockClientCache.createClientRegionFactory(any(ClientRegionShortcut.class)))
.thenReturn(mockClientRegionFactory);
Region mockRegion = mock(Region.class,
ClientRegionNamespaceTest.class.getSimpleName().concat(".MockClientRegion"));
when(mockClientRegionFactory.create(anyString())).thenReturn(mockRegion);
MOCK_REGION_REF.compareAndSet(null, mockRegion);
}
@Override
public ClientCache getObject() throws Exception {
return this.mockClientCache;
}
@Override
public Class<?> getObjectType() {
return ClientCache.class;
}
}
public static final class TestCacheLoader implements CacheLoader<Object, Object> {
@Override
@@ -350,12 +315,11 @@ public class ClientRegionNamespaceTest {
}
@Override
public void close() {
}
public void close() { }
}
public static final class TestCacheWriter extends CacheWriterAdapter<Object, Object> {
}
public static final class TestCacheWriter extends CacheWriterAdapter<Object, Object> { }
public static class TestCompressor implements Compressor {

View File

@@ -42,18 +42,21 @@ public class InvalidRegionDefinitionUsingBeansNamespaceTest {
@Test(expected = IllegalArgumentException.class)
public void testInvalidDataPolicyPersistentAttributeSettings() {
try {
new ClassPathXmlApplicationContext(CONFIG_LOCATION);
}
catch (BeanCreationException expected) {
assertTrue(expected.getCause() instanceof IllegalArgumentException);
assertEquals("Data Policy [REPLICATE] is invalid when persistent is true.", expected.getCause().getMessage());
assertEquals("Data Policy [REPLICATE] is not valid when persistent is true",
expected.getCause().getMessage());
throw (IllegalArgumentException) expected.getCause();
}
}
@SuppressWarnings("unused")
public static final class TestRegionFactoryBean<K, V> extends RegionFactoryBean<K, V> {
}
public static final class TestRegionFactoryBean<K, V> extends RegionFactoryBean<K, V> { }
}

View File

@@ -62,13 +62,15 @@ import org.springframework.util.ObjectUtils;
public class ReplicatedRegionNamespaceTest {
@Autowired
private ApplicationContext context;
private ApplicationContext applicationContext;
@Test
public void testSimpleReplicateRegion() throws Exception {
assertTrue(context.containsBean("simple"));
RegionFactoryBean simpleRegionFactoryBean = context.getBean("&simple", RegionFactoryBean.class);
assertTrue(applicationContext.containsBean("simple"));
RegionFactoryBean simpleRegionFactoryBean =
applicationContext.getBean("&simple", RegionFactoryBean.class);
assertEquals("simple", TestUtils.readField("beanName", simpleRegionFactoryBean));
assertEquals(false, TestUtils.readField("close", simpleRegionFactoryBean));
@@ -85,9 +87,11 @@ public class ReplicatedRegionNamespaceTest {
@Test
@SuppressWarnings({ "deprecation", "rawtypes" })
public void testPublishReplicateRegion() throws Exception {
assertTrue(context.containsBean("pub"));
RegionFactoryBean publisherRegionFactoryBean = context.getBean("&pub", RegionFactoryBean.class);
assertTrue(applicationContext.containsBean("pub"));
RegionFactoryBean publisherRegionFactoryBean =
applicationContext.getBean("&pub", RegionFactoryBean.class);
assertTrue(publisherRegionFactoryBean instanceof ReplicatedRegionFactoryBean);
assertEquals("publisher", TestUtils.readField("name", publisherRegionFactoryBean));
@@ -102,9 +106,11 @@ public class ReplicatedRegionNamespaceTest {
@Test
@SuppressWarnings("rawtypes")
public void testComplexReplicateRegion() throws Exception {
assertTrue(context.containsBean("complex"));
RegionFactoryBean complexRegionFactoryBean = context.getBean("&complex", RegionFactoryBean.class);
assertTrue(applicationContext.containsBean("complex"));
RegionFactoryBean complexRegionFactoryBean =
applicationContext.getBean("&complex", RegionFactoryBean.class);
assertNotNull(complexRegionFactoryBean);
assertEquals("complex", TestUtils.readField("beanName", complexRegionFactoryBean));
@@ -113,19 +119,20 @@ public class ReplicatedRegionNamespaceTest {
assertFalse(ObjectUtils.isEmpty(cacheListeners));
assertEquals(2, cacheListeners.length);
assertSame(context.getBean("c-listener"), cacheListeners[0]);
assertSame(applicationContext.getBean("c-listener"), cacheListeners[0]);
assertTrue(cacheListeners[1] instanceof SimpleCacheListener);
assertNotSame(cacheListeners[0], cacheListeners[1]);
assertSame(context.getBean("c-loader"), TestUtils.readField("cacheLoader", complexRegionFactoryBean));
assertSame(context.getBean("c-writer"), TestUtils.readField("cacheWriter", complexRegionFactoryBean));
assertSame(applicationContext.getBean("c-loader"), TestUtils.readField("cacheLoader", complexRegionFactoryBean));
assertSame(applicationContext.getBean("c-writer"), TestUtils.readField("cacheWriter", complexRegionFactoryBean));
}
@Test
@SuppressWarnings("rawtypes")
public void testReplicatedRegionWithAttributes() throws Exception {
assertTrue(context.containsBean("replicated-with-attributes"));
Region region = context.getBean("replicated-with-attributes", Region.class);
assertTrue(applicationContext.containsBean("replicated-with-attributes"));
Region region = applicationContext.getBean("replicated-with-attributes", Region.class);
assertNotNull("The 'replicated-with-attributes' Region was not properly configured and initialized!", region);
@@ -151,9 +158,10 @@ public class ReplicatedRegionNamespaceTest {
@Test
public void testReplicatedWithSynchronousIndexUpdates() {
assertTrue(context.containsBean("replicated-with-synchronous-index-updates"));
Region region = context.getBean("replicated-with-synchronous-index-updates", Region.class);
assertTrue(applicationContext.containsBean("replicated-with-synchronous-index-updates"));
Region region = applicationContext.getBean("replicated-with-synchronous-index-updates", Region.class);
assertNotNull(String.format("The '%1$s' Region was not properly configured and initialized!",
"replicated-with-synchronous-index-updates"), region);
@@ -167,23 +175,27 @@ public class ReplicatedRegionNamespaceTest {
@Test
@SuppressWarnings("rawtypes")
public void testRegionLookup() throws Exception {
Cache cache = context.getBean(Cache.class);
Cache cache = applicationContext.getBean(Cache.class);
Region existing = cache.createRegionFactory().create("existing");
assertTrue(context.containsBean("lookup"));
assertTrue(applicationContext.containsBean("lookup"));
RegionLookupFactoryBean regionLookupFactoryBean = context.getBean("&lookup", RegionLookupFactoryBean.class);
RegionLookupFactoryBean regionLookupFactoryBean =
applicationContext.getBean("&lookup", RegionLookupFactoryBean.class);
assertNotNull(regionLookupFactoryBean);
assertEquals("existing", TestUtils.readField("name", regionLookupFactoryBean));
assertSame(existing, context.getBean("lookup"));
assertSame(existing, applicationContext.getBean("lookup"));
}
@Test
public void testCompressedReplicateRegion() {
assertTrue(context.containsBean("Compressed"));
Region<?, ?> compressed = context.getBean("Compressed", Region.class);
assertTrue(applicationContext.containsBean("Compressed"));
Region<?, ?> compressed = applicationContext.getBean("Compressed", Region.class);
assertNotNull("The 'Compressed' REPLICATE Region was not properly configured and initialized!", compressed);
assertEquals("Compressed", compressed.getName());

View File

@@ -39,11 +39,13 @@ public class SubRegionWithInvalidDataPolicyTest {
@Test(expected = XmlBeanDefinitionStoreException.class)
public void testSubRegionBeanDefinitionWithInconsistentDataPolicy() {
try {
new ClassPathXmlApplicationContext(
"/org/springframework/data/gemfire/config/xml/subregion-with-invalid-datapolicy.xml");
}
catch (XmlBeanDefinitionStoreException expected) {
assertTrue(expected.getCause() instanceof SAXParseException);
assertTrue(expected.getCause().getMessage().contains("PERSISTENT_PARTITION"));
@@ -53,14 +55,16 @@ public class SubRegionWithInvalidDataPolicyTest {
@Test(expected = BeanCreationException.class)
public void testSubRegionBeanDefinitionWithInvalidDataPolicyPersistentSettings() {
try {
new ClassPathXmlApplicationContext(
"/org/springframework/data/gemfire/config/xml/subregion-with-inconsistent-datapolicy-persistent-settings.xml");
}
catch (BeanCreationException expected) {
assertTrue(expected.getMessage().contains("Error creating bean with name '/Parent/Child'"));
assertTrue(expected.getCause() instanceof IllegalArgumentException);
assertEquals("Data Policy [REPLICATE] is invalid when persistent is true.",
assertEquals("Data Policy [REPLICATE] is not valid when persistent is true",
expected.getCause().getMessage());
throw expected;

View File

@@ -16,7 +16,7 @@
package org.springframework.data.gemfire.config.xml;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
import org.springframework.beans.factory.parsing.BeanDefinitionParsingException;
@@ -37,20 +37,23 @@ import org.springframework.context.support.ClassPathXmlApplicationContext;
*/
public class TemplateRegionDefinitionOrderErrorNamespaceTest {
protected String getConfigLocation() {
private String getConfigLocation() {
return getClass().getName().replace(".", "/").concat("-context.xml");
}
@Test(expected = BeanDefinitionParsingException.class)
public void testIncorrectTemplateRegionDefinitionOrder() throws Exception {
try {
new ClassPathXmlApplicationContext(getConfigLocation());
}
catch (BeanDefinitionParsingException expected) {
assertTrue(expected.getMessage().contains(
"The Region template [RegionTemplate] must be 'defined before' the Region [TemplateBasedPartitionRegion] referring to the template!"));
assertThat(expected)
.hasMessageContaining("The Region template [RegionTemplate] must be defined before the Region [TemplateBasedPartitionRegion] referring to the template");
assertThat(expected).hasNoCause();
throw expected;
}
}
}

View File

@@ -31,10 +31,11 @@ import org.springframework.data.gemfire.test.support.FileSystemUtils;
import org.springframework.data.gemfire.test.support.ThreadUtils;
/**
* The LocatorProcess class is a main Java class that is used fork and launch a GemFire Locator process using the
* LocatorLauncher class.
* The {@link LocatorProcess} class is a main Java class that is used fork and launch a {@link Locator} process
* using the {@link LocatorLauncher} class.
*
* @author John Blum
* @see org.apache.geode.distributed.Locator
* @see org.apache.geode.distributed.LocatorLauncher
* @since 1.5.0
*/
@@ -43,11 +44,12 @@ public class LocatorProcess {
private static final int DEFAULT_LOCATOR_PORT = 20668;
private static final String GEMFIRE_NAME = "SpringDataGemFireLocator";
private static final String GEMFIRE_LOG_LEVEL = "warning";
private static final String GEMFIRE_LOG_LEVEL = "error";
private static final String HOSTNAME_FOR_CLIENTS = "localhost";
private static final String HTTP_SERVICE_PORT = "0";
public static void main(final String... args) throws IOException {
public static void main(String... args) throws IOException {
//runLocator();
runInternalLocator();
@@ -67,8 +69,9 @@ public class LocatorProcess {
@SuppressWarnings("unused")
private static InternalLocator runInternalLocator() throws IOException {
String hostnameForClients = System.getProperty("spring.gemfire.hostname-for-clients",
HOSTNAME_FOR_CLIENTS);
String hostnameForClients =
System.getProperty("spring.data.gemfire.locator.hostname-for-clients", HOSTNAME_FOR_CLIENTS);
int locatorPort = Integer.getInteger("spring.data.gemfire.locator.port", DEFAULT_LOCATOR_PORT);
@@ -90,21 +93,23 @@ public class LocatorProcess {
distributedSystemProperties.setProperty(DistributionConfig.LOG_LEVEL_NAME,
System.getProperty("spring.data.gemfire.log-level", GEMFIRE_LOG_LEVEL));
return InternalLocator.startLocator(locatorPort, null, null, null, null,
true, distributedSystemProperties, hostnameForClients);
return InternalLocator.startLocator(locatorPort, null, null, null,
null, true, distributedSystemProperties, hostnameForClients);
}
@SuppressWarnings("unused")
private static LocatorLauncher runLocator() {
LocatorLauncher locatorLauncher = buildLocatorLauncher();
// start the GemFire Locator process...
// Start a Pivotal GemFire Locator process...
locatorLauncher.start();
return locatorLauncher;
}
private static LocatorLauncher buildLocatorLauncher() {
return new LocatorLauncher.Builder()
.setMemberName(GEMFIRE_NAME)
.setHostnameForClients(getProperty("spring.data.gemfire.hostname-for-clients", HOSTNAME_FOR_CLIENTS))
@@ -136,7 +141,9 @@ public class LocatorProcess {
}
private static void registerShutdownHook() {
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
Locator locator = GemfireUtils.getLocator();
if (locator != null) {
@@ -146,6 +153,7 @@ public class LocatorProcess {
}
private static void waitForLocatorStart(final long milliseconds) {
InternalLocator locator = InternalLocator.getLocator();
if (isClusterConfigurationEnabled(locator)) {
@@ -158,7 +166,8 @@ public class LocatorProcess {
}
private static boolean isClusterConfigurationEnabled(final InternalLocator locator) {
return (locator != null && Boolean.valueOf(locator.getDistributedSystem().getProperties().getProperty(
DistributionConfig.ENABLE_CLUSTER_CONFIGURATION_NAME)));
return locator != null && Boolean.valueOf(locator.getDistributedSystem().getProperties()
.getProperty(DistributionConfig.ENABLE_CLUSTER_CONFIGURATION_NAME));
}
}

View File

@@ -42,7 +42,7 @@ import org.springframework.data.gemfire.process.ProcessWrapper;
import org.springframework.data.gemfire.test.support.FileSystemUtils;
import org.springframework.data.gemfire.test.support.ThreadUtils;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.Assert;
/**
@@ -63,34 +63,37 @@ import org.springframework.util.Assert;
* @see org.springframework.test.context.junit4.SpringJUnit4ClassRunner
* @since 1.7.0
*/
@RunWith(SpringJUnit4ClassRunner.class)
@RunWith(SpringRunner.class)
@ContextConfiguration
@SuppressWarnings("unused")
public class ExceptionThrowingFunctionExecutionIntegrationTest {
private static ProcessWrapper serverProcess;
private static ProcessWrapper gemfireServer;
@Rule
public ExpectedException expectedException = ExpectedException.none();
public ExpectedException exception = ExpectedException.none();
@Autowired
private ExceptionThrowingFunctionExecution exceptionThrowingFunctionExecution;
@BeforeClass
public static void setup() throws IOException {
public static void startGemFireServer() throws IOException {
String serverName = ExceptionThrowingFunctionExecutionIntegrationTest.class.getSimpleName().concat("Server");
File serverWorkingDirectory = new File(FileSystemUtils.WORKING_DIRECTORY, serverName.toLowerCase());
Assert.isTrue(serverWorkingDirectory.isDirectory() || serverWorkingDirectory.mkdirs());
Assert.isTrue(serverWorkingDirectory.isDirectory() || serverWorkingDirectory.mkdirs(),
String.format("Failed to create working directory [%s]", serverWorkingDirectory));
List<String> arguments = new ArrayList<String>();
arguments.add("-Dgemfire.name=" + serverName);
arguments.add("-Dgemfire.log-level=error");
arguments.add(ExceptionThrowingFunctionExecutionIntegrationTest.class.getName().replace(".", "/")
.concat("-server-context.xml"));
serverProcess = ProcessExecutor.launch(serverWorkingDirectory, ServerProcess.class,
gemfireServer = ProcessExecutor.launch(serverWorkingDirectory, ServerProcess.class,
arguments.toArray(new String[arguments.size()]));
waitForServerStart(TimeUnit.SECONDS.toMillis(20));
@@ -99,34 +102,41 @@ public class ExceptionThrowingFunctionExecutionIntegrationTest {
}
private static void waitForServerStart(final long milliseconds) {
ThreadUtils.timedWait(milliseconds, TimeUnit.MILLISECONDS.toMillis(500), new ThreadUtils.WaitCondition() {
private File serverPidControlFile = new File(serverProcess.getWorkingDirectory(),
private File serverPidControlFile = new File(gemfireServer.getWorkingDirectory(),
ServerProcess.getServerProcessControlFilename());
@Override public boolean waiting() {
@Override
public boolean waiting() {
return !serverPidControlFile.isFile();
}
});
}
@AfterClass
public static void tearDown() {
serverProcess.shutdown();
public static void stopGemFireServer() {
gemfireServer.shutdown();
if (Boolean.valueOf(System.getProperty("spring.gemfire.fork.clean", Boolean.TRUE.toString()))) {
org.springframework.util.FileSystemUtils.deleteRecursively(serverProcess.getWorkingDirectory());
org.springframework.util.FileSystemUtils.deleteRecursively(gemfireServer.getWorkingDirectory());
}
}
@Test
public void exceptionThrowingFunctionExecutionRethrowsException() {
expectedException.expect(FunctionException.class);
expectedException.expectCause(isA(IllegalArgumentException.class));
expectedException.expectMessage(containsString("Execution of Function with ID 'exceptionThrowingFunction' failed"));
exception.expect(FunctionException.class);
exception.expectCause(isA(IllegalArgumentException.class));
exception.expectMessage(containsString("Execution of Function with ID [exceptionThrowingFunction] failed"));
exceptionThrowingFunctionExecution.exceptionThrowingFunction();
}
public static class ExceptionThrowingFunction extends FunctionAdapter {
@Override
public String getId() {
return "exceptionThrowingFunction";
@@ -136,5 +146,4 @@ public class ExceptionThrowingFunctionExecutionIntegrationTest {
context.getResultSender().sendException(new IllegalArgumentException("TEST"));
}
}
}

View File

@@ -66,18 +66,21 @@ public class AbstractFunctionExecutionTest {
@Mock
private Execution mockExecution;
// TODO add more tests!!!
// TODO: add more tests!!!
@Test
@SuppressWarnings("unchecked")
public void executeWithResults() throws Exception {
Object[] args = { "one", "two", "three" };
List<Object> results = Arrays.asList(args);
Function mockFunction = mock(Function.class, "MockFunction");
ResultCollector mockResultCollector = mock(ResultCollector.class, "MockResultCollector");
when(mockExecution.withArgs(eq(args))).thenReturn(mockExecution);
when(mockExecution.setArguments(eq(args))).thenReturn(mockExecution);
when(mockExecution.execute(eq(mockFunction))).thenReturn(mockResultCollector);
when(mockFunction.hasResult()).thenReturn(true);
when(mockResultCollector.getResult(500, TimeUnit.MILLISECONDS)).thenReturn(results);
@@ -94,7 +97,7 @@ public class AbstractFunctionExecutionTest {
assertThat(actualResults).isNotNull();
assertThat(actualResults).isEqualTo((Iterable<Object>) results);
verify(mockExecution, times(1)).withArgs(eq(args));
verify(mockExecution, times(1)).setArguments(eq(args));
verify(mockExecution, never()).withCollector(any(ResultCollector.class));
verify(mockExecution, never()).withFilter(any(Set.class));
verify(mockExecution, times(1)).execute(eq(mockFunction));
@@ -173,8 +176,11 @@ public class AbstractFunctionExecutionTest {
@Test
public void executeAndExtractWithThrowsException() {
AbstractFunctionExecution functionExecution = new AbstractFunctionExecution() {
@Override protected Execution getExecution() {
@Override
protected Execution getExecution() {
return mockExecution;
}
@@ -186,7 +192,7 @@ public class AbstractFunctionExecutionTest {
expectedException.expect(FunctionException.class);
expectedException.expectCause(isA(IllegalArgumentException.class));
expectedException.expectMessage(containsString("Execution of Function with ID 'TestFunction' failed"));
expectedException.expectMessage(containsString("Execution of Function with ID [TestFunction] failed"));
functionExecution.setFunctionId("TestFunction").executeAndExtract();
}

View File

@@ -45,6 +45,9 @@ public class RepositoryClientRegionIntegrationTests extends ClientServerIntegrat
@BeforeClass
public static void startGemFireServer() throws Exception {
System.setProperty("gemfire.log-level", GEMFIRE_LOG_LEVEL);
int availablePort = findAvailablePort();
gemfireServer = run(ServerProcess.class,
@@ -58,6 +61,7 @@ public class RepositoryClientRegionIntegrationTests extends ClientServerIntegrat
@AfterClass
public static void stopGemFireServer() {
System.clearProperty("gemfire.log-level");
System.clearProperty(GEMFIRE_CACHE_SERVER_PORT_PROPERTY);
stop(gemfireServer);
}

View File

@@ -19,8 +19,11 @@ import org.apache.geode.cache.GemFireCache;
import org.springframework.data.gemfire.CacheFactoryBean;
/**
* Mock {@link CacheFactoryBean} used in Unit Tests.
*
* @author David Turanski
* @author John Blum
* @see org.springframework.data.gemfire.CacheFactoryBean
*/
public class MockCacheFactoryBean extends CacheFactoryBean {
@@ -57,6 +60,7 @@ public class MockCacheFactoryBean extends CacheFactoryBean {
setTransactionListeners(it.getTransactionListeners());
setTransactionWriter(it.getTransactionWriter());
setUseBeanFactoryLocator(it.isUseBeanFactoryLocator());
setUseClusterConfiguration(it.getUseClusterConfiguration());
});
applyPeerCacheConfigurers(cacheFactoryBean.getCompositePeerCacheConfigurer());

View File

@@ -190,7 +190,7 @@ public class ClientServerIntegrationTestsSupport {
/* (non-Javadoc) */
protected static ProcessWrapper run(File workingDirectory, Class<?> type, String... arguments) throws IOException {
return (isProcessRunAuto() ? launch(createDirectory(workingDirectory), type, arguments) : null);
return isProcessRunAuto() ? launch(createDirectory(workingDirectory), type, arguments) : null;
}
/* (non-Javadoc) */
@@ -202,7 +202,7 @@ public class ClientServerIntegrationTestsSupport {
protected static ProcessWrapper run(File workingDirectory, String classpath, Class<?> type, String... arguments)
throws IOException {
return (isProcessRunAuto() ? launch(createDirectory(workingDirectory), classpath, type, arguments) : null);
return isProcessRunAuto() ? launch(createDirectory(workingDirectory), classpath, type, arguments) : null;
}
/* (non-Javadoc) */

View File

@@ -73,6 +73,7 @@ public abstract class ThreadUtils {
}
// TODO rename interface to Condition and waiting() method to evaluate()
@FunctionalInterface
public interface WaitCondition {
boolean waiting();
}

View File

@@ -0,0 +1,85 @@
/*
* Copyright 2018 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 org.apache.geode.cache.DataPolicy;
import org.junit.Test;
/**
* Unit tests for {@link RegionUtils}.
*
* @author John Blum
* @see org.springframework.data.gemfire.util.RegionUtils
* @since 2.1.0
*/
public class RegionUtilsUnitTests {
@Test
public void assertAllDataPoliciesWithNullPersistentPropertyIsCompatible() {
RegionUtils.assertDataPolicyAndPersistentAttributeAreCompatible(DataPolicy.PARTITION, null);
RegionUtils.assertDataPolicyAndPersistentAttributeAreCompatible(DataPolicy.REPLICATE, null);
RegionUtils.assertDataPolicyAndPersistentAttributeAreCompatible(DataPolicy.PERSISTENT_PARTITION, null);
RegionUtils.assertDataPolicyAndPersistentAttributeAreCompatible(DataPolicy.PERSISTENT_REPLICATE, null);
}
@Test
public void assertNonPersistentDataPolicyWithNoPersistenceIsCompatible() {
RegionUtils.assertDataPolicyAndPersistentAttributeAreCompatible(DataPolicy.PARTITION, false);
RegionUtils.assertDataPolicyAndPersistentAttributeAreCompatible(DataPolicy.REPLICATE, false);
}
@Test
public void assertPersistentDataPolicyWithPersistenceIsCompatible() {
RegionUtils.assertDataPolicyAndPersistentAttributeAreCompatible(DataPolicy.PERSISTENT_PARTITION, true);
RegionUtils.assertDataPolicyAndPersistentAttributeAreCompatible(DataPolicy.PERSISTENT_REPLICATE, true);
}
@Test(expected = IllegalArgumentException.class)
public void testAssertNonPersistentDataPolicyWithPersistentAttribute() {
try {
RegionUtils.assertDataPolicyAndPersistentAttributeAreCompatible(DataPolicy.REPLICATE, true);
}
catch (IllegalArgumentException expected) {
assertThat(expected).hasMessage("Data Policy [REPLICATE] is not valid when persistent is true");
assertThat(expected).hasNoCause();
throw expected;
}
}
@Test(expected = IllegalArgumentException.class)
public void testAssertPersistentDataPolicyWithNonPersistentAttribute() {
try {
RegionUtils.assertDataPolicyAndPersistentAttributeAreCompatible(DataPolicy.PERSISTENT_PARTITION, false);
}
catch (IllegalArgumentException expected) {
assertThat(expected).hasMessage("Data Policy [PERSISTENT_PARTITION] is not valid when persistent is false");
assertThat(expected).hasNoCause();
throw expected;
}
}
}