DATACASS-298 - Add missing PoolingOptions to the XML namespace as well as the PoolingOptionsFactoryBean.

Original pull request: #66.
This commit is contained in:
John Blum
2016-06-16 19:13:25 -07:00
committed by Mark Paluch
parent 857d508744
commit 3d9835d99a
14 changed files with 2772 additions and 1376 deletions

View File

@@ -1,70 +0,0 @@
/*
* Copyright 2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cassandra.config;
import org.junit.Assert;
import org.junit.Test;
/**
* Unit tests for {@link PoolingOptionsFactoryBean}
*
* @author Sumit Kumar
* @author David Webb
*/
public class PoolingOptionsFactoryBeanUnitTest {
private static final int REMOTE_MIN_SIMULTANEOUS_REQUESTS = 111;
private static final int REMOTE_MAX_SIMULTANEOUS_REQUESTS = 127;
private static final int REMOTE_CORE_CONNECTIONS = 110;
private static final int REMOTE_MAX_CONNECTIONS = 210;
private static final int LOCAL_MIN_SIMULTANEOUS_REQUESTS = 97;
private static final int LOCAL_MAX_SIMULTANEOUS_REQUESTS = 99;
private static final int LOCAL_CORE_CONNECTIONS = 100;
private static final int LOCAL_MAX_CONNECTIONS = 200;
/**
* The max values should be set before setting core values. Otherwise the core values will be compared with the
* default max values which is 8. Same for other min-max properties pairs. This test checks the same.
*
* @throws Exception Any unhandled scenarios will result in a test failure.
* @see DATACASS-176
*/
@Test
public void testAfterPropertiesSet() throws Exception {
PoolingOptionsFactoryBean factoryBean = new PoolingOptionsFactoryBean();
factoryBean.setLocalMaxConnections(LOCAL_MAX_CONNECTIONS);
factoryBean.setLocalCoreConnections(LOCAL_CORE_CONNECTIONS);
factoryBean.setLocalMaxSimultaneousRequests(LOCAL_MAX_SIMULTANEOUS_REQUESTS);
factoryBean.setLocalMinSimultaneousRequests(LOCAL_MIN_SIMULTANEOUS_REQUESTS);
factoryBean.setRemoteMaxConnections(REMOTE_MAX_CONNECTIONS);
factoryBean.setRemoteCoreConnections(REMOTE_CORE_CONNECTIONS);
factoryBean.setRemoteMaxSimultaneousRequests(REMOTE_MAX_SIMULTANEOUS_REQUESTS);
factoryBean.setRemoteMinSimultaneousRequests(REMOTE_MIN_SIMULTANEOUS_REQUESTS);
factoryBean.afterPropertiesSet();
Assert.assertEquals(factoryBean.getLocalMaxConnections().intValue(), LOCAL_MAX_CONNECTIONS);
Assert.assertEquals(factoryBean.getLocalCoreConnections().intValue(), LOCAL_CORE_CONNECTIONS);
Assert.assertEquals(factoryBean.getLocalMaxSimultaneousRequests().intValue(), LOCAL_MAX_SIMULTANEOUS_REQUESTS);
Assert.assertEquals(factoryBean.getLocalMinSimultaneousRequests().intValue(), LOCAL_MIN_SIMULTANEOUS_REQUESTS);
Assert.assertEquals(factoryBean.getRemoteMaxConnections().intValue(), REMOTE_MAX_CONNECTIONS);
Assert.assertEquals(factoryBean.getRemoteCoreConnections().intValue(), REMOTE_CORE_CONNECTIONS);
Assert.assertEquals(factoryBean.getRemoteMaxSimultaneousRequests().intValue(), REMOTE_MAX_SIMULTANEOUS_REQUESTS);
Assert.assertEquals(factoryBean.getRemoteMinSimultaneousRequests().intValue(), REMOTE_MIN_SIMULTANEOUS_REQUESTS);
}
}

View File

@@ -0,0 +1,347 @@
/*
* Copyright 2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cassandra.config;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.anyInt;
import static org.mockito.Mockito.*;
import static org.mockito.Mockito.same;
import java.util.concurrent.Executor;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InOrder;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.runners.MockitoJUnitRunner;
import org.mockito.stubbing.Answer;
import com.datastax.driver.core.HostDistance;
import com.datastax.driver.core.PoolingOptions;
/**
* Unit tests for {@link PoolingOptionsFactoryBean}.
*
* @author Sumit Kumar
* @author David Webb
* @author John Blum
* @see org.springframework.cassandra.config.PoolingOptionsFactoryBean
* @see <a href="https://jira.spring.io/browse/DATACASS-298">DATACASS-176</a>
* @see <a href="https://jira.spring.io/browse/DATACASS-298">DATACASS-298</a>
*/
@RunWith(MockitoJUnitRunner.class)
public class PoolingOptionsFactoryBeanUnitTests {
@Mock
private Executor mockExecutor;
@Spy
private PoolingOptions poolingOptionsSpy;
private PoolingOptionsFactoryBean poolingOptionsFactoryBean;
@Before
public void setup() {
poolingOptionsFactoryBean = new PoolingOptionsFactoryBean();
}
@Test
public void getObjectReturnsNullWhenNotInitialized() throws Exception {
assertThat(poolingOptionsFactoryBean.getObject(), is(nullValue(PoolingOptions.class)));
}
@Test
@SuppressWarnings("unchecked")
public void getObjectTypeReturnsPoolingOptionsClassWhenNotInitialized() {
assertThat((Class<PoolingOptions>) poolingOptionsFactoryBean.getObjectType(), is(equalTo(PoolingOptions.class)));
}
@Test
public void isSingletonIsTrue() {
assertThat(poolingOptionsFactoryBean.isSingleton(), is(true));
}
/**
* @see <a href="https://jira.spring.io/browse/DATACASS-298">DATACASS-298</a>
*/
@Test
public void setAndGetFactoryBeanProperties() {
poolingOptionsFactoryBean.setHeartbeatIntervalSeconds(15);
poolingOptionsFactoryBean.setIdleTimeoutSeconds(120);
poolingOptionsFactoryBean.setInitializationExecutor(mockExecutor);
poolingOptionsFactoryBean.setLocalCoreConnections(50);
poolingOptionsFactoryBean.setLocalMaxConnections(1000);
poolingOptionsFactoryBean.setLocalMaxSimultaneousRequests(200);
poolingOptionsFactoryBean.setLocalMinSimultaneousRequests(100);
poolingOptionsFactoryBean.setPoolTimeoutMilliseconds(300);
poolingOptionsFactoryBean.setRemoteCoreConnections(25);
poolingOptionsFactoryBean.setRemoteMaxConnections(250);
poolingOptionsFactoryBean.setRemoteMaxSimultaneousRequests(100);
poolingOptionsFactoryBean.setRemoteMinSimultaneousRequests(50);
assertThat(poolingOptionsFactoryBean.getHeartbeatIntervalSeconds(), is(equalTo(15)));
assertThat(poolingOptionsFactoryBean.getIdleTimeoutSeconds(), is(equalTo(120)));
assertThat(poolingOptionsFactoryBean.getInitializationExecutor(), is(equalTo(mockExecutor)));
assertThat(poolingOptionsFactoryBean.getLocalCoreConnections(), is(equalTo(50)));
assertThat(poolingOptionsFactoryBean.getLocalMaxConnections(), is(equalTo(1000)));
assertThat(poolingOptionsFactoryBean.getLocalMaxSimultaneousRequests(), is(equalTo(200)));
assertThat(poolingOptionsFactoryBean.getLocalMinSimultaneousRequests(), is(equalTo(100)));
assertThat(poolingOptionsFactoryBean.getPoolTimeoutMilliseconds(), is(equalTo(300)));
assertThat(poolingOptionsFactoryBean.getRemoteCoreConnections(), is(equalTo(25)));
assertThat(poolingOptionsFactoryBean.getRemoteMaxConnections(), is(equalTo(250)));
assertThat(poolingOptionsFactoryBean.getRemoteMaxSimultaneousRequests(), is(equalTo(100)));
assertThat(poolingOptionsFactoryBean.getRemoteMinSimultaneousRequests(), is(equalTo(50)));
}
/**
* @see <a href="https://jira.spring.io/browse/DATACASS-298">DATACASS-298</a>
*/
@Test
public void afterPropertiesSetInitializesLocalPoolingOptions() throws Exception {
PoolingOptionsFactoryBean poolingOptionsFactoryBean = new PoolingOptionsFactoryBean() {
@Override PoolingOptions newPoolingOptions() {
poolingOptionsSpy.setNewConnectionThreshold(HostDistance.LOCAL, 1);
return poolingOptionsSpy;
}
};
poolingOptionsFactoryBean.setHeartbeatIntervalSeconds(60);
poolingOptionsFactoryBean.setIdleTimeoutSeconds(300);
poolingOptionsFactoryBean.setInitializationExecutor(mockExecutor);
poolingOptionsFactoryBean.setLocalCoreConnections(10);
poolingOptionsFactoryBean.setLocalMaxConnections(100);
poolingOptionsFactoryBean.setLocalMaxSimultaneousRequests(50);
poolingOptionsFactoryBean.setLocalMinSimultaneousRequests(5);
poolingOptionsFactoryBean.setPoolTimeoutMilliseconds(180);
assertThat(poolingOptionsFactoryBean.getObject(), is(nullValue(PoolingOptions.class)));
poolingOptionsFactoryBean.afterPropertiesSet();
assertThat(poolingOptionsFactoryBean.getObject(), is(sameInstance(poolingOptionsSpy)));
assertThat(poolingOptionsFactoryBean.getObjectType(), is(equalTo((Class) poolingOptionsSpy.getClass())));
verify(poolingOptionsSpy, times(1)).setHeartbeatIntervalSeconds(eq(60));
verify(poolingOptionsSpy, times(1)).setIdleTimeoutSeconds(eq(300));
verify(poolingOptionsSpy, times(1)).setInitializationExecutor(eq(mockExecutor));
verify(poolingOptionsSpy, times(1)).setPoolTimeoutMillis(eq(180));
verify(poolingOptionsSpy, times(1)).setCoreConnectionsPerHost(eq(HostDistance.LOCAL), eq(10));
verify(poolingOptionsSpy, times(1)).setMaxConnectionsPerHost(eq(HostDistance.LOCAL), eq(100));
verify(poolingOptionsSpy, times(1)).setMaxRequestsPerConnection(eq(HostDistance.LOCAL), eq(50));
verify(poolingOptionsSpy, times(1)).setNewConnectionThreshold(eq(HostDistance.LOCAL), eq(5));
verify(poolingOptionsSpy, never()).setCoreConnectionsPerHost(eq(HostDistance.REMOTE), anyInt());
verify(poolingOptionsSpy, never()).setMaxConnectionsPerHost(eq(HostDistance.REMOTE), anyInt());
verify(poolingOptionsSpy, never()).setMaxRequestsPerConnection(eq(HostDistance.REMOTE), anyInt());
verify(poolingOptionsSpy, never()).setNewConnectionThreshold(eq(HostDistance.REMOTE), anyInt());
}
/**
* @see <a href="https://jira.spring.io/browse/DATACASS-298">DATACASS-298</a>
*/
@Test
public void afterPropertiesSetInitializesRemotePoolingOptions() throws Exception {
PoolingOptionsFactoryBean poolingOptionsFactoryBean = new PoolingOptionsFactoryBean() {
@Override PoolingOptions newPoolingOptions() {
poolingOptionsSpy.setNewConnectionThreshold(HostDistance.REMOTE, 10);
return poolingOptionsSpy;
}
};
poolingOptionsFactoryBean.setHeartbeatIntervalSeconds(30);
poolingOptionsFactoryBean.setIdleTimeoutSeconds(120);
poolingOptionsFactoryBean.setInitializationExecutor(mockExecutor);
poolingOptionsFactoryBean.setPoolTimeoutMilliseconds(120);
poolingOptionsFactoryBean.setRemoteCoreConnections(5);
poolingOptionsFactoryBean.setRemoteMaxConnections(50);
poolingOptionsFactoryBean.setRemoteMaxSimultaneousRequests(20);
poolingOptionsFactoryBean.setRemoteMinSimultaneousRequests(5);
assertThat(poolingOptionsFactoryBean.getObject(), is(nullValue(PoolingOptions.class)));
poolingOptionsFactoryBean.afterPropertiesSet();
assertThat(poolingOptionsFactoryBean.getObject(), is(sameInstance(poolingOptionsSpy)));
assertThat(poolingOptionsFactoryBean.getObjectType(), is(equalTo((Class) poolingOptionsSpy.getClass())));
verify(poolingOptionsSpy, times(1)).setHeartbeatIntervalSeconds(eq(30));
verify(poolingOptionsSpy, times(1)).setIdleTimeoutSeconds(eq(120));
verify(poolingOptionsSpy, times(1)).setInitializationExecutor(eq(mockExecutor));
verify(poolingOptionsSpy, times(1)).setPoolTimeoutMillis(eq(120));
verify(poolingOptionsSpy, times(1)).setCoreConnectionsPerHost(eq(HostDistance.REMOTE), eq(5));
verify(poolingOptionsSpy, times(1)).setMaxConnectionsPerHost(eq(HostDistance.REMOTE), eq(50));
verify(poolingOptionsSpy, times(1)).setMaxRequestsPerConnection(eq(HostDistance.REMOTE), eq(20));
verify(poolingOptionsSpy, never()).setCoreConnectionsPerHost(eq(HostDistance.LOCAL), anyInt());
verify(poolingOptionsSpy, never()).setMaxConnectionsPerHost(eq(HostDistance.LOCAL), anyInt());
verify(poolingOptionsSpy, never()).setMaxRequestsPerConnection(eq(HostDistance.LOCAL), anyInt());
verify(poolingOptionsSpy, never()).setNewConnectionThreshold(eq(HostDistance.LOCAL), anyInt());
verify(poolingOptionsSpy, never()).setNewConnectionThreshold(eq(HostDistance.REMOTE), eq(5));
}
/**
* This particular test case is technically an integration test since it uses an actual instance of
* a DataStax Java driver class type... {@link PoolingOptions}!
*
* The max values should be set before setting core values. Otherwise the core values will be compared with the
* default max values which is 8. Same for other min-max properties pairs. This test checks the same.
*
* @throws Exception Any unhandled scenarios will result in a test failure.
* @see <a href="https://jira.spring.io/browse/DATACASS-176">DATACASS-176</a>
*/
@Test
public void afterPropertiesSetProperlySetsPoolingOptionsMaxBeforeMinProperties() throws Exception {
poolingOptionsFactoryBean = new PoolingOptionsFactoryBean() {
@Override PoolingOptions newPoolingOptions() {
return spy(super.newPoolingOptions());
}
};
poolingOptionsFactoryBean.setLocalMaxConnections(200);
poolingOptionsFactoryBean.setLocalCoreConnections(100);
poolingOptionsFactoryBean.setLocalMaxSimultaneousRequests(99);
poolingOptionsFactoryBean.setLocalMinSimultaneousRequests(97);
poolingOptionsFactoryBean.setRemoteMaxConnections(210);
poolingOptionsFactoryBean.setRemoteCoreConnections(110);
poolingOptionsFactoryBean.setRemoteMaxSimultaneousRequests(127);
poolingOptionsFactoryBean.setRemoteMinSimultaneousRequests(111);
assertThat(poolingOptionsFactoryBean.getObject(), is(nullValue(PoolingOptions.class)));
poolingOptionsFactoryBean.afterPropertiesSet();
PoolingOptions poolingOptions = poolingOptionsFactoryBean.getObject();
assertThat(poolingOptions, is(notNullValue(PoolingOptions.class)));
assertThat(poolingOptions.getCoreConnectionsPerHost(HostDistance.LOCAL), is(equalTo(100)));
assertThat(poolingOptions.getMaxConnectionsPerHost(HostDistance.LOCAL), is(equalTo(200)));
assertThat(poolingOptions.getMaxRequestsPerConnection(HostDistance.LOCAL), is(equalTo(99)));
assertThat(poolingOptions.getNewConnectionThreshold(HostDistance.LOCAL), is(equalTo(97)));
assertThat(poolingOptions.getCoreConnectionsPerHost(HostDistance.REMOTE), is(equalTo(110)));
assertThat(poolingOptions.getMaxConnectionsPerHost(HostDistance.REMOTE), is(equalTo(210)));
assertThat(poolingOptions.getMaxRequestsPerConnection(HostDistance.REMOTE), is(equalTo(127)));
assertThat(poolingOptions.getNewConnectionThreshold(HostDistance.REMOTE), is(equalTo(111)));
InOrder inOrder = inOrder(poolingOptions);
inOrder.verify(poolingOptions, times(1)).setMaxConnectionsPerHost(eq(HostDistance.LOCAL), eq(200));
inOrder.verify(poolingOptions, times(1)).setCoreConnectionsPerHost(eq(HostDistance.LOCAL), eq(100));
inOrder.verify(poolingOptions, times(1)).setMaxRequestsPerConnection(eq(HostDistance.LOCAL), eq(99));
inOrder.verify(poolingOptions, times(1)).setNewConnectionThreshold(eq(HostDistance.LOCAL), eq(97));
inOrder.verify(poolingOptions, times(1)).setMaxConnectionsPerHost(eq(HostDistance.REMOTE), eq(210));
inOrder.verify(poolingOptions, times(1)).setCoreConnectionsPerHost(eq(HostDistance.REMOTE), eq(110));
inOrder.verify(poolingOptions, times(1)).setMaxRequestsPerConnection(eq(HostDistance.REMOTE), eq(127));
inOrder.verify(poolingOptions, times(1)).setNewConnectionThreshold(eq(HostDistance.REMOTE), eq(111));
}
@Test
public void newLocalHostDistancePoolingOptionsReturnsLocalHostDistancePoolingOptionsFactoryBeanSettings() {
poolingOptionsFactoryBean.setLocalCoreConnections(50);
poolingOptionsFactoryBean.setLocalMaxConnections(500);
poolingOptionsFactoryBean.setLocalMaxSimultaneousRequests(1000);
poolingOptionsFactoryBean.setLocalMinSimultaneousRequests(100);
poolingOptionsFactoryBean.setRemoteCoreConnections(20);
poolingOptionsFactoryBean.setRemoteMaxConnections(200);
poolingOptionsFactoryBean.setRemoteMaxSimultaneousRequests(400);
poolingOptionsFactoryBean.setRemoteMinSimultaneousRequests(40);
PoolingOptionsFactoryBean.HostDistancePoolingOptions poolingOptions =
poolingOptionsFactoryBean.newLocalHostDistancePoolingOptions();
assertThat(poolingOptions.getHostDistance(), is(equalTo(HostDistance.LOCAL)));
assertThat(poolingOptions.getCoreConnectionsPerHost(), is(equalTo(50)));
assertThat(poolingOptions.getMaxConnectionsPerHost(), is(equalTo(500)));
assertThat(poolingOptions.getMaxRequestsPerConnection(), is(equalTo(1000)));
assertThat(poolingOptions.getNewConnectionThreshold(), is(equalTo(100)));
}
@Test
public void newLocalHostDistancePoolingOptionsReturnsRemoteHostDistancePoolingOptionsFactoryBeanSettings() {
poolingOptionsFactoryBean.setLocalCoreConnections(50);
poolingOptionsFactoryBean.setLocalMaxConnections(500);
poolingOptionsFactoryBean.setLocalMaxSimultaneousRequests(1000);
poolingOptionsFactoryBean.setLocalMinSimultaneousRequests(100);
poolingOptionsFactoryBean.setRemoteCoreConnections(20);
poolingOptionsFactoryBean.setRemoteMaxConnections(200);
poolingOptionsFactoryBean.setRemoteMaxSimultaneousRequests(400);
poolingOptionsFactoryBean.setRemoteMinSimultaneousRequests(40);
PoolingOptionsFactoryBean.HostDistancePoolingOptions poolingOptions =
poolingOptionsFactoryBean.newRemoteHostDistancePoolingOptions();
assertThat(poolingOptions.getHostDistance(), is(equalTo(HostDistance.REMOTE)));
assertThat(poolingOptions.getCoreConnectionsPerHost(), is(equalTo(20)));
assertThat(poolingOptions.getMaxConnectionsPerHost(), is(equalTo(200)));
assertThat(poolingOptions.getMaxRequestsPerConnection(), is(equalTo(400)));
assertThat(poolingOptions.getNewConnectionThreshold(), is(equalTo(40)));
}
@Test
public void configureLocalHostDistancePoolingOptionsCallsConfigureWithExpectedInstance() {
final PoolingOptionsFactoryBean.HostDistancePoolingOptions mockHostDistancePoolingOptions = mock(
PoolingOptionsFactoryBean.HostDistancePoolingOptions.class);
when(mockHostDistancePoolingOptions.configure(any(PoolingOptions.class))).thenAnswer(
new Answer<PoolingOptions>() {
@Override
public PoolingOptions answer(InvocationOnMock invocationOnMock) throws Throwable {
return invocationOnMock.getArgumentAt(0, PoolingOptions.class);
}
}
);
poolingOptionsFactoryBean = new PoolingOptionsFactoryBean() {
@Override protected HostDistancePoolingOptions newLocalHostDistancePoolingOptions() {
return mockHostDistancePoolingOptions;
}
};
assertThat(poolingOptionsFactoryBean.configureLocalHostDistancePoolingOptions(poolingOptionsSpy),
is(sameInstance(poolingOptionsSpy)));
verify(mockHostDistancePoolingOptions, times(1)).configure(same(poolingOptionsSpy));
}
@Test
public void configureRemoteHostDistancePoolingOptionsCallsConfigureWithExpectedInstance() {
final PoolingOptionsFactoryBean.HostDistancePoolingOptions mockHostDistancePoolingOptions = mock(
PoolingOptionsFactoryBean.HostDistancePoolingOptions.class);
when(mockHostDistancePoolingOptions.configure(any(PoolingOptions.class))).thenAnswer(
new Answer<PoolingOptions>() {
@Override
public PoolingOptions answer(InvocationOnMock invocationOnMock) throws Throwable {
return invocationOnMock.getArgumentAt(0, PoolingOptions.class);
}
}
);
poolingOptionsFactoryBean = new PoolingOptionsFactoryBean() {
@Override protected HostDistancePoolingOptions newRemoteHostDistancePoolingOptions() {
return mockHostDistancePoolingOptions;
}
};
assertThat(poolingOptionsFactoryBean.configureRemoteHostDistancePoolingOptions(poolingOptionsSpy),
is(sameInstance(poolingOptionsSpy)));
verify(mockHostDistancePoolingOptions, times(1)).configure(same(poolingOptionsSpy));
}
}

View File

@@ -0,0 +1,403 @@
/*
* Copyright 2013-2016 the original author or authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cassandra.config.xml;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.beans.PropertyValue;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.RuntimeBeanReference;
import org.springframework.beans.factory.parsing.PassThroughSourceExtractor;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.xml.BeanDefinitionParserDelegate;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.beans.factory.xml.XmlReaderContext;
import org.springframework.cassandra.config.CassandraCqlClusterFactoryBean;
import org.springframework.cassandra.config.PoolingOptionsFactoryBean;
import org.springframework.cassandra.config.SocketOptionsFactoryBean;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
/**
* Test suite of Unit tests testing the contract and functionality of the {@link CassandraCqlClusterParser}.
*
* @author John Blum
* @see org.springframework.cassandra.config.xml.CassandraCqlClusterParser
* @since 1.5.0
*/
// TODO add more tests!
@RunWith(MockitoJUnitRunner.class)
public class CassandraCqlClusterParserUnitTests {
@Mock
private Element mockElement;
private CassandraCqlClusterParser parser = new CassandraCqlClusterParser();
@SuppressWarnings("unchecked")
protected <T> T getPropertyValue(BeanDefinition beanDefinition, String propertyName) {
PropertyValue propertyValue = beanDefinition.getPropertyValues().getPropertyValue(propertyName);
return (T) (propertyValue != null ? propertyValue.getValue() : null);
}
protected String getPropertyValueAsString(BeanDefinition beanDefinition, String propertyName) {
Object value = getPropertyValue(beanDefinition, propertyName);
return (value instanceof RuntimeBeanReference ? ((RuntimeBeanReference) value).getBeanName()
: (value != null ? String.valueOf(value) : null));
}
protected BeanDefinitionParserDelegate mockBeanDefinitionParserDelegate(XmlReaderContext xmlReaderContext) {
return new BeanDefinitionParserDelegate(xmlReaderContext);
}
protected NodeList mockNodeList(Element... childElements) {
NodeList mockNodeList = mock(NodeList.class);
when(mockNodeList.getLength()).thenReturn(childElements.length);
for (int index = 0; index < childElements.length; index++) {
when(mockNodeList.item(eq(index))).thenReturn(childElements[index]);
}
return mockNodeList;
}
protected ParserContext mockParserContext() {
return mockParserContext(null);
}
protected ParserContext mockParserContext(BeanDefinition beanDefinition) {
XmlReaderContext readerContext = mockXmlReaderContext();
return new ParserContext(readerContext, mockBeanDefinitionParserDelegate(readerContext), beanDefinition);
}
protected XmlReaderContext mockXmlReaderContext() {
return new XmlReaderContext(null, null, null, new PassThroughSourceExtractor(), null, null);
}
@Test
public void resolveIdFromElement() {
when(mockElement.getAttribute(eq(CassandraCqlClusterParser.ID_ATTRIBUTE))).thenReturn("test");
assertThat(parser.resolveId(mockElement, null, null), is(equalTo("test")));
verify(mockElement, times(1)).getAttribute(eq(CassandraCqlClusterParser.ID_ATTRIBUTE));
}
@Test
public void resolveIdUsingDefault() {
when(mockElement.getAttribute(eq(CassandraCqlClusterParser.ID_ATTRIBUTE))).thenReturn("");
assertThat(parser.resolveId(mockElement, null, null), is(equalTo(DefaultCqlBeanNames.CLUSTER)));
verify(mockElement, times(1)).getAttribute(eq(CassandraCqlClusterParser.ID_ATTRIBUTE));
}
@Test
public void parseInternalCallsDoParseAndConstructsBeanDefinition() {
BeanDefinition mockContainingBeanDefinition = mock(BeanDefinition.class);
when(mockContainingBeanDefinition.getScope()).thenReturn("Singleton");
when(mockElement.getAttribute("auth-info-provider-ref")).thenReturn("testAuthInfoProvider");
when(mockElement.getAttribute("host-state-listener-ref")).thenReturn("testHostStateListener");
when(mockElement.getAttribute("latency-tracker-ref")).thenReturn("testLatencyTracker");
when(mockElement.getAttribute("load-balancing-policy-ref")).thenReturn("testLoadBalancingPolicy");
when(mockElement.getAttribute("reconnection-policy-ref")).thenReturn("testReconnectionPolicy");
when(mockElement.getAttribute("retry-policy-ref")).thenReturn("testRetryPolicy");
when(mockElement.getAttribute("ssl-options-ref")).thenReturn("testSslOptions");
when(mockElement.getAttribute("contact-points")).thenReturn("skullbox");
when(mockElement.getAttribute("compression")).thenReturn("SNAPPY");
when(mockElement.getAttribute("jmx-reporting-enabled")).thenReturn("true");
when(mockElement.getAttribute("metrics-enabled")).thenReturn("true");
when(mockElement.getAttribute("password")).thenReturn("p@55w0rd");
when(mockElement.getAttribute("port")).thenReturn("12345");
when(mockElement.getAttribute("ssl-enabled")).thenReturn("true");
when(mockElement.getAttribute("username")).thenReturn("jonDoe");
CassandraCqlClusterParser parser = new CassandraCqlClusterParser() {
@Override
protected void parseChildElements(Element element, ParserContext parserContext,
BeanDefinitionBuilder builder) {
}
};
AbstractBeanDefinition beanDefinition = parser.parseInternal(mockElement, mockParserContext(
mockContainingBeanDefinition));
assertThat(beanDefinition, is(notNullValue(BeanDefinition.class)));
assertThat(beanDefinition.getBeanClassName(), is(equalTo(CassandraCqlClusterFactoryBean.class.getName())));
assertThat(beanDefinition.getDestroyMethodName(), is(equalTo("destroy")));
assertThat((Element) beanDefinition.getSource(), is(equalTo(mockElement)));
assertThat(beanDefinition.isLazyInit(), is(false));
assertThat(getPropertyValueAsString(beanDefinition, "authProvider"), is(equalTo("testAuthInfoProvider")));
assertThat(getPropertyValueAsString(beanDefinition, "hostStateListener"), is(equalTo("testHostStateListener")));
assertThat(getPropertyValueAsString(beanDefinition, "latencyTracker"), is(equalTo("testLatencyTracker")));
assertThat(getPropertyValueAsString(beanDefinition, "loadBalancingPolicy"), is(equalTo("testLoadBalancingPolicy")));
assertThat(getPropertyValueAsString(beanDefinition, "reconnectionPolicy"), is(equalTo("testReconnectionPolicy")));
assertThat(getPropertyValueAsString(beanDefinition, "retryPolicy"), is(equalTo("testRetryPolicy")));
assertThat(getPropertyValueAsString(beanDefinition, "sslOptions"), is(equalTo("testSslOptions")));
assertThat(getPropertyValueAsString(beanDefinition, "contactPoints"), is(equalTo("skullbox")));
assertThat(getPropertyValueAsString(beanDefinition, "compressionType"), is(equalTo("SNAPPY")));
assertThat(getPropertyValueAsString(beanDefinition, "jmxReportingEnabled"), is(equalTo("true")));
assertThat(getPropertyValueAsString(beanDefinition, "metricsEnabled"), is(equalTo("true")));
assertThat(getPropertyValueAsString(beanDefinition, "password"), is(equalTo("p@55w0rd")));
assertThat(getPropertyValueAsString(beanDefinition, "port"), is(equalTo("12345")));
assertThat(getPropertyValueAsString(beanDefinition, "sslEnabled"), is(equalTo("true")));
assertThat(getPropertyValueAsString(beanDefinition, "username"), is(equalTo("jonDoe")));
verify(mockContainingBeanDefinition, times(1)).getScope();
verify(mockElement, times(1)).getAttribute(eq("auth-info-provider-ref"));
verify(mockElement, times(1)).getAttribute(eq("host-state-listener-ref"));
verify(mockElement, times(1)).getAttribute(eq("latency-tracker-ref"));
verify(mockElement, times(1)).getAttribute(eq("load-balancing-policy-ref"));
verify(mockElement, times(1)).getAttribute(eq("reconnection-policy-ref"));
verify(mockElement, times(1)).getAttribute(eq("retry-policy-ref"));
verify(mockElement, times(1)).getAttribute(eq("ssl-options-ref"));
verify(mockElement, times(1)).getAttribute(eq("contact-points"));
verify(mockElement, times(1)).getAttribute(eq("compression"));
verify(mockElement, times(1)).getAttribute(eq("jmx-reporting-enabled"));
verify(mockElement, times(1)).getAttribute(eq("metrics-enabled"));
verify(mockElement, times(1)).getAttribute(eq("password"));
verify(mockElement, times(1)).getAttribute(eq("port"));
verify(mockElement, times(1)).getAttribute(eq("ssl-enabled"));
verify(mockElement, times(1)).getAttribute(eq("username"));
}
@Test
public void parseChildElementsWithLocalPoolingOptions() {
Element localPoolingOptionsElement = mock(Element.class);
NodeList mockNodeList = mockNodeList(localPoolingOptionsElement);
when(localPoolingOptionsElement.getLocalName()).thenReturn("local-pooling-options");
when(localPoolingOptionsElement.getAttribute(eq("core-connections"))).thenReturn("50");
when(localPoolingOptionsElement.getAttribute(eq("max-connections"))).thenReturn("200");
when(localPoolingOptionsElement.getAttribute(eq("max-simultaneous-requests"))).thenReturn("50");
when(localPoolingOptionsElement.getAttribute(eq("min-simultaneous-requests"))).thenReturn("5");
when(mockElement.getChildNodes()).thenReturn(mockNodeList);
when(mockElement.getAttribute(eq("heartbeat-interval-seconds"))).thenReturn("15");
when(mockElement.getAttribute(eq("idle-timeout-seconds"))).thenReturn("120");
when(mockElement.getAttribute(eq("initialization-executor-ref"))).thenReturn("testExecutor");
when(mockElement.getAttribute(eq("pool-timeout-milliseconds"))).thenReturn("60000");
BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition();
parser.parseChildElements(mockElement, mockParserContext(), builder);
BeanDefinition beanDefinition = builder.getBeanDefinition();
BeanDefinition poolingOptionsBeanDefinition = getPropertyValue(beanDefinition, "poolingOptions");
assertThat(poolingOptionsBeanDefinition, is(notNullValue(BeanDefinition.class)));
assertThat(poolingOptionsBeanDefinition.getBeanClassName(), is(equalTo(PoolingOptionsFactoryBean.class.getName())));
assertThat(getPropertyValueAsString(poolingOptionsBeanDefinition, "heartbeatIntervalSeconds"), is(equalTo("15")));
assertThat(getPropertyValueAsString(poolingOptionsBeanDefinition, "idleTimeoutSeconds"), is(equalTo("120")));
assertThat(getPropertyValueAsString(poolingOptionsBeanDefinition, "initializationExecutor"), is(equalTo("testExecutor")));
assertThat(getPropertyValueAsString(poolingOptionsBeanDefinition, "poolTimeoutMilliseconds"), is(equalTo("60000")));
assertThat(getPropertyValueAsString(poolingOptionsBeanDefinition, "localCoreConnections"), is(equalTo("50")));
assertThat(getPropertyValueAsString(poolingOptionsBeanDefinition, "localMaxConnections"), is(equalTo("200")));
assertThat(getPropertyValueAsString(poolingOptionsBeanDefinition, "localMaxSimultaneousRequests"), is(equalTo("50")));
assertThat(getPropertyValueAsString(poolingOptionsBeanDefinition, "localMinSimultaneousRequests"), is(equalTo("5")));
assertThat(getPropertyValueAsString(poolingOptionsBeanDefinition, "remoteCoreConnections"), is(nullValue()));
assertThat(getPropertyValueAsString(poolingOptionsBeanDefinition, "remoteMaxConnections"), is(nullValue()));
assertThat(getPropertyValueAsString(poolingOptionsBeanDefinition, "remoteMaxSimultaneousRequests"), is(nullValue()));
assertThat(getPropertyValueAsString(poolingOptionsBeanDefinition, "remoteMinSimultaneousRequests"), is(nullValue()));
verify(mockElement, times(1)).getChildNodes();
verify(mockElement, times(1)).getAttribute(eq("heartbeat-interval-seconds"));
verify(mockElement, times(1)).getAttribute(eq("idle-timeout-seconds"));
verify(mockElement, times(1)).getAttribute(eq("initialization-executor-ref"));
verify(mockElement, times(1)).getAttribute(eq("pool-timeout-milliseconds"));
verify(localPoolingOptionsElement, times(1)).getLocalName();
verify(localPoolingOptionsElement, times(1)).getAttribute(eq("core-connections"));
verify(localPoolingOptionsElement, times(1)).getAttribute(eq("max-connections"));
verify(localPoolingOptionsElement, times(1)).getAttribute(eq("max-simultaneous-requests"));
verify(localPoolingOptionsElement, times(1)).getAttribute(eq("min-simultaneous-requests"));
}
@Test
public void parseChildElementsWithRemotePoolingOptions() {
Element localPoolingOptionsElement = mock(Element.class);
NodeList mockNodeList = mockNodeList(localPoolingOptionsElement);
when(localPoolingOptionsElement.getLocalName()).thenReturn("remote-pooling-options");
when(localPoolingOptionsElement.getAttribute(eq("core-connections"))).thenReturn("50");
when(localPoolingOptionsElement.getAttribute(eq("max-connections"))).thenReturn("200");
when(localPoolingOptionsElement.getAttribute(eq("max-simultaneous-requests"))).thenReturn("50");
when(localPoolingOptionsElement.getAttribute(eq("min-simultaneous-requests"))).thenReturn("5");
when(mockElement.getChildNodes()).thenReturn(mockNodeList);
when(mockElement.getAttribute(eq("heartbeat-interval-seconds"))).thenReturn("15");
when(mockElement.getAttribute(eq("idle-timeout-seconds"))).thenReturn("120");
when(mockElement.getAttribute(eq("initialization-executor-ref"))).thenReturn("testExecutor");
when(mockElement.getAttribute(eq("pool-timeout-milliseconds"))).thenReturn("60000");
BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition();
parser.parseChildElements(mockElement, mockParserContext(), builder);
BeanDefinition beanDefinition = builder.getBeanDefinition();
BeanDefinition poolingOptionsBeanDefinition = getPropertyValue(beanDefinition, "poolingOptions");
assertThat(poolingOptionsBeanDefinition, is(notNullValue(BeanDefinition.class)));
assertThat(poolingOptionsBeanDefinition.getBeanClassName(), is(equalTo(PoolingOptionsFactoryBean.class.getName())));
assertThat(getPropertyValueAsString(poolingOptionsBeanDefinition, "heartbeatIntervalSeconds"), is(equalTo("15")));
assertThat(getPropertyValueAsString(poolingOptionsBeanDefinition, "idleTimeoutSeconds"), is(equalTo("120")));
assertThat(getPropertyValueAsString(poolingOptionsBeanDefinition, "initializationExecutor"), is(equalTo("testExecutor")));
assertThat(getPropertyValueAsString(poolingOptionsBeanDefinition, "poolTimeoutMilliseconds"), is(equalTo("60000")));
assertThat(getPropertyValueAsString(poolingOptionsBeanDefinition, "localCoreConnections"), is(nullValue()));
assertThat(getPropertyValueAsString(poolingOptionsBeanDefinition, "localMaxConnections"), is(nullValue()));
assertThat(getPropertyValueAsString(poolingOptionsBeanDefinition, "localMaxSimultaneousRequests"), is(nullValue()));
assertThat(getPropertyValueAsString(poolingOptionsBeanDefinition, "localMinSimultaneousRequests"), is(nullValue()));
assertThat(getPropertyValueAsString(poolingOptionsBeanDefinition, "remoteCoreConnections"), is(equalTo("50")));
assertThat(getPropertyValueAsString(poolingOptionsBeanDefinition, "remoteMaxConnections"), is(equalTo("200")));
assertThat(getPropertyValueAsString(poolingOptionsBeanDefinition, "remoteMaxSimultaneousRequests"), is(equalTo(
"50")));
assertThat(getPropertyValueAsString(poolingOptionsBeanDefinition, "remoteMinSimultaneousRequests"), is(equalTo(
"5")));
verify(mockElement, times(1)).getChildNodes();
verify(mockElement, times(1)).getAttribute(eq("heartbeat-interval-seconds"));
verify(mockElement, times(1)).getAttribute(eq("idle-timeout-seconds"));
verify(mockElement, times(1)).getAttribute(eq("initialization-executor-ref"));
verify(mockElement, times(1)).getAttribute(eq("pool-timeout-milliseconds"));
verify(localPoolingOptionsElement, times(1)).getLocalName();
verify(localPoolingOptionsElement, times(1)).getAttribute(eq("core-connections"));
verify(localPoolingOptionsElement, times(1)).getAttribute(eq("max-connections"));
verify(localPoolingOptionsElement, times(1)).getAttribute(eq("max-simultaneous-requests"));
verify(localPoolingOptionsElement, times(1)).getAttribute(eq("min-simultaneous-requests"));
}
@Test
public void parseLocalPoolingOptionsProperlyConfiguresBeanDefinition() {
when(mockElement.getAttribute(eq("core-connections"))).thenReturn("50");
when(mockElement.getAttribute(eq("max-connections"))).thenReturn("200");
when(mockElement.getAttribute(eq("max-simultaneous-requests"))).thenReturn("50");
when(mockElement.getAttribute(eq("min-simultaneous-requests"))).thenReturn("5");
BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition();
parser.parseLocalPoolingOptions(mockElement, builder);
BeanDefinition beanDefinition = builder.getBeanDefinition();
assertThat(getPropertyValueAsString(beanDefinition, "heartbeatIntervalSeconds"), is(nullValue()));
assertThat(getPropertyValueAsString(beanDefinition, "idleTimeoutSeconds"), is(nullValue()));
assertThat(getPropertyValueAsString(beanDefinition, "initializationExecutor"), is(nullValue()));
assertThat(getPropertyValueAsString(beanDefinition, "poolTimeoutMilliseconds"), is(nullValue()));
assertThat(getPropertyValueAsString(beanDefinition, "localCoreConnections"), is(equalTo("50")));
assertThat(getPropertyValueAsString(beanDefinition, "localMaxConnections"), is(equalTo("200")));
assertThat(getPropertyValueAsString(beanDefinition, "localMaxSimultaneousRequests"), is(equalTo("50")));
assertThat(getPropertyValueAsString(beanDefinition, "localMinSimultaneousRequests"), is(equalTo("5")));
assertThat(getPropertyValueAsString(beanDefinition, "remoteCoreConnections"), is(nullValue()));
assertThat(getPropertyValueAsString(beanDefinition, "remoteMaxConnections"), is(nullValue()));
assertThat(getPropertyValueAsString(beanDefinition, "remoteMaxSimultaneousRequests"), is(nullValue()));
assertThat(getPropertyValueAsString(beanDefinition, "remoteMinSimultaneousRequests"), is(nullValue()));
verify(mockElement, never()).getAttribute(eq("heartbeat-interval-seconds"));
verify(mockElement, never()).getAttribute(eq("idle-timeout-seconds"));
verify(mockElement, never()).getAttribute(eq("initialization-executor-ref"));
verify(mockElement, never()).getAttribute(eq("pool-timeout-milliseconds"));
verify(mockElement, times(1)).getAttribute(eq("core-connections"));
verify(mockElement, times(1)).getAttribute(eq("max-connections"));
verify(mockElement, times(1)).getAttribute(eq("max-simultaneous-requests"));
verify(mockElement, times(1)).getAttribute(eq("min-simultaneous-requests"));
}
@Test
public void parseRemotePoolingOptionsProperlyConfiguresBeanDefinition() {
when(mockElement.getAttribute(eq("core-connections"))).thenReturn("50");
when(mockElement.getAttribute(eq("max-connections"))).thenReturn("200");
when(mockElement.getAttribute(eq("max-simultaneous-requests"))).thenReturn("50");
when(mockElement.getAttribute(eq("min-simultaneous-requests"))).thenReturn("5");
BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition();
parser.parseRemotePoolingOptions(mockElement, builder);
BeanDefinition beanDefinition = builder.getBeanDefinition();
assertThat(getPropertyValueAsString(beanDefinition, "heartbeatIntervalSeconds"), is(nullValue()));
assertThat(getPropertyValueAsString(beanDefinition, "idleTimeoutSeconds"), is(nullValue()));
assertThat(getPropertyValueAsString(beanDefinition, "initializationExecutor"), is(nullValue()));
assertThat(getPropertyValueAsString(beanDefinition, "poolTimeoutMilliseconds"), is(nullValue()));
assertThat(getPropertyValueAsString(beanDefinition, "localCoreConnections"), is(nullValue()));
assertThat(getPropertyValueAsString(beanDefinition, "localMaxConnections"), is(nullValue()));
assertThat(getPropertyValueAsString(beanDefinition, "localMaxSimultaneousRequests"), is(nullValue()));
assertThat(getPropertyValueAsString(beanDefinition, "localMinSimultaneousRequests"), is(nullValue()));
assertThat(getPropertyValueAsString(beanDefinition, "remoteCoreConnections"), is(equalTo("50")));
assertThat(getPropertyValueAsString(beanDefinition, "remoteMaxConnections"), is(equalTo("200")));
assertThat(getPropertyValueAsString(beanDefinition, "remoteMaxSimultaneousRequests"), is(equalTo("50")));
assertThat(getPropertyValueAsString(beanDefinition, "remoteMinSimultaneousRequests"), is(equalTo("5")));
verify(mockElement, never()).getAttribute(eq("heartbeat-interval-seconds"));
verify(mockElement, never()).getAttribute(eq("idle-timeout-seconds"));
verify(mockElement, never()).getAttribute(eq("initialization-executor-ref"));
verify(mockElement, never()).getAttribute(eq("pool-timeout-milliseconds"));
verify(mockElement, times(1)).getAttribute(eq("core-connections"));
verify(mockElement, times(1)).getAttribute(eq("max-connections"));
verify(mockElement, times(1)).getAttribute(eq("max-simultaneous-requests"));
verify(mockElement, times(1)).getAttribute(eq("min-simultaneous-requests"));
}
@Test
public void parseScript() {
when(mockElement.getTextContent()).thenReturn("CREATE TABLE schema.table;");
assertThat(parser.parseScript(mockElement), is(equalTo("CREATE TABLE schema.table;")));
verify(mockElement, times(1)).getTextContent();
}
@Test
public void newSocketOptionsBeanDefinitionIsProperlyInitialized() {
when(mockElement.getAttribute(eq("connect-timeout-millis"))).thenReturn("15000");
when(mockElement.getAttribute(eq("keep-alive"))).thenReturn("true");
when(mockElement.getAttribute(eq("read-timeout-millis"))).thenReturn("20000");
when(mockElement.getAttribute(eq("receive-buffer-size"))).thenReturn("32768");
when(mockElement.getAttribute(eq("reuse-address"))).thenReturn("true");
when(mockElement.getAttribute(eq("send-buffer-size"))).thenReturn("16384");
when(mockElement.getAttribute(eq("so-linger"))).thenReturn("false");
when(mockElement.getAttribute(eq("tcp-no-delay"))).thenReturn("true");
BeanDefinition beanDefinition = parser.newSocketOptionsBeanDefinition(mockElement, mockParserContext());
assertThat(beanDefinition, is(notNullValue(BeanDefinition.class)));
assertThat(beanDefinition.getBeanClassName(), is(equalTo(SocketOptionsFactoryBean.class.getName())));
assertThat((Element) beanDefinition.getSource(), is(equalTo(mockElement)));
assertThat(getPropertyValueAsString(beanDefinition, "connectTimeoutMillis"), is(equalTo("15000")));
assertThat(getPropertyValueAsString(beanDefinition, "keepAlive"), is(equalTo("true")));
assertThat(getPropertyValueAsString(beanDefinition, "readTimeoutMillis"), is(equalTo("20000")));
assertThat(getPropertyValueAsString(beanDefinition, "receiveBufferSize"), is(equalTo("32768")));
assertThat(getPropertyValueAsString(beanDefinition, "reuseAddress"), is(equalTo("true")));
assertThat(getPropertyValueAsString(beanDefinition, "sendBufferSize"), is(equalTo("16384")));
assertThat(getPropertyValueAsString(beanDefinition, "soLinger"), is(equalTo("false")));
assertThat(getPropertyValueAsString(beanDefinition, "tcpNoDelay"), is(equalTo("true")));
verify(mockElement, times(1)).getAttribute(eq("connect-timeout-millis"));
verify(mockElement, times(1)).getAttribute(eq("keep-alive"));
verify(mockElement, times(1)).getAttribute(eq("read-timeout-millis"));
verify(mockElement, times(1)).getAttribute(eq("receive-buffer-size"));
verify(mockElement, times(1)).getAttribute(eq("reuse-address"));
verify(mockElement, times(1)).getAttribute(eq("send-buffer-size"));
verify(mockElement, times(1)).getAttribute(eq("so-linger"));
verify(mockElement, times(1)).getAttribute(eq("tcp-no-delay"));
}
}

View File

@@ -0,0 +1,152 @@
/*
* Copyright 2013-2016 the original author or authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cassandra.config.xml;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.beans.PropertyValue;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.RuntimeBeanReference;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
/**
* Test suite of unit tests testing the contract and functionality of the {@link ParsingUtils} class.
*
* @author John Blum
* @see org.springframework.cassandra.config.xml.ParsingUtils
* @since 1.5.0
*/
// TODO: add more tests!
public class ParsingUtilsUnitTests {
@Rule
public ExpectedException exception = ExpectedException.none();
@SuppressWarnings("unchecked")
protected <T> T getPropertyValue(BeanDefinition beanDefinition, String propertyName) {
PropertyValue propertyValue = beanDefinition.getPropertyValues().getPropertyValue(propertyName);
return (T) (propertyValue != null ? propertyValue.getValue() : null);
}
@Test
public void addOptionalReferencePropertyUsesDefault() {
BeanDefinitionBuilder builder = ParsingUtils.addProperty(BeanDefinitionBuilder.genericBeanDefinition(),
"referenceProperty", null, "defaultBeanReference", false, true);
RuntimeBeanReference propertyValue = getPropertyValue(builder.getBeanDefinition(), "referenceProperty");
assertThat(propertyValue, is(notNullValue(RuntimeBeanReference.class)));
assertThat(propertyValue.getBeanName(), is(equalTo("defaultBeanReference")));
}
@Test
public void addOptionalReferencePropertyWithNoValueDoesReturnsWithoutAdding() {
BeanDefinitionBuilder builder = ParsingUtils.addProperty(BeanDefinitionBuilder.genericBeanDefinition(),
"referenceProperty", null, null, false, false);
BeanDefinition beanDefinition = builder.getRawBeanDefinition();
assertThat(beanDefinition.getPropertyValues().contains("referenceProperty"), is(false));
assertThat(beanDefinition.getPropertyValues().isEmpty(), is(true));
}
@Test
public void addOptionalValuePropertyUsesDefault() {
BeanDefinitionBuilder builder = ParsingUtils.addProperty(BeanDefinitionBuilder.genericBeanDefinition(),
"valueProperty", null, "defaultValue", false, false);
String propertyValue = getPropertyValue(builder.getBeanDefinition(), "valueProperty");
assertThat(propertyValue, is(equalTo("defaultValue")));
}
@Test
public void addOptionalValuePropertyWithNoValueDoesReturnsWithoutAdding() {
BeanDefinitionBuilder builder = ParsingUtils.addProperty(BeanDefinitionBuilder.genericBeanDefinition(),
"valueProperty", null, null, false, false);
BeanDefinition beanDefinition = builder.getRawBeanDefinition();
assertThat(beanDefinition.getPropertyValues().contains("valueProperty"), is(false));
assertThat(beanDefinition.getPropertyValues().isEmpty(), is(true));
}
@Test
public void addRequiredReferencePropertyIsSuccessful() {
BeanDefinitionBuilder builder = ParsingUtils.addProperty(BeanDefinitionBuilder.genericBeanDefinition(),
"referenceProperty", "reference", null, true, true);
RuntimeBeanReference propertyValue = getPropertyValue(builder.getBeanDefinition(), "referenceProperty");
assertThat(propertyValue, is(notNullValue(RuntimeBeanReference.class)));
assertThat(propertyValue.getBeanName(), is(equalTo("reference")));
}
@Test
public void addRequiredReferencePropertyWithNoReferenceFails() {
exception.expect(IllegalArgumentException.class);
exception.expectCause(is(nullValue(Throwable.class)));
exception.expectMessage("value required for property reference [referenceProperty] on class [null]");
ParsingUtils.addProperty(BeanDefinitionBuilder.genericBeanDefinition(), "referenceProperty", null,
"defaultReference", true, true);
}
@Test
public void addRequiredValuePropertyIsSuccessful() {
BeanDefinitionBuilder builder = ParsingUtils.addProperty(BeanDefinitionBuilder.genericBeanDefinition(),
"valueProperty", "value", null, true, false);
String propertyValue = getPropertyValue(builder.getBeanDefinition(), "valueProperty");
assertThat(propertyValue, is(equalTo("value")));
}
@Test
public void addRequiredValuePropertyWithNoValueFails() {
exception.expect(IllegalArgumentException.class);
exception.expectCause(is(nullValue(Throwable.class)));
exception.expectMessage("value required for property [valueProperty] on class [null]");
ParsingUtils.addProperty(BeanDefinitionBuilder.genericBeanDefinition(), "valueProperty", null,
"defaultValue", true, false);
}
@Test
public void addPropertyThrowsIllegalArgumentExceptionForNullBuilder() {
exception.expect(IllegalArgumentException.class);
exception.expectCause(is(nullValue(Throwable.class)));
exception.expectMessage("BeanDefinitionBuilder must not be null");
ParsingUtils.addProperty(null, "propertyName", "value", "defaultValue", false, false);
}
@Test
public void addPropertyThrowsIllegalArgumentExceptionForNullPropertyName() {
exception.expect(IllegalArgumentException.class);
exception.expectCause(is(nullValue(Throwable.class)));
exception.expectMessage("Property name must not be null");
ParsingUtils.addProperty(BeanDefinitionBuilder.genericBeanDefinition(), null, "value", "defaultValue",
false, true);
}
}

View File

@@ -15,36 +15,45 @@
*/
package org.springframework.cassandra.test.integration.config.xml;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.springframework.cassandra.core.keyspace.DropKeyspaceSpecification.*;
import javax.inject.Inject;
import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cassandra.core.CqlOperations;
import org.springframework.cassandra.test.integration.AbstractEmbeddedCassandraIntegrationTest;
import org.springframework.cassandra.test.integration.config.IntegrationTestUtils;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.HostDistance;
import com.datastax.driver.core.PoolingOptions;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.SocketOptions;
/**
* @author Mark Paluch
* @author John Blum
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@SuppressWarnings("unused")
public class PropertyPlaceholderNamespaceCreatingXmlConfigIntegrationTests
extends AbstractEmbeddedCassandraIntegrationTest {
@Inject private Session session;
@Autowired
private Cluster cassandraCluster;
@Inject private CqlOperations ops;
@Autowired
private CqlOperations ops;
@Autowired
private Session session;
@Test
public void test() {
public void keyspaceExists() {
IntegrationTestUtils.assertSession(session);
IntegrationTestUtils.assertKeyspaceExists("ppncxct", session);
@@ -52,9 +61,38 @@ public class PropertyPlaceholderNamespaceCreatingXmlConfigIntegrationTests
assertNotNull(ops);
}
@After
public void tearDown() throws Exception {
dropKeyspace("ppncxct");
dropKeyspace("foo123");
@Test
public void localAndRemotePoolingOptionsWereConfiguredProperly() {
PoolingOptions poolingOptions = cassandraCluster.getConfiguration().getPoolingOptions();
assertThat(poolingOptions, is(notNullValue(PoolingOptions.class)));
assertThat(poolingOptions.getHeartbeatIntervalSeconds(), is(equalTo(60)));
assertThat(poolingOptions.getIdleTimeoutSeconds(), is(equalTo(180)));
assertThat(poolingOptions.getPoolTimeoutMillis(), is(equalTo(30000)));
assertThat(poolingOptions.getCoreConnectionsPerHost(HostDistance.LOCAL), is(equalTo(4)));
assertThat(poolingOptions.getMaxConnectionsPerHost(HostDistance.LOCAL), is(equalTo(8)));
assertThat(poolingOptions.getMaxRequestsPerConnection(HostDistance.LOCAL), is(equalTo(20)));
assertThat(poolingOptions.getNewConnectionThreshold(HostDistance.LOCAL), is(equalTo(10)));
assertThat(poolingOptions.getCoreConnectionsPerHost(HostDistance.REMOTE), is(equalTo(2)));
assertThat(poolingOptions.getMaxConnectionsPerHost(HostDistance.REMOTE), is(equalTo(4)));
assertThat(poolingOptions.getMaxRequestsPerConnection(HostDistance.REMOTE), is(equalTo(10)));
assertThat(poolingOptions.getNewConnectionThreshold(HostDistance.REMOTE), is(equalTo(5)));
}
@Test
public void socketOptionsWereConfiguredProperly() {
SocketOptions socketOptions = cassandraCluster.getConfiguration().getSocketOptions();
assertThat(socketOptions, is(notNullValue(SocketOptions.class)));
assertThat(socketOptions.getConnectTimeoutMillis(), is(equalTo(15000)));
assertThat(socketOptions.getKeepAlive(), is(true));
assertThat(socketOptions.getReadTimeoutMillis(), is(equalTo(60000)));
assertThat(socketOptions.getReceiveBufferSize(), is(equalTo(1024)));
assertThat(socketOptions.getReuseAddress(), is(true));
assertThat(socketOptions.getSendBufferSize(), is(equalTo(2048)));
assertThat(socketOptions.getSoLinger(), is(equalTo(5)));
assertThat(socketOptions.getTcpNoDelay(), is(false));
}
}

View File

@@ -15,6 +15,11 @@
*/
package org.springframework.cassandra.test.integration.config.xml;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import java.util.concurrent.Executor;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
@@ -25,36 +30,91 @@ import org.springframework.cassandra.test.integration.config.IntegrationTestUtil
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.HostDistance;
import com.datastax.driver.core.PoolingOptions;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.SocketOptions;
/**
* Test XML namespace configuration using the spring-cql-1.0.xsd.
*
* @author Matthews T. Adams
* @author Oliver Gierke
* @author Mark Paluch
* @author John Blum
*/
@SuppressWarnings("unused")
public class XmlConfigIntegrationTests extends AbstractEmbeddedCassandraIntegrationTest {
public static final String KEYSPACE = "xmlconfigtest";
@Rule public KeyspaceRule keyspaceRule = new KeyspaceRule(cassandraEnvironment, KEYSPACE);
@Rule
public KeyspaceRule keyspaceRule = new KeyspaceRule(cassandraEnvironment, KEYSPACE);
private ConfigurableApplicationContext applicationContext;
private Cluster cluster;
private Executor executor;
private Session session;
private ConfigurableApplicationContext context;
@Before
public void setUp() {
this.applicationContext = new ClassPathXmlApplicationContext(
"XmlConfigIntegrationTests-context.xml", getClass());
this.context = new ClassPathXmlApplicationContext("XmlConfigIntegrationTests-context.xml", getClass());
this.session = context.getBean(Session.class);
this.cluster = applicationContext.getBean(Cluster.class);
this.executor = applicationContext.getBean(Executor.class);
this.session = applicationContext.getBean(Session.class);
}
@After
public void tearDown() {
context.close();
if (this.applicationContext != null) {
this.applicationContext.close();
}
}
@Test
public void test() {
public void keyspaceExists() {
IntegrationTestUtils.assertKeyspaceExists(KEYSPACE, session);
}
@Test
public void localAndRemotePoolingOptionsWereConfiguredProperly() {
PoolingOptions poolingOptions = cluster.getConfiguration().getPoolingOptions();
assertThat(poolingOptions, is(notNullValue(PoolingOptions.class)));
assertThat(poolingOptions.getHeartbeatIntervalSeconds(), is(equalTo(60)));
assertThat(poolingOptions.getIdleTimeoutSeconds(), is(equalTo(300)));
assertThat(poolingOptions.getInitializationExecutor(), is(equalTo(executor)));
assertThat(poolingOptions.getPoolTimeoutMillis(), is(equalTo(15000)));
assertThat(poolingOptions.getCoreConnectionsPerHost(HostDistance.LOCAL), is(equalTo(2)));
assertThat(poolingOptions.getMaxConnectionsPerHost(HostDistance.LOCAL), is(equalTo(8)));
assertThat(poolingOptions.getMaxRequestsPerConnection(HostDistance.LOCAL), is(equalTo(100)));
assertThat(poolingOptions.getNewConnectionThreshold(HostDistance.LOCAL), is(equalTo(25)));
assertThat(poolingOptions.getCoreConnectionsPerHost(HostDistance.REMOTE), is(equalTo(1)));
assertThat(poolingOptions.getMaxConnectionsPerHost(HostDistance.REMOTE), is(equalTo(2)));
assertThat(poolingOptions.getMaxRequestsPerConnection(HostDistance.REMOTE), is(equalTo(100)));
assertThat(poolingOptions.getNewConnectionThreshold(HostDistance.REMOTE), is(equalTo(25)));
}
@Test
public void socketOptionsWereConfiguredProperly() {
SocketOptions socketOptions = cluster.getConfiguration().getSocketOptions();
assertThat(socketOptions, is(notNullValue(SocketOptions.class)));
assertThat(socketOptions.getConnectTimeoutMillis(), is(equalTo(5000)));
assertThat(socketOptions.getKeepAlive(), is(true));
assertThat(socketOptions.getReadTimeoutMillis(), is(equalTo(60000)));
assertThat(socketOptions.getReceiveBufferSize(), is(equalTo(65536)));
assertThat(socketOptions.getReuseAddress(), is(true));
assertThat(socketOptions.getSendBufferSize(), is(equalTo(65536)));
assertThat(socketOptions.getSoLinger(), is(equalTo(60)));
assertThat(socketOptions.getTcpNoDelay(), is(true));
}
}