DATACASS-80 - renamed module spring-cassandra -> spring-cql, xml namespace from .../cassandra -> .../cql, + classes

This commit is contained in:
Matthew Adams
2014-02-26 16:44:34 -06:00
parent 14c7a8534e
commit 97d55bcc7a
215 changed files with 146 additions and 312 deletions

View File

@@ -0,0 +1,95 @@
/*
* Copyright 2013-2014 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.test.integration;
import java.io.IOException;
import java.util.UUID;
import org.apache.cassandra.exceptions.ConfigurationException;
import org.apache.thrift.transport.TTransportException;
import org.cassandraunit.utils.EmbeddedCassandraServerHelper;
import org.junit.BeforeClass;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cassandra.test.integration.support.SpringCqlBuildProperties;
import org.springframework.cassandra.test.unit.support.Utils;
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.Session;
/**
* Abstract base integration test class that starts an embedded Cassandra instance.
*
* @author Matthew T. Adams
*/
public class AbstractEmbeddedCassandraIntegrationTest {
public static String uuid() {
return UUID.randomUUID().toString();
}
static Logger log = LoggerFactory.getLogger(AbstractEmbeddedCassandraIntegrationTest.class);
protected static String CASSANDRA_CONFIG = "spring-cassandra.yaml";
protected static String CASSANDRA_HOST = "localhost";
protected static SpringCqlBuildProperties PROPS = new SpringCqlBuildProperties();
protected static int CASSANDRA_NATIVE_PORT = PROPS.getCassandraPort();
/**
* The session connected to the system keyspace.
*/
protected static Session SYSTEM;
/**
* The {@link Cluster} that's connected to Cassandra.
*/
protected static Cluster CLUSTER;
public static String randomKeyspaceName() {
return Utils.randomKeyspaceName();
}
@BeforeClass
public static void startCassandra() throws ConfigurationException, TTransportException, IOException,
InterruptedException {
EmbeddedCassandraServerHelper.startEmbeddedCassandra(CASSANDRA_CONFIG);
}
public static Cluster cluster() {
return Cluster.builder().addContactPoint(CASSANDRA_HOST).withPort(CASSANDRA_NATIVE_PORT).build();
}
/**
* Ensures that the cluster is created and that the session {@link #SYSTEM} is connected to it.
*/
public static void ensureClusterConnection() {
// check cluster
if (CLUSTER == null) {
CLUSTER = cluster();
}
// check system session connected
if (SYSTEM == null) {
SYSTEM = CLUSTER.connect();
}
}
public AbstractEmbeddedCassandraIntegrationTest() {
ensureClusterConnection();
}
}

View File

@@ -0,0 +1,124 @@
/*
* Copyright 2013-2014 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.test.integration;
import org.junit.After;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import com.datastax.driver.core.KeyspaceMetadata;
import com.datastax.driver.core.Session;
/**
* Abstract base integration test class that creates a keyspace
*
* @author Matthew T. Adams
*/
public abstract class AbstractKeyspaceCreatingIntegrationTest extends AbstractEmbeddedCassandraIntegrationTest {
static Logger log = LoggerFactory.getLogger(AbstractKeyspaceCreatingIntegrationTest.class);
/**
* The session that's connected to the keyspace used in the current instance's test.
*/
protected static Session SESSION;
/**
* The name of the keyspace to use for this test instance.
*/
protected String keyspace;
public AbstractKeyspaceCreatingIntegrationTest() {
this(randomKeyspaceName());
}
public AbstractKeyspaceCreatingIntegrationTest(String keyspace) {
this.keyspace = keyspace;
ensureKeyspaceAndSession();
}
/**
* Returns whether we're currently connected to the keyspace.
*/
public static boolean connected() {
return SESSION != null;
}
/**
* Whether to drop the keyspace that was created after the test has completed. Subclasses should override and return
* true, since this default implementation returns false.
*/
public boolean dropKeyspaceAfterTest() {
return false;
}
public void ensureKeyspaceAndSession() {
// ensure that test keyspace exists
if (!StringUtils.hasText(keyspace)) {
keyspace = null;
}
if (keyspace != null) {
// see if we need to create the keyspace
KeyspaceMetadata kmd = CLUSTER.getMetadata().getKeyspace(keyspace);
if (kmd == null) { // then create keyspace
String cql = "CREATE KEYSPACE " + keyspace
+ " WITH replication = {'class': 'SimpleStrategy', 'replication_factor' : 1};";
log.info("creating keyspace {} via CQL [{}]", keyspace, cql);
SYSTEM.execute(cql);
}
}
// keyspace now exists; ensure the session is using it
if (SESSION == null) {
log.info("connecting to keyspace {}", keyspace == null ? "system" : keyspace + "...");
SESSION = keyspace == null ? CLUSTER.connect() : CLUSTER.connect(keyspace);
log.info("connected to keyspace {}", keyspace == null ? "system" : keyspace);
} else {
log.info("session already connected to a keyspace; attempting to change to use {}", keyspace);
String cql = "USE " + (keyspace == null ? "system" : keyspace) + ";";
SESSION.execute(cql);
log.info("now using keyspace " + keyspace);
}
}
@After
public void after() {
if (dropKeyspaceAfterTest() && keyspace != null) {
SESSION.execute("USE system");
log.info("dropping keyspace {} ...", keyspace);
SYSTEM.execute("DROP KEYSPACE " + keyspace);
log.info("dropped keyspace {}", keyspace);
}
}
}

View File

@@ -0,0 +1,37 @@
/*
* Copyright 2013-2014 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.test.integration.config;
import static org.junit.Assert.assertNotNull;
import org.springframework.cassandra.core.CqlTemplate;
import com.datastax.driver.core.Session;
public class IntegrationTestUtils {
public static void assertCqlTemplate(CqlTemplate cqlTemplate) {
assertNotNull(cqlTemplate);
}
public static void assertSession(Session session) {
assertNotNull(session);
}
public static void assertKeyspaceExists(String keyspace, Session session) {
assertNotNull(session.getCluster().getMetadata().getKeyspace(keyspace));
}
}

View File

@@ -0,0 +1,38 @@
/*
* Copyright 2013-2014 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.test.integration.config.java;
import javax.inject.Inject;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.springframework.cassandra.test.integration.AbstractEmbeddedCassandraIntegrationTest;
import org.springframework.cassandra.test.integration.config.IntegrationTestUtils;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.datastax.driver.core.Session;
@RunWith(SpringJUnit4ClassRunner.class)
public abstract class AbstractIntegrationTest extends AbstractEmbeddedCassandraIntegrationTest {
@Inject
protected Session session;
@Before
public void assertSession() {
IntegrationTestUtils.assertSession(session);
}
}

View File

@@ -0,0 +1,55 @@
/*
* Copyright 2013-2014 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.test.integration.config.java;
import static org.springframework.cassandra.core.cql.generator.CreateKeyspaceCqlGenerator.toCql;
import static org.springframework.cassandra.core.keyspace.CreateKeyspaceSpecification.createKeyspace;
import org.springframework.cassandra.config.CassandraCqlSessionFactoryBean;
import org.springframework.cassandra.config.java.AbstractSessionConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import com.datastax.driver.core.KeyspaceMetadata;
import com.datastax.driver.core.Session;
@Configuration
public abstract class AbstractKeyspaceCreatingConfiguration extends AbstractSessionConfiguration {
@Override
public CassandraCqlSessionFactoryBean session() throws Exception {
createKeyspaceIfNecessary();
return super.session();
}
protected void createKeyspaceIfNecessary() throws Exception {
String keyspace = getKeyspaceName();
if (!StringUtils.hasText(keyspace)) {
return;
}
Session system = cluster().getObject().connect();
KeyspaceMetadata kmd = system.getCluster().getMetadata().getKeyspace(keyspace);
if (kmd != null) {
return;
}
system.execute(toCql(createKeyspace().name(keyspace).withSimpleReplication()));
system.shutdown();
}
}

View File

@@ -0,0 +1,28 @@
/*
* Copyright 2013-2014 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.test.integration.config.java;
import org.springframework.context.annotation.Configuration;
import org.springframework.cassandra.test.integration.support.AbstractTestJavaConfig;
@Configuration
public class Config extends AbstractTestJavaConfig {
@Override
protected String getKeyspaceName() {
return null;
}
}

View File

@@ -0,0 +1,30 @@
/*
* Copyright 2013-2014 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.test.integration.config.java;
import org.junit.Test;
import org.springframework.test.context.ContextConfiguration;
@ContextConfiguration(classes = Config.class)
public class ConfigTest extends AbstractIntegrationTest {
@Test
public void test() {
session
.execute("CREATE KEYSPACE ConfigTest WITH REPLICATION = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 };");
session.execute("USE ConfigTest");
}
}

View File

@@ -0,0 +1,46 @@
package org.springframework.cassandra.test.integration.config.java;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cassandra.config.java.AbstractCqlTemplateConfiguration;
import org.springframework.cassandra.core.CqlTemplate;
import org.springframework.cassandra.test.integration.AbstractKeyspaceCreatingIntegrationTest;
import org.springframework.cassandra.test.integration.config.IntegrationTestUtils;
import org.springframework.cassandra.test.unit.support.Utils;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class CqlTemplateConfigIntegrationTest extends AbstractKeyspaceCreatingIntegrationTest {
public static final String KEYSPACE_NAME = Utils.randomKeyspaceName();
@Configuration
public static class Config extends AbstractCqlTemplateConfiguration {
@Override
protected String getKeyspaceName() {
return KEYSPACE_NAME;
}
@Override
protected int getPort() {
return CASSANDRA_NATIVE_PORT;
}
}
@Autowired
CqlTemplate template;
public CqlTemplateConfigIntegrationTest() {
super(KEYSPACE_NAME);
}
@Test
public void test() {
IntegrationTestUtils.assertCqlTemplate(template);
}
}

View File

@@ -0,0 +1,47 @@
/*
* Copyright 2013-2014 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.test.integration.config.java;
import java.util.ArrayList;
import java.util.List;
import org.springframework.cassandra.config.KeyspaceAttributes;
import org.springframework.cassandra.core.keyspace.CreateKeyspaceSpecification;
import org.springframework.cassandra.core.keyspace.KeyspaceOption;
import org.springframework.cassandra.test.integration.support.AbstractTestJavaConfig;
import org.springframework.context.annotation.Configuration;
@Configuration
public class KeyspaceCreatingJavaConfig extends AbstractTestJavaConfig {
public static final String KEYSPACE_NAME = "foo";
@Override
protected String getKeyspaceName() {
return KEYSPACE_NAME;
}
@Override
protected List<CreateKeyspaceSpecification> getKeyspaceCreations() {
ArrayList<CreateKeyspaceSpecification> list = new ArrayList<CreateKeyspaceSpecification>();
CreateKeyspaceSpecification specification = CreateKeyspaceSpecification.createKeyspace().name(getKeyspaceName());
specification.with(KeyspaceOption.REPLICATION, KeyspaceAttributes.newSimpleReplication(1L));
list.add(specification);
return list;
}
}

View File

@@ -0,0 +1,31 @@
/*
* Copyright 2013-2014 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.test.integration.config.java;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.cassandra.test.integration.config.IntegrationTestUtils;
import org.springframework.test.context.ContextConfiguration;
@ContextConfiguration(classes = KeyspaceCreatingJavaConfig.class)
public class KeyspaceCreatingJavaConfigTest extends AbstractIntegrationTest {
@Test
public void test() {
Assert.assertNotNull(session);
IntegrationTestUtils.assertKeyspaceExists(KeyspaceCreatingJavaConfig.KEYSPACE_NAME, session);
}
}

View File

@@ -0,0 +1,43 @@
/*
* Copyright 2013-2014 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.test.integration.config.xml;
import javax.inject.Inject;
import org.junit.Test;
import org.junit.runner.RunWith;
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.Session;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class FullySpecifiedKeyspaceCreatingXmlConfigTest extends AbstractEmbeddedCassandraIntegrationTest {
@Inject
Session s;
@Test
public void test() {
IntegrationTestUtils.assertKeyspaceExists("full1", s);
IntegrationTestUtils.assertKeyspaceExists("full2", s);
IntegrationTestUtils.assertKeyspaceExists("script1", s);
IntegrationTestUtils.assertKeyspaceExists("script2", s);
}
}

View File

@@ -0,0 +1,40 @@
/*
* Copyright 2013-2014 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.test.integration.config.xml;
import javax.inject.Inject;
import org.junit.Test;
import org.junit.runner.RunWith;
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.Session;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class MinimalKeyspaceCreatingXmlConfigTest extends AbstractEmbeddedCassandraIntegrationTest {
@Inject
Session s;
@Test
public void test() {
IntegrationTestUtils.assertKeyspaceExists("minimal", s);
}
}

View File

@@ -0,0 +1,55 @@
/*
* Copyright 2013-2014 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.test.integration.config.xml;
import static org.junit.Assert.assertNotNull;
import javax.inject.Inject;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.cassandra.core.CqlOperations;
import org.springframework.cassandra.test.integration.AbstractKeyspaceCreatingIntegrationTest;
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.Session;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class MinimalXmlConfigTest extends AbstractKeyspaceCreatingIntegrationTest {
public static final String KEYSPACE = "minimalxmlconfigtest";
public MinimalXmlConfigTest() {
super(KEYSPACE);
}
@Inject
Session s;
@Inject
CqlOperations ops;
@Test
public void test() {
IntegrationTestUtils.assertSession(s);
IntegrationTestUtils.assertKeyspaceExists(KEYSPACE, s);
assertNotNull(ops);
}
}

View File

@@ -0,0 +1,51 @@
/*
* Copyright 2013-2014 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.test.integration.config.xml;
import static org.junit.Assert.assertNotNull;
import javax.inject.Inject;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.cassandra.core.CqlOperations;
import org.springframework.cassandra.test.integration.AbstractKeyspaceCreatingIntegrationTest;
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.Session;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class PropertyPlaceholderNamespaceCreatingXmlConfigTest extends AbstractKeyspaceCreatingIntegrationTest {
@Inject
Session s;
@Inject
CqlOperations ops;
@Test
public void test() {
IntegrationTestUtils.assertSession(s);
IntegrationTestUtils.assertKeyspaceExists("ppncxct", s);
assertNotNull(ops);
}
}

View File

@@ -0,0 +1,52 @@
/*
* Copyright 2013-2014 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.test.integration.config.xml;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.datastax.driver.core.Host;
import com.datastax.driver.core.Host.StateListener;
/**
* @author David Webb
*
*/
public class TestHostStateListener implements StateListener {
private final static Logger log = LoggerFactory.getLogger(TestHostStateListener.class);
@Override
public void onAdd(Host host) {
log.info("Host Added: " + host.getAddress());
}
@Override
public void onUp(Host host) {
log.info("Host Up: " + host.getAddress());
}
@Override
public void onDown(Host host) {
log.info("Host Down: " + host.getAddress());
}
@Override
public void onRemove(Host host) {
log.info("Host Removed: " + host.getAddress());
}
}

View File

@@ -0,0 +1,37 @@
/*
* Copyright 2013-2014 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.test.integration.config.xml;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.datastax.driver.core.Host;
import com.datastax.driver.core.LatencyTracker;
/**
* @author David Webb
*
*/
public class TestLatencyTracker implements LatencyTracker {
private final static Logger log = LoggerFactory.getLogger(TestLatencyTracker.class);
@Override
public void update(Host host, long newLatencyNanos) {
log.info("Latency Tracker: " + host.getAddress() + ", " + newLatencyNanos + " nanoseconds.");
}
}

View File

@@ -0,0 +1,47 @@
/*
* Copyright 2013-2014 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.test.integration.config.xml;
import javax.inject.Inject;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.cassandra.test.integration.AbstractKeyspaceCreatingIntegrationTest;
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.Session;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:/org/springframework/cassandra/test/integration/config/xml/XmlConfigTest-context.xml")
public class XmlConfigTest extends AbstractKeyspaceCreatingIntegrationTest {
public static final String KEYSPACE = "xmlconfigtest";
@Inject
Session s;
public XmlConfigTest() {
super(KEYSPACE);
}
@Test
public void test() {
IntegrationTestUtils.assertSession(s);
IntegrationTestUtils.assertKeyspaceExists(KEYSPACE, s);
}
}

View File

@@ -0,0 +1,43 @@
/*
* Copyright 2013-2014 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.test.integration.core.cql.generator;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import org.springframework.cassandra.core.keyspace.IndexDescriptor;
import com.datastax.driver.core.ColumnMetadata.IndexMetadata;
import com.datastax.driver.core.Session;
public class CqlIndexSpecificationAssertions {
public static double DELTA = 1e-6; // delta for comparisons of doubles
public static void assertIndex(IndexDescriptor expected, String keyspace, Session session) {
IndexMetadata imd = session.getCluster().getMetadata().getKeyspace(keyspace.toLowerCase())
.getTable(expected.getTableName().toCql()).getColumn(expected.getColumnName().toCql()).getIndex();
assertEquals(expected.getName(), imd.getName());
}
public static void assertNoIndex(IndexDescriptor expected, String keyspace, Session session) {
IndexMetadata imd = session.getCluster().getMetadata().getKeyspace(keyspace.toLowerCase())
.getTable(expected.getTableName().toCql()).getColumn(expected.getColumnName().toCql()).getIndex();
assertNull(imd);
}
}

View File

@@ -0,0 +1,50 @@
/*
* Copyright 2013-2014 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.test.integration.core.cql.generator;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.Map;
import org.springframework.cassandra.core.keyspace.KeyspaceDescriptor;
import org.springframework.cassandra.core.keyspace.Option;
import com.datastax.driver.core.KeyspaceMetadata;
import com.datastax.driver.core.Session;
public class CqlKeyspaceSpecificationAssertions {
public static double DELTA = 1e-6; // delta for comparisons of doubles
@SuppressWarnings("unchecked")
public static void assertKeyspace(KeyspaceDescriptor expected, String keyspace, Session session) {
KeyspaceMetadata kmd = session.getCluster().getMetadata().getKeyspace(keyspace.toLowerCase());
assertEquals(expected.getName(), kmd.getName());
Map<String, String> options = kmd.getReplication();
Map<String, Object> expectedOptions = expected.getOptions();
Map<Option, Object> replicationMap = (Map<Option, Object>) expectedOptions.get("replication");
assertEquals(replicationMap.size(), options.size());
for (Map.Entry<Option, Object> optionEntry : replicationMap.entrySet()) {
String optionValue = options.get(optionEntry.getKey().getName());
String repMapValue = "" + optionEntry.getValue();
assertTrue(optionValue.endsWith(repMapValue));
}
}
}

View File

@@ -0,0 +1,177 @@
/*
* Copyright 2013-2014 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.test.integration.core.cql.generator;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cassandra.core.cql.CqlStringUtils;
import org.springframework.cassandra.core.keyspace.ColumnSpecification;
import org.springframework.cassandra.core.keyspace.DropTableSpecification;
import org.springframework.cassandra.core.keyspace.TableDescriptor;
import org.springframework.cassandra.core.keyspace.TableOption;
import com.datastax.driver.core.ColumnMetadata;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.TableMetadata;
import com.datastax.driver.core.TableMetadata.Options;
public class CqlTableSpecificationAssertions {
private final static Logger log = LoggerFactory.getLogger(CqlTableSpecificationAssertions.class);
public static double DELTA = 1e-6; // delta for comparisons of doubles
public static void assertTable(TableDescriptor expected, String keyspace, Session session) {
TableMetadata tmd = session.getCluster().getMetadata().getKeyspace(keyspace.toLowerCase())
.getTable(expected.getName().getUnquoted()); // TODO: talk to Datastax about unquoting
assertEquals(expected.getName().getUnquoted(), tmd.getName()); // TODO: talk to Datastax
assertPartitionKeyColumns(expected, tmd);
assertPrimaryKeyColumns(expected, tmd);
assertColumns(expected.getColumns(), tmd.getColumns());
assertOptions(expected.getOptions(), tmd.getOptions());
}
public static void assertNoTable(DropTableSpecification expected, String keyspace, Session session) {
TableMetadata tmd = session.getCluster().getMetadata().getKeyspace(keyspace.toLowerCase())
.getTable(expected.getName().toCql());
assertNull(tmd);
}
public static void assertPartitionKeyColumns(TableDescriptor expected, TableMetadata actual) {
assertColumns(expected.getPartitionKeyColumns(), actual.getPartitionKey());
}
public static void assertPrimaryKeyColumns(TableDescriptor expected, TableMetadata actual) {
assertColumns(expected.getPrimaryKeyColumns(), actual.getPrimaryKey());
}
public static void assertOptions(Map<String, Object> expected, Options actual) {
for (String key : expected.keySet()) {
log.info(key + " -> " + expected.get(key));
Object value = expected.get(key);
TableOption tableOption = getTableOptionFor(key.toUpperCase());
if (tableOption == null && key.equalsIgnoreCase(TableOption.COMPACT_STORAGE.getName())) {
// TODO: figure out how to tell if COMPACT STORAGE was used
continue;
}
assertOption(tableOption, key, value, getOptionFor(tableOption, tableOption.getType(), actual));
}
}
@SuppressWarnings({ "unchecked", "incomplete-switch" })
public static void assertOption(TableOption tableOption, String key, Object expected, Object actual) {
if (tableOption == null) { // then this is a string-only or unknown value
key.equalsIgnoreCase(actual.toString()); // TODO: determine if this is the right test
}
switch (tableOption) {
case BLOOM_FILTER_FP_CHANCE:
case READ_REPAIR_CHANCE:
case DCLOCAL_READ_REPAIR_CHANCE:
assertEquals((Double) expected, (Double) actual, DELTA);
return;
case CACHING:
assertEquals(((String) expected).toUpperCase(), ((String) actual).toUpperCase());
return;
case COMPACTION:
assertCompaction((Map<String, Object>) expected, (Map<String, String>) actual);
return;
case COMPRESSION:
assertCompression((Map<String, Object>) expected, (Map<String, String>) actual);
return;
}
log.info(actual.getClass().getName());
assertEquals(expected,
tableOption.quotesValue() && !(actual instanceof CharSequence) ? CqlStringUtils.singleQuote(actual) : actual);
}
public static void assertCompaction(Map<String, Object> expected, Map<String, String> actual) {
// TODO
}
public static void assertCompression(Map<String, Object> expected, Map<String, String> actual) {
// TODO
}
public static TableOption getTableOptionFor(String key) {
try {
return TableOption.valueOf(key);
} catch (IllegalArgumentException x) {
return null;
}
}
@SuppressWarnings("unchecked")
public static <T> T getOptionFor(TableOption option, Class<?> type, Options options) {
switch (option) {
case BLOOM_FILTER_FP_CHANCE:
return (T) (Double) options.getBloomFilterFalsePositiveChance();
case CACHING:
return (T) CqlStringUtils.singleQuote(options.getCaching());
case COMMENT:
return (T) CqlStringUtils.singleQuote(options.getComment());
case COMPACTION:
return (T) options.getCompaction();
case COMPACT_STORAGE:
throw new Error(); // TODO: figure out
case COMPRESSION:
return (T) options.getCompression();
case DCLOCAL_READ_REPAIR_CHANCE:
return (T) (Double) options.getLocalReadRepairChance();
case GC_GRACE_SECONDS:
return (T) new Long(options.getGcGraceInSeconds());
case READ_REPAIR_CHANCE:
return (T) (Double) options.getReadRepairChance();
case REPLICATE_ON_WRITE:
return (T) (Boolean) options.getReplicateOnWrite();
}
return null;
}
public static void assertColumns(List<ColumnSpecification> expected, List<ColumnMetadata> actual) {
for (int i = 0; i < expected.size(); i++) {
ColumnSpecification expectedColumn = expected.get(i);
ColumnMetadata actualColumn = actual.get(i);
assertColumn(expectedColumn, actualColumn);
}
}
public static void assertColumn(ColumnSpecification expected, ColumnMetadata actual) {
assertEquals(expected.getName().toCql(), actual.getName()); // TODO: expected.getName().getUnquoted()?
assertEquals(expected.getType(), actual.getType());
}
}

View File

@@ -0,0 +1,75 @@
/*
* Copyright 2013-2014 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.test.integration.core.cql.generator;
import static org.springframework.cassandra.test.integration.core.cql.generator.CqlIndexSpecificationAssertions.assertIndex;
import org.cassandraunit.CassandraCQLUnit;
import org.cassandraunit.dataset.cql.ClassPathCQLDataSet;
import org.junit.Rule;
import org.junit.Test;
import org.springframework.cassandra.test.integration.AbstractKeyspaceCreatingIntegrationTest;
import org.springframework.cassandra.test.unit.core.cql.generator.CreateIndexCqlGeneratorTests.BasicTest;
import org.springframework.cassandra.test.unit.core.cql.generator.CreateIndexCqlGeneratorTests.CreateIndexTest;
/**
* Integration tests that reuse unit tests.
*
* @author Matthew T. Adams
*/
public class CreateIndexCqlGeneratorIntegrationTests {
/**
* Integration test base class that knows how to do everything except instantiate the concrete unit test type T.
*
* @author Matthew T. Adams
*
* @param <T> The concrete unit test class to which this integration test corresponds.
*/
public static abstract class Base<T extends CreateIndexTest> extends AbstractKeyspaceCreatingIntegrationTest {
T unit;
public abstract T unit();
@Test
public void test() {
unit = unit();
unit.prepare();
SESSION.execute(unit.cql);
assertIndex(unit.specification, keyspace, SESSION);
}
}
public static class BasicIntegrationTest extends Base<BasicTest> {
/**
* This loads any test specific Cassandra objects
*/
@Rule
public CassandraCQLUnit cassandraCQLUnit = new CassandraCQLUnit(new ClassPathCQLDataSet(
"integration/cql/generator/CreateIndexCqlGeneratorIntegrationTests-BasicTest.cql", this.keyspace),
CASSANDRA_CONFIG, CASSANDRA_HOST, CASSANDRA_NATIVE_PORT);
@Override
public BasicTest unit() {
return new BasicTest();
}
}
}

View File

@@ -0,0 +1,69 @@
/*
* Copyright 2013-2014 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.test.integration.core.cql.generator;
import static org.springframework.cassandra.test.integration.core.cql.generator.CqlKeyspaceSpecificationAssertions.assertKeyspace;
import org.junit.Test;
import org.springframework.cassandra.test.integration.AbstractEmbeddedCassandraIntegrationTest;
import org.springframework.cassandra.test.unit.core.cql.generator.CreateKeyspaceCqlGeneratorTests.BasicTest;
import org.springframework.cassandra.test.unit.core.cql.generator.CreateKeyspaceCqlGeneratorTests.CreateKeyspaceTest;
import org.springframework.cassandra.test.unit.core.cql.generator.CreateKeyspaceCqlGeneratorTests.NetworkTopologyTest;
/**
* Integration tests that reuse unit tests.
*
* @author John McPeek
*/
public class CreateKeyspaceCqlGeneratorIntegrationTests {
/**
* Integration test base class that knows how to do everything except instantiate the concrete unit test type T.
*
* @param <T> The concrete unit test class to which this integration test corresponds.
*/
public static abstract class Base<T extends CreateKeyspaceTest> extends AbstractEmbeddedCassandraIntegrationTest {
T unit;
public abstract T unit();
@Test
public void test() {
unit = unit();
unit.prepare();
SYSTEM.execute(unit.cql);
assertKeyspace(unit.specification, unit.keyspace, SYSTEM);
}
}
public static class BasicIntegrationTest extends Base<BasicTest> {
@Override
public BasicTest unit() {
return new BasicTest();
}
}
public static class NetworkTopologyIntegrationTest extends Base<NetworkTopologyTest> {
@Override
public NetworkTopologyTest unit() {
return new NetworkTopologyTest();
}
}
}

View File

@@ -0,0 +1,71 @@
/*
* Copyright 2013-2014 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.test.integration.core.cql.generator;
import static org.springframework.cassandra.test.integration.core.cql.generator.CqlTableSpecificationAssertions.assertTable;
import org.junit.Test;
import org.springframework.cassandra.test.integration.AbstractKeyspaceCreatingIntegrationTest;
import org.springframework.cassandra.test.unit.core.cql.generator.CreateTableCqlGeneratorTests.BasicTest;
import org.springframework.cassandra.test.unit.core.cql.generator.CreateTableCqlGeneratorTests.CompositePartitionKeyTest;
import org.springframework.cassandra.test.unit.core.cql.generator.CreateTableCqlGeneratorTests.CreateTableTest;
/**
* Integration tests that reuse unit tests.
*
* @author Matthew T. Adams
*/
public class CreateTableCqlGeneratorIntegrationTests {
/**
* Integration test base class that knows how to do everything except instantiate the concrete unit test type T.
*
* @author Matthew T. Adams
*
* @param <T> The concrete unit test class to which this integration test corresponds.
*/
public static abstract class Base<T extends CreateTableTest> extends AbstractKeyspaceCreatingIntegrationTest {
T unit;
public abstract T unit();
@Test
public void test() {
unit = unit();
unit.prepare();
SESSION.execute(unit.cql);
assertTable(unit.specification, keyspace, SESSION);
}
}
public static class BasicIntegrationTest extends Base<BasicTest> {
@Override
public BasicTest unit() {
return new BasicTest();
}
}
public static class CompositePartitionKeyIntegrationTest extends Base<CompositePartitionKeyTest> {
@Override
public CompositePartitionKeyTest unit() {
return new CompositePartitionKeyTest();
}
}
}

View File

@@ -0,0 +1,42 @@
package org.springframework.cassandra.test.integration.core.cql.generator;
import org.junit.Test;
import org.springframework.cassandra.core.cql.generator.CreateTableCqlGenerator;
import org.springframework.cassandra.core.keyspace.CreateTableSpecification;
import org.springframework.cassandra.test.integration.AbstractKeyspaceCreatingIntegrationTest;
import org.springframework.cassandra.test.unit.core.cql.generator.CreateTableCqlGeneratorTests.FunkyTableNameTest;
import com.datastax.driver.core.DataType;
public class FunkyIdentifierIntegrationTest extends AbstractKeyspaceCreatingIntegrationTest {
public FunkyIdentifierIntegrationTest() {
super(randomKeyspaceName());
}
@Test
public void testFunkyTableName() {
for (String name : FunkyTableNameTest.FUNKY_LEGAL_NAMES) {
SESSION.execute(new CreateTableCqlGenerator(CreateTableSpecification.createTable().name(name)
.partitionKeyColumn("key", DataType.text())).toCql());
}
}
@Test
public void testFunkyColumnName() {
String table = "funky";
int i = 0;
for (String name : FunkyTableNameTest.FUNKY_LEGAL_NAMES) {
SESSION.execute(new CreateTableCqlGenerator(CreateTableSpecification.createTable().name(table + i++)
.partitionKeyColumn(name, DataType.text())).toCql());
}
}
@Test
public void testFunkyTableAndColumnName() {
for (String name : FunkyTableNameTest.FUNKY_LEGAL_NAMES) {
SESSION.execute(new CreateTableCqlGenerator(CreateTableSpecification.createTable().name(name)
.partitionKeyColumn(name, DataType.text())).toCql());
}
}
}

View File

@@ -0,0 +1,76 @@
/*
* Copyright 2013-2014 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.test.integration.core.cql.generator;
import static org.springframework.cassandra.test.integration.core.cql.generator.CqlIndexSpecificationAssertions.assertIndex;
import static org.springframework.cassandra.test.integration.core.cql.generator.CqlIndexSpecificationAssertions.assertNoIndex;
import org.cassandraunit.CassandraCQLUnit;
import org.cassandraunit.dataset.cql.ClassPathCQLDataSet;
import org.junit.Rule;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cassandra.test.integration.AbstractKeyspaceCreatingIntegrationTest;
import org.springframework.cassandra.test.unit.core.cql.generator.CreateIndexCqlGeneratorTests;
import org.springframework.cassandra.test.unit.core.cql.generator.DropIndexCqlGeneratorTests;
/**
* Integration tests that reuse unit tests.
*
* @author Matthew T. Adams
*/
public class IndexLifecycleCqlGeneratorIntegrationTests extends AbstractKeyspaceCreatingIntegrationTest {
Logger log = LoggerFactory.getLogger(IndexLifecycleCqlGeneratorIntegrationTests.class);
/**
* This loads any test specific Cassandra objects
*/
@Rule
public CassandraCQLUnit cassandraCQLUnit = new CassandraCQLUnit(new ClassPathCQLDataSet(
"integration/cql/generator/CreateIndexCqlGeneratorIntegrationTests-BasicTest.cql", this.keyspace),
CASSANDRA_CONFIG, CASSANDRA_HOST, CASSANDRA_NATIVE_PORT);
@Test
public void lifecycleTest() {
CreateIndexCqlGeneratorTests.BasicTest createTest = new CreateIndexCqlGeneratorTests.BasicTest();
DropIndexCqlGeneratorTests.BasicTest dropTest = new DropIndexCqlGeneratorTests.BasicTest();
DropIndexCqlGeneratorTests.IfExistsTest dropIfExists = new DropIndexCqlGeneratorTests.IfExistsTest();
createTest.prepare();
dropTest.prepare();
dropIfExists.prepare();
log.info(createTest.cql);
SESSION.execute(createTest.cql);
assertIndex(createTest.specification, keyspace, SESSION);
log.info(dropTest.cql);
SESSION.execute(dropTest.cql);
assertNoIndex(createTest.specification, keyspace, SESSION);
// log.info(dropIfExists.cql);
// SESSION.execute(dropIfExists.cql);
//
// assertNoIndex(createTest.specification, keyspace, SESSION);
}
}

View File

@@ -0,0 +1,124 @@
/*
* Copyright 2013-2014 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.test.integration.core.cql.generator;
import static org.springframework.cassandra.test.integration.core.cql.generator.CqlTableSpecificationAssertions.assertNoTable;
import static org.springframework.cassandra.test.integration.core.cql.generator.CqlTableSpecificationAssertions.assertTable;
import org.cassandraunit.CassandraCQLUnit;
import org.cassandraunit.dataset.cql.ClassPathCQLDataSet;
import org.junit.Rule;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cassandra.core.cql.generator.DropTableCqlGenerator;
import org.springframework.cassandra.core.keyspace.DropTableSpecification;
import org.springframework.cassandra.test.integration.AbstractKeyspaceCreatingIntegrationTest;
import org.springframework.cassandra.test.unit.core.cql.generator.AlterTableCqlGeneratorTests;
import org.springframework.cassandra.test.unit.core.cql.generator.CreateTableCqlGeneratorTests;
import org.springframework.cassandra.test.unit.core.cql.generator.DropTableCqlGeneratorTests;
/**
* Test CREATE TABLE / ALTER TABLE / DROP TABLE
*
* @author David Webb
*/
public class TableLifecycleIntegrationTest extends AbstractKeyspaceCreatingIntegrationTest {
private final static Logger log = LoggerFactory.getLogger(TableLifecycleIntegrationTest.class);
CreateTableCqlGeneratorTests.MultipleOptionsTest createTableTest = new CreateTableCqlGeneratorTests.MultipleOptionsTest();
public TableLifecycleIntegrationTest() {
super("tlit");
}
@Override
public boolean dropKeyspaceAfterTest() {
return true;
}
// This only ensures the keyspace exists before each test, while using a static SESSION from the parent object.
// TODO - DW Make this better.
@Rule
public CassandraCQLUnit cassandraCQLUnit = new CassandraCQLUnit(new ClassPathCQLDataSet(
"cassandraOperationsTest-cql-dataload.cql", this.keyspace), CASSANDRA_CONFIG, CASSANDRA_HOST,
CASSANDRA_NATIVE_PORT);
@Test
public void testDrop() {
createTableTest.prepare();
log.info(createTableTest.cql);
SESSION.execute(createTableTest.cql);
assertTable(createTableTest.specification, keyspace, SESSION);
DropTableTest dropTest = new DropTableTest();
dropTest.prepare();
log.info(dropTest.cql);
SESSION.execute(dropTest.cql);
assertNoTable(dropTest.specification, keyspace, SESSION);
}
@Test
public void testAlter() {
createTableTest.prepare();
log.info(createTableTest.cql);
SESSION.execute(createTableTest.cql);
assertTable(createTableTest.specification, keyspace, SESSION);
AlterTableCqlGeneratorTests.MultipleOptionsTest alterTest = new AlterTableCqlGeneratorTests.MultipleOptionsTest();
alterTest.prepare();
log.info(alterTest.cql);
SESSION.execute(alterTest.cql);
// assertTable(alterTest.specification, keyspace, SESSION);
}
public class DropTableTest extends DropTableCqlGeneratorTests.DropTableTest {
/* (non-Javadoc)
* @see org.springframework.cassandra.test.unit.core.cql.generator.TableOperationCqlGeneratorTest#specification()
*/
@Override
public DropTableSpecification specification() {
return DropTableSpecification.dropTable().name(createTableTest.specification.getName());
}
/* (non-Javadoc)
* @see org.springframework.cassandra.test.unit.core.cql.generator.TableOperationCqlGeneratorTest#generator()
*/
@Override
public DropTableCqlGenerator generator() {
return new DropTableCqlGenerator(specification);
}
}
}

View File

@@ -0,0 +1,48 @@
/*
* Copyright 2013-2014 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.test.integration.core.cql.generator;
import static org.springframework.cassandra.test.integration.core.cql.generator.CqlTableSpecificationAssertions.assertTable;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cassandra.test.integration.AbstractKeyspaceCreatingIntegrationTest;
import org.springframework.cassandra.test.unit.core.cql.generator.CreateTableCqlGeneratorTests;
/**
* Test CREATE TABLE for all Options and assert against C* TableMetaData
*
* @author David Webb
*/
public class TableOptionsIntegrationTest extends AbstractKeyspaceCreatingIntegrationTest {
private final static Logger log = LoggerFactory.getLogger(TableOptionsIntegrationTest.class);
@Test
public void test() {
CreateTableCqlGeneratorTests.MultipleOptionsTest optionsTest = new CreateTableCqlGeneratorTests.MultipleOptionsTest();
optionsTest.prepare();
log.info(optionsTest.cql);
SESSION.execute(optionsTest.cql);
assertTable(optionsTest.specification, keyspace, SESSION);
}
}

View File

@@ -0,0 +1,99 @@
/*
* Copyright 2013-2014 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.test.integration.core.template;
/**
* Test POJO
*
* @author David Webb
*
*/
public class Book {
private String isbn;
private String title;
private String author;
private int pages;
/**
* @return Returns the isbn.
*/
public String getIsbn() {
return isbn;
}
/**
* @param isbn The isbn to set.
*/
public void setIsbn(String isbn) {
this.isbn = isbn;
}
/**
* @return Returns the title.
*/
public String getTitle() {
return title;
}
/**
* @param title The title to set.
*/
public void setTitle(String title) {
this.title = title;
}
/**
* @return Returns the author.
*/
public String getAuthor() {
return author;
}
/**
* @param author The author to set.
*/
public void setAuthor(String author) {
this.author = author;
}
/**
* @return Returns the pages.
*/
public int getPages() {
return pages;
}
/**
* @param pages The pages to set.
*/
public void setPages(int pages) {
this.pages = pages;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("isbn -> " + isbn).append("\n");
sb.append("tile -> " + title).append("\n");
sb.append("author -> " + author).append("\n");
sb.append("pages -> " + pages).append("\n");
return sb.toString();
}
}

View File

@@ -0,0 +1,72 @@
/*
* Copyright 2013-2014 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.test.integration.core.template;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cassandra.core.AsynchronousQueryListener;
import com.datastax.driver.core.ResultSetFuture;
import com.datastax.driver.core.Row;
/**
* Test Implementation of the {@link AsynchronousQueryListener}
*
* @author David Webb
*
*/
public class BookListener implements AsynchronousQueryListener {
private static Logger log = LoggerFactory.getLogger(BookListener.class);
private Book book;
private boolean done;
@Override
public void onQueryComplete(ResultSetFuture rsf) {
log.info("QueryCompleted");
Row row;
try {
row = rsf.get().one();
} catch (Exception e) {
throw new RuntimeException("Failed to get ResultSet from ResultSetFuture", e);
}
book = new Book();
book.setIsbn(row.getString("isbn"));
book.setTitle(row.getString("title"));
book.setAuthor(row.getString("author"));
book.setPages(row.getInt("pages"));
done = true;
log.info("DONE");
}
/**
* @return Returns the done.
*/
public boolean isDone() {
return done;
}
/**
* @return Returns the book.
*/
public Book getBook() {
return book;
}
}

View File

@@ -0,0 +1,31 @@
/*
* Copyright 2013-2014 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.test.integration.support;
import org.springframework.cassandra.config.java.AbstractSessionConfiguration;
import org.springframework.context.annotation.Configuration;
@Configuration
public abstract class AbstractTestJavaConfig extends AbstractSessionConfiguration {
public static SpringCqlBuildProperties PROPS = new SpringCqlBuildProperties();
public static final int PORT = PROPS.getCassandraPort();
@Override
protected int getPort() {
return PORT;
}
}

View File

@@ -0,0 +1,87 @@
/*
* Copyright 2013-2014 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.test.integration.support;
import java.io.InputStream;
import java.util.Properties;
@SuppressWarnings("serial")
public class SpringCqlBuildProperties extends Properties {
protected String resourceName = null;
public SpringCqlBuildProperties() {
this("/" + SpringCqlBuildProperties.class.getName() + ".properties");
}
protected SpringCqlBuildProperties(String resourceName) {
this.resourceName = resourceName;
loadProperties();
}
public void loadProperties() {
loadProperties(resourceName);
}
protected void loadProperties(String resourceName) {
InputStream in = null;
try {
in = getClass().getResourceAsStream(resourceName);
if (in == null) {
return;
}
load(in);
} catch (Exception x) {
throw new RuntimeException(x);
} finally {
if (in != null) {
try {
in.close();
} catch (Exception e) {
// gulp
}
}
}
}
public int getCassandraPort() {
return getInt("build.cassandra.native_transport_port");
}
public int getCassandraRpcPort() {
return getInt("build.cassandra.rpc_port");
}
public int getCassandraStoragePort() {
return getInt("build.cassandra.storage_port");
}
public int getCassandraSslStoragePort() {
return getInt("build.cassandra.ssl_storage_port");
}
public int getInt(String key) {
String property = getProperty(key);
return Integer.parseInt(property);
}
public boolean getBoolean(String key) {
return Boolean.parseBoolean(getProperty(key));
}
}

View File

@@ -0,0 +1,78 @@
/*
* Copyright 2013-2014 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.test.unit.core.cql;
import static org.junit.Assert.*;
import static org.springframework.cassandra.core.cql.CqlIdentifier.cqlId;
import static org.springframework.cassandra.core.cql.CqlIdentifier.quotedCqlId;
import org.junit.Test;
import org.springframework.cassandra.core.ReservedKeyword;
import org.springframework.cassandra.core.cql.CqlIdentifier;
public class CqlIdentifierTest {
@Test
public void testUnquotedIdentifiers() {
String[] ids = new String[] { "foo", "Foo", "FOO", "a_", "a1" };
for (String id : ids) {
CqlIdentifier cqlId = cqlId(id);
assertFalse(cqlId.isQuoted());
assertEquals(id.toLowerCase(), cqlId.toCql());
}
}
@Test
public void testForceQuotedIdentifiers() {
String[] ids = new String[] { "foo", "Foo", "FOO", "a_", "a1" };
for (String id : ids) {
CqlIdentifier cqlId = quotedCqlId(id);
assertTrue(cqlId.isQuoted());
assertEquals("\"" + id + "\"", cqlId.toCql());
}
}
@Test
public void testReservedWordsEndUpQuoted() {
for (ReservedKeyword id : ReservedKeyword.values()) {
CqlIdentifier cqlId = cqlId(id.name());
assertTrue(cqlId.isQuoted());
assertEquals("\"" + id.name() + "\"", cqlId.toCql());
cqlId = cqlId(id.name().toLowerCase());
assertTrue(cqlId.isQuoted());
assertEquals("\"" + id.name().toLowerCase() + "\"", cqlId.toCql());
}
}
@Test
public void testIllegals() {
String[] illegals = new String[] { null, "", "a ", "a a", "a\"", "a'", "a''", "\"\"", "''", "-", "a-", "_", "_a" };
for (String illegal : illegals) {
try {
cqlId(illegal);
fail(String.format("identifier [%s] should have caused IllegalArgumentException", illegal));
} catch (IllegalArgumentException x) {
// :)
}
}
}
}

View File

@@ -0,0 +1,20 @@
/*
* Copyright 2013-2014 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.test.unit.core.cql;
public class CqlStringUtilsTest {
}

View File

@@ -0,0 +1,123 @@
/*
* Copyright 2013-2014 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.test.unit.core.cql.generator;
import static org.junit.Assert.assertTrue;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import org.springframework.cassandra.core.cql.generator.AlterKeyspaceCqlGenerator;
import org.springframework.cassandra.core.keyspace.AlterKeyspaceSpecification;
import org.springframework.cassandra.core.keyspace.DefaultOption;
import org.springframework.cassandra.core.keyspace.KeyspaceOption;
import org.springframework.cassandra.core.keyspace.Option;
import org.springframework.cassandra.test.unit.support.Utils;
public class AlterKeyspaceCqlGeneratorTests {
/**
* Asserts that the preamble is first & correctly formatted in the given CQL string.
*/
public static void assertPreamble(String tableName, String cql) {
assertTrue(cql.startsWith("ALTER KEYSPACE " + tableName + " "));
}
private static void assertReplicationMap(Map<Option, Object> replicationMap, String cql) {
assertTrue(cql.contains(" WITH replication = { "));
for (Map.Entry<Option, Object> entry : replicationMap.entrySet()) {
String keyValuePair = "'" + entry.getKey().getName() + "' : '" + entry.getValue().toString() + "'";
assertTrue(cql.contains(keyValuePair));
}
}
public static void assertDurableWrites(Boolean durableWrites, String cql) {
assertTrue(cql.contains(" AND durable_writes = " + durableWrites));
}
/**
* Convenient base class that other test classes can use so as not to repeat the generics declarations.
*/
public static abstract class AlterKeyspaceTest extends
KeyspaceOperationCqlGeneratorTest<AlterKeyspaceSpecification, AlterKeyspaceCqlGenerator> {
}
public static class CompleteTest extends AlterKeyspaceTest {
public String name = Utils.randomKeyspaceName();
public Boolean durableWrites = true;
public Map<Option, Object> replicationMap = new HashMap<Option, Object>();
@Override
public AlterKeyspaceSpecification specification() {
replicationMap.put(new DefaultOption("class", String.class, false, false, true), "SimpleStrategy");
replicationMap.put(new DefaultOption("replication_factor", Long.class, false, false, true), 1);
replicationMap.put(new DefaultOption("dc1", Long.class, false, false, true), 2);
replicationMap.put(new DefaultOption("dc2", Long.class, false, false, true), 3);
return AlterKeyspaceSpecification.alterKeyspace().name(name).with(KeyspaceOption.REPLICATION, replicationMap)
.with(KeyspaceOption.DURABLE_WRITES, durableWrites);
}
@Override
public AlterKeyspaceCqlGenerator generator() {
return new AlterKeyspaceCqlGenerator(specification);
}
@Test
public void test() {
prepare();
assertPreamble(name, cql);
assertReplicationMap(replicationMap, cql);
assertDurableWrites(durableWrites, cql);
}
}
public static class ReplicationMapOnlyTest extends AlterKeyspaceTest {
public String name = "mytable";
public Boolean durableWrites = true;
public Map<Option, Object> replicationMap = new HashMap<Option, Object>();
@Override
public AlterKeyspaceSpecification specification() {
replicationMap.put(new DefaultOption("class", String.class, false, false, true), "SimpleStrategy");
replicationMap.put(new DefaultOption("replication_factor", Long.class, false, false, true), 1);
replicationMap.put(new DefaultOption("dc1", Long.class, false, false, true), 2);
replicationMap.put(new DefaultOption("dc2", Long.class, false, false, true), 3);
return AlterKeyspaceSpecification.alterKeyspace().name(name).with(KeyspaceOption.REPLICATION, replicationMap);
}
@Override
public AlterKeyspaceCqlGenerator generator() {
return new AlterKeyspaceCqlGenerator(specification);
}
@Test
public void test() {
prepare();
assertPreamble(name, cql);
assertReplicationMap(replicationMap, cql);
}
}
}

View File

@@ -0,0 +1,170 @@
/*
* Copyright 2013-2014 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.test.unit.core.cql.generator;
import static org.junit.Assert.assertTrue;
import java.util.LinkedHashMap;
import java.util.Map;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cassandra.core.cql.generator.AlterTableCqlGenerator;
import org.springframework.cassandra.core.keyspace.AlterTableSpecification;
import org.springframework.cassandra.core.keyspace.Option;
import org.springframework.cassandra.core.keyspace.TableOption;
import org.springframework.cassandra.core.keyspace.TableOption.CachingOption;
import org.springframework.cassandra.core.keyspace.TableOption.CompactionOption;
import org.springframework.cassandra.core.keyspace.TableOption.CompressionOption;
import com.datastax.driver.core.DataType;
public class AlterTableCqlGeneratorTests {
private final static Logger log = LoggerFactory.getLogger(AlterTableCqlGeneratorTests.class);
/**
* Asserts that the preamble is first & correctly formatted in the given CQL string.
*/
public static void assertPreamble(String tableName, String cql) {
assertTrue(cql.startsWith("ALTER TABLE " + tableName + " "));
}
/**
* Asserts that the given list of columns definitions are contained in the given CQL string properly.
*
* @param columnSpec IE, "foo text, bar blob"
*/
public static void assertColumnChanges(String columnSpec, String cql) {
assertTrue(cql.contains(""));
}
/**
* Convenient base class that other test classes can use so as not to repeat the generics declarations.
*/
public static abstract class AlterTableTest extends
TableOperationCqlGeneratorTest<AlterTableSpecification, AlterTableCqlGenerator> {
}
public static class BasicTest extends AlterTableTest {
public String name = "mytable";
public DataType alteredType = DataType.text();
public String altered = "altered";
public DataType addedType = DataType.text();
public String added = "added";
public String dropped = "dropped";
@Override
public AlterTableSpecification specification() {
return AlterTableSpecification.alterTable().name(name).alter(altered, alteredType).add(added, addedType);
}
@Override
public AlterTableCqlGenerator generator() {
return new AlterTableCqlGenerator(specification);
}
@Test
public void test() {
prepare();
assertPreamble(name, cql);
assertColumnChanges(
String.format("ALTER %s TYPE %s, ADD %s %s, DROP %s", altered, alteredType, added, addedType, dropped), cql);
}
}
/**
* Fully test all available create table options
*
* @author David Webb
*
*/
public static class MultipleOptionsTest extends AlterTableTest {
public String name = "timeseries_table";
public DataType partitionKeyType0 = DataType.timeuuid();
public String partitionKey0 = "tid";
public DataType partitionKeyType1 = DataType.timestamp();
public String partitionKey1 = "create_timestamp";
public DataType columnType1 = DataType.text();
public String column1 = "data_point";
public Double readRepairChance = 0.6;
public Double dcLocalReadRepairChance = 0.8;
public Double bloomFilterFpChance = 0.002;
public Boolean replcateOnWrite = Boolean.FALSE;
public Long gcGraceSeconds = 1200l;
public String comment = "This is My Table";
public Map<Option, Object> compactionMap = new LinkedHashMap<Option, Object>();
public Map<Option, Object> compressionMap = new LinkedHashMap<Option, Object>();
@Override
public AlterTableSpecification specification() {
// Compaction
compactionMap.put(CompactionOption.CLASS, "SizeTieredCompactionStrategy");
compactionMap.put(CompactionOption.MIN_THRESHOLD, "4");
// Compression
compressionMap.put(CompressionOption.SSTABLE_COMPRESSION, "SnappyCompressor");
compressionMap.put(CompressionOption.CHUNK_LENGTH_KB, 128);
compressionMap.put(CompressionOption.CRC_CHECK_CHANCE, 0.75);
return AlterTableSpecification
.alterTable()
.name(name)
// .with(TableOption.COMPACT_STORAGE)
.with(TableOption.READ_REPAIR_CHANCE, readRepairChance).with(TableOption.COMPACTION, compactionMap)
.with(TableOption.COMPRESSION, compressionMap).with(TableOption.BLOOM_FILTER_FP_CHANCE, bloomFilterFpChance)
.with(TableOption.CACHING, CachingOption.KEYS_ONLY).with(TableOption.REPLICATE_ON_WRITE, replcateOnWrite)
.with(TableOption.COMMENT, comment).with(TableOption.DCLOCAL_READ_REPAIR_CHANCE, dcLocalReadRepairChance)
.with(TableOption.GC_GRACE_SECONDS, gcGraceSeconds);
}
@Test
public void test() {
prepare();
log.info(cql);
assertPreamble(name, cql);
// assertColumns(String.format("%s %s, %s %s, %s %s", partitionKey0, partitionKeyType0, partitionKey1,
// partitionKeyType1, column1, columnType1), cql);
// assertPrimaryKey(String.format("(%s, %s)", partitionKey0, partitionKey1), cql);
// assertNullOption(TableOption.COMPACT_STORAGE.getName(), cql);
// assertDoubleOption(TableOption.READ_REPAIR_CHANCE.getName(), readRepairChance, cql);
// assertDoubleOption(TableOption.DCLOCAL_READ_REPAIR_CHANCE.getName(), dcLocalReadRepairChance, cql);
// assertDoubleOption(TableOption.BLOOM_FILTER_FP_CHANCE.getName(), bloomFilterFpChance, cql);
// assertStringOption(TableOption.CACHING.getName(), CachingOption.KEYS_ONLY.getValue(), cql);
// assertStringOption(TableOption.REPLICATE_ON_WRITE.getName(), replcateOnWrite.toString(), cql);
// assertStringOption(TableOption.COMMENT.getName(), comment, cql);
// assertLongOption(TableOption.GC_GRACE_SECONDS.getName(), gcGraceSeconds, cql);
}
/* (non-Javadoc)
* @see org.springframework.cassandra.test.unit.core.cql.generator.TableOperationCqlGeneratorTest#generator()
*/
@Override
public AlterTableCqlGenerator generator() {
return new AlterTableCqlGenerator(specification);
}
}
}

View File

@@ -0,0 +1,74 @@
/*
* Copyright 2013-2014 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.test.unit.core.cql.generator;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import org.springframework.cassandra.core.cql.generator.CreateIndexCqlGenerator;
import org.springframework.cassandra.core.keyspace.CreateIndexSpecification;
public class CreateIndexCqlGeneratorTests {
/**
* Asserts that the preamble is first & correctly formatted in the given CQL string.
*/
public static void assertPreamble(String indexName, String tableName, String cql) {
assertTrue(cql.startsWith("CREATE INDEX " + indexName + " ON " + tableName));
}
/**
* Asserts that the given list of columns definitions are contained in the given CQL string properly.
*
* @param columnSpec IE, "(foo)"
*/
public static void assertColumn(String columnName, String cql) {
assertTrue(cql.contains("(" + columnName + ")"));
}
/**
* Convenient base class that other test classes can use so as not to repeat the generics declarations or
* {@link #generator()} method.
*/
public static abstract class CreateIndexTest extends
IndexOperationCqlGeneratorTest<CreateIndexSpecification, CreateIndexCqlGenerator> {
public CreateIndexCqlGenerator generator() {
return new CreateIndexCqlGenerator(specification);
}
}
public static class BasicTest extends CreateIndexTest {
public String name = "myindex";
public String tableName = "mytable";
public String column1 = "column1";
public CreateIndexSpecification specification() {
return CreateIndexSpecification.createIndex().name(name).tableName(tableName).columnName(column1);
}
@Test
public void test() {
prepare();
assertPreamble(name, tableName, cql);
assertColumn(column1, cql);
}
}
}

View File

@@ -0,0 +1,145 @@
/*
* Copyright 2013-2014 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.test.unit.core.cql.generator;
import static org.junit.Assert.assertTrue;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import org.springframework.cassandra.config.KeyspaceAttributes;
import org.springframework.cassandra.core.cql.generator.CreateKeyspaceCqlGenerator;
import org.springframework.cassandra.core.keyspace.CreateKeyspaceSpecification;
import org.springframework.cassandra.core.keyspace.DefaultOption;
import org.springframework.cassandra.core.keyspace.KeyspaceOption;
import org.springframework.cassandra.core.keyspace.Option;
import org.springframework.cassandra.test.unit.support.Utils;
public class CreateKeyspaceCqlGeneratorTests {
/**
* Asserts that the preamble is first & correctly formatted in the given CQL string.
*/
public static void assertPreamble(String keyspaceName, String cql) {
assertTrue(cql.startsWith("CREATE KEYSPACE " + keyspaceName + " "));
}
private static void assertReplicationMap(Map<Option, Object> replicationMap, String cql) {
assertTrue(cql.contains(" WITH replication = { "));
for (Map.Entry<Option, Object> entry : replicationMap.entrySet()) {
String keyValuePair = "'" + entry.getKey().getName() + "' : " + (entry.getKey().quotesValue() ? "'" : "")
+ entry.getValue().toString() + (entry.getKey().quotesValue() ? "'" : "");
assertTrue(cql.contains(keyValuePair));
}
}
public static void assertDurableWrites(Boolean durableWrites, String cql) {
assertTrue(cql.contains(" AND durable_writes = " + durableWrites));
}
/**
* Convenient base class that other test classes can use so as not to repeat the generics declarations or
* {@link #generator()} method.
*/
public static abstract class CreateKeyspaceTest extends
KeyspaceOperationCqlGeneratorTest<CreateKeyspaceSpecification, CreateKeyspaceCqlGenerator> {
@Override
public CreateKeyspaceCqlGenerator generator() {
return new CreateKeyspaceCqlGenerator(specification);
}
}
public static class BasicTest extends CreateKeyspaceTest {
public String name = Utils.randomKeyspaceName();
public Boolean durableWrites = true;
public Map<Option, Object> replicationMap = KeyspaceAttributes.newSimpleReplication();
@Override
public CreateKeyspaceSpecification specification() {
keyspace = name;
return CreateKeyspaceSpecification.createKeyspace().name(keyspace)
.with(KeyspaceOption.REPLICATION, replicationMap).with(KeyspaceOption.DURABLE_WRITES, durableWrites);
}
@Test
public void test() {
prepare();
assertPreamble(keyspace, cql);
assertReplicationMap(replicationMap, cql);
assertDurableWrites(durableWrites, cql);
}
}
public static class NoOptionsBasicTest extends CreateKeyspaceTest {
public String name = Utils.randomKeyspaceName();
public Boolean durableWrites = true;
public Map<Option, Object> replicationMap = KeyspaceAttributes.newSimpleReplication();
@Override
public CreateKeyspaceSpecification specification() {
keyspace = name;
return CreateKeyspaceSpecification.createKeyspace().name(keyspace);
}
@Test
public void test() {
prepare();
assertPreamble(keyspace, cql);
assertReplicationMap(replicationMap, cql);
assertDurableWrites(durableWrites, cql);
}
}
public static class NetworkTopologyTest extends CreateKeyspaceTest {
public String name = Utils.randomKeyspaceName();
public Boolean durableWrites = false;
public Map<Option, Object> replicationMap = new HashMap<Option, Object>();
@Override
public CreateKeyspaceSpecification specification() {
keyspace = name;
replicationMap.put(new DefaultOption("class", String.class, false, false, true), "NetworkTopologyStrategy");
replicationMap.put(new DefaultOption("dc1", Long.class, false, false, true), 2);
replicationMap.put(new DefaultOption("dc2", Long.class, false, false, true), 3);
return CreateKeyspaceSpecification.createKeyspace().name(keyspace)
.with(KeyspaceOption.REPLICATION, replicationMap).with(KeyspaceOption.DURABLE_WRITES, durableWrites);
}
@Test
public void test() {
prepare();
assertPreamble(keyspace, cql);
assertReplicationMap(replicationMap, cql);
assertDurableWrites(durableWrites, cql);
}
}
}

View File

@@ -0,0 +1,316 @@
/*
* Copyright 2013-2014 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.test.unit.core.cql.generator;
import static org.junit.Assert.assertTrue;
import static org.springframework.cassandra.core.cql.CqlIdentifier.cqlId;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cassandra.core.ReservedKeyword;
import org.springframework.cassandra.core.cql.CqlIdentifier;
import org.springframework.cassandra.core.cql.generator.CreateTableCqlGenerator;
import org.springframework.cassandra.core.keyspace.CreateTableSpecification;
import org.springframework.cassandra.core.keyspace.Option;
import org.springframework.cassandra.core.keyspace.TableOption;
import org.springframework.cassandra.core.keyspace.TableOption.CachingOption;
import org.springframework.cassandra.core.keyspace.TableOption.CompactionOption;
import org.springframework.cassandra.core.keyspace.TableOption.CompressionOption;
import com.datastax.driver.core.DataType;
public class CreateTableCqlGeneratorTests {
private static final Logger log = LoggerFactory.getLogger(CreateTableCqlGeneratorTests.class);
/**
* Asserts that the preamble is first & correctly formatted in the given CQL string.
*/
public static void assertPreamble(CqlIdentifier tableName, String cql) {
assertTrue(cql.startsWith("CREATE TABLE " + tableName + " "));
}
/**
* Asserts that the given primary key definition is contained in the given CQL string properly.
*
* @param primaryKeyString IE, "foo", "foo, bar, baz", "(foo, bar), baz", etc
*/
public static void assertPrimaryKey(String primaryKeyString, String cql) {
assertTrue(cql.contains(", PRIMARY KEY (" + primaryKeyString + "))"));
}
/**
* Asserts that the given list of columns definitions are contained in the given CQL string properly.
*
* @param columnSpec IE, "foo text, bar blob"
*/
public static void assertColumns(String columnSpec, String cql) {
assertTrue(cql.contains("(" + columnSpec + ","));
}
/**
* Asserts that the read repair change is set properly
*/
public static void assertStringOption(String name, String value, String cql) {
log.info(name + " -> " + value);
assertTrue(cql.contains(name + " = '" + value + "'"));
}
/**
* Asserts that the option is set
*/
public static void assertDoubleOption(String name, Double value, String cql) {
log.info(name + " -> " + value);
assertTrue(cql.contains(name + " = " + value));
}
public static void assertLongOption(String name, Long value, String cql) {
log.info(name + " -> " + value);
assertTrue(cql.contains(name + " = " + value));
}
/**
* Asserts that the read repair change is set properly
*/
public static void assertNullOption(String name, String cql) {
log.info(name);
assertTrue(cql.contains(" " + name + " "));
}
/**
* Convenient base class that other test classes can use so as not to repeat the generics declarations or
* {@link #generator()} method.
*/
public static abstract class CreateTableTest extends
TableOperationCqlGeneratorTest<CreateTableSpecification, CreateTableCqlGenerator> {
@Override
public CreateTableCqlGenerator generator() {
return new CreateTableCqlGenerator(specification);
}
}
public static class BasicTest extends CreateTableTest {
public CqlIdentifier name = cqlId("mytable");
public DataType partitionKeyType0 = DataType.text();
public CqlIdentifier partitionKey0 = cqlId("partitionKey0");
public DataType columnType1 = DataType.text();
public String column1 = "column1";
@Override
public CreateTableSpecification specification() {
return CreateTableSpecification.createTable().name(name).partitionKeyColumn(partitionKey0, partitionKeyType0)
.column(column1, columnType1);
}
@Test
public void test() {
prepare();
assertPreamble(name, cql);
assertColumns(String.format("%s %s, %s %s", partitionKey0, partitionKeyType0, column1, columnType1), cql);
assertPrimaryKey(partitionKey0.toCql(), cql);
}
}
public static class CompositePartitionKeyTest extends CreateTableTest {
public CqlIdentifier name = cqlId("composite_partition_key_table");
public DataType partKeyType0 = DataType.text();
public CqlIdentifier partKey0 = cqlId("partKey0");
public DataType partKeyType1 = DataType.text();
public CqlIdentifier partKey1 = cqlId("partKey1");
public CqlIdentifier column0 = cqlId("column0");
public DataType columnType0 = DataType.text();
@Override
public CreateTableSpecification specification() {
return CreateTableSpecification.createTable().name(name).partitionKeyColumn(partKey0, partKeyType0)
.partitionKeyColumn(partKey1, partKeyType1).column(column0, columnType0);
}
@Test
public void test() {
prepare();
assertPreamble(name, cql);
assertColumns(
String.format("%s %s, %s %s, %s %s", partKey0, partKeyType0, partKey1, partKeyType1, column0, columnType0),
cql);
assertPrimaryKey(String.format("(%s, %s)", partKey0, partKey1), cql);
}
}
/**
* Test just the Read Repair Chance
*
* @author David Webb
*
*/
public static class ReadRepairChanceTest extends CreateTableTest {
public CqlIdentifier name = cqlId("mytable");
public DataType partitionKeyType0 = DataType.text();
public CqlIdentifier partitionKey0 = cqlId("partitionKey0");
public DataType partitionKeyType1 = DataType.timestamp();
public CqlIdentifier partitionKey1 = cqlId("create_timestamp");
public DataType columnType1 = DataType.text();
public CqlIdentifier column1 = cqlId("column1");
public Double readRepairChance = 0.5;
@Override
public CreateTableSpecification specification() {
return CreateTableSpecification.createTable().name(name).partitionKeyColumn(partitionKey0, partitionKeyType0)
.partitionKeyColumn(partitionKey1, partitionKeyType1).column(column1, columnType1)
.with(TableOption.READ_REPAIR_CHANCE, readRepairChance);
}
@Test
public void test() {
prepare();
assertPreamble(name, cql);
assertColumns(String.format("%s %s, %s %s, %s %s", partitionKey0, partitionKeyType0, partitionKey1,
partitionKeyType1, column1, columnType1), cql);
assertPrimaryKey(String.format("(%s, %s)", partitionKey0, partitionKey1), cql);
assertDoubleOption(TableOption.READ_REPAIR_CHANCE.getName(), readRepairChance, cql);
}
}
/**
* Fully test all available create table options
*
* @author David Webb
*
*/
public static class MultipleOptionsTest extends CreateTableTest {
public CqlIdentifier name = cqlId("timeseries_table");
public DataType partitionKeyType0 = DataType.timeuuid();
public CqlIdentifier partitionKey0 = cqlId("tid");
public DataType partitionKeyType1 = DataType.timestamp();
public CqlIdentifier partitionKey1 = cqlId("create_timestamp");
public DataType columnType1 = DataType.text();
public CqlIdentifier column1 = cqlId("data_point");
public Double readRepairChance = 0.5;
public Double dcLocalReadRepairChance = 0.7;
public Double bloomFilterFpChance = 0.001;
public Boolean replcateOnWrite = Boolean.FALSE;
public Long gcGraceSeconds = 600l;
public String comment = "This is My Table";
public Map<Option, Object> compactionMap = new LinkedHashMap<Option, Object>();
public Map<Option, Object> compressionMap = new LinkedHashMap<Option, Object>();
@Override
public CreateTableSpecification specification() {
// Compaction
compactionMap.put(CompactionOption.CLASS, "SizeTieredCompactionStrategy");
compactionMap.put(CompactionOption.MIN_THRESHOLD, "4");
// Compression
compressionMap.put(CompressionOption.SSTABLE_COMPRESSION, "SnappyCompressor");
compressionMap.put(CompressionOption.CHUNK_LENGTH_KB, 128);
compressionMap.put(CompressionOption.CRC_CHECK_CHANCE, 0.75);
return CreateTableSpecification.createTable().name(name).partitionKeyColumn(partitionKey0, partitionKeyType0)
.partitionKeyColumn(partitionKey1, partitionKeyType1).column(column1, columnType1)
.with(TableOption.COMPACT_STORAGE).with(TableOption.READ_REPAIR_CHANCE, readRepairChance)
.with(TableOption.COMPACTION, compactionMap).with(TableOption.COMPRESSION, compressionMap)
.with(TableOption.BLOOM_FILTER_FP_CHANCE, bloomFilterFpChance)
.with(TableOption.CACHING, CachingOption.KEYS_ONLY).with(TableOption.REPLICATE_ON_WRITE, replcateOnWrite)
.with(TableOption.COMMENT, comment).with(TableOption.DCLOCAL_READ_REPAIR_CHANCE, dcLocalReadRepairChance)
.with(TableOption.GC_GRACE_SECONDS, gcGraceSeconds);
}
@Test
public void test() {
prepare();
log.info(cql);
assertPreamble(name, cql);
assertColumns(String.format("%s %s, %s %s, %s %s", partitionKey0, partitionKeyType0, partitionKey1,
partitionKeyType1, column1, columnType1), cql);
assertPrimaryKey(String.format("(%s, %s)", partitionKey0, partitionKey1), cql);
assertNullOption(TableOption.COMPACT_STORAGE.getName(), cql);
assertDoubleOption(TableOption.READ_REPAIR_CHANCE.getName(), readRepairChance, cql);
assertDoubleOption(TableOption.DCLOCAL_READ_REPAIR_CHANCE.getName(), dcLocalReadRepairChance, cql);
assertDoubleOption(TableOption.BLOOM_FILTER_FP_CHANCE.getName(), bloomFilterFpChance, cql);
assertStringOption(TableOption.CACHING.getName(), CachingOption.KEYS_ONLY.getValue(), cql);
assertStringOption(TableOption.REPLICATE_ON_WRITE.getName(), replcateOnWrite.toString(), cql);
assertStringOption(TableOption.COMMENT.getName(), comment, cql);
assertLongOption(TableOption.GC_GRACE_SECONDS.getName(), gcGraceSeconds, cql);
}
}
public static class FunkyTableNameTest {
public static final List<String> FUNKY_LEGAL_NAMES;
static {
List<String> funkies = new ArrayList<String>(Arrays.asList(new String[] { /* TODO */}));
// TODO: should these work? "a \"\" x", "a\"\"\"\"x", "a b"
for (ReservedKeyword funky : ReservedKeyword.values()) {
funkies.add(funky.name());
}
FUNKY_LEGAL_NAMES = Collections.unmodifiableList(funkies);
}
@Test
public void test() {
for (String name : FUNKY_LEGAL_NAMES) {
new TableNameTest(name).test();
}
}
}
/**
* This class is supposed to be used by other test classes.
*/
public static class TableNameTest extends CreateTableTest {
public String tableName;
public TableNameTest(String tableName) {
this.tableName = tableName;
}
@Override
public CreateTableSpecification specification() {
return CreateTableSpecification.createTable().name(tableName).partitionKeyColumn(cqlId("pk"), DataType.text());
}
/**
* There is no @Test annotation on this method on purpose! It's supposed to be called by another test class's @Test
* method so that you can loop, calling this test method as many times as are necessary.
*/
public void test() {
prepare();
assertPreamble(cqlId(tableName), cql);
}
}
}

View File

@@ -0,0 +1,84 @@
/*
* Copyright 2013-2014 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.test.unit.core.cql.generator;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import org.springframework.cassandra.core.cql.generator.DropIndexCqlGenerator;
import org.springframework.cassandra.core.keyspace.DropIndexSpecification;
public class DropIndexCqlGeneratorTests {
/**
* Asserts that the preamble is first & correctly formatted in the given CQL string.
*/
public static void assertStatement(String indexName, boolean ifExists, String cql) {
assertTrue(cql.equals("DROP INDEX " + (ifExists ? "IF EXISTS " : "") + indexName + ";"));
}
/**
* Convenient base class that other test classes can use so as not to repeat the generics declarations.
*/
public static abstract class DropIndexTest extends
IndexOperationCqlGeneratorTest<DropIndexSpecification, DropIndexCqlGenerator> {
}
public static class BasicTest extends DropIndexTest {
public String name = "myindex";
public DropIndexSpecification specification() {
return DropIndexSpecification.dropIndex().name(name);
}
public DropIndexCqlGenerator generator() {
return new DropIndexCqlGenerator(specification);
}
@Test
public void test() {
prepare();
assertStatement(name, false, cql);
}
}
public static class IfExistsTest extends DropIndexTest {
public String name = "myindex";
public DropIndexSpecification specification() {
return DropIndexSpecification.dropIndex().name(name)
// .ifExists()
;
}
public DropIndexCqlGenerator generator() {
return new DropIndexCqlGenerator(specification);
}
@Test
public void test() {
prepare();
// assertStatement(name, true, cql);
assertStatement(name, false, cql);
}
}
}

View File

@@ -0,0 +1,62 @@
/*
* Copyright 2013-2014 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.test.unit.core.cql.generator;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import org.springframework.cassandra.core.cql.generator.DropKeyspaceCqlGenerator;
import org.springframework.cassandra.core.keyspace.DropKeyspaceSpecification;
import org.springframework.cassandra.test.unit.support.Utils;
public class DropKeyspaceCqlGeneratorTests {
/**
* Asserts that the preamble is first & correctly formatted in the given CQL string.
*/
public static void assertStatement(String tableName, String cql) {
assertTrue(cql.equals("DROP KEYSPACE " + tableName + ";"));
}
/**
* Convenient base class that other test classes can use so as not to repeat the generics declarations.
*/
public static abstract class DropTableTest extends
KeyspaceOperationCqlGeneratorTest<DropKeyspaceSpecification, DropKeyspaceCqlGenerator> {
}
public static class BasicTest extends DropTableTest {
public String name = Utils.randomKeyspaceName();
@Override
public DropKeyspaceSpecification specification() {
return DropKeyspaceSpecification.dropKeyspace().name(name);
}
@Override
public DropKeyspaceCqlGenerator generator() {
return new DropKeyspaceCqlGenerator(specification);
}
@Test
public void test() {
prepare();
assertStatement(name, cql);
}
}
}

View File

@@ -0,0 +1,88 @@
/*
* Copyright 2013-2014 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.test.unit.core.cql.generator;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import org.springframework.cassandra.core.cql.generator.DropTableCqlGenerator;
import org.springframework.cassandra.core.keyspace.DropTableSpecification;
public class DropTableCqlGeneratorTests {
/**
* Asserts that the preamble is first & correctly formatted in the given CQL string.
*/
public static void assertStatement(String tableName, boolean ifExists, String cql) {
assertTrue(cql.equals("DROP TABLE " + (ifExists ? "IF EXISTS " : "") + tableName + ";"));
}
/**
* Asserts that the given list of columns definitions are contained in the given CQL string properly.
*
* @param columnSpec IE, "foo text, bar blob"
*/
public static void assertColumnChanges(String columnSpec, String cql) {
assertTrue(cql.contains(""));
}
/**
* Convenient base class that other test classes can use so as not to repeat the generics declarations.
*/
public static abstract class DropTableTest extends
TableOperationCqlGeneratorTest<DropTableSpecification, DropTableCqlGenerator> {
}
public static class BasicTest extends DropTableTest {
public String name = "mytable";
public DropTableSpecification specification() {
return DropTableSpecification.dropTable().name(name);
}
public DropTableCqlGenerator generator() {
return new DropTableCqlGenerator(specification);
}
@Test
public void test() {
prepare();
assertStatement(name, false, cql);
}
}
// public static class IfExistsTest extends DropTableTest {
//
// public String name = "mytable";
//
// public DropTableSpecification specification() {
// return DropTableSpecification.dropTable().ifExists().name(name);
// }
//
// public DropTableCqlGenerator generator() {
// return new DropTableCqlGenerator(specification);
// }
//
// @Test
// public void test() {
// prepare();
//
// assertStatement(name, true, cql);
// }
// }
}

View File

@@ -0,0 +1,53 @@
/*
* Copyright 2013-2014 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.test.unit.core.cql.generator;
import org.junit.Test;
import org.springframework.cassandra.core.cql.generator.IndexNameCqlGenerator;
import org.springframework.cassandra.core.keyspace.IndexNameSpecification;
/**
* Useful test class that specifies just about as much as you can for a CQL generation test. Intended to be extended by
* classes that contain methods annotated with {@link Test}. Everything is public because this is a test class with no
* need for encapsulation, and it makes for easier reuse in other tests like integration tests (hint hint).
*
* @author Matthew T. Adams
* @author David Webb
*
* @param <S> The type of the {@link IndexNameSpecification}
* @param <G> The type of the {@link IndexNameCqlGenerator}
*/
public abstract class IndexOperationCqlGeneratorTest<S extends IndexNameSpecification<?>, G extends IndexNameCqlGenerator<?>> {
public abstract S specification();
public abstract G generator();
public String indexName;
public S specification;
public G generator;
public String cql;
public void prepare() {
this.specification = specification();
this.generator = generator();
this.cql = generateCql();
}
public String generateCql() {
return generator.toCql();
}
}

View File

@@ -0,0 +1,62 @@
/*
* Copyright 2013-2014 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.test.unit.core.cql.generator;
import java.util.UUID;
import org.apache.commons.lang.StringUtils;
import org.junit.Test;
import org.springframework.cassandra.core.cql.generator.KeyspaceNameCqlGenerator;
import org.springframework.cassandra.core.cql.generator.TableNameCqlGenerator;
import org.springframework.cassandra.core.keyspace.KeyspaceActionSpecification;
import org.springframework.cassandra.core.keyspace.TableNameSpecification;
/**
* Useful test class that specifies just about as much as you can for a CQL generation test. Intended to be extended by
* classes that contain methods annotated with {@link Test}. Everything is public because this is a test class with no
* need for encapsulation, and it makes for easier reuse in other tests like integration tests (hint hint).
*
* @author Matthew T. Adams
*
* @param <S> The type of the {@link TableNameSpecification}
* @param <G> The type of the {@link TableNameCqlGenerator}
*/
public abstract class KeyspaceOperationCqlGeneratorTest<S extends KeyspaceActionSpecification<?>, G extends KeyspaceNameCqlGenerator<?>> {
public abstract S specification();
public abstract G generator();
public String keyspace;
public S specification;
public G generator;
public String cql;
public void prepare() {
this.specification = specification();
this.generator = generator();
this.cql = generateCql();
}
public String generateCql() {
return generator.toCql();
}
public String randomKeyspaceName() {
String name = getClass().getSimpleName() + "_" + UUID.randomUUID().toString().replace("-", "");
return StringUtils.left(name, 47).toLowerCase();
}
}

View File

@@ -0,0 +1,50 @@
/*
* Copyright 2013-2014 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.test.unit.core.cql.generator;
import org.springframework.cassandra.core.cql.generator.TableNameCqlGenerator;
import org.springframework.cassandra.core.keyspace.TableNameSpecification;
/**
* Useful test class that specifies just about as much as you can for a CQL generation test. Intended to be extended by
* classes that contain methods annotated with {@link Test}. Everything is public because this is a test class with no
* need for encapsulation, and it makes for easier reuse in other tests like integration tests (hint hint).
*
* @author Matthew T. Adams
*
* @param <S> The type of the {@link TableNameSpecification}
* @param <G> The type of the {@link TableNameCqlGenerator}
*/
public abstract class TableOperationCqlGeneratorTest<S extends TableNameSpecification<?>, G extends TableNameCqlGenerator<?>> {
public abstract S specification();
public abstract G generator();
public S specification;
public G generator;
public String cql;
public void prepare() {
this.specification = specification();
this.generator = generator();
this.cql = generateCql();
}
public String generateCql() {
return generator.toCql();
}
}

View File

@@ -0,0 +1,119 @@
/*
* Copyright 2013-2014 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.test.unit.core.keyspace;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.lang.annotation.RetentionPolicy;
import org.junit.Test;
import org.springframework.cassandra.core.keyspace.DefaultOption;
import org.springframework.cassandra.core.keyspace.Option;
public class OptionTest {
@Test(expected = IllegalArgumentException.class)
public void testOptionWithNullName() {
new DefaultOption(null, Object.class, true, true, true);
}
@Test(expected = IllegalArgumentException.class)
public void testOptionWithEmptyName() {
new DefaultOption("", Object.class, true, true, true);
}
@Test
public void testOptionWithNullType() {
new DefaultOption("opt", null, true, true, true);
new DefaultOption("opt", null, false, true, true);
}
@Test
public void testOptionWithNullTypeIsCoerceable() {
Option op = new DefaultOption("opt", null, true, true, true);
assertTrue(op.isCoerceable(""));
assertTrue(op.isCoerceable(null));
}
@Test
public void testOptionValueCoercion() {
String name = "my_option";
Class<?> type = String.class;
boolean requires = true;
boolean escapes = true;
boolean quotes = true;
Option op = new DefaultOption(name, type, requires, escapes, quotes);
assertTrue(op.isCoerceable("opt"));
assertEquals("'opt'", op.toString("opt"));
assertEquals("'opt''n'", op.toString("opt'n"));
type = Long.class;
escapes = false;
quotes = false;
op = new DefaultOption(name, type, requires, escapes, quotes);
String expected = "1";
for (Object value : new Object[] { 1, "1" }) {
assertTrue(op.isCoerceable(value));
assertEquals(expected, op.toString(value));
}
assertFalse(op.isCoerceable("x"));
assertTrue(op.isCoerceable(null));
type = Long.class;
escapes = false;
quotes = true;
op = new DefaultOption(name, type, requires, escapes, quotes);
expected = "'1'";
for (Object value : new Object[] { 1, "1" }) {
assertTrue(op.isCoerceable(value));
assertEquals(expected, op.toString(value));
}
assertFalse(op.isCoerceable("x"));
assertTrue(op.isCoerceable(null));
type = Double.class;
escapes = false;
quotes = false;
op = new DefaultOption(name, type, requires, escapes, quotes);
String[] expecteds = new String[] { "1", "1.0", "1.0", "1", "1.0", null };
Object[] values = new Object[] { 1, 1.0F, 1.0D, "1", "1.0", null };
for (int i = 0; i < values.length; i++) {
assertTrue(op.isCoerceable(values[i]));
assertEquals(expecteds[i], op.toString(values[i]));
}
assertFalse(op.isCoerceable("x"));
assertTrue(op.isCoerceable(null));
type = RetentionPolicy.class;
escapes = false;
quotes = false;
op = new DefaultOption(name, type, requires, escapes, quotes);
assertTrue(op.isCoerceable(null));
assertTrue(op.isCoerceable(RetentionPolicy.CLASS));
assertTrue(op.isCoerceable("CLASS"));
assertFalse(op.isCoerceable("x"));
assertEquals("CLASS", op.toString("CLASS"));
assertEquals("CLASS", op.toString(RetentionPolicy.CLASS));
}
}

View File

@@ -0,0 +1,86 @@
/*
* Copyright 2013-2014 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.test.unit.support;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import org.springframework.cassandra.support.CassandraExceptionTranslator;
import org.springframework.cassandra.support.exception.CassandraInvalidConfigurationInQueryException;
import org.springframework.cassandra.support.exception.CassandraInvalidQueryException;
import org.springframework.cassandra.support.exception.CassandraKeyspaceExistsException;
import org.springframework.cassandra.support.exception.CassandraSchemaElementExistsException;
import org.springframework.cassandra.support.exception.CassandraTableExistsException;
import org.springframework.dao.DataAccessException;
import com.datastax.driver.core.exceptions.AlreadyExistsException;
import com.datastax.driver.core.exceptions.InvalidConfigurationInQueryException;
import com.datastax.driver.core.exceptions.InvalidQueryException;
public class CassandraExceptionTranslatorTest {
CassandraExceptionTranslator tx = new CassandraExceptionTranslator();
@Test
public void testTableExistsException() {
String keyspace = "";
String table = "tbl";
AlreadyExistsException cx = new AlreadyExistsException(keyspace, table);
DataAccessException dax = tx.translateExceptionIfPossible(cx);
assertNotNull(dax);
assertTrue(dax instanceof CassandraTableExistsException);
CassandraTableExistsException x = (CassandraTableExistsException) dax;
assertEquals(table, x.getTableName());
assertEquals(x.getTableName(), x.getElementName());
assertEquals(CassandraSchemaElementExistsException.ElementType.TABLE, x.getElementType());
assertEquals(cx, x.getCause());
}
@Test
public void testKeyspaceExistsException() {
String keyspace = "ks";
String table = "";
AlreadyExistsException cx = new AlreadyExistsException(keyspace, table);
DataAccessException dax = tx.translateExceptionIfPossible(cx);
assertNotNull(dax);
assertTrue(dax instanceof CassandraKeyspaceExistsException);
CassandraKeyspaceExistsException x = (CassandraKeyspaceExistsException) dax;
assertEquals(keyspace, x.getKeyspaceName());
assertEquals(x.getKeyspaceName(), x.getElementName());
assertEquals(CassandraSchemaElementExistsException.ElementType.KEYSPACE, x.getElementType());
assertEquals(cx, x.getCause());
}
@Test
public void testInvalidConfigurationInQueryException() {
String msg = "msg";
InvalidQueryException cx = new InvalidConfigurationInQueryException(msg);
DataAccessException dax = tx.translateExceptionIfPossible(cx);
assertNotNull(dax);
assertTrue(dax instanceof CassandraInvalidConfigurationInQueryException);
assertEquals(cx, dax.getCause());
cx = new InvalidQueryException(msg);
dax = tx.translateExceptionIfPossible(cx);
assertNotNull(dax);
assertTrue(dax instanceof CassandraInvalidQueryException);
assertEquals(cx, dax.getCause());
}
}

View File

@@ -0,0 +1,26 @@
/*
* Copyright 2013-2014 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.test.unit.support;
import java.util.UUID;
public class Utils {
public static String randomKeyspaceName() {
return "ks" + UUID.randomUUID().toString().replace("-", "");
}
}