Elffuss BraidHub

kikocis/java-driver public

Merge branch '2.1' into 3.0

Conflicts:
	changelog/README.md
	driver-core/src/main/java/com/datastax/driver/core/Cluster.java
	driver-core/src/main/java/com/datastax/driver/core/Connection.java
	driver-core/src/main/java/com/datastax/driver/core/ProtocolVersion.java
	driver-core/src/test/java/com/datastax/driver/core/AuthenticationTest.java
	driver-core/src/test/java/com/datastax/driver/core/BatchStatementTest.java
	driver-core/src/test/java/com/datastax/driver/core/CCMBridge.java
	driver-core/src/test/java/com/datastax/driver/core/ConsistencyTest.java
	driver-core/src/test/java/com/datastax/driver/core/CustomTypeTest.java
	driver-core/src/test/java/com/datastax/driver/core/FetchingTest.java
	driver-core/src/test/java/com/datastax/driver/core/IndexMetadataTest.java
	driver-core/src/test/java/com/datastax/driver/core/NodeRefreshDebouncerTest.java
	driver-core/src/test/java/com/datastax/driver/core/RequestHandlerTest.java
	driver-core/src/test/java/com/datastax/driver/core/SSLAuthenticatedEncryptionTest.java
	driver-core/src/test/java/com/datastax/driver/core/SSLEncryptionTest.java
	driver-core/src/test/java/com/datastax/driver/core/SSLTestBase.java
	driver-core/src/test/java/com/datastax/driver/core/ScassandraTestBase.java
	driver-core/src/test/java/com/datastax/driver/core/SchemaRefreshDebouncerTest.java
	driver-core/src/test/java/com/datastax/driver/core/SchemaTest.java
	driver-core/src/test/java/com/datastax/driver/core/SessionLeakTest.java
	driver-core/src/test/java/com/datastax/driver/core/SessionTest.java
	driver-core/src/test/java/com/datastax/driver/core/SpeculativeExecutionTest.java
	driver-core/src/test/java/com/datastax/driver/core/TableMetadataTest.java
	driver-core/src/test/java/com/datastax/driver/core/TestUtils.java
	driver-core/src/test/java/com/datastax/driver/core/TokenIntegrationTest.java
	driver-core/src/test/java/com/datastax/driver/core/TupleTest.java
	driver-core/src/test/java/com/datastax/driver/core/UserTypesTest.java
	driver-core/src/test/java/com/datastax/driver/core/exceptions/ExceptionsTest.java
	driver-core/src/test/java/com/datastax/driver/core/policies/DefaultRetryPolicyIntegrationTest.java
	driver-core/src/test/java/com/datastax/driver/core/policies/DowngradingConsistencyRetryPolicyIntegrationTest.java
	driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderRoutingKeyTest.java
	driver-examples/osgi/src/test/java/com/datastax/driver/osgi/MailboxServiceIT.java
	driver-mapping/src/test/java/com/datastax/driver/mapping/MapperAccessorParamsTest.java
	driver-mapping/src/test/java/com/datastax/driver/mapping/MapperDefaultKeyspaceTest.java
	driver-mapping/src/test/java/com/datastax/driver/mapping/MapperEnumTest.java
	driver-mapping/src/test/java/com/datastax/driver/mapping/MapperInvalidCollectionTypesTest.java
	driver-mapping/src/test/java/com/datastax/driver/mapping/MapperTest.java
	driver-mapping/src/test/java/com/datastax/driver/mapping/MapperUDTCollectionsTest.java
	driver-mapping/src/test/java/com/datastax/driver/mapping/MapperUDTTest.java
Changeset28abe791a9212816fcce9cf2d4dc6427a3b009698e737a65fafe9565c821bcb8
AuthorAlexandre Dutra <alexandre.dutra@datastax.com> · 2016-01-14 19:55 +01:00
CommitterAlexandre Dutra <alexandre.dutra@datastax.com> · 2016-01-14 19:55 +01:00
Parentsdf354c9a28e1, 2e4fff5155ad

Browse the files at this changeset

155 files changed

modified build.yaml +2 −0
@@ -22,6 +22,7 @@
2222 ccm.path=$CCM_JAVA_HOME/bin
2323 failIfNoTests=false
2424 maven.test.failure.ignore=true
25+ maven.javadoc.skip=true
2526 - type: maven
2627 version: 3.2.5
2728 goals: verify --fail-never -Pisolated
@@ -33,6 +34,7 @@
3334 ccm.path=$CCM_JAVA_HOME/bin
3435 failIfNoTests=false
3536 maven.test.failure.ignore=true
37+ maven.javadoc.skip=true
3638 - xunit:
3739 - "**/target/surefire-reports/TEST-*.xml"
3840 - "**/target/failsafe-reports/TEST-*.xml"
modified changelog/README.md +8 −0
@@ -1,5 +1,12 @@
11 ## Changelog
22
3+### 3.0.0 (in progress)
4+
5+Merged from 2.1 branch:
6+
7+- [improvement] JAVA-1030: Log token to replica map computation times.
8+
9+
310 ### 3.0.0-rc1
411
512 - [bug] JAVA-890: fix mapper for case-sensitive UDT.
@@ -252,6 +259,7 @@
252259 ### 2.1.10 (in progress)
253260
254261 - [bug] JAVA-988: Metadata.handleId should handle escaped double quotes.
262+- [improvement] JAVA-1030: Log token to replica map computation times.
255263
256264 Merged from 2.0 branch:
257265
modified driver-core/src/main/java/com/datastax/driver/core/AbstractReconnectionHandler.java +2 −2
@@ -50,7 +50,8 @@
5050 */
5151 private final AtomicReference<ListenableFuture<?>> currentAttempt;
5252
53- private final HandlerFuture handlerFuture = new HandlerFuture();
53+ @VisibleForTesting
54+ final HandlerFuture handlerFuture = new HandlerFuture();
5455
5556 private final long initialDelayMs;
5657
@@ -133,7 +134,6 @@
133134
134135 if (handlerFuture.isCancelled()) {
135136 logger.debug("Got cancelled, stopping");
136- currentAttempt.compareAndSet(handlerFuture, null);
137137 return;
138138 }
139139
modified driver-core/src/main/java/com/datastax/driver/core/Cluster.java +29 −3
@@ -897,11 +897,37 @@
897897 * points. Contrarily to other {@code addContactPoints} methods, this method
898898 * allow to provide a different port for each contact points. Since Cassandra
899899 * nodes must always all listen on the same port, this is rarelly what you
900- * want and most use should prefer other {@code addContactPoints} methods to
900+ * want and most users should prefer other {@code addContactPoints} methods to
901901 * this one. However, this can be useful if the Cassandra nodes are behind
902902 * a router and are not accessed directly. Note that if you are in this
903- * situtation (Cassandra nodes are behind a router, not directly accessible),
904- * you almost surely want to provide a specific {@link AddressTranslator}
903+ * situation (Cassandra nodes are behind a router, not directly accessible),
904+ * you almost surely want to provide a specific {@code AddressTranslator}
905+ * (through {@link #withAddressTranslator}) to translate actual Cassandra node
906+ * addresses to the addresses the driver should use, otherwise the driver
907+ * will not be able to auto-detect new nodes (and will generally not function
908+ * optimally).
909+ *
910+ * @param addresses addresses of the nodes to add as contact point
911+ * @return this Builder
912+ * @see Builder#addContactPoint
913+ */
914+ public Builder addContactPointsWithPorts(InetSocketAddress... addresses) {
915+ Collections.addAll(this.addresses, addresses);
916+ return this;
917+ }
918+
919+ /**
920+ * Adds contact points.
921+ * <p/>
922+ * See {@link Builder#addContactPoint} for more details on contact
923+ * points. Contrarily to other {@code addContactPoints} methods, this method
924+ * allow to provide a different port for each contact points. Since Cassandra
925+ * nodes must always all listen on the same port, this is rarelly what you
926+ * want and most users should prefer other {@code addContactPoints} methods to
927+ * this one. However, this can be useful if the Cassandra nodes are behind
928+ * a router and are not accessed directly. Note that if you are in this
929+ * situation (Cassandra nodes are behind a router, not directly accessible),
930+ * you almost surely want to provide a specific {@code AddressTranslator}
905931 * (through {@link #withAddressTranslator}) to translate actual Cassandra node
906932 * addresses to the addresses the driver should use, otherwise the driver
907933 * will not be able to auto-detect new nodes (and will generally not function
modified driver-core/src/main/java/com/datastax/driver/core/ConvictionPolicy.java +3 −1
@@ -126,8 +126,10 @@
126126
127127 @Override
128128 boolean canReconnectNow() {
129- return nextReconnectionTime == Long.MIN_VALUE ||
129+ boolean canReconnectNow = nextReconnectionTime == Long.MIN_VALUE ||
130130 System.nanoTime() >= nextReconnectionTime;
131+ Host.statesLogger.trace("canReconnectNow={}", canReconnectNow);
132+ return canReconnectNow;
131133 }
132134
133135 static class Factory implements ConvictionPolicy.Factory {
modified driver-core/src/main/java/com/datastax/driver/core/ReplicationStategy.java +11 −1
@@ -118,7 +118,12 @@
118118 }
119119
120120 @Override
121- Map<Token, Set<Host>> computeTokenToReplicaMap(String keyspaceName, Map<Token, Host> tokenToPrimary, List<Token> ring) {
121+ Map<Token, Set<Host>> computeTokenToReplicaMap(String keyspaceName, Map<Token, Host> tokenToPrimary, List<Token> ring) {
122+
123+ logger.debug("Computing token to replica map for keyspace: {}.", keyspaceName);
124+
125+ // Track how long it takes to compute the token to replica map
126+ long startTime = System.currentTimeMillis();
122127
123128 // This is essentially a copy of org.apache.cassandra.locator.NetworkTopologyStrategy
124129 Map<String, Set<String>> racks = getRacksInDcs(tokenToPrimary.values());
@@ -201,6 +206,11 @@
201206
202207 replicaMap.put(ring.get(i), ImmutableSet.copyOf(replicas));
203208 }
209+
210+ long duration = System.currentTimeMillis() - startTime;
211+ logger.debug("Token to replica map computation for keyspace {} completed in {} milliseconds",
212+ keyspaceName, duration);
213+
204214 return replicaMap;
205215 }
206216
modified driver-core/src/test/java/com/datastax/driver/core/AbstractPoliciesTest.java +61 −50
@@ -15,47 +15,55 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import org.testng.annotations.BeforeMethod;
19+
1820 import java.net.InetAddress;
1921 import java.nio.ByteBuffer;
2022 import java.util.HashMap;
2123 import java.util.Map;
24+import java.util.concurrent.Callable;
2225
2326 import static com.datastax.driver.core.TestUtils.*;
2427 import static com.datastax.driver.core.querybuilder.QueryBuilder.batch;
2528 import static com.datastax.driver.core.querybuilder.QueryBuilder.insertInto;
2629 import static org.testng.Assert.*;
2730
28-public abstract class AbstractPoliciesTest {
31+public abstract class AbstractPoliciesTest extends CCMTestsSupport {
32+
2933 private static final boolean DEBUG = false;
3034
3135 protected Map<InetAddress, Integer> coordinators = new HashMap<InetAddress, Integer>();
32- protected PreparedStatement prepared;
3336
37+ protected PreparedStatement prepared;
3438
35- /**
36- * Create schemas for the policy tests, depending on replication factors/strategies.
37- */
38- public static void createSchema(Session session) {
39- createSchema(session, 1);
40- }
41-
42- public static void createSchema(Session session, int replicationFactor) {
43- session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, SIMPLE_KEYSPACE, replicationFactor));
44- session.execute("USE " + SIMPLE_KEYSPACE);
39+ protected void createSchema(int replicationFactor) {
40+ final String ks = TestUtils.getAvailableKeyspaceName();
41+ session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, ks, replicationFactor));
42+ // tests fail randomly here with InvalidQueryException: Keyspace 'xxx' does not exist
43+ ConditionChecker.awaitUntil(new Callable<Boolean>() {
44+ @Override
45+ public Boolean call() {
46+ return cluster.getMetadata().getKeyspace(ks) != null;
47+ }
48+ }, 60000);
49+ session.execute("USE " + ks);
4550 session.execute(String.format("CREATE TABLE %s (k int PRIMARY KEY, i int)", SIMPLE_TABLE));
4651 }
4752
48- public static void createMultiDCSchema(Session session) {
49- createMultiDCSchema(session, 1, 1);
50- }
51-
52- public static void createMultiDCSchema(Session session, int dc1RF, int dc2RF) {
53- session.execute(String.format(CREATE_KEYSPACE_GENERIC_FORMAT, SIMPLE_KEYSPACE, "NetworkTopologyStrategy", String.format("'dc1' : %d, 'dc2' : %d", dc1RF, dc2RF)));
54- session.execute("USE " + SIMPLE_KEYSPACE);
53+ protected void createMultiDCSchema(int dc1RF, int dc2RF) {
54+ final String ks = TestUtils.getAvailableKeyspaceName();
55+ session.execute(String.format(CREATE_KEYSPACE_GENERIC_FORMAT, ks, "NetworkTopologyStrategy", String.format("'dc1' : %d, 'dc2' : %d", dc1RF, dc2RF)));
56+ // tests fail randomly here with InvalidQueryException: Keyspace 'xxx' does not exist
57+ ConditionChecker.awaitUntil(new Callable<Boolean>() {
58+ @Override
59+ public Boolean call() {
60+ return cluster.getMetadata().getKeyspace(ks) != null;
61+ }
62+ }, 60000);
63+ session.execute("USE " + ks);
5564 session.execute(String.format("CREATE TABLE %s (k int PRIMARY KEY, i int)", SIMPLE_TABLE));
5665 }
5766
58-
5967 /**
6068 * Coordinator management/count
6169 */
@@ -65,6 +73,7 @@
6573 coordinators.put(coordinator, n == null ? 1 : n + 1);
6674 }
6775
76+ @BeforeMethod(groups = "long")
6877 protected void resetCoordinators() {
6978 coordinators = new HashMap<InetAddress, Integer>();
7079 }
@@ -120,12 +129,12 @@
120129 else {
121130
122131 if (n == queried) {
123- if (found == true)
124- throw new AssertionError(String.format("Found 2 nodes with " + n + " queries in " + queriedMapString()));
132+ if (found)
133+ throw new AssertionError(String.format("Found 2 nodes with %s queries in %s", n, queriedMapString()));
125134 found = true;
126135 } else {
127136 if (queried != 0)
128- throw new AssertionError(String.format("Host " + addr + " should have be queried: " + queriedMapString()));
137+ throw new AssertionError(String.format("Host %s should have be queried: %s", addr, queriedMapString()));
129138 }
130139 }
131140 }
@@ -147,72 +156,74 @@
147156 /**
148157 * Init methods that handle writes using batch and consistency options.
149158 */
150- protected void init(CCMBridge.CCMCluster c, int n) {
151- write(c, n, false, ConsistencyLevel.ONE);
152- prepared = c.session.prepare("SELECT * FROM " + SIMPLE_TABLE + " WHERE k = ?").setConsistencyLevel(ConsistencyLevel.ONE);
159+ protected void init(int n) {
160+ init(n, false, ConsistencyLevel.ONE);
161+ }
162+
163+ protected void init(int n, boolean batch) {
164+ init(n, batch, ConsistencyLevel.ONE);
153165 }
154166
155- protected void init(CCMBridge.CCMCluster c, int n, boolean batch) {
156- write(c, n, batch, ConsistencyLevel.ONE);
157- prepared = c.session.prepare("SELECT * FROM " + SIMPLE_TABLE + " WHERE k = ?").setConsistencyLevel(ConsistencyLevel.ONE);
167+ protected void init(int n, ConsistencyLevel cl) {
168+ write(n, false, cl);
158169 }
159170
160- protected void init(CCMBridge.CCMCluster c, int n, ConsistencyLevel cl) {
161- write(c, n, false, cl);
162- prepared = c.session.prepare("SELECT * FROM " + SIMPLE_TABLE + " WHERE k = ?").setConsistencyLevel(cl);
171+ protected void init(int n, boolean batch, ConsistencyLevel cl) {
172+ write(n, batch, cl);
173+ prepared = session.prepare("SELECT * FROM " + SIMPLE_TABLE + " WHERE k = ?").setConsistencyLevel(cl);
163174 }
164175
165- protected void write(CCMBridge.CCMCluster c, int n) {
166- write(c, n, false, ConsistencyLevel.ONE);
176+ protected void write(int n) {
177+ write(n, false, ConsistencyLevel.ONE);
167178 }
168179
169- protected void write(CCMBridge.CCMCluster c, int n, boolean batch) {
170- write(c, n, batch, ConsistencyLevel.ONE);
180+ protected void write(int n, boolean batch) {
181+ write(n, batch, ConsistencyLevel.ONE);
171182 }
172183
173- protected void write(CCMBridge.CCMCluster c, int n, ConsistencyLevel cl) {
174- write(c, n, false, cl);
184+ protected void write(int n, ConsistencyLevel cl) {
185+ write(n, false, cl);
175186 }
176187
177- protected void write(CCMBridge.CCMCluster c, int n, boolean batch, ConsistencyLevel cl) {
188+ protected void write(int n, boolean batch, ConsistencyLevel cl) {
178189 // We don't use insert for our test because the resultSet don't ship the queriedHost
179190 // Also note that we don't use tracing because this would trigger requests that screw up the test
180191 for (int i = 0; i < n; ++i)
181192 if (batch)
182193 // BUG: WriteType == SIMPLE
183- c.session.execute(batch()
194+ session.execute(batch()
184195 .add(insertInto(SIMPLE_TABLE).values(new String[]{"k", "i"}, new Object[]{0, 0}))
185196 .setConsistencyLevel(cl));
186197 else
187- c.session.execute(new SimpleStatement(String.format("INSERT INTO %s(k, i) VALUES (0, 0)", SIMPLE_TABLE)).setConsistencyLevel(cl));
198+ session.execute(new SimpleStatement(String.format("INSERT INTO %s(k, i) VALUES (0, 0)", SIMPLE_TABLE)).setConsistencyLevel(cl));
188199 }
189200
190201
191202 /**
192203 * Query methods that handle reads based on PreparedStatements and/or ConsistencyLevels.
193204 */
194- protected void query(CCMBridge.CCMCluster c, int n) {
195- query(c, n, false, ConsistencyLevel.ONE);
205+ protected void query(int n) {
206+ query(n, false, ConsistencyLevel.ONE);
196207 }
197208
198- protected void query(CCMBridge.CCMCluster c, int n, boolean usePrepared) {
199- query(c, n, usePrepared, ConsistencyLevel.ONE);
209+ protected void query(int n, boolean usePrepared) {
210+ query(n, usePrepared, ConsistencyLevel.ONE);
200211 }
201212
202- protected void query(CCMBridge.CCMCluster c, int n, ConsistencyLevel cl) {
203- query(c, n, false, cl);
213+ protected void query(int n, ConsistencyLevel cl) {
214+ query(n, false, cl);
204215 }
205216
206- protected void query(CCMBridge.CCMCluster c, int n, boolean usePrepared, ConsistencyLevel cl) {
217+ protected void query(int n, boolean usePrepared, ConsistencyLevel cl) {
207218 if (usePrepared) {
208219 BoundStatement bs = prepared.bind(0);
209220 for (int i = 0; i < n; ++i)
210- addCoordinator(c.session.execute(bs));
221+ addCoordinator(session.execute(bs));
211222 } else {
212223 ByteBuffer routingKey = ByteBuffer.allocate(4);
213224 routingKey.putInt(0, 0);
214225 for (int i = 0; i < n; ++i)
215- addCoordinator(c.session.execute(new SimpleStatement(String.format("SELECT * FROM %s WHERE k = 0", SIMPLE_TABLE)).setRoutingKey(routingKey).setConsistencyLevel(cl)));
226+ addCoordinator(session.execute(new SimpleStatement(String.format("SELECT * FROM %s WHERE k = 0", SIMPLE_TABLE)).setRoutingKey(routingKey).setConsistencyLevel(cl)));
216227 }
217228 }
218229 }
modified driver-core/src/test/java/com/datastax/driver/core/AbstractReconnectionHandlerTest.java +13 −12
@@ -23,7 +23,6 @@
2323 import com.google.common.util.concurrent.Futures;
2424 import com.google.common.util.concurrent.ListenableFuture;
2525 import com.google.common.util.concurrent.SettableFuture;
26-import com.google.common.util.concurrent.Uninterruptibles;
2726 import org.slf4j.Logger;
2827 import org.slf4j.LoggerFactory;
2928 import org.testng.annotations.AfterMethod;
@@ -31,10 +30,7 @@
3130 import org.testng.annotations.Test;
3231
3332 import java.net.InetSocketAddress;
34-import java.util.concurrent.CyclicBarrier;
35-import java.util.concurrent.Executors;
36-import java.util.concurrent.ScheduledExecutorService;
37-import java.util.concurrent.TimeUnit;
33+import java.util.concurrent.*;
3834 import java.util.concurrent.atomic.AtomicReference;
3935
4036 import static org.assertj.core.api.Assertions.assertThat;
@@ -69,7 +65,7 @@
6965 };
7066 }
7167
72- @AfterMethod(groups = {"unit", "short"})
68+ @AfterMethod(groups = {"unit", "short"}, alwaysRun = true)
7369 public void tearDown() {
7470 if (future.get() != null)
7571 future.get().cancel(false);
@@ -138,7 +134,7 @@
138134 handler.start();
139135
140136 // Wait for the initial schedule of a reconnect.
141- verify(executor, timeout(1000)).schedule(handler, 0, TimeUnit.MILLISECONDS);
137+ verify(executor, timeout(10000)).schedule(handler, 0, TimeUnit.MILLISECONDS);
142138
143139 // Force a failed reconnect.
144140 schedule.tick();
@@ -152,10 +148,16 @@
152148
153149 // Ensure reconnect is scheduled (slight timing window after handling failed reconnect
154150 // and scheduling next reconnect).
155- verify(executor, timeout(1000)).schedule(handler, schedule.delay, TimeUnit.MILLISECONDS);
151+ verify(executor, timeout(10000)).schedule(handler, schedule.delay, TimeUnit.MILLISECONDS);
152+
153+ // Wait until nextTry is assigned after schedule completes.
154+ ConditionChecker.awaitUntil(new Callable<Boolean>() {
155+ @Override
156+ public Boolean call() throws Exception {
157+ return handler.handlerFuture.nextTry != null;
158+ }
159+ }, 10000);
156160
157- // Add a short delay to account for nextTry being assigned after schedule completes.
158- Uninterruptibles.sleepUninterruptibly(5, TimeUnit.MILLISECONDS);
159161 future.get().cancel(false);
160162
161163 // Should immediately return as the future was cancelled while the task was scheduled.
@@ -167,6 +169,7 @@
167169
168170 // The future will be marked cancelled and thus not executed.
169171 ListenableFuture<?> currentAttempt = future.get();
172+
170173 assertThat(currentAttempt).isInstanceOf(HandlerFuture.class);
171174 HandlerFuture handlerFuture = (HandlerFuture) currentAttempt;
172175 assertThat(handlerFuture.isCancelled());
@@ -329,8 +332,6 @@
329332 SUCCEED, THROW_EXCEPTION
330333 }
331334
332- ;
333-
334335 private final CyclicBarrier barrier = new CyclicBarrier(2);
335336
336337 volatile ReconnectBehavior nextReconnect;
modified driver-core/src/test/java/com/datastax/driver/core/AggregateMetadataTest.java +3 −2
@@ -26,7 +26,8 @@
2626 import static com.google.common.collect.Lists.newArrayList;
2727
2828 @CassandraVersion(major = 2.2)
29-public class AggregateMetadataTest extends CCMBridge.PerClassSingleNodeCluster {
29+@CCMConfig(config = "enable_user_defined_functions:true")
30+public class AggregateMetadataTest extends CCMTestsSupport {
3031
3132 @Test(groups = "short")
3233 public void should_parse_and_format_aggregate_with_initcond_and_no_finalfunc() {
@@ -174,7 +175,7 @@
174175 }
175176
176177 @Override
177- protected Collection<String> getTableDefinitions() {
178+ public Collection<String> createTestFixtures() {
178179 return newArrayList(
179180 String.format("CREATE TYPE IF NOT EXISTS %s.phone (number text)", keyspace),
180181 String.format("CREATE TYPE IF NOT EXISTS %s.\"Address\" ("
modified driver-core/src/test/java/com/datastax/driver/core/AsyncQueryTest.java +2 −2
@@ -30,7 +30,7 @@
3030 import static org.testng.Assert.assertEquals;
3131 import static org.testng.Assert.assertTrue;
3232
33-public class AsyncQueryTest extends CCMBridge.PerClassSingleNodeCluster {
33+public class AsyncQueryTest extends CCMTestsSupport {
3434
3535 @DataProvider(name = "keyspace")
3636 public static Object[][] keyspace() {
@@ -38,7 +38,7 @@
3838 }
3939
4040 @Override
41- protected Collection<String> getTableDefinitions() {
41+ public Collection<String> createTestFixtures() {
4242 List<String> definitions = Lists.newArrayList();
4343
4444 for (Object[] objects : keyspace()) {
modified driver-core/src/test/java/com/datastax/driver/core/AsyncResultSetTest.java +2 −2
@@ -30,9 +30,9 @@
3030 import static org.assertj.core.api.Assertions.assertThat;
3131
3232 @CassandraVersion(major = 2.0, description = "uses paging")
33-public class AsyncResultSetTest extends CCMBridge.PerClassSingleNodeCluster {
33+public class AsyncResultSetTest extends CCMTestsSupport {
3434 @Override
35- protected Collection<String> getTableDefinitions() {
35+ public Collection<String> createTestFixtures() {
3636 return Lists.newArrayList(
3737 "create table ints (i int primary key)");
3838 }
modified driver-core/src/test/java/com/datastax/driver/core/AuthenticationTest.java +33 −58
@@ -16,89 +16,64 @@
1616 package com.datastax.driver.core;
1717
1818 import com.datastax.driver.core.exceptions.AuthenticationException;
19-import com.datastax.driver.core.exceptions.NoHostAvailableException;
20-import org.slf4j.Logger;
21-import org.slf4j.LoggerFactory;
22-import org.testng.annotations.AfterClass;
23-import org.testng.annotations.BeforeClass;
19+import com.google.common.util.concurrent.Uninterruptibles;
20+import org.testng.annotations.BeforeMethod;
2421 import org.testng.annotations.Test;
2522
2623 import java.util.concurrent.TimeUnit;
2724
25+import static com.datastax.driver.core.CreateCCM.TestMode.PER_METHOD;
2826 import static com.datastax.driver.core.TestUtils.findHost;
2927 import static org.mockito.Mockito.*;
3028
3129 /**
3230 * Tests for authenticated cluster access
3331 */
34-public class AuthenticationTest {
35-
36- private static final Logger logger = LoggerFactory.getLogger(AuthenticationTest.class);
37-
38- private CCMBridge ccm;
39-
40- /**
41- * creates a cluster and turns on password authentication before starting it.
42- */
43- @BeforeClass(groups = "short")
44- public void setupClusterWithAuthentication() throws InterruptedException {
45- ccm = CCMBridge.builder("test")
46- .withCassandraConfiguration("authenticator", "PasswordAuthenticator")
47- .notStarted()
48- .build();
49- ccm.start(1, "-Dcassandra.superuser_setup_delay_ms=0");
50-
51- // Even though we've override the default user setup delay, still wait
52- // one second to make sure we don't race
53- TimeUnit.SECONDS.sleep(1);
54- }
55-
56- @AfterClass(groups = "short")
57- public void shutdownCluster() {
58- if (ccm != null)
59- ccm.stop();
32+@CreateCCM(PER_METHOD)
33+@CCMConfig(
34+ config = "authenticator:PasswordAuthenticator",
35+ jvmArgs = "-Dcassandra.superuser_setup_delay_ms=0",
36+ createCluster = false)
37+public class AuthenticationTest extends CCMTestsSupport {
38+
39+ @BeforeMethod(groups = "short")
40+ public void sleepIf12() {
41+ // For C* 1.2, sleep before attempting to connect as there is a small delay between
42+ // user being created.
43+ if (ccm.getVersion().getMajor() < 2) {
44+ Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
45+ }
6046 }
6147
6248 @Test(groups = "short")
6349 public void should_connect_with_credentials() throws InterruptedException {
6450 PlainTextAuthProvider authProvider = spy(new PlainTextAuthProvider("cassandra", "cassandra"));
65- Cluster cluster = Cluster.builder().addContactPoint(CCMBridge.IP_PREFIX + '1')
51+ Cluster cluster = Cluster.builder()
52+ .addContactPointsWithPorts(getInitialContactPoints())
53+ .withAddressTranslator(getAddressTranslator())
6654 .withAuthProvider(authProvider)
6755 .build();
68- try {
69- cluster.connect();
70- verify(authProvider, atLeastOnce()).newAuthenticator(findHost(cluster, 1).getSocketAddress(), "org.apache.cassandra.auth.PasswordAuthenticator");
71- } catch (NoHostAvailableException e) {
72- logger.error(e.getCustomMessage(1, true, true));
73- } finally {
74- cluster.close();
75- }
56+ cluster.connect();
57+ verify(authProvider, atLeastOnce()).newAuthenticator(findHost(cluster, 1).getSocketAddress(), "org.apache.cassandra.auth.PasswordAuthenticator");
7658 }
7759
7860 @Test(groups = "short", expectedExceptions = AuthenticationException.class)
7961 public void should_fail_to_connect_with_wrong_credentials() throws InterruptedException {
80- Cluster cluster = Cluster.builder().addContactPoint(CCMBridge.IP_PREFIX + '1')
62+ Cluster cluster = register(Cluster.builder()
63+ .addContactPointsWithPorts(getInitialContactPoints())
64+ .withAddressTranslator(getAddressTranslator())
8165 .withCredentials("bogus", "bogus")
82- .build();
83- try {
84- cluster.connect();
85- } catch (NoHostAvailableException e) {
86- logger.error(e.getCustomMessage(1, true, true));
87- } finally {
88- cluster.close();
89- }
66+ .build());
67+ cluster.connect();
9068 }
9169
9270 @Test(groups = "short", expectedExceptions = AuthenticationException.class)
9371 public void should_fail_to_connect_without_credentials() throws InterruptedException {
94- Cluster cluster = Cluster.builder().addContactPoint(CCMBridge.IP_PREFIX + '1')
95- .build();
96- try {
97- cluster.connect();
98- } catch (NoHostAvailableException e) {
99- logger.error(e.getCustomMessage(1, true, true));
100- } finally {
101- cluster.close();
102- }
72+ Cluster cluster = register(Cluster.builder()
73+ .addContactPointsWithPorts(getInitialContactPoints())
74+ .withAddressTranslator(getAddressTranslator())
75+ .build());
76+ cluster.connect();
10377 }
78+
10479 }
modified driver-core/src/test/java/com/datastax/driver/core/BatchStatementTest.java +21 −38
@@ -22,18 +22,20 @@
2222 import java.util.Collection;
2323 import java.util.Collections;
2424
25+import static com.datastax.driver.core.CreateCCM.TestMode.PER_METHOD;
2526 import static org.testng.Assert.assertEquals;
2627 import static org.testng.Assert.assertTrue;
2728
28-public class BatchStatementTest extends CCMBridge.PerClassSingleNodeCluster {
29+@CreateCCM(PER_METHOD)
30+public class BatchStatementTest extends CCMTestsSupport {
2931
3032 @Override
31- protected Collection<String> getTableDefinitions() {
33+ public Collection<String> createTestFixtures() {
3234 return Collections.singletonList("CREATE TABLE test (k text, v int, PRIMARY KEY (k, v))");
3335 }
3436
3537 @Test(groups = "short")
36- public void simpleBatchTest() throws Throwable {
38+ public void simpleBatchTest() {
3739 try {
3840 PreparedStatement st = session.prepare("INSERT INTO test (k, v) VALUES (?, ?)");
3941
@@ -65,52 +67,33 @@
6567
6668 assertTrue(rs.isExhausted());
6769
68- session.execute("DELETE FROM test WHERE k='key1'");
69- session.execute("DELETE FROM test WHERE k='key2'");
70-
7170 } catch (UnsupportedFeatureException e) {
7271 // This is expected when testing the protocol v1
73- if (cluster.getConfiguration().getProtocolOptions().getProtocolVersion() != ProtocolVersion.V1)
74- throw e;
75- } catch (Throwable t) {
76- errorOut();
77- throw t;
72+ assertEquals(cluster.getConfiguration().getProtocolOptions().getProtocolVersion(), ProtocolVersion.V1);
7873 }
7974 }
8075
8176 @Test(groups = "short")
8277 @CassandraVersion(major = 2.0, minor = 9, description = "This will only work with C* 2.0.9 (CASSANDRA-7337)")
83- public void casBatchTest() throws Throwable {
84- try {
85- PreparedStatement st = session.prepare("INSERT INTO test (k, v) VALUES (?, ?) IF NOT EXISTS");
78+ public void casBatchTest() {
79+ PreparedStatement st = session.prepare("INSERT INTO test (k, v) VALUES (?, ?) IF NOT EXISTS");
8680
87- BatchStatement batch = new BatchStatement();
88-
89- batch.add(new SimpleStatement("INSERT INTO test (k, v) VALUES (?, ?)", "key1", 0));
90- batch.add(st.bind("key1", 1));
91- batch.add(st.bind("key1", 2));
81+ BatchStatement batch = new BatchStatement();
9282
93- assertEquals(3, batch.size());
83+ batch.add(new SimpleStatement("INSERT INTO test (k, v) VALUES (?, ?)", "key1", 0));
84+ batch.add(st.bind("key1", 1));
85+ batch.add(st.bind("key1", 2));
9486
95- ResultSet rs = session.execute(batch);
96- Row r = rs.one();
97- assertTrue(!r.isNull("[applied]"));
98- assertEquals(r.getBool("[applied]"), true);
87+ assertEquals(3, batch.size());
9988
100- rs = session.execute(batch);
101- r = rs.one();
102- assertTrue(!r.isNull("[applied]"));
103- assertEquals(r.getBool("[applied]"), false);
89+ ResultSet rs = session.execute(batch);
90+ Row r = rs.one();
91+ assertTrue(!r.isNull("[applied]"));
92+ assertEquals(r.getBool("[applied]"), true);
10493
105- } catch (UnsupportedFeatureException e) {
106- // This is expected when testing the protocol v1
107- if (cluster.getConfiguration().getProtocolOptions().getProtocolVersion() != ProtocolVersion.V1)
108- throw e;
109- } catch (Throwable t) {
110- errorOut();
111- throw t;
112- } finally {
113- session.execute("DELETE FROM test WHERE k='key1'");
114- }
94+ rs = session.execute(batch);
95+ r = rs.one();
96+ assertTrue(!r.isNull("[applied]"));
97+ assertEquals(r.getBool("[applied]"), false);
11598 }
11699 }
modified driver-core/src/test/java/com/datastax/driver/core/BoundStatementTest.java +3 −3
@@ -25,12 +25,12 @@
2525 import static org.assertj.core.api.Assertions.assertThat;
2626 import static org.assertj.core.api.Assertions.fail;
2727
28-public class BoundStatementTest extends CCMBridge.PerClassSingleNodeCluster {
28+public class BoundStatementTest extends CCMTestsSupport {
2929
3030 PreparedStatement prepared;
3131
3232 @Override
33- protected Collection<String> getTableDefinitions() {
33+ public Collection<String> createTestFixtures() {
3434 return Lists.newArrayList("CREATE TABLE foo (k int primary key, v1 text, v2 list<int>)");
3535 }
3636
@@ -66,4 +66,4 @@
6666 fail("Expected index error");
6767 } catch (IndexOutOfBoundsException e) { /* expected */ }
6868 }
69-}
No newline at the end of the file
69+}
modified driver-core/src/test/java/com/datastax/driver/core/CCMBridge.java +474 −440
@@ -15,10 +15,9 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import com.datastax.driver.core.exceptions.AlreadyExistsException;
19-import com.datastax.driver.core.exceptions.DriverException;
20-import com.datastax.driver.core.exceptions.NoHostAvailableException;
18+import com.datastax.driver.core.policies.AddressTranslator;
2119 import com.google.common.base.Joiner;
20+import com.google.common.base.Throwables;
2221 import com.google.common.collect.ImmutableMap;
2322 import com.google.common.collect.Maps;
2423 import com.google.common.io.ByteStreams;
@@ -27,29 +26,18 @@
2726 import org.apache.commons.exec.*;
2827 import org.slf4j.Logger;
2928 import org.slf4j.LoggerFactory;
30-import org.testng.annotations.AfterClass;
31-import org.testng.annotations.BeforeClass;
3229
3330 import java.io.*;
34-import java.net.InetAddress;
3531 import java.net.InetSocketAddress;
36-import java.net.Socket;
37-import java.net.UnknownHostException;
38-import java.util.Collection;
39-import java.util.Collections;
40-import java.util.Map;
41-import java.util.concurrent.TimeUnit;
42-import java.util.concurrent.atomic.AtomicLong;
43-
44-import static com.datastax.driver.core.TestUtils.CREATE_KEYSPACE_SIMPLE_FORMAT;
45-import static com.datastax.driver.core.TestUtils.SIMPLE_KEYSPACE;
46-import static org.testng.Assert.fail;
47-
48-public class CCMBridge {
32+import java.util.*;
33+import java.util.concurrent.atomic.AtomicInteger;
4934
50- private static final Logger logger = LoggerFactory.getLogger(CCMBridge.class);
35+import static com.datastax.driver.core.TestUtils.executeNoFail;
36+import static com.datastax.driver.core.TestUtils.findAvailablePort;
37+
38+public class CCMBridge implements Closeable {
5139
52- public static final String IP_PREFIX;
40+ private static final Logger logger = LoggerFactory.getLogger(CCMBridge.class);
5341
5442 private static final String CASSANDRA_VERSION;
5543
@@ -157,7 +145,7 @@
157145 installArgs.append("-v git:");
158146 installArgs.append(branch.trim().replaceAll("\"", ""));
159147 } else {
160- installArgs.append("-v");
148+ installArgs.append("-v ");
161149 installArgs.append(CASSANDRA_VERSION);
162150 }
163151
@@ -167,12 +155,6 @@
167155
168156 CASSANDRA_INSTALL_ARGS = installArgs.toString();
169157
170- String ip_prefix = System.getProperty("ipprefix");
171- if (ip_prefix == null || ip_prefix.isEmpty()) {
172- ip_prefix = "127.0.1.";
173- }
174- IP_PREFIX = ip_prefix;
175-
176158 // Inherit the current environment.
177159 Map<String, String> envMap = Maps.newHashMap(new ProcessBuilder().environment());
178160 // If ccm.path is set, override the PATH variable with it.
@@ -218,13 +200,38 @@
218200 return osName != null && osName.startsWith("Windows");
219201 }
220202
203+ private final String clusterName;
204+
205+ private final VersionNumber version;
206+
207+ private final int storagePort;
208+
209+ private final int thriftPort;
210+
211+ private final int binaryPort;
212+
221213 private final File ccmDir;
222214
223215 private final boolean isDSE;
224216
225- private CCMBridge(boolean isDSE) {
226- this.ccmDir = Files.createTempDir();
217+ private final String jvmArgs;
218+
219+ private final int initialNumberOfNodes;
220+
221+ private boolean keepLogs = false;
222+
223+ private boolean closed = false;
224+
225+ private CCMBridge(String clusterName, boolean isDSE, VersionNumber version, int storagePort, int thriftPort, int binaryPort, String jvmArgs, int initialNumberOfNodes) {
226+ this.clusterName = clusterName;
227+ this.version = version;
228+ this.storagePort = storagePort;
229+ this.thriftPort = thriftPort;
230+ this.binaryPort = binaryPort;
227231 this.isDSE = isDSE;
232+ this.jvmArgs = jvmArgs;
233+ this.initialNumberOfNodes = initialNumberOfNodes;
234+ this.ccmDir = Files.createTempDir();
228235 }
229236
230237 /**
@@ -284,154 +291,242 @@
284291 return CASSANDRA_INSTALL_ARGS;
285292 }
286293
294+ public static Builder builder() {
295+ return new Builder();
296+ }
297+
287298 /**
288- * <p>
289- * Extracts a keystore from the classpath into a temporary file.
290- * </p>
299+ * Returns the address of the {@code nth} host in the CCM cluster (counting from 1, i.e.,
300+ * {@code getHostAddress(1)} returns the address of the first node.
291301 * <p/>
292- * <p>
293- * This is needed as the keystore could be part of a built test jar used by other
294- * projects, and they need to be extracted to a file system so cassandra may use them.
295- * </p>
302+ * In multi-DC setups, nodes are numbered in ascending order of their datacenter number.
303+ * E.g. with 2 DCs and 3 nodes in each DC, the first node in DC 2 is number 4.
296304 *
297- * @param storePath Path in classpath where the keystore exists.
298- * @return The generated File.
305+ * @return the address of the {@code nth} host in the cluster.
299306 */
300- private static File createTempStore(String storePath) {
301- File f = null;
302- Closer closer = Closer.create();
303- try {
304- InputStream trustStoreIs = CCMBridge.class.getResourceAsStream(storePath);
305- closer.register(trustStoreIs);
306- f = File.createTempFile("server", ".store");
307- logger.debug("Created store file {} for {}.", f, storePath);
308- OutputStream trustStoreOs = new FileOutputStream(f);
309- closer.register(trustStoreOs);
310- ByteStreams.copy(trustStoreIs, trustStoreOs);
311- } catch (IOException e) {
312- logger.warn("Failure to write keystore, SSL-enabled servers may fail to start.", e);
313- } finally {
314- try {
315- closer.close();
316- } catch (IOException e) {
317- logger.warn("Failure closing streams.", e);
307+ public InetSocketAddress addressOfNode(int n) {
308+ return new InetSocketAddress(TestUtils.ipOfNode(n), binaryPort);
309+ }
310+
311+ /**
312+ * Returns an {@link AddressTranslator} to use when tests must manually create
313+ * {@link Cluster} instances.
314+ * <p/>
315+ * This translator is necessary because hosts in this cluster do not necessarily use standard ports.
316+ *
317+ * @return an {@link AddressTranslator} to use when tests must manually create
318+ * {@link Cluster} instances.
319+ */
320+ public AddressTranslator addressTranslator() {
321+ return new AddressTranslator() {
322+ @Override
323+ public InetSocketAddress translate(InetSocketAddress address) {
324+ return new InetSocketAddress(address.getAddress(), getBinaryPort());
318325 }
319- }
320- return f;
326+
327+ @Override
328+ public void init(Cluster cluster) {
329+
330+ }
331+
332+ @Override
333+ public void close() {
334+
335+ }
336+ };
337+ }
338+
339+ /**
340+ * Returns the Cassandra version of this CCM cluster.
341+ * <p/>
342+ * By default the version is equal to {@link #getCassandraVersion()}.
343+ *
344+ * @return The version of this CCM cluster.
345+ */
346+ public VersionNumber getVersion() {
347+ return version;
348+ }
349+
350+ /**
351+ * The number of nodes that were initially created with this CCM instance.
352+ * <p/>
353+ * This does not account for nodes created or removed during the cluster's lifecycle.
354+ *
355+ * @return The number of nodes that were initially created with this CCM instance.
356+ */
357+ public int getInitialNumberOfNodes() {
358+ return initialNumberOfNodes;
359+ }
360+
361+ public File getCcmDir() {
362+ return ccmDir;
321363 }
322364
323- public static Builder builder(String clusterName) {
324- return new Builder(clusterName);
365+ public File getClusterDir() {
366+ return new File(ccmDir, clusterName);
325367 }
326368
327- public static CCMBridge.CCMCluster buildCluster(int nbNodes, Cluster.Builder builder) {
328- return CCMCluster.create(nbNodes, builder);
369+ public File getNodeDir(int n) {
370+ return new File(getClusterDir(), "node" + n);
329371 }
330372
331- public static CCMBridge.CCMCluster buildCluster(int nbNodesDC1, int nbNodesDC2, Cluster.Builder builder) {
332- return CCMCluster.create(nbNodesDC1, nbNodesDC2, builder);
373+ public File getNodeConfDir(int n) {
374+ return new File(getNodeDir(n), "conf");
375+ }
376+
377+ public int getStoragePort() {
378+ return storagePort;
379+ }
380+
381+ public int getThriftPort() {
382+ return thriftPort;
383+ }
384+
385+ public int getBinaryPort() {
386+ return binaryPort;
387+ }
388+
389+ public void setKeepLogs(boolean keepLogs) {
390+ this.keepLogs = keepLogs;
391+ }
392+
393+ @Override
394+ public synchronized void close() {
395+ if (closed)
396+ return;
397+ logger.debug("Closing: " + this);
398+ if (keepLogs) {
399+ executeNoFail(new Runnable() {
400+ @Override
401+ public void run() {
402+ stop();
403+ }
404+ }, false);
405+ logger.info("Error during tests, kept C* logs in " + getCcmDir());
406+ } else {
407+ executeNoFail(new Runnable() {
408+ @Override
409+ public void run() {
410+ remove();
411+ }
412+ }, false);
413+ executeNoFail(new Runnable() {
414+ @Override
415+ public void run() {
416+ org.assertj.core.util.Files.delete(getCcmDir());
417+ }
418+ }, false);
419+ }
420+ closed = true;
421+ logger.debug("Closed: " + this);
333422 }
334423
335424 public void start() {
336- execute(CCM_COMMAND + " start --wait-other-notice --wait-for-binary-proto");
425+ logger.debug("Starting: " + this);
426+ execute(CCM_COMMAND + " start --wait-other-notice --wait-for-binary-proto" + jvmArgs);
337427 }
338428
339- public void stop() {
429+ public synchronized void stop() {
430+ if (closed)
431+ return;
432+ logger.debug("Stopping: " + this);
340433 execute(CCM_COMMAND + " stop");
434+ closed = true;
341435 }
342436
343- public void forceStop() {
437+ public synchronized void forceStop() {
438+ if (closed)
439+ return;
440+ logger.debug("Force stopping: " + this);
344441 execute(CCM_COMMAND + " stop --not-gently");
442+ closed = true;
345443 }
346444
347445 public void start(int n) {
348- logger.info("Starting: " + IP_PREFIX + n);
349- execute(CCM_COMMAND + " node%d start --wait-other-notice --wait-for-binary-proto", n);
350- }
351-
352- public void start(int n, String... jvmArg) {
353- StringBuilder jvmArgs = new StringBuilder("");
354- for (int i = 0; i < jvmArg.length; i++) {
355- jvmArgs.append(" --jvm_arg=");
356- jvmArgs.append(jvmArg[i]);
357- }
358- logger.info("Starting: " + IP_PREFIX + n + " with " + jvmArgs);
359- execute(CCM_COMMAND + " node%d start --wait-other-notice --wait-for-binary-proto %s", n, jvmArgs.toString());
446+ logger.debug(String.format("Starting: node %s (%s%s:%s) in %s", n, TestUtils.IP_PREFIX, n, binaryPort, this));
447+ execute(CCM_COMMAND + " node%d start --wait-other-notice --wait-for-binary-proto" + jvmArgs, n);
360448 }
361449
362450 public void stop(int n) {
363- logger.info("Stopping: " + IP_PREFIX + n);
451+ logger.debug(String.format("Stopping: node %s (%s%s:%s) in %s", n, TestUtils.IP_PREFIX, n, binaryPort, this));
364452 execute(CCM_COMMAND + " node%d stop", n);
365453 }
366454
367- public void stop(String clusterName) {
368- logger.info("Stopping Cluster : " + clusterName);
369- execute(CCM_COMMAND + " stop " + clusterName);
370- }
371-
372455 public void forceStop(int n) {
373- logger.info("Force stopping: " + IP_PREFIX + n);
456+ logger.debug(String.format("Force stopping: node %s (%s%s:%s) in %s", n, TestUtils.IP_PREFIX, n, binaryPort, this));
374457 execute(CCM_COMMAND + " node%d stop --not-gently", n);
375458 }
376459
377- public void remove() {
460+ public synchronized void remove() {
378461 stop();
462+ logger.debug("Removing: " + this);
379463 execute(CCM_COMMAND + " remove");
380464 }
381465
382- public void remove(String clusterName) {
383- stop(clusterName);
384- execute(CCM_COMMAND + " remove " + clusterName);
385- }
386-
387466 public void remove(int n) {
388- logger.info("Removing: " + IP_PREFIX + n);
467+ logger.debug(String.format("Removing: node %s (%s%s:%s) from %s", n, TestUtils.IP_PREFIX, n, binaryPort, this));
389468 execute(CCM_COMMAND + " node%d remove", n);
390469 }
391470
392- public void bootstrapNode(int n) {
393- bootstrapNode(n, null);
394- }
395-
396- public void bootstrapNode(int n, String dc) {
397- if (dc == null)
398- execute(CCM_COMMAND + " add node%d -i %s%d -j %d -r %d -b -s" + (isDSE ? " --dse" : ""), n, IP_PREFIX, n, 7000 + 100 * n, 8000 + 100 * n);
399- else
400- execute(CCM_COMMAND + " add node%d -i %s%d -j %d -b -d %s -s" + (isDSE ? " --dse" : ""), n, IP_PREFIX, n, 7000 + 100 * n, dc);
401- execute(CCM_COMMAND + " node%d start --wait-other-notice --wait-for-binary-proto", n);
471+ public void add(int n) {
472+ add(1, n);
402473 }
403474
404- public void bootstrapNodeWithPorts(int n, int thriftPort, int storagePort, int binaryPort, int jmxPort, int remoteDebugPort, String option) {
405- String thriftItf = IP_PREFIX + n + ":" + thriftPort;
406- String storageItf = IP_PREFIX + n + ":" + storagePort;
407- String binaryItf = IP_PREFIX + n + ":" + binaryPort;
408- String remoteLogItf = IP_PREFIX + n + ":" + remoteDebugPort;
409- execute(CCM_COMMAND + " add node%d -i %s%d -b -t %s -l %s --binary-itf %s -j %d -r %s -s" + (isDSE ? " --dse" : ""),
410- n, IP_PREFIX, n, thriftItf, storageItf, binaryItf, jmxPort, remoteLogItf);
411- if (option == null) start(n);
412- else start(n, option);
475+ public void add(int dc, int n) {
476+ logger.debug(String.format("Adding: node %s (%s%s:%s) to %s", n, TestUtils.IP_PREFIX, n, binaryPort, this));
477+ String thriftItf = TestUtils.ipOfNode(n) + ":" + thriftPort;
478+ String storageItf = TestUtils.ipOfNode(n) + ":" + storagePort;
479+ String binaryItf = TestUtils.ipOfNode(n) + ":" + binaryPort;
480+ String remoteLogItf = TestUtils.ipOfNode(n) + ":" + TestUtils.findAvailablePort();
481+ execute(CCM_COMMAND + " add node%d -d dc%s -i %s%d -t %s -l %s --binary-itf %s -j %d -r %s -s -b" + (isDSE ? " --dse" : ""),
482+ n, dc, TestUtils.IP_PREFIX, n, thriftItf, storageItf, binaryItf, TestUtils.findAvailablePort(), remoteLogItf);
413483 }
414484
415485 public void decommissionNode(int n) {
486+ logger.debug(String.format("Decommissioning: node %s (%s%s:%s) from %s", n, TestUtils.IP_PREFIX, n, binaryPort, this));
416487 execute(CCM_COMMAND + " node%d decommission", n);
417488 }
418489
419- public void updateConfig(Map<String, String> configs) {
490+ public void updateConfig(Map<String, Object> configs) {
420491 StringBuilder confStr = new StringBuilder();
421- for (Map.Entry<String, String> entry : configs.entrySet()) {
422- confStr.append(entry.getKey() + ":" + entry.getValue() + " ");
492+ for (Map.Entry<String, Object> entry : configs.entrySet()) {
493+ confStr
494+ .append(entry.getKey())
495+ .append(":")
496+ .append(entry.getValue())
497+ .append(" ");
423498 }
424499 execute(CCM_COMMAND + " updateconf " + confStr);
425500 }
426501
427- public void updateDSEConfig(Map<String, String> configs) {
502+ public void updateDSEConfig(Map<String, Object> configs) {
428503 StringBuilder confStr = new StringBuilder();
429- for (Map.Entry<String, String> entry : configs.entrySet()) {
430- confStr.append(entry.getKey() + ":" + entry.getValue() + " ");
504+ for (Map.Entry<String, Object> entry : configs.entrySet()) {
505+ confStr
506+ .append(entry.getKey())
507+ .append(":")
508+ .append(entry.getValue())
509+ .append(" ");
431510 }
432511 execute(CCM_COMMAND + " updatedseconf " + confStr);
433512 }
434513
514+ public void updateNodeConfig(int n, String key, Object value) {
515+ updateNodeConfig(n, ImmutableMap.<String, Object>builder().put(key, value).build());
516+ }
517+
518+ public void updateNodeConfig(int n, Map<String, Object> configs) {
519+ StringBuilder confStr = new StringBuilder();
520+ for (Map.Entry<String, Object> entry : configs.entrySet()) {
521+ confStr
522+ .append(entry.getKey())
523+ .append(":")
524+ .append(entry.getValue())
525+ .append(" ");
526+ }
527+ execute(CCM_COMMAND + " node%s updateconf %s", n, confStr);
528+ }
529+
435530 public void setWorkload(int node, String workload) {
436531 execute(CCM_COMMAND + " node%d setworkload %s", node, workload);
437532 }
@@ -439,6 +534,9 @@
439534 private void execute(String command, Object... args) {
440535
441536 String fullCommand = String.format(command, args) + " --config-dir=" + ccmDir;
537+ Closer closer = Closer.create();
538+ // 5 minutes timeout
539+ ExecuteWatchdog watchDog = new ExecuteWatchdog(5 * 60 * 1000);
442540 try {
443541 logger.debug("Executing: " + fullCommand);
444542 CommandLine cli = CommandLine.parse(fullCommand);
@@ -456,9 +554,11 @@
456554 logger.error("ccmerr> " + line);
457555 }
458556 };
459-
557+ closer.register(outStream);
558+ closer.register(errStream);
460559 ExecuteStreamHandler streamHandler = new PumpStreamHandler(outStream, errStream);
461560 executor.setStreamHandler(streamHandler);
561+ executor.setWatchdog(watchDog);
462562
463563 int retValue = executor.execute(cli, ENVIRONMENT_MAP);
464564 if (retValue != 0) {
@@ -466,7 +566,15 @@
466566 throw new RuntimeException();
467567 }
468568 } catch (IOException e) {
569+ if (watchDog.killedProcess())
570+ logger.error("The command {} was killed after 5 minutes", fullCommand);
469571 throw new RuntimeException(String.format("The command %s failed to execute", fullCommand), e);
572+ } finally {
573+ try {
574+ closer.close();
575+ } catch (IOException e) {
576+ Throwables.propagate(e);
577+ }
470578 }
471579 }
472580
@@ -474,323 +582,83 @@
474582 * Waits for a host to be up by pinging the TCP socket directly, without using the Java driver's API.
475583 */
476584 public void waitForUp(int node) {
477- try {
478- InetAddress address = InetAddress.getByName(ipOfNode(node));
479- CCMBridge.busyWaitForPort(address, 9042, true);
480- } catch (UnknownHostException e) {
481- fail("Unknown host " + ipOfNode(node) + "( node " + node + " of CCMBridge)");
482- }
585+ TestUtils.waitUntilPortIsUp(addressOfNode(node));
483586 }
484587
485588 /**
486589 * Waits for a host to be down by pinging the TCP socket directly, without using the Java driver's API.
487590 */
488591 public void waitForDown(int node) {
489- try {
490- InetAddress address = InetAddress.getByName(ipOfNode(node));
491- CCMBridge.busyWaitForPort(address, 9042, false);
492- } catch (UnknownHostException e) {
493- fail("Unknown host " + ipOfNode(node) + "( node " + node + " of CCMBridge)");
494- }
495- }
496-
497- private static void busyWaitForPort(InetAddress address, int port, boolean expectedConnectionState) {
498- long maxAcceptableWaitTime = TimeUnit.SECONDS.toMillis(10);
499- long waitQuantum = TimeUnit.MILLISECONDS.toMillis(500);
500- long waitTimeSoFar = 0;
501- boolean connectionState = !expectedConnectionState;
502-
503- while (connectionState != expectedConnectionState && waitTimeSoFar < maxAcceptableWaitTime) {
504- connectionState = CCMBridge.pingPort(address, port);
505- try {
506- Thread.sleep(waitQuantum);
507- waitTimeSoFar += waitQuantum;
508- } catch (InterruptedException e) {
509- throw new RuntimeException("Interrupted while pinging " + address + ":" + port, e);
510- }
511- }
592+ TestUtils.waitUntilPortIsDown(addressOfNode(node));
512593 }
513594
514- private static boolean pingPort(InetAddress address, int port) {
515- logger.debug("Trying {}:{}...", address, port);
516- boolean connectionSuccessful = false;
517- Socket socket = null;
595+ /**
596+ * <p>
597+ * Extracts a keystore from the classpath into a temporary file.
598+ * </p>
599+ * <p/>
600+ * <p>
601+ * This is needed as the keystore could be part of a built test jar used by other
602+ * projects, and they need to be extracted to a file system so cassandra may use them.
603+ * </p>
604+ *
605+ * @param storePath Path in classpath where the keystore exists.
606+ * @return The generated File.
607+ */
608+ private static File createTempStore(String storePath) {
609+ File f = null;
610+ Closer closer = Closer.create();
518611 try {
519- socket = new Socket(address, port);
520- connectionSuccessful = true;
521- logger.debug("Successfully connected");
612+ InputStream trustStoreIs = CCMBridge.class.getResourceAsStream(storePath);
613+ closer.register(trustStoreIs);
614+ f = File.createTempFile("server", ".store");
615+ logger.debug("Created store file {} for {}.", f, storePath);
616+ OutputStream trustStoreOs = new FileOutputStream(f);
617+ closer.register(trustStoreOs);
618+ ByteStreams.copy(trustStoreIs, trustStoreOs);
522619 } catch (IOException e) {
523- logger.debug("Connection failed");
620+ logger.warn("Failure to write keystore, SSL-enabled servers may fail to start.", e);
524621 } finally {
525- if (socket != null)
526- try {
527- socket.close();
528- } catch (IOException e) {
529- logger.warn("Error closing socket to " + address);
530- }
531- }
532- return connectionSuccessful;
533- }
534-
535- public static String ipOfNode(int nodeNumber) {
536- return IP_PREFIX + Integer.toString(nodeNumber);
537- }
538-
539- public static class TerminationHook extends Thread {
540- @Override
541- public void run() {
542- logger.debug("shut down hook task..");
543-
544- if (PerClassSingleNodeCluster.cluster != null) {
545- PerClassSingleNodeCluster.cluster.close();
546- }
547- if (PerClassSingleNodeCluster.ccmBridge == null) {
548- logger.error("No cluster to discard");
549- } else if (PerClassSingleNodeCluster.erroredOut) {
550- PerClassSingleNodeCluster.ccmBridge.remove("test-class");
551- logger.info("Error during tests, kept C* logs in " + PerClassSingleNodeCluster.ccmBridge.ccmDir);
552- } else {
553- PerClassSingleNodeCluster.ccmBridge.remove("test-class");
554- PerClassSingleNodeCluster.ccmBridge.ccmDir.delete();
555- }
556-
557- }
558- }
559-
560- // One cluster for the whole test class
561- public static abstract class PerClassSingleNodeCluster {
562-
563- private static CCMBridge ccmBridge;
564- private static boolean erroredOut;
565- private static boolean clusterInitialized = false;
566- private static AtomicLong ksNumber;
567- private static final String jvmArgs = "-Dcassandra.custom_query_handler_class=org.apache.cassandra.cql3.CustomPayloadMirroringQueryHandler";
568- protected String keyspace;
569-
570- protected static InetSocketAddress hostAddress;
571- protected static int[] ports;
572-
573- protected static Cluster cluster;
574- protected static Session session;
575-
576- protected final VersionNumber cassandraVersion = VersionNumber.parse(System.getProperty("cassandra.version"));
577-
578- protected abstract Collection<String> getTableDefinitions();
579-
580- // Give individual tests a chance to customize the cluster configuration
581- protected Cluster.Builder configure(Cluster.Builder builder) {
582- return builder;
583- }
584-
585- public void errorOut() {
586- erroredOut = true;
587- }
588-
589- @BeforeClass(groups = {"isolated", "short", "long"})
590- public void beforeClass() {
591- maybeInitCluster();
592- initKeyspace();
593- }
594-
595- @AfterClass(groups = {"isolated", "short", "long"})
596- public void afterClass() {
597- try {
598- clearSimpleKeyspace();
599- } finally {
600- if (cluster != null) {
601- cluster.close();
602- }
603- }
604- }
605-
606- private void maybeInitCluster() {
607- if (!clusterInitialized) {
608- try {
609- ProtocolVersion protocolVersion = TestUtils.getDesiredProtocolVersion();
610-
611- CCMBridge.Builder builder = CCMBridge.builder("test-class")
612- .withoutNodes()
613- .notStarted();
614-
615- if (protocolVersion.compareTo(ProtocolVersion.V4) >= 0) {
616- builder = builder.withCassandraConfiguration("enable_user_defined_functions", "true");
617- }
618- ccmBridge = builder.build();
619-
620- ports = new int[5];
621- for (int i = 0; i < 5; i++) {
622- ports[i] = TestUtils.findAvailablePort(11000 + i);
623- }
624-
625- ccmBridge.bootstrapNodeWithPorts(1, ports[0], ports[1], ports[2], ports[3], ports[4], jvmArgs);
626- ksNumber = new AtomicLong(0);
627- erroredOut = false;
628- hostAddress = new InetSocketAddress(InetAddress.getByName(IP_PREFIX + 1), ports[2]);
629-
630- Runtime r = Runtime.getRuntime();
631- r.addShutdownHook(new TerminationHook());
632- clusterInitialized = true;
633-
634- } catch (UnknownHostException e) {
635- throw new RuntimeException(e);
636- }
637- }
638-
639- }
640-
641-
642- private void initKeyspace() {
643622 try {
644- Cluster.Builder builder = Cluster.builder();
645-
646- builder = configure(builder);
647-
648- cluster = builder.addContactPointsWithPorts(Collections.singletonList(hostAddress)).build();
649- session = cluster.connect();
650- keyspace = SIMPLE_KEYSPACE + "_" + ksNumber.incrementAndGet();
651- session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, 1));
652-
653- session.execute("USE " + keyspace);
654- for (String tableDef : getTableDefinitions()) {
655- try {
656- session.execute(tableDef);
657- } catch (AlreadyExistsException e) {
658- // It's ok, ignore
659- }
660- }
661- } catch (AlreadyExistsException e) {
662- // It's ok, ignore (not supposed to go there)
663- } catch (NoHostAvailableException e) {
664- erroredOut = true;
665- for (Map.Entry<InetSocketAddress, Throwable> entry : e.getErrors().entrySet())
666- logger.info("Error connecting to " + entry.getKey() + ": " + entry.getValue());
667- throw new RuntimeException(e);
668- } catch (DriverException e) {
669- erroredOut = true;
670- throw e;
671- }
672- }
673-
674- private void clearSimpleKeyspace() {
675- if (keyspace != null) {
676- // Temporarily extend read timeout to 1 minute to accommodate keyspaces with many tables.
677- // This should be more than enough although some tests create many tables, so dropping a keyspace
678- // could take as long as 12 seconds on restricted hardware.
679- int currentTimeout = cluster.getConfiguration().getSocketOptions().getReadTimeoutMillis();
680- cluster.getConfiguration().getSocketOptions().setReadTimeoutMillis(60000);
681- try {
682- session.execute("DROP KEYSPACE " + keyspace);
683- } finally {
684- cluster.getConfiguration().getSocketOptions().setReadTimeoutMillis(currentTimeout);
685- }
623+ closer.close();
624+ } catch (IOException e) {
625+ logger.warn("Failure closing streams.", e);
686626 }
687627 }
688-
689- protected void stop() {
690- ccmBridge.stop();
691- }
692-
693- protected void start() {
694- ccmBridge.start(1, jvmArgs);
695- }
696-
628+ return f;
697629 }
698630
699- public static class CCMCluster {
700-
701- public final Cluster cluster;
702- public final Session session;
703-
704- public final CCMBridge cassandraCluster;
705-
706- private boolean erroredOut;
707-
708- public static CCMCluster create(int nbNodes, Cluster.Builder builder) {
709- if (nbNodes == 0)
710- throw new IllegalArgumentException();
711-
712- CCMBridge ccm = CCMBridge.builder("test").withNodes(nbNodes).build();
713- return new CCMCluster(ccm, builder, nbNodes);
714- }
715-
716- public static CCMCluster create(int nbNodesDC1, int nbNodesDC2, Cluster.Builder builder) {
717- if (nbNodesDC1 == 0)
718- throw new IllegalArgumentException();
719-
720- CCMBridge ccm = CCMBridge.builder("test").withNodes(nbNodesDC1, nbNodesDC2).build();
721- return new CCMCluster(ccm, builder, nbNodesDC1 + nbNodesDC2);
722- }
723-
724- public static CCMCluster create(CCMBridge cassandraCluster, Cluster.Builder builder, int totalNodes) {
725- return new CCMCluster(cassandraCluster, builder, totalNodes);
726- }
727-
728- private CCMCluster(CCMBridge cassandraCluster, Cluster.Builder builder, int totalNodes) {
729- this.cassandraCluster = cassandraCluster;
730- try {
731- String[] contactPoints = new String[totalNodes];
732- for (int i = 0; i < totalNodes; i++)
733- contactPoints[i] = IP_PREFIX + (i + 1);
734-
735- try {
736- Thread.sleep(1000);
737- } catch (InterruptedException e) {
738- fail("Unexpected interruption");
739- }
740- this.cluster = builder.addContactPoints(contactPoints).build();
741- this.session = cluster.connect();
742- } catch (NoHostAvailableException e) {
743- for (Map.Entry<InetSocketAddress, Throwable> entry : e.getErrors().entrySet())
744- logger.info("Error connecting to " + entry.getKey() + ": " + entry.getValue());
745- discard();
746- throw new RuntimeException(e);
747- }
748- }
749-
750- public void errorOut() {
751- erroredOut = true;
752- }
753-
754- public void discard() {
755- if (cluster != null)
756- cluster.close();
757-
758- if (cassandraCluster == null) {
759- logger.error("No cluster to discard");
760- } else if (erroredOut) {
761- cassandraCluster.stop();
762- logger.info("Error during tests, kept C* logs in " + cassandraCluster.ccmDir);
763- } else {
764- cassandraCluster.remove();
765- cassandraCluster.ccmDir.delete();
766- }
767- }
631+ @Override
632+ public String toString() {
633+ return "CCM cluster " + clusterName;
768634 }
769635
770636 /**
771- * use {@link #builder(String)} to get an instance
637+ * use {@link #builder()} to get an instance
772638 */
773639 public static class Builder {
774- private final String clusterName;
775- private Integer[] nodes = {1};
640+ private static final AtomicInteger COUNTER = new AtomicInteger(0);
641+ private final String clusterName = "test_" + COUNTER.incrementAndGet();
642+ int[] nodes = {1};
776643 private boolean start = true;
777- private boolean isDSE = IS_DSE;
778- private String cassandraInstallArgs = CASSANDRA_INSTALL_ARGS;
779- private String[] startOptions = new String[0];
780-
781- private Map<String, String> cassandraConfiguration = Maps.newHashMap();
782-
783- private Map<String, String> dseConfiguration = Maps.newHashMap();
784-
785-
786- Builder(String clusterName) {
787- this.clusterName = clusterName;
644+ private boolean isDSE = isDSE();
645+ private String cassandraVersion = getCassandraVersion();
646+ private Set<String> createOptions = new LinkedHashSet<String>();
647+ private Set<String> jvmArgs = new LinkedHashSet<String>();
648+ private final Map<String, Object> cassandraConfiguration = Maps.newHashMap();
649+ private final Map<String, Object> dseConfiguration = Maps.newHashMap();
650+ // -1 means random
651+ private int thriftPort = -1;
652+ private int binaryPort = -1;
653+ private int storagePort = -1;
654+
655+ private Builder() {
788656 }
789657
790658 /**
791- * Number of nodes for each DC. Defaults to [1] (1 DC with 1 node)
659+ * Number of hosts for each DC. Defaults to [1] (1 DC with 1 node)
792660 */
793- public Builder withNodes(Integer... nodes) {
661+ public Builder withNodes(int... nodes) {
794662 this.nodes = nodes;
795663 return this;
796664 }
@@ -799,21 +667,30 @@
799667 return withNodes();
800668 }
801669
802- public Builder withSSL(boolean requireClientAuth) {
670+ /**
671+ * Enables SSL encryption.
672+ */
673+ public Builder withSSL() {
803674 cassandraConfiguration.put("client_encryption_options.enabled", "true");
804675 cassandraConfiguration.put("client_encryption_options.keystore", DEFAULT_SERVER_KEYSTORE_FILE.getAbsolutePath());
805676 cassandraConfiguration.put("client_encryption_options.keystore_password", DEFAULT_SERVER_KEYSTORE_PASSWORD);
677+ return this;
678+ }
806679
807- if (requireClientAuth) {
808- cassandraConfiguration.put("client_encryption_options.require_client_auth", "true");
809- cassandraConfiguration.put("client_encryption_options.truststore", DEFAULT_SERVER_TRUSTSTORE_FILE.getAbsolutePath());
810- cassandraConfiguration.put("client_encryption_options.truststore_password", DEFAULT_SERVER_TRUSTSTORE_PASSWORD);
811- }
680+ /**
681+ * Enables client authentication.
682+ * This also enables encryption ({@link #withSSL()}.
683+ */
684+ public Builder withAuth() {
685+ withSSL();
686+ cassandraConfiguration.put("client_encryption_options.require_client_auth", "true");
687+ cassandraConfiguration.put("client_encryption_options.truststore", DEFAULT_SERVER_TRUSTSTORE_FILE.getAbsolutePath());
688+ cassandraConfiguration.put("client_encryption_options.truststore_password", DEFAULT_SERVER_TRUSTSTORE_PASSWORD);
812689 return this;
813690 }
814691
815692 /**
816- * Whether to start the cluster immediately (defaults to true if this is never called)
693+ * Whether to start the cluster immediately (defaults to true if this is never called).
817694 */
818695 public Builder notStarted() {
819696 this.start = false;
@@ -821,46 +698,96 @@
821698 }
822699
823700 /**
824- * Defaults to system property cassandra.version
701+ * Sets this cluster to be a DSE cluster (defaults to {@link #isDSE()} if this is never called).
825702 */
826- public Builder withCassandraVersion(String cassandraVersion) {
827- this.cassandraInstallArgs = "-v " + cassandraVersion;
828- this.isDSE = false;
703+ public Builder withDSE() {
704+ this.isDSE = true;
829705 return this;
830706 }
831707
832- public Builder withDSEVersion(String dseVersion) {
833- this.cassandraInstallArgs = "-v " + dseVersion + " --dse";
834- this.isDSE = true;
708+ /**
709+ * The Cassandra or DSE version to use.
710+ * <p/>
711+ * Defaults to {@link #getCassandraVersion()}.
712+ */
713+ public Builder withVersion(String cassandraVersion) {
714+ this.cassandraVersion = cassandraVersion;
835715 return this;
836716 }
837717
838718 /**
839- * Free-form options that will be added at the end of the start command
719+ * Free-form options that will be added at the end of the {@code ccm create} command.
840720 */
841- public Builder withStartOptions(String... options) {
842- this.startOptions = options;
721+ public Builder withCreateOptions(String... createOptions) {
722+ Collections.addAll(this.createOptions, createOptions);
843723 return this;
844724 }
845725
846726 /**
847727 * Customizes entries in cassandra.yaml (can be called multiple times)
848728 */
849- public Builder withCassandraConfiguration(String key, String value) {
729+ public Builder withCassandraConfiguration(String key, Object value) {
850730 this.cassandraConfiguration.put(key, value);
851731 return this;
852732 }
853733
854- public Builder withDSEConfiguration(String key, String value) {
734+ /**
735+ * Customizes entries in dse.yaml (can be called multiple times)
736+ */
737+ public Builder withDSEConfiguration(String key, Object value) {
855738 this.dseConfiguration.put(key, value);
856739 return this;
857740 }
858741
742+ /**
743+ * JVM args to use when starting hosts.
744+ * System properties should be provided one by one, as a string in the form:
745+ * {@code -Dname=value}.
746+ */
747+ public Builder withJvmArgs(String... jvmArgs) {
748+ Collections.addAll(this.jvmArgs, jvmArgs);
749+ return this;
750+ }
751+
752+ public Builder withStoragePort(int port) {
753+ storagePort = port;
754+ return this;
755+ }
756+
757+ public Builder withThriftPort(int port) {
758+ thriftPort = port;
759+ return this;
760+ }
761+
762+ public Builder withBinaryPort(int port) {
763+ binaryPort = port;
764+ return this;
765+ }
766+
859767 public CCMBridge build() {
860- CCMBridge ccm = new CCMBridge(isDSE);
768+ // be careful NOT to alter internal state (hashCode/equals) during build!
769+ int initialNumberOfNodes = 0;
770+ for (int nodesPerDc : nodes) {
771+ initialNumberOfNodes += nodesPerDc;
772+ }
773+ int storagePort = this.storagePort == -1 ? findAvailablePort() : this.storagePort;
774+ int thriftPort = this.thriftPort == -1 ? findAvailablePort() : this.thriftPort;
775+ int binaryPort = this.binaryPort == -1 ? findAvailablePort() : this.binaryPort;
776+ VersionNumber version = VersionNumber.parse(cassandraVersion);
777+ final CCMBridge ccm = new CCMBridge(clusterName, isDSE, version, storagePort, thriftPort, binaryPort, joinJvmArgs(), initialNumberOfNodes);
778+ Runtime.getRuntime().addShutdownHook(new Thread() {
779+ @Override
780+ public void run() {
781+ ccm.close();
782+ }
783+ });
861784 ccm.execute(buildCreateCommand());
862- if (!cassandraConfiguration.isEmpty())
863- ccm.updateConfig(cassandraConfiguration);
785+ updateNodeConf(ccm);
786+ HashMap<String, Object> config = new HashMap<String, Object>(cassandraConfiguration);
787+ config.put("storage_port", storagePort);
788+ config.put("rpc_port", thriftPort);
789+ config.put("native_transport_port", binaryPort);
790+ ccm.updateConfig(config);
864791 if (!dseConfiguration.isEmpty())
865792 ccm.updateDSEConfig(dseConfiguration);
866793 if (start)
@@ -868,16 +795,123 @@
868795 return ccm;
869796 }
870797
798+ private String joinJvmArgs() {
799+ StringBuilder allJvmArgs = new StringBuilder("");
800+ for (String jvmArg : jvmArgs) {
801+ allJvmArgs.append(" --jvm_arg=");
802+ allJvmArgs.append(jvmArg);
803+ }
804+ return allJvmArgs.toString();
805+ }
806+
871807 private String buildCreateCommand() {
872808 StringBuilder result = new StringBuilder(CCM_COMMAND + " create");
873- result.append(" " + clusterName);
874- result.append(" -i" + IP_PREFIX);
875- result.append(" " + cassandraInstallArgs);
876- if (nodes.length > 0)
877- result.append(" -n " + Joiner.on(":").join(nodes));
878- if (startOptions.length > 0)
879- result.append(" " + Joiner.on(" ").join(startOptions));
809+ result.append(" ").append(clusterName);
810+ result.append(" -i ").append(TestUtils.IP_PREFIX);
811+ result.append(" ");
812+ if (cassandraVersion != null)
813+ result.append("-v ").append(cassandraVersion);
814+ else
815+ result.append(CASSANDRA_INSTALL_ARGS);
816+ if (nodes.length > 0) {
817+ result.append(" -n ");
818+ for (int i = 0; i < nodes.length; i++) {
819+ int node = nodes[i];
820+ if (i > 0)
821+ result.append(':');
822+ result.append(node);
823+ }
824+ }
825+ if (!createOptions.isEmpty())
826+ result.append(" ").append(Joiner.on(" ").join(createOptions));
880827 return result.toString();
881828 }
829+
830+ /**
831+ * This is a workaround for an oddity in CCM:
832+ * when we create a cluster with -n option and
833+ * non-standard ports, the node.conf files are not updated accordingly.
834+ */
835+ private void updateNodeConf(CCMBridge ccm) {
836+ int n = 1;
837+ Closer closer = Closer.create();
838+ try {
839+ for (int dc = 1; dc <= nodes.length; dc++) {
840+ int nodesInDc = nodes[dc - 1];
841+ for (int i = 0; i < nodesInDc; i++) {
842+ int jmxPort = findAvailablePort();
843+ int debugPort = findAvailablePort();
844+ logger.debug("Node {} in cluster {} using JMX port {} and debug port {}", n, clusterName, jmxPort, debugPort);
845+ File nodeConf = new File(ccm.getNodeDir(n), "node.conf");
846+ File nodeConf2 = new File(ccm.getNodeDir(n), "node.conf.tmp");
847+ BufferedReader br = closer.register(new BufferedReader(new FileReader(nodeConf)));
848+ PrintWriter pw = closer.register(new PrintWriter(new FileWriter(nodeConf2)));
849+ String line;
850+ while ((line = br.readLine()) != null) {
851+ line = line
852+ .replace("9042", Integer.toString(ccm.binaryPort))
853+ .replace("9160", Integer.toString(ccm.thriftPort))
854+ .replace("7000", Integer.toString(ccm.storagePort));
855+ if (line.startsWith("jmx_port")) {
856+ line = String.format("jmx_port: '%s'", jmxPort);
857+ } else if (line.startsWith("remote_debug_port")) {
858+ line = String.format("remote_debug_port: %s:%s", TestUtils.ipOfNode(n), debugPort);
859+ }
860+ pw.println(line);
861+ }
862+ pw.flush();
863+ pw.close();
864+ Files.move(nodeConf2, nodeConf);
865+ n++;
866+ }
867+ }
868+ } catch (IOException e) {
869+ Throwables.propagate(e);
870+ } finally {
871+ try {
872+ closer.close();
873+ } catch (IOException e) {
874+ Throwables.propagate(e);
875+ }
876+ }
877+ }
878+
879+ @Override
880+ @SuppressWarnings("SimplifiableIfStatement")
881+ public boolean equals(Object o) {
882+ // do not include cluster name and start, only
883+ // properties relevant to the settings of the cluster
884+ if (this == o) return true;
885+ if (o == null || getClass() != o.getClass()) return false;
886+ Builder builder = (Builder) o;
887+ if (isDSE != builder.isDSE) return false;
888+ if (thriftPort != builder.thriftPort) return false;
889+ if (binaryPort != builder.binaryPort) return false;
890+ if (storagePort != builder.storagePort) return false;
891+ if (!Arrays.equals(nodes, builder.nodes)) return false;
892+ if (!createOptions.equals(builder.createOptions)) return false;
893+ if (!jvmArgs.equals(builder.jvmArgs)) return false;
894+ if (!dseConfiguration.equals(builder.dseConfiguration)) return false;
895+ if (!cassandraConfiguration.equals(builder.cassandraConfiguration)) return false;
896+ return cassandraVersion.equals(builder.cassandraVersion);
897+ }
898+
899+ @Override
900+ public int hashCode() {
901+ // do not include cluster name and start, only
902+ // properties relevant to the settings of the cluster
903+ int result = Arrays.hashCode(nodes);
904+ result = 31 * result + (isDSE ? 1 : 0);
905+ result = 31 * result + createOptions.hashCode();
906+ result = 31 * result + jvmArgs.hashCode();
907+ result = 31 * result + cassandraConfiguration.hashCode();
908+ result = 31 * result + dseConfiguration.hashCode();
909+ result = 31 * result + thriftPort;
910+ result = 31 * result + binaryPort;
911+ result = 31 * result + storagePort;
912+ result = 31 * result + cassandraVersion.hashCode();
913+ return result;
914+ }
882915 }
916+
883917 }
added driver-core/src/test/java/com/datastax/driver/core/CCMConfig.java +240 −0
@@ -0,0 +1,240 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core;
17+
18+import java.lang.annotation.Retention;
19+import java.lang.annotation.Target;
20+
21+import static java.lang.annotation.ElementType.METHOD;
22+import static java.lang.annotation.ElementType.TYPE;
23+import static java.lang.annotation.RetentionPolicy.RUNTIME;
24+
25+/**
26+ * The configuration to use when running tests with {@link CCMTestsSupport}.
27+ */
28+@Retention(RUNTIME)
29+@Target({TYPE, METHOD})
30+public @interface CCMConfig {
31+
32+ final class Undefined {
33+ }
34+
35+ /**
36+ * The number of nodes to create, per data center.
37+ * If not set, this defaults to {1}, i.e., one data center with one node.
38+ *
39+ * @return The number of nodes to create, per data center.
40+ */
41+ int[] numberOfNodes() default {};
42+
43+ /**
44+ * The C* or DSE version to use; defaults to the version defined by
45+ * the System property {@code cassandra.version}.
46+ *
47+ * @return The C* or DSE version to use
48+ * @see CCMBridge#getCassandraVersion()
49+ */
50+ String version() default "";
51+
52+ /**
53+ * Whether to launch a DSE instance rather than an OSS C*.
54+ *
55+ * @return {@code true} to launch a DSE instance, {@code false} to launch an OSS C* instance (default).
56+ */
57+ boolean[] dse() default {};
58+
59+ /**
60+ * Configuration items to add to cassandra.yaml configuration file.
61+ * Each configuration item must be in the form {@code key:value}.
62+ *
63+ * @return Configuration items to add to cassandra.yaml configuration file.
64+ */
65+ String[] config() default {};
66+
67+ /**
68+ * Configuration items to add to dse.yaml configuration file.
69+ * Each configuration item must be in the form {@code key:value}.
70+ *
71+ * @return Configuration items to add to dse.yaml configuration file.
72+ */
73+ String[] dseConfig() default {};
74+
75+ /**
76+ * JVM args to use when starting hosts.
77+ * System properties should be provided one by one, in the form
78+ * {@code -Dname=value}.
79+ *
80+ * @return JVM args to use when starting hosts.
81+ */
82+ String[] jvmArgs() default {};
83+
84+ /**
85+ * Free-form options that will be added at the end of the {@code ccm create} command.
86+ *
87+ * @return Free-form options that will be added at the end of the {@code ccm create} command.
88+ */
89+ String[] options() default {};
90+
91+ /**
92+ * Whether to use SSL encryption.
93+ *
94+ * @return {@code true} to use encryption, {@code false} to use unencrypted communication (default).
95+ */
96+ boolean[] ssl() default {};
97+
98+ /**
99+ * Whether to use authentication. Implies the use of SSL encryption.
100+ *
101+ * @return {@code true} to use authentication, {@code false} to use unauthenticated communication (default).
102+ */
103+ boolean[] auth() default {};
104+
105+ /**
106+ * Returns {@code true} if a {@link CCMBridge} instance should be automatically created, {@code false} otherwise.
107+ * <p/>
108+ * If {@code true}, a CCM cluster builder will be created or retrieved from the cache.
109+ * If {@code false}, no CCM cluster will be activated for this test; this can be useful
110+ * when some tests in a test class require CCM, while others don't but are in one of the allowed
111+ * CCM test groups ("short" for example).
112+ * <p/>
113+ * The cluster will be created once for the whole class if CCM test mode is {@link CreateCCM.TestMode#PER_CLASS},
114+ * or once per test method, if the CCM test mode is {@link CreateCCM.TestMode#PER_METHOD},
115+ *
116+ * @return {@code true} if a {@link Cluster} instance should be automatically created, {@code false} otherwise.
117+ */
118+ boolean[] createCcm() default {};
119+
120+ /**
121+ * Returns {@code true} if a {@link Cluster} instance should be automatically created, {@code false} otherwise.
122+ * <p/>
123+ * If {@code true}, a cluster builder will be obtained by invoking the method
124+ * specified by {@link #clusterProvider()} and {@link #clusterProviderClass()}.
125+ * <p/>
126+ * The CCM cluster will be created once for the whole class if CCM test mode is {@link CreateCCM.TestMode#PER_CLASS},
127+ * or once per test method, if the CCM test mode is {@link CreateCCM.TestMode#PER_METHOD},
128+ *
129+ * @return {@code true} if a {@link Cluster} instance should be automatically created, {@code false} otherwise.
130+ */
131+ boolean[] createCluster() default {};
132+
133+ /**
134+ * Returns {@code true} if a {@link Session} instance should be automatically created, {@code false} otherwise.
135+ * <p/>
136+ * If {@code true}, a cluster builder will be obtained by invoking the method
137+ * specified by {@link #clusterProvider()} and {@link #clusterProviderClass()},
138+ * and then the session will be created through {@link Cluster#connect()}.
139+ * <p/>
140+ * The session will be created once for the whole class if CCM test mode is {@link CreateCCM.TestMode#PER_CLASS},
141+ * or once per test method, if the CCM test mode is {@link CreateCCM.TestMode#PER_METHOD},
142+ *
143+ * @return {@code true} if a {@link Session} instance should be automatically created, {@code false} otherwise.
144+ */
145+ boolean[] createSession() default {};
146+
147+ /**
148+ * Returns {@code true} if a test keyspace should be automatically created, {@code false} otherwise.
149+ * <p/>
150+ * If {@code true}, a cluster builder will be obtained by invoking the method
151+ * specified by {@link #clusterProvider()} and {@link #clusterProviderClass()},
152+ * then a session will be created through {@link Cluster#connect()},
153+ * and this session will be used to create the test keyspace.
154+ * <p/>
155+ * The keyspace will be created once for the whole class if CCM test mode is {@link CreateCCM.TestMode#PER_CLASS},
156+ * or once per test method, if the CCM test mode is {@link CreateCCM.TestMode#PER_METHOD},
157+ * <p/>
158+ * The test keyspace will be automatically populated upon creation with fixtures provided by
159+ * {@link #fixturesProvider()} and {@link #fixturesProviderClass()}.
160+ *
161+ * @return {@code true} if a test keyspace should be automatically created, {@code false} otherwise.
162+ */
163+ boolean[] createKeyspace() default {};
164+
165+ /**
166+ * Returns {@code true} if the test class or the test method alters the CCM cluster,
167+ * e.g. by adding or removing nodes,
168+ * in which case, it should not be reused after the test is finished.
169+ * <p/>
170+ * If {@code true}, CCM cluster will be destroyed after the test method if test mode is
171+ * {@link CreateCCM.TestMode#PER_METHOD}, or after the test class, if test mode
172+ * is {@link CreateCCM.TestMode#PER_CLASS}.
173+ *
174+ * @return {@code true} if the test class or the test method alters the CCM cluster used,
175+ * {@code false} otherwise.
176+ */
177+ boolean[] dirtiesContext() default {};
178+
179+ /**
180+ * Returns the name of the method that should be invoked to obtain
181+ * a {@link com.datastax.driver.core.Cluster.Builder} instance.
182+ * <p/>
183+ * This method should be declared in {@link #clusterProviderClass()},
184+ * or if that property is not set,
185+ * it will be looked up on the test class itself.
186+ * <p/>
187+ * The method should not have parameters. It can be static or not,
188+ * and have any visibility.
189+ * <p/>
190+ * By default, the test will look for a method named after {@code createClusterBuilder}.
191+ *
192+ * @return The name of the method that should be invoked to obtain a
193+ * {@link com.datastax.driver.core.Cluster.Builder} instance.
194+ */
195+ String clusterProvider() default "";
196+
197+ /**
198+ * Returns the name of the class that should be invoked to obtain
199+ * a {@link com.datastax.driver.core.Cluster.Builder} instance.
200+ * <p/>
201+ * This class should contain a method named after {@link #clusterProvider()};
202+ * if this property is not set,
203+ * it will default to the test class itself.
204+ *
205+ * @return The name of the class that should be invoked to obtain a
206+ * {@link com.datastax.driver.core.Cluster.Builder} instance.
207+ */
208+ Class<?> clusterProviderClass() default Undefined.class;
209+
210+ /**
211+ * Returns the name of the method that should be invoked to obtain
212+ * the test fixtures to use.
213+ * <p/>
214+ * This method should return {@code Collection<String>}.
215+ * <p/>
216+ * This method should be declared in {@link #fixturesProviderClass()},
217+ * or if that property is not set,
218+ * it will be looked up on the test class itself.
219+ * <p/>
220+ * The method should not have parameters. It can be static or not,
221+ * and have any visibility.
222+ *
223+ * @return The name of the method that should be invoked to obtain the test fixtures to use.
224+ */
225+ String fixturesProvider() default "";
226+
227+ /**
228+ * Returns the name of the class that should be invoked to obtain
229+ * the test fixtures to use.
230+ * <p/>
231+ * This class should contain a method named after {@link #fixturesProvider()};
232+ * if this property is not set,
233+ * it will default to the test class itself.
234+ *
235+ * @return The name of the class that should be invoked to obtain a
236+ * {@link com.datastax.driver.core.Cluster.Builder} instance.
237+ */
238+ Class<?> fixturesProviderClass() default Undefined.class;
239+
240+}
added driver-core/src/test/java/com/datastax/driver/core/CCMTestsSupport.java +756 −0
@@ -0,0 +1,756 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core;
17+
18+import com.datastax.driver.core.CreateCCM.TestMode;
19+import com.datastax.driver.core.policies.AddressTranslator;
20+import com.google.common.base.Throwables;
21+import com.google.common.cache.*;
22+import com.google.common.collect.Lists;
23+import com.google.common.io.Closer;
24+import org.slf4j.Logger;
25+import org.slf4j.LoggerFactory;
26+import org.testng.ITestResult;
27+import org.testng.annotations.*;
28+
29+import java.io.Closeable;
30+import java.io.IOException;
31+import java.lang.annotation.Annotation;
32+import java.lang.reflect.Constructor;
33+import java.lang.reflect.Method;
34+import java.lang.reflect.Modifier;
35+import java.lang.reflect.ParameterizedType;
36+import java.net.InetSocketAddress;
37+import java.util.*;
38+import java.util.concurrent.Callable;
39+import java.util.concurrent.ExecutionException;
40+import java.util.concurrent.atomic.AtomicInteger;
41+
42+import static com.datastax.driver.core.CreateCCM.TestMode.PER_CLASS;
43+import static com.datastax.driver.core.CreateCCM.TestMode.PER_METHOD;
44+import static com.datastax.driver.core.TestUtils.*;
45+import static org.assertj.core.api.Assertions.fail;
46+
47+@SuppressWarnings("unused")
48+public class CCMTestsSupport {
49+
50+ private static final Logger LOGGER = LoggerFactory.getLogger(CCMTestsSupport.class);
51+
52+ private static final AtomicInteger CCM_COUNTER = new AtomicInteger(1);
53+
54+ private static final List<String> TEST_GROUPS = Lists.newArrayList("isolated", "short", "long", "stress", "duration");
55+
56+ private static class CCMTestConfig {
57+
58+ private final List<CCMConfig> annotations;
59+
60+ private CCMBridge.Builder ccmBuilder;
61+
62+ public CCMTestConfig(List<CCMConfig> annotations) {
63+ this.annotations = annotations;
64+ }
65+
66+ private int[] numberOfNodes() {
67+ for (CCMConfig ann : annotations) {
68+ if (ann != null && ann.numberOfNodes().length > 0)
69+ return ann.numberOfNodes();
70+ }
71+ return new int[]{1};
72+ }
73+
74+ @SuppressWarnings("SimplifiableIfStatement")
75+ private String version() {
76+ for (CCMConfig ann : annotations) {
77+ if (ann != null && !ann.version().isEmpty())
78+ return ann.version();
79+ }
80+ return null;
81+ }
82+
83+ @SuppressWarnings("SimplifiableIfStatement")
84+ private boolean dse() {
85+ for (CCMConfig ann : annotations) {
86+ if (ann != null && ann.dse().length > 0)
87+ return ann.dse()[0];
88+ }
89+ return false;
90+ }
91+
92+ @SuppressWarnings("SimplifiableIfStatement")
93+ private boolean ssl() {
94+ for (CCMConfig ann : annotations) {
95+ if (ann != null && ann.ssl().length > 0)
96+ return ann.ssl()[0];
97+ }
98+ return false;
99+ }
100+
101+ @SuppressWarnings("SimplifiableIfStatement")
102+ private boolean auth() {
103+ for (CCMConfig ann : annotations) {
104+ if (ann != null && ann.auth().length > 0)
105+ return ann.auth()[0];
106+ }
107+ return false;
108+ }
109+
110+ @SuppressWarnings("SimplifiableIfStatement")
111+ private Map<String, Object> config() {
112+ Map<String, Object> config = new HashMap<String, Object>();
113+ for (int i = annotations.size() - 1; i == 0; i--) {
114+ CCMConfig ann = annotations.get(i);
115+ addConfigOptions(ann.config(), config);
116+ }
117+ return config;
118+ }
119+
120+ @SuppressWarnings("SimplifiableIfStatement")
121+ private Map<String, Object> dseConfig() {
122+ Map<String, Object> config = new HashMap<String, Object>();
123+ for (int i = annotations.size() - 1; i >= 0; i--) {
124+ CCMConfig ann = annotations.get(i);
125+ addConfigOptions(ann.dseConfig(), config);
126+ }
127+ return config;
128+ }
129+
130+ private void addConfigOptions(String[] conf, Map<String, Object> config) {
131+ for (String aConf : conf) {
132+ String[] tokens = aConf.split(":");
133+ if (tokens.length != 2)
134+ fail("Wrong configuration option: " + aConf);
135+ String key = tokens[0];
136+ String value = tokens[1];
137+ config.put(key, value);
138+ }
139+ }
140+
141+ @SuppressWarnings("SimplifiableIfStatement")
142+ private Set<String> jvmArgs() {
143+ Set<String> args = new LinkedHashSet<String>();
144+ for (int i = annotations.size() - 1; i >= 0; i--) {
145+ CCMConfig ann = annotations.get(i);
146+ Collections.addAll(args, ann.jvmArgs());
147+ }
148+ return args;
149+ }
150+
151+ @SuppressWarnings("SimplifiableIfStatement")
152+ private Set<String> startOptions() {
153+ Set<String> args = new LinkedHashSet<String>();
154+ for (int i = annotations.size() - 1; i >= 0; i--) {
155+ CCMConfig ann = annotations.get(i);
156+ Collections.addAll(args, ann.options());
157+ }
158+ return args;
159+ }
160+
161+ @SuppressWarnings("SimplifiableIfStatement")
162+ private boolean createCcm() {
163+ for (CCMConfig ann : annotations) {
164+ if (ann != null && ann.createCcm().length > 0)
165+ return ann.createCcm()[0];
166+ }
167+ return true;
168+ }
169+
170+ @SuppressWarnings("SimplifiableIfStatement")
171+ private boolean createCluster() {
172+ for (CCMConfig ann : annotations) {
173+ if (ann != null && ann.createCluster().length > 0)
174+ return ann.createCluster()[0];
175+ }
176+ return true;
177+ }
178+
179+ @SuppressWarnings("SimplifiableIfStatement")
180+ private boolean createSession() {
181+ for (CCMConfig ann : annotations) {
182+ if (ann != null && ann.createSession().length > 0)
183+ return ann.createSession()[0];
184+ }
185+ return true;
186+ }
187+
188+ @SuppressWarnings("SimplifiableIfStatement")
189+ private boolean createKeyspace() {
190+ for (CCMConfig ann : annotations) {
191+ if (ann != null && ann.createKeyspace().length > 0)
192+ return ann.createKeyspace()[0];
193+ }
194+ return true;
195+ }
196+
197+ @SuppressWarnings("SimplifiableIfStatement")
198+ private boolean dirtiesContext() {
199+ for (CCMConfig ann : annotations) {
200+ if (ann != null && ann.dirtiesContext().length > 0)
201+ return ann.dirtiesContext()[0];
202+ }
203+ return false;
204+ }
205+
206+ private CCMBridge.Builder ccmBuilder() {
207+ if (ccmBuilder == null) {
208+ ccmBuilder = CCMBridge.builder()
209+ .withNodes(numberOfNodes());
210+ if (version() != null)
211+ ccmBuilder.withVersion(version());
212+ if (dse())
213+ ccmBuilder.withDSE();
214+ if (ssl())
215+ ccmBuilder.withSSL();
216+ if (auth())
217+ ccmBuilder.withAuth();
218+ for (Map.Entry<String, Object> entry : config().entrySet()) {
219+ ccmBuilder.withCassandraConfiguration(entry.getKey(), entry.getValue());
220+ }
221+ for (Map.Entry<String, Object> entry : dseConfig().entrySet()) {
222+ ccmBuilder.withDSEConfiguration(entry.getKey(), entry.getValue());
223+ }
224+ for (String option : startOptions()) {
225+ ccmBuilder.withCreateOptions(option);
226+ }
227+ for (String arg : jvmArgs()) {
228+ ccmBuilder.withJvmArgs(arg);
229+ }
230+ }
231+ return ccmBuilder;
232+ }
233+
234+ private Cluster.Builder clusterBuilder(Object testInstance) throws Exception {
235+ String methodName = null;
236+ Class<?> clazz = null;
237+ for (int i = annotations.size() - 1; i >= 0; i--) {
238+ CCMConfig ann = annotations.get(i);
239+ if (!ann.clusterProvider().isEmpty()) {
240+ methodName = ann.clusterProvider();
241+ }
242+ if (!ann.clusterProviderClass().equals(CCMConfig.Undefined.class)) {
243+ clazz = ann.clusterProviderClass();
244+ }
245+ }
246+ if (methodName == null)
247+ methodName = "createClusterBuilder";
248+ if (clazz == null)
249+ clazz = testInstance.getClass();
250+ Method method = locateMethod(methodName, clazz);
251+ assert Cluster.Builder.class.isAssignableFrom(method.getReturnType());
252+ if (Modifier.isStatic(method.getModifiers())) {
253+ return (Cluster.Builder) method.invoke(null);
254+ } else {
255+ Object receiver = testInstance.getClass().equals(clazz) ? testInstance : instantiate(clazz);
256+ return (Cluster.Builder) method.invoke(receiver);
257+ }
258+ }
259+
260+ @SuppressWarnings("unchecked")
261+ private Collection<String> fixtures(Object testInstance) throws Exception {
262+ String methodName = null;
263+ Class<?> clazz = null;
264+ for (int i = annotations.size() - 1; i >= 0; i--) {
265+ CCMConfig ann = annotations.get(i);
266+ if (!ann.fixturesProvider().isEmpty()) {
267+ methodName = ann.fixturesProvider();
268+ }
269+ if (!ann.fixturesProviderClass().equals(CCMConfig.Undefined.class)) {
270+ clazz = ann.fixturesProviderClass();
271+ }
272+ }
273+ if (methodName == null)
274+ methodName = "createTestFixtures";
275+ if (clazz == null)
276+ clazz = testInstance.getClass();
277+ Method method = locateMethod(methodName, clazz);
278+ assert Collection.class.isAssignableFrom(method.getReturnType());
279+ assert method.getGenericReturnType() instanceof ParameterizedType;
280+ assert String.class.equals(((ParameterizedType) method.getGenericReturnType()).getActualTypeArguments()[0]);
281+ if (Modifier.isStatic(method.getModifiers())) {
282+ return (Collection<String>) method.invoke(null);
283+ } else {
284+ Object receiver = testInstance.getClass().equals(clazz) ? testInstance : instantiate(clazz);
285+ return (Collection<String>) method.invoke(receiver);
286+ }
287+ }
288+
289+ }
290+
291+ private static class CCMTestContextLoader extends CacheLoader<CCMBridge.Builder, CCMBridge> {
292+
293+ @Override
294+ public CCMBridge load(CCMBridge.Builder builder) {
295+ return builder.build();
296+ }
297+
298+ }
299+
300+ private static class CCMTestContextWeigher implements Weigher<CCMBridge.Builder, CCMBridge> {
301+ @Override
302+ public int weigh(CCMBridge.Builder key, CCMBridge value) {
303+ return value.getInitialNumberOfNodes();
304+ }
305+ }
306+
307+ private static class CCMTestContextRemovalListener implements RemovalListener<CCMBridge.Builder, CCMBridge> {
308+
309+ @Override
310+ public void onRemoval(RemovalNotification<CCMBridge.Builder, CCMBridge> notification) {
311+ if (notification.getValue() != null) {
312+ LOGGER.debug("Evicting: " + notification.getValue());
313+ notification.getValue().close();
314+ }
315+ }
316+
317+ }
318+
319+ /**
320+ * A LoadingCache that stores running CCM clusters.
321+ */
322+ private static final LoadingCache<CCMBridge.Builder, CCMBridge> CACHE;
323+
324+ static {
325+ long maximumWeight;
326+ String numberOfNodes = System.getProperty("ccm.maxNumberOfNodes");
327+ if (numberOfNodes == null) {
328+ long freeMemoryMB = TestUtils.getFreeMemoryMB();
329+ if (freeMemoryMB < 1000)
330+ LOGGER.warn("Available memory below 1GB: {}MB, CCM clusters might fail to start", freeMemoryMB);
331+ // CCM nodes are started with -Xms500M -Xmx500M
332+ // leave at least 500 MB out, with a minimum of 1 node and a maximum of 10 nodes
333+ maximumWeight = Math.min(10, Math.max(1, (freeMemoryMB / 500) - 1));
334+ } else {
335+ maximumWeight = Integer.parseInt(numberOfNodes);
336+ }
337+ LOGGER.info("Maximum number of running CCM nodes: {}", maximumWeight);
338+ CACHE = CacheBuilder.newBuilder()
339+ .initialCapacity(1)
340+ .maximumWeight(maximumWeight)
341+ .weigher(new CCMTestContextWeigher())
342+ .removalListener(new CCMTestContextRemovalListener())
343+ .build(new CCMTestContextLoader());
344+ }
345+
346+ private TestMode testMode;
347+
348+ private CCMTestConfig ccmTestConfig;
349+
350+ protected CCMBridge ccm;
351+
352+ protected Cluster cluster;
353+
354+ protected Session session;
355+
356+ protected String keyspace;
357+
358+ private boolean erroredOut = false;
359+
360+ private Closer closer;
361+
362+ /**
363+ * Hook invoked at the beginning of a test class to initialize CCM test context.
364+ *
365+ * @throws Exception
366+ */
367+ @BeforeClass(groups = {"isolated", "short", "long", "stress", "duration"})
368+ public void beforeTestClass() throws Exception {
369+ beforeTestClass(this);
370+ }
371+
372+ /**
373+ * Hook invoked at the beginning of a test class to initialize CCM test context.
374+ * <p/>
375+ * Useful when this class is not a superclass of the test being run.
376+ *
377+ * @throws Exception
378+ */
379+ public void beforeTestClass(Object testInstance) throws Exception {
380+ testMode = determineTestMode(testInstance.getClass());
381+ if (testMode == PER_CLASS) {
382+ closer = Closer.create();
383+ initTestContext(testInstance, null);
384+ initTestCluster(testInstance);
385+ initTestSession();
386+ initTestKeyspace();
387+ initTestFixtures(testInstance);
388+ }
389+ }
390+
391+ /**
392+ * Hook executed before each test method.
393+ *
394+ * @throws Exception
395+ */
396+ @BeforeMethod(groups = {"isolated", "short", "long", "stress", "duration"})
397+ public void beforeTestMethod(Method testMethod) throws Exception {
398+ beforeTestMethod(this, testMethod);
399+ }
400+
401+ /**
402+ * Hook executed before each test method.
403+ * <p/>
404+ * Useful when this class is not a superclass of the test being run.
405+ *
406+ * @throws Exception
407+ */
408+ public void beforeTestMethod(Object testInstance, Method testMethod) throws Exception {
409+ if (isCcmEnabled(testMethod)) {
410+ if (closer == null)
411+ closer = Closer.create();
412+ if (testMode == PER_METHOD || erroredOut) {
413+ initTestContext(testInstance, testMethod);
414+ initTestCluster(testInstance);
415+ initTestSession();
416+ initTestKeyspace();
417+ initTestFixtures(testInstance);
418+ }
419+ assert ccmTestConfig != null;
420+ assert !ccmTestConfig.createCcm() || ccm != null;
421+ }
422+ }
423+
424+ /**
425+ * Hook executed after each test method.
426+ */
427+ @AfterMethod(groups = {"isolated", "short", "long", "stress", "duration"}, alwaysRun = true)
428+ public void afterTestMethod(ITestResult tr) {
429+ if (isCcmEnabled(tr.getMethod().getConstructorOrMethod().getMethod())) {
430+ if (tr.getStatus() == ITestResult.FAILURE) {
431+ errorOut();
432+ }
433+ if (erroredOut || testMode == PER_METHOD) {
434+ closeCloseables();
435+ closeTestCluster();
436+ }
437+ if (testMode == PER_METHOD)
438+ closeTestContext();
439+ }
440+ }
441+
442+ /**
443+ * Hook executed after each test class.
444+ */
445+ @AfterClass(groups = {"isolated", "short", "long", "stress", "duration"}, alwaysRun = true)
446+ public void afterTestClass() {
447+ if (testMode == PER_CLASS) {
448+ closeCloseables();
449+ closeTestCluster();
450+ closeTestContext();
451+ }
452+ }
453+
454+ /**
455+ * Returns the cluster builder to use for this test.
456+ * <p/>
457+ * The default implementation returns a vanilla builder.
458+ * <p/>
459+ * It's not required to call {@link com.datastax.driver.core.Cluster.Builder#addContactPointsWithPorts},
460+ * it will be done automatically.
461+ *
462+ * @return The cluster builder to use for the tests.
463+ */
464+ public Cluster.Builder createClusterBuilder() {
465+ return Cluster.builder()
466+ // use a different codec registry for each cluster instance
467+ .withCodecRegistry(new CodecRegistry());
468+ }
469+
470+ /**
471+ * Returns an alternate cluster builder to use for this test,
472+ * with no event debouncing.
473+ * <p/>
474+ * It's not required to call {@link com.datastax.driver.core.Cluster.Builder#addContactPointsWithPorts},
475+ * it will be done automatically.
476+ *
477+ * @return The cluster builder to use for the tests.
478+ */
479+ public Cluster.Builder createClusterBuilderNoDebouncing() {
480+ return Cluster.builder().withQueryOptions(TestUtils.nonDebouncingQueryOptions());
481+ }
482+
483+ /**
484+ * The CQL statements to execute before the tests in this class.
485+ * Useful to create tables or other objects inside the test keyspace,
486+ * or to insert test data.
487+ * <p/>
488+ * Statements do not need to be qualified with keyspace name.
489+ * <p/>
490+ * The default implementation returns an empty list (no fixtures required).
491+ *
492+ * @return The DDL statements to execute before the tests.
493+ */
494+ public Collection<String> createTestFixtures() {
495+ return Collections.emptyList();
496+ }
497+
498+ /**
499+ * Signals that the test has encountered an unexpected error.
500+ * <p/>
501+ * This method is automatically called when a test finishes with an unexpected exception
502+ * being thrown, but it is also possible to manually invoke it.
503+ * <p/>
504+ * Calling this method will close the current cluster and session.
505+ * The CCM data directory will be kept after the test session is finished,
506+ * for debugging purposes
507+ * <p/>
508+ * This method should not be called before the test has started, nor after the test is finished.
509+ */
510+ public void errorOut() {
511+ erroredOut = true;
512+ if (ccm != null)
513+ ccm.setKeepLogs(true);
514+ }
515+
516+ /**
517+ * Returns the contact points to use to contact the CCM cluster.
518+ * <p/>
519+ * This method returns as many contact points as the number of nodes initially present in the CCM cluster,
520+ * according to {@link CCMConfig} annotations.
521+ * <p/>
522+ * On a multi-DC setup, this will include nodes in all data centers.
523+ * <p/>
524+ * This method should not be called before the test has started, nor after the test is finished.
525+ *
526+ * @return the contact points to use to contact the CCM cluster.
527+ */
528+ public List<InetSocketAddress> getInitialContactPoints() {
529+ assert ccmTestConfig != null;
530+ List<InetSocketAddress> contactPoints = new ArrayList<InetSocketAddress>();
531+ int n = 1;
532+ int[] numberOfNodes = ccmTestConfig.numberOfNodes();
533+ for (int dc = 1; dc <= numberOfNodes.length; dc++) {
534+ int nodesInDc = numberOfNodes[dc - 1];
535+ for (int i = 0; i < nodesInDc; i++) {
536+ contactPoints.add(new InetSocketAddress(ipOfNode(n), ccm.getBinaryPort()));
537+ n++;
538+ }
539+ }
540+ return contactPoints;
541+ }
542+
543+ /**
544+ * Returns the address of the {@code nth} host in the CCM cluster (counting from 1, i.e.,
545+ * {@code getHostAddress(1)} returns the address of the first node.
546+ * <p/>
547+ * In multi-DC setups, nodes are numbered in ascending order of their datacenter number.
548+ * E.g. with 2 DCs and 3 nodes in each DC, the first node in DC 2 is number 4.
549+ * <p/>
550+ * This method should not be called before the test has started, nor after the test is finished.
551+ *
552+ * @return the address of the {@code nth} host in the cluster.
553+ */
554+ public InetSocketAddress getHostAddress(int n) {
555+ return ccm.addressOfNode(n);
556+ }
557+
558+ /**
559+ * Returns an {@link AddressTranslator} to use when tests must manually create
560+ * {@link Cluster} instances.
561+ * <p/>
562+ * This translator is necessary because hosts create with this class do not use standard ports.
563+ * <p/>
564+ * This method should not be called before the test has started, nor after the test is finished.
565+ *
566+ * @return an {@link AddressTranslator} to use when tests must manually create
567+ * {@link Cluster} instances.
568+ */
569+ public AddressTranslator getAddressTranslator() {
570+ return ccm.addressTranslator();
571+ }
572+
573+ /**
574+ * Registers the given {@link Closeable} to be closed at the end of the current test method.
575+ * <p/>
576+ * This method should not be called before the test has started, nor after the test is finished.
577+ *
578+ * @param closeable The closeable to close
579+ * @return The closeable to close
580+ */
581+ public <T extends Closeable> T register(T closeable) {
582+ closer.register(closeable);
583+ return closeable;
584+ }
585+
586+ private void initTestContext(Object testInstance, Method testMethod) throws Exception {
587+ erroredOut = false;
588+ ccmTestConfig = createCCMTestConfig(testInstance, testMethod);
589+ assert ccmTestConfig != null;
590+ if (ccmTestConfig.createCcm()) {
591+ if (ccmTestConfig.dirtiesContext()) {
592+ ccm = ccmTestConfig.ccmBuilder().build();
593+ LOGGER.debug("Using dedicated {}", ccm);
594+ } else {
595+ CCMBridge.Builder key = ccmTestConfig.ccmBuilder();
596+ ccm = CACHE.getIfPresent(key);
597+ if (ccm != null) {
598+ LOGGER.debug("Reusing {}", ccm);
599+ } else {
600+ try {
601+ ccm = CACHE.get(ccmTestConfig.ccmBuilder());
602+ LOGGER.debug("Using newly-created {}", ccm);
603+ } catch (ExecutionException e) {
604+ Throwables.propagate(e);
605+ }
606+ }
607+ }
608+ assert ccm != null;
609+ }
610+ }
611+
612+ private void initTestCluster(Object testInstance) throws Exception {
613+ if (ccmTestConfig.createCcm() && ccmTestConfig.createCluster()) {
614+ Cluster.Builder builder = ccmTestConfig.clusterBuilder(testInstance);
615+ // add contact points only if the provided builder didn't do so
616+ if (builder.getContactPoints().isEmpty())
617+ builder.addContactPointsWithPorts(getInitialContactPoints());
618+ builder.withAddressTranslator(ccm.addressTranslator());
619+ cluster = register(builder.build());
620+ cluster.init();
621+ }
622+ }
623+
624+ private void initTestSession() throws Exception {
625+ if (ccmTestConfig.createCcm() && ccmTestConfig.createCluster() && ccmTestConfig.createSession())
626+ session = register(cluster.connect());
627+ }
628+
629+ private void initTestKeyspace() {
630+ if (ccmTestConfig.createCcm() && ccmTestConfig.createCluster() && ccmTestConfig.createSession() && ccmTestConfig.createKeyspace()) {
631+ try {
632+ keyspace = TestUtils.getAvailableKeyspaceName();
633+ LOGGER.debug("Using keyspace " + keyspace);
634+ session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, 1));
635+ session.execute("USE " + keyspace);
636+ } catch (Exception e) {
637+ errorOut();
638+ LOGGER.error("Could not create test keyspace", e);
639+ Throwables.propagate(e);
640+ }
641+ }
642+ }
643+
644+ private void initTestFixtures(Object testInstance) throws Exception {
645+ if (ccmTestConfig.createCcm() && ccmTestConfig.createCluster() && ccmTestConfig.createSession()) {
646+ for (String stmt : ccmTestConfig.fixtures(testInstance)) {
647+ try {
648+ session.execute(stmt);
649+ } catch (Exception e) {
650+ errorOut();
651+ LOGGER.error("Could not execute statement: " + stmt, e);
652+ Throwables.propagate(e);
653+ }
654+ }
655+ }
656+ }
657+
658+ private void closeTestContext() {
659+ if (ccmTestConfig != null && ccm != null && ccmTestConfig.dirtiesContext()) {
660+ ccm.close();
661+ }
662+ ccmTestConfig = null;
663+ ccm = null;
664+ }
665+
666+ private void closeTestCluster() {
667+ if (cluster != null && !cluster.isClosed())
668+ executeNoFail(new Runnable() {
669+ @Override
670+ public void run() {
671+ cluster.close();
672+ }
673+ }, false);
674+ cluster = null;
675+ session = null;
676+ keyspace = null;
677+ }
678+
679+ private void closeCloseables() {
680+ if (closer != null)
681+ executeNoFail(new Callable<Void>() {
682+ @Override
683+ public Void call() throws IOException {
684+ closer.close();
685+ return null;
686+ }
687+ }, false);
688+ }
689+
690+ private static boolean isCcmEnabled(Method testMethod) {
691+ Test ann = locateAnnotation(testMethod, Test.class);
692+ return !Collections.disjoint(Arrays.asList(ann.groups()), TEST_GROUPS);
693+ }
694+
695+ private static CCMTestConfig createCCMTestConfig(Object testInstance, Method testMethod) throws Exception {
696+ ArrayList<CCMConfig> annotations = new ArrayList<CCMConfig>();
697+ CCMConfig ann = locateAnnotation(testMethod, CCMConfig.class);
698+ if (ann != null)
699+ annotations.add(ann);
700+ locateClassAnnotations(testInstance.getClass(), CCMConfig.class, annotations);
701+ return new CCMTestConfig(annotations);
702+ }
703+
704+ private static TestMode determineTestMode(Class<?> testClass) {
705+ List<CreateCCM> annotations = locateClassAnnotations(testClass, CreateCCM.class, new ArrayList<CreateCCM>());
706+ if (!annotations.isEmpty())
707+ return annotations.get(0).value();
708+ return PER_CLASS;
709+ }
710+
711+ private static <A extends Annotation> A locateAnnotation(Method testMethod, Class<? extends A> clazz) {
712+ if (testMethod == null)
713+ return null;
714+ testMethod.setAccessible(true);
715+ return testMethod.getAnnotation(clazz);
716+ }
717+
718+ private static <A extends Annotation> List<A> locateClassAnnotations(Class<?> clazz, Class<? extends A> annotationClass, List<A> annotations) {
719+ A ann = clazz.getAnnotation(annotationClass);
720+ if (ann != null)
721+ annotations.add(ann);
722+ clazz = clazz.getSuperclass();
723+ if (clazz == null)
724+ return annotations;
725+ return locateClassAnnotations(clazz, annotationClass, annotations);
726+ }
727+
728+ private static Method locateMethod(String methodName, Class<?> clazz) throws NoSuchMethodException {
729+ try {
730+ Method method = clazz.getDeclaredMethod(methodName);
731+ method.setAccessible(true);
732+ return method;
733+ } catch (NoSuchMethodException e) {
734+ clazz = clazz.getSuperclass();
735+ if (clazz == null)
736+ throw e;
737+ return locateMethod(methodName, clazz);
738+ }
739+ }
740+
741+ @SuppressWarnings("unchecked")
742+ private static <T> T instantiate(Class<? extends T> clazz) throws NoSuchMethodException, InstantiationException, IllegalAccessException, java.lang.reflect.InvocationTargetException {
743+ if (clazz.getEnclosingClass() == null || Modifier.isStatic(clazz.getModifiers())) {
744+ Constructor<?> constructor = clazz.getDeclaredConstructor();
745+ constructor.setAccessible(true);
746+ return (T) constructor.newInstance();
747+ } else {
748+ Class<?> enclosingClass = clazz.getEnclosingClass();
749+ Object enclosingInstance = enclosingClass.newInstance();
750+ Constructor<?> constructor = clazz.getDeclaredConstructor(enclosingClass);
751+ constructor.setAccessible(true);
752+ return (T) constructor.newInstance(enclosingInstance);
753+ }
754+ }
755+
756+}
modified driver-core/src/test/java/com/datastax/driver/core/CaseSensitivityTest.java +24 −55
@@ -20,69 +20,38 @@
2020 import static com.datastax.driver.core.TestUtils.CREATE_KEYSPACE_SIMPLE_FORMAT;
2121 import static org.testng.Assert.*;
2222
23-public class CaseSensitivityTest {
24-
25- private void assertExists(CCMBridge.CCMCluster c, String fetchName, String realName) {
26- KeyspaceMetadata km = c.cluster.getMetadata().getKeyspace(fetchName);
27- assertNotNull(km);
28- assertEquals(realName, km.getName());
29- }
30-
31- private void assertNotExists(CCMBridge.CCMCluster c, String name) {
32- assertNull(c.cluster.getMetadata().getKeyspace(name));
33- }
23+@CCMConfig(clusterProvider = "createClusterBuilderNoDebouncing")
24+public class CaseSensitivityTest extends CCMTestsSupport {
3425
3526 @Test(groups = "short")
3627 public void testCaseInsensitiveKeyspace() throws Throwable {
37- CCMBridge.CCMCluster c = CCMBridge.buildCluster(1, Cluster.builder()
38- .withQueryOptions(new QueryOptions()
39- .setRefreshNodeIntervalMillis(0)
40- .setRefreshNodeListIntervalMillis(0)
41- .setRefreshSchemaIntervalMillis(0)
42- )
43- );
44- Session s = c.session;
45- try {
46- String ksName = "MyKeyspace";
47- s.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, ksName, 1));
48-
49- assertExists(c, ksName, "mykeyspace");
50- assertExists(c, "mykeyspace", "mykeyspace");
51- assertExists(c, "MYKEYSPACE", "mykeyspace");
52-
53- } catch (Throwable e) {
54- c.errorOut();
55- throw e;
56- } finally {
57- c.discard();
58- }
28+ String ksName = "MyKeyspace1";
29+ session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, ksName, 1));
30+ assertExists(ksName, "mykeyspace1");
31+ assertExists("mykeyspace1", "mykeyspace1");
32+ assertExists("MYKEYSPACE1", "mykeyspace1");
5933 }
6034
6135 @Test(groups = "short")
6236 public void testCaseSensitiveKeyspace() throws Throwable {
63- CCMBridge.CCMCluster c = CCMBridge.buildCluster(1, Cluster.builder()
64- .withQueryOptions(new QueryOptions()
65- .setRefreshNodeIntervalMillis(0)
66- .setRefreshNodeListIntervalMillis(0)
67- .setRefreshSchemaIntervalMillis(0)
68- )
69- );
70- Session s = c.session;
71- try {
72- String ksName = "\"MyKeyspace\"";
73- s.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, ksName, 1));
37+ String ksName = "\"MyKeyspace2\"";
38+ session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, ksName, 1));
39+ assertExists(ksName, "MyKeyspace2");
40+ assertExists(Metadata.quote("MyKeyspace2"), "MyKeyspace2");
41+ assertNotExists("mykeyspace2");
42+ assertNotExists("MyKeyspace2");
43+ assertNotExists("MYKEYSPACE2");
44+ }
7445
75- assertExists(c, ksName, "MyKeyspace");
76- assertExists(c, Metadata.quote("MyKeyspace"), "MyKeyspace");
77- assertNotExists(c, "mykeyspace");
78- assertNotExists(c, "MyKeyspace");
79- assertNotExists(c, "MYKEYSPACE");
46+ private void assertExists(String fetchName, String realName) {
47+ KeyspaceMetadata km = cluster.getMetadata().getKeyspace(fetchName);
48+ assertNotNull(km);
49+ assertEquals(realName, km.getName());
50+ }
8051
81- } catch (Throwable e) {
82- c.errorOut();
83- throw e;
84- } finally {
85- c.discard();
86- }
52+ private void assertNotExists(String name) {
53+ assertNull(cluster.getMetadata().getKeyspace(name));
8754 }
55+
56+
8857 }
modified driver-core/src/test/java/com/datastax/driver/core/ClusterAssert.java +6 −1
@@ -18,6 +18,7 @@
1818 import com.google.common.collect.Iterators;
1919 import org.assertj.core.api.AbstractAssert;
2020
21+import java.net.InetAddress;
2122 import java.util.Iterator;
2223 import java.util.Set;
2324 import java.util.TreeSet;
@@ -31,7 +32,7 @@
3132 }
3233
3334 public ClusterAssert usesControlHost(int node) {
34- String expectedAddress = CCMBridge.ipOfNode(node);
35+ String expectedAddress = TestUtils.ipOfNode(node);
3536 Host controlHost = actual.manager.controlConnection.connectedHost();
3637 assertThat(controlHost.getAddress().getHostAddress()).isEqualTo(expectedAddress);
3738 return this;
@@ -66,6 +67,10 @@
6667 return new HostAssert(host, actual);
6768 }
6869
70+ public HostAssert host(InetAddress hostAddress) {
71+ return host(hostAddress.getHostAddress());
72+ }
73+
6974 /**
7075 * Asserts that {@link Cluster}'s {@link Host}s have valid {@link TokenRange}s with the given keyspace.
7176 * <p/>
modified driver-core/src/test/java/com/datastax/driver/core/ClusterDelegateTest.java +1 −8
@@ -15,18 +15,11 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import com.google.common.collect.Lists;
1918 import org.testng.annotations.Test;
2019
21-import java.util.Collection;
22-
2320 import static org.assertj.core.api.Assertions.assertThat;
2421
25-public class ClusterDelegateTest extends CCMBridge.PerClassSingleNodeCluster {
26- @Override
27- protected Collection<String> getTableDefinitions() {
28- return Lists.newArrayList();
29- }
22+public class ClusterDelegateTest extends CCMTestsSupport {
3023
3124 @Test(groups = "short")
3225 public void should_allow_subclass_to_delegate_to_other_instance() {
modified driver-core/src/test/java/com/datastax/driver/core/ClusterInitTest.java +23 −20
@@ -42,8 +42,7 @@
4242 import static com.datastax.driver.core.Assertions.fail;
4343 import static com.datastax.driver.core.FakeHost.Behavior.THROWING_CONNECT_TIMEOUTS;
4444 import static com.datastax.driver.core.HostDistance.LOCAL;
45-import static com.datastax.driver.core.TestUtils.nonDebouncingQueryOptions;
46-import static com.datastax.driver.core.TestUtils.nonQuietClusterCloseOptions;
45+import static com.datastax.driver.core.TestUtils.*;
4746 import static org.mockito.Mockito.*;
4847
4948 public class ClusterInitTest {
@@ -67,19 +66,18 @@
6766 // - 1 is an actual Scassandra instance that will accept connections:
6867 scassandra = TestUtils.createScassandraServer();
6968 scassandra.start();
70- String realHostAddress = "127.0.0.1";
7169 int port = scassandra.getBinaryPort();
7270
7371 // - the remaining 4 are fake servers that will throw connect timeouts:
7472 for (int i = 2; i <= 5; i++) {
75- FakeHost failingHost = new FakeHost(CCMBridge.ipOfNode(i), port, THROWING_CONNECT_TIMEOUTS);
73+ FakeHost failingHost = new FakeHost(TestUtils.ipOfNode(i), port, THROWING_CONNECT_TIMEOUTS);
7674 failingHosts.add(failingHost);
7775 failingHost.start();
7876 }
7977
8078 // - we also have a "missing" contact point, i.e. there's no server listening at this address,
8179 // and the address is not listed in the live host's system.peers
82- String missingHostAddress = CCMBridge.ipOfNode(6);
80+ String missingHostAddress = TestUtils.ipOfNode(6);
8381
8482 primePeerRows(scassandra, failingHosts);
8583
@@ -100,7 +98,7 @@
10098 cluster = Cluster.builder()
10199 .withPort(scassandra.getBinaryPort())
102100 .addContactPoints(
103- realHostAddress,
101+ ipOfNode(1),
104102 failingHosts.get(0).address, failingHosts.get(1).address,
105103 failingHosts.get(2).address, failingHosts.get(3).address,
106104 missingHostAddress
@@ -126,7 +124,7 @@
126124 verify(socketOptions, atLeast(6)).getKeepAlive();
127125 verify(socketOptions, atMost(7)).getKeepAlive();
128126
129- assertThat(cluster).host(realHostAddress).isNotNull().isUp();
127+ assertThat(cluster).host(1).isNotNull().isUp();
130128 // It is likely but not guaranteed that a host is marked down at this point.
131129 // It should eventually be marked down as Cluster.Manager.triggerOnDown should be
132130 // called and submit a task that marks the host down.
@@ -166,8 +164,8 @@
166164 public void should_not_schedule_reconnections_before_init_complete() {
167165 // Both contact points time out so we're sure we'll try both of them and init will never complete.
168166 List<FakeHost> hosts = Lists.newArrayList(
169- new FakeHost(CCMBridge.ipOfNode(0), 9042, THROWING_CONNECT_TIMEOUTS),
170- new FakeHost(CCMBridge.ipOfNode(1), 9042, THROWING_CONNECT_TIMEOUTS));
167+ new FakeHost(TestUtils.ipOfNode(0), 9042, THROWING_CONNECT_TIMEOUTS),
168+ new FakeHost(TestUtils.ipOfNode(1), 9042, THROWING_CONNECT_TIMEOUTS));
171169 // Use a low reconnection interval and keep the default connect timeout (5 seconds). So if a reconnection was scheduled,
172170 // we would see a call to the reconnection policy.
173171 CountingReconnectionPolicy reconnectionPolicy = new CountingReconnectionPolicy(new ConstantReconnectionPolicy(100));
@@ -184,6 +182,7 @@
184182 for (FakeHost fakeHost : hosts) {
185183 fakeHost.stop();
186184 }
185+ cluster.close();
187186 }
188187 // We don't test that reconnections are scheduled if init succeeds, but that's covered in
189188 // should_handle_failing_or_missing_contact_points
@@ -206,12 +205,13 @@
206205 cluster.connect();
207206 fail("Should not have been able to connect.");
208207 } catch (NoHostAvailableException e) {
209- } // Expected.
210- CloseFuture closeFuture = cluster.closeAsync();
211- try {
212- closeFuture.get(1, TimeUnit.SECONDS);
213- } catch (TimeoutException e) {
214- fail("Close Future did not complete quickly.");
208+ // Expected.
209+ CloseFuture closeFuture = cluster.closeAsync();
210+ try {
211+ closeFuture.get(1, TimeUnit.SECONDS);
212+ } catch (TimeoutException e1) {
213+ fail("Close Future did not complete quickly.");
214+ }
215215 }
216216 }
217217
@@ -225,13 +225,14 @@
225225 @Test(groups = "short")
226226 public void should_not_abort_init_if_host_does_not_support_protocol_version() {
227227 ScassandraCluster scassandraCluster = ScassandraCluster.builder()
228- .withIpPrefix(CCMBridge.IP_PREFIX)
228+ .withIpPrefix(TestUtils.IP_PREFIX)
229229 .withNodes(5)
230230 // For node 2, report an older version which uses protocol v1.
231231 .forcePeerInfo(1, 2, "release_version", "1.2.19")
232232 .build();
233233 Cluster cluster = Cluster.builder()
234- .addContactPoints(scassandraCluster.address(1))
234+ .addContactPointsWithPorts(scassandraCluster.address(1))
235+ .withAddressTranslator(scassandraCluster.addressTranslator())
235236 .withNettyOptions(nonQuietClusterCloseOptions)
236237 .build();
237238
@@ -239,7 +240,7 @@
239240 scassandraCluster.init();
240241 cluster.init();
241242 for (int i = 1; i <= 5; i++) {
242- String hostAddress = scassandraCluster.address(i);
243+ InetAddress hostAddress = scassandraCluster.address(i).getAddress();
243244 if (i == 2) {
244245 // As this host is at an older protocol version, it should be ignored and not marked up.
245246 assertThat(cluster).host(hostAddress).hasState(Host.State.ADDED);
@@ -256,8 +257,10 @@
256257 }
257258
258259 private void primePeerRows(Scassandra scassandra, List<FakeHost> otherHosts) throws UnknownHostException {
259- PrimingClient primingClient = PrimingClient.builder()
260- .withHost("localhost").withPort(scassandra.getAdminPort())
260+ PrimingClient primingClient =
261+ PrimingClient.builder()
262+ .withHost(ipOfNode(1))
263+ .withPort(scassandra.getAdminPort())
261264 .build();
262265
263266 List<Map<String, ?>> rows = Lists.newArrayListWithCapacity(5);
modified driver-core/src/test/java/com/datastax/driver/core/ClusterStressTest.java +38 −25
@@ -17,20 +17,21 @@
1717
1818 import com.datastax.driver.core.utils.SocketChannelMonitor;
1919 import com.google.common.collect.Lists;
20+import com.google.common.util.concurrent.Uninterruptibles;
2021 import org.slf4j.Logger;
2122 import org.slf4j.LoggerFactory;
23+import org.testng.annotations.AfterMethod;
2224 import org.testng.annotations.Test;
2325
24-import java.net.InetSocketAddress;
2526 import java.util.ArrayList;
26-import java.util.Collection;
27-import java.util.Collections;
2827 import java.util.List;
2928 import java.util.concurrent.*;
3029
3130 import static org.testng.Assert.assertEquals;
31+import static org.testng.Assert.fail;
32+
33+public class ClusterStressTest extends CCMTestsSupport {
3234
33-public class ClusterStressTest extends CCMBridge.PerClassSingleNodeCluster {
3435 private static final Logger logger = LoggerFactory.getLogger(ClusterStressTest.class);
3536
3637 private ExecutorService executorService;
@@ -40,22 +41,35 @@
4041 executorService = Executors.newFixedThreadPool(8);
4142 }
4243
43- @Override
44- protected Collection<String> getTableDefinitions() {
45- return new ArrayList<String>(0);
46- }
47-
4844 @Test(groups = "long")
4945 public void clusters_should_not_leak_connections() {
5046 int numberOfClusters = 10;
5147 int numberOfIterations = 500;
52- for (int i = 1; i < numberOfIterations; i++) {
53- logger.info("On iteration {}/{}.", i, numberOfIterations);
54- logger.info("Creating {} clusters", numberOfClusters);
55- List<CreateClusterAndCheckConnections> actions =
56- waitForCreates(createClustersConcurrently(numberOfClusters));
57- waitForCloses(closeClustersConcurrently(actions));
58- logger.debug("# {} threads currently running", Thread.getAllStackTraces().keySet().size());
48+ try {
49+ for (int i = 1; i < numberOfIterations; i++) {
50+ logger.info("On iteration {}/{}.", i, numberOfIterations);
51+ logger.info("Creating {} clusters", numberOfClusters);
52+ List<CreateClusterAndCheckConnections> actions =
53+ waitForCreates(createClustersConcurrently(numberOfClusters));
54+ waitForCloses(closeClustersConcurrently(actions));
55+ if (logger.isDebugEnabled())
56+ logger.debug("# {} threads currently running", Thread.getAllStackTraces().keySet().size());
57+ }
58+ } finally {
59+ logger.info("Sleeping 60 seconds to free TCP resources");
60+ Uninterruptibles.sleepUninterruptibly(60, TimeUnit.SECONDS);
61+ }
62+ }
63+
64+ @AfterMethod(groups = "long", alwaysRun = true)
65+ public void shutdown() throws Exception {
66+ executorService.shutdown();
67+ try {
68+ boolean shutdown = executorService.awaitTermination(30, TimeUnit.SECONDS);
69+ if (!shutdown)
70+ fail("executor ran for longer than expected");
71+ } catch (InterruptedException e) {
72+ fail("Interrupted while waiting for executor to shutdown");
5973 }
6074 }
6175
@@ -148,15 +162,14 @@
148162 return result;
149163 }
150164
151- private static class CreateClusterAndCheckConnections implements Callable<CreateClusterAndCheckConnections> {
165+ private class CreateClusterAndCheckConnections implements Callable<CreateClusterAndCheckConnections> {
152166 private final CountDownLatch startSignal;
153167 private final Cluster cluster;
154168 private final SocketChannelMonitor channelMonitor = new SocketChannelMonitor();
155- private final List<InetSocketAddress> contactPoints = Collections.singletonList(hostAddress);
156169
157170 CreateClusterAndCheckConnections(CountDownLatch startSignal) {
158171 this.startSignal = startSignal;
159- this.cluster = Cluster.builder().addContactPointsWithPorts(contactPoints)
172+ this.cluster = Cluster.builder().addContactPointsWithPorts(getInitialContactPoints())
160173 .withPoolingOptions(new PoolingOptions().setCoreConnectionsPerHost(HostDistance.LOCAL, 1))
161174 .withNettyOptions(channelMonitor.nettyOptions()).build();
162175 }
@@ -170,19 +183,19 @@
170183 cluster.init();
171184 assertEquals(cluster.manager.sessions.size(), 0);
172185 assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1);
173- assertEquals(channelMonitor.openChannels(contactPoints).size(), 1);
186+ assertEquals(channelMonitor.openChannels(getInitialContactPoints()).size(), 1);
174187
175188 // The first session initializes the cluster and its control connection
176189 Session session = cluster.connect();
177190 assertEquals(cluster.manager.sessions.size(), 1);
178191 assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1 + TestUtils.numberOfLocalCoreConnections(cluster));
179- assertEquals(channelMonitor.openChannels(contactPoints).size(), 1 + TestUtils.numberOfLocalCoreConnections(cluster));
192+ assertEquals(channelMonitor.openChannels(getInitialContactPoints()).size(), 1 + TestUtils.numberOfLocalCoreConnections(cluster));
180193
181194 // Closing the session keeps the control connection opened
182195 session.close();
183196 assertEquals(cluster.manager.sessions.size(), 0);
184197 assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1);
185- assertEquals(channelMonitor.openChannels(contactPoints).size(), 1);
198+ assertEquals(channelMonitor.openChannels(getInitialContactPoints()).size(), 1);
186199
187200 return this;
188201 } catch (AssertionError e) {
@@ -196,7 +209,7 @@
196209 }
197210 }
198211
199- private static class CloseCluster implements Callable<Void> {
212+ private class CloseCluster implements Callable<Void> {
200213 private final Cluster cluster;
201214 private final SocketChannelMonitor channelMonitor;
202215 private final CountDownLatch startSignal;
@@ -213,7 +226,7 @@
213226
214227 cluster.close();
215228 assertEquals(cluster.manager.sessions.size(), 0);
216- assertEquals(channelMonitor.openChannels(Collections.singletonList(hostAddress)).size(), 0);
229+ assertEquals(channelMonitor.openChannels(getInitialContactPoints()).size(), 0);
217230 channelMonitor.stop();
218231
219232 return null;
@@ -225,4 +238,4 @@
225238 error.initCause(cause);
226239 return error;
227240 }
228-}
No newline at the end of the file
241+}
added driver-core/src/test/java/com/datastax/driver/core/ConditionChecker.java +158 −0
@@ -0,0 +1,158 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core;
17+
18+import com.google.common.base.Predicate;
19+import com.google.common.base.Predicates;
20+import org.slf4j.Logger;
21+import org.slf4j.LoggerFactory;
22+
23+import java.util.Timer;
24+import java.util.TimerTask;
25+import java.util.concurrent.Callable;
26+import java.util.concurrent.locks.Condition;
27+import java.util.concurrent.locks.Lock;
28+import java.util.concurrent.locks.ReentrantLock;
29+
30+import static com.google.common.base.Preconditions.checkState;
31+import static java.util.concurrent.TimeUnit.MILLISECONDS;
32+import static org.assertj.core.api.Fail.fail;
33+
34+public class ConditionChecker {
35+
36+ private static final Logger logger = LoggerFactory.getLogger(ConditionChecker.class);
37+
38+ private static final int DEFAULT_PERIOD_MILLIS = 500;
39+
40+ public static <T> void awaitUntil(T input, Predicate<? super T> predicate, long timeoutMillis) {
41+ new ConditionChecker(input, predicate).await(timeoutMillis);
42+ }
43+
44+ public static void awaitUntil(final Callable<Boolean> condition, long timeoutMillis) {
45+ new ConditionChecker(condition).await(timeoutMillis);
46+ }
47+
48+ public static <T> void awaitWhile(T input, Predicate<? super T> predicate, long timeoutMillis) {
49+ new ConditionChecker(input, Predicates.not(predicate)).await(timeoutMillis);
50+ }
51+
52+ public static void awaitWhile(final Callable<Boolean> condition, long timeoutMillis) {
53+ new ConditionChecker(new Callable<Boolean>() {
54+ @Override
55+ public Boolean call() throws Exception {
56+ return !condition.call();
57+ }
58+ }).await(timeoutMillis);
59+ }
60+
61+ private final Object input;
62+
63+ private final Predicate<Object> predicate;
64+
65+ private final Lock lock;
66+
67+ private final Condition condition;
68+
69+ private final Timer timer;
70+
71+ /**
72+ * When using this constructor, one must override {@link #evalCondition()}.
73+ */
74+ public ConditionChecker() {
75+ this(null, null);
76+ checkState(!this.getClass().equals(ConditionChecker.class), "This constructor requires subclassing ConditionChecker");
77+ }
78+
79+ public ConditionChecker(Callable<Boolean> condition) {
80+ this(condition, DEFAULT_PERIOD_MILLIS);
81+ }
82+
83+ public ConditionChecker(final Callable<Boolean> condition, int periodMillis) {
84+ this(null, new Predicate<Void>() {
85+ @Override
86+ public boolean apply(Void input) {
87+ try {
88+ return condition.call();
89+ } catch (Exception e) {
90+ logger.error("Evaluation of condition threw exception", e);
91+ return false;
92+ }
93+ }
94+ }, periodMillis);
95+ }
96+
97+ public <T> ConditionChecker(T input, Predicate<? super T> predicate) {
98+ this(input, predicate, DEFAULT_PERIOD_MILLIS);
99+ }
100+
101+ @SuppressWarnings("unchecked")
102+ public <T> ConditionChecker(T input, Predicate<? super T> predicate, int periodMillis) {
103+ this.input = input;
104+ this.predicate = (Predicate<Object>) predicate;
105+ lock = new ReentrantLock();
106+ condition = lock.newCondition();
107+ timer = new Timer("condition-checker", true);
108+ timer.schedule(new TimerTask() {
109+ @Override
110+ public void run() {
111+ checkCondition();
112+ }
113+ }, 0, periodMillis);
114+ }
115+
116+ /**
117+ * Waits until the predicate becomes true,
118+ * or a timeout occurs, whichever happens first.
119+ *
120+ * @param timeoutMillis timeout in milliseconds
121+ */
122+ public void await(long timeoutMillis) {
123+ boolean interrupted = false;
124+ long nanos = MILLISECONDS.toNanos(timeoutMillis);
125+ lock.lock();
126+ try {
127+ while (!evalCondition()) {
128+ if (nanos <= 0L)
129+ fail(String.format("Timeout after %s milliseconds while waiting for condition", timeoutMillis));
130+ try {
131+ nanos = condition.awaitNanos(nanos);
132+ } catch (InterruptedException e) {
133+ interrupted = true;
134+ }
135+ }
136+ } finally {
137+ timer.cancel();
138+ if (interrupted)
139+ Thread.currentThread().interrupt();
140+ }
141+ }
142+
143+ private void checkCondition() {
144+ lock.lock();
145+ try {
146+ if (evalCondition()) {
147+ condition.signal();
148+ }
149+ } finally {
150+ lock.unlock();
151+ }
152+ }
153+
154+ protected boolean evalCondition() {
155+ return predicate.apply(input);
156+ }
157+
158+}
modified driver-core/src/test/java/com/datastax/driver/core/ConditionalUpdateTest.java +2 −2
@@ -28,10 +28,10 @@
2828 * Test {@link ResultSet#wasApplied()} for conditional updates.
2929 */
3030 @CassandraVersion(major = 2.0, description = "Conditional Updates requires 2.0+.")
31-public class ConditionalUpdateTest extends CCMBridge.PerClassSingleNodeCluster {
31+public class ConditionalUpdateTest extends CCMTestsSupport {
3232
3333 @Override
34- protected Collection<String> getTableDefinitions() {
34+ public Collection<String> createTestFixtures() {
3535 return Collections.singletonList("CREATE TABLE test(k1 int, k2 int, v int, PRIMARY KEY (k1, k2))");
3636 }
3737
modified driver-core/src/test/java/com/datastax/driver/core/ConsistencyTest.java +590 −604
@@ -23,6 +23,7 @@
2323 import com.datastax.driver.core.policies.DowngradingConsistencyRetryPolicy;
2424 import com.datastax.driver.core.policies.RoundRobinPolicy;
2525 import com.datastax.driver.core.policies.TokenAwarePolicy;
26+import com.google.common.util.concurrent.Uninterruptibles;
2627 import org.slf4j.Logger;
2728 import org.slf4j.LoggerFactory;
2829 import org.testng.annotations.Test;
@@ -31,713 +32,698 @@
3132 import java.util.EnumSet;
3233 import java.util.List;
3334 import java.util.Set;
34-
35-import static com.datastax.driver.core.TestUtils.stopAndWait;
35+import java.util.concurrent.TimeUnit;
36+
37+import static com.datastax.driver.core.CreateCCM.TestMode.PER_METHOD;
38+import static com.datastax.driver.core.TestUtils.IP_PREFIX;
39+import static com.datastax.driver.core.TestUtils.ipOfNode;
40+import static java.util.Collections.emptyList;
41+import static java.util.Collections.singletonList;
3642 import static org.testng.Assert.assertTrue;
3743 import static org.testng.Assert.fail;
3844
45+@SuppressWarnings("unused")
46+@CreateCCM(PER_METHOD)
47+@CCMConfig(
48+ dirtiesContext = true,
49+ createKeyspace = false,
50+ config = {
51+ "hinted_handoff_enabled:true",
52+ "phi_convict_threshold:1",
53+ "read_request_timeout_in_ms:100000",
54+ "write_request_timeout_in_ms:100000"}
55+)
3956 public class ConsistencyTest extends AbstractPoliciesTest {
4057
41- private static final Logger logger = LoggerFactory.getLogger(CCMBridge.class);
58+ private static final Logger logger = LoggerFactory.getLogger(ConsistencyTest.class);
59+
60+ private Cluster.Builder tokenAwareRoundRobin() {
61+ return Cluster.builder()
62+ .withSocketOptions(new SocketOptions().setReadTimeoutMillis(120000))
63+ .withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy()));
64+ }
65+
66+ private Cluster.Builder tokenAwareRoundRobinNoShuffle() {
67+ return Cluster.builder()
68+ .withSocketOptions(new SocketOptions().setReadTimeoutMillis(120000))
69+ .withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy(), false));
70+ }
71+
72+ private Cluster.Builder tokenAwareRoundRobinDowngrading() {
73+ return Cluster.builder()
74+ .withSocketOptions(new SocketOptions().setReadTimeoutMillis(120000))
75+ .withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy()))
76+ .withRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE);
77+ }
78+
79+ private Cluster.Builder tokenAwareRoundRobinNoShuffleDowngrading() {
80+ return Cluster.builder()
81+ .withSocketOptions(new SocketOptions().setReadTimeoutMillis(120000))
82+ .withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy(), false))
83+ .withRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE);
84+ }
85+
86+ private Cluster.Builder roundRobinDowngrading() {
87+ return Cluster.builder()
88+ .withSocketOptions(new SocketOptions().setReadTimeoutMillis(120000))
89+ .withLoadBalancingPolicy(new RoundRobinPolicy())
90+ .withRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE);
91+ }
92+
93+ private Cluster.Builder tokenAwareDCAwareRoundRobinNoShuffleDowngrading() {
94+ return Cluster.builder()
95+ .withSocketOptions(new SocketOptions().setReadTimeoutMillis(120000))
96+ .withLoadBalancingPolicy(new TokenAwarePolicy(DCAwareRoundRobinPolicy.builder().withLocalDc("dc2").build(), false))
97+ .withRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE);
98+ }
4299
43100 @Test(groups = "long")
101+ @CCMConfig(
102+ numberOfNodes = 3,
103+ clusterProvider = "tokenAwareRoundRobin")
44104 public void testRFOneTokenAware() throws Throwable {
45- Cluster.Builder builder = Cluster.builder().withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy()));
46- CCMBridge.CCMCluster c = CCMBridge.buildCluster(3, builder);
47- try {
48105
49- createSchema(c.session, 1);
50- init(c, 12, ConsistencyLevel.ONE);
51- query(c, 12, ConsistencyLevel.ONE);
52-
53- assertQueried(CCMBridge.IP_PREFIX + '1', 0);
54- assertQueried(CCMBridge.IP_PREFIX + '2', 12);
55- assertQueried(CCMBridge.IP_PREFIX + '3', 0);
56-
57- resetCoordinators();
58- stopAndWait(c, 2);
59-
60- List<ConsistencyLevel> acceptedList = Arrays.asList(ConsistencyLevel.ANY);
61-
62- List<ConsistencyLevel> failList = Arrays.asList(
63- ConsistencyLevel.ONE,
64- ConsistencyLevel.TWO,
65- ConsistencyLevel.THREE,
66- ConsistencyLevel.QUORUM,
67- ConsistencyLevel.ALL,
68- ConsistencyLevel.LOCAL_QUORUM,
69- ConsistencyLevel.EACH_QUORUM);
70-
71- // Test successful writes
72- for (ConsistencyLevel cl : acceptedList) {
73- try {
74- init(c, 12, cl);
75- } catch (Exception e) {
76- fail(String.format("Test failed at CL.%s with message: %s", cl, e.getMessage()));
77- }
78- }
106+ createSchema(1);
107+ init(12, ConsistencyLevel.ONE);
108+ query(12, ConsistencyLevel.ONE);
109+
110+ assertQueried(IP_PREFIX + '1', 0);
111+ assertQueried(IP_PREFIX + '2', 12);
112+ assertQueried(IP_PREFIX + '3', 0);
113+
114+ resetCoordinators();
115+ stopAndWait(2);
116+
117+ List<ConsistencyLevel> acceptedList = singletonList(ConsistencyLevel.ANY);
118+
119+ List<ConsistencyLevel> failList = Arrays.asList(
120+ ConsistencyLevel.ONE,
121+ ConsistencyLevel.TWO,
122+ ConsistencyLevel.THREE,
123+ ConsistencyLevel.QUORUM,
124+ ConsistencyLevel.ALL,
125+ ConsistencyLevel.LOCAL_QUORUM,
126+ ConsistencyLevel.EACH_QUORUM);
79127
80- // Test successful reads
81- for (ConsistencyLevel cl : acceptedList) {
82- try {
83- query(c, 12, cl);
84- } catch (InvalidQueryException e) {
85- List<String> acceptableErrorMessages = Arrays.asList(
86- "ANY ConsistencyLevel is only supported for writes");
87- assertTrue(acceptableErrorMessages.contains(e.getMessage()));
88- }
128+ // Test successful writes
129+ for (ConsistencyLevel cl : acceptedList) {
130+ try {
131+ init(12, cl);
132+ } catch (Exception e) {
133+ fail(String.format("Test failed at CL.%s with message: %s", cl, e.getMessage()));
89134 }
135+ }
90136
91- // Test writes which should fail
92- for (ConsistencyLevel cl : failList) {
93- try {
94- init(c, 12, cl);
95- fail(String.format("Test passed at CL.%s.", cl));
96- } catch (InvalidQueryException e) {
97- List<String> acceptableErrorMessages = Arrays.asList(
98- "consistency level LOCAL_QUORUM not compatible with replication strategy (org.apache.cassandra.locator.SimpleStrategy)",
99- "consistency level EACH_QUORUM not compatible with replication strategy (org.apache.cassandra.locator.SimpleStrategy)");
100- assertTrue(acceptableErrorMessages.contains(e.getMessage()), String.format("Received: %s", e.getMessage()));
101- } catch (UnavailableException e) {
102- // expected to fail when the client has already marked the
103- // node as DOWN
104- } catch (WriteTimeoutException e) {
105- // expected to fail when the client hasn't marked the
106- // node as DOWN yet
107- }
137+ // Test successful reads
138+ for (ConsistencyLevel cl : acceptedList) {
139+ try {
140+ query(12, cl);
141+ } catch (InvalidQueryException e) {
142+ List<String> acceptableErrorMessages = singletonList(
143+ "ANY ConsistencyLevel is only supported for writes");
144+ assertTrue(acceptableErrorMessages.contains(e.getMessage()));
108145 }
146+ }
109147
110- // Test reads which should fail
111- for (ConsistencyLevel cl : failList) {
112- try {
113- query(c, 12, cl);
114- fail(String.format("Test passed at CL.%s.", cl));
115- } catch (InvalidQueryException e) {
116- List<String> acceptableErrorMessages = Arrays.asList(
117- "consistency level LOCAL_QUORUM not compatible with replication strategy (org.apache.cassandra.locator.SimpleStrategy)",
118- "EACH_QUORUM ConsistencyLevel is only supported for writes");
119- assertTrue(acceptableErrorMessages.contains(e.getMessage()), String.format("Received: %s", e.getMessage()));
120- } catch (ReadTimeoutException e) {
121- // expected to fail when the client hasn't marked the
122- // node as DOWN yet
123- } catch (UnavailableException e) {
124- // expected to fail when the client has already marked the
125- // node as DOWN
126- }
148+ // Test writes which should fail
149+ for (ConsistencyLevel cl : failList) {
150+ try {
151+ init(12, cl);
152+ fail(String.format("Test passed at CL.%s.", cl));
153+ } catch (InvalidQueryException e) {
154+ List<String> acceptableErrorMessages = Arrays.asList(
155+ "consistency level LOCAL_QUORUM not compatible with replication strategy (org.apache.cassandra.locator.SimpleStrategy)",
156+ "consistency level EACH_QUORUM not compatible with replication strategy (org.apache.cassandra.locator.SimpleStrategy)");
157+ assertTrue(acceptableErrorMessages.contains(e.getMessage()), String.format("Received: %s", e.getMessage()));
158+ } catch (UnavailableException e) {
159+ // expected to fail when the client has already marked the
160+ // node as DOWN
161+ } catch (WriteTimeoutException e) {
162+ // expected to fail when the client hasn't marked the
163+ // node as DOWN yet
127164 }
165+ }
128166
129- } catch (Throwable e) {
130- c.errorOut();
131- throw e;
132- } finally {
133- resetCoordinators();
134- c.discard();
167+ // Test reads which should fail
168+ for (ConsistencyLevel cl : failList) {
169+ try {
170+ query(12, cl);
171+ fail(String.format("Test passed at CL.%s.", cl));
172+ } catch (InvalidQueryException e) {
173+ List<String> acceptableErrorMessages = Arrays.asList(
174+ "consistency level LOCAL_QUORUM not compatible with replication strategy (org.apache.cassandra.locator.SimpleStrategy)",
175+ "EACH_QUORUM ConsistencyLevel is only supported for writes");
176+ assertTrue(acceptableErrorMessages.contains(e.getMessage()), String.format("Received: %s", e.getMessage()));
177+ } catch (ReadTimeoutException e) {
178+ // expected to fail when the client hasn't marked the
179+ // node as DOWN yet
180+ } catch (UnavailableException e) {
181+ // expected to fail when the client has already marked the
182+ // node as DOWN
183+ }
135184 }
136185 }
137186
138187 @Test(groups = "long")
188+ @CCMConfig(numberOfNodes = 3,
189+ clusterProvider = "tokenAwareRoundRobinNoShuffle")
139190 public void testRFTwoTokenAware() throws Throwable {
140- Cluster.Builder builder = Cluster.builder().withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy(), false));
141- CCMBridge.CCMCluster c = CCMBridge.buildCluster(3, builder);
142- try {
143-
144- createSchema(c.session, 2);
145- init(c, 12, ConsistencyLevel.TWO);
146- query(c, 12, ConsistencyLevel.TWO);
147-
148- assertQueried(CCMBridge.IP_PREFIX + '1', 0);
149- assertQueried(CCMBridge.IP_PREFIX + '2', 12);
150- assertQueried(CCMBridge.IP_PREFIX + '3', 0);
151-
152- resetCoordinators();
153- stopAndWait(c, 2);
154-
155- List<ConsistencyLevel> acceptedList = Arrays.asList(
156- ConsistencyLevel.ANY,
157- ConsistencyLevel.ONE
158- );
159-
160- List<ConsistencyLevel> failList = Arrays.asList(
161- ConsistencyLevel.TWO,
162- ConsistencyLevel.QUORUM,
163- ConsistencyLevel.THREE,
164- ConsistencyLevel.ALL,
165- ConsistencyLevel.LOCAL_QUORUM,
166- ConsistencyLevel.EACH_QUORUM);
167-
168- // Test successful writes
169- for (ConsistencyLevel cl : acceptedList) {
170- try {
171- init(c, 12, cl);
172- } catch (Exception e) {
173- fail(String.format("Test failed at CL.%s with message: %s", cl, e.getMessage()));
174- }
191+ createSchema(2);
192+ init(12, ConsistencyLevel.TWO);
193+ query(12, ConsistencyLevel.TWO);
194+
195+ assertQueried(IP_PREFIX + '1', 0);
196+ assertQueried(IP_PREFIX + '2', 12);
197+ assertQueried(IP_PREFIX + '3', 0);
198+
199+ resetCoordinators();
200+ stopAndWait(2);
201+
202+ List<ConsistencyLevel> acceptedList = Arrays.asList(
203+ ConsistencyLevel.ANY,
204+ ConsistencyLevel.ONE
205+ );
206+
207+ List<ConsistencyLevel> failList = Arrays.asList(
208+ ConsistencyLevel.TWO,
209+ ConsistencyLevel.QUORUM,
210+ ConsistencyLevel.THREE,
211+ ConsistencyLevel.ALL,
212+ ConsistencyLevel.LOCAL_QUORUM,
213+ ConsistencyLevel.EACH_QUORUM);
214+
215+ // Test successful writes
216+ for (ConsistencyLevel cl : acceptedList) {
217+ try {
218+ init(12, cl);
219+ } catch (Exception e) {
220+ fail(String.format("Test failed at CL.%s with message: %s", cl, e.getMessage()));
175221 }
222+ }
176223
177- // Test successful reads
178- for (ConsistencyLevel cl : acceptedList) {
179- try {
180- query(c, 12, cl);
181- } catch (InvalidQueryException e) {
182- List<String> acceptableErrorMessages = Arrays.asList(
183- "ANY ConsistencyLevel is only supported for writes");
184- assertTrue(acceptableErrorMessages.contains(e.getMessage()));
185- }
224+ // Test successful reads
225+ for (ConsistencyLevel cl : acceptedList) {
226+ try {
227+ query(12, cl);
228+ } catch (InvalidQueryException e) {
229+ List<String> acceptableErrorMessages = singletonList(
230+ "ANY ConsistencyLevel is only supported for writes");
231+ assertTrue(acceptableErrorMessages.contains(e.getMessage()));
186232 }
233+ }
187234
188- // Test writes which should fail
189- for (ConsistencyLevel cl : failList) {
190- try {
191- init(c, 12, cl);
192- fail(String.format("Test passed at CL.%s.", cl));
193- } catch (InvalidQueryException e) {
194- List<String> acceptableErrorMessages = Arrays.asList(
195- "consistency level LOCAL_QUORUM not compatible with replication strategy (org.apache.cassandra.locator.SimpleStrategy)",
196- "consistency level EACH_QUORUM not compatible with replication strategy (org.apache.cassandra.locator.SimpleStrategy)");
197- assertTrue(acceptableErrorMessages.contains(e.getMessage()), String.format("Received: %s", e.getMessage()));
198- } catch (UnavailableException e) {
199- // expected to fail when the client has already marked the
200- // node as DOWN
201- } catch (WriteTimeoutException e) {
202- // expected to fail when the client hasn't marked the
203- // node as DOWN yet
204- }
235+ // Test writes which should fail
236+ for (ConsistencyLevel cl : failList) {
237+ try {
238+ init(12, cl);
239+ fail(String.format("Test passed at CL.%s.", cl));
240+ } catch (InvalidQueryException e) {
241+ List<String> acceptableErrorMessages = Arrays.asList(
242+ "consistency level LOCAL_QUORUM not compatible with replication strategy (org.apache.cassandra.locator.SimpleStrategy)",
243+ "consistency level EACH_QUORUM not compatible with replication strategy (org.apache.cassandra.locator.SimpleStrategy)");
244+ assertTrue(acceptableErrorMessages.contains(e.getMessage()), String.format("Received: %s", e.getMessage()));
245+ } catch (UnavailableException e) {
246+ // expected to fail when the client has already marked the
247+ // node as DOWN
248+ } catch (WriteTimeoutException e) {
249+ // expected to fail when the client hasn't marked the
250+ // node as DOWN yet
205251 }
252+ }
206253
207- // Test reads which should fail
208- for (ConsistencyLevel cl : failList) {
209- try {
210- query(c, 12, cl);
211- fail(String.format("Test passed at CL.%s.", cl));
212- } catch (InvalidQueryException e) {
213- List<String> acceptableErrorMessages = Arrays.asList(
214- "consistency level LOCAL_QUORUM not compatible with replication strategy (org.apache.cassandra.locator.SimpleStrategy)",
215- "EACH_QUORUM ConsistencyLevel is only supported for writes");
216- assertTrue(acceptableErrorMessages.contains(e.getMessage()), String.format("Received: %s", e.getMessage()));
217- } catch (ReadTimeoutException e) {
218- // expected to fail when the client hasn't marked the
219- // node as DOWN yet
220- } catch (UnavailableException e) {
221- // expected to fail when the client has already marked the
222- // node as DOWN
223- }
254+ // Test reads which should fail
255+ for (ConsistencyLevel cl : failList) {
256+ try {
257+ query(12, cl);
258+ fail(String.format("Test passed at CL.%s.", cl));
259+ } catch (InvalidQueryException e) {
260+ List<String> acceptableErrorMessages = Arrays.asList(
261+ "consistency level LOCAL_QUORUM not compatible with replication strategy (org.apache.cassandra.locator.SimpleStrategy)",
262+ "EACH_QUORUM ConsistencyLevel is only supported for writes");
263+ assertTrue(acceptableErrorMessages.contains(e.getMessage()), String.format("Received: %s", e.getMessage()));
264+ } catch (ReadTimeoutException e) {
265+ // expected to fail when the client hasn't marked the
266+ // node as DOWN yet
267+ } catch (UnavailableException e) {
268+ // expected to fail when the client has already marked the
269+ // node as DOWN
224270 }
225-
226- } catch (Throwable e) {
227- c.errorOut();
228- throw e;
229- } finally {
230- resetCoordinators();
231- c.discard();
232271 }
233272 }
234273
235274 @Test(groups = "long")
275+ @CCMConfig(numberOfNodes = 3,
276+ clusterProvider = "tokenAwareRoundRobinNoShuffle")
236277 public void testRFThreeTokenAware() throws Throwable {
237- Cluster.Builder builder = Cluster.builder().withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy(), false));
238- CCMBridge.CCMCluster c = CCMBridge.buildCluster(3, builder);
239- try {
240-
241- createSchema(c.session, 3);
242- init(c, 12, ConsistencyLevel.TWO);
243- query(c, 12, ConsistencyLevel.TWO);
244-
245- assertQueried(CCMBridge.IP_PREFIX + '1', 0);
246- assertQueried(CCMBridge.IP_PREFIX + '2', 12);
247- assertQueried(CCMBridge.IP_PREFIX + '3', 0);
248-
249- resetCoordinators();
250- stopAndWait(c, 2);
251-
252- Set<ConsistencyLevel> cls = EnumSet.allOf(ConsistencyLevel.class);
253- // Remove serial consistencies as they require conditional read/writes
254- cls.remove(ConsistencyLevel.SERIAL);
255- cls.remove(ConsistencyLevel.LOCAL_SERIAL);
256-
257- List<ConsistencyLevel> acceptedList = Arrays.asList(
258- ConsistencyLevel.ANY,
259- ConsistencyLevel.ONE,
260- ConsistencyLevel.TWO,
261- ConsistencyLevel.QUORUM,
262- ConsistencyLevel.LOCAL_QUORUM,
263- ConsistencyLevel.EACH_QUORUM
264- );
265-
266- List<ConsistencyLevel> failList = Arrays.asList(
267- ConsistencyLevel.THREE,
268- ConsistencyLevel.ALL
269- );
270-
271-
272- // Test successful writes
273- for (ConsistencyLevel cl : acceptedList) {
274- try {
275- init(c, 12, cl);
276- } catch (Exception e) {
277- fail(String.format("Test failed at CL.%s with message: %s", cl, e.getMessage()));
278- }
278+ createSchema(3);
279+ init(12, ConsistencyLevel.TWO);
280+ query(12, ConsistencyLevel.TWO);
281+
282+ assertQueried(IP_PREFIX + '1', 0);
283+ assertQueried(IP_PREFIX + '2', 12);
284+ assertQueried(IP_PREFIX + '3', 0);
285+
286+ resetCoordinators();
287+ stopAndWait(2);
288+
289+ Set<ConsistencyLevel> cls = EnumSet.allOf(ConsistencyLevel.class);
290+ // Remove serial consistencies as they require conditional read/writes
291+ cls.remove(ConsistencyLevel.SERIAL);
292+ cls.remove(ConsistencyLevel.LOCAL_SERIAL);
293+
294+ List<ConsistencyLevel> acceptedList = Arrays.asList(
295+ ConsistencyLevel.ANY,
296+ ConsistencyLevel.ONE,
297+ ConsistencyLevel.TWO,
298+ ConsistencyLevel.QUORUM,
299+ ConsistencyLevel.LOCAL_QUORUM,
300+ ConsistencyLevel.EACH_QUORUM
301+ );
302+
303+ List<ConsistencyLevel> failList = Arrays.asList(
304+ ConsistencyLevel.THREE,
305+ ConsistencyLevel.ALL
306+ );
307+
308+
309+ // Test successful writes
310+ for (ConsistencyLevel cl : acceptedList) {
311+ try {
312+ init(12, cl);
313+ } catch (Exception e) {
314+ fail(String.format("Test failed at CL.%s with message: %s", cl, e.getMessage()));
279315 }
316+ }
280317
281- // Test successful reads
282- for (ConsistencyLevel cl : acceptedList) {
283- try {
284- query(c, 12, cl);
285- } catch (InvalidQueryException e) {
286- List<String> acceptableErrorMessages = Arrays.asList(
287- "ANY ConsistencyLevel is only supported for writes",
288- "EACH_QUORUM ConsistencyLevel is only supported for writes"
289- );
290- assertTrue(acceptableErrorMessages.contains(e.getMessage()), "Got unexpected message " + e.getMessage());
291- }
318+ // Test successful reads
319+ for (ConsistencyLevel cl : acceptedList) {
320+ try {
321+ query(12, cl);
322+ } catch (InvalidQueryException e) {
323+ List<String> acceptableErrorMessages = Arrays.asList(
324+ "ANY ConsistencyLevel is only supported for writes",
325+ "EACH_QUORUM ConsistencyLevel is only supported for writes"
326+ );
327+ assertTrue(acceptableErrorMessages.contains(e.getMessage()), "Got unexpected message " + e.getMessage());
292328 }
329+ }
293330
294- // Test writes which should fail
295- for (ConsistencyLevel cl : failList) {
296- try {
297- init(c, 12, cl);
298- fail(String.format("Test passed at CL.%s.", cl));
299- } catch (UnavailableException e) {
300- // expected to fail when the client has already marked the
301- // node as DOWN
302- } catch (WriteTimeoutException e) {
303- // expected to fail when the client hasn't marked the
304- // node as DOWN yet
305- }
331+ // Test writes which should fail
332+ for (ConsistencyLevel cl : failList) {
333+ try {
334+ init(12, cl);
335+ fail(String.format("Test passed at CL.%s.", cl));
336+ } catch (UnavailableException e) {
337+ // expected to fail when the client has already marked the
338+ // node as DOWN
339+ } catch (WriteTimeoutException e) {
340+ // expected to fail when the client hasn't marked the
341+ // node as DOWN yet
306342 }
343+ }
307344
308- // Test reads which should fail
309- for (ConsistencyLevel cl : failList) {
310- try {
311- query(c, 12, cl);
312- fail(String.format("Test passed at CL.%s.", cl));
313- } catch (ReadTimeoutException e) {
314- // expected to fail when the client hasn't marked the
315- // node as DOWN yet
316- } catch (UnavailableException e) {
317- // expected to fail when the client has already marked the
318- // node as DOWN
319- }
345+ // Test reads which should fail
346+ for (ConsistencyLevel cl : failList) {
347+ try {
348+ query(12, cl);
349+ fail(String.format("Test passed at CL.%s.", cl));
350+ } catch (ReadTimeoutException e) {
351+ // expected to fail when the client hasn't marked the
352+ // node as DOWN yet
353+ } catch (UnavailableException e) {
354+ // expected to fail when the client has already marked the
355+ // node as DOWN
320356 }
321-
322- } catch (Throwable e) {
323- c.errorOut();
324- throw e;
325- } finally {
326- resetCoordinators();
327- c.discard();
328357 }
329358 }
330359
331360
332361 @Test(groups = "long")
362+ @CCMConfig(numberOfNodes = 3,
363+ clusterProvider = "tokenAwareRoundRobinDowngrading")
333364 public void testRFOneDowngradingCL() throws Throwable {
334- Cluster.Builder builder = Cluster.builder().withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy())).withRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE);
335- CCMBridge.CCMCluster c = CCMBridge.buildCluster(3, builder);
336- try {
337-
338- createSchema(c.session, 1);
339- init(c, 12, ConsistencyLevel.ONE);
340- query(c, 12, ConsistencyLevel.ONE);
341-
342- assertQueried(CCMBridge.IP_PREFIX + '1', 0);
343- assertQueried(CCMBridge.IP_PREFIX + '2', 12);
344- assertQueried(CCMBridge.IP_PREFIX + '3', 0);
345-
346- resetCoordinators();
347- stopAndWait(c, 2);
348-
349- List<ConsistencyLevel> acceptedList = Arrays.asList(
350- ConsistencyLevel.ANY
351- );
352-
353- List<ConsistencyLevel> failList = Arrays.asList(
354- ConsistencyLevel.ONE,
355- ConsistencyLevel.TWO,
356- ConsistencyLevel.THREE,
357- ConsistencyLevel.QUORUM,
358- ConsistencyLevel.ALL,
359- ConsistencyLevel.LOCAL_QUORUM,
360- ConsistencyLevel.EACH_QUORUM);
361-
362- // Test successful writes
363- for (ConsistencyLevel cl : acceptedList) {
364- try {
365- init(c, 12, cl);
366- } catch (Exception e) {
367- fail(String.format("Test failed at CL.%s with message: %s", cl, e.getMessage()));
368- }
365+ createSchema(1);
366+ init(12, ConsistencyLevel.ONE);
367+ query(12, ConsistencyLevel.ONE);
368+
369+ assertQueried(IP_PREFIX + '1', 0);
370+ assertQueried(IP_PREFIX + '2', 12);
371+ assertQueried(IP_PREFIX + '3', 0);
372+
373+ resetCoordinators();
374+ stopAndWait(2);
375+
376+ List<ConsistencyLevel> acceptedList = singletonList(
377+ ConsistencyLevel.ANY
378+ );
379+
380+ List<ConsistencyLevel> failList = Arrays.asList(
381+ ConsistencyLevel.ONE,
382+ ConsistencyLevel.TWO,
383+ ConsistencyLevel.THREE,
384+ ConsistencyLevel.QUORUM,
385+ ConsistencyLevel.ALL,
386+ ConsistencyLevel.LOCAL_QUORUM,
387+ ConsistencyLevel.EACH_QUORUM);
388+
389+ // Test successful writes
390+ for (ConsistencyLevel cl : acceptedList) {
391+ try {
392+ init(12, cl);
393+ } catch (Exception e) {
394+ fail(String.format("Test failed at CL.%s with message: %s", cl, e.getMessage()));
369395 }
396+ }
370397
371- // Test successful reads
372- for (ConsistencyLevel cl : acceptedList) {
373- try {
374- query(c, 12, cl);
375- } catch (InvalidQueryException e) {
376- List<String> acceptableErrorMessages = Arrays.asList(
377- "ANY ConsistencyLevel is only supported for writes");
378- assertTrue(acceptableErrorMessages.contains(e.getMessage()));
379- }
398+ // Test successful reads
399+ for (ConsistencyLevel cl : acceptedList) {
400+ try {
401+ query(12, cl);
402+ } catch (InvalidQueryException e) {
403+ List<String> acceptableErrorMessages = singletonList(
404+ "ANY ConsistencyLevel is only supported for writes");
405+ assertTrue(acceptableErrorMessages.contains(e.getMessage()));
380406 }
407+ }
381408
382- // Test writes which should fail
383- for (ConsistencyLevel cl : failList) {
384- try {
385- init(c, 12, cl);
386- fail(String.format("Test passed at CL.%s.", cl));
387- } catch (UnavailableException e) {
388- // expected to fail when the client has already marked the
389- // node as DOWN
390- } catch (WriteTimeoutException e) {
391- // expected to fail when the client hasn't marked the
392- // node as DOWN yet
393- }
409+ // Test writes which should fail
410+ for (ConsistencyLevel cl : failList) {
411+ try {
412+ init(12, cl);
413+ fail(String.format("Test passed at CL.%s.", cl));
414+ } catch (UnavailableException e) {
415+ // expected to fail when the client has already marked the
416+ // node as DOWN
417+ } catch (WriteTimeoutException e) {
418+ // expected to fail when the client hasn't marked the
419+ // node as DOWN yet
394420 }
421+ }
395422
396- // Test reads which should fail
397- for (ConsistencyLevel cl : failList) {
398- try {
399- query(c, 12, cl);
400- fail(String.format("Test passed at CL.%s.", cl));
401- } catch (InvalidQueryException e) {
402- List<String> acceptableErrorMessages = Arrays.asList(
403- "EACH_QUORUM ConsistencyLevel is only supported for writes"
404- );
405- assertTrue(acceptableErrorMessages.contains(e.getMessage()), "Got unexpected message " + e.getMessage());
406- } catch (ReadTimeoutException e) {
407- // expected to fail when the client hasn't marked the
408- // node as DOWN yet
409- } catch (UnavailableException e) {
410- // expected to fail when the client has already marked the
411- // node as DOWN
412- }
423+ // Test reads which should fail
424+ for (ConsistencyLevel cl : failList) {
425+ try {
426+ query(12, cl);
427+ fail(String.format("Test passed at CL.%s.", cl));
428+ } catch (InvalidQueryException e) {
429+ List<String> acceptableErrorMessages = singletonList(
430+ "EACH_QUORUM ConsistencyLevel is only supported for writes"
431+ );
432+ assertTrue(acceptableErrorMessages.contains(e.getMessage()), "Got unexpected message " + e.getMessage());
433+ } catch (ReadTimeoutException e) {
434+ // expected to fail when the client hasn't marked the
435+ // node as DOWN yet
436+ } catch (UnavailableException e) {
437+ // expected to fail when the client has already marked the
438+ // node as DOWN
413439 }
414-
415- } catch (Throwable e) {
416- c.errorOut();
417- throw e;
418- } finally {
419- resetCoordinators();
420- c.discard();
421440 }
422441 }
423442
424443 @Test(groups = "long")
444+ @CCMConfig(numberOfNodes = 3,
445+ clusterProvider = "tokenAwareRoundRobinNoShuffleDowngrading")
425446 public void testRFTwoDowngradingCL() throws Throwable {
426- Cluster.Builder builder = Cluster.builder()
427- .withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy(), false))
428- .withRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE);
429- CCMBridge.CCMCluster c = CCMBridge.buildCluster(3, builder);
430- try {
431-
432- createSchema(c.session, 2);
433- init(c, 12, ConsistencyLevel.TWO);
434- query(c, 12, ConsistencyLevel.TWO);
435-
436- assertQueried(CCMBridge.IP_PREFIX + '1', 0);
437- assertQueried(CCMBridge.IP_PREFIX + '2', 12);
438- assertQueried(CCMBridge.IP_PREFIX + '3', 0);
439-
440- resetCoordinators();
441- stopAndWait(c, 2);
442-
443- Set<ConsistencyLevel> acceptedList = EnumSet.allOf(ConsistencyLevel.class);
444- // Remove serial consistencies as they require conditional read/writes
445- acceptedList.remove(ConsistencyLevel.SERIAL);
446- acceptedList.remove(ConsistencyLevel.LOCAL_SERIAL);
447-
448- // Test successful writes
449- for (ConsistencyLevel cl : acceptedList) {
450- try {
451- init(c, 12, cl);
452- } catch (Exception e) {
453- fail(String.format("Test failed at CL.%s with message: %s", cl, e.getMessage()));
454- }
447+ createSchema(2);
448+ init(12, ConsistencyLevel.TWO);
449+ query(12, ConsistencyLevel.TWO);
450+
451+ assertQueried(IP_PREFIX + '1', 0);
452+ assertQueried(IP_PREFIX + '2', 12);
453+ assertQueried(IP_PREFIX + '3', 0);
454+
455+ resetCoordinators();
456+ stopAndWait(2);
457+
458+ Set<ConsistencyLevel> acceptedList = EnumSet.allOf(ConsistencyLevel.class);
459+ // Remove serial consistencies as they require conditional read/writes
460+ acceptedList.remove(ConsistencyLevel.SERIAL);
461+ acceptedList.remove(ConsistencyLevel.LOCAL_SERIAL);
462+
463+ // Test successful writes
464+ for (ConsistencyLevel cl : acceptedList) {
465+ try {
466+ init(12, cl);
467+ } catch (Exception e) {
468+ fail(String.format("Test failed at CL.%s with message: %s", cl, e.getMessage()));
455469 }
470+ }
456471
457- // Test successful reads
458- for (ConsistencyLevel cl : acceptedList) {
459- try {
460- query(c, 12, cl);
461- } catch (InvalidQueryException e) {
462- List<String> acceptableErrorMessages = Arrays.asList(
463- "ANY ConsistencyLevel is only supported for writes",
464- "EACH_QUORUM ConsistencyLevel is only supported for writes"
465- );
466- assertTrue(acceptableErrorMessages.contains(e.getMessage()), "Got unexpected message " + e.getMessage());
467- }
472+ // Test successful reads
473+ for (ConsistencyLevel cl : acceptedList) {
474+ try {
475+ query(12, cl);
476+ } catch (InvalidQueryException e) {
477+ List<String> acceptableErrorMessages = Arrays.asList(
478+ "ANY ConsistencyLevel is only supported for writes",
479+ "EACH_QUORUM ConsistencyLevel is only supported for writes"
480+ );
481+ assertTrue(acceptableErrorMessages.contains(e.getMessage()), "Got unexpected message " + e.getMessage());
468482 }
469-
470- } catch (Throwable e) {
471- c.errorOut();
472- throw e;
473- } finally {
474- resetCoordinators();
475- c.discard();
476483 }
477484 }
478485
479486 @Test(groups = "long")
487+ @CCMConfig(numberOfNodes = 3,
488+ clusterProvider = "roundRobinDowngrading")
480489 public void testRFThreeRoundRobinDowngradingCL() throws Throwable {
481- Cluster.Builder builder = Cluster.builder().withLoadBalancingPolicy(new RoundRobinPolicy()).withRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE);
482- testRFThreeDowngradingCL(builder);
490+ testRFThreeDowngradingCL();
483491 }
484492
485493 @Test(groups = "long")
494+ @CCMConfig(numberOfNodes = 3,
495+ clusterProvider = "tokenAwareRoundRobinNoShuffleDowngrading")
486496 public void testRFThreeTokenAwareDowngradingCL() throws Throwable {
487- Cluster.Builder builder = Cluster.builder()
488- .withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy(), false))
489- .withRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE);
490- testRFThreeDowngradingCL(builder);
497+ testRFThreeDowngradingCL();
491498 }
492499
493- public void testRFThreeDowngradingCL(Cluster.Builder builder) throws Throwable {
494- CCMBridge.CCMCluster c = CCMBridge.buildCluster(3, builder);
500+ private void testRFThreeDowngradingCL() throws Throwable {
501+
502+ createSchema(3);
503+ init(12, ConsistencyLevel.ALL);
504+ query(12, ConsistencyLevel.ALL);
505+
495506 try {
507+ // This test catches TokenAwarePolicy
508+ // However, full tests in LoadBalancingPolicyTest.java
509+ assertQueried(IP_PREFIX + '1', 0);
510+ assertQueried(IP_PREFIX + '2', 12);
511+ assertQueried(IP_PREFIX + '3', 0);
512+ } catch (AssertionError e) {
513+ // This test catches RoundRobinPolicy
514+ assertQueried(IP_PREFIX + '1', 4);
515+ assertQueried(IP_PREFIX + '2', 4);
516+ assertQueried(IP_PREFIX + '3', 4);
517+ }
496518
497- createSchema(c.session, 3);
498- init(c, 12, ConsistencyLevel.ALL);
499- query(c, 12, ConsistencyLevel.ALL);
519+ resetCoordinators();
520+ stopAndWait(2);
500521
501- try {
502- // This test catches TokenAwarePolicy
503- // However, full tests in LoadBalancingPolicyTest.java
504- assertQueried(CCMBridge.IP_PREFIX + '1', 0);
505- assertQueried(CCMBridge.IP_PREFIX + '2', 12);
506- assertQueried(CCMBridge.IP_PREFIX + '3', 0);
507- } catch (AssertionError e) {
508- // This test catches RoundRobinPolicy
509- assertQueried(CCMBridge.IP_PREFIX + '1', 4);
510- assertQueried(CCMBridge.IP_PREFIX + '2', 4);
511- assertQueried(CCMBridge.IP_PREFIX + '3', 4);
512- }
522+ Set<ConsistencyLevel> acceptedList = EnumSet.allOf(ConsistencyLevel.class);
523+ // Remove serial consistencies as they require conditional read/writes
524+ acceptedList.remove(ConsistencyLevel.SERIAL);
525+ acceptedList.remove(ConsistencyLevel.LOCAL_SERIAL);
513526
514- resetCoordinators();
515- stopAndWait(c, 2);
516-
517- Set<ConsistencyLevel> acceptedList = EnumSet.allOf(ConsistencyLevel.class);
518- // Remove serial consistencies as they require conditional read/writes
519- acceptedList.remove(ConsistencyLevel.SERIAL);
520- acceptedList.remove(ConsistencyLevel.LOCAL_SERIAL);
521-
522- // Test successful writes
523- for (ConsistencyLevel cl : acceptedList) {
524- try {
525- init(c, 12, cl);
526- } catch (Exception e) {
527- fail(String.format("Test failed at CL.%s with message: %s", cl, e.getMessage()));
528- }
527+ // Test successful writes
528+ for (ConsistencyLevel cl : acceptedList) {
529+ try {
530+ init(12, cl);
531+ } catch (Exception e) {
532+ fail(String.format("Test failed at CL.%s with message: %s", cl, e.getMessage()));
529533 }
534+ }
530535
531- // Test successful reads
532- for (ConsistencyLevel cl : acceptedList) {
533- try {
534- query(c, 12, cl);
535- } catch (InvalidQueryException e) {
536- List<String> acceptableErrorMessages = Arrays.asList(
537- "ANY ConsistencyLevel is only supported for writes",
538- "EACH_QUORUM ConsistencyLevel is only supported for writes"
539- );
540- assertTrue(acceptableErrorMessages.contains(e.getMessage()), "Got unexpected message " + e.getMessage());
541- }
536+ // Test successful reads
537+ for (ConsistencyLevel cl : acceptedList) {
538+ try {
539+ query(12, cl);
540+ } catch (InvalidQueryException e) {
541+ List<String> acceptableErrorMessages = Arrays.asList(
542+ "ANY ConsistencyLevel is only supported for writes",
543+ "EACH_QUORUM ConsistencyLevel is only supported for writes"
544+ );
545+ assertTrue(acceptableErrorMessages.contains(e.getMessage()), "Got unexpected message " + e.getMessage());
542546 }
543-
544- } catch (Throwable e) {
545- c.errorOut();
546- throw e;
547- } finally {
548- resetCoordinators();
549- c.discard();
550547 }
551548 }
552549
553550 @Test(groups = "long")
551+ @CCMConfig(
552+ numberOfNodes = {3, 3},
553+ clusterProvider = "tokenAwareRoundRobinNoShuffleDowngrading"
554+ )
554555 public void testRFThreeDowngradingCLTwoDCs() throws Throwable {
555- Cluster.Builder builder = Cluster.builder()
556- .withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy(), false))
557- .withRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE);
558- CCMBridge.CCMCluster c = CCMBridge.buildCluster(3, 3, builder);
559- try {
560-
561- createMultiDCSchema(c.session, 3, 3);
562- init(c, 12, ConsistencyLevel.TWO);
563- query(c, 12, ConsistencyLevel.TWO);
564-
565- assertQueried(CCMBridge.IP_PREFIX + '1', 0);
566- assertQueried(CCMBridge.IP_PREFIX + '2', 12);
567- assertQueried(CCMBridge.IP_PREFIX + '3', 0);
568- assertQueried(CCMBridge.IP_PREFIX + '4', 0);
569- assertQueried(CCMBridge.IP_PREFIX + '5', 0);
570- assertQueried(CCMBridge.IP_PREFIX + '6', 0);
571-
572- resetCoordinators();
573- logger.info("Stopping node 3...");
574- stopAndWait(c, 3);
575- logger.info("Node 3 stopped.");
576-
577- List<ConsistencyLevel> acceptedList = Arrays.asList(
578- ConsistencyLevel.ANY,
579- ConsistencyLevel.ONE,
580- ConsistencyLevel.TWO,
581- ConsistencyLevel.QUORUM,
582- ConsistencyLevel.THREE,
583- ConsistencyLevel.ALL,
584- ConsistencyLevel.LOCAL_QUORUM,
585- ConsistencyLevel.EACH_QUORUM
586- );
587-
588- List<ConsistencyLevel> failList = Arrays.asList();
589-
590- // Test successful writes
591- for (ConsistencyLevel cl : acceptedList) {
592- logger.info("Test successful init(): " + cl);
593- try {
594- init(c, 12, cl);
595- } catch (Exception e) {
596- fail(String.format("Test failed at CL.%s with message: %s", cl, e.getMessage()));
597- }
556+ createMultiDCSchema(3, 3);
557+ init(12, ConsistencyLevel.TWO);
558+ query(12, ConsistencyLevel.TWO);
559+
560+ assertQueried(IP_PREFIX + '1', 0);
561+ assertQueried(IP_PREFIX + '2', 12);
562+ assertQueried(IP_PREFIX + '3', 0);
563+ assertQueried(IP_PREFIX + '4', 0);
564+ assertQueried(IP_PREFIX + '5', 0);
565+ assertQueried(IP_PREFIX + '6', 0);
566+
567+ resetCoordinators();
568+ stopAndWait(3);
569+
570+ List<ConsistencyLevel> acceptedList = Arrays.asList(
571+ ConsistencyLevel.ANY,
572+ ConsistencyLevel.ONE,
573+ ConsistencyLevel.TWO,
574+ ConsistencyLevel.QUORUM,
575+ ConsistencyLevel.THREE,
576+ ConsistencyLevel.ALL,
577+ ConsistencyLevel.LOCAL_QUORUM,
578+ ConsistencyLevel.EACH_QUORUM
579+ );
580+
581+ List<ConsistencyLevel> failList = emptyList();
582+
583+ // Test successful writes
584+ for (ConsistencyLevel cl : acceptedList) {
585+ logger.debug("Test successful init(): " + cl);
586+ try {
587+ init(12, cl);
588+ } catch (Exception e) {
589+ fail(String.format("Test failed at CL.%s with message: %s", cl, e.getMessage()));
598590 }
591+ }
599592
600- // Test successful reads
601- for (ConsistencyLevel cl : acceptedList) {
602- logger.info("Test successful query(): " + cl);
603- try {
604- query(c, 12, cl);
605- } catch (InvalidQueryException e) {
606- List<String> acceptableErrorMessages = Arrays.asList(
607- "EACH_QUORUM ConsistencyLevel is only supported for writes",
608- "ANY ConsistencyLevel is only supported for writes");
609- assertTrue(acceptableErrorMessages.contains(e.getMessage()), String.format("Received: %s", e.getMessage()));
610- }
593+ // Test successful reads
594+ for (ConsistencyLevel cl : acceptedList) {
595+ logger.debug("Test successful query(): " + cl);
596+ try {
597+ query(12, cl);
598+ } catch (InvalidQueryException e) {
599+ List<String> acceptableErrorMessages = Arrays.asList(
600+ "EACH_QUORUM ConsistencyLevel is only supported for writes",
601+ "ANY ConsistencyLevel is only supported for writes");
602+ assertTrue(acceptableErrorMessages.contains(e.getMessage()), String.format("Received: %s", e.getMessage()));
611603 }
604+ }
612605
613- // Test writes which should fail
614- for (ConsistencyLevel cl : failList) {
615- logger.info("Test failure init(): " + cl);
616- try {
617- init(c, 12, cl);
618- fail(String.format("Test passed at CL.%s.", cl));
619- } catch (UnavailableException e) {
620- // expected to fail when the client has already marked the
621- // node as DOWN
622- } catch (WriteTimeoutException e) {
623- // expected to fail when the client hasn't marked the
624- // node as DOWN yet
625- }
606+ // Test writes which should fail
607+ for (ConsistencyLevel cl : failList) {
608+ logger.debug("Test failure init(): " + cl);
609+ try {
610+ init(12, cl);
611+ fail(String.format("Test passed at CL.%s.", cl));
612+ } catch (UnavailableException e) {
613+ // expected to fail when the client has already marked the
614+ // node as DOWN
615+ } catch (WriteTimeoutException e) {
616+ // expected to fail when the client hasn't marked the
617+ // node as DOWN yet
626618 }
619+ }
627620
628- // Test reads which should fail
629- for (ConsistencyLevel cl : failList) {
630- logger.info("Test failure query(): " + cl);
631- try {
632- query(c, 12, cl);
633- fail(String.format("Test passed at CL.%s.", cl));
634- } catch (ReadTimeoutException e) {
635- // expected to fail when the client hasn't marked the
636- // node as DOWN yet
637- } catch (UnavailableException e) {
638- // expected to fail when the client has already marked the
639- // node as DOWN
640- }
621+ // Test reads which should fail
622+ for (ConsistencyLevel cl : failList) {
623+ logger.debug("Test failure query(): " + cl);
624+ try {
625+ query(12, cl);
626+ fail(String.format("Test passed at CL.%s.", cl));
627+ } catch (ReadTimeoutException e) {
628+ // expected to fail when the client hasn't marked the
629+ // node as DOWN yet
630+ } catch (UnavailableException e) {
631+ // expected to fail when the client has already marked the
632+ // node as DOWN
641633 }
642-
643- } catch (Throwable e) {
644- c.errorOut();
645- throw e;
646- } finally {
647- resetCoordinators();
648- c.discard();
649634 }
650635 }
651636
652637 @Test(groups = "long")
638+ @CCMConfig(
639+ numberOfNodes = {3, 3},
640+ clusterProvider = "tokenAwareDCAwareRoundRobinNoShuffleDowngrading"
641+ )
653642 public void testRFThreeDowngradingCLTwoDCsDCAware() throws Throwable {
654- Cluster.Builder builder = Cluster.builder()
655- .withLoadBalancingPolicy(new TokenAwarePolicy(DCAwareRoundRobinPolicy.builder().withLocalDc("dc2").build(), false))
656- .withRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE);
657- CCMBridge.CCMCluster c = CCMBridge.buildCluster(3, 3, builder);
658- try {
659-
660- createMultiDCSchema(c.session, 3, 3);
661- init(c, 12, ConsistencyLevel.TWO);
662- query(c, 12, ConsistencyLevel.TWO);
663-
664- assertQueried(CCMBridge.IP_PREFIX + '1', 0);
665- assertQueried(CCMBridge.IP_PREFIX + '2', 0);
666- assertQueried(CCMBridge.IP_PREFIX + '3', 0);
667- assertQueried(CCMBridge.IP_PREFIX + '4', 0);
668- assertQueried(CCMBridge.IP_PREFIX + '5', 12);
669- assertQueried(CCMBridge.IP_PREFIX + '6', 0);
670-
671- resetCoordinators();
672- c.cassandraCluster.stop(2);
673-
674- List<ConsistencyLevel> acceptedList = Arrays.asList(
675- ConsistencyLevel.ANY,
676- ConsistencyLevel.ONE,
677- ConsistencyLevel.TWO,
678- ConsistencyLevel.QUORUM,
679- ConsistencyLevel.THREE,
680- ConsistencyLevel.ALL,
681- ConsistencyLevel.LOCAL_QUORUM,
682- ConsistencyLevel.EACH_QUORUM
683- );
684-
685- List<ConsistencyLevel> failList = Arrays.asList();
686-
687- // Test successful writes
688- for (ConsistencyLevel cl : acceptedList) {
689- try {
690- init(c, 12, cl);
691- } catch (Exception e) {
692- fail(String.format("Test failed at CL.%s with message: %s", cl, e.getMessage()));
693- }
643+ createMultiDCSchema(3, 3);
644+ init(12, ConsistencyLevel.TWO);
645+ query(12, ConsistencyLevel.TWO);
646+
647+ assertQueried(IP_PREFIX + '1', 0);
648+ assertQueried(IP_PREFIX + '2', 0);
649+ assertQueried(IP_PREFIX + '3', 0);
650+ assertQueried(IP_PREFIX + '4', 0);
651+ assertQueried(IP_PREFIX + '5', 12);
652+ assertQueried(IP_PREFIX + '6', 0);
653+
654+ resetCoordinators();
655+ stopAndWait(2);
656+
657+ List<ConsistencyLevel> acceptedList = Arrays.asList(
658+ ConsistencyLevel.ANY,
659+ ConsistencyLevel.ONE,
660+ ConsistencyLevel.TWO,
661+ ConsistencyLevel.QUORUM,
662+ ConsistencyLevel.THREE,
663+ ConsistencyLevel.ALL,
664+ ConsistencyLevel.LOCAL_QUORUM,
665+ ConsistencyLevel.EACH_QUORUM
666+ );
667+
668+ List<ConsistencyLevel> failList = emptyList();
669+
670+ // Test successful writes
671+ for (ConsistencyLevel cl : acceptedList) {
672+ try {
673+ init(12, cl);
674+ } catch (Exception e) {
675+ fail(String.format("Test failed at CL.%s with message: %s", cl, e.getMessage()));
694676 }
677+ }
695678
696- // Test successful reads
697- for (ConsistencyLevel cl : acceptedList) {
698- try {
699- query(c, 12, cl);
700- } catch (InvalidQueryException e) {
701- List<String> acceptableErrorMessages = Arrays.asList(
702- "EACH_QUORUM ConsistencyLevel is only supported for writes",
703- "ANY ConsistencyLevel is only supported for writes");
704- assertTrue(acceptableErrorMessages.contains(e.getMessage()), String.format("Received: %s", e.getMessage()));
705- }
679+ // Test successful reads
680+ for (ConsistencyLevel cl : acceptedList) {
681+ try {
682+ query(12, cl);
683+ } catch (InvalidQueryException e) {
684+ List<String> acceptableErrorMessages = Arrays.asList(
685+ "EACH_QUORUM ConsistencyLevel is only supported for writes",
686+ "ANY ConsistencyLevel is only supported for writes");
687+ assertTrue(acceptableErrorMessages.contains(e.getMessage()), String.format("Received: %s", e.getMessage()));
706688 }
689+ }
707690
708- // Test writes which should fail
709- for (ConsistencyLevel cl : failList) {
710- try {
711- init(c, 12, cl);
712- fail(String.format("Test passed at CL.%s.", cl));
713- } catch (UnavailableException e) {
714- // expected to fail when the client has already marked the
715- // node as DOWN
716- } catch (WriteTimeoutException e) {
717- // expected to fail when the client hasn't marked the
718- // node as DOWN yet
719- }
691+ // Test writes which should fail
692+ for (ConsistencyLevel cl : failList) {
693+ try {
694+ init(12, cl);
695+ fail(String.format("Test passed at CL.%s.", cl));
696+ } catch (UnavailableException e) {
697+ // expected to fail when the client has already marked the
698+ // node as DOWN
699+ } catch (WriteTimeoutException e) {
700+ // expected to fail when the client hasn't marked the
701+ // node as DOWN yet
720702 }
703+ }
721704
722- // Test reads which should fail
723- for (ConsistencyLevel cl : failList) {
724- try {
725- query(c, 12, cl);
726- fail(String.format("Test passed at CL.%s.", cl));
727- } catch (ReadTimeoutException e) {
728- // expected to fail when the client hasn't marked the
729- // node as DOWN yet
730- } catch (UnavailableException e) {
731- // expected to fail when the client has already marked the
732- // node as DOWN
733- }
705+ // Test reads which should fail
706+ for (ConsistencyLevel cl : failList) {
707+ try {
708+ query(12, cl);
709+ fail(String.format("Test passed at CL.%s.", cl));
710+ } catch (ReadTimeoutException e) {
711+ // expected to fail when the client hasn't marked the
712+ // node as DOWN yet
713+ } catch (UnavailableException e) {
714+ // expected to fail when the client has already marked the
715+ // node as DOWN
734716 }
735- } catch (Throwable e) {
736- c.errorOut();
737- throw e;
738- } finally {
739- resetCoordinators();
740- c.discard();
741717 }
742718 }
719+
720+ private void stopAndWait(int node) {
721+ logger.debug("Stopping node " + node);
722+ ccm.stop(node);
723+ ccm.waitForDown(node);// this uses port ping
724+ TestUtils.waitForDown(ipOfNode(node), cluster, 10); // this uses UP/DOWN events
725+ logger.debug("Node " + node + " stopped, sleeping one extra minute to allow nodes to gossip");
726+ Uninterruptibles.sleepUninterruptibly(1, TimeUnit.MINUTES);
727+ }
728+
743729 }
modified driver-core/src/test/java/com/datastax/driver/core/ControlConnectionTest.java +64 −82
@@ -25,6 +25,7 @@
2525 import org.testng.annotations.Test;
2626
2727 import java.net.InetAddress;
28+import java.net.InetSocketAddress;
2829 import java.util.Collection;
2930 import java.util.Iterator;
3031 import java.util.Map;
@@ -32,18 +33,21 @@
3233 import java.util.concurrent.atomic.AtomicInteger;
3334
3435 import static com.datastax.driver.core.Assertions.assertThat;
36+import static com.datastax.driver.core.CreateCCM.TestMode.PER_METHOD;
3537 import static com.datastax.driver.core.TestUtils.nonDebouncingQueryOptions;
3638 import static com.datastax.driver.core.TestUtils.nonQuietClusterCloseOptions;
3739 import static com.google.common.collect.Lists.newArrayList;
3840
39-public class ControlConnectionTest {
41+@CreateCCM(PER_METHOD)
42+@CCMConfig(dirtiesContext = true, createCluster = false)
43+public class ControlConnectionTest extends CCMTestsSupport {
4044
4145 static final Logger logger = LoggerFactory.getLogger(ControlConnectionTest.class);
4246
4347 @Test(groups = "short")
48+ @CCMConfig(numberOfNodes = 2)
4449 public void should_prevent_simultaneous_reconnection_attempts() throws InterruptedException {
45- CCMBridge ccm = null;
46- Cluster cluster = null;
50+ Cluster cluster;
4751
4852 // Custom load balancing policy that counts the number of calls to newQueryPlan().
4953 // Since we don't open any session from our Cluster, only the control connection reattempts are calling this
@@ -55,31 +59,23 @@
5559 // only the first reconnection attempt of each reconnection handler.
5660 ReconnectionPolicy reconnectionPolicy = new ConstantReconnectionPolicy(60 * 1000);
5761
58- try {
59- ccm = CCMBridge.builder("test").withNodes(2).build();
60- // We pass only the first host as contact point, so we know the control connection will be on this host
61- cluster = Cluster.builder()
62- .addContactPoint(CCMBridge.ipOfNode(1))
63- .withReconnectionPolicy(reconnectionPolicy)
64- .withLoadBalancingPolicy(loadBalancingPolicy)
65- .build();
66- cluster.init();
67-
68- // Kill the control connection host, there should be exactly one reconnection attempt
69- ccm.stop(1);
70- TimeUnit.SECONDS.sleep(1); // Sleep for a while to make sure our final count is not the result of lucky timing
71- assertThat(reconnectionAttempts.get()).isEqualTo(1);
72-
73- ccm.stop(2);
74- TimeUnit.SECONDS.sleep(1);
75- assertThat(reconnectionAttempts.get()).isEqualTo(2);
76-
77- } finally {
78- if (cluster != null)
79- cluster.close();
80- if (ccm != null)
81- ccm.remove();
82- }
62+ // We pass only the first host as contact point, so we know the control connection will be on this host
63+ cluster = register(Cluster.builder()
64+ .addContactPointsWithPorts(getHostAddress(1))
65+ .withAddressTranslator(getAddressTranslator())
66+ .withReconnectionPolicy(reconnectionPolicy)
67+ .withLoadBalancingPolicy(loadBalancingPolicy)
68+ .build());
69+ cluster.init();
70+
71+ // Kill the control connection host, there should be exactly one reconnection attempt
72+ ccm.stop(1);
73+ TimeUnit.SECONDS.sleep(1); // Sleep for a while to make sure our final count is not the result of lucky timing
74+ assertThat(reconnectionAttempts.get()).isEqualTo(1);
75+
76+ ccm.stop(2);
77+ TimeUnit.SECONDS.sleep(1);
78+ assertThat(reconnectionAttempts.get()).isEqualTo(2);
8379 }
8480
8581 /**
@@ -91,30 +87,23 @@
9187 @Test(groups = "short")
9288 @CassandraVersion(major = 2.1)
9389 public void should_parse_UDT_definitions_when_using_default_protocol_version() {
94- CCMBridge ccm = null;
95- Cluster cluster = null;
96-
97- try {
98- ccm = CCMBridge.builder("test").build();
99-
100- // First driver instance: create UDT
101- cluster = Cluster.builder().addContactPoint(CCMBridge.ipOfNode(1)).build();
102- Session session = cluster.connect();
103- session.execute("create keyspace ks WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}");
104- session.execute("create type ks.foo (i int)");
105- cluster.close();
106-
107- // Second driver instance: read UDT definition
108- cluster = Cluster.builder().addContactPoint(CCMBridge.ipOfNode(1)).build();
109- UserType fooType = cluster.getMetadata().getKeyspace("ks").getUserType("foo");
110-
111- assertThat(fooType.getFieldNames()).containsExactly("i");
112- } finally {
113- if (cluster != null)
114- cluster.close();
115- if (ccm != null)
116- ccm.remove();
117- }
90+ Cluster cluster;
91+ InetSocketAddress firstHost = getHostAddress(1);
92+ // First driver instance: create UDT
93+ cluster = register(Cluster.builder()
94+ .addContactPointsWithPorts(firstHost)
95+ .withAddressTranslator(getAddressTranslator())
96+ .build());
97+ Session session = cluster.connect();
98+ session.execute("create keyspace ks WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}");
99+ session.execute("create type ks.foo (i int)");
100+ cluster.close();
101+
102+ // Second driver instance: read UDT definition
103+ cluster = register(Cluster.builder().addContactPointsWithPorts(firstHost).build());
104+ UserType fooType = cluster.getMetadata().getKeyspace("ks").getUserType("foo");
105+
106+ assertThat(fooType.getFieldNames()).containsExactly("i");
118107 }
119108
120109 /**
@@ -127,36 +116,27 @@
127116 * @since 2.0.9
128117 */
129118 @Test(groups = "long")
119+ @CCMConfig(numberOfNodes = 3)
130120 public void should_reestablish_if_control_node_decommissioned() throws InterruptedException {
131- CCMBridge ccm = null;
132- Cluster cluster = null;
121+ InetSocketAddress firstHost = getHostAddress(1);
122+ Cluster cluster = register(Cluster.builder()
123+ .addContactPointsWithPorts(firstHost)
124+ .withAddressTranslator(getAddressTranslator())
125+ .withQueryOptions(nonDebouncingQueryOptions())
126+ .build());
127+ cluster.init();
128+
129+ // Ensure the control connection host is that of the first node.
130+ InetAddress controlHost = cluster.manager.controlConnection.connectedHost().getAddress();
131+ assertThat(controlHost).isEqualTo(firstHost.getAddress());
133132
134- try {
135- ccm = CCMBridge.builder("test").withNodes(3).build();
136-
137- cluster = Cluster.builder()
138- .addContactPoint(CCMBridge.ipOfNode(1))
139- .withQueryOptions(nonDebouncingQueryOptions())
140- .build();
141- cluster.init();
142-
143- // Ensure the control connection host is that of the first node.
144- String controlHost = cluster.manager.controlConnection.connectedHost().getAddress().getHostAddress();
145- assertThat(controlHost).isEqualTo(CCMBridge.ipOfNode(1));
146-
147- // Decommission the node.
148- ccm.decommissionNode(1);
149-
150- // Ensure that the new control connection is not null and it's host is not equal to the decommissioned node.
151- Host newHost = cluster.manager.controlConnection.connectedHost();
152- assertThat(newHost).isNotNull();
153- assertThat(newHost.getAddress().getHostAddress()).isNotEqualTo(controlHost);
154- } finally {
155- if (cluster != null)
156- cluster.close();
157- if (ccm != null)
158- ccm.remove();
159- }
133+ // Decommission the node.
134+ ccm.decommissionNode(1);
135+
136+ // Ensure that the new control connection is not null and it's host is not equal to the decommissioned node.
137+ Host newHost = cluster.manager.controlConnection.connectedHost();
138+ assertThat(newHost).isNotNull();
139+ assertThat(newHost.getAddress()).isNotEqualTo(controlHost);
160140 }
161141
162142 /**
@@ -173,6 +153,7 @@
173153 * @since 2.0.11, 2.1.8, 2.2.0
174154 */
175155 @Test(groups = "short")
156+ @CCMConfig(createCcm = false)
176157 public void should_randomize_contact_points_when_determining_control_connection() {
177158 int hostCount = 5;
178159 int iterations = 100;
@@ -180,14 +161,15 @@
180161 scassandras.init();
181162
182163 try {
183- Collection<String> contactPoints = newArrayList();
164+ Collection<InetSocketAddress> contactPoints = newArrayList();
184165 for (int i = 1; i <= hostCount; i++) {
185166 contactPoints.add(scassandras.address(i));
186167 }
187168 final HashMultiset<InetAddress> occurrencesByHost = HashMultiset.create(hostCount);
188169 for (int i = 0; i < iterations; i++) {
189170 Cluster cluster = Cluster.builder()
190- .addContactPoints(contactPoints.toArray(new String[hostCount]))
171+ .addContactPointsWithPorts(contactPoints)
172+ .withAddressTranslator(scassandras.addressTranslator())
191173 .withNettyOptions(nonQuietClusterCloseOptions)
192174 .build();
193175
added driver-core/src/test/java/com/datastax/driver/core/CreateCCM.java +64 −0
@@ -0,0 +1,64 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core;
17+
18+import java.lang.annotation.Retention;
19+import java.lang.annotation.Target;
20+
21+import static java.lang.annotation.ElementType.TYPE;
22+import static java.lang.annotation.RetentionPolicy.RUNTIME;
23+
24+@Retention(RUNTIME)
25+@Target(TYPE)
26+public @interface CreateCCM {
27+
28+ enum TestMode {
29+
30+ /**
31+ * When this mode is selected, one single CCM cluster will
32+ * be shared for all tests in the test class.
33+ * <p/>
34+ * When this mode is selected, only class-level {@link CCMConfig} annotations
35+ * are processed; method-level annotations are ignored.
36+ * <p/>
37+ * This mode usually runs faster, but care should be taken
38+ * not to alter the CCM cluster in a test in such a way
39+ * that subsequent tests could fail.
40+ */
41+ PER_CLASS,
42+
43+ /**
44+ * When this mode is selected, a different CCM cluster
45+ * will be used for each test in the test class.
46+ * <p/>
47+ * When this mode is selected, both class-level and method-level {@link CCMConfig} annotations
48+ * are processed; the test configuration results from the merge of
49+ * both annotations, if both are present (method-level annotations
50+ * override class-level ones).
51+ * <p/>
52+ * This mode is slower, but is safer to use
53+ * if a test method alters the CCM cluster.
54+ */
55+ PER_METHOD
56+ }
57+
58+ /**
59+ * The test mode to use for tests in this class.
60+ *
61+ * @return The test mode to use for tests in this class.
62+ */
63+ TestMode value() default TestMode.PER_CLASS;
64+}
modified driver-core/src/test/java/com/datastax/driver/core/CustomPayloadTest.java +5 −4
@@ -19,7 +19,6 @@
1919 import com.datastax.driver.core.exceptions.UnsupportedFeatureException;
2020 import com.datastax.driver.core.utils.CassandraVersion;
2121 import com.google.common.base.Throwables;
22-import com.google.common.collect.ImmutableList;
2322 import com.google.common.collect.ImmutableMap;
2423 import org.apache.log4j.Logger;
2524 import org.assertj.core.api.iterable.Extractor;
@@ -40,7 +39,8 @@
4039 import static org.assertj.core.api.Fail.fail;
4140
4241 @CassandraVersion(major = 2.2)
43-public class CustomPayloadTest extends CCMBridge.PerClassSingleNodeCluster {
42+@CCMConfig(jvmArgs = "-Dcassandra.custom_query_handler_class=org.apache.cassandra.cql3.CustomPayloadMirroringQueryHandler")
43+public class CustomPayloadTest extends CCMTestsSupport {
4444
4545 private Map<String, ByteBuffer> payload1;
4646
@@ -240,7 +240,8 @@
240240 Session v3session = null;
241241 try {
242242 v3cluster = Cluster.builder()
243- .addContactPointsWithPorts(ImmutableList.of(hostAddress))
243+ .addContactPointsWithPorts(getInitialContactPoints())
244+ .withAddressTranslator(getAddressTranslator())
244245 .withProtocolVersion(V3)
245246 .build()
246247 .init();
@@ -296,7 +297,7 @@
296297 }
297298
298299 @Override
299- protected Collection<String> getTableDefinitions() {
300+ public Collection<String> createTestFixtures() {
300301 return Collections.singletonList("CREATE TABLE t1 (c1 int, c2 text, PRIMARY KEY (c1, c2))");
301302 }
302303
modified driver-core/src/test/java/com/datastax/driver/core/CustomTypeTest.java +2 −3
@@ -31,7 +31,7 @@
3131 /**
3232 * Test we "support" custom types.
3333 */
34-public class CustomTypeTest extends CCMBridge.PerClassSingleNodeCluster {
34+public class CustomTypeTest extends CCMTestsSupport {
3535
3636 public static final DataType CUSTOM_DYNAMIC_COMPOSITE = custom(
3737 "org.apache.cassandra.db.marshal.DynamicCompositeType("
@@ -44,7 +44,7 @@
4444 + "org.apache.cassandra.db.marshal.Int32Type)");
4545
4646 @Override
47- protected Collection<String> getTableDefinitions() {
47+ public Collection<String> createTestFixtures() {
4848 return Collections.singleton(
4949 "CREATE TABLE test ("
5050 + " k int,"
@@ -157,7 +157,6 @@
157157
158158
159159 private ByteBuffer serializeForDynamicCompositeType(Object... params) {
160-
161160 List<ByteBuffer> l = new ArrayList<ByteBuffer>();
162161 int size = 0;
163162 for (Object p : params) {
modified driver-core/src/test/java/com/datastax/driver/core/DataTypeCqlNameParserTest.java +2 −2
@@ -27,7 +27,7 @@
2727 import static com.datastax.driver.core.Metadata.quote;
2828
2929 @CassandraVersion(major = 3.0)
30-public class DataTypeCqlNameParserTest extends CCMBridge.PerClassSingleNodeCluster {
30+public class DataTypeCqlNameParserTest extends CCMTestsSupport {
3131
3232 @Test(groups = "short")
3333 public void should_parse_native_types() {
@@ -119,7 +119,7 @@
119119 }
120120
121121 @Override
122- protected Collection<String> getTableDefinitions() {
122+ public Collection<String> createTestFixtures() {
123123 return Lists.newArrayList(
124124 String.format("CREATE TYPE %s.\"A\" (f1 int)", keyspace),
125125 String.format("CREATE TYPE %s.\"Incr,edibly\"\" EvilTy<>><<><p\"\"e\" (a frozen<\"A\">)", keyspace)
modified driver-core/src/test/java/com/datastax/driver/core/DataTypeIntegrationTest.java +4 −15
@@ -19,7 +19,6 @@
1919 import com.google.common.collect.*;
2020 import org.slf4j.Logger;
2121 import org.slf4j.LoggerFactory;
22-import org.testng.annotations.AfterClass;
2322 import org.testng.annotations.Test;
2423
2524 import java.nio.ByteBuffer;
@@ -37,7 +36,8 @@
3736 * (protocol > v2 only) and a prepared statement.
3837 * This is repeated with a large number of datatypes.
3938 */
40-public class DataTypeIntegrationTest extends CCMBridge.PerClassSingleNodeCluster {
39+@CCMConfig(clusterProvider = "createClusterBuilderNoDebouncing")
40+public class DataTypeIntegrationTest extends CCMTestsSupport {
4141 private static final Logger logger = LoggerFactory.getLogger(DataTypeIntegrationTest.class);
4242
4343 List<TestTable> tables = allTables();
@@ -46,7 +46,7 @@
4646 enum StatementType {RAW_STRING, SIMPLE_WITH_PARAM, PREPARED}
4747
4848 @Override
49- protected Collection<String> getTableDefinitions() {
49+ public Collection<String> createTestFixtures() {
5050 Host host = cluster.getMetadata().getAllHosts().iterator().next();
5151 cassandraVersion = host.getCassandraVersion().nextStable();
5252
@@ -62,16 +62,6 @@
6262 return statements;
6363 }
6464
65- @AfterClass
66- @Override
67- public void afterClass() {
68- // drop tables one by one to avoid a timeout when issuing the DROP KEYSPACE statement
69- for (TestTable table : tables) {
70- session.execute("DROP TABLE " + table.tableName);
71- }
72- super.afterClass();
73- }
74-
7565 @Test(groups = "long")
7666 public void should_insert_and_retrieve_data_with_legacy_statements() {
7767 should_insert_and_retrieve_data(StatementType.RAW_STRING);
@@ -227,7 +217,6 @@
227217 // type maps to a java primitive type it's value will by the default value instead of null.
228218 for (DataType dataType : DataType.allPrimitiveTypes(TestUtils.getDesiredProtocolVersion())) {
229219 Object expectedPrimitiveValue = null;
230- Object expectedValue = null;
231220 switch (dataType.getName()) {
232221 case BIGINT:
233222 case TIME:
@@ -254,7 +243,7 @@
254243 }
255244
256245 if (!dataType.getName().equals(DataType.Name.COUNTER)) {
257- tables.add(new TestTable(dataType, null, expectedValue, expectedPrimitiveValue, "1.2.0"));
246+ tables.add(new TestTable(dataType, null, null, expectedPrimitiveValue, "1.2.0"));
258247 }
259248 }
260249 return tables;
modified driver-core/src/test/java/com/datastax/driver/core/EventDebouncerIntegrationTest.java +28 −36
@@ -22,11 +22,13 @@
2222 import java.util.concurrent.CyclicBarrier;
2323 import java.util.concurrent.TimeUnit;
2424
25-import static com.datastax.driver.core.CCMBridge.ipOfNode;
25+import static com.datastax.driver.core.CreateCCM.TestMode.PER_METHOD;
26+import static com.datastax.driver.core.TestUtils.ipOfNode;
2627 import static org.assertj.core.api.Assertions.assertThat;
2728 import static org.assertj.core.api.Fail.fail;
2829
29-public class EventDebouncerIntegrationTest {
30+@CreateCCM(PER_METHOD)
31+public class EventDebouncerIntegrationTest extends CCMTestsSupport {
3032
3133 /**
3234 * Tests that DOWN, UP, REMOVE or ADD events will not be delivered to
@@ -37,43 +39,33 @@
3739 * @jira_ticket JAVA-784
3840 * @since 2.0.11
3941 */
42+ @CCMConfig(numberOfNodes = 3, createCluster = false, dirtiesContext = true)
4043 @Test(groups = "long")
4144 public void should_wait_until_load_balancing_policy_is_fully_initialized() throws InterruptedException {
4245 TestLoadBalancingPolicy policy = new TestLoadBalancingPolicy();
43- CCMBridge ccm = CCMBridge.builder("main").withNodes(3).build();
44- final Cluster cluster = new Cluster.Builder()
45- .addContactPoints(ipOfNode(1))
46- .withLoadBalancingPolicy(policy)
47- .withQueryOptions(new QueryOptions()
48- .setRefreshNodeIntervalMillis(0)
49- .setRefreshNodeListIntervalMillis(0)
50- .setRefreshSchemaIntervalMillis(0)
51- ).build();
52- try {
53- new Thread() {
54- @Override
55- public void run() {
56- cluster.init();
57- }
58- }.start();
59- // stop cluster initialization in the middle of LBP initialization
60- policy.stop();
61- // generate a DOWN event - will not be delivered immediately
62- // because the debouncers are not started
63- // note: a graceful stop notify other nodes which send a topology change event to the driver right away
64- // while forceStop kills the node so other nodes take much more time to detect node failure
65- ccm.stop(3);
66- ccm.waitForDown(3);
67- // finish cluster initialization and deliver the DOWN event
68- policy.proceed();
69- assertThat(policy.onDownCalledBeforeInit).isFalse();
70- assertThat(policy.onDownCalled()).isTrue();
71- assertThat(policy.hosts).doesNotContain(TestUtils.findHost(cluster, 3));
72- } finally {
73- if (cluster != null)
74- cluster.close();
75- ccm.remove("main");
76- }
46+ final Cluster cluster = register(createClusterBuilderNoDebouncing()
47+ .addContactPointsWithPorts(getHostAddress(1))
48+ .withAddressTranslator(getAddressTranslator())
49+ .withLoadBalancingPolicy(policy).build());
50+ new Thread() {
51+ @Override
52+ public void run() {
53+ cluster.init();
54+ }
55+ }.start();
56+ // stop cluster initialization in the middle of LBP initialization
57+ policy.stop();
58+ // generate a DOWN event - will not be delivered immediately
59+ // because the debouncers are not started
60+ // note: a graceful stop notify other nodes which send a topology change event to the driver right away
61+ // while forceStop kills the node so other nodes take much more time to detect node failure
62+ ccm.stop(3);
63+ ccm.waitForDown(3);
64+ // finish cluster initialization and deliver the DOWN event
65+ policy.proceed();
66+ assertThat(policy.onDownCalledBeforeInit).isFalse();
67+ assertThat(policy.onDownCalled()).isTrue();
68+ assertThat(policy.hosts).doesNotContain(TestUtils.findHost(cluster, 3));
7769 }
7870
7971 private class TestLoadBalancingPolicy extends SortingLoadBalancingPolicy {
modified driver-core/src/test/java/com/datastax/driver/core/EventDebouncerTest.java +2 −2
@@ -190,7 +190,7 @@
190190 }
191191
192192 void awaitEvents(int expected) throws InterruptedException {
193- long nanos = SECONDS.toNanos(10);
193+ long nanos = SECONDS.toNanos(60);
194194 lock.lock();
195195 try {
196196 while (events.size() < expected) {
@@ -204,7 +204,7 @@
204204 }
205205
206206 void awaitInvocations(int expected) throws InterruptedException {
207- long nanos = SECONDS.toNanos(10);
207+ long nanos = SECONDS.toNanos(60);
208208 lock.lock();
209209 try {
210210 while (invocations.get() < expected) {
modified driver-core/src/test/java/com/datastax/driver/core/FetchingTest.java +4 −10
@@ -26,18 +26,16 @@
2626 /**
2727 * Test ResultSet paging correct behavior.
2828 */
29-public class FetchingTest extends CCMBridge.PerClassSingleNodeCluster {
29+public class FetchingTest extends CCMTestsSupport {
3030
3131 @Override
32- protected Collection<String> getTableDefinitions() {
32+ public Collection<String> createTestFixtures() {
3333 return Collections.singletonList("CREATE TABLE test (k text, v int, PRIMARY KEY (k, v))");
3434 }
3535
3636 @Test(groups = "short")
37- public void simplePagingTest() throws Throwable {
38-
37+ public void simplePagingTest() {
3938 try {
40-
4139 // Insert data
4240 String key = "paging_test";
4341 for (int i = 0; i < 100; i++)
@@ -61,11 +59,7 @@
6159
6260 } catch (UnsupportedFeatureException e) {
6361 // This is expected when testing the protocol v1
64- if (cluster.getConfiguration().getProtocolOptions().getProtocolVersion() != ProtocolVersion.V1)
65- throw e;
66- } catch (Throwable e) {
67- errorOut();
68- throw e;
62+ assertEquals(cluster.getConfiguration().getProtocolOptions().getProtocolVersion(), ProtocolVersion.V1);
6963 }
7064 }
7165 }
modified driver-core/src/test/java/com/datastax/driver/core/FunctionMetadataTest.java +3 −2
@@ -26,7 +26,8 @@
2626 import static org.assertj.core.api.Assertions.entry;
2727
2828 @CassandraVersion(major = 2.2)
29-public class FunctionMetadataTest extends CCMBridge.PerClassSingleNodeCluster {
29+@CCMConfig(config = "enable_user_defined_functions:true")
30+public class FunctionMetadataTest extends CCMTestsSupport {
3031
3132 @Test(groups = "short")
3233 public void should_parse_and_format_simple_function() {
@@ -126,7 +127,7 @@
126127 }
127128
128129 @Override
129- protected Collection<String> getTableDefinitions() {
130+ public Collection<String> createTestFixtures() {
130131 return newArrayList(
131132 String.format("CREATE TYPE IF NOT EXISTS %s.\"Phone\" (number text)", keyspace),
132133 String.format("CREATE TYPE IF NOT EXISTS %s.\"Address\" ("
modified driver-core/src/test/java/com/datastax/driver/core/GettableDataIntegrationTest.java +6 −6
@@ -34,10 +34,9 @@
3434 import static com.google.common.collect.Lists.newArrayList;
3535 import static org.assertj.core.api.Assertions.assertThat;
3636
37-public class GettableDataIntegrationTest extends CCMBridge.PerClassSingleNodeCluster {
37+public class GettableDataIntegrationTest extends CCMTestsSupport {
3838
39- boolean is21 = cassandraVersion.compareTo(VersionNumber.parse("2.1.3")) > 0;
40- boolean is20 = cassandraVersion.compareTo(VersionNumber.parse("2.0")) > 0;
39+ boolean is21;
4140
4241 CodecRegistry registry = new CodecRegistry();
4342
@@ -45,7 +44,8 @@
4544 AtomicInteger keyCounter = new AtomicInteger(0);
4645
4746 @Override
48- protected Collection<String> getTableDefinitions() {
47+ public Collection<String> createTestFixtures() {
48+ is21 = ccm.getVersion().compareTo(VersionNumber.parse("2.1.3")) > 0;
4949 // only add tuples / nested collections at > 2.1.3.
5050 return newArrayList("CREATE TABLE codec_mapping (k int PRIMARY KEY, "
5151 + "v int, l list<int>, m map<int,int>" +
@@ -53,8 +53,8 @@
5353 }
5454
5555 @Override
56- protected Cluster.Builder configure(Cluster.Builder builder) {
57- return super.configure(builder).withCodecRegistry(registry);
56+ public Cluster.Builder createClusterBuilder() {
57+ return Cluster.builder().withCodecRegistry(registry);
5858 }
5959
6060 @BeforeClass(groups = "short")
modified driver-core/src/test/java/com/datastax/driver/core/HeartbeatTest.java +64 −77
@@ -24,21 +24,24 @@
2424 import static com.datastax.driver.core.Assertions.assertThat;
2525 import static java.util.concurrent.TimeUnit.SECONDS;
2626
27-public class HeartbeatTest {
27+@CCMConfig(createCluster = false)
28+public class HeartbeatTest extends CCMTestsSupport {
2829
2930 Logger connectionLogger = Logger.getLogger(Connection.class);
3031 MemoryAppender logs;
32+ Level originalLevel;
3133
3234 @BeforeMethod(groups = "long")
3335 public void startCapturingLogs() {
36+ originalLevel = connectionLogger.getLevel();
3437 connectionLogger.setLevel(Level.DEBUG);
3538 logs = new MemoryAppender();
3639 connectionLogger.addAppender(logs);
3740 }
3841
39- @AfterMethod(groups = "long")
42+ @AfterMethod(groups = "long", alwaysRun = true)
4043 public void stopCapturingLogs() {
41- connectionLogger.setLevel(null);
44+ connectionLogger.setLevel(originalLevel);
4245 connectionLogger.removeAppender(logs);
4346 }
4447
@@ -53,55 +56,47 @@
5356 */
5457 @Test(groups = "long")
5558 public void should_send_heartbeat_when_connection_is_inactive() throws InterruptedException {
56- CCMBridge ccm = null;
57- Cluster cluster = null;
58- try {
59- ccm = CCMBridge.builder("test").withNodes(1).build();
60- cluster = Cluster.builder().addContactPoint(CCMBridge.ipOfNode(1))
61- .withPoolingOptions(new PoolingOptions()
62- .setHeartbeatIntervalSeconds(3))
63- .build();
64-
65- // Don't create any session, only the control connection will be established
66- cluster.init();
67-
68- for (int i = 0; i < 5; i++) {
69- triggerRequestOnControlConnection(cluster);
70- SECONDS.sleep(1);
71- }
72- assertThat(logs.getNext()).doesNotContain("sending heartbeat");
73-
74- // Ensure heartbeat is sent after no activity.
75- SECONDS.sleep(4);
76- assertThat(logs.getNext())
77- .contains("sending heartbeat")
78- .contains("heartbeat query succeeded");
79-
80- // Ensure heartbeat is sent after continued inactivity.
81- SECONDS.sleep(4);
82- assertThat(logs.getNext())
83- .contains("sending heartbeat")
84- .contains("heartbeat query succeeded");
85-
86- // Ensure heartbeat is not sent after activity.
87- logs.getNext();
88- for (int i = 0; i < 5; i++) {
89- triggerRequestOnControlConnection(cluster);
90- SECONDS.sleep(1);
91- }
92- assertThat(logs.getNext()).doesNotContain("sending heartbeat");
93-
94- // Finally, ensure heartbeat is sent after inactivity.
95- SECONDS.sleep(4);
96- assertThat(logs.getNext())
97- .contains("sending heartbeat")
98- .contains("heartbeat query succeeded");
99- } finally {
100- if (cluster != null)
101- cluster.close();
102- if (ccm != null)
103- ccm.remove();
59+ Cluster cluster = register(Cluster.builder()
60+ .addContactPointsWithPorts(getHostAddress(1))
61+ .withAddressTranslator(getAddressTranslator())
62+ .withPoolingOptions(new PoolingOptions()
63+ .setHeartbeatIntervalSeconds(3))
64+ .build());
65+
66+ // Don't create any session, only the control connection will be established
67+ cluster.init();
68+
69+ for (int i = 0; i < 5; i++) {
70+ triggerRequestOnControlConnection(cluster);
71+ SECONDS.sleep(1);
10472 }
73+ assertThat(logs.getNext()).doesNotContain("sending heartbeat");
74+
75+ // Ensure heartbeat is sent after no activity.
76+ SECONDS.sleep(4);
77+ assertThat(logs.getNext())
78+ .contains("sending heartbeat")
79+ .contains("heartbeat query succeeded");
80+
81+ // Ensure heartbeat is sent after continued inactivity.
82+ SECONDS.sleep(4);
83+ assertThat(logs.getNext())
84+ .contains("sending heartbeat")
85+ .contains("heartbeat query succeeded");
86+
87+ // Ensure heartbeat is not sent after activity.
88+ logs.getNext();
89+ for (int i = 0; i < 5; i++) {
90+ triggerRequestOnControlConnection(cluster);
91+ SECONDS.sleep(1);
92+ }
93+ assertThat(logs.getNext()).doesNotContain("sending heartbeat");
94+
95+ // Finally, ensure heartbeat is sent after inactivity.
96+ SECONDS.sleep(4);
97+ assertThat(logs.getNext())
98+ .contains("sending heartbeat")
99+ .contains("heartbeat query succeeded");
105100 }
106101
107102 /**
@@ -117,33 +112,25 @@
117112 */
118113 @Test(groups = "long")
119114 public void should_not_send_heartbeat_when_disabled() throws InterruptedException {
120- CCMBridge ccm = null;
121- Cluster cluster = null;
122- try {
123- ccm = CCMBridge.builder("test").withNodes(1).build();
124- cluster = Cluster.builder().addContactPoint(CCMBridge.ipOfNode(1))
125- .withPoolingOptions(new PoolingOptions()
126- .setHeartbeatIntervalSeconds(0))
127- .build();
128-
129- // Don't create any session, only the control connection will be established
130- cluster.init();
131-
132- for (int i = 0; i < 5; i++) {
133- triggerRequestOnControlConnection(cluster);
134- SECONDS.sleep(1);
135- }
136- assertThat(logs.get()).doesNotContain("sending heartbeat");
137-
138- // Sleep for a while and ensure no heartbeat is sent.
139- SECONDS.sleep(32);
140- assertThat(logs.get()).doesNotContain("sending heartbeat");
141- } finally {
142- if (cluster != null)
143- cluster.close();
144- if (ccm != null)
145- ccm.remove();
115+ Cluster cluster = register(Cluster.builder()
116+ .addContactPointsWithPorts(getHostAddress(1))
117+ .withAddressTranslator(getAddressTranslator())
118+ .withPoolingOptions(new PoolingOptions()
119+ .setHeartbeatIntervalSeconds(0))
120+ .build());
121+
122+ // Don't create any session, only the control connection will be established
123+ cluster.init();
124+
125+ for (int i = 0; i < 5; i++) {
126+ triggerRequestOnControlConnection(cluster);
127+ SECONDS.sleep(1);
146128 }
129+ assertThat(logs.get()).doesNotContain("sending heartbeat");
130+
131+ // Sleep for a while and ensure no heartbeat is sent.
132+ SECONDS.sleep(32);
133+ assertThat(logs.get()).doesNotContain("sending heartbeat");
147134 }
148135
149136 // Simulates activity on the control connection via the internal API
modified driver-core/src/test/java/com/datastax/driver/core/HostConnectionPoolMultiTest.java +3 −2
@@ -41,7 +41,7 @@
4141 scassandra.init();
4242 }
4343
44- @AfterMethod(groups = {"short", "long"})
44+ @AfterMethod(groups = {"short", "long"}, alwaysRun = true)
4545 private void tearDown() {
4646 if (cluster != null) {
4747 cluster.close();
@@ -53,7 +53,8 @@
5353 PoolingOptions poolingOptions = new PoolingOptions().setConnectionsPerHost(LOCAL, core, max);
5454 SocketOptions socketOptions = new SocketOptions().setReadTimeoutMillis(1000);
5555 cluster = Cluster.builder()
56- .addContactPoint(CCMBridge.ipOfNode(1))
56+ .addContactPointsWithPorts(scassandra.address(1))
57+ .withAddressTranslator(scassandra.addressTranslator())
5758 .withQueryOptions(nonDebouncingQueryOptions())
5859 .withPoolingOptions(poolingOptions)
5960 .withSocketOptions(socketOptions)
modified driver-core/src/test/java/com/datastax/driver/core/HostConnectionPoolTest.java +54 −5
@@ -19,7 +19,7 @@
1919 import com.datastax.driver.core.exceptions.BusyConnectionException;
2020 import com.datastax.driver.core.exceptions.ConnectionException;
2121 import com.datastax.driver.core.policies.ConstantReconnectionPolicy;
22-import com.google.common.util.concurrent.Uninterruptibles;
22+import com.google.common.util.concurrent.*;
2323 import org.scassandra.cql.PrimitiveType;
2424 import org.scassandra.http.client.PrimingRequest;
2525 import org.testng.annotations.BeforeClass;
@@ -43,7 +43,6 @@
4343
4444 public class HostConnectionPoolTest extends ScassandraTestBase.PerClassCluster {
4545
46-
4746 @BeforeClass(groups = {"short", "long"})
4847 public void reinitializeCluster() {
4948 // Don't use the provided cluster, each test will create its own instead.
@@ -575,6 +574,9 @@
575574 Connection.Factory factory = spy(cluster.manager.connectionFactory);
576575 cluster.manager.connectionFactory = factory;
577576
577+ TestExecutorService blockingExecutor = new TestExecutorService(cluster.manager.blockingExecutor);
578+ cluster.manager.blockingExecutor = blockingExecutor;
579+
578580 HostConnectionPool pool = createPool(cluster, 3, 3);
579581 Connection core0 = pool.connections.get(0);
580582 Connection core1 = pool.connections.get(1);
@@ -603,12 +605,14 @@
603605 Uninterruptibles.sleepUninterruptibly(reconnectInterval, TimeUnit.MILLISECONDS);
604606
605607 // Attempt to borrow connection, this should trigger ensureCoreConnections thus spawning a new connection.
608+ blockingExecutor.reset();
606609 request = MockRequest.send(pool);
607610 requests.add(request);
608611 assertThat(request.connection).isEqualTo(core1);
609612
610613 // Should have tried to open up to core connections as result of borrowing a connection past reconnect time and not being at core.
611- verify(factory, timeout(reconnectInterval).times(1)).open(any(HostConnectionPool.class));
614+ blockingExecutor.blockUntilNextTaskCompleted();
615+ verify(factory).open(any(HostConnectionPool.class));
612616 reset(factory);
613617
614618 // Sleep for reconnect interval to allow reconnection time to elapse.
@@ -620,13 +624,17 @@
620624 Uninterruptibles.sleepUninterruptibly(reconnectInterval, TimeUnit.MILLISECONDS);
621625
622626 // Try to borrow a connection, the pool should grow.
627+ blockingExecutor.reset();
623628 requests.add(MockRequest.send(pool));
624- verify(factory, timeout((reconnectInterval + readTimeout) * 2).times(1)).open(any(HostConnectionPool.class));
629+ blockingExecutor.blockUntilNextTaskCompleted();
630+ verify(factory).open(any(HostConnectionPool.class));
625631 reset(factory);
626632
627633 // Another core connection should be opened as result of another request to get us up to core connections.
634+ blockingExecutor.reset();
628635 requests.add(MockRequest.send(pool));
629- verify(factory, timeout((reconnectInterval + readTimeout) * 2).times(1)).open(any(HostConnectionPool.class));
636+ blockingExecutor.blockUntilNextTaskCompleted();
637+ verify(factory).open(any(HostConnectionPool.class));
630638 reset(factory);
631639
632640 // Sending another request should not grow the pool any more, since we are now at core connections.
@@ -1104,4 +1112,45 @@
11041112 return 0; // value not important for this test class
11051113 }
11061114 }
1115+
1116+ static class TestExecutorService extends ForwardingListeningExecutorService {
1117+
1118+ private final ListeningExecutorService delegate;
1119+
1120+ private final Semaphore semaphore = new Semaphore(0);
1121+
1122+ TestExecutorService(ListeningExecutorService delegate) {
1123+ this.delegate = delegate;
1124+ }
1125+
1126+ @Override
1127+ protected ListeningExecutorService delegate() {
1128+ return delegate;
1129+ }
1130+
1131+ public void reset() {
1132+ semaphore.drainPermits();
1133+ }
1134+
1135+ public void blockUntilNextTaskCompleted() throws InterruptedException {
1136+ semaphore.tryAcquire(1, 1, TimeUnit.MINUTES);
1137+ }
1138+
1139+ @Override
1140+ public ListenableFuture<?> submit(Runnable task) {
1141+ ListenableFuture<?> future = super.submit(task);
1142+ Futures.addCallback(future, new FutureCallback<Object>() {
1143+ @Override
1144+ public void onSuccess(Object result) {
1145+ semaphore.release(1);
1146+ }
1147+
1148+ @Override
1149+ public void onFailure(Throwable t) {
1150+ semaphore.release(1);
1151+ }
1152+ });
1153+ return future;
1154+ }
1155+ }
11071156 }
modified driver-core/src/test/java/com/datastax/driver/core/IndexMetadataTest.java +24 −31
@@ -21,7 +21,6 @@
2121 import com.google.common.collect.ImmutableList;
2222 import com.google.common.collect.ImmutableMap;
2323 import com.google.common.primitives.Ints;
24-import org.testng.annotations.BeforeClass;
2524 import org.testng.annotations.Test;
2625
2726 import java.nio.ByteBuffer;
@@ -35,7 +34,7 @@
3534 import static com.datastax.driver.core.IndexMetadata.Kind.*;
3635
3736 @CassandraVersion(major = 1.2)
38-public class IndexMetadataTest extends CCMBridge.PerClassSingleNodeCluster {
37+public class IndexMetadataTest extends CCMTestsSupport {
3938
4039 /**
4140 * Column definitions for schema_columns table (legacy pre-3.0 layout).
@@ -64,34 +63,28 @@
6463 private ProtocolVersion protocolVersion;
6564
6665 @Override
67- @BeforeClass(groups = {"short", "long"})
68- public void beforeClass() {
69- super.beforeClass();
66+ public Collection<String> createTestFixtures() {
7067 protocolVersion = cluster.getConfiguration().getProtocolOptions().getProtocolVersion();
71- }
72-
73- @Override
74- protected Collection<String> getTableDefinitions() {
7568 ImmutableList.Builder<String> builder = ImmutableList.builder();
7669 builder.add("CREATE TABLE indexing ("
77- + "id int,"
78- + "id2 int,"
79- + "map_values map<text, int>,"
80- + "map_keys map<text, int>,"
81- + "map_entries map<text, int>,"
82- + "map_all map<text, int>,"
83- + "text_column text, "
84- + "\"MixedCaseColumn\" list<text>,"
85- +
86- // Frozen collections was introduced only in C* 2.1.3
87- (cassandraVersion.compareTo(VersionNumber.parse("2.1.3")) >= 0
88- ?
89- ", map_full frozen<map<text, int>>,"
90- + "set_full frozen<set<text>>,"
91- + "list_full frozen<list<text>>,"
92- :
93- "")
94- + "PRIMARY KEY (id, id2));"
70+ + "id int,"
71+ + "id2 int,"
72+ + "map_values map<text, int>,"
73+ + "map_keys map<text, int>,"
74+ + "map_entries map<text, int>,"
75+ + "map_all map<text, int>,"
76+ + "text_column text, "
77+ + "\"MixedCaseColumn\" list<text>,"
78+ +
79+ // Frozen collections was introduced only in C* 2.1.3
80+ (ccm.getVersion().compareTo(VersionNumber.parse("2.1.3")) >= 0
81+ ?
82+ ", map_full frozen<map<text, int>>,"
83+ + "set_full frozen<set<text>>,"
84+ + "list_full frozen<list<text>>,"
85+ :
86+ "")
87+ + "PRIMARY KEY (id, id2));"
9588 );
9689
9790 return builder.build();
@@ -117,7 +110,7 @@
117110 @CassandraVersion(major = 2.1, description = "index names with quoted identifiers and collection indexes not supported until 2.1")
118111 public void should_create_metadata_for_values_index_on_mixed_case_column() {
119112 // 3.0 assumes the 'values' keyword if index on a collection
120- String createValuesIndex = cassandraVersion.getMajor() > 2 ?
113+ String createValuesIndex = ccm.getVersion().getMajor() > 2 ?
121114 String.format("CREATE INDEX \"MixedCaseIndex\" ON %s.indexing (values(\"MixedCaseColumn\"));", keyspace) :
122115 String.format("CREATE INDEX \"MixedCaseIndex\" ON %s.indexing (\"MixedCaseColumn\");", keyspace);
123116 session.execute(createValuesIndex);
@@ -127,7 +120,7 @@
127120 .hasName("MixedCaseIndex")
128121 .hasParent((TableMetadata) column.getParent())
129122 .isNotCustomIndex()
130- .hasTarget(cassandraVersion.getMajor() > 2 ? "values(\"MixedCaseColumn\")" : "\"MixedCaseColumn\"")
123+ .hasTarget(ccm.getVersion().getMajor() > 2 ? "values(\"MixedCaseColumn\")" : "\"MixedCaseColumn\"")
131124 .hasKind(COMPOSITES)
132125 .asCqlQuery(createValuesIndex);
133126 assertThat((TableMetadata) column.getParent()).hasIndex(index);
@@ -137,7 +130,7 @@
137130 @CassandraVersion(major = 2.1)
138131 public void should_create_metadata_for_index_on_map_values() {
139132 // 3.0 assumes the 'values' keyword if index on a collection
140- String createValuesIndex = cassandraVersion.getMajor() > 2 ?
133+ String createValuesIndex = ccm.getVersion().getMajor() > 2 ?
141134 String.format("CREATE INDEX map_values_index ON %s.indexing (values(map_values));", keyspace) :
142135 String.format("CREATE INDEX map_values_index ON %s.indexing (map_values);", keyspace);
143136 session.execute(createValuesIndex);
@@ -147,7 +140,7 @@
147140 .hasName("map_values_index")
148141 .hasParent((TableMetadata) column.getParent())
149142 .isNotCustomIndex()
150- .hasTarget(cassandraVersion.getMajor() > 2 ? "values(map_values)" : "map_values")
143+ .hasTarget(ccm.getVersion().getMajor() > 2 ? "values(map_values)" : "map_values")
151144 .hasKind(COMPOSITES)
152145 .asCqlQuery(createValuesIndex);
153146 assertThat((TableMetadata) column.getParent()).hasIndex(index);
modified driver-core/src/test/java/com/datastax/driver/core/LargeDataTest.java +65 −130
@@ -22,6 +22,7 @@
2222
2323 import java.nio.ByteBuffer;
2424
25+import static com.datastax.driver.core.CreateCCM.TestMode.PER_METHOD;
2526 import static com.datastax.driver.core.TestUtils.CREATE_KEYSPACE_SIMPLE_FORMAT;
2627 import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
2728 import static org.testng.Assert.assertEquals;
@@ -30,7 +31,8 @@
3031 /**
3132 * Test limitations when using large amounts of data with the driver
3233 */
33-public class LargeDataTest {
34+@CreateCCM(PER_METHOD)
35+public class LargeDataTest extends CCMTestsSupport {
3436
3537 /*
3638 * Test a wide row of size 1,000,000
@@ -38,14 +40,14 @@
3840 * @param key The key value that will receive the data
3941 * @throws Throwable
4042 */
41- private void testWideRows(CCMBridge.CCMCluster c, int key) throws Throwable {
43+ private void testWideRows(int key) throws Throwable {
4244 // Write data
4345 for (int i = 0; i < 1000000; ++i) {
44- c.session.execute(insertInto("wide_rows").value("k", key).value("i", i).setConsistencyLevel(ConsistencyLevel.QUORUM));
46+ session.execute(insertInto("wide_rows").value("k", key).value("i", i).setConsistencyLevel(ConsistencyLevel.QUORUM));
4547 }
4648
4749 // Read data
48- ResultSet rs = c.session.execute(select("i").from("wide_rows").where(eq("k", key)));
50+ ResultSet rs = session.execute(select("i").from("wide_rows").where(eq("k", key)));
4951
5052 // Verify data
5153 int i = 0;
@@ -60,16 +62,16 @@
6062 * @param key The key value that will receive the data
6163 * @throws Throwable
6264 */
63- private void testWideBatchRows(CCMBridge.CCMCluster c, int key) throws Throwable {
65+ private void testWideBatchRows(int key) throws Throwable {
6466 // Write data
6567 Batch q = batch();
6668 for (int i = 0; i < 4000; ++i) {
6769 q = q.add(insertInto("wide_batch_rows").value("k", key).value("i", i));
6870 }
69- c.session.execute(q.setConsistencyLevel(ConsistencyLevel.QUORUM));
71+ session.execute(q.setConsistencyLevel(ConsistencyLevel.QUORUM));
7072
7173 // Read data
72- ResultSet rs = c.session.execute(select("i").from("wide_batch_rows").where(eq("k", key)));
74+ ResultSet rs = session.execute(select("i").from("wide_batch_rows").where(eq("k", key)));
7375
7476 // Verify data
7577 int i = 0;
@@ -84,7 +86,7 @@
8486 * @param key The key value that will receive the data
8587 * @throws Throwable
8688 */
87- private void testByteRows(CCMBridge.CCMCluster c, int key) throws Throwable {
89+ private void testByteRows(int key) throws Throwable {
8890 // Build small ByteBuffer sample
8991 ByteBuffer bb = ByteBuffer.allocate(58);
9092 bb.putShort((short) 0xCAFE);
@@ -92,11 +94,11 @@
9294
9395 // Write data
9496 for (int i = 0; i < 1000000; ++i) {
95- c.session.execute(insertInto("wide_byte_rows").value("k", key).value("i", bb).setConsistencyLevel(ConsistencyLevel.QUORUM));
97+ session.execute(insertInto("wide_byte_rows").value("k", key).value("i", bb).setConsistencyLevel(ConsistencyLevel.QUORUM));
9698 }
9799
98100 // Read data
99- ResultSet rs = c.session.execute(select("i").from("wide_byte_rows").where(eq("k", key)));
101+ ResultSet rs = session.execute(select("i").from("wide_byte_rows").where(eq("k", key)));
100102
101103 // Verify data
102104 for (Row row : rs) {
@@ -110,17 +112,17 @@
110112 * @param key The key value that will receive the data
111113 * @throws Throwable
112114 */
113- private void testLargeText(CCMBridge.CCMCluster c, int key) throws Throwable {
115+ private void testLargeText(int key) throws Throwable {
114116 // Write data
115117 StringBuilder b = new StringBuilder();
116118 for (int i = 0; i < 1000000; ++i) {
117119 // Create ultra-long text
118120 b.append(i);
119121 }
120- c.session.execute(insertInto("large_text").value("k", key).value("txt", b.toString()).setConsistencyLevel(ConsistencyLevel.QUORUM));
122+ session.execute(insertInto("large_text").value("k", key).value("txt", b.toString()).setConsistencyLevel(ConsistencyLevel.QUORUM));
121123
122124 // Read data
123- Row row = c.session.execute(select().all().from("large_text").where(eq("k", key))).one();
125+ Row row = session.execute(select().all().from("large_text").where(eq("k", key))).one();
124126
125127 // Verify data
126128 assertTrue(b.toString().equals(row.getString("txt")));
@@ -158,16 +160,16 @@
158160 * @param key The key value that will receive the data
159161 * @throws Throwable
160162 */
161- private void testWideTable(CCMBridge.CCMCluster c, int key) throws Throwable {
163+ private void testWideTable(int key) throws Throwable {
162164 // Write data
163165 Insert insertStatement = insertInto("wide_table").value("k", key);
164166 for (int i = 0; i < 330; ++i) {
165167 insertStatement = insertStatement.value(createColumnName(i), i);
166168 }
167- c.session.execute(insertStatement.setConsistencyLevel(ConsistencyLevel.QUORUM));
169+ session.execute(insertStatement.setConsistencyLevel(ConsistencyLevel.QUORUM));
168170
169171 // Read data
170- Row row = c.session.execute(select().all().from("wide_table").where(eq("k", key))).one();
172+ Row row = session.execute(select().all().from("wide_table").where(eq("k", key))).one();
171173
172174 // Verify data
173175 for (int i = 0; i < 330; ++i) {
@@ -184,21 +186,10 @@
184186 @Test(groups = "stress")
185187 @CassandraVersion(major = 2.0, minor = 0, description = "< 2.0 is skipped as 1.2 does not handle reading wide rows well.")
186188 public void wideRows() throws Throwable {
187- Cluster.Builder builder = Cluster.builder();
188- CCMBridge.CCMCluster c = CCMBridge.buildCluster(1, builder);
189-
190- c.session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, "large_data", 1));
191- c.session.execute("USE large_data");
192- c.session.execute(String.format("CREATE TABLE %s (k INT, i INT, PRIMARY KEY(k, i))", "wide_rows"));
193-
194- try {
195- testWideRows(c, 0);
196- } catch (Throwable e) {
197- c.errorOut();
198- throw e;
199- } finally {
200- c.discard();
201- }
189+ session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, "large_data", 1));
190+ session.execute("USE large_data");
191+ session.execute(String.format("CREATE TABLE %s (k INT, i INT, PRIMARY KEY(k, i))", "wide_rows"));
192+ testWideRows(0);
202193 }
203194
204195 /**
@@ -209,21 +200,10 @@
209200 @Test(groups = "stress")
210201 @CassandraVersion(major = 2.0, minor = 0, description = "< 2.0 is skipped as 1.2 does not handle large batches well.")
211202 public void wideBatchRows() throws Throwable {
212- Cluster.Builder builder = Cluster.builder();
213- CCMBridge.CCMCluster c = CCMBridge.buildCluster(1, builder);
214-
215- c.session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, "large_data", 1));
216- c.session.execute("USE large_data");
217- c.session.execute(String.format("CREATE TABLE %s (k INT, i INT, PRIMARY KEY(k, i))", "wide_batch_rows"));
218-
219- try {
220- testWideBatchRows(c, 0);
221- } catch (Throwable e) {
222- c.errorOut();
223- throw e;
224- } finally {
225- c.discard();
226- }
203+ session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, "large_data", 1));
204+ session.execute("USE large_data");
205+ session.execute(String.format("CREATE TABLE %s (k INT, i INT, PRIMARY KEY(k, i))", "wide_batch_rows"));
206+ testWideBatchRows(0);
227207 }
228208
229209 /**
@@ -233,21 +213,10 @@
233213 */
234214 @Test(groups = "stress")
235215 public void wideByteRows() throws Throwable {
236- Cluster.Builder builder = Cluster.builder();
237- CCMBridge.CCMCluster c = CCMBridge.buildCluster(1, builder);
238-
239- c.session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, "large_data", 1));
240- c.session.execute("USE large_data");
241- c.session.execute(String.format("CREATE TABLE %s (k INT, i BLOB, PRIMARY KEY(k, i))", "wide_byte_rows"));
242-
243- try {
244- testByteRows(c, 0);
245- } catch (Throwable e) {
246- c.errorOut();
247- throw e;
248- } finally {
249- c.discard();
250- }
216+ session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, "large_data", 1));
217+ session.execute("USE large_data");
218+ session.execute(String.format("CREATE TABLE %s (k INT, i BLOB, PRIMARY KEY(k, i))", "wide_byte_rows"));
219+ testByteRows(0);
251220 }
252221
253222 /**
@@ -257,21 +226,10 @@
257226 */
258227 @Test(groups = "stress")
259228 public void largeText() throws Throwable {
260- Cluster.Builder builder = Cluster.builder();
261- CCMBridge.CCMCluster c = CCMBridge.buildCluster(1, builder);
262-
263- c.session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, "large_data", 1));
264- c.session.execute("USE large_data");
265- c.session.execute(String.format("CREATE TABLE %s (k int PRIMARY KEY, txt text)", "large_text"));
266-
267- try {
268- testLargeText(c, 0);
269- } catch (Throwable e) {
270- c.errorOut();
271- throw e;
272- } finally {
273- c.discard();
274- }
229+ session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, "large_data", 1));
230+ session.execute("USE large_data");
231+ session.execute(String.format("CREATE TABLE %s (k int PRIMARY KEY, txt text)", "large_text"));
232+ testLargeText(0);
275233 }
276234
277235 /**
@@ -281,12 +239,8 @@
281239 */
282240 @Test(groups = "stress")
283241 public void wideTable() throws Throwable {
284- Cluster.Builder builder = Cluster.builder();
285- CCMBridge.CCMCluster c = CCMBridge.buildCluster(1, builder);
286-
287- c.session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, "large_data", 1));
288- c.session.execute("USE large_data");
289-
242+ session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, "large_data", 1));
243+ session.execute("USE large_data");
290244 // Create the extra wide table definition
291245 StringBuilder tableDeclaration = new StringBuilder();
292246 tableDeclaration.append("CREATE TABLE wide_table (");
@@ -295,16 +249,8 @@
295249 tableDeclaration.append(String.format(", %s INT", createColumnName(i)));
296250 }
297251 tableDeclaration.append(')');
298- c.session.execute(tableDeclaration.toString());
299-
300- try {
301- testWideTable(c, 0);
302- } catch (Throwable e) {
303- c.errorOut();
304- throw e;
305- } finally {
306- c.discard();
307- }
252+ session.execute(tableDeclaration.toString());
253+ testWideTable(0);
308254 }
309255
310256 /**
@@ -313,17 +259,14 @@
313259 * @throws Throwable
314260 */
315261 @Test(groups = "duration")
262+ @CCMConfig(numberOfNodes = 3)
316263 public void mixedDurationTest() throws Throwable {
317- Cluster.Builder builder = Cluster.builder();
318- CCMBridge.CCMCluster c = CCMBridge.buildCluster(3, builder);
319-
320- c.session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, "large_data", 3));
321- c.session.execute("USE large_data");
322- c.session.execute(String.format("CREATE TABLE %s (k INT, i INT, PRIMARY KEY(k, i))", "wide_rows"));
323- c.session.execute(String.format("CREATE TABLE %s (k INT, i INT, PRIMARY KEY(k, i))", "wide_batch_rows"));
324- c.session.execute(String.format("CREATE TABLE %s (k INT, i BLOB, PRIMARY KEY(k, i))", "wide_byte_rows"));
325- c.session.execute(String.format("CREATE TABLE %s (k int PRIMARY KEY, txt text)", "large_text"));
326-
264+ session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, "large_data", 3));
265+ session.execute("USE large_data");
266+ session.execute(String.format("CREATE TABLE %s (k INT, i INT, PRIMARY KEY(k, i))", "wide_rows"));
267+ session.execute(String.format("CREATE TABLE %s (k INT, i INT, PRIMARY KEY(k, i))", "wide_batch_rows"));
268+ session.execute(String.format("CREATE TABLE %s (k INT, i BLOB, PRIMARY KEY(k, i))", "wide_byte_rows"));
269+ session.execute(String.format("CREATE TABLE %s (k int PRIMARY KEY, txt text)", "large_text"));
327270 // Create the extra wide table definition
328271 StringBuilder tableDeclaration = new StringBuilder();
329272 tableDeclaration.append("CREATE TABLE wide_table (");
@@ -332,35 +275,27 @@
332275 tableDeclaration.append(String.format(", %s INT", createColumnName(i)));
333276 }
334277 tableDeclaration.append(')');
335- c.session.execute(tableDeclaration.toString());
336-
337- try {
338- for (int i = 0; i < 10; ++i) {
339- switch ((int) (Math.random() * 5)) {
340- case 0:
341- testWideRows(c, 0);
342- break;
343- case 1:
344- testWideBatchRows(c, 0);
345- break;
346- case 2:
347- testByteRows(c, 0);
348- break;
349- case 3:
350- testLargeText(c, 0);
351- break;
352- case 4:
353- testWideTable(c, 0);
354- break;
355- default:
356- break;
357- }
278+ session.execute(tableDeclaration.toString());
279+ for (int i = 0; i < 10; ++i) {
280+ switch ((int) (Math.random() * 5)) {
281+ case 0:
282+ testWideRows(0);
283+ break;
284+ case 1:
285+ testWideBatchRows(0);
286+ break;
287+ case 2:
288+ testByteRows(0);
289+ break;
290+ case 3:
291+ testLargeText(0);
292+ break;
293+ case 4:
294+ testWideTable(0);
295+ break;
296+ default:
297+ break;
358298 }
359- } catch (Throwable e) {
360- c.errorOut();
361- throw e;
362- } finally {
363- c.discard();
364299 }
365300 }
366301 }
modified driver-core/src/test/java/com/datastax/driver/core/LoadBalancingPolicyBootstrapTest.java +59 −77
@@ -31,7 +31,8 @@
3131 import static com.datastax.driver.core.LoadBalancingPolicyBootstrapTest.HistoryPolicy.entry;
3232 import static org.assertj.core.api.Assertions.assertThat;
3333
34-public class LoadBalancingPolicyBootstrapTest {
34+@CCMConfig(numberOfNodes = 2, dirtiesContext = true, createCluster = false)
35+public class LoadBalancingPolicyBootstrapTest extends CCMTestsSupport {
3536
3637 private static final Logger logger = LoggerFactory.getLogger(LoadBalancingPolicyBootstrapTest.class);
3738
@@ -46,27 +47,18 @@
4647 public void should_init_policy_with_up_contact_points() throws Exception {
4748 HistoryPolicy policy = new HistoryPolicy(new RoundRobinPolicy());
4849
49- CCMBridge ccm = null;
50- Cluster cluster = null;
51- try {
52- ccm = CCMBridge.builder("test").withNodes(2).build();
53- cluster = Cluster.builder()
54- .addContactPoints(CCMBridge.ipOfNode(1), CCMBridge.ipOfNode(2))
55- .withLoadBalancingPolicy(policy)
56- .build();
57-
58- cluster.init();
59-
60- assertThat(policy.history).containsOnly(
61- entry(INIT, TestUtils.findHost(cluster, 1)),
62- entry(INIT, TestUtils.findHost(cluster, 2))
63- );
64- } finally {
65- if (cluster != null)
66- cluster.close();
67- if (ccm != null)
68- ccm.remove();
69- }
50+ Cluster cluster = register(Cluster.builder()
51+ .addContactPointsWithPorts(getInitialContactPoints())
52+ .withAddressTranslator(ccm.addressTranslator())
53+ .withLoadBalancingPolicy(policy)
54+ .build());
55+
56+ cluster.init();
57+
58+ assertThat(policy.history).containsOnly(
59+ entry(INIT, TestUtils.findHost(cluster, 1)),
60+ entry(INIT, TestUtils.findHost(cluster, 2))
61+ );
7062 }
7163
7264 /**
@@ -79,66 +71,56 @@
7971 * @jira_ticket JAVA-613
8072 * @since 2.0.10, 2.1.5
8173 */
82- @Test(groups = "short")
74+ @Test(groups = "short", dependsOnMethods = "should_init_policy_with_up_contact_points")
8375 public void should_send_down_notifications_after_init_when_contact_points_are_down() throws Exception {
84- CCMBridge ccm = null;
85- Cluster cluster = null;
86- try {
87- ccm = CCMBridge.builder("test").withNodes(2).build();
88-
89- // In order to validate this behavior, we need to stop the first node that would be attempted to be
90- // established as the control connection.
91- // This depends on the internal behavior and will even be made totally random by JAVA-618, therefore
92- // we retry the scenario until we get the desired preconditions.
93-
94- int nodeToStop = 1;
95- int tries = 1, maxTries = 10;
96- for (; tries <= maxTries; tries++) {
97- nodeToStop = (nodeToStop == 1) ? 2 : 1; // switch nodes at each try
98- int activeNode = nodeToStop == 2 ? 1 : 2;
99-
100- ccm.stop(nodeToStop);
101- ccm.waitForDown(nodeToStop);
102-
103- HistoryPolicy policy = new HistoryPolicy(new RoundRobinPolicy());
104- cluster = Cluster.builder()
105- .addContactPoints(CCMBridge.ipOfNode(1), CCMBridge.ipOfNode(2))
106- .withLoadBalancingPolicy(policy)
107- .build();
108-
109- cluster.init();
110-
111- if (policy.history.contains(entry(DOWN, TestUtils.findHost(cluster, nodeToStop)))) {
112- // This is the situation we're testing, the control connection tried the stopped node first.
113- assertThat(policy.history).containsExactly(
114- entry(INIT, TestUtils.findHost(cluster, activeNode)),
115- entry(DOWN, TestUtils.findHost(cluster, nodeToStop))
116- );
117- break;
118- } else {
119- assertThat(policy.history).containsOnly(
120- entry(INIT, TestUtils.findHost(cluster, 1)),
121- entry(INIT, TestUtils.findHost(cluster, 2))
122- );
123-
124- logger.info("Could not get first contact point to fail, retrying");
125-
126- cluster.close();
127-
128- ccm.start(nodeToStop);
129- ccm.waitForUp(nodeToStop);
130- }
131- }
13276
133- if (tries == maxTries + 1)
134- logger.warn("Could not get first contact point to fail after {} tries", maxTries);
77+ // In order to validate this behavior, we need to stop the first node that would be attempted to be
78+ // established as the control connection.
79+ // This depends on the internal behavior and will even be made totally random by JAVA-618, therefore
80+ // we retry the scenario until we get the desired preconditions.
81+
82+ int nodeToStop = 1;
83+ int tries = 1, maxTries = 10;
84+ for (; tries <= maxTries; tries++) {
85+ nodeToStop = (nodeToStop == 1) ? 2 : 1; // switch nodes at each try
86+ int activeNode = nodeToStop == 2 ? 1 : 2;
87+
88+ ccm.stop(nodeToStop);
89+ ccm.waitForDown(nodeToStop);
90+
91+ HistoryPolicy policy = new HistoryPolicy(new RoundRobinPolicy());
92+ Cluster cluster = register(Cluster.builder()
93+ .addContactPointsWithPorts(getInitialContactPoints())
94+ .withAddressTranslator(ccm.addressTranslator())
95+ .withLoadBalancingPolicy(policy)
96+ .build());
97+
98+ cluster.init();
99+
100+ if (policy.history.contains(entry(DOWN, TestUtils.findHost(cluster, nodeToStop)))) {
101+ // This is the situation we're testing, the control connection tried the stopped node first.
102+ assertThat(policy.history).containsExactly(
103+ entry(INIT, TestUtils.findHost(cluster, activeNode)),
104+ entry(DOWN, TestUtils.findHost(cluster, nodeToStop))
105+ );
106+ break;
107+ } else {
108+ assertThat(policy.history).containsOnly(
109+ entry(INIT, TestUtils.findHost(cluster, 1)),
110+ entry(INIT, TestUtils.findHost(cluster, 2))
111+ );
112+
113+ logger.info("Could not get first contact point to fail, retrying");
135114
136- } finally {
137- if (cluster != null)
138115 cluster.close();
139- if (ccm != null)
140- ccm.remove();
116+
117+ ccm.start(nodeToStop);
118+ ccm.waitForUp(nodeToStop);
119+ }
141120 }
121+
122+ if (tries == maxTries + 1)
123+ logger.warn("Could not get first contact point to fail after {} tries", maxTries);
142124 }
143125
144126 static class HistoryPolicy extends DelegatingLoadBalancingPolicy {
modified driver-core/src/test/java/com/datastax/driver/core/LoadBalancingPolicyRefreshTest.java +26 −30
@@ -23,12 +23,16 @@
2323 import java.util.Collection;
2424 import java.util.Iterator;
2525
26+import static com.datastax.driver.core.CreateCCM.TestMode.PER_METHOD;
2627 import static org.testng.Assert.assertTrue;
2728
2829 // Test that PoolingOpions.refreshConnectedHosts works as expected (JAVA-309)
29-public class LoadBalancingPolicyRefreshTest {
30+@CreateCCM(PER_METHOD)
31+public class LoadBalancingPolicyRefreshTest extends CCMTestsSupport {
3032
31- private static class UpdatablePolicy implements LoadBalancingPolicy {
33+ UpdatablePolicy policy;
34+
35+ private class UpdatablePolicy implements LoadBalancingPolicy {
3236
3337 private Cluster cluster;
3438 private Host theHost;
@@ -42,7 +46,7 @@
4246 this.cluster = cluster;
4347 try {
4448 for (Host h : hosts)
45- if (h.getAddress().equals(InetAddress.getByName(CCMBridge.IP_PREFIX + '1')))
49+ if (h.getAddress().equals(InetAddress.getByName(TestUtils.IP_PREFIX + '1')))
4650 this.theHost = h;
4751 } catch (Exception e) {
4852 throw new RuntimeException(e);
@@ -74,37 +78,29 @@
7478 }
7579
7680 @Test(groups = "short")
81+ @CCMConfig(numberOfNodes = 2, clusterProvider = "updatablePolicy")
7782 public void refreshTest() throws Throwable {
83+ // Ugly
84+ Host[] hosts = new Host[2];
85+ for (Host h : cluster.getMetadata().getAllHosts()) {
86+ if (h.getAddress().equals(ccm.addressOfNode(1).getAddress()))
87+ hosts[0] = h;
88+ else
89+ hosts[1] = h;
90+ }
7891
79- UpdatablePolicy policy = new UpdatablePolicy();
80- Cluster.Builder builder = Cluster.builder().withLoadBalancingPolicy(policy);
81- CCMBridge.CCMCluster c = CCMBridge.buildCluster(2, builder);
82- try {
83-
84- Session s = c.session;
85-
86- // Ugly
87- Host[] hosts = new Host[2];
88- for (Host h : c.cluster.getMetadata().getAllHosts()) {
89- if (h.getAddress().equals(InetAddress.getByName(CCMBridge.IP_PREFIX + '1')))
90- hosts[0] = h;
91- else
92- hosts[1] = h;
93- }
94-
95- assertTrue(s.getState().getConnectedHosts().contains(hosts[0]), "Connected hosts: " + s.getState().getConnectedHosts());
96- assertTrue(!s.getState().getConnectedHosts().contains(hosts[1]), "Connected hosts: " + s.getState().getConnectedHosts());
92+ assertTrue(session.getState().getConnectedHosts().contains(hosts[0]), "Connected hosts: " + session.getState().getConnectedHosts());
93+ assertTrue(!session.getState().getConnectedHosts().contains(hosts[1]), "Connected hosts: " + session.getState().getConnectedHosts());
9794
98- policy.changeTheHost(hosts[1]);
95+ policy.changeTheHost(hosts[1]);
9996
100- assertTrue(!s.getState().getConnectedHosts().contains(hosts[0]), "Connected hosts: " + s.getState().getConnectedHosts());
101- assertTrue(s.getState().getConnectedHosts().contains(hosts[1]), "Connected hosts: " + s.getState().getConnectedHosts());
97+ assertTrue(!session.getState().getConnectedHosts().contains(hosts[0]), "Connected hosts: " + session.getState().getConnectedHosts());
98+ assertTrue(session.getState().getConnectedHosts().contains(hosts[1]), "Connected hosts: " + session.getState().getConnectedHosts());
99+ }
102100
103- } catch (Throwable e) {
104- c.errorOut();
105- throw e;
106- } finally {
107- c.discard();
108- }
101+ @SuppressWarnings("unused")
102+ private Cluster.Builder updatablePolicy() {
103+ policy = new UpdatablePolicy();
104+ return Cluster.builder().withLoadBalancingPolicy(policy);
109105 }
110106 }
modified driver-core/src/test/java/com/datastax/driver/core/M3PTokenIntegrationTest.java +2 −1
@@ -18,8 +18,9 @@
1818 import com.datastax.driver.core.Token.M3PToken;
1919
2020 public class M3PTokenIntegrationTest extends TokenIntegrationTest {
21+
2122 public M3PTokenIntegrationTest() {
22- super("", DataType.bigint());
23+ super(DataType.bigint(), false);
2324 }
2425
2526 @Override
modified driver-core/src/test/java/com/datastax/driver/core/M3PTokenVnodeIntegrationTest.java +3 −1
@@ -15,9 +15,11 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+@CCMConfig(options = "--vnodes")
1819 public class M3PTokenVnodeIntegrationTest extends TokenIntegrationTest {
20+
1921 public M3PTokenVnodeIntegrationTest() {
20- super("", DataType.bigint(), true);
22+ super(DataType.bigint(), true);
2123 }
2224
2325 @Override
modified driver-core/src/test/java/com/datastax/driver/core/MaterializedViewMetadataTest.java +2 −2
@@ -26,7 +26,7 @@
2626 import static com.datastax.driver.core.DataType.cint;
2727
2828 @CassandraVersion(major = 3)
29-public class MaterializedViewMetadataTest extends CCMBridge.PerClassSingleNodeCluster {
29+public class MaterializedViewMetadataTest extends CCMTestsSupport {
3030
3131 /**
3232 * Validates that a materialized view is properly retrieved and parsed.
@@ -124,7 +124,7 @@
124124 }
125125
126126 @Override
127- protected Collection<String> getTableDefinitions() {
127+ public Collection<String> createTestFixtures() {
128128 return Collections.emptyList();
129129 }
130130 }
modified driver-core/src/test/java/com/datastax/driver/core/MetadataTest.java +56 −63
@@ -21,10 +21,12 @@
2121 import java.util.Map;
2222
2323 import static com.datastax.driver.core.Assertions.assertThat;
24+import static com.datastax.driver.core.CreateCCM.TestMode.PER_METHOD;
2425 import static com.datastax.driver.core.TestUtils.nonDebouncingQueryOptions;
2526 import static com.datastax.driver.core.TestUtils.waitFor;
2627
27-public class MetadataTest {
28+@CreateCCM(PER_METHOD)
29+public class MetadataTest extends CCMTestsSupport {
2830
2931 /**
3032 * <p>
@@ -50,71 +52,62 @@
5052 * @since 2.0.10, 2.1.5
5153 */
5254 @Test(groups = "long")
55+ @CCMConfig(numberOfNodes = 3, dirtiesContext = true, createCluster = false)
5356 public void should_update_metadata_on_topology_change() {
54- CCMBridge ccm = null;
55- Cluster cluster = null;
56-
57- try {
58- ccm = CCMBridge.builder("test").withNodes(3).build();
59-
60- cluster = Cluster.builder()
61- .addContactPoint(CCMBridge.ipOfNode(1))
62- .withQueryOptions(nonDebouncingQueryOptions())
63- .build();
64- Session session = cluster.connect();
65-
66- String keyspace = "test";
67- session.execute("CREATE KEYSPACE " + keyspace + " WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}");
68- Metadata metadata = cluster.getMetadata();
69-
70- // Capture all Token data.
71- assertThat(metadata.getTokenRanges()).hasSize(3);
72- Map<Host, Token> tokensForHost = getTokenForHosts(metadata);
73-
74- // Capture host3s token and range before we take it down.
75- Host host3 = TestUtils.findHost(cluster, 3);
76- Token host3Token = tokensForHost.get(host3);
77-
78- ccm.decommissionNode(3);
79- ccm.remove(3);
80-
81- // Ensure that the token ranges were updated, there should only be 2 ranges now.
82- assertThat(metadata.getTokenRanges()).hasSize(2);
83-
84- // The token should not be present for any Host.
85- assertThat(getTokenForHosts(metadata)).doesNotContainValue(host3Token);
86-
87- // The ring should be fully accounted for.
88- assertThat(cluster).hasValidTokenRanges("test");
89- assertThat(cluster).hasValidTokenRanges();
90-
91- // Add an additional node.
92- ccm.bootstrapNode(4);
93- waitFor(CCMBridge.IP_PREFIX + '4', cluster);
94-
95- // Ensure that the token ranges were updated, there should only be 3 ranges now.
96- assertThat(metadata.getTokenRanges()).hasSize(3);
97-
98- Host host4 = TestUtils.findHost(cluster, 4);
99- TokenRange host4Range = metadata.getTokenRanges(keyspace, host4).iterator().next();
100-
101- // Ensure no host token range intersects with node 4.
102- for (Host host : metadata.getAllHosts()) {
103- if (!host.equals(host4)) {
104- TokenRange hostRange = metadata.getTokenRanges(keyspace, host).iterator().next();
105- assertThat(host4Range).doesNotIntersect(hostRange);
106- }
57+ Cluster cluster = register(Cluster.builder()
58+ .addContactPointsWithPorts(getHostAddress(1))
59+ .withAddressTranslator(getAddressTranslator())
60+ .withQueryOptions(nonDebouncingQueryOptions())
61+ .build());
62+ Session session = cluster.connect();
63+
64+ String keyspace = "test";
65+ session.execute("CREATE KEYSPACE " + keyspace + " WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}");
66+ Metadata metadata = cluster.getMetadata();
67+
68+ // Capture all Token data.
69+ assertThat(metadata.getTokenRanges()).hasSize(3);
70+ Map<Host, Token> tokensForHost = getTokenForHosts(metadata);
71+
72+ // Capture host3s token and range before we take it down.
73+ Host host3 = TestUtils.findHost(cluster, 3);
74+ Token host3Token = tokensForHost.get(host3);
75+
76+ ccm.decommissionNode(3);
77+ ccm.remove(3);
78+
79+ // Ensure that the token ranges were updated, there should only be 2 ranges now.
80+ assertThat(metadata.getTokenRanges()).hasSize(2);
81+
82+ // The token should not be present for any Host.
83+ assertThat(getTokenForHosts(metadata)).doesNotContainValue(host3Token);
84+
85+ // The ring should be fully accounted for.
86+ assertThat(cluster).hasValidTokenRanges("test");
87+ assertThat(cluster).hasValidTokenRanges();
88+
89+ // Add an additional node.
90+ ccm.add(4);
91+ ccm.start(4);
92+ waitFor(TestUtils.IP_PREFIX + '4', cluster);
93+
94+ // Ensure that the token ranges were updated, there should only be 3 ranges now.
95+ assertThat(metadata.getTokenRanges()).hasSize(3);
96+
97+ Host host4 = TestUtils.findHost(cluster, 4);
98+ TokenRange host4Range = metadata.getTokenRanges(keyspace, host4).iterator().next();
99+
100+ // Ensure no host token range intersects with node 4.
101+ for (Host host : metadata.getAllHosts()) {
102+ if (!host.equals(host4)) {
103+ TokenRange hostRange = metadata.getTokenRanges(keyspace, host).iterator().next();
104+ assertThat(host4Range).doesNotIntersect(hostRange);
107105 }
108-
109- // The ring should be fully accounted for.
110- assertThat(cluster).hasValidTokenRanges("test");
111- assertThat(cluster).hasValidTokenRanges();
112- } finally {
113- if (cluster != null)
114- cluster.close();
115- if (ccm != null)
116- ccm.remove();
117106 }
107+
108+ // The ring should be fully accounted for.
109+ assertThat(cluster).hasValidTokenRanges("test");
110+ assertThat(cluster).hasValidTokenRanges();
118111 }
119112
120113 /**
modified driver-core/src/test/java/com/datastax/driver/core/MetricsTest.java +12 −11
@@ -28,19 +28,18 @@
2828 import javax.management.ObjectName;
2929 import java.lang.management.ManagementFactory;
3030 import java.util.Collection;
31-import java.util.Collections;
3231
3332 import static com.datastax.driver.core.Assertions.assertThat;
3433 import static org.testng.Assert.assertEquals;
3534
36-public class MetricsTest extends CCMBridge.PerClassSingleNodeCluster {
35+public class MetricsTest extends CCMTestsSupport {
3736 private volatile RetryDecision retryDecision;
3837
3938 MBeanServer server = ManagementFactory.getPlatformMBeanServer();
4039
4140 @Override
42- protected Cluster.Builder configure(Cluster.Builder builder) {
43- return builder.withRetryPolicy(new RetryPolicy() {
41+ public Cluster.Builder createClusterBuilder() {
42+ return Cluster.builder().withRetryPolicy(new RetryPolicy() {
4443 @Override
4544 public RetryDecision onReadTimeout(Statement statement, ConsistencyLevel cl, int requiredResponses, int receivedResponses, boolean dataRetrieved, int nbRetry) {
4645 return retryDecision;
@@ -72,7 +71,7 @@
7271 }
7372
7473 @Override
75- protected Collection<String> getTableDefinitions() {
74+ public Collection<String> createTestFixtures() {
7675 return Lists.newArrayList("CREATE TABLE test (k int primary key, v int)",
7776 "INSERT INTO test (k, v) VALUES (1, 1)");
7877 }
@@ -125,10 +124,11 @@
125124 */
126125 @Test(groups = "short", expectedExceptions = InstanceNotFoundException.class)
127126 public void metrics_should_be_null_when_metrics_disabled() throws Exception {
128- Cluster cluster = super.configure(Cluster.builder())
129- .addContactPointsWithPorts(Collections.singletonList(hostAddress))
127+ Cluster cluster = register(Cluster.builder()
128+ .addContactPointsWithPorts(getInitialContactPoints())
129+ .withAddressTranslator(getAddressTranslator())
130130 .withoutMetrics()
131- .build();
131+ .build());
132132 try {
133133 cluster.init();
134134 assertThat(cluster.getMetrics()).isNull();
@@ -149,10 +149,11 @@
149149 */
150150 @Test(groups = "short", expectedExceptions = InstanceNotFoundException.class)
151151 public void should_be_no_jmx_mbean_when_jmx_is_disabled() throws Exception {
152- Cluster cluster = super.configure(Cluster.builder())
153- .addContactPointsWithPorts(Collections.singletonList(hostAddress))
152+ Cluster cluster = register(Cluster.builder()
153+ .addContactPointsWithPorts(getInitialContactPoints())
154+ .withAddressTranslator(getAddressTranslator())
154155 .withoutJMXReporting()
155- .build();
156+ .build());
156157 try {
157158 cluster.init();
158159 assertThat(cluster.getMetrics()).isNotNull();
modified driver-core/src/test/java/com/datastax/driver/core/MissingRpcAddressTest.java +28 −39
@@ -23,6 +23,8 @@
2323 import java.net.InetAddress;
2424 import java.net.InetSocketAddress;
2525
26+import static com.datastax.driver.core.CreateCCM.TestMode.PER_METHOD;
27+import static java.util.Collections.singleton;
2628 import static org.testng.Assert.assertEquals;
2729 import static org.testng.Assert.assertNull;
2830
@@ -31,53 +33,40 @@
3133 * <p/>
3234 * This can happen because of gossip bugs. We want to ignore these hosts because this is most likely indicative of an error state.
3335 */
34-public class MissingRpcAddressTest {
36+@CreateCCM(PER_METHOD)
37+@CCMConfig(numberOfNodes = 2, dirtiesContext = true, createCluster = false)
38+public class MissingRpcAddressTest extends CCMTestsSupport {
3539
3640 @Test(groups = "short")
3741 public void testMissingRpcAddressAtStartup() throws Exception {
38- CCMBridge ccm = CCMBridge.builder("ccm").withNodes(2).build();
42+ deleteNode2RpcAddressFromNode1();
43+ // Use only one contact point to make sure that the control connection is on node1
44+ Cluster cluster = register(Cluster.builder()
45+ .addContactPointsWithPorts(getHostAddress(1))
46+ .withAddressTranslator(getAddressTranslator())
47+ .build());
48+ cluster.connect();
3949
40- Cluster cluster = null;
41- try {
42- deleteNode2RpcAddressFromNode1();
43- // Use only one contact point to make sure that the control connection is on node1
44- cluster = Cluster.builder()
45- .addContactPoint(CCMBridge.IP_PREFIX + "1")
46- .build();
47- cluster.connect();
48-
49- // Since node2's RPC address is unknown on our control host, it should have been ignored
50- assertEquals(cluster.getMetrics().getConnectedToHosts().getValue().intValue(), 1);
51- assertNull(cluster.getMetadata().getHost(socketAddress(2)));
52- } finally {
53- if (cluster != null)
54- cluster.close();
55- ccm.remove();
56- }
50+ // Since node2's RPC address is unknown on our control host, it should have been ignored
51+ assertEquals(cluster.getMetrics().getConnectedToHosts().getValue().intValue(), 1);
52+ assertNull(cluster.getMetadata().getHost(getInitialContactPoints().get(1)));
5753 }
5854
5955 // Artificially modify the system tables to simulate the missing rpc_address.
6056 private void deleteNode2RpcAddressFromNode1() throws Exception {
61- Cluster cluster = null;
62- try {
63- cluster = Cluster.builder()
64- .addContactPoint(CCMBridge.IP_PREFIX + "1")
65- // ensure we will only connect to node1
66- .withLoadBalancingPolicy(new WhiteListPolicy(Policies.defaultLoadBalancingPolicy(),
67- Lists.newArrayList(socketAddress(1))))
68- .build();
69- Session session = cluster.connect();
70- String deleteStmt = String.format("DELETE rpc_address FROM system.peers WHERE peer = '%s'",
71- InetAddress.getByName(CCMBridge.IP_PREFIX + "2").getHostName());
72- session.execute(deleteStmt);
73- session.close();
74- } finally {
75- if (cluster != null)
76- cluster.close();
77- }
57+ InetSocketAddress firstHost = getHostAddress(1);
58+ Cluster cluster = register(Cluster.builder()
59+ .addContactPointsWithPorts(singleton(firstHost))
60+ .withAddressTranslator(getAddressTranslator())
61+ // ensure we will only connect to node1
62+ .withLoadBalancingPolicy(new WhiteListPolicy(Policies.defaultLoadBalancingPolicy(),
63+ Lists.newArrayList(firstHost)))
64+ .build());
65+ Session session = cluster.connect();
66+ String deleteStmt = String.format("DELETE rpc_address FROM system.peers WHERE peer = '%s'",
67+ InetAddress.getByName(TestUtils.IP_PREFIX + "2").getHostName());
68+ session.execute(deleteStmt);
69+ session.close();
7870 }
7971
80- private static InetSocketAddress socketAddress(int node) {
81- return new InetSocketAddress(CCMBridge.IP_PREFIX + Integer.toString(node), 9042);
82- }
8372 }
modified driver-core/src/test/java/com/datastax/driver/core/NettyOptionsTest.java +4 −4
@@ -30,7 +30,6 @@
3030
3131 import java.util.concurrent.ThreadFactory;
3232
33-import static com.datastax.driver.core.CCMBridge.ipOfNode;
3433 import static org.mockito.Answers.CALLS_REAL_METHODS;
3534 import static org.mockito.Matchers.any;
3635 import static org.mockito.Mockito.*;
@@ -46,7 +45,7 @@
4645 @Test(groups = "short", dataProvider = "NettyOptionsTest")
4746 public void should_invoke_netty_options_hooks(int hosts, int coreConnections) throws Exception {
4847 //given
49- CCMBridge ccm = CCMBridge.builder("test").withNodes(hosts).build();
48+ CCMBridge ccm = CCMBridge.builder().withNodes(hosts).build();
5049 Cluster cluster = null;
5150 try {
5251 NettyOptions nettyOptions = mock(NettyOptions.class, CALLS_REAL_METHODS.get());
@@ -64,7 +63,8 @@
6463 }
6564 }).when(nettyOptions).afterChannelInitialized(any(SocketChannel.class));
6665 cluster = Cluster.builder()
67- .addContactPoint(ipOfNode(1))
66+ .addContactPointsWithPorts(ccm.addressOfNode(1))
67+ .withAddressTranslator(ccm.addressTranslator())
6868 .withPoolingOptions(new PoolingOptions()
6969 .setConnectionsPerHost(HostDistance.LOCAL, coreConnections, coreConnections)
7070 )
@@ -100,4 +100,4 @@
100100 }
101101 }
102102
103-}
No newline at the end of the file
103+}
modified driver-core/src/test/java/com/datastax/driver/core/NetworkTopologyStrategyTest.java +34 −31
@@ -641,36 +641,39 @@
641641 public void should_warn_if_replication_factor_cannot_be_met() {
642642 Logger logger = Logger.getLogger(ReplicationStrategy.NetworkTopologyStrategy.class);
643643 MemoryAppender logs = new MemoryAppender();
644- logger.setLevel(Level.WARN);
645- logger.addAppender(logs);
646-
647- List<Token> ring = ImmutableList.<Token>builder()
648- .add(TOKEN01)
649- .add(TOKEN02)
650- .add(TOKEN03)
651- .add(TOKEN04)
652- .build();
653-
654- Map<Token, Host> tokenToPrimary = ImmutableMap.<Token, Host>builder()
655- .put(TOKEN01, host(IP1, DC1, RACK11))
656- .put(TOKEN02, host(IP2, DC1, RACK12))
657- .put(TOKEN03, host(IP3, DC2, RACK21))
658- .put(TOKEN04, host(IP4, DC2, RACK22))
659- .build();
660-
661- // Wrong configuration: impossible replication factor for DC2
662- networkTopologyStrategy(rf(DC1, 2), rf(DC2, 3))
663- .computeTokenToReplicaMap(keyspace, tokenToPrimary, ring);
664- assertThat(logs.getNext())
665- .contains(String.format("Error while computing token map for keyspace %s with datacenter %s", keyspace, DC2));
666-
667- // Wrong configuration: non-existing datacenter
668- networkTopologyStrategy(rf(DC1, 2), rf("does_not_exist", 2))
669- .computeTokenToReplicaMap(keyspace, tokenToPrimary, ring);
670- assertThat(logs.getNext())
671- .contains(String.format("Error while computing token map for keyspace %s with datacenter %s", keyspace, "does_not_exist"));
672-
673- logger.setLevel(null);
674- logger.removeAppender(logs);
644+ Level originalLevel = logger.getLevel();
645+ try {
646+ logger.setLevel(Level.WARN);
647+ logger.addAppender(logs);
648+
649+ List<Token> ring = ImmutableList.<Token>builder()
650+ .add(TOKEN01)
651+ .add(TOKEN02)
652+ .add(TOKEN03)
653+ .add(TOKEN04)
654+ .build();
655+
656+ Map<Token, Host> tokenToPrimary = ImmutableMap.<Token, Host>builder()
657+ .put(TOKEN01, host(IP1, DC1, RACK11))
658+ .put(TOKEN02, host(IP2, DC1, RACK12))
659+ .put(TOKEN03, host(IP3, DC2, RACK21))
660+ .put(TOKEN04, host(IP4, DC2, RACK22))
661+ .build();
662+
663+ // Wrong configuration: impossible replication factor for DC2
664+ networkTopologyStrategy(rf(DC1, 2), rf(DC2, 3))
665+ .computeTokenToReplicaMap(keyspace, tokenToPrimary, ring);
666+ assertThat(logs.getNext())
667+ .contains(String.format("Error while computing token map for keyspace %s with datacenter %s", keyspace, DC2));
668+
669+ // Wrong configuration: non-existing datacenter
670+ networkTopologyStrategy(rf(DC1, 2), rf("does_not_exist", 2))
671+ .computeTokenToReplicaMap(keyspace, tokenToPrimary, ring);
672+ assertThat(logs.getNext())
673+ .contains(String.format("Error while computing token map for keyspace %s with datacenter %s", keyspace, "does_not_exist"));
674+ } finally {
675+ logger.setLevel(originalLevel);
676+ logger.removeAppender(logs);
677+ }
675678 }
676679 }
modified driver-core/src/test/java/com/datastax/driver/core/NodeListRefreshDebouncerTest.java +8 −20
@@ -15,18 +15,20 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import org.testng.annotations.AfterClass;
1918 import org.testng.annotations.AfterMethod;
20-import org.testng.annotations.BeforeClass;
19+import org.testng.annotations.BeforeMethod;
2120 import org.testng.annotations.Test;
2221
2322 import java.util.Collection;
2423
24+import static com.datastax.driver.core.CreateCCM.TestMode.PER_METHOD;
2525 import static com.datastax.driver.core.TestUtils.CREATE_KEYSPACE_SIMPLE_FORMAT;
2626 import static com.google.common.collect.Lists.newArrayList;
2727 import static org.mockito.Mockito.*;
2828
29-public class NodeListRefreshDebouncerTest extends CCMBridge.PerClassSingleNodeCluster {
29+@CreateCCM(PER_METHOD)
30+@CCMConfig(dirtiesContext = true, createKeyspace = false)
31+public class NodeListRefreshDebouncerTest extends CCMTestsSupport {
3032
3133 private static final int DEBOUNCE_TIME = 2000;
3234
@@ -42,20 +44,15 @@
4244 // Keyspaces to drop after test completes.
4345 private Collection<String> keyspaces = newArrayList();
4446
45- @Override
46- protected Collection<String> getTableDefinitions() {
47- return newArrayList();
48- }
49-
50- @BeforeClass(groups = "short")
47+ @BeforeMethod(groups = "short")
5148 public void setup() {
5249 queryOptions = new QueryOptions();
5350 queryOptions.setRefreshNodeListIntervalMillis(DEBOUNCE_TIME);
5451 queryOptions.setMaxPendingRefreshNodeListRequests(5);
5552 queryOptions.setRefreshSchemaIntervalMillis(0);
5653 // Create a separate cluster that will receive the schema events on its control connection.
57- cluster2 = this.configure(Cluster.builder())
58- .addContactPointsWithPorts(newArrayList(hostAddress))
54+ cluster2 = Cluster.builder()
55+ .addContactPointsWithPorts(getInitialContactPoints())
5956 .withQueryOptions(queryOptions)
6057 .build();
6158 session2 = cluster2.connect();
@@ -67,17 +64,8 @@
6764 }
6865
6966 @AfterMethod(groups = "short")
70- public void beforeMethod() {
71- reset(controlConnection);
72- }
73-
74- @AfterClass(groups = "short")
7567 public void teardown() {
7668 cluster2.close();
77- // drop all keyspaces
78- for (String keyspace : keyspaces) {
79- session.execute("DROP KEYSPACE " + keyspace);
80- }
8169 }
8270
8371 /**
modified driver-core/src/test/java/com/datastax/driver/core/NodeRefreshDebouncerTest.java +26 −37
@@ -18,20 +18,14 @@
1818 import org.mockito.ArgumentCaptor;
1919 import org.testng.annotations.Test;
2020
21-import java.util.Collection;
2221 import java.util.concurrent.TimeUnit;
2322
2423 import static com.datastax.driver.core.Assertions.assertThat;
25-import static com.google.common.collect.Lists.newArrayList;
2624 import static org.mockito.ArgumentCaptor.forClass;
2725 import static org.mockito.Mockito.*;
2826
29-public class NodeRefreshDebouncerTest extends CCMBridge.PerClassSingleNodeCluster {
30-
31- @Override
32- protected Collection<String> getTableDefinitions() {
33- return newArrayList();
34- }
27+@CCMConfig(dirtiesContext = true, createCluster = false)
28+public class NodeRefreshDebouncerTest extends CCMTestsSupport {
3529
3630 /**
3731 * Ensures that when a new node is bootstrapped into the cluster, stopped, and then subsequently
@@ -46,36 +40,31 @@
4640 */
4741 @Test(groups = "long")
4842 public void should_call_onAdd_with_bootstrap_stop_start() {
49- int refreshNodeInterval = 10000;
43+ int refreshNodeInterval = 30000;
5044 QueryOptions queryOptions = new QueryOptions().setRefreshNodeIntervalMillis(refreshNodeInterval);
51- CCMBridge ccm = CCMBridge.builder("test").withNodes(1).build();
52- Cluster cluster = Cluster.builder()
53- .addContactPoint(CCMBridge.ipOfNode(1))
45+ Cluster cluster = register(Cluster.builder()
46+ .addContactPointsWithPorts(getHostAddress(1))
47+ .withAddressTranslator(getAddressTranslator())
5448 .withQueryOptions(queryOptions)
55- .build();
56-
57- try {
58- cluster.connect();
59- Host.StateListener listener = mock(Host.StateListener.class);
60- cluster.register(listener);
61- ccm.bootstrapNode(2);
62- ccm.stop(2);
63- ccm.start(2);
64-
65- ArgumentCaptor<Host> captor = forClass(Host.class);
66-
67- // Only register and onAdd should be called, since stop and start should be discarded.
68- verify(listener).onRegister(cluster);
69- long addDelay = refreshNodeInterval + TimeUnit.MILLISECONDS.convert(Cluster.NEW_NODE_DELAY_SECONDS, TimeUnit.SECONDS);
70- verify(listener, timeout(addDelay)).onAdd(captor.capture());
71- verifyNoMoreInteractions(listener);
72-
73- // The hosts state should be UP.
74- assertThat(captor.getValue().getState()).isEqualTo("UP");
75- assertThat(cluster).host(2).hasState(Host.State.UP);
76- } finally {
77- cluster.close();
78- ccm.remove();
79- }
49+ .build());
50+ cluster.connect();
51+ Host.StateListener listener = mock(Host.StateListener.class);
52+ cluster.register(listener);
53+ ccm.add(2);
54+ ccm.start(2);
55+ ccm.stop(2);
56+ ccm.start(2);
57+
58+ ArgumentCaptor<Host> captor = forClass(Host.class);
59+
60+ // Only register and onAdd should be called, since stop and start should be discarded.
61+ verify(listener).onRegister(cluster);
62+ long addDelay = refreshNodeInterval + TimeUnit.MILLISECONDS.convert(Cluster.NEW_NODE_DELAY_SECONDS, TimeUnit.SECONDS);
63+ verify(listener, timeout(addDelay)).onAdd(captor.capture());
64+ verifyNoMoreInteractions(listener);
65+
66+ // The hosts state should be UP.
67+ assertThat(captor.getValue().getState()).isEqualTo("UP");
68+ assertThat(cluster).host(2).hasState(Host.State.UP);
8069 }
8170 }
modified driver-core/src/test/java/com/datastax/driver/core/OPPTokenIntegrationTest.java +3 −1
@@ -17,9 +17,11 @@
1717
1818 import com.datastax.driver.core.Token.OPPToken;
1919
20+@CCMConfig(options = "-p ByteOrderedPartitioner")
2021 public class OPPTokenIntegrationTest extends TokenIntegrationTest {
22+
2123 public OPPTokenIntegrationTest() {
22- super("-p ByteOrderedPartitioner", DataType.blob());
24+ super(DataType.blob(), false);
2325 }
2426
2527 @Override
modified driver-core/src/test/java/com/datastax/driver/core/OPPTokenVnodeIntegrationTest.java +3 −1
@@ -15,9 +15,11 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+@CCMConfig(options = {"-p ByteOrderedPartitioner", "--vnodes"})
1819 public class OPPTokenVnodeIntegrationTest extends TokenIntegrationTest {
20+
1921 public OPPTokenVnodeIntegrationTest() {
20- super("-p ByteOrderedPartitioner", DataType.blob(), true);
22+ super(DataType.blob(), true);
2123 }
2224
2325 @Override
modified driver-core/src/test/java/com/datastax/driver/core/PagingStateTest.java +4 −2
@@ -29,12 +29,14 @@
2929 import static org.assertj.core.api.Assertions.assertThat;
3030
3131 @CassandraVersion(major = 2.0)
32-public class PagingStateTest extends CCMBridge.PerClassSingleNodeCluster {
32+public class PagingStateTest extends CCMTestsSupport {
33+
3334 private static final Logger logger = LoggerFactory.getLogger(PagingStateTest.class);
35+
3436 public static final String KEY = "paging_test";
3537
3638 @Override
37- protected Collection<String> getTableDefinitions() {
39+ public Collection<String> createTestFixtures() {
3840 return Collections.singletonList("CREATE TABLE test (k text, v int, PRIMARY KEY (k, v))");
3941 }
4042
modified driver-core/src/test/java/com/datastax/driver/core/PoolingOptionsIntegrationTest.java +34 −36
@@ -15,10 +15,9 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import org.testng.annotations.AfterMethod;
1819 import org.testng.annotations.Test;
1920
20-import java.util.Collection;
21-import java.util.Collections;
2221 import java.util.concurrent.LinkedBlockingQueue;
2322 import java.util.concurrent.ThreadPoolExecutor;
2423 import java.util.concurrent.TimeUnit;
@@ -27,10 +26,23 @@
2726 import static org.mockito.Matchers.any;
2827 import static org.mockito.Mockito.*;
2928
30-public class PoolingOptionsIntegrationTest extends CCMBridge.PerClassSingleNodeCluster {
29+@CCMConfig(createSession = false)
30+public class PoolingOptionsIntegrationTest extends CCMTestsSupport {
31+
32+ private ThreadPoolExecutor executor;
33+
3134 @Override
32- protected Collection<String> getTableDefinitions() {
33- return Collections.emptyList();
35+ public Cluster.Builder createClusterBuilder() {
36+ executor = spy(new ThreadPoolExecutor(1, 1, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>()));
37+ PoolingOptions poolingOptions = new PoolingOptions();
38+ poolingOptions.setInitializationExecutor(executor);
39+ return Cluster.builder().withPoolingOptions(poolingOptions);
40+ }
41+
42+ @AfterMethod(groups = "short")
43+ public void shutdownExecutor() {
44+ if (executor != null)
45+ executor.shutdown();
3446 }
3547
3648 /**
@@ -46,44 +58,30 @@
4658 */
4759 @Test(groups = "short")
4860 public void should_be_able_to_use_custom_initialization_executor() {
49- ThreadPoolExecutor executor = spy(new ThreadPoolExecutor(1, 1, 60, TimeUnit.SECONDS,
50- new LinkedBlockingQueue<Runnable>()));
51-
52- PoolingOptions poolingOptions = new PoolingOptions();
53- poolingOptions.setInitializationExecutor(executor);
61+ cluster.init();
62+ // Ensure executor used.
63+ verify(executor, atLeastOnce()).execute(any(Runnable.class));
5464
55- Cluster cluster = Cluster.builder()
56- .addContactPointsWithPorts(Collections.singletonList(hostAddress))
57- .withPoolingOptions(poolingOptions).build();
58- try {
59- cluster.init();
60- // Ensure executor used.
61- verify(executor, atLeastOnce()).execute(any(Runnable.class));
65+ // Reset invocation count.
66+ reset();
6267
63- // Reset invocation count.
64- reset();
68+ Session session = cluster.connect();
6569
66- Session session = cluster.connect();
70+ // Ensure executor used again to establish core connections.
71+ verify(executor, atLeastOnce()).execute(any(Runnable.class));
6772
68- // Ensure executor used again to establish core connections.
69- verify(executor, atLeastOnce()).execute(any(Runnable.class));
73+ // Expect core connections + control connection.
74+ assertThat(cluster.getMetrics().getOpenConnections().getValue()).isEqualTo(
75+ TestUtils.numberOfLocalCoreConnections(cluster) + 1);
7076
71- // Expect core connections + control connection.
72- assertThat(cluster.getMetrics().getOpenConnections().getValue()).isEqualTo(
73- TestUtils.numberOfLocalCoreConnections(cluster) + 1);
77+ reset();
7478
75- reset();
79+ session.close();
7680
77- session.close();
81+ // Executor should have been used to close connections associated with the session.
82+ verify(executor, atLeastOnce()).execute(any(Runnable.class));
7883
79- // Executor should have been used to close connections associated with the session.
80- verify(executor, atLeastOnce()).execute(any(Runnable.class));
81-
82- // Only the control connection should remain.
83- assertThat(cluster.getMetrics().getOpenConnections().getValue()).isEqualTo(1);
84- } finally {
85- cluster.close();
86- executor.shutdown();
87- }
84+ // Only the control connection should remain.
85+ assertThat(cluster.getMetrics().getOpenConnections().getValue()).isEqualTo(1);
8886 }
8987 }
modified driver-core/src/test/java/com/datastax/driver/core/PreparedIdTest.java +3 −3
@@ -22,10 +22,10 @@
2222
2323 import static com.datastax.driver.core.Assertions.assertThat;
2424
25-public class PreparedIdTest extends CCMBridge.PerClassSingleNodeCluster {
25+public class PreparedIdTest extends CCMTestsSupport {
2626
2727 @Override
28- protected Collection<String> getTableDefinitions() {
28+ public Collection<String> createTestFixtures() {
2929 return Lists.newArrayList(
3030 "CREATE TABLE foo(k1 int, k2 int, k3 int, v int, PRIMARY KEY ((k1, k2, k3)))"
3131 );
@@ -63,4 +63,4 @@
6363 PreparedStatement pst = session.prepare("INSERT INTO foo (k3, k1, k2, v) VALUES (1, 1, 1, 1)");
6464 assertThat(pst.getPreparedId().routingKeyIndexes).isNull();
6565 }
66-}
No newline at the end of the file
66+}
modified driver-core/src/test/java/com/datastax/driver/core/PreparedStatementTest.java +10 −12
@@ -18,7 +18,6 @@
1818 import com.datastax.driver.core.exceptions.InvalidQueryException;
1919 import com.datastax.driver.core.exceptions.UnsupportedFeatureException;
2020 import com.datastax.driver.core.utils.CassandraVersion;
21-import com.google.common.collect.ImmutableList;
2221 import org.testng.annotations.Test;
2322
2423 import java.net.InetAddress;
@@ -33,7 +32,8 @@
3332 * <p/>
3433 * Note: this class also happens to test all the get methods from Row.
3534 */
36-public class PreparedStatementTest extends CCMBridge.PerClassSingleNodeCluster {
35+@CCMConfig(clusterProvider = "createClusterBuilderNoDebouncing")
36+public class PreparedStatementTest extends CCMTestsSupport {
3737
3838 private static final String ALL_NATIVE_TABLE = "all_native";
3939 private static final String ALL_LIST_TABLE = "all_list";
@@ -49,7 +49,7 @@
4949 }
5050
5151 @Override
52- protected Collection<String> getTableDefinitions() {
52+ public Collection<String> createTestFixtures() {
5353
5454 List<String> defs = new ArrayList<String>(4);
5555
@@ -107,11 +107,6 @@
107107 return defs;
108108 }
109109
110- @Override
111- protected Cluster.Builder configure(Cluster.Builder builder) {
112- return builder.withQueryOptions(TestUtils.nonDebouncingQueryOptions());
113- }
114-
115110 @Test(groups = "short")
116111 public void preparedNativeTest() {
117112 // Test preparing/bounding for all native types
@@ -350,7 +345,7 @@
350345 */
351346 @Test(groups = {"docs"})
352347 public void printTableDefinitions() {
353- for (String definition : getTableDefinitions()) {
348+ for (String definition : createTestFixtures()) {
354349 System.out.println(definition);
355350 }
356351 }
@@ -411,7 +406,8 @@
411406 @Test(groups = "short", expectedExceptions = InvalidQueryException.class)
412407 public void should_fail_when_prepared_on_another_cluster() throws Exception {
413408 Cluster otherCluster = Cluster.builder()
414- .addContactPointsWithPorts(ImmutableList.of(hostAddress))
409+ .addContactPointsWithPorts(getInitialContactPoints())
410+ .withAddressTranslator(getAddressTranslator())
415411 .build();
416412 try {
417413 PreparedStatement pst = otherCluster.connect().prepare("select * from system.peers where inet = ?");
@@ -437,7 +433,8 @@
437433 @Test(groups = "short")
438434 public void should_not_allow_unbound_value_on_bound_statement_when_protocol_lesser_than_v4() {
439435 Cluster cluster = Cluster.builder()
440- .addContactPointsWithPorts(Collections.singleton(hostAddress))
436+ .addContactPointsWithPorts(getInitialContactPoints())
437+ .withAddressTranslator(getAddressTranslator())
441438 .withProtocolVersion(TestUtils.getDesiredProtocolVersion(ProtocolVersion.V3))
442439 .build();
443440 Session session = cluster.connect();
@@ -469,7 +466,8 @@
469466 @CassandraVersion(major = 2.0)
470467 public void should_not_allow_unbound_value_on_batch_statement_when_protocol_lesser_than_v4() {
471468 Cluster cluster = Cluster.builder()
472- .addContactPointsWithPorts(Collections.singleton(hostAddress))
469+ .addContactPointsWithPorts(getInitialContactPoints())
470+ .withAddressTranslator(getAddressTranslator())
473471 .withProtocolVersion(TestUtils.getDesiredProtocolVersion(ProtocolVersion.V3))
474472 .build();
475473 Session session = cluster.connect();
modified driver-core/src/test/java/com/datastax/driver/core/QueryLoggerErrorsTest.java +8 −3
@@ -16,6 +16,7 @@
1616 package com.datastax.driver.core;
1717
1818 import com.datastax.driver.core.exceptions.*;
19+import org.apache.log4j.Level;
1920 import org.apache.log4j.Logger;
2021 import org.scassandra.http.client.PrimingRequest;
2122 import org.testng.annotations.AfterMethod;
@@ -48,9 +49,13 @@
4849 private Cluster cluster = null;
4950 private Session session = null;
5051 private QueryLogger queryLogger = null;
52+ private Level originalError;
53+ private Level originalSlow;
5154
5255 @BeforeMethod(groups = {"short", "unit"})
5356 public void setUp() {
57+ originalSlow = slow.getLevel();
58+ originalError = error.getLevel();
5459 slow.setLevel(INFO);
5560 error.setLevel(INFO);
5661 slow.addAppender(slowAppender = new MemoryAppender());
@@ -62,10 +67,10 @@
6267 session = cluster.connect();
6368 }
6469
65- @AfterMethod(groups = {"short", "unit"})
70+ @AfterMethod(groups = {"short", "unit"}, alwaysRun = true)
6671 public void tearDown() {
67- slow.setLevel(null);
68- error.setLevel(null);
72+ slow.setLevel(originalSlow);
73+ error.setLevel(originalError);
6974 slow.removeAppender(slowAppender);
7075 error.removeAppender(errorAppender);
7176
modified driver-core/src/test/java/com/datastax/driver/core/QueryLoggerTest.java +18 −15
@@ -23,6 +23,7 @@
2323 import com.google.common.collect.Lists;
2424 import com.google.common.collect.Sets;
2525 import com.google.common.primitives.Bytes;
26+import org.apache.log4j.Level;
2627 import org.apache.log4j.Logger;
2728 import org.testng.annotations.AfterMethod;
2829 import org.testng.annotations.BeforeMethod;
@@ -34,9 +35,9 @@
3435
3536 import static com.datastax.driver.core.BatchStatement.Type.COUNTER;
3637 import static com.datastax.driver.core.BatchStatement.Type.UNLOGGED;
37-import static com.datastax.driver.core.CCMBridge.ipOfNode;
3838 import static com.datastax.driver.core.QueryLogger.*;
3939 import static com.datastax.driver.core.TestUtils.getFixedValue;
40+import static com.datastax.driver.core.TestUtils.ipOfNode;
4041 import static org.apache.log4j.Level.*;
4142 import static org.assertj.core.api.Assertions.assertThat;
4243 import static org.mockito.Mockito.mock;
@@ -46,7 +47,7 @@
4647 * More tests, specifically targeting slow and unsuccessful queries, can be found in
4748 * {@link QueryLoggerErrorsTest}.
4849 */
49-public class QueryLoggerTest extends CCMBridge.PerClassSingleNodeCluster {
50+public class QueryLoggerTest extends CCMTestsSupport {
5051
5152 private static final List<DataType> dataTypes = new ArrayList<DataType>(
5253 Sets.filter(DataType.allPrimitiveTypes(TestUtils.getDesiredProtocolVersion()), new Predicate<DataType>() {
@@ -93,32 +94,34 @@
9394 private MemoryAppender errorAppender;
9495
9596 private QueryLogger queryLogger;
97+ private Level originalNormal;
98+ private Level originalSlow;
99+ private Level originalError;
96100
97101 @BeforeMethod(groups = {"short", "unit"})
98102 public void startCapturingLogs() {
103+ originalNormal = normal.getLevel();
104+ originalSlow = slow.getLevel();
105+ originalError = error.getLevel();
106+ normal.setLevel(INFO);
107+ slow.setLevel(INFO);
108+ error.setLevel(INFO);
99109 normal.addAppender(normalAppender = new MemoryAppender());
100110 slow.addAppender(slowAppender = new MemoryAppender());
101111 error.addAppender(errorAppender = new MemoryAppender());
102112 }
103113
104- @AfterMethod(groups = {"short", "unit"})
114+ @AfterMethod(groups = {"short", "unit"}, alwaysRun = true)
105115 public void stopCapturingLogs() {
106- normal.setLevel(null);
107- slow.setLevel(null);
108- error.setLevel(null);
116+ normal.setLevel(originalNormal);
117+ slow.setLevel(originalSlow);
118+ error.setLevel(originalError);
109119 normal.removeAppender(normalAppender);
110120 slow.removeAppender(slowAppender);
111121 error.removeAppender(errorAppender);
112122 }
113123
114- @BeforeMethod(groups = {"short", "unit"})
115- public void resetLogLevels() {
116- normal.setLevel(INFO);
117- slow.setLevel(INFO);
118- error.setLevel(INFO);
119- }
120-
121- @AfterMethod(groups = {"short", "unit"})
124+ @AfterMethod(groups = {"short", "unit"}, alwaysRun = true)
122125 public void unregisterQueryLogger() {
123126 if (cluster != null && queryLogger != null) {
124127 cluster.unregister(queryLogger);
@@ -744,7 +747,7 @@
744747 }
745748
746749 @Override
747- protected List<String> getTableDefinitions() {
750+ public List<String> createTestFixtures() {
748751 return Lists.newArrayList("CREATE TABLE test (pk int PRIMARY KEY, " + definitions + ")");
749752 }
750753
modified driver-core/src/test/java/com/datastax/driver/core/QueryOptionsTest.java +15 −2
@@ -22,12 +22,14 @@
2222 import org.testng.annotations.Test;
2323
2424 import java.util.List;
25+import java.util.concurrent.Callable;
2526 import java.util.concurrent.TimeUnit;
2627
2728 import static com.datastax.driver.core.Assertions.assertThat;
2829 import static com.datastax.driver.core.TestUtils.nonQuietClusterCloseOptions;
2930
3031 public class QueryOptionsTest {
32+
3133 ScassandraCluster scassandra;
3234
3335 QueryOptions queryOptions;
@@ -47,7 +49,8 @@
4749 queryOptions = new QueryOptions();
4850 loadBalancingPolicy = new SortingLoadBalancingPolicy();
4951 cluster = Cluster.builder()
50- .addContactPoint(CCMBridge.ipOfNode(2))
52+ .addContactPointsWithPorts(scassandra.address(2))
53+ .withAddressTranslator(scassandra.addressTranslator())
5154 .withLoadBalancingPolicy(loadBalancingPolicy)
5255 .withQueryOptions(queryOptions)
5356 .withNettyOptions(nonQuietClusterCloseOptions)
@@ -62,6 +65,7 @@
6265 // Make sure there are no prepares
6366 for (int host : Lists.newArrayList(1, 2, 3)) {
6467 assertThat(scassandra.node(host).activityClient().retrievePreparedStatementPreparations()).hasSize(0);
68+ scassandra.node(host).activityClient().clearAllRecordedActivity();
6569 }
6670 }
6771
@@ -158,6 +162,15 @@
158162
159163 preparationOne = scassandra.node(1).activityClient().retrievePreparedStatementPreparations();
160164 if (expectReprepare) {
165+ // tests fail randomly at this point, probably due to
166+ // https://github.com/scassandra/scassandra-server/issues/116
167+ ConditionChecker.awaitWhile(new Callable<Boolean>() {
168+ @Override
169+ public Boolean call() {
170+ return session.getState().getConnectedHosts().size() < 3
171+ || scassandra.node(1).activityClient().retrievePreparedStatementPreparations().isEmpty();
172+ }
173+ }, TimeUnit.MINUTES.toMillis(1));
161174 assertThat(preparationOne).hasSize(1);
162175 assertThat(preparationOne.get(0).getPreparedStatementText()).isEqualTo(query);
163176 } else {
@@ -215,7 +228,7 @@
215228 valideReprepareOnUp(false);
216229 }
217230
218- @AfterMethod(groups = "short")
231+ @AfterMethod(groups = "short", alwaysRun = true)
219232 public void afterMethod() {
220233 if (cluster != null)
221234 cluster.close();
modified driver-core/src/test/java/com/datastax/driver/core/QueryTimestampTest.java +4 −5
@@ -15,7 +15,6 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import com.datastax.driver.core.Cluster.Builder;
1918 import com.datastax.driver.core.Metrics.Errors;
2019 import com.datastax.driver.core.policies.DowngradingConsistencyRetryPolicy;
2120 import com.datastax.driver.core.utils.CassandraVersion;
@@ -32,18 +31,18 @@
3231 * Tests the behavior of client-provided timestamps with protocol v3.
3332 */
3433 @CassandraVersion(major = 2.1)
35-public class QueryTimestampTest extends CCMBridge.PerClassSingleNodeCluster {
34+public class QueryTimestampTest extends CCMTestsSupport {
3635
3736 @Override
38- protected Collection<String> getTableDefinitions() {
37+ public Collection<String> createTestFixtures() {
3938 return Lists.newArrayList("CREATE TABLE foo (k int PRIMARY KEY, v int)");
4039 }
4140
4241 private volatile long timestampFromGenerator;
4342
4443 @Override
45- protected Builder configure(Builder builder) {
46- return builder
44+ public Cluster.Builder createClusterBuilder() {
45+ return Cluster.builder()
4746 .withTimestampGenerator(new TimestampGenerator() {
4847 @Override
4948 public long next() {
modified driver-core/src/test/java/com/datastax/driver/core/QueryTracker.java +3 −2
@@ -21,6 +21,7 @@
2121 import org.assertj.core.util.Maps;
2222
2323 import java.net.InetAddress;
24+import java.net.InetSocketAddress;
2425 import java.util.List;
2526 import java.util.Map;
2627 import java.util.concurrent.ExecutionException;
@@ -88,8 +89,8 @@
8889
8990 public int queryCount(ScassandraCluster sCluster, int dc, int node) {
9091 try {
91- String host = sCluster.address(dc, node);
92- Integer queried = coordinators.get(InetAddress.getByName(host));
92+ InetSocketAddress host = sCluster.address(dc, node);
93+ Integer queried = coordinators.get(host.getAddress());
9394 return queried != null ? queried : 0;
9495 } catch (Exception e) {
9596 throw new RuntimeException(e);
modified driver-core/src/test/java/com/datastax/driver/core/RPTokenIntegrationTest.java +3 −1
@@ -17,9 +17,11 @@
1717
1818 import com.datastax.driver.core.Token.RPToken;
1919
20+@CCMConfig(options = "-p RandomPartitioner")
2021 public class RPTokenIntegrationTest extends TokenIntegrationTest {
22+
2123 public RPTokenIntegrationTest() {
22- super("-p RandomPartitioner", DataType.varint());
24+ super(DataType.varint(), false);
2325 }
2426
2527 @Override
modified driver-core/src/test/java/com/datastax/driver/core/RPTokenVnodeIntegrationTest.java +3 −1
@@ -15,9 +15,11 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+@CCMConfig(options = {"-p RandomPartitioner", "--vnodes"})
1819 public class RPTokenVnodeIntegrationTest extends TokenIntegrationTest {
20+
1921 public RPTokenVnodeIntegrationTest() {
20- super("-p RandomPartitioner", DataType.varint(), true);
22+ super(DataType.varint(), true);
2123 }
2224
2325 @Override
modified driver-core/src/test/java/com/datastax/driver/core/RecommissionedNodeTest.java +39 −14
@@ -44,20 +44,26 @@
4444
4545 @Test(groups = "long")
4646 public void should_ignore_recommissioned_node_on_reconnection_attempt() throws Exception {
47- mainCcm = CCMBridge.builder("main").withNodes(3).build();
47+ mainCcm = CCMBridge.builder().withNodes(3).build();
4848 // node1 will be our "recommissioned" node, for now we just stop it so that it stays in the peers table.
4949 mainCcm.stop(1);
5050 mainCcm.waitForDown(1);
5151
5252 // Now start the driver that will connect to node2 and node3, and consider node1 down
53- mainCluster = Cluster.builder().addContactPoint(CCMBridge.IP_PREFIX + "2")
53+ mainCluster = Cluster.builder()
54+ .addContactPointsWithPorts(mainCcm.addressOfNode(2))
55+ .withAddressTranslator(mainCcm.addressTranslator())
5456 .withQueryOptions(nonDebouncingQueryOptions()).build();
5557 mainCluster.connect();
5658 waitForCountUpHosts(mainCluster, 2);
5759 // From that point, reconnections to node1 have been scheduled.
5860
5961 // Start another ccm that will reuse node1's address
60- otherCcm = CCMBridge.builder("other").withNodes(1).build();
62+ otherCcm = CCMBridge.builder()
63+ .withStoragePort(mainCcm.getStoragePort())
64+ .withThriftPort(mainCcm.getThriftPort())
65+ .withBinaryPort(mainCcm.getBinaryPort())
66+ .withNodes(1).build();
6167 otherCcm.waitForUp(1);
6268
6369 // Give the driver the time to notice the node is back up and try to connect to it.
@@ -68,18 +74,24 @@
6874
6975 @Test(groups = "long")
7076 public void should_ignore_recommissioned_node_on_control_connection_reconnect() throws Exception {
71- mainCcm = CCMBridge.builder("main").withNodes(2).build();
77+ mainCcm = CCMBridge.builder().withNodes(2).build();
7278 mainCcm.stop(1);
7379 mainCcm.waitForDown(1);
7480
7581 // Start the driver, the control connection will be on node2
76- mainCluster = Cluster.builder().addContactPoint(CCMBridge.IP_PREFIX + "2")
82+ mainCluster = Cluster.builder()
83+ .addContactPointsWithPorts(mainCcm.addressOfNode(2))
84+ .withAddressTranslator(mainCcm.addressTranslator())
7785 .withQueryOptions(nonDebouncingQueryOptions()).build();
7886 mainCluster.connect();
7987 waitForCountUpHosts(mainCluster, 1);
8088
8189 // Start another ccm that will reuse node1's address
82- otherCcm = CCMBridge.builder("other").withNodes(1).build();
90+ otherCcm = CCMBridge.builder()
91+ .withStoragePort(mainCcm.getStoragePort())
92+ .withThriftPort(mainCcm.getThriftPort())
93+ .withBinaryPort(mainCcm.getBinaryPort())
94+ .withNodes(1).build();
8395 otherCcm.waitForUp(1);
8496
8597 // Stop node2, the control connection gets defunct
@@ -93,15 +105,21 @@
93105 @Test(groups = "long")
94106 public void should_ignore_recommissioned_node_on_session_init() throws Exception {
95107 // Simulate the bug before starting the cluster
96- mainCcm = CCMBridge.builder("main").withNodes(2).build();
108+ mainCcm = CCMBridge.builder().withNodes(2).build();
97109 mainCcm.stop(1);
98110 mainCcm.waitForDown(1);
99111
100- otherCcm = CCMBridge.builder("other").withNodes(1).build();
112+ otherCcm = CCMBridge.builder()
113+ .withStoragePort(mainCcm.getStoragePort())
114+ .withThriftPort(mainCcm.getThriftPort())
115+ .withBinaryPort(mainCcm.getBinaryPort())
116+ .withNodes(1).build();
101117 otherCcm.waitForUp(1);
102118
103119 // Start the driver, it should only connect to node 2
104- mainCluster = Cluster.builder().addContactPoint(CCMBridge.IP_PREFIX + "2")
120+ mainCluster = Cluster.builder()
121+ .addContactPointsWithPorts(mainCcm.addressOfNode(2))
122+ .withAddressTranslator(mainCcm.addressTranslator())
105123 .withQueryOptions(nonDebouncingQueryOptions()).build();
106124
107125 // When we first initialize the Cluster, all hosts are marked UP
@@ -122,15 +140,22 @@
122140 @CassandraVersion(major = 2.0)
123141 public void should_ignore_node_that_does_not_support_protocol_version_on_session_init() throws Exception {
124142 // Simulate the bug before starting the cluster
125- mainCcm = CCMBridge.builder("main").withNodes(2).build();
143+ mainCcm = CCMBridge.builder().withNodes(2).build();
126144 mainCcm.stop(1);
127145 mainCcm.waitForDown(1);
128146
129- otherCcm = CCMBridge.builder("main").withNodes(1).withCassandraVersion("1.2.19").build();
147+ otherCcm = CCMBridge.builder().withNodes(1)
148+ .withStoragePort(mainCcm.getStoragePort())
149+ .withThriftPort(mainCcm.getThriftPort())
150+ .withBinaryPort(mainCcm.getBinaryPort())
151+ .withVersion("1.2.19")
152+ .build();
130153 otherCcm.waitForUp(1);
131154
132155 // Start the driver, it should only connect to node 2
133- mainCluster = Cluster.builder().addContactPoint(CCMBridge.IP_PREFIX + "2")
156+ mainCluster = Cluster.builder()
157+ .addContactPointsWithPorts(mainCcm.addressOfNode(2))
158+ .withAddressTranslator(mainCcm.addressTranslator())
134159 .withQueryOptions(nonDebouncingQueryOptions()).build();
135160
136161 // Create a session. This will try to open a pool to node 1 and find that it doesn't support protocol version.
@@ -151,7 +176,7 @@
151176 otherCcm = null;
152177 }
153178
154- @AfterMethod(groups = "long")
179+ @AfterMethod(groups = "long", alwaysRun = true)
155180 public void teardown() {
156181 if (mainCluster != null)
157182 mainCluster.close();
@@ -189,4 +214,4 @@
189214 TimeUnit.SECONDS.sleep(interval);
190215 }
191216 }
192-}
No newline at the end of the file
217+}
modified driver-core/src/test/java/com/datastax/driver/core/ReconnectionPolicyTest.java +84 −76
@@ -21,25 +21,37 @@
2121 import com.datastax.driver.core.policies.ReconnectionPolicy;
2222 import org.testng.annotations.Test;
2323
24+import static com.datastax.driver.core.CreateCCM.TestMode.PER_METHOD;
2425 import static org.testng.Assert.assertTrue;
2526 import static org.testng.Assert.fail;
2627
28+@CreateCCM(PER_METHOD)
29+@CCMConfig(dirtiesContext = true, createKeyspace = false)
30+@SuppressWarnings("unused")
2731 public class ReconnectionPolicyTest extends AbstractPoliciesTest {
2832
33+ private Cluster.Builder exponential() {
34+ return Cluster.builder().withReconnectionPolicy(new ExponentialReconnectionPolicy(2 * 1000, 5 * 60 * 1000));
35+ }
36+
37+ private Cluster.Builder constant() {
38+ return Cluster.builder().withReconnectionPolicy(new ConstantReconnectionPolicy(10 * 1000));
39+ }
40+
2941 /*
3042 * Test the ExponentialReconnectionPolicy.
3143 */
3244 @Test(groups = "long")
45+ @CCMConfig(clusterProvider = "exponential")
3346 public void exponentialReconnectionPolicyTest() throws Throwable {
34- Cluster.Builder builder = Cluster.builder().withReconnectionPolicy(new ExponentialReconnectionPolicy(2 * 1000, 5 * 60 * 1000));
3547
3648 // Ensure that ExponentialReconnectionPolicy is what we should be testing
37- if (!(builder.getConfiguration().getPolicies().getReconnectionPolicy() instanceof ExponentialReconnectionPolicy)) {
49+ if (!(cluster.getConfiguration().getPolicies().getReconnectionPolicy() instanceof ExponentialReconnectionPolicy)) {
3850 fail("Set policy does not match retrieved policy.");
3951 }
4052
4153 // Test basic getters
42- ExponentialReconnectionPolicy reconnectionPolicy = (ExponentialReconnectionPolicy) builder.getConfiguration().getPolicies().getReconnectionPolicy();
54+ ExponentialReconnectionPolicy reconnectionPolicy = (ExponentialReconnectionPolicy) cluster.getConfiguration().getPolicies().getReconnectionPolicy();
4355 assertTrue(reconnectionPolicy.getBaseDelayMs() == 2 * 1000);
4456 assertTrue(reconnectionPolicy.getMaxDelayMs() == 5 * 60 * 1000);
4557
@@ -48,24 +60,28 @@
4860 new ExponentialReconnectionPolicy(-1, 1);
4961 fail();
5062 } catch (IllegalArgumentException e) {
63+ //ok
5164 }
5265
5366 try {
5467 new ExponentialReconnectionPolicy(1, -1);
5568 fail();
5669 } catch (IllegalArgumentException e) {
70+ //ok
5771 }
5872
5973 try {
6074 new ExponentialReconnectionPolicy(-1, -1);
6175 fail();
6276 } catch (IllegalArgumentException e) {
77+ //ok
6378 }
6479
6580 try {
6681 new ExponentialReconnectionPolicy(2, 1);
6782 fail();
6883 } catch (IllegalArgumentException e) {
84+ //ok
6985 }
7086
7187 // Test nextDelays()
@@ -85,23 +101,23 @@
85101 long breakTime = 62; // time until next reconnection attempt
86102
87103 // TODO: Try to sort out variance
88- //reconnectionPolicyTest(builder, restartTime, retryTime, breakTime);
104+ //reconnectionPolicyTest(restartTime, retryTime, breakTime);
89105 }
90106
91107 /*
92108 * Test the ConstantReconnectionPolicy.
93109 */
94110 @Test(groups = "long")
111+ @CCMConfig(clusterProvider = "constant")
95112 public void constantReconnectionPolicyTest() throws Throwable {
96- Cluster.Builder builder = Cluster.builder().withReconnectionPolicy(new ConstantReconnectionPolicy(10 * 1000));
97113
98114 // Ensure that ConstantReconnectionPolicy is what we should be testing
99- if (!(builder.getConfiguration().getPolicies().getReconnectionPolicy() instanceof ConstantReconnectionPolicy)) {
115+ if (!(cluster.getConfiguration().getPolicies().getReconnectionPolicy() instanceof ConstantReconnectionPolicy)) {
100116 fail("Set policy does not match retrieved policy.");
101117 }
102118
103119 // Test basic getters
104- ConstantReconnectionPolicy reconnectionPolicy = (ConstantReconnectionPolicy) builder.getConfiguration().getPolicies().getReconnectionPolicy();
120+ ConstantReconnectionPolicy reconnectionPolicy = (ConstantReconnectionPolicy) cluster.getConfiguration().getPolicies().getReconnectionPolicy();
105121 assertTrue(reconnectionPolicy.getConstantDelayMs() == 10 * 1000);
106122
107123 // Test erroneous instantiations
@@ -109,6 +125,7 @@
109125 new ConstantReconnectionPolicy(-1);
110126 fail();
111127 } catch (IllegalArgumentException e) {
128+ //ok
112129 }
113130
114131 // Test nextDelays()
@@ -125,46 +142,87 @@
125142 long breakTime = 10; // time until next reconnection attempt
126143
127144 // TODO: Try to sort out variance
128- //reconnectionPolicyTest(builder, restartTime, retryTime, breakTime);
145+ //reconnectionPolicyTest(restartTime, retryTime, breakTime);
129146 }
130147
131- public void reconnectionPolicyTest(Cluster.Builder builder, long restartTime, long retryTime, long breakTime) throws Throwable {
132- CCMBridge.CCMCluster c = CCMBridge.buildCluster(1, builder);
133-
148+ public void reconnectionPolicyTest(long restartTime, long retryTime, long breakTime) throws Throwable {
149+ createSchema(1);
150+ init(12);
151+ query(12);
152+
153+ // Ensure a basic test works
154+ assertQueried(TestUtils.IP_PREFIX + '1', 12);
155+ resetCoordinators();
156+ ccm.forceStop(1);
157+
158+ // Start timing and ensure that the node is down
159+ long startTime = 0;
134160 try {
135- createSchema(c.session, 1);
136- init(c, 12);
137- query(c, 12);
138-
139- // Ensure a basic test works
140- assertQueried(CCMBridge.IP_PREFIX + '1', 12);
161+ startTime = System.nanoTime() / 1000000000;
162+ query(12);
163+ fail("Test race condition where node has not shut off quickly enough.");
164+ } catch (NoHostAvailableException e) {
165+ //ok
166+ }
167+
168+ long thisTime;
169+ boolean restarted = false;
170+ while (true) {
171+ thisTime = System.nanoTime() / 1000000000;
172+
173+ // Restart node at restartTime
174+ if (!restarted && thisTime - startTime > restartTime) {
175+ ccm.start(1);
176+ restarted = true;
177+ }
178+
179+ // Continue testing queries each second
180+ try {
181+ query(12);
182+ assertQueried(TestUtils.IP_PREFIX + '1', 12);
183+ resetCoordinators();
184+
185+ // Ensure the time when the query completes successfully is what was expected
186+ assertTrue(retryTime - 2 < thisTime - startTime && thisTime - startTime < retryTime + 2, String.format("Waited %s seconds instead an expected %s seconds wait", thisTime - startTime, retryTime));
187+ } catch (NoHostAvailableException e) {
188+ Thread.sleep(1000);
189+ continue;
190+ }
191+
192+ Thread.sleep(breakTime);
193+
194+ // The the same query once more, just to be sure
195+ query(12);
196+ assertQueried(TestUtils.IP_PREFIX + '1', 12);
141197 resetCoordinators();
142- c.cassandraCluster.forceStop(1);
198+
199+ // Ensure the reconnection times reset
200+ ccm.forceStop(1);
143201
144202 // Start timing and ensure that the node is down
145- long startTime = 0;
203+ startTime = 0;
146204 try {
147205 startTime = System.nanoTime() / 1000000000;
148- query(c, 12);
206+ query(12);
149207 fail("Test race condition where node has not shut off quickly enough.");
150208 } catch (NoHostAvailableException e) {
209+ //ok
151210 }
152211
153- long thisTime;
154- boolean restarted = false;
212+ restarted = false;
155213 while (true) {
156214 thisTime = System.nanoTime() / 1000000000;
157215
158216 // Restart node at restartTime
159217 if (!restarted && thisTime - startTime > restartTime) {
160- c.cassandraCluster.start(1);
218+ ccm.start(1);
161219 restarted = true;
162220 }
163221
164222 // Continue testing queries each second
165223 try {
166- query(c, 12);
167- assertQueried(CCMBridge.IP_PREFIX + '1', 12);
224+ query(12);
225+ assertQueried(TestUtils.IP_PREFIX + '1', 12);
168226 resetCoordinators();
169227
170228 // Ensure the time when the query completes successfully is what was expected
@@ -173,59 +231,9 @@
173231 Thread.sleep(1000);
174232 continue;
175233 }
176-
177- Thread.sleep(breakTime);
178-
179- // The the same query once more, just to be sure
180- query(c, 12);
181- assertQueried(CCMBridge.IP_PREFIX + '1', 12);
182- resetCoordinators();
183-
184- // Ensure the reconnection times reset
185- c.cassandraCluster.forceStop(1);
186-
187- // Start timing and ensure that the node is down
188- startTime = 0;
189- try {
190- startTime = System.nanoTime() / 1000000000;
191- query(c, 12);
192- fail("Test race condition where node has not shut off quickly enough.");
193- } catch (NoHostAvailableException e) {
194- }
195-
196- restarted = false;
197- while (true) {
198- thisTime = System.nanoTime() / 1000000000;
199-
200- // Restart node at restartTime
201- if (!restarted && thisTime - startTime > restartTime) {
202- c.cassandraCluster.start(1);
203- restarted = true;
204- }
205-
206- // Continue testing queries each second
207- try {
208- query(c, 12);
209- assertQueried(CCMBridge.IP_PREFIX + '1', 12);
210- resetCoordinators();
211-
212- // Ensure the time when the query completes successfully is what was expected
213- assertTrue(retryTime - 2 < thisTime - startTime && thisTime - startTime < retryTime + 2, String.format("Waited %s seconds instead an expected %s seconds wait", thisTime - startTime, retryTime));
214- } catch (NoHostAvailableException e) {
215- Thread.sleep(1000);
216- continue;
217- }
218- break;
219- }
220234 break;
221235 }
222-
223- } catch (Throwable e) {
224- c.errorOut();
225- throw e;
226- } finally {
227- resetCoordinators();
228- c.discard();
236+ break;
229237 }
230238 }
231239 }
modified driver-core/src/test/java/com/datastax/driver/core/ReconnectionTest.java +181 −223
@@ -21,6 +21,7 @@
2121 import com.datastax.driver.core.policies.LoadBalancingPolicy;
2222 import com.datastax.driver.core.policies.RoundRobinPolicy;
2323 import com.google.common.util.concurrent.ListenableFuture;
24+import com.google.common.util.concurrent.Uninterruptibles;
2425 import org.testng.annotations.Test;
2526
2627 import java.io.IOException;
@@ -33,266 +34,223 @@
3334 import java.util.concurrent.atomic.AtomicInteger;
3435
3536 import static com.datastax.driver.core.Assertions.assertThat;
37+import static com.datastax.driver.core.CreateCCM.TestMode.PER_METHOD;
3638 import static java.util.concurrent.TimeUnit.SECONDS;
3739 import static org.mockito.Mockito.*;
3840
3941 /**
4042 * Scenarios where a Cluster loses connection to a host and reconnects.
4143 */
42-public class ReconnectionTest {
44+@CreateCCM(PER_METHOD)
45+public class ReconnectionTest extends CCMTestsSupport {
4346
47+ private final int reconnectionDelayMillis = 1000;
48+
49+ @CCMConfig(dirtiesContext = true, numberOfNodes = 2, createCluster = false)
4450 @Test(groups = "long")
4551 public void should_reconnect_after_full_connectivity_loss() throws InterruptedException {
46- CCMBridge ccm = null;
47- Cluster cluster = null;
48- try {
49- ccm = CCMBridge.builder("test").withNodes(2).build();
50- int reconnectionDelay = 1000;
51- cluster = Cluster.builder()
52- .addContactPoint(CCMBridge.ipOfNode(1))
53- .withReconnectionPolicy(new ConstantReconnectionPolicy(reconnectionDelay))
54- .build();
55- cluster.connect();
56-
57- assertThat(cluster).usesControlHost(1);
58-
59- // Stop all nodes. We won't get notifications anymore, so the only mechanism to
60- // reconnect is the background reconnection attempts.
61- ccm.stop(2);
62- ccm.stop(1);
63-
64- ccm.waitForDown(2);
65- ccm.start(2);
66- ccm.waitForUp(2);
67-
68- assertThat(cluster).host(2).comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS * 2, SECONDS);
69-
70- // Give the control connection a few moments to reconnect
71- TimeUnit.MILLISECONDS.sleep(reconnectionDelay * 2);
72- assertThat(cluster).usesControlHost(2);
73- } finally {
74- if (cluster != null)
75- cluster.close();
76- if (ccm != null)
77- ccm.remove();
78- }
52+ Cluster cluster = register(Cluster.builder()
53+ .addContactPointsWithPorts(ccm.addressOfNode(1))
54+ .withAddressTranslator(ccm.addressTranslator())
55+ .withReconnectionPolicy(new ConstantReconnectionPolicy(reconnectionDelayMillis))
56+ .build());
57+ cluster.connect();
58+
59+ assertThat(cluster).usesControlHost(1);
60+
61+ // Stop all nodes. We won't get notifications anymore, so the only mechanism to
62+ // reconnect is the background reconnection attempts.
63+ ccm.stop(2);
64+ ccm.stop(1);
65+
66+ ccm.waitForDown(2);
67+ ccm.start(2);
68+ ccm.waitForUp(2);
69+
70+ assertThat(cluster).host(2).comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS * 2, SECONDS);
71+
72+ // Give the control connection a few moments to reconnect
73+ TimeUnit.MILLISECONDS.sleep(reconnectionDelayMillis * 2);
74+ assertThat(cluster).usesControlHost(2);
7975 }
8076
77+ @CCMConfig(
78+ dirtiesContext = true,
79+ config = "authenticator:PasswordAuthenticator",
80+ jvmArgs = "-Dcassandra.superuser_setup_delay_ms=0",
81+ createCluster = false)
8182 @Test(groups = "long")
8283 public void should_keep_reconnecting_on_authentication_error() throws InterruptedException {
83- CCMBridge ccm = null;
84- Cluster cluster = null;
85- try {
86- ccm = CCMBridge.builder("test")
87- .withCassandraConfiguration("authenticator", "PasswordAuthenticator") // default credentials: cassandra / cassandra
88- .notStarted()
89- .build();
90- ccm.start(1, "-Dcassandra.superuser_setup_delay_ms=0");
91-
92- CountingAuthProvider authProvider = new CountingAuthProvider("cassandra", "cassandra");
93- int reconnectionDelayMs = 1000;
94- CountingReconnectionPolicy reconnectionPolicy = new CountingReconnectionPolicy(new ConstantReconnectionPolicy(reconnectionDelayMs));
95-
96- cluster = Cluster.builder()
97- .addContactPoint(CCMBridge.ipOfNode(1))
98- // Start with the correct auth so that we can initialize the server
99- .withAuthProvider(authProvider)
100- .withReconnectionPolicy(reconnectionPolicy)
101- .build();
102-
103- cluster.init();
104- assertThat(cluster).usesControlHost(1);
105-
106- // Stop the server, set wrong credentials and restart
107- ccm.stop(1);
108- ccm.waitForDown(1);
109- authProvider.setPassword("wrongPassword");
110- ccm.start(1);
111- ccm.waitForUp(1);
112-
113- // Wait a few iterations to ensure that our authProvider has returned the wrong credentials at least once
114- // NB: authentication errors show up in the logs
115- int initialCount = authProvider.count.get();
116- int iterations = 0, maxIterations = 12; // make sure we don't wait indefinitely
117- do {
118- iterations += 1;
119- TimeUnit.SECONDS.sleep(5);
120- } while (iterations < maxIterations && authProvider.count.get() <= initialCount);
121- assertThat(iterations).isLessThan(maxIterations);
122-
123- // Fix the credentials
124- authProvider.setPassword("cassandra");
125-
126- // The driver should eventually reconnect to the node
127- assertThat(cluster).host(1).comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS * 2, SECONDS);
128- } finally {
129- if (cluster != null)
130- cluster.close();
131- if (ccm != null)
132- ccm.remove();
84+ // For C* 1.2, sleep before attempting to connect as there is a small delay between
85+ // user being created.
86+ if (ccm.getVersion().getMajor() < 2) {
87+ Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
13388 }
89+ CountingReconnectionPolicy reconnectionPolicy = new CountingReconnectionPolicy(new ConstantReconnectionPolicy(reconnectionDelayMillis));
90+ CountingAuthProvider authProvider = new CountingAuthProvider("cassandra", "cassandra");
91+ Cluster cluster = register(Cluster.builder()
92+ .addContactPointsWithPorts(ccm.addressOfNode(1))
93+ .withAddressTranslator(ccm.addressTranslator())
94+ // Start with the correct auth so that we can initialize the server
95+ .withAuthProvider(authProvider)
96+ .withReconnectionPolicy(reconnectionPolicy)
97+ .build());
98+
99+ cluster.init();
100+ assertThat(cluster).usesControlHost(1);
101+
102+ // Stop the server, set wrong credentials and restart
103+ ccm.stop(1);
104+ ccm.waitForDown(1);
105+ authProvider.setPassword("wrongPassword");
106+ ccm.start(1);
107+ ccm.waitForUp(1);
108+
109+ // Wait a few iterations to ensure that our authProvider has returned the wrong credentials at least once
110+ // NB: authentication errors show up in the logs
111+ int initialCount = authProvider.count.get();
112+ int iterations = 0, maxIterations = 12; // make sure we don't wait indefinitely
113+ do {
114+ iterations += 1;
115+ TimeUnit.SECONDS.sleep(5);
116+ } while (iterations < maxIterations && authProvider.count.get() <= initialCount);
117+ assertThat(iterations).isLessThan(maxIterations);
118+
119+ // Fix the credentials
120+ authProvider.setPassword("cassandra");
121+
122+ // The driver should eventually reconnect to the node
123+ assertThat(cluster).host(1).comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS * 2, SECONDS);
134124 }
135125
126+ @CCMConfig(dirtiesContext = true, numberOfNodes = 2, createCluster = false)
136127 @Test(groups = "long")
137128 public void should_cancel_reconnection_attempts() throws InterruptedException {
138- CCMBridge ccm = null;
139- Cluster cluster = null;
140-
141- long reconnectionDelayMillis = 1000;
129+ // Stop a node and cancel the reconnection attempts to it
142130 CountingReconnectionPolicy reconnectionPolicy = new CountingReconnectionPolicy(new ConstantReconnectionPolicy(reconnectionDelayMillis));
143131
144- try {
145- ccm = CCMBridge.builder("test").withNodes(2).build();
146- cluster = Cluster.builder()
147- .addContactPoint(CCMBridge.ipOfNode(1))
148- .withReconnectionPolicy(reconnectionPolicy)
149- .build();
150- cluster.connect();
151-
152- // Stop a node and cancel the reconnection attempts to it
153- ccm.stop(2);
154- Host host2 = TestUtils.findHost(cluster, 2);
155- host2.getReconnectionAttemptFuture().cancel(false);
156-
157- // The reconnection count should not vary over time anymore
158- int initialCount = reconnectionPolicy.count.get();
159- TimeUnit.MILLISECONDS.sleep(reconnectionDelayMillis * 2);
160- assertThat(reconnectionPolicy.count.get()).isEqualTo(initialCount);
161-
162- // Restart the node, which will trigger an UP notification
163- ccm.start(2);
164- ccm.waitForUp(2);
165-
166- // The driver should now see the node as UP again
167- assertThat(cluster).host(2).comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS * 2, SECONDS);
168-
169- } finally {
170- if (cluster != null)
171- cluster.close();
172- if (ccm != null)
173- ccm.remove();
174- }
132+ Cluster cluster = register(Cluster.builder()
133+ .addContactPointsWithPorts(ccm.addressOfNode(1))
134+ .withAddressTranslator(ccm.addressTranslator())
135+ .withReconnectionPolicy(reconnectionPolicy).build());
136+ cluster.connect();
137+
138+ // Stop a node and cancel the reconnection attempts to it
139+ ccm.stop(2);
140+ Host host2 = TestUtils.findHost(cluster, 2);
141+ host2.getReconnectionAttemptFuture().cancel(false);
142+
143+ // The reconnection count should not vary over time anymore
144+ int initialCount = reconnectionPolicy.count.get();
145+ TimeUnit.MILLISECONDS.sleep(reconnectionDelayMillis * 2);
146+ assertThat(reconnectionPolicy.count.get()).isEqualTo(initialCount);
147+
148+ // Restart the node, which will trigger an UP notification
149+ ccm.start(2);
150+ ccm.waitForUp(2);
151+
152+ // The driver should now see the node as UP again
153+ assertThat(cluster).host(2).comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS * 2, SECONDS);
175154 }
176155
156+ @CCMConfig(dirtiesContext = true, createCluster = false)
177157 @Test(groups = "long")
178158 public void should_trigger_one_time_reconnect() throws InterruptedException, IOException {
179- CCMBridge ccm = null;
180- Cluster cluster = null;
181-
182- long reconnectionDelayMillis = 1000;
183159 TogglabePolicy loadBalancingPolicy = new TogglabePolicy(new RoundRobinPolicy());
184-
185- try {
186- ccm = CCMBridge.builder("test").withNodes(1).build();
187- cluster = Cluster.builder()
188- .addContactPoint(CCMBridge.ipOfNode(1))
189- .withLoadBalancingPolicy(loadBalancingPolicy)
190- .withReconnectionPolicy(new ConstantReconnectionPolicy(reconnectionDelayMillis))
191- .build();
192- cluster.connect();
193-
194- // Tweak the LBP so that the control connection never reconnects, otherwise
195- // it would interfere with the rest of the test (this is a bit of a hack)
196- loadBalancingPolicy.returnEmptyQueryPlan = true;
197-
198- // Stop the node, ignore it and cancel reconnection attempts to it
199- ccm.stop(1);
200- ccm.waitForDown(1);
201- assertThat(cluster).host(1).goesDownWithin(20, SECONDS);
202- Host host1 = TestUtils.findHost(cluster, 1);
203- loadBalancingPolicy.setDistance(TestUtils.findHost(cluster, 1), HostDistance.IGNORED);
204- ListenableFuture<?> reconnectionAttemptFuture = host1.getReconnectionAttemptFuture();
205- if (reconnectionAttemptFuture != null)
206- reconnectionAttemptFuture.cancel(false);
207-
208- // Trigger a one-time reconnection attempt (this will fail)
209- host1.tryReconnectOnce();
210-
211- // Wait for a few reconnection cycles before checking
212- TimeUnit.MILLISECONDS.sleep(reconnectionDelayMillis * 2);
213- assertThat(cluster).host(1).hasState(State.DOWN);
214-
215- // Restart the node (this will not trigger an UP notification thanks to our
216- // hack to disable the control connection reconnects). The host should stay
217- // down for the driver.
218- ccm.start(1);
219- ccm.waitForUp(1);
220- assertThat(cluster).host(1).hasState(State.DOWN);
221-
222- TimeUnit.SECONDS.sleep(Cluster.NEW_NODE_DELAY_SECONDS);
223- assertThat(cluster).host(1).hasState(State.DOWN);
224-
225- // Trigger another one-time reconnection attempt (this will succeed). The
226- // host should be back up.
227- host1.tryReconnectOnce();
228- assertThat(cluster).host(1).comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS * 2, SECONDS);
229- } finally {
230- if (cluster != null)
231- cluster.close();
232- if (ccm != null)
233- ccm.remove();
234- }
160+ Cluster cluster = register(Cluster.builder()
161+ .addContactPointsWithPorts(ccm.addressOfNode(1))
162+ .withAddressTranslator(ccm.addressTranslator())
163+ .withLoadBalancingPolicy(loadBalancingPolicy)
164+ .withReconnectionPolicy(new ConstantReconnectionPolicy(reconnectionDelayMillis))
165+ .build());
166+ cluster.connect();
167+
168+ // Tweak the LBP so that the control connection never reconnects, otherwise
169+ // it would interfere with the rest of the test (this is a bit of a hack)
170+ loadBalancingPolicy.returnEmptyQueryPlan = true;
171+
172+ // Stop the node, ignore it and cancel reconnection attempts to it
173+ ccm.stop(1);
174+ ccm.waitForDown(1);
175+ assertThat(cluster).host(1).goesDownWithin(20, SECONDS);
176+ Host host1 = TestUtils.findHost(cluster, 1);
177+ loadBalancingPolicy.setDistance(TestUtils.findHost(cluster, 1), HostDistance.IGNORED);
178+ ListenableFuture<?> reconnectionAttemptFuture = host1.getReconnectionAttemptFuture();
179+ if (reconnectionAttemptFuture != null)
180+ reconnectionAttemptFuture.cancel(false);
181+
182+ // Trigger a one-time reconnection attempt (this will fail)
183+ host1.tryReconnectOnce();
184+
185+ // Wait for a few reconnection cycles before checking
186+ TimeUnit.MILLISECONDS.sleep(reconnectionDelayMillis * 2);
187+ assertThat(cluster).host(1).hasState(State.DOWN);
188+
189+ // Restart the node (this will not trigger an UP notification thanks to our
190+ // hack to disable the control connection reconnects). The host should stay
191+ // down for the driver.
192+ ccm.start(1);
193+ ccm.waitForUp(1);
194+ assertThat(cluster).host(1).hasState(State.DOWN);
195+
196+ TimeUnit.SECONDS.sleep(Cluster.NEW_NODE_DELAY_SECONDS);
197+ assertThat(cluster).host(1).hasState(State.DOWN);
198+
199+ // Trigger another one-time reconnection attempt (this will succeed). The
200+ // host should be back up.
201+ host1.tryReconnectOnce();
202+ assertThat(cluster).host(1).comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS * 2, SECONDS);
235203 }
236204
237205 /**
238206 * The connection established by a successful reconnection attempt should be reused in one of the
239207 * connection pools (JAVA-505).
240208 */
209+ @CCMConfig(dirtiesContext = true, createCluster = false)
241210 @Test(groups = "long")
242211 public void should_use_connection_from_reconnection_in_pool() {
243- CCMBridge ccm = null;
244- Cluster cluster = null;
245-
246212 TogglabePolicy loadBalancingPolicy = new TogglabePolicy(new RoundRobinPolicy());
247213
248214 // Spy SocketOptions.getKeepAlive to count how many connections were instantiated.
249215 SocketOptions socketOptions = spy(new SocketOptions());
250-
251- try {
252- ccm = CCMBridge.builder("test").withNodes(1).build();
253- cluster = Cluster.builder()
254- .addContactPoint(CCMBridge.ipOfNode(1))
255- .withReconnectionPolicy(new ConstantReconnectionPolicy(5000))
256- .withLoadBalancingPolicy(loadBalancingPolicy)
257- .withSocketOptions(socketOptions)
258- .withProtocolVersion(TestUtils.getDesiredProtocolVersion())
259- .build();
260- // Create two sessions to have multiple pools
261- cluster.connect();
262- cluster.connect();
263-
264- int corePoolSize = TestUtils.numberOfLocalCoreConnections(cluster);
265-
266- // Right after init, 1 connection has been opened by the control connection, and the core size for each pool.
267- verify(socketOptions, times(1 + corePoolSize * 2)).getKeepAlive();
268-
269- // Tweak the LBP so that the control connection never reconnects. This makes it easier
270- // to reason about the number of connection attempts.
271- loadBalancingPolicy.returnEmptyQueryPlan = true;
272-
273- // Stop the node and cancel the reconnection attempts to it
274- ccm.stop(1);
275- ccm.waitForDown(1);
276- assertThat(cluster).host(1).goesDownWithin(20, SECONDS);
277- Host host1 = TestUtils.findHost(cluster, 1);
278- host1.getReconnectionAttemptFuture().cancel(false);
279-
280- ccm.start(1);
281- ccm.waitForUp(1);
282-
283- // Reset the spy and count the number of connections attempts for 1 reconnect
284- reset(socketOptions);
285- host1.tryReconnectOnce();
286- assertThat(cluster).host(1).comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS * 2, SECONDS);
287- // Expect 1 connection from the reconnection attempt 3 for the pools (we need 4
288- // but the one from the reconnection attempt gets reused).
289- verify(socketOptions, times(corePoolSize * 2)).getKeepAlive();
290- } finally {
291- if (cluster != null)
292- cluster.close();
293- if (ccm != null)
294- ccm.remove();
295- }
216+ Cluster cluster = register(Cluster.builder()
217+ .addContactPointsWithPorts(ccm.addressOfNode(1))
218+ .withAddressTranslator(ccm.addressTranslator())
219+ .withReconnectionPolicy(new ConstantReconnectionPolicy(5000))
220+ .withLoadBalancingPolicy(loadBalancingPolicy)
221+ .withSocketOptions(socketOptions)
222+ .withProtocolVersion(TestUtils.getDesiredProtocolVersion())
223+ .build());
224+ // Create two sessions to have multiple pools
225+ cluster.connect();
226+ cluster.connect();
227+
228+ int corePoolSize = TestUtils.numberOfLocalCoreConnections(cluster);
229+
230+ // Right after init, 1 connection has been opened by the control connection, and the core size for each pool.
231+ verify(socketOptions, times(1 + corePoolSize * 2)).getKeepAlive();
232+
233+ // Tweak the LBP so that the control connection never reconnects. This makes it easier
234+ // to reason about the number of connection attempts.
235+ loadBalancingPolicy.returnEmptyQueryPlan = true;
236+
237+ // Stop the node and cancel the reconnection attempts to it
238+ ccm.stop(1);
239+ ccm.waitForDown(1);
240+ assertThat(cluster).host(1).goesDownWithin(20, SECONDS);
241+ Host host1 = TestUtils.findHost(cluster, 1);
242+ host1.getReconnectionAttemptFuture().cancel(false);
243+
244+ ccm.start(1);
245+ ccm.waitForUp(1);
246+
247+ // Reset the spy and count the number of connections attempts for 1 reconnect
248+ reset(socketOptions);
249+ host1.tryReconnectOnce();
250+ assertThat(cluster).host(1).comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS * 2, SECONDS);
251+ // Expect 1 connection from the reconnection attempt 3 for the pools (we need 4
252+ // but the one from the reconnection attempt gets reused).
253+ verify(socketOptions, times(corePoolSize * 2)).getKeepAlive();
296254 }
297255
298256 /**
modified driver-core/src/test/java/com/datastax/driver/core/RefreshConnectedHostTest.java +67 −77
@@ -25,88 +25,78 @@
2525 import static com.datastax.driver.core.Assertions.assertThat;
2626 import static java.util.concurrent.TimeUnit.SECONDS;
2727
28-public class RefreshConnectedHostTest {
28+@CCMConfig(
29+ dirtiesContext = true,
30+ numberOfNodes = 2,
31+ createCluster = false
32+)
33+public class RefreshConnectedHostTest extends CCMTestsSupport {
2934
3035 /**
3136 * Tests {@link PoolingOptions#refreshConnectedHost(Host)} through a custom load balancing policy.
3237 */
3338 @Test(groups = "long")
3439 public void should_refresh_single_connected_host() {
35- CCMBridge ccm = null;
36- Cluster cluster = null;
37- try {
38- // This will make the driver use at most 2 hosts, the others will be ignored
39- LimitingLoadBalancingPolicy loadBalancingPolicy = new LimitingLoadBalancingPolicy(new RoundRobinPolicy(), 2, 1);
40-
41- // Setup a 3-host cluster, start only two hosts so that we know in advance which ones the policy will use
42- ccm = CCMBridge.builder("test").withNodes(3).notStarted().build();
43- ccm.start(1);
44- ccm.start(2);
45- ccm.waitForUp(1);
46- ccm.waitForUp(2);
47-
48- PoolingOptions poolingOptions = Mockito.spy(new PoolingOptions());
49- cluster = Cluster.builder()
50- .addContactPoint(CCMBridge.ipOfNode(1))
51- .withPoolingOptions(poolingOptions)
52- .withLoadBalancingPolicy(loadBalancingPolicy)
53- .withReconnectionPolicy(new ConstantReconnectionPolicy(1000))
54- .withQueryOptions(TestUtils.nonDebouncingQueryOptions())
55- .build();
56-
57- Session session = cluster.connect();
58-
59- assertThat(cluster).usesControlHost(1);
60- assertThat(cluster).host(1)
61- .hasState(State.UP)
62- .isAtDistance(HostDistance.LOCAL);
63- // Wait for the node to be up, because apparently on Jenkins it's still only ADDED when we reach this line
64- // Waiting for NEW_NODE_DELAY_SECONDS+1 allows the driver to create a connection pool and mark the node up
65- assertThat(cluster).host(2)
66- .comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS + 1, SECONDS)
67- .isAtDistance(HostDistance.LOCAL);
68-
69- // Bring host 3 up, its presence should be acknowledged but it should be ignored
70- ccm.start(3);
71- ccm.waitForUp(3);
72-
73- assertThat(cluster).host(1)
74- .hasState(State.UP)
75- .isAtDistance(HostDistance.LOCAL);
76- assertThat(cluster).host(2)
77- .hasState(State.UP)
78- .isAtDistance(HostDistance.LOCAL);
79-
80- // Ensure that the host is added to the Cluster.
81- assertThat(cluster).host(3)
82- .comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS + 1, SECONDS)
83- .isAtDistance(HostDistance.IGNORED);
84- assertThat(session).hasNoPoolFor(3);
85-
86- // Kill host 2, host 3 should take its place
87- ccm.stop(2);
88- TestUtils.waitFor(CCMBridge.ipOfNode(3), cluster);
89-
90- assertThat(cluster).host(1)
91- .hasState(State.UP)
92- .isAtDistance(HostDistance.LOCAL);
93- assertThat(cluster).host(2)
94- .hasState(State.DOWN);
95- assertThat(cluster).host(3)
96- .hasState(State.UP)
97- .isAtDistance(HostDistance.LOCAL);
98- assertThat(session).hasPoolFor(3);
99-
100- // This is when refreshConnectedHost should have been invoked, it triggers pool creation when
101- // we switch the node from IGNORED to UP:
102- Mockito.verify(poolingOptions)
103- .refreshConnectedHost(TestUtils.findHost(cluster, 3));
104-
105- } finally {
106- if (cluster != null)
107- cluster.close();
108- if (ccm != null)
109- ccm.remove();
110- }
40+ // This will make the driver use at most 2 hosts, the others will be ignored
41+ LimitingLoadBalancingPolicy loadBalancingPolicy = new LimitingLoadBalancingPolicy(new RoundRobinPolicy(), 2, 1);
42+
43+ PoolingOptions poolingOptions = Mockito.spy(new PoolingOptions());
44+ cluster = register(Cluster.builder()
45+ .addContactPointsWithPorts(ccm.addressOfNode(1))
46+ .withAddressTranslator(ccm.addressTranslator())
47+ .withPoolingOptions(poolingOptions)
48+ .withLoadBalancingPolicy(loadBalancingPolicy)
49+ .withReconnectionPolicy(new ConstantReconnectionPolicy(1000))
50+ .withQueryOptions(TestUtils.nonDebouncingQueryOptions())
51+ .build());
52+
53+ Session session = cluster.connect();
54+
55+ assertThat(cluster).usesControlHost(1);
56+ assertThat(cluster).host(1)
57+ .hasState(State.UP)
58+ .isAtDistance(HostDistance.LOCAL);
59+ // Wait for the node to be up, because apparently on Jenkins it's still only ADDED when we reach this line
60+ // Waiting for NEW_NODE_DELAY_SECONDS+1 allows the driver to create a connection pool and mark the node up
61+ assertThat(cluster).host(2)
62+ .comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS + 1, SECONDS)
63+ .isAtDistance(HostDistance.LOCAL);
64+
65+ // Add and bring host 3 up, its presence should be acknowledged but it should be ignored
66+ ccm.add(3);
67+ ccm.start(3);
68+ ccm.waitForUp(3);
69+
70+ assertThat(cluster).host(1)
71+ .hasState(State.UP)
72+ .isAtDistance(HostDistance.LOCAL);
73+ assertThat(cluster).host(2)
74+ .hasState(State.UP)
75+ .isAtDistance(HostDistance.LOCAL);
76+
77+ // Ensure that the host is added to the Cluster.
78+ assertThat(cluster).host(3)
79+ .comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS + 1, SECONDS)
80+ .isAtDistance(HostDistance.IGNORED);
81+ assertThat(session).hasNoPoolFor(3);
82+
83+ // Kill host 2, host 3 should take its place
84+ ccm.stop(2);
85+ TestUtils.waitFor(TestUtils.ipOfNode(3), cluster);
86+
87+ assertThat(cluster).host(1)
88+ .hasState(State.UP)
89+ .isAtDistance(HostDistance.LOCAL);
90+ assertThat(cluster).host(2)
91+ .hasState(State.DOWN);
92+ assertThat(cluster).host(3)
93+ .hasState(State.UP)
94+ .isAtDistance(HostDistance.LOCAL);
95+ assertThat(session).hasPoolFor(3);
96+
97+ // This is when refreshConnectedHost should have been invoked, it triggers pool creation when
98+ // we switch the node from IGNORED to UP:
99+ Mockito.verify(poolingOptions)
100+ .refreshConnectedHost(TestUtils.findHost(cluster, 3));
111101 }
112102 }
modified driver-core/src/test/java/com/datastax/driver/core/RequestHandlerTest.java +3 −3
@@ -29,7 +29,7 @@
2929
3030 @Test(groups = "long")
3131 public void should_handle_race_between_response_and_cancellation() {
32- Scassandra scassandra = TestUtils.createScassandraServer();
32+ final Scassandra scassandra = TestUtils.createScassandraServer();
3333 Cluster cluster = null;
3434
3535 try {
@@ -44,9 +44,9 @@
4444 );
4545
4646 cluster = Cluster.builder()
47- .addContactPoint("127.0.0.1")
47+ .addContactPoint(TestUtils.ipOfNode(1))
4848 .withPort(scassandra.getBinaryPort())
49- // Scassandra does not support V3 nor V4 yet, and V4 may cause the server to crash
49+ // Scassandra does not support V3 nor V4 yet, and V4 may cause the server to crash
5050 .withProtocolVersion(ProtocolVersion.V2)
5151 .withPoolingOptions(new PoolingOptions()
5252 .setCoreConnectionsPerHost(HostDistance.LOCAL, 1)
modified driver-core/src/test/java/com/datastax/driver/core/SSLAuthenticatedEncryptionTest.java +19 −10
@@ -18,11 +18,10 @@
1818 import com.datastax.driver.core.exceptions.NoHostAvailableException;
1919 import org.testng.annotations.Test;
2020
21-public class SSLAuthenticatedEncryptionTest extends SSLTestBase {
21+import static com.datastax.driver.core.CCMBridge.*;
2222
23- public SSLAuthenticatedEncryptionTest() {
24- super(true);
25- }
23+@CCMConfig(auth = true)
24+public class SSLAuthenticatedEncryptionTest extends SSLTestBase {
2625
2726 /**
2827 * <p>
@@ -64,11 +63,21 @@
6463 */
6564 @Test(groups = "isolated")
6665 public void should_use_system_properties_with_default_ssl_options() throws Exception {
67- System.setProperty("javax.net.ssl.keyStore", CCMBridge.DEFAULT_CLIENT_KEYSTORE_FILE.getAbsolutePath());
68- System.setProperty("javax.net.ssl.keyStorePassword", CCMBridge.DEFAULT_CLIENT_KEYSTORE_PASSWORD);
69- System.setProperty("javax.net.ssl.trustStore", CCMBridge.DEFAULT_CLIENT_TRUSTSTORE_FILE.getAbsolutePath());
70- System.setProperty("javax.net.ssl.trustStorePassword", CCMBridge.DEFAULT_CLIENT_TRUSTSTORE_PASSWORD);
71-
72- connectWithSSL();
66+ System.setProperty("javax.net.ssl.keyStore", DEFAULT_CLIENT_KEYSTORE_FILE.getAbsolutePath());
67+ System.setProperty("javax.net.ssl.keyStorePassword", DEFAULT_CLIENT_KEYSTORE_PASSWORD);
68+ System.setProperty("javax.net.ssl.trustStore", DEFAULT_CLIENT_TRUSTSTORE_FILE.getAbsolutePath());
69+ System.setProperty("javax.net.ssl.trustStorePassword", DEFAULT_CLIENT_TRUSTSTORE_PASSWORD);
70+ try {
71+ connectWithSSL();
72+ } finally {
73+ try {
74+ System.clearProperty("javax.net.ssl.keyStore");
75+ System.clearProperty("javax.net.ssl.keyStorePassword");
76+ System.clearProperty("javax.net.ssl.trustStore");
77+ System.clearProperty("javax.net.ssl.trustStorePassword");
78+ } catch (SecurityException e) {
79+ // ok
80+ }
81+ }
7382 }
7483 }
modified driver-core/src/test/java/com/datastax/driver/core/SSLEncryptionTest.java +30 −33
@@ -21,13 +21,12 @@
2121 import java.util.concurrent.TimeUnit;
2222
2323 import static com.datastax.driver.core.Assertions.assertThat;
24+import static com.datastax.driver.core.CCMBridge.DEFAULT_CLIENT_TRUSTSTORE_FILE;
25+import static com.datastax.driver.core.CCMBridge.DEFAULT_CLIENT_TRUSTSTORE_PASSWORD;
2426
27+@CCMConfig(auth = false)
2528 public class SSLEncryptionTest extends SSLTestBase {
2629
27- public SSLEncryptionTest() {
28- super(false);
29- }
30-
3130 /**
3231 * <p>
3332 * Validates that an SSL connection can be established without client auth if the target
@@ -72,17 +71,11 @@
7271 */
7372 @Test(groups = "short", expectedExceptions = {NoHostAvailableException.class})
7473 public void should_not_connect_without_ssl_but_node_uses_ssl() throws Exception {
75- Cluster cluster = null;
76- try {
77- cluster = Cluster.builder()
78- .addContactPoint(CCMBridge.IP_PREFIX + '1')
79- .build();
80-
81- cluster.connect();
82- } finally {
83- if (cluster != null)
84- cluster.close();
85- }
74+ Cluster cluster = register(Cluster.builder()
75+ .addContactPointsWithPorts(this.getInitialContactPoints())
76+ .withAddressTranslator(ccm.addressTranslator())
77+ .build());
78+ cluster.connect();
8679 }
8780
8881 /**
@@ -94,25 +87,21 @@
9487 * @test_category connection:ssl
9588 * @expected_result Connection is re-established within a sufficient amount of time after a node comes back online.
9689 */
90+ @CCMConfig(dirtiesContext = true)
9791 @Test(groups = "long", dataProvider = "sslImplementation", dataProviderClass = SSLTestBase.class)
9892 public void should_reconnect_with_ssl_on_node_up(SslImplementation sslImplementation) throws Exception {
99- Cluster cluster = null;
100- try {
101- cluster = Cluster.builder()
102- .addContactPoint(CCMBridge.IP_PREFIX + '1')
103- .withSSL(getSSLOptions(sslImplementation, true, true))
104- .build();
93+ Cluster cluster = register(Cluster.builder()
94+ .addContactPointsWithPorts(this.getInitialContactPoints())
95+ .withAddressTranslator(ccm.addressTranslator())
96+ .withSSL(getSSLOptions(sslImplementation, true, true))
97+ .build());
10598
106- cluster.connect();
99+ cluster.connect();
107100
108- ccm.stop(1);
109- ccm.start(1);
101+ ccm.stop(1);
102+ ccm.start(1);
110103
111- assertThat(cluster).host(1).comesUpWithin(TestUtils.TEST_BASE_NODE_WAIT, TimeUnit.SECONDS);
112- } finally {
113- if (cluster != null)
114- cluster.close();
115- }
104+ assertThat(cluster).host(1).comesUpWithin(TestUtils.TEST_BASE_NODE_WAIT, TimeUnit.SECONDS);
116105 }
117106
118107 /**
@@ -125,9 +114,17 @@
125114 */
126115 @Test(groups = "isolated")
127116 public void should_use_system_properties_with_default_ssl_options() throws Exception {
128- System.setProperty("javax.net.ssl.trustStore", CCMBridge.DEFAULT_CLIENT_TRUSTSTORE_FILE.getAbsolutePath());
129- System.setProperty("javax.net.ssl.trustStorePassword", CCMBridge.DEFAULT_CLIENT_TRUSTSTORE_PASSWORD);
130-
131- connectWithSSL();
117+ System.setProperty("javax.net.ssl.trustStore", DEFAULT_CLIENT_TRUSTSTORE_FILE.getAbsolutePath());
118+ System.setProperty("javax.net.ssl.trustStorePassword", DEFAULT_CLIENT_TRUSTSTORE_PASSWORD);
119+ try {
120+ connectWithSSL();
121+ } finally {
122+ try {
123+ System.clearProperty("javax.net.ssl.trustStore");
124+ System.clearProperty("javax.net.ssl.trustStorePassword");
125+ } catch (SecurityException e) {
126+ // ok
127+ }
128+ }
132129 }
133130 }
modified driver-core/src/test/java/com/datastax/driver/core/SSLTestBase.java +14 −47
@@ -16,8 +16,6 @@
1616 package com.datastax.driver.core;
1717
1818 import io.netty.handler.ssl.SslContextBuilder;
19-import org.testng.annotations.AfterClass;
20-import org.testng.annotations.BeforeClass;
2119 import org.testng.annotations.DataProvider;
2220
2321 import javax.net.ssl.KeyManagerFactory;
@@ -31,15 +29,8 @@
3129 import static io.netty.handler.ssl.SslProvider.OPENSSL;
3230 import static org.assertj.core.api.Assertions.fail;
3331
34-public abstract class SSLTestBase {
35-
36- private final boolean requireClientAuth;
37-
38- protected CCMBridge ccm;
39-
40- public SSLTestBase(boolean requireClientAuth) {
41- this.requireClientAuth = requireClientAuth;
42- }
32+@CCMConfig(ssl = true, createCluster = false)
33+public abstract class SSLTestBase extends CCMTestsSupport {
4334
4435 @DataProvider(name = "sslImplementation")
4536 public static Object[][] sslImplementation() {
@@ -52,18 +43,6 @@
5243 }
5344 }
5445
55- @BeforeClass(groups = {"isolated", "short", "long"})
56- public void beforeClass() {
57- ccm = CCMBridge.builder("test")
58- .withSSL(requireClientAuth)
59- .build();
60- }
61-
62- @AfterClass(groups = {"isolated", "short", "long"})
63- public void afterClass() {
64- ccm.remove();
65- }
66-
6746 /**
6847 * <p>
6948 * Attempts to connect to a cassandra cluster with the given SSLOptions and then closes the
@@ -75,18 +54,12 @@
7554 * raised here if connection cannot be established.
7655 */
7756 protected void connectWithSSLOptions(SSLOptions sslOptions) throws Exception {
78- Cluster cluster = null;
79- try {
80- cluster = Cluster.builder()
81- .addContactPoint(CCMBridge.IP_PREFIX + '1')
82- .withSSL(sslOptions)
83- .build();
84-
85- cluster.connect();
86- } finally {
87- if (cluster != null)
88- cluster.close();
89- }
57+ Cluster cluster = register(Cluster.builder()
58+ .addContactPointsWithPorts(this.getInitialContactPoints())
59+ .withAddressTranslator(ccm.addressTranslator())
60+ .withSSL(sslOptions)
61+ .build());
62+ cluster.connect();
9063 }
9164
9265 /**
@@ -99,18 +72,12 @@
9972 * raised here if connection cannot be established.
10073 */
10174 protected void connectWithSSL() throws Exception {
102- Cluster cluster = null;
103- try {
104- cluster = Cluster.builder()
105- .addContactPoint(CCMBridge.IP_PREFIX + '1')
106- .withSSL()
107- .build();
108-
109- cluster.connect();
110- } finally {
111- if (cluster != null)
112- cluster.close();
113- }
75+ Cluster cluster = register(Cluster.builder()
76+ .addContactPointsWithPorts(this.getInitialContactPoints())
77+ .withAddressTranslator(ccm.addressTranslator())
78+ .withSSL()
79+ .build());
80+ cluster.connect();
11481 }
11582
11683 enum SslImplementation {JDK, NETTY_OPENSSL}
modified driver-core/src/test/java/com/datastax/driver/core/ScassandraCluster.java +53 −13
@@ -17,6 +17,7 @@
1717
1818 import com.beust.jcommander.internal.Lists;
1919 import com.beust.jcommander.internal.Maps;
20+import com.datastax.driver.core.policies.AddressTranslator;
2021 import com.google.common.collect.ImmutableList;
2122 import com.google.common.collect.ImmutableMap;
2223 import com.google.common.collect.ImmutableSet;
@@ -27,6 +28,8 @@
2728 import org.slf4j.Logger;
2829 import org.slf4j.LoggerFactory;
2930
31+import java.net.InetAddress;
32+import java.net.InetSocketAddress;
3033 import java.util.List;
3134 import java.util.Map;
3235 import java.util.TreeSet;
@@ -45,18 +48,22 @@
4548
4649 private final String ipPrefix;
4750
51+ private final int binaryPort;
52+
4853 private final List<Scassandra> instances;
4954
5055 private final Map<Integer, List<Scassandra>> dcNodeMap;
5156
52- private final List<Map<String, ? extends Object>> keyspaceRows;
57+ private final List<Map<String, ?>> keyspaceRows;
58+
5359
5460 private final Map<Integer, Map<Integer, Map<String, Object>>> forcedPeerInfos;
5561
5662 ScassandraCluster(Integer[] nodes, String ipPrefix, int binaryPort, int adminPort,
57- List<Map<String, ? extends Object>> keyspaceRows,
63+ List<Map<String, ?>> keyspaceRows,
5864 Map<Integer, Map<Integer, Map<String, Object>>> forcedPeerInfos) {
5965 this.ipPrefix = ipPrefix;
66+ this.binaryPort = binaryPort;
6067 this.forcedPeerInfos = forcedPeerInfos;
6168
6269 int node = 1;
@@ -85,10 +92,6 @@
8592 return instances;
8693 }
8794
88- public String address(int node) {
89- return ipPrefix + node;
90- }
91-
9295 public Scassandra node(int dc, int node) {
9396 return dcNodeMap.get(dc).get(node - 1);
9497 }
@@ -112,16 +115,53 @@
112115 return -1;
113116 }
114117
115- public String address(int dc, int node) {
118+ public InetSocketAddress address(int node) {
119+ return new InetSocketAddress(ipPrefix + node, binaryPort);
120+ }
121+
122+ public InetSocketAddress address(int dc, int node) {
116123 // TODO: Scassandra should be updated to include address to avoid O(n) lookup.
117124 int ipSuffix = ipSuffix(dc, node);
118- return ipSuffix == -1 ? null : ipPrefix + ipSuffix;
125+ if (ipSuffix == -1)
126+ return null;
127+ return new InetSocketAddress(ipPrefix + ipSuffix, binaryPort);
128+ }
129+
130+ /**
131+ * Returns an {@link AddressTranslator} to use when tests must manually create
132+ * {@link Cluster} instances.
133+ * <p/>
134+ * This translator is necessary because hosts create with this class do not use standard ports.
135+ * <p/>
136+ * This method should not be called before the test has started, nor after the test is finished.
137+ *
138+ * @return an {@link AddressTranslator} to use when tests must manually create
139+ * {@link Cluster} instances.
140+ */
141+ public AddressTranslator addressTranslator() {
142+ return new AddressTranslator() {
143+ @Override
144+ public InetSocketAddress translate(InetSocketAddress address) {
145+ return new InetSocketAddress(address.getAddress(), binaryPort);
146+ }
147+
148+ @Override
149+ public void init(Cluster cluster) {
150+
151+ }
152+
153+ @Override
154+ public void close() {
155+
156+ }
157+ };
119158 }
120159
160+
121161 public Host host(Cluster cluster, int dc, int node) {
122- String address = address(dc, node);
162+ InetAddress address = address(dc, node).getAddress();
123163 for (Host host : cluster.getMetadata().getAllHosts()) {
124- if (host.getAddress().getHostAddress().equals(address)) {
164+ if (host.getAddress().equals(address)) {
125165 return host;
126166 }
127167 }
@@ -441,8 +481,8 @@
441481 public static class ScassandraClusterBuilder {
442482
443483 private Integer nodes[] = {1};
444- private String ipPrefix = CCMBridge.IP_PREFIX;
445- private final List<Map<String, ? extends Object>> keyspaceRows = Lists.newArrayList();
484+ private String ipPrefix = TestUtils.IP_PREFIX;
485+ private final List<Map<String, ?>> keyspaceRows = Lists.newArrayList();
446486 private final Map<Integer, Map<Integer, Map<String, Object>>> forcedPeerInfos = Maps.newHashMap();
447487
448488 public ScassandraClusterBuilder withNodes(Integer... nodes) {
@@ -506,7 +546,7 @@
506546 }
507547
508548 public ScassandraCluster build() {
509- return new ScassandraCluster(nodes, ipPrefix, 9042, 9052, keyspaceRows, forcedPeerInfos);
549+ return new ScassandraCluster(nodes, ipPrefix, TestUtils.findAvailablePort(), TestUtils.findAvailablePort(), keyspaceRows, forcedPeerInfos);
510550 }
511551 }
512552 }
modified driver-core/src/test/java/com/datastax/driver/core/ScassandraTestBase.java +8 −10
@@ -16,7 +16,6 @@
1616 package com.datastax.driver.core;
1717
1818 import org.scassandra.Scassandra;
19-import org.scassandra.ScassandraFactory;
2019 import org.scassandra.http.client.ActivityClient;
2120 import org.scassandra.http.client.CurrentClient;
2221 import org.scassandra.http.client.PrimingClient;
@@ -41,8 +40,6 @@
4140 * consider using {@link com.datastax.driver.core.ScassandraTestBase.PerClassCluster} instead.
4241 */
4342 public abstract class ScassandraTestBase {
44- private static final int BINARY_PORT = 9042;
45- private static final int ADMIN_PORT = 9052;
4643
4744 private static final Logger logger = LoggerFactory.getLogger(ScassandraTestBase.class);
4845
@@ -56,11 +53,11 @@
5653
5754 protected CurrentClient currentClient;
5855
59- protected static String ip = CCMBridge.IP_PREFIX + "1";
56+ protected static String ip = TestUtils.ipOfNode(1);
6057
6158 @BeforeClass(groups = {"short", "long"})
6259 public void startScassandra() {
63- scassandra = ScassandraFactory.createServer(ip, BINARY_PORT, ip, ADMIN_PORT);
60+ scassandra = TestUtils.createScassandraServer();
6461 scassandra.start();
6562 primingClient = scassandra.primingClient();
6663 activityClient = scassandra.activityClient();
@@ -84,8 +81,9 @@
8481
8582 protected Cluster.Builder createClusterBuilder() {
8683 Cluster.Builder builder = Cluster.builder()
87- .addContactPointsWithPorts(Collections.singletonList(hostAddress))
88- // Scassandra does not support V3 yet, and V4 may cause the server to crash
84+ .withPort(scassandra.getBinaryPort())
85+ .addContactPoints(Collections.singletonList(hostAddress.getAddress()))
86+ // Scassandra does not support V3 yet, and V4 may cause the server to crash
8987 .withProtocolVersion(ProtocolVersion.V2)
9088 .withPoolingOptions(new PoolingOptions()
9189 .setCoreConnectionsPerHost(HostDistance.LOCAL, 1)
@@ -134,13 +132,13 @@
134132 session = cluster.connect();
135133 }
136134
137- @AfterClass(groups = {"short", "long"})
135+ @AfterClass(groups = {"short", "long"}, alwaysRun = true)
138136 public void closeCluster() {
139137 if (cluster != null)
140138 cluster.close();
141139 }
142140
143- @AfterClass(groups = {"short", "long"}, dependsOnMethods = "closeCluster")
141+ @AfterClass(groups = {"short", "long"}, dependsOnMethods = "closeCluster", alwaysRun = true)
144142 @Override
145143 public void stopScassandra() {
146144 super.stopScassandra();
@@ -148,4 +146,4 @@
148146
149147 }
150148
151-}
No newline at the end of the file
149+}
modified driver-core/src/test/java/com/datastax/driver/core/SchemaAgreementTest.java +30 −64
@@ -15,48 +15,34 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import com.datastax.driver.core.exceptions.DriverException;
1918 import com.datastax.driver.core.utils.UUIDs;
20-import org.testng.annotations.AfterClass;
21-import org.testng.annotations.AfterMethod;
22-import org.testng.annotations.BeforeClass;
2319 import org.testng.annotations.Test;
2420
2521 import java.net.InetAddress;
2622 import java.util.UUID;
23+import java.util.concurrent.atomic.AtomicInteger;
2724
2825 import static org.assertj.core.api.Assertions.assertThat;
2926
30-public class SchemaAgreementTest {
27+@CCMConfig(numberOfNodes = 2)
28+public class SchemaAgreementTest extends CCMTestsSupport {
3129
3230 // Don't use "IF EXISTS" to remain compatible with older C* versions
33- static final String CREATE_TABLE = "CREATE TABLE foo (k int primary key, v int)";
34- static final String DROP_TABLE = "DROP TABLE foo";
35-
36- CCMBridge ccm;
37- Cluster cluster;
38- Session session;
39- ProtocolOptions protocolOptions;
40-
41- @BeforeClass(groups = "short")
42- public void setup() {
43- ccm = CCMBridge.builder("schema_agreement").withNodes(2).build();
44- cluster = Cluster.builder().addContactPoint(CCMBridge.ipOfNode(1)).build();
45- session = cluster.connect();
46- session.execute("create keyspace test with replication = {'class': 'SimpleStrategy', 'replication_factor': 1}");
47- session.execute("use test");
48- protocolOptions = cluster.getConfiguration().getProtocolOptions();
49- }
31+ static final String CREATE_TABLE = "CREATE TABLE table_%s (k int primary key, v int)";
32+
33+ static final AtomicInteger COUNTER = new AtomicInteger(1);
5034
5135 @Test(groups = "short")
5236 public void should_set_flag_on_successful_agreement() {
37+ ProtocolOptions protocolOptions = cluster.getConfiguration().getProtocolOptions();
5338 protocolOptions.maxSchemaAgreementWaitSeconds = 10;
54- ResultSet rs = session.execute(CREATE_TABLE);
39+ ResultSet rs = session.execute(String.format(CREATE_TABLE, COUNTER.getAndIncrement()));
5540 assertThat(rs.getExecutionInfo().isSchemaInAgreement()).isTrue();
5641 }
5742
5843 @Test(groups = "short")
5944 public void should_set_flag_on_non_schema_altering_statement() {
45+ ProtocolOptions protocolOptions = cluster.getConfiguration().getProtocolOptions();
6046 protocolOptions.maxSchemaAgreementWaitSeconds = 10;
6147 ResultSet rs = session.execute("select release_version from system.local");
6248 assertThat(rs.getExecutionInfo().isSchemaInAgreement()).isTrue();
@@ -65,38 +51,33 @@
6551 @Test(groups = "short")
6652 public void should_unset_flag_on_failed_agreement() {
6753 // Setting to 0 results in no query being set, so agreement fails
54+ ProtocolOptions protocolOptions = cluster.getConfiguration().getProtocolOptions();
6855 protocolOptions.maxSchemaAgreementWaitSeconds = 0;
69- ResultSet rs = session.execute(CREATE_TABLE);
56+ ResultSet rs = session.execute(String.format(CREATE_TABLE, COUNTER.getAndIncrement()));
7057 assertThat(rs.getExecutionInfo().isSchemaInAgreement()).isFalse();
7158 }
7259
7360 @Test(groups = "short")
7461 public void should_check_agreement_through_cluster_metadata() {
75- Cluster controlCluster = null;
76- try {
77- controlCluster = TestUtils.buildControlCluster(cluster);
78- Session controlSession = controlCluster.connect();
79-
80- Row localRow = controlSession.execute("SELECT schema_version FROM system.local").one();
81- UUID localVersion = localRow.getUUID("schema_version");
82- Row peerRow = controlSession.execute("SELECT peer, schema_version FROM system.peers").one();
83- InetAddress peerAddress = peerRow.getInet("peer");
84- UUID peerVersion = peerRow.getUUID("schema_version");
85- // The two nodes should be in agreement at this point, but check just in case:
86- assertThat(localVersion).isEqualTo(peerVersion);
87-
88- // Now check the method under test:
89- assertThat(cluster.getMetadata().checkSchemaAgreement()).isTrue();
90-
91- // Insert a fake version to simulate a disagreement:
92- forceSchemaVersion(controlSession, peerAddress, UUIDs.random());
93- assertThat(cluster.getMetadata().checkSchemaAgreement()).isFalse();
94-
95- forceSchemaVersion(controlSession, peerAddress, peerVersion);
96- } finally {
97- if (controlCluster != null)
98- controlCluster.close();
99- }
62+ Cluster controlCluster = register(TestUtils.buildControlCluster(cluster, ccm));
63+ Session controlSession = controlCluster.connect();
64+
65+ Row localRow = controlSession.execute("SELECT schema_version FROM system.local").one();
66+ UUID localVersion = localRow.getUUID("schema_version");
67+ Row peerRow = controlSession.execute("SELECT peer, schema_version FROM system.peers").one();
68+ InetAddress peerAddress = peerRow.getInet("peer");
69+ UUID peerVersion = peerRow.getUUID("schema_version");
70+ // The two nodes should be in agreement at this point, but check just in case:
71+ assertThat(localVersion).isEqualTo(peerVersion);
72+
73+ // Now check the method under test:
74+ assertThat(cluster.getMetadata().checkSchemaAgreement()).isTrue();
75+
76+ // Insert a fake version to simulate a disagreement:
77+ forceSchemaVersion(controlSession, peerAddress, UUIDs.random());
78+ assertThat(cluster.getMetadata().checkSchemaAgreement()).isFalse();
79+
80+ forceSchemaVersion(controlSession, peerAddress, peerVersion);
10081 }
10182
10283 private static void forceSchemaVersion(Session session, InetAddress peerAddress, UUID schemaVersion) {
@@ -104,20 +85,5 @@
10485 TypeCodec.uuid().format(schemaVersion), TypeCodec.inet().format(peerAddress)));
10586 }
10687
107- @AfterMethod(groups = "short")
108- public void cleanupSchema() {
109- protocolOptions.maxSchemaAgreementWaitSeconds = 10;
110- try {
111- session.execute(DROP_TABLE);
112- } catch (DriverException e) { /*ignore*/ }
113- }
114-
115- @AfterClass(groups = "short")
116- public void teardown() {
117- if (cluster != null)
118- cluster.close();
119- if (ccm != null)
120- ccm.remove();
121- }
12288 }
12389
modified driver-core/src/test/java/com/datastax/driver/core/SchemaChangesCCTest.java +134 −132
@@ -31,7 +31,8 @@
3131 import static org.mockito.Matchers.any;
3232 import static org.mockito.Mockito.*;
3333
34-public class SchemaChangesCCTest {
34+@CCMConfig(numberOfNodes = 2, dirtiesContext = true, createCluster = false)
35+public class SchemaChangesCCTest extends CCMTestsSupport {
3536
3637 private static final int NOTIF_TIMEOUT_MS = 5000;
3738
@@ -52,139 +53,140 @@
5253 @Test(groups = "long")
5354 public void should_receive_changes_made_while_control_connection_is_down_on_reconnect() throws Exception {
5455 ToggleablePolicy lbPolicy = new ToggleablePolicy(Policies.defaultLoadBalancingPolicy());
55-
56- CCMBridge ccm = CCMBridge.builder("SchemaChangesCCTest").withNodes(2).build();
57- Cluster.Builder builder = Cluster.builder()
58- .withLoadBalancingPolicy(lbPolicy);
59- Cluster cluster = builder.addContactPoint(CCMBridge.ipOfNode(1)).build();
56+ Cluster cluster = register(
57+ Cluster.builder()
58+ .withLoadBalancingPolicy(lbPolicy)
59+ .addContactPointsWithPorts(ccm.addressOfNode(1))
60+ .withAddressTranslator(ccm.addressTranslator())
61+ .build());
6062 // Put cluster2 control connection on node 2 so it doesn't go down (to prevent noise for debugging).
61- Cluster cluster2 = builder.addContactPoint(CCMBridge.ipOfNode(2)).build();
62- try {
63- SchemaChangeListener listener = mock(SchemaChangeListener.class);
64-
65- cluster.init();
66- cluster.register(listener);
67-
68- Session session2 = cluster2.connect();
69- // Create two keyspaces to experiment with.
70- session2.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, "ks1", 1));
71- session2.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, "ks2", 1));
72- session2.execute("create table ks1.tbl1 (k text primary key, v text)");
73- session2.execute("create table ks1.tbl2 (k text primary key, v text)");
74-
75- // Wait for both create events to be received.
76- verify(listener, timeout(NOTIF_TIMEOUT_MS).times(2)).onKeyspaceAdded(any(KeyspaceMetadata.class));
77- verify(listener, timeout(NOTIF_TIMEOUT_MS).times(2)).onTableAdded(any(TableMetadata.class));
78-
79-
80- KeyspaceMetadata prealteredKeyspace = cluster.getMetadata().getKeyspace("ks1");
81- KeyspaceMetadata predroppedKeyspace = cluster.getMetadata().getKeyspace("ks2");
82- TableMetadata prealteredTable = cluster.getMetadata().getKeyspace("ks1").getTable("tbl1");
83- TableMetadata predroppedTable = cluster.getMetadata().getKeyspace("ks1").getTable("tbl2");
84-
85- // Enable returning empty query plan for default statements. This will
86- // prevent the control connection from being able to reconnect.
87- lbPolicy.returnEmptyQueryPlan = true;
88-
89- // Stop node 1, which hosts the control connection.
90- ccm.stop(1);
91- assertThat(cluster).host(1).goesDownWithin(20, TimeUnit.SECONDS);
92-
93- // Ensure control connection is down.
94- assertThat(cluster.manager.controlConnection.isOpen()).isFalse();
95-
96- // Perform some schema changes that we'll validate when the control connection comes back.
97- session2.execute("drop keyspace ks2");
98- session2.execute("drop table ks1.tbl2");
99- session2.execute("alter keyspace ks1 with durable_writes=false");
100- session2.execute("alter table ks1.tbl1 alter v type blob");
101- session2.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, "ks3", 1));
102- session2.execute("create table ks1.tbl3 (k text primary key, v text)");
103-
104- // Reset the mock to clear invocations. (sanity check to ensure all events happen after CC comes back up)
105- reset(listener);
106-
107- // Switch the flag so the control connection may now be established.
108- lbPolicy.returnEmptyQueryPlan = false;
109-
110- // Poll on the control connection and wait for it to be reestablished.
111- long maxControlConnectionWait = 60000;
112- long startTime = System.currentTimeMillis();
113- while (!cluster.manager.controlConnection.isOpen() && System.currentTimeMillis() - startTime < maxControlConnectionWait) {
114- Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
115- }
116-
117- assertThat(cluster.manager.controlConnection.isOpen())
118- .as("Control connection was not opened after %dms.", maxControlConnectionWait)
119- .isTrue();
120-
121- // Ensure the drop keyspace event shows up.
122- ArgumentCaptor<KeyspaceMetadata> removedKeyspace = ArgumentCaptor.forClass(KeyspaceMetadata.class);
123- verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onKeyspaceRemoved(removedKeyspace.capture());
124- assertThat(removedKeyspace.getValue())
125- .hasName("ks2")
126- .isEqualTo(predroppedKeyspace);
127-
128- // Ensure the drop table event shows up.
129- ArgumentCaptor<TableMetadata> droppedTable = ArgumentCaptor.forClass(TableMetadata.class);
130- verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onTableRemoved(droppedTable.capture());
131-
132- assertThat(droppedTable.getValue())
133- .isInKeyspace("ks1")
134- .hasName("tbl2")
135- .isEqualTo(predroppedTable);
136-
137- // Ensure that the alter keyspace event shows up.
138- ArgumentCaptor<KeyspaceMetadata> alteredKeyspace = ArgumentCaptor.forClass(KeyspaceMetadata.class);
139- ArgumentCaptor<KeyspaceMetadata> originalKeyspace = ArgumentCaptor.forClass(KeyspaceMetadata.class);
140- verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onKeyspaceChanged(alteredKeyspace.capture(), originalKeyspace.capture());
141-
142- // Previous metadata should match the metadata observed before disconnect.
143- assertThat(originalKeyspace.getValue())
144- .hasName("ks1")
145- .isDurableWrites()
146- .isEqualTo(prealteredKeyspace);
147-
148- // New metadata should reflect that the durable writes attribute changed.
149- assertThat(alteredKeyspace.getValue())
150- .hasName("ks1")
151- .isNotDurableWrites();
152-
153- // Ensure the alter table event shows up.
154- ArgumentCaptor<TableMetadata> alteredTable = ArgumentCaptor.forClass(TableMetadata.class);
155- ArgumentCaptor<TableMetadata> originalTable = ArgumentCaptor.forClass(TableMetadata.class);
156- verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onTableChanged(alteredTable.capture(), originalTable.capture());
157-
158- // Previous metadata should match the metadata observed before disconnect.
159- assertThat(originalTable.getValue())
160- .isInKeyspace("ks1")
161- .hasName("tbl1")
162- .hasColumn("v", DataType.text())
163- .isEqualTo(prealteredTable);
164-
165- // New metadata should reflect that the column type changed.
166- assertThat(alteredTable.getValue())
167- .isInKeyspace("ks1")
168- .hasName("tbl1")
169- .hasColumn("v", DataType.blob());
170-
171- // Ensure the add keyspace event shows up.
172- ArgumentCaptor<KeyspaceMetadata> addedKeyspace = ArgumentCaptor.forClass(KeyspaceMetadata.class);
173- verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onKeyspaceAdded(addedKeyspace.capture());
174-
175- assertThat(addedKeyspace.getValue()).hasName("ks3");
176-
177- // Ensure the add table event shows up.
178- ArgumentCaptor<TableMetadata> addedTable = ArgumentCaptor.forClass(TableMetadata.class);
179- verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onTableAdded(addedTable.capture());
180-
181- assertThat(addedTable.getValue())
182- .isInKeyspace("ks1")
183- .hasName("tbl3");
184- } finally {
185- cluster.close();
186- ccm.remove();
63+ Cluster cluster2 = register(
64+ Cluster.builder()
65+ .withLoadBalancingPolicy(lbPolicy)
66+ .addContactPointsWithPorts(ccm.addressOfNode(2))
67+ .withAddressTranslator(ccm.addressTranslator())
68+ .build());
69+ SchemaChangeListener listener = mock(SchemaChangeListener.class);
70+
71+ cluster.init();
72+ cluster.register(listener);
73+
74+ Session session2 = cluster2.connect();
75+ // Create two keyspaces to experiment with.
76+ session2.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, "ks1", 1));
77+ session2.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, "ks2", 1));
78+ session2.execute("create table ks1.tbl1 (k text primary key, v text)");
79+ session2.execute("create table ks1.tbl2 (k text primary key, v text)");
80+
81+ // Wait for both create events to be received.
82+ verify(listener, timeout(NOTIF_TIMEOUT_MS).times(2)).onKeyspaceAdded(any(KeyspaceMetadata.class));
83+ verify(listener, timeout(NOTIF_TIMEOUT_MS).times(2)).onTableAdded(any(TableMetadata.class));
84+
85+
86+ KeyspaceMetadata prealteredKeyspace = cluster.getMetadata().getKeyspace("ks1");
87+ KeyspaceMetadata predroppedKeyspace = cluster.getMetadata().getKeyspace("ks2");
88+ TableMetadata prealteredTable = cluster.getMetadata().getKeyspace("ks1").getTable("tbl1");
89+ TableMetadata predroppedTable = cluster.getMetadata().getKeyspace("ks1").getTable("tbl2");
90+
91+ // Enable returning empty query plan for default statements. This will
92+ // prevent the control connection from being able to reconnect.
93+ lbPolicy.returnEmptyQueryPlan = true;
94+
95+ // Stop node 1, which hosts the control connection.
96+ ccm.stop(1);
97+ assertThat(cluster).host(1).goesDownWithin(20, TimeUnit.SECONDS);
98+
99+ // Ensure control connection is down.
100+ assertThat(cluster.manager.controlConnection.isOpen()).isFalse();
101+
102+ // Perform some schema changes that we'll validate when the control connection comes back.
103+ session2.execute("drop keyspace ks2");
104+ session2.execute("drop table ks1.tbl2");
105+ session2.execute("alter keyspace ks1 with durable_writes=false");
106+ session2.execute("alter table ks1.tbl1 alter v type blob");
107+ session2.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, "ks3", 1));
108+ session2.execute("create table ks1.tbl3 (k text primary key, v text)");
109+
110+ // Reset the mock to clear invocations. (sanity check to ensure all events happen after CC comes back up)
111+ reset(listener);
112+
113+ // Switch the flag so the control connection may now be established.
114+ lbPolicy.returnEmptyQueryPlan = false;
115+
116+ // Poll on the control connection and wait for it to be reestablished.
117+ long maxControlConnectionWait = 60000;
118+ long startTime = System.currentTimeMillis();
119+ while (!cluster.manager.controlConnection.isOpen() && System.currentTimeMillis() - startTime < maxControlConnectionWait) {
120+ Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
187121 }
122+
123+ assertThat(cluster.manager.controlConnection.isOpen())
124+ .as("Control connection was not opened after %dms.", maxControlConnectionWait)
125+ .isTrue();
126+
127+ // Ensure the drop keyspace event shows up.
128+ ArgumentCaptor<KeyspaceMetadata> removedKeyspace = ArgumentCaptor.forClass(KeyspaceMetadata.class);
129+ verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onKeyspaceRemoved(removedKeyspace.capture());
130+ assertThat(removedKeyspace.getValue())
131+ .hasName("ks2")
132+ .isEqualTo(predroppedKeyspace);
133+
134+ // Ensure the drop table event shows up.
135+ ArgumentCaptor<TableMetadata> droppedTable = ArgumentCaptor.forClass(TableMetadata.class);
136+ verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onTableRemoved(droppedTable.capture());
137+
138+ assertThat(droppedTable.getValue())
139+ .isInKeyspace("ks1")
140+ .hasName("tbl2")
141+ .isEqualTo(predroppedTable);
142+
143+ // Ensure that the alter keyspace event shows up.
144+ ArgumentCaptor<KeyspaceMetadata> alteredKeyspace = ArgumentCaptor.forClass(KeyspaceMetadata.class);
145+ ArgumentCaptor<KeyspaceMetadata> originalKeyspace = ArgumentCaptor.forClass(KeyspaceMetadata.class);
146+ verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onKeyspaceChanged(alteredKeyspace.capture(), originalKeyspace.capture());
147+
148+ // Previous metadata should match the metadata observed before disconnect.
149+ assertThat(originalKeyspace.getValue())
150+ .hasName("ks1")
151+ .isDurableWrites()
152+ .isEqualTo(prealteredKeyspace);
153+
154+ // New metadata should reflect that the durable writes attribute changed.
155+ assertThat(alteredKeyspace.getValue())
156+ .hasName("ks1")
157+ .isNotDurableWrites();
158+
159+ // Ensure the alter table event shows up.
160+ ArgumentCaptor<TableMetadata> alteredTable = ArgumentCaptor.forClass(TableMetadata.class);
161+ ArgumentCaptor<TableMetadata> originalTable = ArgumentCaptor.forClass(TableMetadata.class);
162+ verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onTableChanged(alteredTable.capture(), originalTable.capture());
163+
164+ // Previous metadata should match the metadata observed before disconnect.
165+ assertThat(originalTable.getValue())
166+ .isInKeyspace("ks1")
167+ .hasName("tbl1")
168+ .hasColumn("v", DataType.text())
169+ .isEqualTo(prealteredTable);
170+
171+ // New metadata should reflect that the column type changed.
172+ assertThat(alteredTable.getValue())
173+ .isInKeyspace("ks1")
174+ .hasName("tbl1")
175+ .hasColumn("v", DataType.blob());
176+
177+ // Ensure the add keyspace event shows up.
178+ ArgumentCaptor<KeyspaceMetadata> addedKeyspace = ArgumentCaptor.forClass(KeyspaceMetadata.class);
179+ verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onKeyspaceAdded(addedKeyspace.capture());
180+
181+ assertThat(addedKeyspace.getValue()).hasName("ks3");
182+
183+ // Ensure the add table event shows up.
184+ ArgumentCaptor<TableMetadata> addedTable = ArgumentCaptor.forClass(TableMetadata.class);
185+ verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onTableAdded(addedTable.capture());
186+
187+ assertThat(addedTable.getValue())
188+ .isInKeyspace("ks1")
189+ .hasName("tbl3");
188190 }
189191
190192 /**
modified driver-core/src/test/java/com/datastax/driver/core/SchemaChangesTest.java +111 −115
@@ -23,8 +23,6 @@
2323 import org.mockito.ArgumentCaptor;
2424 import org.testng.annotations.*;
2525
26-import java.util.Collection;
27-import java.util.Collections;
2826 import java.util.List;
2927
3028 import static com.datastax.driver.core.Assertions.assertThat;
@@ -33,7 +31,8 @@
3331 import static org.mockito.Matchers.any;
3432 import static org.mockito.Mockito.*;
3533
36-public class SchemaChangesTest extends CCMBridge.PerClassSingleNodeCluster {
34+@CCMConfig(createCluster = false, config = "enable_user_defined_functions:true")
35+public class SchemaChangesTest extends CCMTestsSupport {
3736
3837 private static final String CREATE_KEYSPACE = "CREATE KEYSPACE %s WITH REPLICATION = { 'class' : 'SimpleStrategy', 'replication_factor': '1' }";
3938 private static final String ALTER_KEYSPACE = "ALTER KEYSPACE %s WITH durable_writes = false";
@@ -46,15 +45,12 @@
4645 /**
4746 * The maximum time that the test will wait to check that listeners have been notified
4847 */
49- private static final int NOTIF_TIMEOUT_MS = 5000;
48+ private static final int NOTIF_TIMEOUT_MS = 120000;
5049
5150 Cluster cluster1;
5251 Cluster cluster2; // a second cluster to check that other clients also get notified
5352 Cluster schemaDisabledCluster; // a cluster with schema metadata disabled.
5453
55- // The metadatas of the two clusters (we'll test that they're kept in sync)
56- List<Metadata> metadatas;
57-
5854 Session session1;
5955
6056 Session schemaDisabledSession;
@@ -67,20 +63,15 @@
6763
6864 ControlConnection schemaDisabledControlConnection;
6965
70- @Override
71- protected Collection<String> getTableDefinitions() {
72- return Lists.newArrayList();
73- }
74-
7566 @BeforeClass(groups = "short")
7667 public void setup() throws InterruptedException {
77- Cluster.Builder builder = configure(Cluster.builder())
78- .addContactPointsWithPorts(Collections.singletonList(hostAddress))
68+ Cluster.Builder builder = Cluster.builder()
69+ .addContactPointsWithPorts(getInitialContactPoints())
7970 .withQueryOptions(nonDebouncingQueryOptions());
8071 cluster1 = builder.build();
8172 cluster2 = builder.build();
82- schemaDisabledCluster = spy(configure(Cluster.builder())
83- .addContactPointsWithPorts(Collections.singletonList(hostAddress))
73+ schemaDisabledCluster = spy(Cluster.builder()
74+ .addContactPointsWithPorts(getInitialContactPoints())
8475 .withClusterName("schema-disabled")
8576 .withQueryOptions(nonDebouncingQueryOptions()
8677 .setMetadataEnabled(false)
@@ -91,8 +82,6 @@
9182 schemaDisabledControlConnection = spy(schemaDisabledCluster.manager.controlConnection);
9283 schemaDisabledCluster.manager.controlConnection = schemaDisabledControlConnection;
9384
94- metadatas = Lists.newArrayList(cluster1.getMetadata(), cluster2.getMetadata());
95-
9685 session1 = cluster1.connect();
9786
9887 cluster1.register(listener1 = mock(SchemaChangeListener.class));
@@ -106,7 +95,7 @@
10695 execute(CREATE_KEYSPACE, "\"CaseSensitive\"");
10796 }
10897
109- @AfterClass(groups = "short")
98+ @AfterClass(groups = "short", alwaysRun = true)
11099 public void teardown() {
111100 if (cluster1 != null)
112101 cluster1.close();
@@ -157,16 +146,13 @@
157146 .isInKeyspace(handleId(keyspace))
158147 .hasName("table1");
159148 }
160-
161- for (Metadata m : metadatas)
149+ for (Metadata m : metadatas())
162150 assertThat(m.getKeyspace(keyspace).getTable("table1")).isNotNull();
163151 }
164152
165153 @Test(groups = "short", dataProvider = "existingKeyspaceName")
166154 public void should_notify_of_table_update(String keyspace) throws InterruptedException {
167155 execute(CREATE_TABLE, keyspace);
168- for (Metadata m : metadatas)
169- assertThat(m.getKeyspace(keyspace).getTable("table1")).hasNoColumn("j");
170156 ArgumentCaptor<TableMetadata> added = null;
171157 for (SchemaChangeListener listener : listeners) {
172158 added = ArgumentCaptor.forClass(TableMetadata.class);
@@ -175,6 +161,9 @@
175161 .isInKeyspace(handleId(keyspace))
176162 .hasName("table1");
177163 }
164+ for (Metadata m : metadatas())
165+ assertThat(m.getKeyspace(keyspace).getTable("table1")).hasNoColumn("j");
166+ assert added != null;
178167 execute(ALTER_TABLE, keyspace);
179168 for (SchemaChangeListener listener : listeners) {
180169 ArgumentCaptor<TableMetadata> current = ArgumentCaptor.forClass(TableMetadata.class);
@@ -188,7 +177,7 @@
188177 .hasName("table1")
189178 .hasColumn("j");
190179 }
191- for (Metadata m : metadatas)
180+ for (Metadata m : metadatas())
192181 assertThat(m.getKeyspace(keyspace).getTable("table1")).hasColumn("j");
193182 }
194183
@@ -203,38 +192,35 @@
203192 .isInKeyspace(handleId(keyspace));
204193 }
205194 execute(DROP_TABLE, keyspace);
206- for (Metadata m : metadatas)
207- assertThat(m.getKeyspace(keyspace).getTable("table1")).isNull();
208195 for (SchemaChangeListener listener : listeners) {
209196 ArgumentCaptor<TableMetadata> removed = ArgumentCaptor.forClass(TableMetadata.class);
210197 verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onTableRemoved(removed.capture());
211198 assertThat(removed.getValue()).hasName("table1");
212199 }
200+ for (Metadata m : metadatas())
201+ assertThat(m.getKeyspace(keyspace).getTable("table1")).isNull();
213202 }
214203
204+ @SuppressWarnings("RedundantCast")
215205 @Test(groups = "short", dataProvider = "existingKeyspaceName")
216206 @CassandraVersion(major = 2.1)
217207 public void should_notify_of_udt_creation(String keyspace) {
218- session.execute(String.format("CREATE TYPE %s.type1(i int)", keyspace));
219-
208+ session1.execute(String.format("CREATE TYPE %s.type1(i int)", keyspace));
220209 for (SchemaChangeListener listener : listeners) {
221210 ArgumentCaptor<UserType> added = ArgumentCaptor.forClass(UserType.class);
222211 verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onUserTypeAdded(added.capture());
223212 assertThat((DataType) added.getValue())
224213 .isUserType(handleId(keyspace), "type1");
225214 }
226-
227- for (Metadata m : metadatas)
228- assertThat((DataType) m.getKeyspace(keyspace).getUserType("type1"))
229- .isNotNull();
215+ for (Metadata m : metadatas())
216+ assertThat((DataType) m.getKeyspace(keyspace).getUserType("type1")).isNotNull();
230217 }
231218
232219 @Test(groups = "short", dataProvider = "existingKeyspaceName")
233220 @CassandraVersion(major = 2.1)
234221 public void should_notify_of_udt_update(String keyspace) {
235- session.execute(String.format("CREATE TYPE %s.type1(i int)", keyspace));
236- session.execute(String.format("ALTER TYPE %s.type1 ADD j int", keyspace));
237-
222+ session1.execute(String.format("CREATE TYPE %s.type1(i int)", keyspace));
223+ session1.execute(String.format("ALTER TYPE %s.type1 ADD j int", keyspace));
238224 for (SchemaChangeListener listener : listeners) {
239225 ArgumentCaptor<UserType> current = ArgumentCaptor.forClass(UserType.class);
240226 ArgumentCaptor<UserType> previous = ArgumentCaptor.forClass(UserType.class);
@@ -242,33 +228,29 @@
242228 assertThat(previous.getValue().getFieldNames()).doesNotContain("j");
243229 assertThat(current.getValue().getFieldNames()).contains("j");
244230 }
245-
246- for (Metadata m : metadatas)
247- assertThat(m.getKeyspace(keyspace).getUserType("type1").getFieldType("j"))
248- .isNotNull();
231+ for (Metadata m : metadatas())
232+ assertThat(m.getKeyspace(keyspace).getUserType("type1").getFieldType("j")).isNotNull();
249233 }
250234
235+ @SuppressWarnings("RedundantCast")
251236 @Test(groups = "short", dataProvider = "existingKeyspaceName")
252237 @CassandraVersion(major = 2.1)
253238 public void should_notify_of_udt_drop(String keyspace) {
254- session.execute(String.format("CREATE TYPE %s.type1(i int)", keyspace));
255- session.execute(String.format("DROP TYPE %s.type1", keyspace));
256-
239+ session1.execute(String.format("CREATE TYPE %s.type1(i int)", keyspace));
240+ session1.execute(String.format("DROP TYPE %s.type1", keyspace));
257241 for (SchemaChangeListener listener : listeners) {
258242 ArgumentCaptor<UserType> removed = ArgumentCaptor.forClass(UserType.class);
259243 verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onUserTypeRemoved(removed.capture());
260244 assertThat((DataType) removed.getValue()).isUserType(handleId(keyspace), "type1");
261245 }
262-
263- for (Metadata m : metadatas)
264- assertThat((DataType) m.getKeyspace(keyspace).getUserType("type1"))
265- .isNull();
246+ for (Metadata m : metadatas())
247+ assertThat((DataType) m.getKeyspace(keyspace).getUserType("type1")).isNull();
266248 }
267249
268250 @Test(groups = "short", dataProvider = "existingKeyspaceName")
269251 @CassandraVersion(major = 2.2)
270252 public void should_notify_of_function_creation(String keyspace) {
271- session.execute(String.format("CREATE FUNCTION %s.\"ID\"(i int) RETURNS NULL ON NULL INPUT RETURNS int LANGUAGE java AS 'return i;'", keyspace));
253+ session1.execute(String.format("CREATE FUNCTION %s.\"ID\"(i int) RETURNS NULL ON NULL INPUT RETURNS int LANGUAGE java AS 'return i;'", keyspace));
272254
273255 for (SchemaChangeListener listener : listeners) {
274256 ArgumentCaptor<FunctionMetadata> added = ArgumentCaptor.forClass(FunctionMetadata.class);
@@ -278,7 +260,7 @@
278260 .hasSignature("\"ID\"(int)");
279261 }
280262
281- for (Metadata m : metadatas)
263+ for (Metadata m : metadatas())
282264 assertThat(m.getKeyspace(keyspace).getFunction("\"ID\"", DataType.cint()))
283265 .isNotNull();
284266 }
@@ -286,14 +268,14 @@
286268 @Test(groups = "short", dataProvider = "existingKeyspaceName")
287269 @CassandraVersion(major = 2.2)
288270 public void should_notify_of_function_update(String keyspace) {
289- session.execute(String.format("CREATE TYPE IF NOT EXISTS %s.user (\"ID\" int, name text)", keyspace));
290- session.execute(String.format("CREATE FUNCTION %s.\"ID\"(user user) RETURNS NULL ON NULL INPUT RETURNS int LANGUAGE java AS 'return user.getInt(\"ID\");'", keyspace));
271+ session1.execute(String.format("CREATE TYPE IF NOT EXISTS %s.user (\"ID\" int, name text)", keyspace));
272+ session1.execute(String.format("CREATE FUNCTION %s.\"ID\"(user user) RETURNS NULL ON NULL INPUT RETURNS int LANGUAGE java AS 'return user.getInt(\"ID\");'", keyspace));
291273
292- for (Metadata m : metadatas)
274+ for (Metadata m : metadatas())
293275 assertThat(m.getKeyspace(keyspace).getFunction("\"ID\"", m.getKeyspace(keyspace).getUserType("user")).getBody())
294276 .isEqualTo("return user.getInt(\"ID\");");
295277
296- session.execute(String.format("CREATE OR REPLACE FUNCTION %s.\"ID\"(user user) RETURNS NULL ON NULL INPUT RETURNS int LANGUAGE java "
278+ session1.execute(String.format("CREATE OR REPLACE FUNCTION %s.\"ID\"(user user) RETURNS NULL ON NULL INPUT RETURNS int LANGUAGE java "
297279 + "AS 'return 1 + user.getInt(\"ID\");'", keyspace));
298280
299281 for (SchemaChangeListener listener : listeners) {
@@ -304,7 +286,7 @@
304286 assertThat(current.getValue()).hasBody("return 1 + user.getInt(\"ID\");");
305287 }
306288
307- for (Metadata m : metadatas)
289+ for (Metadata m : metadatas())
308290 assertThat(m.getKeyspace(keyspace).getFunction("\"ID\"", m.getKeyspace(keyspace).getUserType("user")).getBody())
309291 .isEqualTo("return 1 + user.getInt(\"ID\");");
310292 }
@@ -312,9 +294,9 @@
312294 @Test(groups = "short", dataProvider = "existingKeyspaceName")
313295 @CassandraVersion(major = 2.2)
314296 public void should_notify_of_function_drop(String keyspace) {
315- session.execute(String.format("CREATE TYPE IF NOT EXISTS %s.user (\"ID\" int, name text)", keyspace));
316- session.execute(String.format("CREATE FUNCTION %s.\"ID\"(user user) RETURNS NULL ON NULL INPUT RETURNS int LANGUAGE java AS 'return user.getInt(\"ID\");'", keyspace));
317- session.execute(String.format("DROP FUNCTION %s.\"ID\"", keyspace));
297+ session1.execute(String.format("CREATE TYPE IF NOT EXISTS %s.user (\"ID\" int, name text)", keyspace));
298+ session1.execute(String.format("CREATE FUNCTION %s.\"ID\"(user user) RETURNS NULL ON NULL INPUT RETURNS int LANGUAGE java AS 'return user.getInt(\"ID\");'", keyspace));
299+ session1.execute(String.format("DROP FUNCTION %s.\"ID\"", keyspace));
318300
319301 for (SchemaChangeListener listener : listeners) {
320302 ArgumentCaptor<FunctionMetadata> removed = ArgumentCaptor.forClass(FunctionMetadata.class);
@@ -324,7 +306,7 @@
324306 .hasSignature("\"ID\"(user)");
325307 }
326308
327- for (Metadata m : metadatas)
309+ for (Metadata m : metadatas())
328310 assertThat(m.getKeyspace(keyspace).getFunction("\"ID\"", m.getKeyspace(keyspace).getUserType("user")))
329311 .isNull();
330312 }
@@ -332,9 +314,9 @@
332314 @Test(groups = "short", dataProvider = "existingKeyspaceName")
333315 @CassandraVersion(major = 2.2)
334316 public void should_notify_of_aggregate_creation(String keyspace) {
335- session.execute(String.format("CREATE FUNCTION %s.\"PLUS\"(s int, v int) RETURNS NULL ON NULL INPUT RETURNS int LANGUAGE java"
317+ session1.execute(String.format("CREATE FUNCTION %s.\"PLUS\"(s int, v int) RETURNS NULL ON NULL INPUT RETURNS int LANGUAGE java"
336318 + " AS 'return s+v;'", keyspace));
337- session.execute(String.format("CREATE AGGREGATE %s.\"SUM\"(int) SFUNC \"PLUS\" STYPE int INITCOND 0;", keyspace));
319+ session1.execute(String.format("CREATE AGGREGATE %s.\"SUM\"(int) SFUNC \"PLUS\" STYPE int INITCOND 0;", keyspace));
338320
339321 for (SchemaChangeListener listener : listeners) {
340322 ArgumentCaptor<AggregateMetadata> added = ArgumentCaptor.forClass(AggregateMetadata.class);
@@ -344,7 +326,7 @@
344326 .hasSignature("\"SUM\"(int)");
345327 }
346328
347- for (Metadata m : metadatas)
329+ for (Metadata m : metadatas())
348330 assertThat(m.getKeyspace(keyspace).getAggregate("\"SUM\"", DataType.cint()))
349331 .isNotNull();
350332 }
@@ -352,15 +334,15 @@
352334 @Test(groups = "short", dataProvider = "existingKeyspaceName")
353335 @CassandraVersion(major = 2.2)
354336 public void should_notify_of_aggregate_update(String keyspace) {
355- session.execute(String.format("CREATE FUNCTION %s.\"PLUS\"(s int, v int) RETURNS NULL ON NULL INPUT RETURNS int LANGUAGE java"
337+ session1.execute(String.format("CREATE FUNCTION %s.\"PLUS\"(s int, v int) RETURNS NULL ON NULL INPUT RETURNS int LANGUAGE java"
356338 + " AS 'return s+v;'", keyspace));
357- session.execute(String.format("CREATE AGGREGATE %s.\"SUM\"(int) SFUNC \"PLUS\" STYPE int INITCOND 0", keyspace));
339+ session1.execute(String.format("CREATE AGGREGATE %s.\"SUM\"(int) SFUNC \"PLUS\" STYPE int INITCOND 0", keyspace));
358340
359- for (Metadata m : metadatas)
341+ for (Metadata m : metadatas())
360342 assertThat(m.getKeyspace(keyspace).getAggregate("\"SUM\"", DataType.cint()).getInitCond())
361343 .isEqualTo(0);
362344
363- session.execute(String.format("CREATE OR REPLACE AGGREGATE %s.\"SUM\"(int) SFUNC \"PLUS\" STYPE int INITCOND 1", keyspace));
345+ session1.execute(String.format("CREATE OR REPLACE AGGREGATE %s.\"SUM\"(int) SFUNC \"PLUS\" STYPE int INITCOND 1", keyspace));
364346
365347 for (SchemaChangeListener listener : listeners) {
366348 ArgumentCaptor<AggregateMetadata> current = ArgumentCaptor.forClass(AggregateMetadata.class);
@@ -370,7 +352,7 @@
370352 assertThat(current.getValue()).hasInitCond(1);
371353 }
372354
373- for (Metadata m : metadatas)
355+ for (Metadata m : metadatas())
374356 assertThat(m.getKeyspace(keyspace).getAggregate("\"SUM\"", DataType.cint()).getInitCond())
375357 .isEqualTo(1);
376358 }
@@ -378,10 +360,10 @@
378360 @Test(groups = "short", dataProvider = "existingKeyspaceName")
379361 @CassandraVersion(major = 2.2)
380362 public void should_notify_of_aggregate_drop(String keyspace) {
381- session.execute(String.format("CREATE FUNCTION %s.\"PLUS\"(s int, v int) RETURNS NULL ON NULL INPUT RETURNS int LANGUAGE java"
363+ session1.execute(String.format("CREATE FUNCTION %s.\"PLUS\"(s int, v int) RETURNS NULL ON NULL INPUT RETURNS int LANGUAGE java"
382364 + " AS 'return s+v;'", keyspace));
383- session.execute(String.format("CREATE AGGREGATE %s.\"SUM\"(int) SFUNC \"PLUS\" STYPE int INITCOND 0", keyspace));
384- session.execute(String.format("DROP AGGREGATE %s.\"SUM\"", keyspace));
365+ session1.execute(String.format("CREATE AGGREGATE %s.\"SUM\"(int) SFUNC \"PLUS\" STYPE int INITCOND 0", keyspace));
366+ session1.execute(String.format("DROP AGGREGATE %s.\"SUM\"", keyspace));
385367
386368 for (SchemaChangeListener listener : listeners) {
387369 ArgumentCaptor<AggregateMetadata> removed = ArgumentCaptor.forClass(AggregateMetadata.class);
@@ -391,7 +373,7 @@
391373 .hasSignature("\"SUM\"(int)");
392374 }
393375
394- for (Metadata m : metadatas)
376+ for (Metadata m : metadatas())
395377 assertThat(m.getKeyspace(keyspace).getAggregate("\"SUM\"", DataType.cint()))
396378 .isNull();
397379 }
@@ -399,49 +381,49 @@
399381 @Test(groups = "short", dataProvider = "existingKeyspaceName")
400382 @CassandraVersion(major = 3.0)
401383 public void should_notify_of_view_creation(String keyspace) {
402- session.execute(String.format("CREATE TABLE %s.table1 (pk int PRIMARY KEY, c int)", keyspace));
403- session.execute(String.format("CREATE MATERIALIZED VIEW %s.mv1 AS SELECT c FROM %s.table1 WHERE c IS NOT NULL PRIMARY KEY (pk, c)", keyspace, keyspace));
384+ session1.execute(String.format("CREATE TABLE %s.table1 (pk int PRIMARY KEY, c int)", keyspace));
385+ session1.execute(String.format("CREATE MATERIALIZED VIEW %s.mv1 AS SELECT c FROM %s.table1 WHERE c IS NOT NULL PRIMARY KEY (pk, c)", keyspace, keyspace));
404386
405- for (Metadata m : metadatas)
387+ for (Metadata m : metadatas())
406388 assertThat(m.getKeyspace(keyspace).getMaterializedView("mv1")).isNotNull();
407389 }
408390
409391 @Test(groups = "short", dataProvider = "existingKeyspaceName")
410392 @CassandraVersion(major = 3.0)
411393 public void should_notify_of_view_update(String keyspace) {
412- session.execute(String.format("CREATE TABLE %s.table1 (pk int PRIMARY KEY, c int)", keyspace));
413- session.execute(String.format("CREATE MATERIALIZED VIEW %s.mv1 AS SELECT c FROM %s.table1 WHERE c IS NOT NULL PRIMARY KEY (pk, c) WITH compaction = { 'class' : 'SizeTieredCompactionStrategy' }", keyspace, keyspace));
394+ session1.execute(String.format("CREATE TABLE %s.table1 (pk int PRIMARY KEY, c int)", keyspace));
395+ session1.execute(String.format("CREATE MATERIALIZED VIEW %s.mv1 AS SELECT c FROM %s.table1 WHERE c IS NOT NULL PRIMARY KEY (pk, c) WITH compaction = { 'class' : 'SizeTieredCompactionStrategy' }", keyspace, keyspace));
414396
415- for (Metadata m : metadatas)
397+ for (Metadata m : metadatas())
416398 assertThat(m.getKeyspace(keyspace).getMaterializedView("mv1").getOptions().getCompaction().get("class")).contains("SizeTieredCompactionStrategy");
417399
418- session.execute(String.format("ALTER MATERIALIZED VIEW %s.mv1 WITH compaction = { 'class' : 'LeveledCompactionStrategy' }", keyspace));
400+ session1.execute(String.format("ALTER MATERIALIZED VIEW %s.mv1 WITH compaction = { 'class' : 'LeveledCompactionStrategy' }", keyspace));
419401
420- for (Metadata m : metadatas)
402+ for (Metadata m : metadatas())
421403 assertThat(m.getKeyspace(keyspace).getMaterializedView("mv1").getOptions().getCompaction().get("class")).contains("LeveledCompactionStrategy");
422404 }
423405
424406 @Test(groups = "short", dataProvider = "existingKeyspaceName")
425407 @CassandraVersion(major = 3.0)
426408 public void should_notify_of_view_drop(String keyspace) {
427- session.execute(String.format("CREATE TABLE %s.table1 (pk int PRIMARY KEY, c int)", keyspace));
428- session.execute(String.format("CREATE MATERIALIZED VIEW %s.mv1 AS SELECT c FROM %s.table1 WHERE c IS NOT NULL PRIMARY KEY (pk, c)", keyspace, keyspace));
429- session.execute(String.format("DROP MATERIALIZED VIEW %s.mv1", keyspace));
430-
431- for (Metadata m : metadatas)
409+ session1.execute(String.format("CREATE TABLE %s.table1 (pk int PRIMARY KEY, c int)", keyspace));
410+ session1.execute(String.format("CREATE MATERIALIZED VIEW %s.mv1 AS SELECT c FROM %s.table1 WHERE c IS NOT NULL PRIMARY KEY (pk, c)", keyspace, keyspace));
411+ session1.execute(String.format("DROP MATERIALIZED VIEW %s.mv1", keyspace));
412+
413+ for (Metadata m : metadatas())
432414 assertThat(m.getKeyspace(keyspace).getMaterializedView("mv1")).isNull();
433415 }
434416
435417 @Test(groups = "short", dataProvider = "newKeyspaceName")
436418 public void should_notify_of_keyspace_creation(String keyspace) throws InterruptedException {
437419 execute(CREATE_KEYSPACE, keyspace);
438- for (Metadata m : metadatas)
439- assertThat(m.getKeyspace(keyspace)).isNotNull();
440420 for (SchemaChangeListener listener : listeners) {
441421 ArgumentCaptor<KeyspaceMetadata> added = ArgumentCaptor.forClass(KeyspaceMetadata.class);
442422 verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onKeyspaceAdded(added.capture());
443423 assertThat(added.getValue()).hasName(handleId(keyspace));
444424 }
425+ for (Metadata m : metadatas())
426+ assertThat(m.getKeyspace(keyspace)).isNotNull();
445427 }
446428
447429 @Test(groups = "short", dataProvider = "newKeyspaceName")
@@ -453,7 +435,8 @@
453435 verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onKeyspaceAdded(added.capture());
454436 assertThat(added.getValue()).hasName(handleId(keyspace));
455437 }
456- for (Metadata m : metadatas)
438+ assert added != null;
439+ for (Metadata m : metadatas())
457440 assertThat(m.getKeyspace(keyspace).isDurableWrites()).isTrue();
458441 execute(ALTER_KEYSPACE, keyspace);
459442 for (SchemaChangeListener listener : listeners) {
@@ -467,14 +450,21 @@
467450 .hasName(handleId(keyspace))
468451 .isNotDurableWrites();
469452 }
470- for (Metadata m : metadatas)
453+ for (Metadata m : metadatas())
471454 assertThat(m.getKeyspace(keyspace)).isNotDurableWrites();
472455 }
473456
474457 @Test(groups = "short", dataProvider = "newKeyspaceName")
475458 public void should_notify_of_keyspace_drop(String keyspace) throws InterruptedException {
476459 execute(CREATE_KEYSPACE, keyspace);
477- for (Metadata m : metadatas)
460+ ArgumentCaptor<KeyspaceMetadata> added = null;
461+ for (SchemaChangeListener listener : listeners) {
462+ added = ArgumentCaptor.forClass(KeyspaceMetadata.class);
463+ verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onKeyspaceAdded(added.capture());
464+ assertThat(added.getValue()).hasName(handleId(keyspace));
465+ }
466+ assert added != null;
467+ for (Metadata m : metadatas())
478468 assertThat(m.getReplicas(keyspace, Bytes.fromHexString("0xCAFEBABE"))).isNotEmpty();
479469 execute(CREATE_TABLE, keyspace); // to test table drop notifications
480470 execute(DROP_KEYSPACE, keyspace);
@@ -484,13 +474,12 @@
484474 assertThat(table.getValue())
485475 .hasName("table1")
486476 .isInKeyspace(handleId(keyspace));
487-
488477 ArgumentCaptor<KeyspaceMetadata> ks = ArgumentCaptor.forClass(KeyspaceMetadata.class);
489478 verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onKeyspaceRemoved(ks.capture());
490479 assertThat(ks.getValue())
491480 .hasName(handleId(keyspace));
492481 }
493- for (Metadata m : metadatas) {
482+ for (Metadata m : metadatas()) {
494483 assertThat(m.getKeyspace(keyspace)).isNull();
495484 assertThat(m.getReplicas(keyspace, Bytes.fromHexString("0xCAFEBABE"))).isEmpty();
496485 }
@@ -506,8 +495,8 @@
506495 */
507496 @Test(groups = "short", expectedExceptions = IllegalStateException.class)
508497 public void should_throw_illegal_state_exception_on_newToken_with_metadata_disabled() {
509- Cluster cluster = configure(Cluster.builder())
510- .addContactPointsWithPorts(Collections.singletonList(hostAddress))
498+ Cluster cluster = Cluster.builder()
499+ .addContactPointsWithPorts(getInitialContactPoints())
511500 .withQueryOptions(nonDebouncingQueryOptions()
512501 .setMetadataEnabled(false)
513502 ).build();
@@ -530,8 +519,8 @@
530519 */
531520 @Test(groups = "short", expectedExceptions = IllegalStateException.class)
532521 public void should_throw_illegal_state_exception_on_newTokenRange_with_metadata_disabled() {
533- Cluster cluster = configure(Cluster.builder())
534- .addContactPointsWithPorts(Collections.singletonList(hostAddress))
522+ Cluster cluster = Cluster.builder()
523+ .addContactPointsWithPorts(getInitialContactPoints())
535524 .withQueryOptions(nonDebouncingQueryOptions()
536525 .setMetadataEnabled(false)
537526 ).build();
@@ -553,8 +542,8 @@
553542 * @jira_ticket JAVA-858
554543 * @since 2.0.11
555544 */
556- @Test(groups = "short")
557- public void should_not_refresh_schema_on_schema_change_response() throws InterruptedException {
545+ @Test(groups = "short", dataProvider = "existingKeyspaceName")
546+ public void should_not_refresh_schema_on_schema_change_response(String keyspace) throws InterruptedException {
558547 ResultSet rs = schemaDisabledSession.execute(String.format(CREATE_TABLE, keyspace));
559548
560549 // Should still wait on schema agreement.
@@ -572,8 +561,8 @@
572561 * @jira_ticket JAVA-858
573562 * @since 2.0.11
574563 */
575- @Test(groups = "short")
576- public void should_refresh_schema_and_token_map_if_schema_metadata_reenabled() throws Exception {
564+ @Test(groups = "short", dataProvider = "existingKeyspaceName")
565+ public void should_refresh_schema_and_token_map_if_schema_metadata_reenabled(String keyspace) throws Exception {
577566 try {
578567 schemaDisabledCluster.getConfiguration().getQueryOptions().setMetadataEnabled(true);
579568
@@ -602,28 +591,35 @@
602591 }
603592 }
604593
605- @AfterMethod(groups = "short")
594+ @AfterMethod(groups = "short", alwaysRun = true)
606595 public void cleanup() throws InterruptedException {
607- ListenableFuture<List<ResultSet>> f = Futures.successfulAsList(Lists.newArrayList(
608- session1.executeAsync("DROP TABLE lowercase.table1"),
609- session1.executeAsync("DROP TABLE \"CaseSensitive\".table1"),
610- session1.executeAsync("DROP TYPE lowercase.type1"),
611- session1.executeAsync("DROP TYPE \"CaseSensitive\".type1"),
612- session1.executeAsync("DROP FUNCTION lowercase.\"ID\""),
613- session1.executeAsync("DROP FUNCTION \"CaseSensitive\".\"ID\""),
614- session1.executeAsync("DROP FUNCTION lowercase.\"PLUS\""),
615- session1.executeAsync("DROP FUNCTION \"CaseSensitive\".\"PLUS\""),
616- session1.executeAsync("DROP AGGREGATE lowercase.\"SUM\""),
617- session1.executeAsync("DROP AGGREGATE \"CaseSensitive\".\"SUM\""),
618- session1.executeAsync("DROP MATERIALIZED VIEW lowercase.mv1"),
619- session1.executeAsync("DROP MATERIALIZED VIEW \"CaseSensitive\".mv1"),
620- session1.executeAsync("DROP KEYSPACE lowercase2"),
621- session1.executeAsync("DROP KEYSPACE \"CaseSensitive2\"")
622- ));
623- Futures.getUnchecked(f);
596+ if (session1 != null) {
597+ ListenableFuture<List<ResultSet>> f = Futures.successfulAsList(Lists.newArrayList(
598+ session1.executeAsync("DROP TABLE lowercase.table1"),
599+ session1.executeAsync("DROP TABLE \"CaseSensitive\".table1"),
600+ session1.executeAsync("DROP TYPE lowercase.type1"),
601+ session1.executeAsync("DROP TYPE \"CaseSensitive\".type1"),
602+ session1.executeAsync("DROP FUNCTION lowercase.\"ID\""),
603+ session1.executeAsync("DROP FUNCTION \"CaseSensitive\".\"ID\""),
604+ session1.executeAsync("DROP FUNCTION lowercase.\"PLUS\""),
605+ session1.executeAsync("DROP FUNCTION \"CaseSensitive\".\"PLUS\""),
606+ session1.executeAsync("DROP AGGREGATE lowercase.\"SUM\""),
607+ session1.executeAsync("DROP AGGREGATE \"CaseSensitive\".\"SUM\""),
608+ session1.executeAsync("DROP MATERIALIZED VIEW lowercase.mv1"),
609+ session1.executeAsync("DROP MATERIALIZED VIEW \"CaseSensitive\".mv1"),
610+ session1.executeAsync("DROP KEYSPACE lowercase2"),
611+ session1.executeAsync("DROP KEYSPACE \"CaseSensitive2\"")
612+ ));
613+ Futures.getUnchecked(f);
614+ }
624615 }
625616
626617 private void execute(String cql, String keyspace) throws InterruptedException {
627618 session1.execute(String.format(cql, keyspace));
628619 }
620+
621+ private List<Metadata> metadatas() {
622+ return Lists.newArrayList(cluster1.getMetadata(), cluster2.getMetadata());
623+ }
624+
629625 }
modified driver-core/src/test/java/com/datastax/driver/core/SchemaRefreshDebouncerTest.java +9 −33
@@ -17,23 +17,23 @@
1717
1818 import org.mockito.ArgumentCaptor;
1919 import org.testng.SkipException;
20-import org.testng.annotations.AfterClass;
2120 import org.testng.annotations.AfterMethod;
22-import org.testng.annotations.BeforeClass;
21+import org.testng.annotations.BeforeMethod;
2322 import org.testng.annotations.Test;
2423
25-import java.util.Collection;
2624 import java.util.Collections;
2725
2826 import static com.datastax.driver.core.Assertions.assertThat;
27+import static com.datastax.driver.core.CreateCCM.TestMode.PER_METHOD;
2928 import static com.datastax.driver.core.SchemaElement.KEYSPACE;
3029 import static com.datastax.driver.core.SchemaElement.TABLE;
3130 import static com.datastax.driver.core.TestUtils.CREATE_KEYSPACE_SIMPLE_FORMAT;
32-import static com.google.common.collect.Lists.newArrayList;
3331 import static org.mockito.ArgumentCaptor.forClass;
3432 import static org.mockito.Mockito.*;
3533
36-public class SchemaRefreshDebouncerTest extends CCMBridge.PerClassSingleNodeCluster {
34+@CreateCCM(PER_METHOD)
35+@CCMConfig(dirtiesContext = true, createKeyspace = false)
36+public class SchemaRefreshDebouncerTest extends CCMTestsSupport {
3737
3838 // This may need to be tweaked depending on the reliability of the test environment.
3939 private static final int DEBOUNCE_TIME = 5000;
@@ -48,22 +48,14 @@
4848 private Session session2;
4949 private Cluster cluster2;
5050
51- // Keyspaces to drop after test completes.
52- private Collection<String> keyspaces = newArrayList();
53-
54- @Override
55- protected Collection<String> getTableDefinitions() {
56- return newArrayList();
57- }
58-
59- @BeforeClass(groups = "short")
51+ @BeforeMethod(groups = "short")
6052 public void setup() {
6153 QueryOptions queryOptions = new QueryOptions();
6254 queryOptions.setRefreshSchemaIntervalMillis(DEBOUNCE_TIME);
6355 queryOptions.setMaxPendingRefreshSchemaRequests(5);
6456 // Create a separate cluster that will receive the schema events on its control connection.
65- cluster2 = this.configure(Cluster.builder())
66- .addContactPointsWithPorts(newArrayList(hostAddress))
57+ cluster2 = Cluster.builder()
58+ .addContactPointsWithPorts(getInitialContactPoints())
6759 .withQueryOptions(queryOptions)
6860 .build();
6961 session2 = cluster2.connect();
@@ -82,17 +74,7 @@
8274
8375 @AfterMethod(groups = "short")
8476 public void beforeMethod() {
85- reset(listener);
86- reset(controlConnection);
87- }
88-
89- @AfterClass(groups = "short")
90- public void teardown() {
9177 cluster2.close();
92- // drop all keyspaces
93- for (String keyspace : keyspaces) {
94- session.execute("DROP KEYSPACE " + keyspace);
95- }
9678 }
9779
9880 /**
@@ -108,7 +90,6 @@
10890 public void should_debounce_and_coalesce_create_and_alter_keyspace_into_refresh_keyspace() throws Exception {
10991 String keyspace = "sdaccaak";
11092 session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, 1));
111- keyspaces.add(keyspace);
11293 session.execute(String.format("ALTER KEYSPACE %s WITH DURABLE_WRITES=false", keyspace));
11394
11495 ArgumentCaptor<KeyspaceMetadata> captor = forClass(KeyspaceMetadata.class);
@@ -141,7 +122,6 @@
141122 String keyspace = "sdacckt";
142123 String table = "tbl1";
143124 session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, 1));
144- keyspaces.add(keyspace);
145125 session.execute(String.format("CREATE TABLE %s (k text PRIMARY KEY, t text, i int, f float)", keyspace + "." + table));
146126
147127 ArgumentCaptor<KeyspaceMetadata> keyspaceCaptor = forClass(KeyspaceMetadata.class);
@@ -176,7 +156,6 @@
176156 public void should_debounce_and_coalesce_tables_in_same_keyspace_into_refresh_keyspace() throws Exception {
177157 String keyspace = "sdactisk";
178158 session2.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, 1));
179- keyspaces.add(keyspace);
180159 // Reset invocations as creating keyspace causes a keyspace refresh.
181160 reset(controlConnection);
182161 reset(listener);
@@ -215,7 +194,7 @@
215194 */
216195 @Test(groups = "short")
217196 public void should_debounce_and_coalesce_multiple_alter_events_on_same_table_into_refresh_table() throws Exception {
218- if (cassandraVersion.getMajor() > 2 || cassandraVersion.getMajor() == 2 && cassandraVersion.getMinor() > 1)
197+ if (ccm.getVersion().getMajor() > 2 || ccm.getVersion().getMajor() == 2 && ccm.getVersion().getMinor() > 1)
219198 throw new SkipException("Disabled in Cassandra 2.2+ because of CASSANDRA-9996");
220199
221200 String keyspace = "sdacmaeost";
@@ -224,7 +203,6 @@
224203 String columnName = "added_column";
225204 // Execute on session 2 which refreshes schema as part of processing responses.
226205 session2.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, 1));
227- keyspaces.add(keyspace);
228206 session2.execute(String.format("CREATE TABLE %s (k text PRIMARY KEY, t text, i int, f float)", keyspace + "." + table));
229207 reset(controlConnection);
230208 reset(listener);
@@ -275,7 +253,6 @@
275253 String prefix = "sdacmkc";
276254 for (int i = 0; i < 3; i++) {
277255 session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, prefix + i, 1));
278- keyspaces.add(prefix + i);
279256 }
280257
281258 verify(listener, timeout(DEBOUNCE_TIME * 3).times(3)).onKeyspaceAdded(any(KeyspaceMetadata.class));
@@ -302,7 +279,6 @@
302279 String prefix = "srwmprr";
303280 for (int i = 0; i < 5; i++) {
304281 session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, prefix + i, 1));
305- keyspaces.add(prefix + i);
306282 }
307283
308284 // Event should be processed immediately as we hit our threshold.
modified driver-core/src/test/java/com/datastax/driver/core/SessionLeakTest.java +69 −98
@@ -17,139 +17,110 @@
1717
1818 import com.datastax.driver.core.exceptions.InvalidQueryException;
1919 import com.datastax.driver.core.utils.SocketChannelMonitor;
20-import com.google.common.collect.Lists;
2120 import org.testng.annotations.Test;
2221
23-import java.net.InetSocketAddress;
24-import java.util.Collections;
25-import java.util.List;
2622 import java.util.concurrent.TimeUnit;
2723
2824 import static com.datastax.driver.core.Assertions.assertThat;
25+import static com.datastax.driver.core.CreateCCM.TestMode.PER_METHOD;
2926 import static com.datastax.driver.core.TestUtils.nonDebouncingQueryOptions;
27+import static com.google.common.collect.Lists.newArrayList;
3028 import static java.util.concurrent.TimeUnit.MINUTES;
3129 import static org.assertj.core.api.Assertions.fail;
3230
33-public class SessionLeakTest {
31+@CreateCCM(PER_METHOD)
32+@CCMConfig(dirtiesContext = true, createCluster = false)
33+public class SessionLeakTest extends CCMTestsSupport {
3434
35- Cluster cluster;
36- List<InetSocketAddress> nodes = Lists.newArrayList(
37- new InetSocketAddress(CCMBridge.IP_PREFIX + '1', 9042),
38- new InetSocketAddress(CCMBridge.IP_PREFIX + '2', 9042));
3935 SocketChannelMonitor channelMonitor;
4036
4137 @Test(groups = "short")
4238 public void connectionLeakTest() throws Exception {
4339 // Checking for JAVA-342
44- CCMBridge ccmBridge;
45- ccmBridge = CCMBridge.builder("test").withNodes(1).build();
4640 channelMonitor = new SocketChannelMonitor();
4741 channelMonitor.reportAtFixedInterval(1, TimeUnit.SECONDS);
48- try {
49- cluster = Cluster.builder()
50- .addContactPointsWithPorts(Collections.singletonList(
51- new InetSocketAddress(CCMBridge.IP_PREFIX + '1', 9042)))
52- .withNettyOptions(channelMonitor.nettyOptions())
53- .withQueryOptions(nonDebouncingQueryOptions())
54- .build();
55-
56- cluster.init();
57-
58- assertThat(cluster.manager.sessions.size()).isEqualTo(0);
59- // Should be 1 control connection after initialization.
60- assertOpenConnections(1);
61-
62- // ensure sessions.size() returns with 1 control connection + core pool size.
63- int corePoolSize = TestUtils.numberOfLocalCoreConnections(cluster);
64- Session session = cluster.connect();
65-
66- assertThat(cluster.manager.sessions.size()).isEqualTo(1);
67- assertOpenConnections(1 + corePoolSize);
68-
69- // ensure sessions.size() returns to 0 with only 1 active connection (the control connection)
70- session.close();
71- assertThat(cluster.manager.sessions.size()).isEqualTo(0);
72- assertOpenConnections(1);
73-
74- // ensure bootstrapping a node does not create additional connections
75- ccmBridge.bootstrapNode(2);
76- ccmBridge.waitForUp(2);
77- assertThat(cluster).host(2).comesUpWithin(2, MINUTES);
78-
79- assertThat(cluster.manager.sessions.size()).isEqualTo(0);
80- assertOpenConnections(1);
81-
82- // ensure a new session gets registered and core connections are established
83- // there should be corePoolSize more connections to accommodate for the new host.
84- Session thisSession = cluster.connect();
85- assertThat(cluster.manager.sessions.size()).isEqualTo(1);
86- assertOpenConnections(1 + (corePoolSize * 2));
87-
88- // ensure bootstrapping a node does not create additional connections that won't get cleaned up
89- thisSession.close();
90-
91- assertThat(cluster.manager.sessions.size()).isEqualTo(0);
92- assertOpenConnections(1);
93- } finally {
94- if (cluster != null) {
95- cluster.close();
96- }
97- if (ccmBridge != null) {
98- ccmBridge.remove();
99- }
100- // Ensure no channels remain open.
101- channelMonitor.stop();
102- channelMonitor.report();
103- assertThat(channelMonitor.openChannels(nodes).size()).isEqualTo(0);
104- }
42+ cluster = register(Cluster.builder()
43+ .addContactPointsWithPorts(getHostAddress(1))
44+ .withAddressTranslator(getAddressTranslator())
45+ .withNettyOptions(channelMonitor.nettyOptions())
46+ .withQueryOptions(nonDebouncingQueryOptions())
47+ .build());
48+
49+ cluster.init();
50+
51+ assertThat(cluster.manager.sessions.size()).isEqualTo(0);
52+ // Should be 1 control connection after initialization.
53+ assertOpenConnections(1);
54+
55+ // ensure sessions.size() returns with 1 control connection + core pool size.
56+ int corePoolSize = TestUtils.numberOfLocalCoreConnections(cluster);
57+ Session session = cluster.connect();
58+
59+ assertThat(cluster.manager.sessions.size()).isEqualTo(1);
60+ assertOpenConnections(1 + corePoolSize);
61+
62+ // ensure sessions.size() returns to 0 with only 1 active connection (the control connection)
63+ session.close();
64+ assertThat(cluster.manager.sessions.size()).isEqualTo(0);
65+ assertOpenConnections(1);
66+
67+ // ensure bootstrapping a node does not create additional connections
68+ ccm.add(2);
69+ ccm.start(2);
70+ ccm.waitForUp(2);
71+ assertThat(cluster).host(2).comesUpWithin(2, MINUTES);
72+
73+ assertThat(cluster.manager.sessions.size()).isEqualTo(0);
74+ assertOpenConnections(1);
75+
76+ // ensure a new session gets registered and core connections are established
77+ // there should be corePoolSize more connections to accommodate for the new host.
78+ Session thisSession = cluster.connect();
79+ assertThat(cluster.manager.sessions.size()).isEqualTo(1);
80+ assertOpenConnections(1 + (corePoolSize * 2));
81+
82+ // ensure bootstrapping a node does not create additional connections that won't get cleaned up
83+ thisSession.close();
84+
85+ assertThat(cluster.manager.sessions.size()).isEqualTo(0);
86+ assertOpenConnections(1);
87+ cluster.close();
88+ // Ensure no channels remain open.
89+ channelMonitor.stop();
90+ channelMonitor.report();
91+ assertThat(channelMonitor.openChannels(newArrayList(ccm.addressOfNode(1), ccm.addressOfNode(2))).size()).isEqualTo(0);
10592 }
10693
10794 @Test(groups = "short")
10895 public void should_not_leak_session_when_wrong_keyspace() throws Exception {
10996 // Checking for JAVA-806
110- CCMBridge ccmBridge;
111- ccmBridge = CCMBridge.builder("test").withNodes(1).build();
11297 channelMonitor = new SocketChannelMonitor();
11398 channelMonitor.reportAtFixedInterval(1, TimeUnit.SECONDS);
99+ cluster = register(Cluster.builder()
100+ .addContactPointsWithPorts(getHostAddress(1))
101+ .withAddressTranslator(getAddressTranslator())
102+ .withNettyOptions(channelMonitor.nettyOptions())
103+ .build());
104+ cluster.init();
105+ assertThat(cluster.manager.sessions.size()).isEqualTo(0);
114106 try {
115- cluster = Cluster.builder()
116- .addContactPointsWithPorts(Collections.singletonList(
117- new InetSocketAddress(CCMBridge.IP_PREFIX + '1', 9042)))
118- .withNettyOptions(channelMonitor.nettyOptions()).build();
119-
120- cluster.init();
121-
122- assertThat(cluster.manager.sessions.size()).isEqualTo(0);
123107 // Should be 1 control connection after initialization.
124108 assertOpenConnections(1);
125-
126109 cluster.connect("wrong_keyspace");
127-
128110 fail("Should not have connected to a wrong keyspace");
129-
130111 } catch (InvalidQueryException e) {
131-
132112 // ok
133-
134- } finally {
135-
136- assertThat(cluster.manager.sessions.size()).isEqualTo(0);
137-
138- if (cluster != null) {
139- cluster.close();
140- }
141- if (ccmBridge != null) {
142- ccmBridge.remove();
143- }
144- // Ensure no channels remain open.
145- channelMonitor.stop();
146- channelMonitor.report();
147- assertThat(channelMonitor.openChannels(nodes).size()).isEqualTo(0);
148113 }
114+ assertThat(cluster.manager.sessions.size()).isEqualTo(0);
115+ cluster.close();
116+ // Ensure no channels remain open.
117+ channelMonitor.stop();
118+ channelMonitor.report();
119+ assertThat(channelMonitor.openChannels(ccm.addressOfNode(1), ccm.addressOfNode(2)).size()).isEqualTo(0);
149120 }
150121
151122 private void assertOpenConnections(int expected) {
152123 assertThat((cluster.getMetrics().getOpenConnections().getValue())).isEqualTo(expected);
153- assertThat(channelMonitor.openChannels(nodes).size()).isEqualTo(expected);
124+ assertThat(channelMonitor.openChannels(ccm.addressOfNode(1), ccm.addressOfNode(2)).size()).isEqualTo(expected);
154125 }
155126 }
modified driver-core/src/test/java/com/datastax/driver/core/SessionStressTest.java +29 −16
@@ -23,16 +23,19 @@
2323 import com.google.common.util.concurrent.Uninterruptibles;
2424 import org.slf4j.Logger;
2525 import org.slf4j.LoggerFactory;
26+import org.testng.annotations.AfterMethod;
2627 import org.testng.annotations.Test;
2728
28-import java.net.InetSocketAddress;
29-import java.util.*;
29+import java.util.Iterator;
30+import java.util.List;
31+import java.util.Stack;
3032 import java.util.concurrent.*;
3133
3234 import static org.testng.Assert.assertEquals;
3335 import static org.testng.Assert.fail;
3436
35-public class SessionStressTest extends CCMBridge.PerClassSingleNodeCluster {
37+@CCMConfig(dirtiesContext = true)
38+public class SessionStressTest extends CCMTestsSupport {
3639
3740 private static final Logger logger = LoggerFactory.getLogger(SessionStressTest.class);
3841
@@ -47,9 +50,16 @@
4750 executorService = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(8));
4851 }
4952
50- @Override
51- protected Collection<String> getTableDefinitions() {
52- return new ArrayList<String>(0);
53+ @AfterMethod(groups = "long", alwaysRun = true)
54+ public void shutdown() throws Exception {
55+ executorService.shutdown();
56+ try {
57+ boolean shutdown = executorService.awaitTermination(30, TimeUnit.SECONDS);
58+ if (!shutdown)
59+ fail("executor ran for longer than expected");
60+ } catch (InterruptedException e) {
61+ fail("Interrupted while waiting for executor to shutdown");
62+ }
5363 }
5464
5565 /**
@@ -77,10 +87,9 @@
7787 */
7888 @Test(groups = "long")
7989 public void sessions_should_not_leak_connections() {
80- List<InetSocketAddress> contactPoints = Collections.singletonList(hostAddress);
8190 // override inherited field with a new cluster object and ensure 0 sessions and connections
8291 channelMonitor.reportAtFixedInterval(1, TimeUnit.SECONDS);
83- stressCluster = Cluster.builder().addContactPointsWithPorts(contactPoints)
92+ stressCluster = Cluster.builder().addContactPointsWithPorts(getInitialContactPoints())
8493 .withPoolingOptions(new PoolingOptions().setCoreConnectionsPerHost(HostDistance.LOCAL, 1))
8594 .withNettyOptions(channelMonitor.nettyOptions()).build();
8695
@@ -97,13 +106,13 @@
97106 assertEquals(stressCluster.manager.sessions.size(), 1);
98107 int coreConnections = TestUtils.numberOfLocalCoreConnections(stressCluster);
99108 assertEquals((int) stressCluster.getMetrics().getOpenConnections().getValue(), 1 + coreConnections);
100- assertEquals(channelMonitor.openChannels(contactPoints).size(), 1 + coreConnections);
109+ assertEquals(channelMonitor.openChannels(getInitialContactPoints()).size(), 1 + coreConnections);
101110
102111 // Closing the session keeps the control connection opened
103112 session.close();
104113 assertEquals(stressCluster.manager.sessions.size(), 0);
105114 assertEquals((int) stressCluster.getMetrics().getOpenConnections().getValue(), 1);
106- assertEquals(channelMonitor.openChannels(contactPoints).size(), 1);
115+ assertEquals(channelMonitor.openChannels(getInitialContactPoints()).size(), 1);
107116
108117 int nbOfSessions = 2000;
109118 int halfOfTheSessions = nbOfSessions / 2;
@@ -120,7 +129,7 @@
120129 assertEquals(stressCluster.manager.sessions.size(), nbOfSessions);
121130 assertEquals((int) stressCluster.getMetrics().getOpenConnections().getValue(),
122131 coreConnections * nbOfSessions + 1);
123- assertEquals(channelMonitor.openChannels(contactPoints).size(), coreConnections * nbOfSessions + 1);
132+ assertEquals(channelMonitor.openChannels(getInitialContactPoints()).size(), coreConnections * nbOfSessions + 1);
124133
125134 // Close half of the sessions asynchronously
126135 logger.info("Closing {}/{} sessions.", halfOfTheSessions, nbOfSessions);
@@ -130,7 +139,7 @@
130139 assertEquals(stressCluster.manager.sessions.size(), halfOfTheSessions);
131140 assertEquals((int) stressCluster.getMetrics().getOpenConnections().getValue(),
132141 coreConnections * (nbOfSessions / 2) + 1);
133- assertEquals(channelMonitor.openChannels(contactPoints).size(),
142+ assertEquals(channelMonitor.openChannels(getInitialContactPoints()).size(),
134143 coreConnections * (nbOfSessions / 2) + 1);
135144
136145 // Close and open the same number of sessions concurrently
@@ -148,7 +157,7 @@
148157 assertEquals(stressCluster.manager.sessions.size(), halfOfTheSessions);
149158 assertEquals((int) stressCluster.getMetrics().getOpenConnections().getValue(),
150159 coreConnections * (nbOfSessions / 2) + 1);
151- assertEquals(channelMonitor.openChannels(contactPoints).size(),
160+ assertEquals(channelMonitor.openChannels(getInitialContactPoints()).size(),
152161 coreConnections * (nbOfSessions / 2) + 1);
153162
154163 // Close the remaining sessions
@@ -158,7 +167,7 @@
158167 // Check that we have a clean state
159168 assertEquals(stressCluster.manager.sessions.size(), 0);
160169 assertEquals((int) stressCluster.getMetrics().getOpenConnections().getValue(), 1);
161- assertEquals(channelMonitor.openChannels(contactPoints).size(), 1);
170+ assertEquals(channelMonitor.openChannels(getInitialContactPoints()).size(), 1);
162171
163172 // On OSX, the TCP connections are released after 15s by default (sysctl -a net.inet.tcp.msl)
164173 logger.info("Sleeping {} seconds so that TCP connections are released by the OS", sleepTime);
@@ -168,10 +177,14 @@
168177 stressCluster.close();
169178
170179 // Ensure no channels remain open.
171- assertEquals(channelMonitor.openChannels(contactPoints).size(), 0);
180+ assertEquals(channelMonitor.openChannels(getInitialContactPoints()).size(), 0);
172181
173182 channelMonitor.stop();
174183 channelMonitor.report();
184+
185+ logger.info("Sleeping 60 extra seconds");
186+ Uninterruptibles.sleepUninterruptibly(60, TimeUnit.SECONDS);
187+
175188 }
176189 }
177190
@@ -264,4 +277,4 @@
264277 return session.closeAsync();
265278 }
266279 }
267-}
No newline at the end of the file
280+}
modified driver-core/src/test/java/com/datastax/driver/core/SessionTest.java +48 −46
@@ -16,11 +16,12 @@
1616 package com.datastax.driver.core;
1717
1818 import com.datastax.driver.core.utils.CassandraVersion;
19-import org.slf4j.Logger;
20-import org.slf4j.LoggerFactory;
2119 import org.testng.annotations.Test;
2220
23-import java.util.*;
21+import java.util.Arrays;
22+import java.util.Collection;
23+import java.util.List;
24+import java.util.Locale;
2425 import java.util.concurrent.CountDownLatch;
2526 import java.util.concurrent.ExecutorService;
2627 import java.util.concurrent.Executors;
@@ -32,9 +33,7 @@
3233 /**
3334 * Simple test of the Sessions methods against a one node cluster.
3435 */
35-public class SessionTest extends CCMBridge.PerClassSingleNodeCluster {
36-
37- private static final Logger logger = LoggerFactory.getLogger(SessionTest.class);
36+public class SessionTest extends CCMTestsSupport {
3837
3938 private static final String TABLE1 = "test1";
4039 private static final String TABLE2 = "test2";
@@ -42,7 +41,7 @@
4241 private static final String COUNTER_TABLE = "counters";
4342
4443 @Override
45- protected Collection<String> getTableDefinitions() {
44+ public Collection<String> createTestFixtures() {
4645 return Arrays.asList(String.format("CREATE TABLE %s (k text PRIMARY KEY, t text, i int, f float)", TABLE1),
4746 String.format("CREATE TABLE %s (k text PRIMARY KEY, t text, i int, f float)", TABLE2),
4847 String.format("CREATE TABLE %s (k text PRIMARY KEY, t text, i int, f float)", TABLE3),
@@ -168,49 +167,52 @@
168167 // Use our own cluster and session (not the ones provided by the parent class) because we want an uninitialized cluster
169168 // (note the use of newSession below)
170169 final Cluster cluster = Cluster.builder()
171- .addContactPointsWithPorts(Collections.singletonList(hostAddress))
170+ .addContactPointsWithPorts(getInitialContactPoints())
172171 .withNettyOptions(nonQuietClusterCloseOptions)
173172 .build();
174- final Session session = cluster.newSession();
175-
176- // Spawn two threads to simulate the race
177- ExecutorService executor = Executors.newFixedThreadPool(2);
178- final CountDownLatch startLatch = new CountDownLatch(1);
179-
180- executor.execute(new Runnable() {
181- @Override
182- public void run() {
183- try {
184- startLatch.await();
185- cluster.init();
186- } catch (InterruptedException e) {
187- fail("unexpected interruption", e);
173+ try {
174+ final Session session = cluster.newSession();
175+
176+ // Spawn two threads to simulate the race
177+ ExecutorService executor = Executors.newFixedThreadPool(2);
178+ final CountDownLatch startLatch = new CountDownLatch(1);
179+
180+ executor.execute(new Runnable() {
181+ @Override
182+ public void run() {
183+ try {
184+ startLatch.await();
185+ cluster.init();
186+ } catch (InterruptedException e) {
187+ fail("unexpected interruption", e);
188+ }
188189 }
189- }
190- });
191-
192- executor.execute(new Runnable() {
193- @Override
194- public void run() {
195- try {
196- startLatch.await();
197- TimeUnit.MILLISECONDS.sleep(10);
198- session.close();
199- } catch (InterruptedException e) {
200- fail("unexpected interruption", e);
190+ });
191+
192+ executor.execute(new Runnable() {
193+ @Override
194+ public void run() {
195+ try {
196+ startLatch.await();
197+ TimeUnit.MILLISECONDS.sleep(10);
198+ session.close();
199+ } catch (InterruptedException e) {
200+ fail("unexpected interruption", e);
201+ }
201202 }
202- }
203- });
204-
205- // Start the threads
206- startLatch.countDown();
207-
208- executor.shutdown();
209- boolean normalShutdown = executor.awaitTermination(5, TimeUnit.SECONDS);
210- assertTrue(normalShutdown);
211-
212- // The deadlock occurred here before JAVA-418
213- cluster.close();
203+ });
204+
205+ // Start the threads
206+ startLatch.countDown();
207+
208+ executor.shutdown();
209+ boolean normalShutdown = executor.awaitTermination(5, TimeUnit.SECONDS);
210+ assertTrue(normalShutdown);
211+
212+ } finally {
213+ // The deadlock occurred here before JAVA-418
214+ cluster.close();
215+ }
214216 }
215217 }
216218 }
modified driver-core/src/test/java/com/datastax/driver/core/SingleConnectionPoolTest.java +2 −9
@@ -17,10 +17,7 @@
1717
1818 import com.datastax.driver.core.utils.CassandraVersion;
1919 import org.testng.annotations.Test;
20-import org.testng.collections.Lists;
2120
22-import java.net.InetSocketAddress;
23-import java.util.Collection;
2421 import java.util.concurrent.Executors;
2522 import java.util.concurrent.ScheduledExecutorService;
2623 import java.util.concurrent.TimeUnit;
@@ -29,11 +26,7 @@
2926 import static org.testng.Assert.fail;
3027
3128 @CassandraVersion(major = 2.1)
32-public class SingleConnectionPoolTest extends CCMBridge.PerClassSingleNodeCluster {
33- @Override
34- protected Collection<String> getTableDefinitions() {
35- return Lists.newArrayList();
36- }
29+public class SingleConnectionPoolTest extends CCMTestsSupport {
3730
3831 @Test(groups = "short")
3932 public void should_throttle_requests() {
@@ -44,7 +37,7 @@
4437
4538 // Track in flight requests in a dedicated thread every second
4639 final AtomicBoolean excessInflightQueriesSpotted = new AtomicBoolean(false);
47- final Host host = cluster.getMetadata().getHost(new InetSocketAddress(CCMBridge.IP_PREFIX + "1", 9042));
40+ final Host host = cluster.getMetadata().getHost(ccm.addressOfNode(1));
4841 ScheduledExecutorService openConnectionsWatcherExecutor = Executors.newScheduledThreadPool(1);
4942 final Runnable openConnectionsWatcher = new Runnable() {
5043 @Override
modified driver-core/src/test/java/com/datastax/driver/core/SingleTokenIntegrationTest.java +27 −49
@@ -23,59 +23,37 @@
2323
2424 import static com.datastax.driver.core.Assertions.assertThat;
2525
26-public class SingleTokenIntegrationTest {
26+@CCMConfig(
27+ // force the initial token to a non-min value to validate that the single range will always be ]minToken, minToken]
28+ config = "initial_token:1",
29+ clusterProvider = "createClusterBuilderNoDebouncing"
30+)
31+public class SingleTokenIntegrationTest extends CCMTestsSupport {
32+
2733 /**
2834 * JAVA-684: Empty TokenRange returned in a one token cluster
2935 */
3036 @Test(groups = "short")
3137 public void should_return_single_non_empty_range_when_cluster_has_one_single_token() {
32- CCMBridge ccm = null;
33- Cluster cluster = null;
34-
35- try {
36- ccm = CCMBridge.builder("test")
37- // force the initial token to a non-min value to validate that the single range will always be ]minToken, minToken]
38- .withCassandraConfiguration("initial_token", "1")
39- .build();
40-
41- cluster = Cluster.builder()
42- .addContactPoint(CCMBridge.ipOfNode(1))
43- .withQueryOptions(new QueryOptions()
44- .setRefreshNodeIntervalMillis(0)
45- .setRefreshNodeListIntervalMillis(0)
46- .setRefreshSchemaIntervalMillis(0)
47- )
48- .build();
49-
50- Session session = cluster.connect();
51- session.execute("create keyspace test with replication = {'class': 'SimpleStrategy', 'replication_factor': 1}");
52-
53- Metadata metadata = cluster.getMetadata();
54-
55- Set<TokenRange> tokenRanges = metadata.getTokenRanges();
56- assertThat(tokenRanges).hasSize(1);
57- TokenRange tokenRange = tokenRanges.iterator().next();
58- assertThat(tokenRange)
59- .startsWith(Token.M3PToken.FACTORY.minToken())
60- .endsWith(Token.M3PToken.FACTORY.minToken())
61- .isNotEmpty()
62- .isNotWrappedAround();
63-
64- Set<Host> hostsForRange = metadata.getReplicas("test", tokenRange);
65- Host host1 = TestUtils.findHost(cluster, 1);
66- assertThat(hostsForRange).containsOnly(host1);
67-
68- ByteBuffer randomPartitionKey = Bytes.fromHexString("0xCAFEBABE");
69- Set<Host> hostsForKey = metadata.getReplicas("test", randomPartitionKey);
70- assertThat(hostsForKey).containsOnly(host1);
71-
72- Set<TokenRange> rangesForHost = metadata.getTokenRanges("test", host1);
73- assertThat(rangesForHost).containsOnly(tokenRange);
74- } finally {
75- if (cluster != null)
76- cluster.close();
77- if (ccm != null)
78- ccm.remove();
79- }
38+ Metadata metadata = cluster.getMetadata();
39+ Set<TokenRange> tokenRanges = metadata.getTokenRanges();
40+ assertThat(tokenRanges).hasSize(1);
41+ TokenRange tokenRange = tokenRanges.iterator().next();
42+ assertThat(tokenRange)
43+ .startsWith(Token.M3PToken.FACTORY.minToken())
44+ .endsWith(Token.M3PToken.FACTORY.minToken())
45+ .isNotEmpty()
46+ .isNotWrappedAround();
47+
48+ Set<Host> hostsForRange = metadata.getReplicas(keyspace, tokenRange);
49+ Host host1 = TestUtils.findHost(cluster, 1);
50+ assertThat(hostsForRange).containsOnly(host1);
51+
52+ ByteBuffer randomPartitionKey = Bytes.fromHexString("0xCAFEBABE");
53+ Set<Host> hostsForKey = metadata.getReplicas(keyspace, randomPartitionKey);
54+ assertThat(hostsForKey).containsOnly(host1);
55+
56+ Set<TokenRange> rangesForHost = metadata.getTokenRanges(keyspace, host1);
57+ assertThat(rangesForHost).containsOnly(tokenRange);
8058 }
8159 }
modified driver-core/src/test/java/com/datastax/driver/core/SpeculativeExecutionIntegrationTest.java +4 −4
@@ -30,19 +30,19 @@
3030 * Test that needs a real CCM cluster (as opposed to SCassandra for other specex tests), because
3131 * it uses a protocol v3 feature.
3232 */
33-public class SpeculativeExecutionIntegrationTest extends CCMBridge.PerClassSingleNodeCluster {
33+public class SpeculativeExecutionIntegrationTest extends CCMTestsSupport {
3434
3535 TimestampGenerator timestampGenerator;
3636
3737 @Override
38- protected Collection<String> getTableDefinitions() {
38+ public Collection<String> createTestFixtures() {
3939 return Lists.newArrayList("create table foo(k int primary key, v int)");
4040 }
4141
4242 @Override
43- protected Cluster.Builder configure(Cluster.Builder builder) {
43+ public Cluster.Builder createClusterBuilder() {
4444 timestampGenerator = Mockito.spy(ServerSideTimestampGenerator.INSTANCE);
45- return builder
45+ return Cluster.builder()
4646 .withTimestampGenerator(timestampGenerator)
4747 .withQueryOptions(new QueryOptions().setDefaultIdempotence(true))
4848 // Set an artificially low timeout to force speculative execution
modified driver-core/src/test/java/com/datastax/driver/core/SpeculativeExecutionTest.java +24 −22
@@ -51,7 +51,8 @@
5151
5252 loadBalancingPolicy = new SortingLoadBalancingPolicy();
5353 cluster = Cluster.builder()
54- .addContactPoint(scassandras.address(2))
54+ .addContactPointsWithPorts(scassandras.address(2))
55+ .withAddressTranslator(scassandras.addressTranslator())
5556 .withProtocolVersion(ProtocolVersion.V2) // Scassandra does not support V3 nor V4 yet
5657 .withLoadBalancingPolicy(loadBalancingPolicy)
5758 .withSpeculativeExecutionPolicy(new ConstantSpeculativeExecutionPolicy(speculativeExecutionDelay, 1))
@@ -69,7 +70,7 @@
6970 errors = cluster.getMetrics().getErrorMetrics();
7071 }
7172
72- @AfterMethod(groups = "short")
73+ @AfterMethod(groups = "short", alwaysRun = true)
7374 public void afterMethod() {
7475 if (cluster != null)
7576 cluster.close();
@@ -80,9 +81,9 @@
8081 @Test(groups = "short")
8182 public void should_not_start_speculative_execution_if_first_execution_completes_successfully() {
8283 scassandras.node(1).primingClient().prime(PrimingRequest.queryBuilder()
83- .withQuery("mock query")
84- .withRows(row("result", "result1"))
85- .build()
84+ .withQuery("mock query")
85+ .withRows(row("result", "result1"))
86+ .build()
8687 );
8788
8889 long execStartCount = errors.getSpeculativeExecutions().getCount();
@@ -99,17 +100,17 @@
99100 public void should_not_start_speculative_execution_if_first_execution_retries_but_is_still_fast_enough() {
100101 // will retry once on this node:
101102 scassandras.node(1).primingClient().prime(PrimingRequest.queryBuilder()
102- .withQuery("mock query")
103- .withConsistency(PrimingRequest.Consistency.TWO)
104- .withResult(PrimingRequest.Result.read_request_timeout)
105- .build()
103+ .withQuery("mock query")
104+ .withConsistency(PrimingRequest.Consistency.TWO)
105+ .withResult(PrimingRequest.Result.read_request_timeout)
106+ .build()
106107 );
107108
108109 scassandras.node(1).primingClient().prime(PrimingRequest.queryBuilder()
109- .withQuery("mock query")
110- .withConsistency(PrimingRequest.Consistency.ONE)
111- .withRows(row("result", "result1"))
112- .build()
110+ .withQuery("mock query")
111+ .withConsistency(PrimingRequest.Consistency.ONE)
112+ .withRows(row("result", "result1"))
113+ .build()
113114 );
114115
115116 long execStartCount = errors.getSpeculativeExecutions().getCount();
@@ -129,16 +130,16 @@
129130 @Test(groups = "short")
130131 public void should_start_speculative_execution_if_first_execution_takes_too_long() {
131132 scassandras.node(1).primingClient().prime(PrimingRequest.queryBuilder()
132- .withQuery("mock query")
133- .withFixedDelay(400)
134- .withRows(row("result", "result1"))
135- .build()
133+ .withQuery("mock query")
134+ .withFixedDelay(400)
135+ .withRows(row("result", "result1"))
136+ .build()
136137 );
137138
138139 scassandras.node(2).primingClient().prime(PrimingRequest.queryBuilder()
139- .withQuery("mock query")
140- .withRows(row("result", "result2"))
141- .build()
140+ .withQuery("mock query")
141+ .withRows(row("result", "result2"))
142+ .build()
142143 );
143144 long execStartCount = errors.getSpeculativeExecutions().getCount();
144145
@@ -202,8 +203,9 @@
202203 SpeculativeExecutionPolicy mockPolicy = mock(SpeculativeExecutionPolicy.class);
203204
204205 Cluster cluster = Cluster.builder()
205- .addContactPoint(CCMBridge.ipOfNode(2))
206- // Scassandra does not support V3 nor V4 yet, and V4 may cause the server to crash
206+ .addContactPointsWithPorts(scassandras.address(2))
207+ .withAddressTranslator(scassandras.addressTranslator())
208+ // Scassandra does not support V3 nor V4 yet, and V4 may cause the server to crash
207209 .withProtocolVersion(ProtocolVersion.V2)
208210 .withSpeculativeExecutionPolicy(mockPolicy)
209211 .build();
modified driver-core/src/test/java/com/datastax/driver/core/StateListenerTest.java +20 −30
@@ -21,48 +21,38 @@
2121
2222 import java.util.concurrent.CountDownLatch;
2323
24+import static com.datastax.driver.core.CreateCCM.TestMode.PER_METHOD;
2425 import static com.datastax.driver.core.StateListenerTest.TestListener.Event.*;
2526 import static java.util.concurrent.TimeUnit.MINUTES;
2627 import static org.assertj.core.api.Assertions.assertThat;
2728
28-public class StateListenerTest {
29+@CreateCCM(PER_METHOD)
30+@CCMConfig(dirtiesContext = true, createSession = false)
31+public class StateListenerTest extends CCMTestsSupport {
32+
2933 private static final Logger logger = LoggerFactory.getLogger(StateListenerTest.class);
3034
3135 @Test(groups = "long")
3236 public void should_receive_events_when_node_states_change() throws InterruptedException {
33- CCMBridge ccm = null;
34- Cluster cluster = null;
35- try {
36- ccm = CCMBridge.builder("test").build();
37- cluster = Cluster.builder()
38- .addContactPoint(CCMBridge.ipOfNode(1))
39- .build();
40- cluster.init();
41- TestListener listener = new TestListener();
42- cluster.register(listener);
43-
44- listener.setExpectedEvent(ADD);
45- ccm.bootstrapNode(2);
46- listener.waitForEvent();
37+ TestListener listener = new TestListener();
38+ cluster.register(listener);
4739
48- listener.setExpectedEvent(DOWN);
49- ccm.forceStop(1);
50- listener.waitForEvent();
40+ listener.setExpectedEvent(ADD);
41+ ccm.add(2);
42+ ccm.start(2);
43+ listener.waitForEvent();
5144
52- listener.setExpectedEvent(UP);
53- ccm.start(1);
54- listener.waitForEvent();
45+ listener.setExpectedEvent(DOWN);
46+ ccm.forceStop(1);
47+ listener.waitForEvent();
5548
56- listener.setExpectedEvent(REMOVE);
57- ccm.decommissionNode(2);
58- listener.waitForEvent();
49+ listener.setExpectedEvent(UP);
50+ ccm.start(1);
51+ listener.waitForEvent();
5952
60- } finally {
61- if (cluster != null)
62- cluster.close();
63- if (ccm != null)
64- ccm.remove();
65- }
53+ listener.setExpectedEvent(REMOVE);
54+ ccm.decommissionNode(2);
55+ listener.waitForEvent();
6656 }
6757
6858 static class TestListener implements Host.StateListener {
modified driver-core/src/test/java/com/datastax/driver/core/StatementWrapperTest.java +3 −9
@@ -17,28 +17,22 @@
1717
1818 import com.datastax.driver.core.exceptions.DriverException;
1919 import com.datastax.driver.core.policies.*;
20-import com.google.common.collect.Lists;
2120 import org.testng.annotations.Test;
2221
23-import java.util.Collection;
2422 import java.util.Iterator;
2523 import java.util.concurrent.atomic.AtomicInteger;
2624
2725 import static org.assertj.core.api.Assertions.assertThat;
2826
29-public class StatementWrapperTest extends CCMBridge.PerClassSingleNodeCluster {
30- @Override
31- protected Collection<String> getTableDefinitions() {
32- return Lists.newArrayList();
33- }
27+public class StatementWrapperTest extends CCMTestsSupport {
3428
3529 CustomLoadBalancingPolicy loadBalancingPolicy = new CustomLoadBalancingPolicy();
3630 CustomSpeculativeExecutionPolicy speculativeExecutionPolicy = new CustomSpeculativeExecutionPolicy();
3731 CustomRetryPolicy retryPolicy = new CustomRetryPolicy();
3832
3933 @Override
40- protected Cluster.Builder configure(Cluster.Builder builder) {
41- return builder
34+ public Cluster.Builder createClusterBuilder() {
35+ return Cluster.builder()
4236 .withLoadBalancingPolicy(loadBalancingPolicy)
4337 .withSpeculativeExecutionPolicy(speculativeExecutionPolicy)
4438 .withRetryPolicy(retryPolicy);
modified driver-core/src/test/java/com/datastax/driver/core/TableMetadataTest.java +2 −14
@@ -29,11 +29,8 @@
2929 import static com.datastax.driver.core.DataType.*;
3030 import static org.assertj.core.api.Assertions.entry;
3131
32-public class TableMetadataTest extends CCMBridge.PerClassSingleNodeCluster {
33- @Override
34- protected Collection<String> getTableDefinitions() {
35- return Collections.emptyList();
36- }
32+@CCMConfig(clusterProvider = "createClusterBuilderNoDebouncing")
33+public class TableMetadataTest extends CCMTestsSupport {
3734
3835 @Test(groups = "short")
3936 public void should_parse_table_without_clustering_columns() {
@@ -56,15 +53,6 @@
5653 assertThat(table.getColumns().get(3)).isNotNull().hasName("v").isRegularColumn().hasType(cint());
5754 }
5855
59- @Override
60- protected Cluster.Builder configure(Cluster.Builder builder) {
61- return builder.withQueryOptions(new QueryOptions()
62- .setRefreshNodeIntervalMillis(0)
63- .setRefreshNodeListIntervalMillis(0)
64- .setRefreshSchemaIntervalMillis(0)
65- );
66- }
67-
6856 @Test(groups = "short")
6957 public void should_parse_table_with_clustering_columns() {
7058 // given
modified driver-core/src/test/java/com/datastax/driver/core/TestListener.java +7 −8
@@ -32,10 +32,9 @@
3232 public void onTestFailure(ITestResult tr) {
3333 long elapsedTime = TimeUnit.NANOSECONDS.toSeconds((System.nanoTime() - start_time));
3434 long testTime = tr.getEndMillis() - tr.getStartMillis();
35-
3635 tr.getThrowable().printStackTrace();
37- System.out.println("FAILED: " + tr.getName());
38- System.out.println("Test: " + formatIntoHHMMSS(testTime / 1000));
36+ System.out.println("FAILED : " + tr.getName());
37+ System.out.println("Test : " + formatIntoHHMMSS(testTime / 1000));
3938 System.out.println("Elapsed: " + formatIntoHHMMSS(elapsedTime));
4039 System.out.println();
4140 }
@@ -44,9 +43,8 @@
4443 public void onTestSkipped(ITestResult tr) {
4544 long elapsedTime = TimeUnit.NANOSECONDS.toSeconds((System.nanoTime() - start_time));
4645 long testTime = tr.getEndMillis() - tr.getStartMillis();
47-
4846 System.out.println("SKIPPED: " + tr.getName());
49- System.out.println("Test: " + formatIntoHHMMSS(testTime / 1000));
47+ System.out.println("Test : " + formatIntoHHMMSS(testTime / 1000));
5048 System.out.println("Elapsed: " + formatIntoHHMMSS(elapsedTime));
5149 System.out.println();
5250 }
@@ -55,15 +53,16 @@
5553 public void onTestSuccess(ITestResult tr) {
5654 long elapsedTime = TimeUnit.NANOSECONDS.toSeconds((System.nanoTime() - start_time));
5755 long testTime = tr.getEndMillis() - tr.getStartMillis();
58-
5956 System.out.println("SUCCESS: " + tr.getName());
60- System.out.println("Test: " + formatIntoHHMMSS(testTime / 1000));
57+ System.out.println("Test : " + formatIntoHHMMSS(testTime / 1000));
6158 System.out.println("Elapsed: " + formatIntoHHMMSS(elapsedTime));
62- System.out.println("\n");
59+ System.out.println();
6360 }
6461
6562 @Override
6663 public void onTestStart(ITestResult tr) {
64+ System.out.println();
65+ System.out.println("-----------------------------------------------");
6766 System.out.println("Starting " + tr.getTestClass().getName() + '.' + tr.getName() + " [Test #" + ++test_index + "]...");
6867 }
6968
modified driver-core/src/test/java/com/datastax/driver/core/TestUtils.java +205 −94
@@ -17,8 +17,11 @@
1717
1818 import com.datastax.driver.core.policies.RoundRobinPolicy;
1919 import com.datastax.driver.core.policies.WhiteListPolicy;
20+import com.google.common.base.Predicate;
21+import com.google.common.base.Throwables;
2022 import com.google.common.util.concurrent.Futures;
2123 import com.google.common.util.concurrent.Uninterruptibles;
24+import com.sun.management.OperatingSystemMXBean;
2225 import io.netty.channel.EventLoopGroup;
2326 import org.scassandra.Scassandra;
2427 import org.scassandra.ScassandraFactory;
@@ -26,21 +29,33 @@
2629 import org.slf4j.LoggerFactory;
2730
2831 import java.io.IOException;
32+import java.lang.management.ManagementFactory;
2933 import java.math.BigDecimal;
3034 import java.math.BigInteger;
31-import java.net.InetAddress;
32-import java.net.InetSocketAddress;
33-import java.net.ServerSocket;
35+import java.net.*;
3436 import java.nio.ByteBuffer;
3537 import java.util.*;
38+import java.util.concurrent.Callable;
3639 import java.util.concurrent.CountDownLatch;
3740 import java.util.concurrent.TimeUnit;
41+import java.util.concurrent.atomic.AtomicInteger;
42+import java.util.concurrent.locks.ReentrantLock;
3843
3944 /**
4045 * A number of static fields/methods handy for tests.
4146 */
4247 public abstract class TestUtils {
4348
49+ public static final String IP_PREFIX;
50+
51+ static {
52+ String ip_prefix = System.getProperty("ipprefix");
53+ if (ip_prefix == null || ip_prefix.isEmpty()) {
54+ ip_prefix = "127.0.1.";
55+ }
56+ IP_PREFIX = ip_prefix;
57+ }
58+
4459 private static final Logger logger = LoggerFactory.getLogger(TestUtils.class);
4560
4661 public static final String CREATE_KEYSPACE_SIMPLE_FORMAT = "CREATE KEYSPACE %s WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor' : %d }";
@@ -53,6 +68,8 @@
5368
5469 public static final int TEST_BASE_NODE_WAIT = SystemProperties.getInt("com.datastax.driver.TEST_BASE_NODE_WAIT", 60);
5570
71+ private static final AtomicInteger KS_COUNTER = new AtomicInteger(1);
72+
5673 public static void setValue(SettableByIndexData<?> data, int i, DataType type, Object value) {
5774 switch (type.getName()) {
5875 case ASCII:
@@ -454,114 +471,117 @@
454471 // This is used because there is some delay between when a node has been
455472 // added through ccm and when it's actually available for querying
456473 public static void waitFor(String node, Cluster cluster) {
457- waitFor(node, cluster, TEST_BASE_NODE_WAIT, false, false);
474+ waitFor(node, cluster, TEST_BASE_NODE_WAIT, false);
458475 }
459476
460477 public static void waitFor(String node, Cluster cluster, int maxTry) {
461- waitFor(node, cluster, maxTry, false, false);
478+ waitFor(node, cluster, maxTry, false);
462479 }
463480
464481 public static void waitForDown(String node, Cluster cluster) {
465- waitFor(node, cluster, TEST_BASE_NODE_WAIT * 3, true, false);
466- }
467-
468- public static void waitForDownWithWait(String node, Cluster cluster, int waitTime) {
469- waitForDown(node, cluster);
470-
471- // FIXME: Once stop() works, remove this line
472- try {
473- Thread.sleep(waitTime * 1000);
474- } catch (InterruptedException e) {
475- e.printStackTrace();
476- }
482+ waitFor(node, cluster, TEST_BASE_NODE_WAIT * 3, true);
477483 }
478484
479485 public static void waitForDown(String node, Cluster cluster, int maxTry) {
480- waitFor(node, cluster, maxTry, true, false);
481- }
482-
483- public static void stopAndWait(CCMBridge.CCMCluster c, int node) {
484- c.cassandraCluster.stop(node);
485- waitForDownWithWait(CCMBridge.IP_PREFIX + node, c.cluster, 5);
486+ waitFor(node, cluster, maxTry, true);
486487 }
487488
488489 public static void waitForDecommission(String node, Cluster cluster) {
489- waitFor(node, cluster, TEST_BASE_NODE_WAIT / 2, true, true);
490+ waitFor(node, cluster, TEST_BASE_NODE_WAIT / 2, true);
490491 }
491492
492493 public static void waitForDecommission(String node, Cluster cluster, int maxTry) {
493- waitFor(node, cluster, maxTry, true, true);
494+ waitFor(node, cluster, maxTry, true);
494495 }
495496
496- private static void waitFor(String node, Cluster cluster, int maxTry, boolean waitForDead, boolean waitForOut) {
497- if (waitForDead || waitForOut)
498- if (waitForDead)
499- logger.info("Waiting for stopped node: " + node);
500- else if (waitForOut)
501- logger.info("Waiting for decommissioned node: " + node);
502- else
503- logger.info("Waiting for upcoming node: " + node);
504-
497+ private static void waitFor(String node, Cluster cluster, int timeoutSeconds, boolean waitForDown) {
498+ if (waitForDown)
499+ logger.debug("Waiting for node to leave: {}", node);
500+ else
501+ logger.debug("Waiting for upcoming node: {}", node);
505502 // In the case where the we've killed the last node in the cluster, if we haven't
506503 // tried doing an actual query, the driver won't realize that last node is dead until
507504 // keep alive kicks in, but that's a fairly long time. So we cheat and trigger a force
508505 // the detection by forcing a request.
509- if (waitForDead || waitForOut) {
506+ if (waitForDown) {
510507 Futures.getUnchecked(cluster.manager.submitSchemaRefresh(null, null, null, null));
511508 }
509+ if (waitForDown) {
510+ ConditionChecker.awaitUntil(new HostIsDownCondition(cluster, node), timeoutSeconds * 1000);
511+ } else {
512+ ConditionChecker.awaitUntil(new HostIsUpCondition(cluster, node), timeoutSeconds * 1000);
513+ }
514+ }
512515
513- InetAddress address;
514- try {
515- address = InetAddress.getByName(node);
516- } catch (Exception e) {
517- // That's a problem but that's not *our* problem
518- return;
516+ private static class HostIsDownCondition implements Callable<Boolean> {
517+
518+ private final Cluster cluster;
519+
520+ private final String ip;
521+
522+ public HostIsDownCondition(Cluster cluster, String ip) {
523+ this.cluster = cluster;
524+ this.ip = ip;
519525 }
520526
521- Metadata metadata = cluster.getMetadata();
522- for (int i = 0; i < maxTry; ++i) {
523- for (Host host : metadata.getAllHosts()) {
524- if (host.getAddress().equals(address) && testHost(host, waitForDead)) {
525- try {
526- Thread.sleep(10000);
527- } catch (Exception e) {
528- }
529- return;
530- }
531- }
532- try {
533- Thread.sleep(1000);
534- } catch (Exception e) {
535- }
527+ @Override
528+ public Boolean call() throws Exception {
529+ final Host host = findHost(cluster, ip);
530+ return host == null || !host.isUp();
536531 }
532+ }
537533
538- for (Host host : metadata.getAllHosts()) {
539- if (host.getAddress().equals(address)) {
540- if (testHost(host, waitForDead)) {
541- return;
542- } else {
543- // logging it because this give use the timestamp of when this happens
544- logger.info(node + " is not " + (waitForDead ? "DOWN" : "UP") + " after " + maxTry + 's');
545- throw new IllegalStateException(node + " is not " + (waitForDead ? "DOWN" : "UP") + " after " + maxTry + 's');
546- }
547- }
534+ private static class HostIsUpCondition implements Callable<Boolean> {
535+
536+ private final Cluster cluster;
537+
538+ private final String ip;
539+
540+ public HostIsUpCondition(Cluster cluster, String ip) {
541+ this.cluster = cluster;
542+ this.ip = ip;
548543 }
549544
550- if (waitForOut) {
551- return;
552- } else {
553- logger.info(node + " is not part of the cluster after " + maxTry + 's');
554- throw new IllegalStateException(node + " is not part of the cluster after " + maxTry + 's');
545+ @Override
546+ public Boolean call() throws Exception {
547+ final Host host = findHost(cluster, ip);
548+ return host != null && host.isUp();
555549 }
556550 }
557551
558- private static boolean testHost(Host host, boolean testForDown) {
559- return testForDown ? !host.isUp() : host.isUp();
552+ /**
553+ * Returns the IP of the {@code nth} host in the cluster (counting from 1, i.e.,
554+ * {@code ipOfNode(1)} returns the IP of the first node.
555+ * <p/>
556+ * In multi-DC setups, nodes are numbered in ascending order of their datacenter number.
557+ * E.g. with 2 DCs and 3 nodes in each DC, the first node in DC 2 is number 4.
558+ *
559+ * @return the IP of the {@code nth} host in the cluster.
560+ */
561+ public static String ipOfNode(int n) {
562+ return IP_PREFIX + n;
560563 }
561564
565+ /**
566+ * Returns the address of the {@code nth} host in the cluster (counting from 1, i.e.,
567+ * {@code ipOfNode(1)} returns the address of the first node.
568+ * <p/>
569+ * In multi-DC setups, nodes are numbered in ascending order of their datacenter number.
570+ * E.g. with 2 DCs and 3 nodes in each DC, the first node in DC 2 is number 4.
571+ *
572+ * @return the IP of the {@code nth} host in the cluster.
573+ */
574+ public static InetAddress addressOfNode(int i) {
575+ try {
576+ return InetAddress.getByName(IP_PREFIX + 1);
577+ } catch (UnknownHostException e) {
578+ // should never happen
579+ throw Throwables.propagate(e);
580+ }
581+ }
562582
563583 public static Host findOrWaitForHost(Cluster cluster, int node, long duration, TimeUnit unit) {
564- return findOrWaitForHost(cluster, CCMBridge.ipOfNode(node), duration, unit);
584+ return findOrWaitForHost(cluster, ipOfNode(node), duration, unit);
565585 }
566586
567587 public static Host findOrWaitForHost(final Cluster cluster, final String address, long duration, TimeUnit unit) {
@@ -593,7 +613,7 @@
593613 }
594614
595615 public static Host findHost(Cluster cluster, int hostNumber) {
596- return findHost(cluster, CCMBridge.ipOfNode(hostNumber));
616+ return findHost(cluster, ipOfNode(hostNumber));
597617 }
598618
599619 public static Host findHost(Cluster cluster, String address) {
@@ -635,29 +655,95 @@
635655 * 8052-8152.
636656 */
637657 public static Scassandra createScassandraServer() {
638- int binaryPort = findAvailablePort(8042);
639- int adminPort = findAvailablePort(8052);
640- return ScassandraFactory.createServer(binaryPort, adminPort);
658+ int binaryPort = findAvailablePort();
659+ int adminPort = findAvailablePort();
660+ return ScassandraFactory.createServer(ipOfNode(1), binaryPort, ipOfNode(1), adminPort);
661+ }
662+
663+ public static String getAvailableKeyspaceName() {
664+ return SIMPLE_KEYSPACE + "_" + KS_COUNTER.getAndIncrement();
641665 }
642666
667+ // use ports in the ephemeral range
668+ private static int nextPort = 50000;
669+
670+ private static final ReentrantLock PORT_LOCK = new ReentrantLock();
671+
643672 /**
644- * @param startingWith The first port to try, if unused will keep trying the next port until one is found up to
645- * 100 subsequent ports.
673+ * Find an available port in the ephemeral range.
674+ *
646675 * @return A local port that is currently unused.
647676 */
648- public static int findAvailablePort(int startingWith) {
649- IOException last = null;
650- for (int port = startingWith; port < startingWith + 100; port++) {
651- try {
652- ServerSocket s = new ServerSocket(port);
653- s.close();
654- return port;
655- } catch (IOException e) {
656- last = e;
677+ public static int findAvailablePort() {
678+ PORT_LOCK.lock();
679+ try {
680+ for (int i = 0; i < 3; i++) {
681+ int port = nextPort;
682+ ServerSocket s = null;
683+ for (int j = 0; j < 100; j++) {
684+ try {
685+ s = new ServerSocket(port);
686+ s.close();
687+ nextPort = port + 1;
688+ return port;
689+ } catch (IOException e) {
690+ // ok
691+ } finally {
692+ port++;
693+ if (s != null) {
694+ try {
695+ s.close();
696+ } catch (IOException e) {
697+ // ok
698+ }
699+ }
700+ }
701+ }
702+ logger.warn("Could not acquire an available port after 100 attempts, sleeping for 1 minute");
703+ Uninterruptibles.sleepUninterruptibly(1, TimeUnit.MINUTES);
657704 }
705+ throw new RuntimeException(String.format("Could not acquire an available port within range: %s-%s", nextPort, nextPort + 100));
706+ } finally {
707+ PORT_LOCK.unlock();
708+ }
709+ }
710+
711+ private static final Predicate<InetSocketAddress> PORT_IS_UP = new Predicate<InetSocketAddress>() {
712+
713+ @Override
714+ public boolean apply(InetSocketAddress address) {
715+ return pingPort(address.getAddress(), address.getPort());
716+ }
717+
718+ };
719+
720+ public static void waitUntilPortIsUp(InetSocketAddress address) {
721+ ConditionChecker.awaitUntil(address, PORT_IS_UP, TimeUnit.SECONDS.toMillis(10));
722+ }
723+
724+ public static void waitUntilPortIsDown(InetSocketAddress address) {
725+ ConditionChecker.awaitWhile(address, PORT_IS_UP, TimeUnit.SECONDS.toMillis(10));
726+ }
727+
728+ public static boolean pingPort(InetAddress address, int port) {
729+ logger.debug("Trying {}:{}...", address, port);
730+ boolean connectionSuccessful = false;
731+ Socket socket = null;
732+ try {
733+ socket = new Socket(address, port);
734+ connectionSuccessful = true;
735+ logger.debug("Successfully connected");
736+ } catch (IOException e) {
737+ logger.debug("Connection failed");
738+ } finally {
739+ if (socket != null)
740+ try {
741+ socket.close();
742+ } catch (IOException e) {
743+ logger.warn("Error closing socket to " + address);
744+ }
658745 }
659- // If for whatever reason a port could not be acquired throw the last encountered exception.
660- throw new RuntimeException("Could not acquire an available port", last);
746+ return connectionSuccessful;
661747 }
662748
663749 /**
@@ -688,19 +774,20 @@
688774 }
689775
690776 /**
691- * @return a {@Cluster} instance that connects only to the control host of the given cluster.
777+ * @return a {@link Cluster} instance that connects only to the control host of the given cluster.
692778 */
693- public static Cluster buildControlCluster(Cluster cluster) {
779+ public static Cluster buildControlCluster(Cluster cluster, CCMBridge ccm) {
694780 Host controlHost = cluster.manager.controlConnection.connectedHost();
695781 List<InetSocketAddress> singleAddress = Collections.singletonList(controlHost.getSocketAddress());
696782 return Cluster.builder()
697783 .addContactPointsWithPorts(singleAddress)
784+ .withAddressTranslator(ccm.addressTranslator())
698785 .withLoadBalancingPolicy(new WhiteListPolicy(new RoundRobinPolicy(), singleAddress))
699786 .build();
700787 }
701788
702789 /**
703- * @return a {@QueryOptions} that disables debouncing by setting intervals to 0ms.
790+ * @return a {@link QueryOptions} that disables debouncing by setting intervals to 0ms.
704791 */
705792 public static QueryOptions nonDebouncingQueryOptions() {
706793 return new QueryOptions().setRefreshNodeIntervalMillis(0)
@@ -719,4 +806,28 @@
719806 eventLoopGroup.shutdownGracefully(0, 15, TimeUnit.SECONDS).syncUninterruptibly();
720807 }
721808 };
809+
810+ public static void executeNoFail(Runnable task, boolean logException) {
811+ try {
812+ task.run();
813+ } catch (Exception e) {
814+ if (logException)
815+ logger.error(e.getMessage(), e);
816+ }
817+ }
818+
819+ public static void executeNoFail(Callable<?> task, boolean logException) {
820+ try {
821+ task.call();
822+ } catch (Exception e) {
823+ if (logException)
824+ logger.error(e.getMessage(), e);
825+ }
826+ }
827+
828+ public static long getFreeMemoryMB() {
829+ OperatingSystemMXBean bean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
830+ return (bean.getFreePhysicalMemorySize() + bean.getFreeSwapSpaceSize()) / 1024 / 1024;
831+ }
832+
722833 }
modified driver-core/src/test/java/com/datastax/driver/core/TimeoutStressTest.java +32 −69
@@ -26,20 +26,20 @@
2626 import io.netty.channel.socket.SocketChannel;
2727 import org.slf4j.Logger;
2828 import org.slf4j.LoggerFactory;
29-import org.testng.annotations.AfterClass;
30-import org.testng.annotations.BeforeClass;
3129 import org.testng.annotations.Test;
3230
33-import java.net.InetSocketAddress;
3431 import java.util.Collection;
35-import java.util.List;
36-import java.util.concurrent.*;
32+import java.util.concurrent.ExecutorService;
33+import java.util.concurrent.Executors;
34+import java.util.concurrent.Semaphore;
35+import java.util.concurrent.TimeUnit;
3736 import java.util.concurrent.atomic.AtomicBoolean;
3837 import java.util.concurrent.atomic.AtomicInteger;
3938
4039 import static com.datastax.driver.core.Assertions.assertThat;
4140
42-public class TimeoutStressTest {
41+@CCMConfig(numberOfNodes = 3)
42+public class TimeoutStressTest extends CCMTestsSupport {
4343
4444 static final Logger logger = LoggerFactory.getLogger(TimeoutStressTest.class);
4545
@@ -56,50 +56,31 @@
5656 // Configured connection timeout - this may need to be tuned to the host system running the test.
5757 static final int CONNECTION_TIMEOUT_IN_MS = 20;
5858
59- // Keyspace to use.
60- static final String KEYSPACE = "testks";
59+ private static AtomicInteger executedQueries = new AtomicInteger(0);
6160
62- static Cluster cluster;
63-
64- static CCMBridge ccmBridge;
65-
66- static SocketChannelMonitor channelMonitor;
67-
68- static AtomicInteger executedQueries = new AtomicInteger(0);
69-
70- static List<InetSocketAddress> nodes;
71-
72- @BeforeClass(groups = "stress")
73- public void beforeClass() throws Exception {
74- ccmBridge = CCMBridge.builder("test").withNodes(3).build();
75- channelMonitor = new SocketChannelMonitor();
76- nodes = Lists.newArrayList(
77- new InetSocketAddress(CCMBridge.IP_PREFIX + '1', 9042),
78- new InetSocketAddress(CCMBridge.IP_PREFIX + '2', 9042),
79- new InetSocketAddress(CCMBridge.IP_PREFIX + '3', 9042)
80- );
61+ private SocketChannelMonitor channelMonitor;
8162
63+ @Override
64+ public Cluster.Builder createClusterBuilder() {
65+ channelMonitor = register(new SocketChannelMonitor());
8266 PoolingOptions poolingOptions = new PoolingOptions().setConnectionsPerHost(HostDistance.LOCAL, 8, 8);
83-
84- cluster = Cluster.builder()
85- .addContactPointsWithPorts(nodes)
67+ return Cluster.builder()
8668 .withPoolingOptions(poolingOptions)
8769 .withNettyOptions(channelMonitor.nettyOptions())
88- .withReconnectionPolicy(new ConstantReconnectionPolicy(1000))
89- .build();
70+ .withReconnectionPolicy(new ConstantReconnectionPolicy(1000));
9071 }
9172
92- @AfterClass(groups = "stress")
93- public void afterClass() {
94- if (ccmBridge != null) {
95- ccmBridge.stop();
96- }
97- if (channelMonitor != null) {
98- channelMonitor.stop();
99- }
100- if (cluster != null) {
101- cluster.close();
102- }
73+ @Override
74+ public Collection<String> createTestFixtures() {
75+ return Lists.newArrayList(
76+ "create table record (\n"
77+ + " name text,\n"
78+ + " phone text,\n"
79+ + " value text,\n"
80+ + " PRIMARY KEY (name, phone)\n"
81+ + ")"
82+
83+ );
10384 }
10485
10586 /**
@@ -127,16 +108,14 @@
127108 */
128109 @Test(groups = "stress")
129110 public void host_state_should_be_maintained_with_timeouts() throws Exception {
130- // Setup schema and insert records.
131- Session session = cluster.connect();
132- setupSchema(session);
111+ insertRecords();
133112 session.close();
134113
135114 // Set very low timeouts.
136115 cluster.getConfiguration().getSocketOptions().setConnectTimeoutMillis(CONNECTION_TIMEOUT_IN_MS);
137116 cluster.getConfiguration().getSocketOptions().setReadTimeoutMillis(READ_TIMEOUT_IN_MS);
138- session = cluster.connect();
139- PreparedStatement statement = session.prepare("select * from " + KEYSPACE + ".record where name=? limit 1000;");
117+ session = cluster.connect(keyspace);
118+ PreparedStatement statement = session.prepare("select * from record where name=? limit 1000;");
140119
141120 int workers = Runtime.getRuntime().availableProcessors();
142121 ExecutorService workerPool = Executors.newFixedThreadPool(workers,
@@ -145,7 +124,7 @@
145124 AtomicBoolean stopped = new AtomicBoolean(false);
146125
147126 // Ensure that we never exceed MaxConnectionsPerHost * nodes + 1 control connection.
148- int maxConnections = TestUtils.numberOfLocalCoreConnections(cluster) * nodes.size() + 1;
127+ int maxConnections = TestUtils.numberOfLocalCoreConnections(cluster) * getInitialContactPoints().size() + 1;
149128
150129 try {
151130 Semaphore concurrentQueries = new Semaphore(CONCURRENT_QUERIES);
@@ -159,7 +138,7 @@
159138 channelMonitor.report();
160139 // Some connections that are being closed may have had active requests which are delegated to the
161140 // reaper for cleanup later.
162- Collection<SocketChannel> openChannels = channelMonitor.openChannels(nodes);
141+ Collection<SocketChannel> openChannels = channelMonitor.openChannels(getInitialContactPoints());
163142
164143 // Ensure that we don't exceed maximum connections. Log as warning as there will be a bit of a timing
165144 // factor between retrieving open connections and checking the reaper.
@@ -182,7 +161,7 @@
182161 "and for the pools to recover.");
183162 Uninterruptibles.sleepUninterruptibly(20, TimeUnit.SECONDS);
184163
185- Collection<SocketChannel> openChannels = channelMonitor.openChannels(nodes);
164+ Collection<SocketChannel> openChannels = channelMonitor.openChannels(getInitialContactPoints());
186165 assertThat(openChannels.size())
187166 .as("Number of open connections does not meet expected: %s", openChannels)
188167 .isLessThanOrEqualTo(maxConnections);
@@ -194,7 +173,7 @@
194173
195174 session.close();
196175
197- openChannels = channelMonitor.openChannels(nodes);
176+ openChannels = channelMonitor.openChannels(getInitialContactPoints());
198177 assertThat(openChannels.size())
199178 .as("Number of open connections does not meet expected: %s", openChannels)
200179 .isEqualTo(1);
@@ -203,23 +182,7 @@
203182 }
204183 }
205184
206- /**
207- * Creates the testks schema with a 'record' table and preloads 30k records.
208- */
209- private static void setupSchema(Session session) throws InterruptedException, ExecutionException, TimeoutException {
210- logger.debug("Creating keyspace");
211- session.execute("create KEYSPACE " + KEYSPACE +
212- " WITH replication = {'class': 'SimpleStrategy', 'replication_factor' : 3}");
213- session.execute("use " + KEYSPACE);
214-
215- logger.debug("Creating table");
216- session.execute("create table record (\n"
217- + " name text,\n"
218- + " phone text,\n"
219- + " value text,\n"
220- + " PRIMARY KEY (name, phone)\n"
221- + ");");
222-
185+ private void insertRecords() {
223186 int records = 30000;
224187 PreparedStatement insertStmt = session.prepare("insert into record (name, phone, value) values (?, ?, ?)");
225188
modified driver-core/src/test/java/com/datastax/driver/core/TokenIntegrationTest.java +42 −69
@@ -23,14 +23,9 @@
2323 import com.google.common.base.Function;
2424 import com.google.common.collect.Iterables;
2525 import com.google.common.collect.Lists;
26-import org.testng.annotations.AfterClass;
27-import org.testng.annotations.BeforeClass;
2826 import org.testng.annotations.Test;
2927
30-import java.net.InetSocketAddress;
31-import java.util.HashSet;
32-import java.util.List;
33-import java.util.Set;
28+import java.util.*;
3429
3530 import static com.datastax.driver.core.Assertions.assertThat;
3631
@@ -40,67 +35,45 @@
4035 * There's normally a way to parametrize a TestNG class with @Factory and @DataProvider,
4136 * but it doesn't seem to work with multiple methods.
4237 */
43-public abstract class TokenIntegrationTest {
44-
45- List<String> schema = Lists.newArrayList(
46- "CREATE KEYSPACE test WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}",
47- "CREATE KEYSPACE test2 WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 2}",
48- "USE test",
49- "CREATE TABLE foo(i int primary key)",
50- "INSERT INTO foo (i) VALUES (1)",
51- "INSERT INTO foo (i) VALUES (2)",
52- "INSERT INTO foo (i) VALUES (3)"
53- );
54-
55- private final String ccmOptions;
38+@CCMConfig(numberOfNodes = 3, createKeyspace = false)
39+public abstract class TokenIntegrationTest extends CCMTestsSupport {
40+
5641 private final DataType expectedTokenType;
5742 private final int numTokens;
5843 private final boolean useVnodes;
59- CCMBridge ccm;
60- Cluster cluster;
61- Session session;
62-
63- public TokenIntegrationTest(String ccmOptions, DataType expectedTokenType) {
64- this(ccmOptions, expectedTokenType, false);
65- }
44+ private String ks1;
45+ private String ks2;
6646
67- public TokenIntegrationTest(String ccmOptions, DataType expectedTokenType, boolean useVnodes) {
47+ public TokenIntegrationTest(DataType expectedTokenType, boolean useVnodes) {
6848 this.expectedTokenType = expectedTokenType;
6949 this.numTokens = useVnodes ? 256 : 1;
70- this.ccmOptions = useVnodes ? ccmOptions + " --vnodes" : ccmOptions;
7150 this.useVnodes = useVnodes;
7251 }
7352
74- @BeforeClass(groups = "short")
75- public void setup() {
76- ccm = CCMBridge.builder("test").withNodes(3).withStartOptions(ccmOptions).build();
77-
53+ @Override
54+ public Cluster.Builder createClusterBuilder() {
7855 // Only connect to node 1, which makes it easier to query system tables in should_expose_tokens_per_host()
7956 LoadBalancingPolicy lbp = new WhiteListPolicy(new RoundRobinPolicy(),
80- Lists.newArrayList(new InetSocketAddress(CCMBridge.ipOfNode(1), 9042)));
81-
82- cluster = Cluster.builder()
83- .addContactPoints(CCMBridge.ipOfNode(1))
57+ Collections.singleton(ccm.addressOfNode(1)));
58+ return Cluster.builder()
59+ .addContactPointsWithPorts(ccm.addressOfNode(1))
8460 .withLoadBalancingPolicy(lbp)
85- .withQueryOptions(new QueryOptions()
86- .setRefreshNodeIntervalMillis(0)
87- .setRefreshNodeListIntervalMillis(0)
88- .setRefreshSchemaIntervalMillis(0)
89- )
90- .build();
91- cluster.init();
92- session = cluster.connect();
93-
94- for (String statement : schema)
95- session.execute(statement);
61+ .withQueryOptions(TestUtils.nonDebouncingQueryOptions());
9662 }
9763
98- @AfterClass(groups = "short", alwaysRun = true)
99- public void teardown() {
100- if (cluster != null)
101- cluster.close();
102- if (ccm != null)
103- ccm.remove();
64+ @Override
65+ public Collection<String> createTestFixtures() {
66+ ks1 = TestUtils.getAvailableKeyspaceName();
67+ ks2 = TestUtils.getAvailableKeyspaceName();
68+ return Lists.newArrayList(
69+ String.format("CREATE KEYSPACE %s WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}", ks1),
70+ String.format("CREATE KEYSPACE %s WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 2}", ks2),
71+ String.format("USE %s", ks1),
72+ "CREATE TABLE foo(i int primary key)",
73+ "INSERT INTO foo (i) VALUES (1)",
74+ "INSERT INTO foo (i) VALUES (2)",
75+ "INSERT INTO foo (i) VALUES (3)"
76+ );
10477 }
10578
10679 /**
@@ -120,7 +93,7 @@
12093
12194 // Find the replica for a given partition key
12295 int testKey = 1;
123- Set<Host> replicas = metadata.getReplicas("test", TypeCodec.cint().serialize(testKey, cluster.getConfiguration().getProtocolOptions().getProtocolVersion()));
96+ Set<Host> replicas = metadata.getReplicas(ks1, TypeCodec.cint().serialize(testKey, cluster.getConfiguration().getProtocolOptions().getProtocolVersion()));
12497 assertThat(replicas).hasSize(1);
12598 Host replica = replicas.iterator().next();
12699
@@ -140,7 +113,7 @@
140113 .isNull();
141114 foundRange = range;
142115 // That range should be managed by the replica
143- assertThat(metadata.getReplicas("test", range)).contains(replica);
116+ assertThat(metadata.getReplicas(ks1, range)).contains(replica);
144117 }
145118 }
146119 }
@@ -181,7 +154,7 @@
181154 @Test(groups = "short")
182155 public void should_get_token_from_row_and_set_token_in_query() {
183156 // get by index:
184- Row row = session.execute("SELECT token(i) FROM test.foo WHERE i = 1").one();
157+ Row row = session.execute("SELECT token(i) FROM foo WHERE i = 1").one();
185158 Token token = row.getToken(0);
186159 assertThat(token.getType()).isEqualTo(expectedTokenType);
187160
@@ -189,7 +162,7 @@
189162 row.getPartitionKeyToken()
190163 ).isEqualTo(token);
191164
192- PreparedStatement pst = session.prepare("SELECT * FROM test.foo WHERE token(i) = ?");
165+ PreparedStatement pst = session.prepare("SELECT * FROM foo WHERE token(i) = ?");
193166 row = session.execute(pst.bind(token)).one();
194167 assertThat(row.getInt(0)).isEqualTo(1);
195168
@@ -217,15 +190,15 @@
217190 @Test(groups = "short")
218191 @CassandraVersion(major = 2)
219192 public void should_get_token_from_row_and_set_token_in_query_with_binding_and_aliasing() {
220- Row row = session.execute("SELECT token(i) AS t FROM test.foo WHERE i = 1").one();
193+ Row row = session.execute("SELECT token(i) AS t FROM foo WHERE i = 1").one();
221194 Token token = row.getToken("t");
222195 assertThat(token.getType()).isEqualTo(expectedTokenType);
223196
224- PreparedStatement pst = session.prepare("SELECT * FROM test.foo WHERE token(i) = :myToken");
197+ PreparedStatement pst = session.prepare("SELECT * FROM foo WHERE token(i) = :myToken");
225198 row = session.execute(pst.bind().setToken("myToken", token)).one();
226199 assertThat(row.getInt(0)).isEqualTo(1);
227200
228- row = session.execute("SELECT * FROM test.foo WHERE token(i) = ?", token).one();
201+ row = session.execute("SELECT * FROM foo WHERE token(i) = ?", token).one();
229202 assertThat(row.getInt(0)).isEqualTo(1);
230203 }
231204
@@ -241,7 +214,7 @@
241214 */
242215 @Test(groups = "short", expectedExceptions = InvalidTypeException.class)
243216 public void should_raise_exception_when_get_token_on_non_token() {
244- Row row = session.execute("SELECT i FROM test.foo WHERE i = 1").one();
217+ Row row = session.execute("SELECT i FROM foo WHERE i = 1").one();
245218 row.getToken(0);
246219 }
247220
@@ -263,8 +236,8 @@
263236 */
264237 @Test(groups = "short")
265238 public void should_expose_token_ranges_per_host() {
266- checkRangesPerHost("test", 1);
267- checkRangesPerHost("test2", 2);
239+ checkRangesPerHost(ks1, 1);
240+ checkRangesPerHost(ks2, 2);
268241 assertThat(cluster).hasValidTokenRanges();
269242 }
270243
@@ -350,12 +323,12 @@
350323 assertOnlyOneWrapped(ranges);
351324
352325 Iterable<TokenRange> splitRanges = Iterables.concat(Iterables.transform(ranges,
353- new Function<TokenRange, Iterable<TokenRange>>() {
354- @Override
355- public Iterable<TokenRange> apply(TokenRange input) {
356- return input.splitEvenly(10);
357- }
358- })
326+ new Function<TokenRange, Iterable<TokenRange>>() {
327+ @Override
328+ public Iterable<TokenRange> apply(TokenRange input) {
329+ return input.splitEvenly(10);
330+ }
331+ })
359332 );
360333
361334 assertOnlyOneWrapped(splitRanges);
modified driver-core/src/test/java/com/datastax/driver/core/TracingTest.java +6 −6
@@ -28,17 +28,17 @@
2828 import static org.assertj.core.api.Assertions.assertThat;
2929
3030 @CassandraVersion(major = 2.0)
31-public class TracingTest extends CCMBridge.PerClassSingleNodeCluster {
31+public class TracingTest extends CCMTestsSupport {
32+
33+ private static final String KEY = "tracing_test";
3234
3335 @Override
34- protected Cluster.Builder configure(Cluster.Builder builder) {
35- return builder.withRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE);
36+ public Cluster.Builder createClusterBuilder() {
37+ return Cluster.builder().withRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE);
3638 }
3739
38- public static final String KEY = "tracing_test";
39-
4040 @Override
41- protected Collection<String> getTableDefinitions() {
41+ public Collection<String> createTestFixtures() {
4242 return Collections.singletonList("CREATE TABLE test (k text, v int, PRIMARY KEY (k, v))");
4343 }
4444
modified driver-core/src/test/java/com/datastax/driver/core/TupleTest.java +279 −326
@@ -28,13 +28,13 @@
2828 import static org.testng.Assert.fail;
2929
3030 @CassandraVersion(major = 2.1)
31-public class TupleTest extends CCMBridge.PerClassSingleNodeCluster {
31+public class TupleTest extends CCMTestsSupport {
3232
3333 ProtocolVersion protocolVersion = TestUtils.getDesiredProtocolVersion();
3434
3535 @Override
36- protected Collection<String> getTableDefinitions() {
37- return Arrays.asList("CREATE TABLE t (k int PRIMARY KEY, v frozen<tuple<int, text, float>>)");
36+ public Collection<String> createTestFixtures() {
37+ return Collections.singleton("CREATE TABLE t (k int PRIMARY KEY, v frozen<tuple<int, text, float>>)");
3838 }
3939
4040 @Test(groups = "short")
@@ -49,7 +49,6 @@
4949 assertEquals(v.getType().getComponentTypes().get(0), DataType.cint());
5050 assertEquals(v.getType().getComponentTypes().get(1), DataType.text());
5151 assertEquals(v.getType().getComponentTypes().get(2), DataType.cfloat());
52-
5352 assertEquals(v.getInt(0), 1);
5453 assertEquals(v.getString(1), "a");
5554 assertEquals(v.getFloat(2), 1.0f);
@@ -59,33 +58,28 @@
5958
6059 @Test(groups = "short")
6160 public void simpleWriteReadTest() throws Exception {
62- try {
63- session.execute("USE " + keyspace);
64- PreparedStatement ins = session.prepare("INSERT INTO t(k, v) VALUES (?, ?)");
65- PreparedStatement sel = session.prepare("SELECT * FROM t WHERE k=?");
61+ session.execute("USE " + keyspace);
62+ PreparedStatement ins = session.prepare("INSERT INTO t(k, v) VALUES (?, ?)");
63+ PreparedStatement sel = session.prepare("SELECT * FROM t WHERE k=?");
6664
67- TupleType t = cluster.getMetadata().newTupleType(DataType.cint(), DataType.text(), DataType.cfloat());
65+ TupleType t = cluster.getMetadata().newTupleType(DataType.cint(), DataType.text(), DataType.cfloat());
6866
69- int k = 1;
70- TupleValue v = t.newValue(1, "a", 1.0f);
67+ int k = 1;
68+ TupleValue v = t.newValue(1, "a", 1.0f);
7169
72- session.execute(ins.bind(k, v));
73- TupleValue v2 = session.execute(sel.bind(k)).one().getTupleValue("v");
70+ session.execute(ins.bind(k, v));
71+ TupleValue v2 = session.execute(sel.bind(k)).one().getTupleValue("v");
7472
75- assertEquals(v2, v);
73+ assertEquals(v2, v);
7674
77- // Test simple statement interpolation
78- k = 2;
79- v = t.newValue(2, "b", 2.0f);
75+ // Test simple statement interpolation
76+ k = 2;
77+ v = t.newValue(2, "b", 2.0f);
8078
81- session.execute("INSERT INTO t(k, v) VALUES (?, ?)", k, v);
82- v2 = session.execute(sel.bind(k)).one().getTupleValue("v");
79+ session.execute("INSERT INTO t(k, v) VALUES (?, ?)", k, v);
80+ v2 = session.execute(sel.bind(k)).one().getTupleValue("v");
8381
84- assertEquals(v2, v);
85- } catch (Exception e) {
86- errorOut();
87- throw e;
88- }
82+ assertEquals(v2, v);
8983 }
9084
9185 /**
@@ -96,65 +90,61 @@
9690 */
9791 @Test(groups = "short")
9892 public void tupleTypeTest() throws Exception {
93+ session.execute("CREATE KEYSPACE test_tuple_type " +
94+ "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
95+ session.execute("USE test_tuple_type");
96+ session.execute("CREATE TABLE mytable (a int PRIMARY KEY, b frozen<tuple<ascii, int, boolean>>)");
97+
98+ TupleType t = cluster.getMetadata().newTupleType(DataType.ascii(), DataType.cint(), DataType.cboolean());
99+
100+ // test non-prepared statement
101+ TupleValue complete = t.newValue("foo", 123, true);
102+ session.execute("INSERT INTO mytable (a, b) VALUES (0, ?)", complete);
103+ TupleValue r = session.execute("SELECT b FROM mytable WHERE a=0").one().getTupleValue("b");
104+ assertEquals(r, complete);
105+
106+ // test incomplete tuples
99107 try {
100- session.execute("CREATE KEYSPACE test_tuple_type " +
101- "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
102- session.execute("USE test_tuple_type");
103- session.execute("CREATE TABLE mytable (a int PRIMARY KEY, b frozen<tuple<ascii, int, boolean>>)");
104-
105- TupleType t = cluster.getMetadata().newTupleType(DataType.ascii(), DataType.cint(), DataType.cboolean());
106-
107- // test non-prepared statement
108- TupleValue complete = t.newValue("foo", 123, true);
109- session.execute("INSERT INTO mytable (a, b) VALUES (0, ?)", complete);
110- TupleValue r = session.execute("SELECT b FROM mytable WHERE a=0").one().getTupleValue("b");
111- assertEquals(r, complete);
112-
113- // test incomplete tuples
114- try {
115- TupleValue partial = t.newValue("bar", 456);
116- fail();
117- } catch (IllegalArgumentException e) {
118- }
119-
120- // test incomplete tuples with new TupleType
121- TupleType t1 = cluster.getMetadata().newTupleType(DataType.ascii(), DataType.cint());
122- TupleValue partial = t1.newValue("bar", 456);
123- TupleValue partionResult = t.newValue("bar", 456, null);
124- session.execute("INSERT INTO mytable (a, b) VALUES (0, ?)", partial);
125- r = session.execute("SELECT b FROM mytable WHERE a=0").one().getTupleValue("b");
126- assertEquals(r, partionResult);
127-
128- // test single value tuples
129- try {
130- TupleValue subpartial = t.newValue("zoo");
131- fail();
132- } catch (IllegalArgumentException e) {
133- }
108+ t.newValue("bar", 456);
109+ fail();
110+ } catch (IllegalArgumentException e) {
111+ //ok
112+ }
134113
135- // test single value tuples with new TupleType
136- TupleType t2 = cluster.getMetadata().newTupleType(DataType.ascii());
137- TupleValue subpartial = t2.newValue("zoo");
138- TupleValue subpartialResult = t.newValue("zoo", null, null);
139- session.execute("INSERT INTO mytable (a, b) VALUES (0, ?)", subpartial);
140- r = session.execute("SELECT b FROM mytable WHERE a=0").one().getTupleValue("b");
141- assertEquals(r, subpartialResult);
142-
143- // test prepared statements
144- PreparedStatement prepared = session.prepare("INSERT INTO mytable (a, b) VALUES (?, ?)");
145- session.execute(prepared.bind(3, complete));
146- session.execute(prepared.bind(4, partial));
147- session.execute(prepared.bind(5, subpartial));
148-
149- prepared = session.prepare("SELECT b FROM mytable WHERE a=?");
150- assertEquals(session.execute(prepared.bind(3)).one().getTupleValue("b"), complete);
151- assertEquals(session.execute(prepared.bind(4)).one().getTupleValue("b"), partionResult);
152- assertEquals(session.execute(prepared.bind(5)).one().getTupleValue("b"), subpartialResult);
153-
154- } catch (Exception e) {
155- errorOut();
156- throw e;
114+ // test incomplete tuples with new TupleType
115+ TupleType t1 = cluster.getMetadata().newTupleType(DataType.ascii(), DataType.cint());
116+ TupleValue partial = t1.newValue("bar", 456);
117+ TupleValue partionResult = t.newValue("bar", 456, null);
118+ session.execute("INSERT INTO mytable (a, b) VALUES (0, ?)", partial);
119+ r = session.execute("SELECT b FROM mytable WHERE a=0").one().getTupleValue("b");
120+ assertEquals(r, partionResult);
121+
122+ // test single value tuples
123+ try {
124+ t.newValue("zoo");
125+ fail();
126+ } catch (IllegalArgumentException e) {
127+ //ok
157128 }
129+
130+ // test single value tuples with new TupleType
131+ TupleType t2 = cluster.getMetadata().newTupleType(DataType.ascii());
132+ TupleValue subpartial = t2.newValue("zoo");
133+ TupleValue subpartialResult = t.newValue("zoo", null, null);
134+ session.execute("INSERT INTO mytable (a, b) VALUES (0, ?)", subpartial);
135+ r = session.execute("SELECT b FROM mytable WHERE a=0").one().getTupleValue("b");
136+ assertEquals(r, subpartialResult);
137+
138+ // test prepared statements
139+ PreparedStatement prepared = session.prepare("INSERT INTO mytable (a, b) VALUES (?, ?)");
140+ session.execute(prepared.bind(3, complete));
141+ session.execute(prepared.bind(4, partial));
142+ session.execute(prepared.bind(5, subpartial));
143+
144+ prepared = session.prepare("SELECT b FROM mytable WHERE a=?");
145+ assertEquals(session.execute(prepared.bind(3)).one().getTupleValue("b"), complete);
146+ assertEquals(session.execute(prepared.bind(4)).one().getTupleValue("b"), partionResult);
147+ assertEquals(session.execute(prepared.bind(5)).one().getTupleValue("b"), subpartialResult);
158148 }
159149
160150 /**
@@ -166,47 +156,41 @@
166156 */
167157 @Test(groups = "short")
168158 public void tupleTestTypeVaryingLengths() throws Exception {
169- try {
170- session.execute("CREATE KEYSPACE test_tuple_type_varying_lengths " +
171- "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
172- session.execute("USE test_tuple_type_varying_lengths");
173-
174- // programmatically create the table with tuples of said sizes
175- int[] lengths = {1, 2, 3, 384};
176- ArrayList<String> valueSchema = new ArrayList<String>();
177- for (int i : lengths) {
178- ArrayList<String> ints = new ArrayList<String>();
179- for (int j = 0; j < i; ++j) {
180- ints.add("int");
181- }
182- valueSchema.add(String.format(" v_%d frozen<tuple<%s>>", i, Joiner.on(',').join(ints)));
159+ session.execute("CREATE KEYSPACE test_tuple_type_varying_lengths " +
160+ "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
161+ session.execute("USE test_tuple_type_varying_lengths");
162+
163+ // programmatically create the table with tuples of said sizes
164+ int[] lengths = {1, 2, 3, 384};
165+ ArrayList<String> valueSchema = new ArrayList<String>();
166+ for (int i : lengths) {
167+ ArrayList<String> ints = new ArrayList<String>();
168+ for (int j = 0; j < i; ++j) {
169+ ints.add("int");
183170 }
184- session.execute(String.format("CREATE TABLE mytable (k int PRIMARY KEY, %s)", Joiner.on(',').join(valueSchema)));
185-
186- // insert tuples into same key using different columns
187- // and verify the results
188- for (int i : lengths) {
189- // create tuple
190- ArrayList<DataType> dataTypes = new ArrayList<DataType>();
191- ArrayList<Integer> values = new ArrayList<Integer>();
192- for (int j = 0; j < i; ++j) {
193- dataTypes.add(DataType.cint());
194- values.add(j);
195- }
196- TupleType t = new TupleType(dataTypes, protocolVersion, cluster.getConfiguration().getCodecRegistry());
197- TupleValue createdTuple = t.newValue(values.toArray());
198-
199- // write tuple
200- session.execute(String.format("INSERT INTO mytable (k, v_%s) VALUES (0, ?)", i), createdTuple);
201-
202- // read tuple
203- TupleValue r = session.execute(String.format("SELECT v_%s FROM mytable WHERE k=0", i)).one().getTupleValue(String.format("v_%s", i));
204- assertEquals(r, createdTuple);
171+ valueSchema.add(String.format(" v_%d frozen<tuple<%s>>", i, Joiner.on(',').join(ints)));
172+ }
173+ session.execute(String.format("CREATE TABLE mytable (k int PRIMARY KEY, %s)", Joiner.on(',').join(valueSchema)));
174+
175+ // insert tuples into same key using different columns
176+ // and verify the results
177+ for (int i : lengths) {
178+ // create tuple
179+ ArrayList<DataType> dataTypes = new ArrayList<DataType>();
180+ ArrayList<Integer> values = new ArrayList<Integer>();
181+ for (int j = 0; j < i; ++j) {
182+ dataTypes.add(DataType.cint());
183+ values.add(j);
205184 }
206-
207- } catch (Exception e) {
208- errorOut();
209- throw e;
185+ TupleType t = new TupleType(dataTypes, protocolVersion, cluster.getConfiguration().getCodecRegistry());
186+ TupleValue createdTuple = t.newValue(values.toArray());
187+
188+ // write tuple
189+ session.execute(String.format("INSERT INTO mytable (k, v_%s) VALUES (0, ?)", i), createdTuple);
190+
191+ // read tuple
192+ TupleValue r = session.execute(String.format("SELECT v_%s FROM mytable WHERE k=0", i)).one().getTupleValue(String.format("v_%s", i));
193+ assertEquals(r, createdTuple);
210194 }
211195 }
212196
@@ -220,59 +204,52 @@
220204 public void tupleSubtypesTest() throws Exception {
221205
222206 List<DataType> DATA_TYPE_PRIMITIVES = Lists.newArrayList(PrimitiveTypeSamples.ALL.keySet());
207+ session.execute("CREATE KEYSPACE test_tuple_subtypes " +
208+ "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
209+ session.execute("USE test_tuple_subtypes");
210+
211+ // programmatically create the table with a tuple of all datatypes
212+ session.execute(String.format("CREATE TABLE mytable (k int PRIMARY KEY, v frozen<tuple<%s>>)", Joiner.on(',').join(DATA_TYPE_PRIMITIVES)));
213+
214+ // insert tuples into same key using different columns
215+ // and verify the results
216+ int i = 1;
217+ for (DataType ignored : DATA_TYPE_PRIMITIVES) {
218+ // create tuples to be written and ensure they match with the expected response
219+ // responses have trailing None values for every element that has not been written
220+ ArrayList<DataType> dataTypes = new ArrayList<DataType>();
221+ ArrayList<DataType> completeDataTypes = new ArrayList<DataType>();
222+ ArrayList<Object> createdValues = new ArrayList<Object>();
223+ ArrayList<Object> completeValues = new ArrayList<Object>();
224+
225+ // create written portion of the arrays
226+ for (int j = 0; j < i; ++j) {
227+ dataTypes.add(DATA_TYPE_PRIMITIVES.get(j));
228+ completeDataTypes.add(DATA_TYPE_PRIMITIVES.get(j));
229+ createdValues.add(PrimitiveTypeSamples.ALL.get(DATA_TYPE_PRIMITIVES.get(j)));
230+ completeValues.add(PrimitiveTypeSamples.ALL.get(DATA_TYPE_PRIMITIVES.get(j)));
231+ }
223232
224- try {
225- session.execute("CREATE KEYSPACE test_tuple_subtypes " +
226- "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
227- session.execute("USE test_tuple_subtypes");
228-
229- // programmatically create the table with a tuple of all datatypes
230- session.execute(String.format("CREATE TABLE mytable (k int PRIMARY KEY, v frozen<tuple<%s>>)", Joiner.on(',').join(DATA_TYPE_PRIMITIVES)));
231-
232- // insert tuples into same key using different columns
233- // and verify the results
234- int i = 1;
235- for (DataType datatype : DATA_TYPE_PRIMITIVES) {
236- // create tuples to be written and ensure they match with the expected response
237- // responses have trailing None values for every element that has not been written
238- ArrayList<DataType> dataTypes = new ArrayList<DataType>();
239- ArrayList<DataType> completeDataTypes = new ArrayList<DataType>();
240- ArrayList<Object> createdValues = new ArrayList<Object>();
241- ArrayList<Object> completeValues = new ArrayList<Object>();
242-
243- // create written portion of the arrays
244- for (int j = 0; j < i; ++j) {
245- dataTypes.add(DATA_TYPE_PRIMITIVES.get(j));
246- completeDataTypes.add(DATA_TYPE_PRIMITIVES.get(j));
247- createdValues.add(PrimitiveTypeSamples.ALL.get(DATA_TYPE_PRIMITIVES.get(j)));
248- completeValues.add(PrimitiveTypeSamples.ALL.get(DATA_TYPE_PRIMITIVES.get(j)));
249- }
250-
251- // complete portion of the arrays needed for trailing nulls
252- for (int j = 0; j < DATA_TYPE_PRIMITIVES.size() - i; ++j) {
253- completeDataTypes.add(DATA_TYPE_PRIMITIVES.get(i + j));
254- completeValues.add(null);
255- }
256-
257- // actually create the tuples
258- TupleType t = new TupleType(dataTypes, protocolVersion, cluster.getConfiguration().getCodecRegistry());
259- TupleType t2 = new TupleType(completeDataTypes, protocolVersion, cluster.getConfiguration().getCodecRegistry());
260- TupleValue createdTuple = t.newValue(createdValues.toArray());
261- TupleValue completeTuple = t2.newValue(completeValues.toArray());
262-
263- // write tuple
264- session.execute(String.format("INSERT INTO mytable (k, v) VALUES (%s, ?)", i), createdTuple);
265-
266- // read tuple
267- TupleValue r = session.execute("SELECT v FROM mytable WHERE k=?", i).one().getTupleValue("v");
268-
269- assertEquals(r, completeTuple);
270- ++i;
233+ // complete portion of the arrays needed for trailing nulls
234+ for (int j = 0; j < DATA_TYPE_PRIMITIVES.size() - i; ++j) {
235+ completeDataTypes.add(DATA_TYPE_PRIMITIVES.get(i + j));
236+ completeValues.add(null);
271237 }
272238
273- } catch (Exception e) {
274- errorOut();
275- throw e;
239+ // actually create the tuples
240+ TupleType t = new TupleType(dataTypes, protocolVersion, cluster.getConfiguration().getCodecRegistry());
241+ TupleType t2 = new TupleType(completeDataTypes, protocolVersion, cluster.getConfiguration().getCodecRegistry());
242+ TupleValue createdTuple = t.newValue(createdValues.toArray());
243+ TupleValue completeTuple = t2.newValue(completeValues.toArray());
244+
245+ // write tuple
246+ session.execute(String.format("INSERT INTO mytable (k, v) VALUES (%s, ?)", i), createdTuple);
247+
248+ // read tuple
249+ TupleValue r = session.execute("SELECT v FROM mytable WHERE k=?", i).one().getTupleValue("v");
250+
251+ assertEquals(r, completeTuple);
252+ ++i;
276253 }
277254 }
278255
@@ -286,108 +263,102 @@
286263 public void tupleNonPrimitiveSubTypesTest() throws Exception {
287264
288265 List<DataType> DATA_TYPE_PRIMITIVES = Lists.newArrayList(PrimitiveTypeSamples.ALL.keySet());
266+ session.execute("CREATE KEYSPACE test_tuple_non_primitive_subtypes " +
267+ "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
268+ session.execute("USE test_tuple_non_primitive_subtypes");
269+
270+ ArrayList<String> values = new ArrayList<String>();
271+
272+ //create list values
273+ for (DataType datatype : DATA_TYPE_PRIMITIVES) {
274+ values.add(String.format("v_%s frozen<tuple<list<%s>>>", values.size(), datatype));
275+ }
289276
290- try {
291- session.execute("CREATE KEYSPACE test_tuple_non_primitive_subtypes " +
292- "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
293- session.execute("USE test_tuple_non_primitive_subtypes");
294-
295- ArrayList<String> values = new ArrayList<String>();
296-
297- //create list values
298- for (DataType datatype : DATA_TYPE_PRIMITIVES) {
299- values.add(String.format("v_%s frozen<tuple<list<%s>>>", values.size(), datatype));
300- }
301-
302- // create set values
303- for (DataType datatype : DATA_TYPE_PRIMITIVES) {
304- values.add(String.format("v_%s frozen<tuple<set<%s>>>", values.size(), datatype));
305- }
277+ // create set values
278+ for (DataType datatype : DATA_TYPE_PRIMITIVES) {
279+ values.add(String.format("v_%s frozen<tuple<set<%s>>>", values.size(), datatype));
280+ }
306281
307- // create map values
308- for (DataType datatype : DATA_TYPE_PRIMITIVES) {
309- values.add(String.format("v_%s frozen<tuple<map<%s, %s>>>", values.size(), datatype, datatype));
310- }
282+ // create map values
283+ for (DataType datatype : DATA_TYPE_PRIMITIVES) {
284+ values.add(String.format("v_%s frozen<tuple<map<%s, %s>>>", values.size(), datatype, datatype));
285+ }
311286
312- // create table
313- session.execute(String.format("CREATE TABLE mytable (k int PRIMARY KEY, %s)", Joiner.on(',').join(values)));
287+ // create table
288+ session.execute(String.format("CREATE TABLE mytable (k int PRIMARY KEY, %s)", Joiner.on(',').join(values)));
314289
315290
316- int i = 0;
317- // test tuple<list<datatype>>
318- for (DataType datatype : DATA_TYPE_PRIMITIVES) {
319- // create tuple
320- ArrayList<DataType> dataTypes = new ArrayList<DataType>();
321- ArrayList<Object> createdValues = new ArrayList<Object>();
291+ int i = 0;
292+ // test tuple<list<datatype>>
293+ for (DataType datatype : DATA_TYPE_PRIMITIVES) {
294+ // create tuple
295+ ArrayList<DataType> dataTypes = new ArrayList<DataType>();
296+ ArrayList<Object> createdValues = new ArrayList<Object>();
322297
323- dataTypes.add(DataType.list(datatype));
324- createdValues.add(Arrays.asList(PrimitiveTypeSamples.ALL.get(datatype)));
298+ dataTypes.add(DataType.list(datatype));
299+ createdValues.add(Collections.singletonList(PrimitiveTypeSamples.ALL.get(datatype)));
325300
326- TupleType t = new TupleType(dataTypes, protocolVersion, cluster.getConfiguration().getCodecRegistry());
327- TupleValue createdTuple = t.newValue(createdValues.toArray());
301+ TupleType t = new TupleType(dataTypes, protocolVersion, cluster.getConfiguration().getCodecRegistry());
302+ TupleValue createdTuple = t.newValue(createdValues.toArray());
328303
329- // write tuple
330- session.execute(String.format("INSERT INTO mytable (k, v_%s) VALUES (0, ?)", i), createdTuple);
304+ // write tuple
305+ session.execute(String.format("INSERT INTO mytable (k, v_%s) VALUES (0, ?)", i), createdTuple);
331306
332- // read tuple
333- TupleValue r = session.execute(String.format("SELECT v_%s FROM mytable WHERE k=0", i))
334- .one().getTupleValue(String.format("v_%s", i));
307+ // read tuple
308+ TupleValue r = session.execute(String.format("SELECT v_%s FROM mytable WHERE k=0", i))
309+ .one().getTupleValue(String.format("v_%s", i));
335310
336- assertEquals(r, createdTuple);
337- ++i;
338- }
311+ assertEquals(r, createdTuple);
312+ ++i;
313+ }
339314
340- // test tuple<set<datatype>>
341- for (DataType datatype : DATA_TYPE_PRIMITIVES) {
342- // create tuple
343- ArrayList<DataType> dataTypes = new ArrayList<DataType>();
344- ArrayList<Object> createdValues = new ArrayList<Object>();
315+ // test tuple<set<datatype>>
316+ for (DataType datatype : DATA_TYPE_PRIMITIVES) {
317+ // create tuple
318+ ArrayList<DataType> dataTypes = new ArrayList<DataType>();
319+ ArrayList<Object> createdValues = new ArrayList<Object>();
345320
346- dataTypes.add(DataType.set(datatype));
347- createdValues.add(new HashSet<Object>(Arrays.asList(PrimitiveTypeSamples.ALL.get(datatype))));
321+ dataTypes.add(DataType.set(datatype));
322+ createdValues.add(new HashSet<Object>(Collections.singletonList(PrimitiveTypeSamples.ALL.get(datatype))));
348323
349- TupleType t = new TupleType(dataTypes, protocolVersion, cluster.getConfiguration().getCodecRegistry());
350- TupleValue createdTuple = t.newValue(createdValues.toArray());
324+ TupleType t = new TupleType(dataTypes, protocolVersion, cluster.getConfiguration().getCodecRegistry());
325+ TupleValue createdTuple = t.newValue(createdValues.toArray());
351326
352- // write tuple
353- session.execute(String.format("INSERT INTO mytable (k, v_%s) VALUES (0, ?)", i), createdTuple);
327+ // write tuple
328+ session.execute(String.format("INSERT INTO mytable (k, v_%s) VALUES (0, ?)", i), createdTuple);
354329
355- // read tuple
356- TupleValue r = session.execute(String.format("SELECT v_%s FROM mytable WHERE k=0", i))
357- .one().getTupleValue(String.format("v_%s", i));
330+ // read tuple
331+ TupleValue r = session.execute(String.format("SELECT v_%s FROM mytable WHERE k=0", i))
332+ .one().getTupleValue(String.format("v_%s", i));
358333
359- assertEquals(r, createdTuple);
360- ++i;
361- }
334+ assertEquals(r, createdTuple);
335+ ++i;
336+ }
362337
363- // test tuple<map<datatype, datatype>>
364- for (DataType datatype : DATA_TYPE_PRIMITIVES) {
365- // create tuple
366- ArrayList<DataType> dataTypes = new ArrayList<DataType>();
367- ArrayList<Object> createdValues = new ArrayList<Object>();
338+ // test tuple<map<datatype, datatype>>
339+ for (DataType datatype : DATA_TYPE_PRIMITIVES) {
340+ // create tuple
341+ ArrayList<DataType> dataTypes = new ArrayList<DataType>();
342+ ArrayList<Object> createdValues = new ArrayList<Object>();
368343
369- HashMap<Object, Object> hm = new HashMap<Object, Object>();
370- hm.put(PrimitiveTypeSamples.ALL.get(datatype), PrimitiveTypeSamples.ALL.get(datatype));
344+ HashMap<Object, Object> hm = new HashMap<Object, Object>();
345+ hm.put(PrimitiveTypeSamples.ALL.get(datatype), PrimitiveTypeSamples.ALL.get(datatype));
371346
372- dataTypes.add(DataType.map(datatype, datatype));
373- createdValues.add(hm);
347+ dataTypes.add(DataType.map(datatype, datatype));
348+ createdValues.add(hm);
374349
375- TupleType t = new TupleType(dataTypes, protocolVersion, cluster.getConfiguration().getCodecRegistry());
376- TupleValue createdTuple = t.newValue(createdValues.toArray());
350+ TupleType t = new TupleType(dataTypes, protocolVersion, cluster.getConfiguration().getCodecRegistry());
351+ TupleValue createdTuple = t.newValue(createdValues.toArray());
377352
378- // write tuple
379- session.execute(String.format("INSERT INTO mytable (k, v_%s) VALUES (0, ?)", i), createdTuple);
353+ // write tuple
354+ session.execute(String.format("INSERT INTO mytable (k, v_%s) VALUES (0, ?)", i), createdTuple);
380355
381- // read tuple
382- TupleValue r = session.execute(String.format("SELECT v_%s FROM mytable WHERE k=0", i))
383- .one().getTupleValue(String.format("v_%s", i));
356+ // read tuple
357+ TupleValue r = session.execute(String.format("SELECT v_%s FROM mytable WHERE k=0", i))
358+ .one().getTupleValue(String.format("v_%s", i));
384359
385- assertEquals(r, createdTuple);
386- ++i;
387- }
388- } catch (Exception e) {
389- errorOut();
390- throw e;
360+ assertEquals(r, createdTuple);
361+ ++i;
391362 }
392363 }
393364
@@ -411,9 +382,6 @@
411382
412383 /**
413384 * Helper method for creating nested tuple schema
414- *
415- * @param depth
416- * @return
417385 */
418386 private String nestedTuplesSchemaHelper(int depth) {
419387 if (depth == 0)
@@ -424,9 +392,6 @@
424392
425393 /**
426394 * Helper method for creating nested tuples
427- *
428- * @param depth
429- * @return
430395 */
431396 private TupleValue nestedTuplesCreatorHelper(int depth) {
432397 if (depth == 1) {
@@ -447,39 +412,33 @@
447412 */
448413 @Test(groups = "short")
449414 public void nestedTuplesTest() throws Exception {
450-
451- try {
452- session.execute("CREATE KEYSPACE test_nested_tuples " +
453- "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
454- session.execute("USE test_nested_tuples");
455-
456- // create a table with multiple sizes of nested tuples
457- session.execute(String.format("CREATE TABLE mytable (" +
458- "k int PRIMARY KEY, " +
459- "v_1 %s, " +
460- "v_2 %s, " +
461- "v_3 %s, " +
462- "v_64 %s)", nestedTuplesSchemaHelper(1),
463- nestedTuplesSchemaHelper(2),
464- nestedTuplesSchemaHelper(3),
465- nestedTuplesSchemaHelper(64)));
466-
467- for (int i : Arrays.asList(1, 2, 3, 64)) {
468- // create tuple
469- TupleValue createdTuple = nestedTuplesCreatorHelper(i);
470-
471- // write tuple
472- session.execute(String.format("INSERT INTO mytable (k, v_%s) VALUES (?, ?)", i), i, createdTuple);
473-
474- // verify tuple was written and read correctly
475- TupleValue r = session.execute(String.format("SELECT v_%s FROM mytable WHERE k=?", i), i)
476- .one().getTupleValue(String.format("v_%s", i));
477-
478- assertEquals(r, createdTuple);
479- }
480- } catch (Exception e) {
481- errorOut();
482- throw e;
415+ session.execute("CREATE KEYSPACE test_nested_tuples " +
416+ "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
417+ session.execute("USE test_nested_tuples");
418+
419+ // create a table with multiple sizes of nested tuples
420+ session.execute(String.format("CREATE TABLE mytable (" +
421+ "k int PRIMARY KEY, " +
422+ "v_1 %s, " +
423+ "v_2 %s, " +
424+ "v_3 %s, " +
425+ "v_32 %s)", nestedTuplesSchemaHelper(1),
426+ nestedTuplesSchemaHelper(2),
427+ nestedTuplesSchemaHelper(3),
428+ nestedTuplesSchemaHelper(32)));
429+
430+ for (int i : Arrays.asList(1, 2, 3, 32)) {
431+ // create tuple
432+ TupleValue createdTuple = nestedTuplesCreatorHelper(i);
433+
434+ // write tuple
435+ session.execute(String.format("INSERT INTO mytable (k, v_%s) VALUES (?, ?)", i), i, createdTuple);
436+
437+ // verify tuple was written and read correctly
438+ TupleValue r = session.execute(String.format("SELECT v_%s FROM mytable WHERE k=?", i), i)
439+ .one().getTupleValue(String.format("v_%s", i));
440+
441+ assertEquals(r, createdTuple);
483442 }
484443 }
485444
@@ -491,55 +450,49 @@
491450 */
492451 @Test(groups = "short")
493452 public void testTuplesWithNulls() throws Exception {
494- try {
495- // create keyspace
496- session.execute("CREATE KEYSPACE testTuplesWithNulls " +
497- "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
498- session.execute("USE testTuplesWithNulls");
453+ // create keyspace
454+ session.execute("CREATE KEYSPACE testTuplesWithNulls " +
455+ "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
456+ session.execute("USE testTuplesWithNulls");
499457
500- // create UDT
501- session.execute("CREATE TYPE user (a text, b frozen<tuple<text, int, uuid, blob>>)");
502- session.execute("CREATE TABLE mytable (a int PRIMARY KEY, b frozen<user>)");
458+ // create UDT
459+ session.execute("CREATE TYPE user (a text, b frozen<tuple<text, int, uuid, blob>>)");
460+ session.execute("CREATE TABLE mytable (a int PRIMARY KEY, b frozen<user>)");
503461
504- // insert UDT data
505- UserType userTypeDef = cluster.getMetadata().getKeyspace("testTuplesWithNulls").getUserType("user");
506- UDTValue userType = userTypeDef.newValue();
462+ // insert UDT data
463+ UserType userTypeDef = cluster.getMetadata().getKeyspace("testTuplesWithNulls").getUserType("user");
464+ UDTValue userType = userTypeDef.newValue();
507465
508- TupleType t = cluster.getMetadata().newTupleType(DataType.text(), DataType.cint(), DataType.uuid(), DataType.blob());
509- TupleValue v = t.newValue(null, null, null, null);
510- userType.setTupleValue("b", v);
466+ TupleType t = cluster.getMetadata().newTupleType(DataType.text(), DataType.cint(), DataType.uuid(), DataType.blob());
467+ TupleValue v = t.newValue(null, null, null, null);
468+ userType.setTupleValue("b", v);
511469
512- PreparedStatement ins = session.prepare("INSERT INTO mytable (a, b) VALUES (?, ?)");
513- session.execute(ins.bind(0, userType));
470+ PreparedStatement ins = session.prepare("INSERT INTO mytable (a, b) VALUES (?, ?)");
471+ session.execute(ins.bind(0, userType));
514472
515- // retrieve and verify data
516- ResultSet rs = session.execute("SELECT * FROM mytable");
517- List<Row> rows = rs.all();
518- assertEquals(1, rows.size());
473+ // retrieve and verify data
474+ ResultSet rs = session.execute("SELECT * FROM mytable");
475+ List<Row> rows = rs.all();
476+ assertEquals(1, rows.size());
519477
520- Row row = rows.get(0);
478+ Row row = rows.get(0);
521479
522- assertEquals(row.getInt("a"), 0);
523- assertEquals(row.getUDTValue("b"), userType);
480+ assertEquals(row.getInt("a"), 0);
481+ assertEquals(row.getUDTValue("b"), userType);
524482
525- // test empty strings
526- v = t.newValue("", null, null, ByteBuffer.allocate(0));
527- userType.setTupleValue("b", v);
528- session.execute(ins.bind(0, userType));
483+ // test empty strings
484+ v = t.newValue("", null, null, ByteBuffer.allocate(0));
485+ userType.setTupleValue("b", v);
486+ session.execute(ins.bind(0, userType));
529487
530- // retrieve and verify data
531- rs = session.execute("SELECT * FROM mytable");
532- rows = rs.all();
533- assertEquals(1, rows.size());
488+ // retrieve and verify data
489+ rs = session.execute("SELECT * FROM mytable");
490+ rows = rs.all();
491+ assertEquals(1, rows.size());
534492
535- row = rows.get(0);
493+ row = rows.get(0);
536494
537- assertEquals(row.getInt("a"), 0);
538- assertEquals(row.getUDTValue("b"), userType);
539-
540- } catch (Exception e) {
541- errorOut();
542- throw e;
543- }
495+ assertEquals(row.getInt("a"), 0);
496+ assertEquals(row.getUDTValue("b"), userType);
544497 }
545498 }
modified driver-core/src/test/java/com/datastax/driver/core/TypeCodecCollectionsIntegrationTest.java +2 −2
@@ -35,7 +35,7 @@
3535 import static org.assertj.core.api.Assertions.assertThat;
3636
3737 @CassandraVersion(major = 2.0)
38-public class TypeCodecCollectionsIntegrationTest extends CCMBridge.PerClassSingleNodeCluster {
38+public class TypeCodecCollectionsIntegrationTest extends CCMTestsSupport {
3939
4040 private final String insertQuery = "INSERT INTO \"myTable2\" (c_int, l_int, l_bigint, s_float, s_double, m_varint, m_decimal) VALUES (?, ?, ?, ?, ?, ?, ?)";
4141
@@ -53,7 +53,7 @@
5353 private Map<Integer, BigDecimal> m_decimal = ImmutableMap.of(42, new BigDecimal("424242.42"), 43, new BigDecimal("434343.43"));
5454
5555 @Override
56- protected Collection<String> getTableDefinitions() {
56+ public Collection<String> createTestFixtures() {
5757 return newArrayList(
5858 "CREATE TABLE IF NOT EXISTS \"myTable2\" ("
5959 + "c_int int PRIMARY KEY, "
modified driver-core/src/test/java/com/datastax/driver/core/TypeCodecEncapsulationIntegrationTest.java +4 −4
@@ -33,7 +33,7 @@
3333 import static com.google.common.collect.Lists.newArrayList;
3434 import static org.assertj.core.api.Assertions.assertThat;
3535
36-public class TypeCodecEncapsulationIntegrationTest extends CCMBridge.PerClassSingleNodeCluster {
36+public class TypeCodecEncapsulationIntegrationTest extends CCMTestsSupport {
3737
3838 // @formatter:off
3939 private static final TypeToken<NumberBox<Integer>> NUMBERBOX_OF_INTEGER_TOKEN = new TypeToken<NumberBox<Integer>>() {};
@@ -59,7 +59,7 @@
5959 private BigDecimal n_decimal = new BigDecimal("424242.42");
6060
6161 @Override
62- protected Collection<String> getTableDefinitions() {
62+ public Collection<String> createTestFixtures() {
6363 return newArrayList(
6464 "CREATE TABLE \"myTable\" ("
6565 + "c_int int, "
@@ -74,8 +74,8 @@
7474 }
7575
7676 @Override
77- protected Cluster.Builder configure(Cluster.Builder builder) {
78- return builder.withCodecRegistry(
77+ public Cluster.Builder createClusterBuilder() {
78+ return Cluster.builder().withCodecRegistry(
7979 new CodecRegistry()
8080 .register(
8181 new NumberBoxCodec<Integer>(TypeCodec.cint()),
modified driver-core/src/test/java/com/datastax/driver/core/TypeCodecNestedCollectionsIntegrationTest.java +4 −5
@@ -37,7 +37,7 @@
3737 * even if some inner type requires a custom codec.
3838 */
3939 @CassandraVersion(major = 2.1)
40-public class TypeCodecNestedCollectionsIntegrationTest extends CCMBridge.PerClassSingleNodeCluster {
40+public class TypeCodecNestedCollectionsIntegrationTest extends CCMTestsSupport {
4141
4242 private final String insertQuery = "INSERT INTO \"myTable\" (pk, v) VALUES (?, ?)";
4343
@@ -55,7 +55,7 @@
5555 // @formatter:on
5656
5757 @Override
58- protected Collection<String> getTableDefinitions() {
58+ public Collection<String> createTestFixtures() {
5959 return newArrayList(
6060 "CREATE TABLE IF NOT EXISTS \"myTable\" ("
6161 + "pk int PRIMARY KEY, "
@@ -64,9 +64,8 @@
6464 );
6565 }
6666
67- @Override
68- protected Cluster.Builder configure(Cluster.Builder builder) {
69- return builder.withCodecRegistry(
67+ public Cluster.Builder createClusterBuilder() {
68+ return Cluster.builder().withCodecRegistry(
7069 new CodecRegistry().register(new MyIntCodec()) // global User <-> varchar codec
7170 );
7271 }
modified driver-core/src/test/java/com/datastax/driver/core/TypeCodecNestedUDTAndTupleIntegrationTest.java +2 −2
@@ -32,10 +32,10 @@
3232 * @jira_ticket JAVA-847
3333 */
3434 @CassandraVersion(major = 2.1)
35-public class TypeCodecNestedUDTAndTupleIntegrationTest extends CCMBridge.PerClassSingleNodeCluster {
35+public class TypeCodecNestedUDTAndTupleIntegrationTest extends CCMTestsSupport {
3636
3737 @Override
38- protected Collection<String> getTableDefinitions() {
38+ public Collection<String> createTestFixtures() {
3939 return Lists.newArrayList(
4040 "CREATE TYPE IF NOT EXISTS \"udt3\" (f3 text)",
4141 "CREATE TYPE IF NOT EXISTS \"udt2\" (f2 frozen<udt3>)",
modified driver-core/src/test/java/com/datastax/driver/core/TypeCodecNumbersIntegrationTest.java +2 −2
@@ -25,7 +25,7 @@
2525 import static com.google.common.collect.Lists.newArrayList;
2626 import static org.assertj.core.api.Assertions.assertThat;
2727
28-public class TypeCodecNumbersIntegrationTest extends CCMBridge.PerClassSingleNodeCluster {
28+public class TypeCodecNumbersIntegrationTest extends CCMTestsSupport {
2929
3030 private final String insertQuery = "INSERT INTO \"myTable\" (c_int, c_bigint, c_float, c_double, c_varint, c_decimal) VALUES (?, ?, ?, ?, ?, ?)";
3131
@@ -40,7 +40,7 @@
4040
4141
4242 @Override
43- protected Collection<String> getTableDefinitions() {
43+ public Collection<String> createTestFixtures() {
4444 return newArrayList(
4545 "CREATE TABLE \"myTable\" ("
4646 + "c_int int, "
modified driver-core/src/test/java/com/datastax/driver/core/TypeCodecOverlappingJavaTypeIntegrationTest.java +4 −5
@@ -29,14 +29,14 @@
2929 * SimpleStatements become almost unusable in these cases, but we are adding tests
3030 * to check that at least it is possible to use prepared statements in these situations.
3131 */
32-public class TypeCodecOverlappingJavaTypeIntegrationTest extends CCMBridge.PerClassSingleNodeCluster {
32+public class TypeCodecOverlappingJavaTypeIntegrationTest extends CCMTestsSupport {
3333
3434 private static final String insertQuery = "INSERT INTO \"myTable\" (c_int, l_int, c_text) VALUES (?, ?, ?)";
3535
3636 private static final String selectQuery = "SELECT c_int, l_int, c_text FROM \"myTable\" WHERE c_int = ?";
3737
3838 @Override
39- protected Collection<String> getTableDefinitions() {
39+ public Collection<String> createTestFixtures() {
4040 return newArrayList(
4141 "CREATE TABLE \"myTable\" ("
4242 + "c_int int PRIMARY KEY, "
@@ -46,9 +46,8 @@
4646 );
4747 }
4848
49- @Override
50- protected Cluster.Builder configure(Cluster.Builder builder) {
51- return builder.withCodecRegistry(
49+ public Cluster.Builder createClusterBuilder() {
50+ return Cluster.builder().withCodecRegistry(
5251 new CodecRegistry().register(new IntToStringCodec())
5352 );
5453 }
modified driver-core/src/test/java/com/datastax/driver/core/TypeCodecTupleIntegrationTest.java +50 −63
@@ -20,14 +20,13 @@
2020 import org.testng.annotations.Test;
2121
2222 import java.util.Collection;
23-import java.util.Collections;
2423 import java.util.UUID;
2524
2625 import static com.datastax.driver.core.DataType.cfloat;
2726 import static org.assertj.core.api.Assertions.assertThat;
2827
2928 @CassandraVersion(major = 2.1)
30-public class TypeCodecTupleIntegrationTest extends CCMBridge.PerClassSingleNodeCluster {
29+public class TypeCodecTupleIntegrationTest extends CCMTestsSupport {
3130
3231 private final String insertQuery = "INSERT INTO users (id, name, location) VALUES (?, ?, ?)";
3332 private final String selectQuery = "SELECT id, name, location FROM users WHERE id = ?";
@@ -42,7 +41,7 @@
4241 private TupleValue partialLocationValueRetrieved;
4342
4443 @Override
45- protected Collection<String> getTableDefinitions() {
44+ public Collection<String> createTestFixtures() {
4645 return Lists.newArrayList(
4746 "CREATE TABLE IF NOT EXISTS \"users\" (id uuid PRIMARY KEY, name text, location frozen<tuple<float,float>>)"
4847 );
@@ -93,73 +92,61 @@
9392 @Test(groups = "short")
9493 public void should_handle_tuples_with_custom_codecs() {
9594 CodecRegistry codecRegistry = new CodecRegistry();
96- Cluster cluster = Cluster.builder()
97- .addContactPointsWithPorts(Collections.singleton(hostAddress))
95+ Cluster cluster = register(Cluster.builder()
96+ .addContactPointsWithPorts(getInitialContactPoints())
97+ .withAddressTranslator(getAddressTranslator())
9898 .withCodecRegistry(codecRegistry)
99- .build();
100-
101- try {
102- Session session = cluster.connect(keyspace);
103- setUpTupleTypes(cluster);
104- codecRegistry
105- .register(new LocationCodec(TypeCodec.tuple(locationType)))
106- ;
107- session.execute(insertQuery, uuid, "John Doe", locationValue);
108- ResultSet rows = session.execute(selectQuery, uuid);
109- Row row = rows.one();
110- assertThat(row.getUUID(0)).isEqualTo(uuid);
111- assertThat(row.getObject(0)).isEqualTo(uuid);
112- assertThat(row.get(0, UUID.class)).isEqualTo(uuid);
113- assertThat(row.getString(1)).isEqualTo("John Doe");
114- assertThat(row.getObject(1)).isEqualTo("John Doe");
115- assertThat(row.get(1, String.class)).isEqualTo("John Doe");
116- assertThat(row.getTupleValue(2)).isEqualTo(locationValue);
117- // edge case: getObject should use default codecs;
118- // but tuple and udt codecs are registered on the fly;
119- // so if we have another manually-registered codec
120- // that one will be picked up
121- assertThat(row.getObject(2)).isEqualTo(location);
122- assertThat(row.get(2, TupleValue.class)).isEqualTo(locationValue);
123- assertThat(row.get(2, Location.class)).isEqualTo(location);
124- } finally {
125- cluster.close();
126- }
99+ .build());
100+ Session session = cluster.connect(keyspace);
101+ setUpTupleTypes(cluster);
102+ codecRegistry.register(new LocationCodec(TypeCodec.tuple(locationType)));
103+ session.execute(insertQuery, uuid, "John Doe", locationValue);
104+ ResultSet rows = session.execute(selectQuery, uuid);
105+ Row row = rows.one();
106+ assertThat(row.getUUID(0)).isEqualTo(uuid);
107+ assertThat(row.getObject(0)).isEqualTo(uuid);
108+ assertThat(row.get(0, UUID.class)).isEqualTo(uuid);
109+ assertThat(row.getString(1)).isEqualTo("John Doe");
110+ assertThat(row.getObject(1)).isEqualTo("John Doe");
111+ assertThat(row.get(1, String.class)).isEqualTo("John Doe");
112+ assertThat(row.getTupleValue(2)).isEqualTo(locationValue);
113+ // edge case: getObject should use default codecs;
114+ // but tuple and udt codecs are registered on the fly;
115+ // so if we have another manually-registered codec
116+ // that one will be picked up
117+ assertThat(row.getObject(2)).isEqualTo(location);
118+ assertThat(row.get(2, TupleValue.class)).isEqualTo(locationValue);
119+ assertThat(row.get(2, Location.class)).isEqualTo(location);
127120 }
128121
129122 @Test(groups = "short")
130123 public void should_handle_partial_tuples_with_custom_codecs() {
131124 CodecRegistry codecRegistry = new CodecRegistry();
132- Cluster cluster = Cluster.builder()
133- .addContactPointsWithPorts(Collections.singleton(hostAddress))
125+ Cluster cluster = register(Cluster.builder()
126+ .addContactPointsWithPorts(getInitialContactPoints())
127+ .withAddressTranslator(getAddressTranslator())
134128 .withCodecRegistry(codecRegistry)
135- .build();
136-
137- try {
138- Session session = cluster.connect(keyspace);
139- setUpTupleTypes(cluster);
140- codecRegistry
141- .register(new LocationCodec(TypeCodec.tuple(locationType)))
142- ;
143- session.execute(insertQuery, uuid, "John Doe", partialLocationValueInserted);
144- ResultSet rows = session.execute(selectQuery, uuid);
145- Row row = rows.one();
146- assertThat(row.getUUID(0)).isEqualTo(uuid);
147- assertThat(row.getObject(0)).isEqualTo(uuid);
148- assertThat(row.get(0, UUID.class)).isEqualTo(uuid);
149- assertThat(row.getString(1)).isEqualTo("John Doe");
150- assertThat(row.getObject(1)).isEqualTo("John Doe");
151- assertThat(row.get(1, String.class)).isEqualTo("John Doe");
152- assertThat(row.getTupleValue(2)).isEqualTo(locationType.newValue(37.387224f, null));
153- // corner case: getObject should use default codecs;
154- // but tuple and udt codecs are registered on the fly;
155- // so if we have another manually-registered codec
156- // that one will be picked up :(
157- assertThat(row.getObject(2)).isEqualTo(partialLocation);
158- assertThat(row.get(2, TupleValue.class)).isEqualTo(locationType.newValue(37.387224f, null));
159- assertThat(row.get(2, Location.class)).isEqualTo(partialLocation);
160- } finally {
161- cluster.close();
162- }
129+ .build());
130+ Session session = cluster.connect(keyspace);
131+ setUpTupleTypes(cluster);
132+ codecRegistry.register(new LocationCodec(TypeCodec.tuple(locationType)));
133+ session.execute(insertQuery, uuid, "John Doe", partialLocationValueInserted);
134+ ResultSet rows = session.execute(selectQuery, uuid);
135+ Row row = rows.one();
136+ assertThat(row.getUUID(0)).isEqualTo(uuid);
137+ assertThat(row.getObject(0)).isEqualTo(uuid);
138+ assertThat(row.get(0, UUID.class)).isEqualTo(uuid);
139+ assertThat(row.getString(1)).isEqualTo("John Doe");
140+ assertThat(row.getObject(1)).isEqualTo("John Doe");
141+ assertThat(row.get(1, String.class)).isEqualTo("John Doe");
142+ assertThat(row.getTupleValue(2)).isEqualTo(locationType.newValue(37.387224f, null));
143+ // corner case: getObject should use default codecs;
144+ // but tuple and udt codecs are registered on the fly;
145+ // so if we have another manually-registered codec
146+ // that one will be picked up :(
147+ assertThat(row.getObject(2)).isEqualTo(partialLocation);
148+ assertThat(row.get(2, TupleValue.class)).isEqualTo(locationType.newValue(37.387224f, null));
149+ assertThat(row.get(2, Location.class)).isEqualTo(partialLocation);
163150 }
164151
165152 private void assertRow(Row row) {
modified driver-core/src/test/java/com/datastax/driver/core/TypeCodecUDTIntegrationTest.java +35 −36
@@ -20,12 +20,15 @@
2020 import com.google.common.collect.Sets;
2121 import org.testng.annotations.Test;
2222
23-import java.util.*;
23+import java.util.Collection;
24+import java.util.List;
25+import java.util.Set;
26+import java.util.UUID;
2427
2528 import static org.assertj.core.api.Assertions.assertThat;
2629
2730 @CassandraVersion(major = 2.1)
28-public class TypeCodecUDTIntegrationTest extends CCMBridge.PerClassSingleNodeCluster {
31+public class TypeCodecUDTIntegrationTest extends CCMTestsSupport {
2932
3033 private final String insertQuery = "INSERT INTO users (id, name, address) VALUES (?, ?, ?)";
3134 private final String selectQuery = "SELECT id, name, address FROM users WHERE id = ?";
@@ -42,7 +45,7 @@
4245 private UDTValue addressValue;
4346
4447 @Override
45- protected Collection<String> getTableDefinitions() {
48+ public Collection<String> createTestFixtures() {
4649 return Lists.newArrayList(
4750 "CREATE TYPE IF NOT EXISTS \"phone\" (number text, tags set<text>)",
4851 "CREATE TYPE IF NOT EXISTS \"address\" (street text, zipcode int, phones list<frozen<phone>>)",
@@ -74,40 +77,36 @@
7477 @Test(groups = "short")
7578 public void should_handle_udts_with_custom_codecs() {
7679 CodecRegistry codecRegistry = new CodecRegistry();
77- Cluster cluster = Cluster.builder()
78- .addContactPointsWithPorts(Collections.singleton(hostAddress))
80+ Cluster cluster = register(Cluster.builder()
81+ .addContactPointsWithPorts(getInitialContactPoints())
82+ .withAddressTranslator(getAddressTranslator())
7983 .withCodecRegistry(codecRegistry)
80- .build();
81-
82- try {
83- Session session = cluster.connect(keyspace);
84- setUpUserTypes(cluster);
85- TypeCodec<UDTValue> addressTypeCodec = TypeCodec.userType(addressType);
86- TypeCodec<UDTValue> phoneTypeCodec = TypeCodec.userType(phoneType);
87- codecRegistry
88- .register(new AddressCodec(addressTypeCodec, Address.class))
89- .register(new PhoneCodec(phoneTypeCodec, Phone.class))
90- ;
91- session.execute(insertQuery, uuid, "John Doe", address);
92- ResultSet rows = session.execute(selectQuery, uuid);
93- Row row = rows.one();
94- assertThat(row.getUUID(0)).isEqualTo(uuid);
95- assertThat(row.getObject(0)).isEqualTo(uuid);
96- assertThat(row.get(0, UUID.class)).isEqualTo(uuid);
97- assertThat(row.getString(1)).isEqualTo("John Doe");
98- assertThat(row.getObject(1)).isEqualTo("John Doe");
99- assertThat(row.get(1, String.class)).isEqualTo("John Doe");
100- assertThat(row.getUDTValue(2)).isEqualTo(addressValue);
101- // corner case: getObject should use default codecs;
102- // but tuple and udt codecs are registered on the fly;
103- // so if we have another manually-registered codec
104- // that one will be picked up :(
105- assertThat(row.getObject(2)).isEqualTo(address);
106- assertThat(row.get(2, UDTValue.class)).isEqualTo(addressValue);
107- assertThat(row.get(2, Address.class)).isEqualTo(address);
108- } finally {
109- cluster.close();
110- }
84+ .build());
85+ Session session = cluster.connect(keyspace);
86+ setUpUserTypes(cluster);
87+ TypeCodec<UDTValue> addressTypeCodec = TypeCodec.userType(addressType);
88+ TypeCodec<UDTValue> phoneTypeCodec = TypeCodec.userType(phoneType);
89+ codecRegistry
90+ .register(new AddressCodec(addressTypeCodec, Address.class))
91+ .register(new PhoneCodec(phoneTypeCodec, Phone.class))
92+ ;
93+ session.execute(insertQuery, uuid, "John Doe", address);
94+ ResultSet rows = session.execute(selectQuery, uuid);
95+ Row row = rows.one();
96+ assertThat(row.getUUID(0)).isEqualTo(uuid);
97+ assertThat(row.getObject(0)).isEqualTo(uuid);
98+ assertThat(row.get(0, UUID.class)).isEqualTo(uuid);
99+ assertThat(row.getString(1)).isEqualTo("John Doe");
100+ assertThat(row.getObject(1)).isEqualTo("John Doe");
101+ assertThat(row.get(1, String.class)).isEqualTo("John Doe");
102+ assertThat(row.getUDTValue(2)).isEqualTo(addressValue);
103+ // corner case: getObject should use default codecs;
104+ // but tuple and udt codecs are registered on the fly;
105+ // so if we have another manually-registered codec
106+ // that one will be picked up :(
107+ assertThat(row.getObject(2)).isEqualTo(address);
108+ assertThat(row.get(2, UDTValue.class)).isEqualTo(addressValue);
109+ assertThat(row.get(2, Address.class)).isEqualTo(address);
111110 }
112111
113112 private void assertRow(Row row) {
modified driver-core/src/test/java/com/datastax/driver/core/UnresolvedUserTypeTest.java +7 −11
@@ -20,17 +20,16 @@
2020 import org.testng.annotations.Test;
2121
2222 import java.util.Collection;
23-import java.util.Collections;
2423 import java.util.concurrent.ExecutionException;
2524
2625 import static com.datastax.driver.core.Assertions.assertThat;
2726 import static com.datastax.driver.core.DataType.*;
2827
2928 @CassandraVersion(major = 3.0)
30-public class UnresolvedUserTypeTest extends CCMBridge.PerClassSingleNodeCluster {
29+public class UnresolvedUserTypeTest extends CCMTestsSupport {
3130
3231 @Override
33- protected Collection<String> getTableDefinitions() {
32+ public Collection<String> createTestFixtures() {
3433 return Lists.newArrayList(
3534 /*
3635 Creates the following acyclic graph (edges directed upwards
@@ -68,14 +67,11 @@
6867
6968 // Create a different Cluster instance to force a full refresh where all UDTs are loaded at once.
7069 // The parsing logic should sort them to make sure they are loaded in the right order.
71- Cluster newCluster = null;
72- try {
73- newCluster = Cluster.builder().addContactPointsWithPorts(Collections.singletonList(hostAddress)).build();
74- checkUserTypes(newCluster.getMetadata());
75- } finally {
76- if (newCluster != null)
77- newCluster.close();
78- }
70+ Cluster newCluster = register(Cluster.builder()
71+ .addContactPointsWithPorts(getInitialContactPoints())
72+ .withAddressTranslator(getAddressTranslator())
73+ .build());
74+ checkUserTypes(newCluster.getMetadata());
7975 }
8076
8177 private void checkUserTypes(Metadata metadata) {
modified driver-core/src/test/java/com/datastax/driver/core/UserTypesTest.java +346 −406
@@ -34,7 +34,7 @@
3434 import static org.testng.Assert.assertNotEquals;
3535
3636 @CassandraVersion(major = 2.1)
37-public class UserTypesTest extends CCMBridge.PerClassSingleNodeCluster {
37+public class UserTypesTest extends CCMTestsSupport {
3838
3939 private final static List<DataType> DATA_TYPE_PRIMITIVES = new ArrayList<DataType>(DataType.allPrimitiveTypes(TestUtils.getDesiredProtocolVersion()));
4040
@@ -46,12 +46,10 @@
4646 new ArrayList<DataType.Name>(EnumSet.of(DataType.Name.LIST, DataType.Name.SET, DataType.Name.MAP, DataType.Name.TUPLE));
4747
4848 @Override
49- protected Collection<String> getTableDefinitions() {
49+ public Collection<String> createTestFixtures() {
5050 String type1 = "CREATE TYPE phone (alias text, number text)";
5151 String type2 = "CREATE TYPE \"\"\"User Address\"\"\" (street text, \"ZIP\"\"\" int, phones set<frozen<phone>>)";
52-
5352 String table = "CREATE TABLE user (id int PRIMARY KEY, addr frozen<\"\"\"User Address\"\"\">)";
54-
5553 return Arrays.asList(type1, type2, table);
5654 }
5755
@@ -63,30 +61,23 @@
6361 @Test(groups = "short")
6462 public void simpleWriteReadTest() throws Exception {
6563 int userId = 0;
64+ PreparedStatement ins = session.prepare("INSERT INTO user(id, addr) VALUES (?, ?)");
65+ PreparedStatement sel = session.prepare("SELECT * FROM user WHERE id=?");
6666
67- try {
68- session.execute("USE " + keyspace);
69- PreparedStatement ins = session.prepare("INSERT INTO user(id, addr) VALUES (?, ?)");
70- PreparedStatement sel = session.prepare("SELECT * FROM user WHERE id=?");
71-
72- UserType addrDef = cluster.getMetadata().getKeyspace(keyspace).getUserType(quote("\"User Address\""));
73- UserType phoneDef = cluster.getMetadata().getKeyspace(keyspace).getUserType("phone");
67+ UserType addrDef = cluster.getMetadata().getKeyspace(keyspace).getUserType(quote("\"User Address\""));
68+ UserType phoneDef = cluster.getMetadata().getKeyspace(keyspace).getUserType("phone");
7469
75- UDTValue phone1 = phoneDef.newValue().setString("alias", "home").setString("number", "0123548790");
76- UDTValue phone2 = phoneDef.newValue().setString("alias", "work").setString("number", "0698265251");
70+ UDTValue phone1 = phoneDef.newValue().setString("alias", "home").setString("number", "0123548790");
71+ UDTValue phone2 = phoneDef.newValue().setString("alias", "work").setString("number", "0698265251");
7772
78- UDTValue addr = addrDef.newValue().setString("street", "1600 Pennsylvania Ave NW").setInt(quote("ZIP\""), 20500).setSet("phones", ImmutableSet.of(phone1, phone2));
73+ UDTValue addr = addrDef.newValue().setString("street", "1600 Pennsylvania Ave NW").setInt(quote("ZIP\""), 20500).setSet("phones", ImmutableSet.of(phone1, phone2));
7974
80- session.execute(ins.bind(userId, addr));
75+ session.execute(ins.bind(userId, addr));
8176
82- Row r = session.execute(sel.bind(userId)).one();
77+ Row r = session.execute(sel.bind(userId)).one();
8378
84- assertEquals(r.getInt("id"), 0);
85- assertEquals(r.getUDTValue("addr"), addr);
86- } catch (Exception e) {
87- errorOut();
88- throw e;
89- }
79+ assertEquals(r.getInt("id"), 0);
80+ assertEquals(r.getUDTValue("addr"), addr);
9081 }
9182
9283 /**
@@ -97,27 +88,21 @@
9788 @Test(groups = "short")
9889 public void simpleUnpreparedWriteReadTest() throws Exception {
9990 int userId = 1;
91+ session.execute("USE " + keyspace);
92+ UserType addrDef = cluster.getMetadata().getKeyspace(keyspace).getUserType(quote("\"User Address\""));
93+ UserType phoneDef = cluster.getMetadata().getKeyspace(keyspace).getUserType("phone");
10094
101- try {
102- session.execute("USE " + keyspace);
103- UserType addrDef = cluster.getMetadata().getKeyspace(keyspace).getUserType(quote("\"User Address\""));
104- UserType phoneDef = cluster.getMetadata().getKeyspace(keyspace).getUserType("phone");
105-
106- UDTValue phone1 = phoneDef.newValue().setString("alias", "home").setString("number", "0123548790");
107- UDTValue phone2 = phoneDef.newValue().setString("alias", "work").setString("number", "0698265251");
95+ UDTValue phone1 = phoneDef.newValue().setString("alias", "home").setString("number", "0123548790");
96+ UDTValue phone2 = phoneDef.newValue().setString("alias", "work").setString("number", "0698265251");
10897
109- UDTValue addr = addrDef.newValue().setString("street", "1600 Pennsylvania Ave NW").setInt(quote("ZIP\""), 20500).setSet("phones", ImmutableSet.of(phone1, phone2));
98+ UDTValue addr = addrDef.newValue().setString("street", "1600 Pennsylvania Ave NW").setInt(quote("ZIP\""), 20500).setSet("phones", ImmutableSet.of(phone1, phone2));
11099
111- session.execute("INSERT INTO user(id, addr) VALUES (?, ?)", userId, addr);
100+ session.execute("INSERT INTO user(id, addr) VALUES (?, ?)", userId, addr);
112101
113- Row r = session.execute("SELECT * FROM user WHERE id=?", userId).one();
102+ Row r = session.execute("SELECT * FROM user WHERE id=?", userId).one();
114103
115- assertEquals(r.getInt("id"), 1);
116- assertEquals(r.getUDTValue("addr"), addr);
117- } catch (Exception e) {
118- errorOut();
119- throw e;
120- }
104+ assertEquals(r.getInt("id"), 1);
105+ assertEquals(r.getUDTValue("addr"), addr);
121106 }
122107
123108 /**
@@ -127,41 +112,33 @@
127112 */
128113 @Test(groups = "short")
129114 public void nonExistingTypesTest() throws Exception {
130- try {
131- session.execute("USE " + keyspace);
132-
133- UserType addrDef = cluster.getMetadata().getKeyspace(keyspace).getUserType("address1");
134- UserType phoneDef = cluster.getMetadata().getKeyspace(keyspace).getUserType("phone1");
135- assertEquals(addrDef, null);
136- assertEquals(phoneDef, null);
137-
138- addrDef = cluster.getMetadata().getKeyspace(keyspace).getUserType(quote("\"User Address\""));
139- phoneDef = cluster.getMetadata().getKeyspace(keyspace).getUserType("phone");
140- assertNotEquals(addrDef, null);
141- assertNotEquals(phoneDef, null);
142-
143- // create keyspace
144- String nonExistingKeyspace = keyspace + "_nonEx";
145- session.execute("CREATE KEYSPACE " + nonExistingKeyspace + " " +
146- "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
147- session.execute("USE " + nonExistingKeyspace);
148-
149- addrDef = cluster.getMetadata().getKeyspace(nonExistingKeyspace).getUserType(quote("\"User Address\""));
150- phoneDef = cluster.getMetadata().getKeyspace(nonExistingKeyspace).getUserType("phone");
151- assertEquals(addrDef, null);
152- assertEquals(phoneDef, null);
153-
154- session.execute("USE " + keyspace);
155-
156- addrDef = cluster.getMetadata().getKeyspace(keyspace).getUserType(quote("\"User Address\""));
157- phoneDef = cluster.getMetadata().getKeyspace(keyspace).getUserType("phone");
158- assertNotEquals(addrDef, null);
159- assertNotEquals(phoneDef, null);
160-
161- } catch (Exception e) {
162- errorOut();
163- throw e;
164- }
115+ UserType addrDef = cluster.getMetadata().getKeyspace(keyspace).getUserType("address1");
116+ UserType phoneDef = cluster.getMetadata().getKeyspace(keyspace).getUserType("phone1");
117+ assertEquals(addrDef, null);
118+ assertEquals(phoneDef, null);
119+
120+ addrDef = cluster.getMetadata().getKeyspace(keyspace).getUserType(quote("\"User Address\""));
121+ phoneDef = cluster.getMetadata().getKeyspace(keyspace).getUserType("phone");
122+ assertNotEquals(addrDef, null);
123+ assertNotEquals(phoneDef, null);
124+
125+ // create keyspace
126+ String nonExistingKeyspace = keyspace + "_nonEx";
127+ session.execute("CREATE KEYSPACE " + nonExistingKeyspace + " " +
128+ "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
129+ session.execute("USE " + nonExistingKeyspace);
130+
131+ addrDef = cluster.getMetadata().getKeyspace(nonExistingKeyspace).getUserType(quote("\"User Address\""));
132+ phoneDef = cluster.getMetadata().getKeyspace(nonExistingKeyspace).getUserType("phone");
133+ assertEquals(addrDef, null);
134+ assertEquals(phoneDef, null);
135+
136+ session.execute("USE " + keyspace);
137+
138+ addrDef = cluster.getMetadata().getKeyspace(keyspace).getUserType(quote("\"User Address\""));
139+ phoneDef = cluster.getMetadata().getKeyspace(keyspace).getUserType("phone");
140+ assertNotEquals(addrDef, null);
141+ assertNotEquals(phoneDef, null);
165142 }
166143
167144 /**
@@ -173,48 +150,42 @@
173150 @Test(groups = "short")
174151 public void udtSizesTest() throws Exception {
175152 int MAX_TEST_LENGTH = 1024;
176-
177- try {
178- // create keyspace
179- session.execute("CREATE KEYSPACE test_udt_sizes " +
180- "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
181- session.execute("USE test_udt_sizes");
182-
183- // create the seed udt
184- StringBuilder sb = new StringBuilder();
185- for (int i = 0; i < MAX_TEST_LENGTH; ++i) {
186- sb.append(String.format("v_%s int", i));
187-
188- if (i + 1 < MAX_TEST_LENGTH)
189- sb.append(",");
153+ // create keyspace
154+ session.execute("CREATE KEYSPACE test_udt_sizes " +
155+ "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
156+ session.execute("USE test_udt_sizes");
157+
158+ // create the seed udt
159+ StringBuilder sb = new StringBuilder();
160+ for (int i = 0; i < MAX_TEST_LENGTH; ++i) {
161+ sb.append(String.format("v_%s int", i));
162+
163+ if (i + 1 < MAX_TEST_LENGTH)
164+ sb.append(",");
165+ }
166+ session.execute(String.format("CREATE TYPE lengthy_udt (%s)", sb.toString()));
167+
168+ // create a table with multiple sizes of udts
169+ session.execute("CREATE TABLE mytable (k int PRIMARY KEY, v frozen<lengthy_udt>)");
170+
171+ // hold onto the UserType for future use
172+ UserType udtDef = cluster.getMetadata().getKeyspace("test_udt_sizes").getUserType("lengthy_udt");
173+
174+ // verify inserts and reads
175+ for (int i : Arrays.asList(0, 1, 2, 3, MAX_TEST_LENGTH)) {
176+ // create udt
177+ UDTValue createdUDT = udtDef.newValue();
178+ for (int j = 0; j < i; ++j) {
179+ createdUDT.setInt(j, j);
190180 }
191- session.execute(String.format("CREATE TYPE lengthy_udt (%s)", sb.toString()));
192-
193- // create a table with multiple sizes of udts
194- session.execute("CREATE TABLE mytable (k int PRIMARY KEY, v frozen<lengthy_udt>)");
195-
196- // hold onto the UserType for future use
197- UserType udtDef = cluster.getMetadata().getKeyspace("test_udt_sizes").getUserType("lengthy_udt");
198-
199- // verify inserts and reads
200- for (int i : Arrays.asList(0, 1, 2, 3, MAX_TEST_LENGTH)) {
201- // create udt
202- UDTValue createdUDT = udtDef.newValue();
203- for (int j = 0; j < i; ++j) {
204- createdUDT.setInt(j, j);
205- }
206181
207- // write udt
208- session.execute("INSERT INTO mytable (k, v) VALUES (0, ?)", createdUDT);
182+ // write udt
183+ session.execute("INSERT INTO mytable (k, v) VALUES (0, ?)", createdUDT);
209184
210- // verify udt was written and read correctly
211- UDTValue r = session.execute("SELECT v FROM mytable WHERE k=0")
212- .one().getUDTValue("v");
213- assertEquals(r.toString(), createdUDT.toString());
214- }
215- } catch (Exception e) {
216- errorOut();
217- throw e;
185+ // verify udt was written and read correctly
186+ UDTValue r = session.execute("SELECT v FROM mytable WHERE k=0")
187+ .one().getUDTValue("v");
188+ assertEquals(r.toString(), createdUDT.toString());
218189 }
219190 }
220191
@@ -226,110 +197,104 @@
226197 */
227198 @Test(groups = "short")
228199 public void testPrimitiveDatatypes() throws Exception {
229- try {
230- // create keyspace
231- session.execute("CREATE KEYSPACE testPrimitiveDatatypes " +
232- "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
233- session.execute("USE testPrimitiveDatatypes");
234-
235- // create UDT
236- List<String> alpha_type_list = new ArrayList<String>();
237- int startIndex = (int) 'a';
238- for (int i = 0; i < DATA_TYPE_PRIMITIVES.size(); i++) {
239- alpha_type_list.add(String.format("%s %s", Character.toString((char) (startIndex + i)),
240- DATA_TYPE_PRIMITIVES.get(i).getName()));
241- }
242-
243- session.execute(String.format("CREATE TYPE alldatatypes (%s)", Joiner.on(',').join(alpha_type_list)));
244- session.execute("CREATE TABLE mytable (a int PRIMARY KEY, b frozen<alldatatypes>)");
245-
246- // insert UDT data
247- UserType alldatatypesDef = cluster.getMetadata().getKeyspace("testPrimitiveDatatypes").getUserType("alldatatypes");
248- UDTValue alldatatypes = alldatatypesDef.newValue();
249-
250- for (int i = 0; i < DATA_TYPE_PRIMITIVES.size(); i++) {
251- DataType dataType = DATA_TYPE_PRIMITIVES.get(i);
252- String index = Character.toString((char) (startIndex + i));
253- Object sampleData = PrimitiveTypeSamples.ALL.get(dataType);
200+ // create keyspace
201+ session.execute("CREATE KEYSPACE testPrimitiveDatatypes " +
202+ "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
203+ session.execute("USE testPrimitiveDatatypes");
204+
205+ // create UDT
206+ List<String> alpha_type_list = new ArrayList<String>();
207+ int startIndex = (int) 'a';
208+ for (int i = 0; i < DATA_TYPE_PRIMITIVES.size(); i++) {
209+ alpha_type_list.add(String.format("%s %s", Character.toString((char) (startIndex + i)),
210+ DATA_TYPE_PRIMITIVES.get(i).getName()));
211+ }
254212
255- switch (dataType.getName()) {
256- case ASCII:
257- alldatatypes.setString(index, (String) sampleData);
258- break;
259- case BIGINT:
260- alldatatypes.setLong(index, ((Long) sampleData).longValue());
261- break;
262- case BLOB:
263- alldatatypes.setBytes(index, (ByteBuffer) sampleData);
264- break;
265- case BOOLEAN:
266- alldatatypes.setBool(index, ((Boolean) sampleData).booleanValue());
267- break;
268- case DECIMAL:
269- alldatatypes.setDecimal(index, (BigDecimal) sampleData);
270- break;
271- case DOUBLE:
272- alldatatypes.setDouble(index, ((Double) sampleData).doubleValue());
273- break;
274- case FLOAT:
275- alldatatypes.setFloat(index, ((Float) sampleData).floatValue());
276- break;
277- case INET:
278- alldatatypes.setInet(index, (InetAddress) sampleData);
279- break;
280- case TINYINT:
281- alldatatypes.setByte(index, (Byte) sampleData);
282- break;
283- case SMALLINT:
284- alldatatypes.setShort(index, (Short) sampleData);
285- break;
286- case INT:
287- alldatatypes.setInt(index, ((Integer) sampleData).intValue());
288- break;
289- case TEXT:
290- alldatatypes.setString(index, (String) sampleData);
291- break;
292- case TIMESTAMP:
293- alldatatypes.setTimestamp(index, ((Date) sampleData));
294- break;
295- case DATE:
296- alldatatypes.setDate(index, ((LocalDate) sampleData));
297- break;
298- case TIME:
299- alldatatypes.setTime(index, ((Long) sampleData));
300- break;
301- case TIMEUUID:
302- alldatatypes.setUUID(index, (UUID) sampleData);
303- break;
304- case UUID:
305- alldatatypes.setUUID(index, (UUID) sampleData);
306- break;
307- case VARCHAR:
308- alldatatypes.setString(index, (String) sampleData);
309- break;
310- case VARINT:
311- alldatatypes.setVarint(index, (BigInteger) sampleData);
312- break;
313- }
213+ session.execute(String.format("CREATE TYPE alldatatypes (%s)", Joiner.on(',').join(alpha_type_list)));
214+ session.execute("CREATE TABLE mytable (a int PRIMARY KEY, b frozen<alldatatypes>)");
215+
216+ // insert UDT data
217+ UserType alldatatypesDef = cluster.getMetadata().getKeyspace("testPrimitiveDatatypes").getUserType("alldatatypes");
218+ UDTValue alldatatypes = alldatatypesDef.newValue();
219+
220+ for (int i = 0; i < DATA_TYPE_PRIMITIVES.size(); i++) {
221+ DataType dataType = DATA_TYPE_PRIMITIVES.get(i);
222+ String index = Character.toString((char) (startIndex + i));
223+ Object sampleData = PrimitiveTypeSamples.ALL.get(dataType);
224+
225+ switch (dataType.getName()) {
226+ case ASCII:
227+ alldatatypes.setString(index, (String) sampleData);
228+ break;
229+ case BIGINT:
230+ alldatatypes.setLong(index, ((Long) sampleData).longValue());
231+ break;
232+ case BLOB:
233+ alldatatypes.setBytes(index, (ByteBuffer) sampleData);
234+ break;
235+ case BOOLEAN:
236+ alldatatypes.setBool(index, ((Boolean) sampleData).booleanValue());
237+ break;
238+ case DECIMAL:
239+ alldatatypes.setDecimal(index, (BigDecimal) sampleData);
240+ break;
241+ case DOUBLE:
242+ alldatatypes.setDouble(index, ((Double) sampleData).doubleValue());
243+ break;
244+ case FLOAT:
245+ alldatatypes.setFloat(index, ((Float) sampleData).floatValue());
246+ break;
247+ case INET:
248+ alldatatypes.setInet(index, (InetAddress) sampleData);
249+ break;
250+ case TINYINT:
251+ alldatatypes.setByte(index, (Byte) sampleData);
252+ break;
253+ case SMALLINT:
254+ alldatatypes.setShort(index, (Short) sampleData);
255+ break;
256+ case INT:
257+ alldatatypes.setInt(index, ((Integer) sampleData).intValue());
258+ break;
259+ case TEXT:
260+ alldatatypes.setString(index, (String) sampleData);
261+ break;
262+ case TIMESTAMP:
263+ alldatatypes.setTimestamp(index, ((Date) sampleData));
264+ break;
265+ case DATE:
266+ alldatatypes.setDate(index, ((LocalDate) sampleData));
267+ break;
268+ case TIME:
269+ alldatatypes.setTime(index, ((Long) sampleData));
270+ break;
271+ case TIMEUUID:
272+ alldatatypes.setUUID(index, (UUID) sampleData);
273+ break;
274+ case UUID:
275+ alldatatypes.setUUID(index, (UUID) sampleData);
276+ break;
277+ case VARCHAR:
278+ alldatatypes.setString(index, (String) sampleData);
279+ break;
280+ case VARINT:
281+ alldatatypes.setVarint(index, (BigInteger) sampleData);
282+ break;
314283 }
284+ }
315285
316- PreparedStatement ins = session.prepare("INSERT INTO mytable (a, b) VALUES (?, ?)");
317- session.execute(ins.bind(0, alldatatypes));
318-
319- // retrieve and verify data
320- ResultSet rs = session.execute("SELECT * FROM mytable");
321- List<Row> rows = rs.all();
322- assertEquals(1, rows.size());
286+ PreparedStatement ins = session.prepare("INSERT INTO mytable (a, b) VALUES (?, ?)");
287+ session.execute(ins.bind(0, alldatatypes));
323288
324- Row row = rows.get(0);
289+ // retrieve and verify data
290+ ResultSet rs = session.execute("SELECT * FROM mytable");
291+ List<Row> rows = rs.all();
292+ assertEquals(1, rows.size());
325293
326- assertEquals(row.getInt("a"), 0);
327- assertEquals(row.getUDTValue("b"), alldatatypes);
294+ Row row = rows.get(0);
328295
329- } catch (Exception e) {
330- errorOut();
331- throw e;
332- }
296+ assertEquals(row.getInt("a"), 0);
297+ assertEquals(row.getUDTValue("b"), alldatatypes);
333298 }
334299
335300 /**
@@ -340,83 +305,77 @@
340305 */
341306 @Test(groups = "short")
342307 public void testNonPrimitiveDatatypes() throws Exception {
343- try {
344- // create keyspace
345- session.execute("CREATE KEYSPACE test_nonprimitive_datatypes " +
346- "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
347- session.execute("USE test_nonprimitive_datatypes");
348-
349- // counters are not allowed inside collections
350- DATA_TYPE_PRIMITIVES.remove(DataType.counter());
351-
352- // create UDT
353- List<String> alpha_type_list = new ArrayList<String>();
354- int startIndex = (int) 'a';
355- for (int i = 0; i < DATA_TYPE_NON_PRIMITIVE_NAMES.size(); i++)
356- for (int j = 0; j < DATA_TYPE_PRIMITIVES.size(); j++) {
357- String typeString;
358- if (DATA_TYPE_NON_PRIMITIVE_NAMES.get(i) == DataType.Name.MAP) {
359- typeString = (String.format("%s_%s %s<%s, %s>", Character.toString((char) (startIndex + i)),
360- Character.toString((char) (startIndex + j)), DATA_TYPE_NON_PRIMITIVE_NAMES.get(i),
361- DATA_TYPE_PRIMITIVES.get(j).getName(), DATA_TYPE_PRIMITIVES.get(j).getName()));
362- } else if (DATA_TYPE_NON_PRIMITIVE_NAMES.get(i) == DataType.Name.TUPLE) {
363- typeString = (String.format("%s_%s frozen<%s<%s>>", Character.toString((char) (startIndex + i)),
364- Character.toString((char) (startIndex + j)), DATA_TYPE_NON_PRIMITIVE_NAMES.get(i),
365- DATA_TYPE_PRIMITIVES.get(j).getName()));
366- } else {
367- typeString = (String.format("%s_%s %s<%s>", Character.toString((char) (startIndex + i)),
368- Character.toString((char) (startIndex + j)), DATA_TYPE_NON_PRIMITIVE_NAMES.get(i),
369- DATA_TYPE_PRIMITIVES.get(j).getName()));
370- }
371- alpha_type_list.add(typeString);
372- }
308+ // create keyspace
309+ session.execute("CREATE KEYSPACE test_nonprimitive_datatypes " +
310+ "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
311+ session.execute("USE test_nonprimitive_datatypes");
312+
313+ // counters are not allowed inside collections
314+ DATA_TYPE_PRIMITIVES.remove(DataType.counter());
373315
374- session.execute(String.format("CREATE TYPE alldatatypes (%s)", Joiner.on(',').join(alpha_type_list)));
375- session.execute("CREATE TABLE mytable (a int PRIMARY KEY, b frozen<alldatatypes>)");
376-
377- // insert UDT data
378- UserType alldatatypesDef = cluster.getMetadata().getKeyspace("test_nonprimitive_datatypes").getUserType("alldatatypes");
379- UDTValue alldatatypes = alldatatypesDef.newValue();
380-
381- for (int i = 0; i < DATA_TYPE_NON_PRIMITIVE_NAMES.size(); i++)
382- for (int j = 0; j < DATA_TYPE_PRIMITIVES.size(); j++) {
383- DataType.Name name = DATA_TYPE_NON_PRIMITIVE_NAMES.get(i);
384- DataType dataType = DATA_TYPE_PRIMITIVES.get(j);
385-
386- String index = Character.toString((char) (startIndex + i)) + "_" + Character.toString((char) (startIndex + j));
387- Object sampleElement = PrimitiveTypeSamples.ALL.get(dataType);
388- switch (name) {
389- case LIST:
390- alldatatypes.setList(index, Lists.newArrayList(sampleElement));
391- break;
392- case SET:
393- alldatatypes.setSet(index, Sets.newHashSet(sampleElement));
394- break;
395- case MAP:
396- alldatatypes.setMap(index, ImmutableMap.of(sampleElement, sampleElement));
397- break;
398- case TUPLE:
399- alldatatypes.setTupleValue(index, cluster.getMetadata().newTupleType(dataType).newValue(sampleElement));
400- }
316+ // create UDT
317+ List<String> alpha_type_list = new ArrayList<String>();
318+ int startIndex = (int) 'a';
319+ for (int i = 0; i < DATA_TYPE_NON_PRIMITIVE_NAMES.size(); i++)
320+ for (int j = 0; j < DATA_TYPE_PRIMITIVES.size(); j++) {
321+ String typeString;
322+ if (DATA_TYPE_NON_PRIMITIVE_NAMES.get(i) == DataType.Name.MAP) {
323+ typeString = (String.format("%s_%s %s<%s, %s>", Character.toString((char) (startIndex + i)),
324+ Character.toString((char) (startIndex + j)), DATA_TYPE_NON_PRIMITIVE_NAMES.get(i),
325+ DATA_TYPE_PRIMITIVES.get(j).getName(), DATA_TYPE_PRIMITIVES.get(j).getName()));
326+ } else if (DATA_TYPE_NON_PRIMITIVE_NAMES.get(i) == DataType.Name.TUPLE) {
327+ typeString = (String.format("%s_%s frozen<%s<%s>>", Character.toString((char) (startIndex + i)),
328+ Character.toString((char) (startIndex + j)), DATA_TYPE_NON_PRIMITIVE_NAMES.get(i),
329+ DATA_TYPE_PRIMITIVES.get(j).getName()));
330+ } else {
331+ typeString = (String.format("%s_%s %s<%s>", Character.toString((char) (startIndex + i)),
332+ Character.toString((char) (startIndex + j)), DATA_TYPE_NON_PRIMITIVE_NAMES.get(i),
333+ DATA_TYPE_PRIMITIVES.get(j).getName()));
401334 }
335+ alpha_type_list.add(typeString);
336+ }
337+
338+ session.execute(String.format("CREATE TYPE alldatatypes (%s)", Joiner.on(',').join(alpha_type_list)));
339+ session.execute("CREATE TABLE mytable (a int PRIMARY KEY, b frozen<alldatatypes>)");
340+
341+ // insert UDT data
342+ UserType alldatatypesDef = cluster.getMetadata().getKeyspace("test_nonprimitive_datatypes").getUserType("alldatatypes");
343+ UDTValue alldatatypes = alldatatypesDef.newValue();
344+
345+ for (int i = 0; i < DATA_TYPE_NON_PRIMITIVE_NAMES.size(); i++)
346+ for (int j = 0; j < DATA_TYPE_PRIMITIVES.size(); j++) {
347+ DataType.Name name = DATA_TYPE_NON_PRIMITIVE_NAMES.get(i);
348+ DataType dataType = DATA_TYPE_PRIMITIVES.get(j);
402349
403- PreparedStatement ins = session.prepare("INSERT INTO mytable (a, b) VALUES (?, ?)");
404- session.execute(ins.bind(0, alldatatypes));
350+ String index = Character.toString((char) (startIndex + i)) + "_" + Character.toString((char) (startIndex + j));
351+ Object sampleElement = PrimitiveTypeSamples.ALL.get(dataType);
352+ switch (name) {
353+ case LIST:
354+ alldatatypes.setList(index, Lists.newArrayList(sampleElement));
355+ break;
356+ case SET:
357+ alldatatypes.setSet(index, Sets.newHashSet(sampleElement));
358+ break;
359+ case MAP:
360+ alldatatypes.setMap(index, ImmutableMap.of(sampleElement, sampleElement));
361+ break;
362+ case TUPLE:
363+ alldatatypes.setTupleValue(index, cluster.getMetadata().newTupleType(dataType).newValue(sampleElement));
364+ }
365+ }
405366
406- // retrieve and verify data
407- ResultSet rs = session.execute("SELECT * FROM mytable");
408- List<Row> rows = rs.all();
409- assertEquals(1, rows.size());
367+ PreparedStatement ins = session.prepare("INSERT INTO mytable (a, b) VALUES (?, ?)");
368+ session.execute(ins.bind(0, alldatatypes));
410369
411- Row row = rows.get(0);
370+ // retrieve and verify data
371+ ResultSet rs = session.execute("SELECT * FROM mytable");
372+ List<Row> rows = rs.all();
373+ assertEquals(1, rows.size());
412374
413- assertEquals(row.getInt("a"), 0);
414- assertEquals(row.getUDTValue("b"), alldatatypes);
375+ Row row = rows.get(0);
415376
416- } catch (Exception e) {
417- errorOut();
418- throw e;
419- }
377+ assertEquals(row.getInt("a"), 0);
378+ assertEquals(row.getUDTValue("b"), alldatatypes);
420379 }
421380
422381 /**
@@ -428,60 +387,53 @@
428387 @Test(groups = "short")
429388 public void udtNestedTest() throws Exception {
430389 final int MAX_NESTING_DEPTH = 4;
390+ // create keyspace
391+ session.execute("CREATE KEYSPACE udtNestedTest " +
392+ "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
393+ session.execute("USE udtNestedTest");
394+
395+ // create UDT
396+ session.execute("CREATE TYPE depth_0 (age int, name text)");
397+
398+ for (int i = 1; i <= MAX_NESTING_DEPTH; i++) {
399+ session.execute(String.format("CREATE TYPE depth_%s (value frozen<depth_%s>)", String.valueOf(i), String.valueOf(i - 1)));
400+ }
431401
432- try {
433- // create keyspace
434- session.execute("CREATE KEYSPACE udtNestedTest " +
435- "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
436- session.execute("USE udtNestedTest");
437-
438- // create UDT
439- session.execute("CREATE TYPE depth_0 (age int, name text)");
440-
441- for (int i = 1; i <= MAX_NESTING_DEPTH; i++) {
442- session.execute(String.format("CREATE TYPE depth_%s (value frozen<depth_%s>)", String.valueOf(i), String.valueOf(i - 1)));
443- }
444-
445- session.execute(String.format("CREATE TABLE mytable (a int PRIMARY KEY, b frozen<depth_0>, c frozen<depth_1>, d frozen<depth_2>, e frozen<depth_3>," +
446- "f frozen<depth_%s>)", MAX_NESTING_DEPTH));
447-
448- // insert UDT data
449- UserType depthZeroDef = cluster.getMetadata().getKeyspace("udtNestedTest").getUserType("depth_0");
450- UDTValue depthZero = depthZeroDef.newValue().setInt("age", 42).setString("name", "Bob");
402+ session.execute(String.format("CREATE TABLE mytable (a int PRIMARY KEY, b frozen<depth_0>, c frozen<depth_1>, d frozen<depth_2>, e frozen<depth_3>," +
403+ "f frozen<depth_%s>)", MAX_NESTING_DEPTH));
451404
452- UserType depthOneDef = cluster.getMetadata().getKeyspace("udtNestedTest").getUserType("depth_1");
453- UDTValue depthOne = depthOneDef.newValue().setUDTValue("value", depthZero);
405+ // insert UDT data
406+ UserType depthZeroDef = cluster.getMetadata().getKeyspace("udtNestedTest").getUserType("depth_0");
407+ UDTValue depthZero = depthZeroDef.newValue().setInt("age", 42).setString("name", "Bob");
454408
455- UserType depthTwoDef = cluster.getMetadata().getKeyspace("udtNestedTest").getUserType("depth_2");
456- UDTValue depthTwo = depthTwoDef.newValue().setUDTValue("value", depthOne);
409+ UserType depthOneDef = cluster.getMetadata().getKeyspace("udtNestedTest").getUserType("depth_1");
410+ UDTValue depthOne = depthOneDef.newValue().setUDTValue("value", depthZero);
457411
458- UserType depthThreeDef = cluster.getMetadata().getKeyspace("udtNestedTest").getUserType("depth_3");
459- UDTValue depthThree = depthThreeDef.newValue().setUDTValue("value", depthTwo);
412+ UserType depthTwoDef = cluster.getMetadata().getKeyspace("udtNestedTest").getUserType("depth_2");
413+ UDTValue depthTwo = depthTwoDef.newValue().setUDTValue("value", depthOne);
460414
461- UserType depthFourDef = cluster.getMetadata().getKeyspace("udtNestedTest").getUserType("depth_4");
462- UDTValue depthFour = depthFourDef.newValue().setUDTValue("value", depthThree);
415+ UserType depthThreeDef = cluster.getMetadata().getKeyspace("udtNestedTest").getUserType("depth_3");
416+ UDTValue depthThree = depthThreeDef.newValue().setUDTValue("value", depthTwo);
463417
464- PreparedStatement ins = session.prepare("INSERT INTO mytable (a, b, c, d, e, f) VALUES (?, ?, ?, ?, ?, ?)");
465- session.execute(ins.bind(0, depthZero, depthOne, depthTwo, depthThree, depthFour));
418+ UserType depthFourDef = cluster.getMetadata().getKeyspace("udtNestedTest").getUserType("depth_4");
419+ UDTValue depthFour = depthFourDef.newValue().setUDTValue("value", depthThree);
466420
467- // retrieve and verify data
468- ResultSet rs = session.execute("SELECT * FROM mytable");
469- List<Row> rows = rs.all();
470- assertEquals(1, rows.size());
421+ PreparedStatement ins = session.prepare("INSERT INTO mytable (a, b, c, d, e, f) VALUES (?, ?, ?, ?, ?, ?)");
422+ session.execute(ins.bind(0, depthZero, depthOne, depthTwo, depthThree, depthFour));
471423
472- Row row = rows.get(0);
424+ // retrieve and verify data
425+ ResultSet rs = session.execute("SELECT * FROM mytable");
426+ List<Row> rows = rs.all();
427+ assertEquals(1, rows.size());
473428
474- assertEquals(row.getInt("a"), 0);
475- assertEquals(row.getUDTValue("b"), depthZero);
476- assertEquals(row.getUDTValue("c"), depthOne);
477- assertEquals(row.getUDTValue("d"), depthTwo);
478- assertEquals(row.getUDTValue("e"), depthThree);
479- assertEquals(row.getUDTValue("f"), depthFour);
429+ Row row = rows.get(0);
480430
481- } catch (Exception e) {
482- errorOut();
483- throw e;
484- }
431+ assertEquals(row.getInt("a"), 0);
432+ assertEquals(row.getUDTValue("b"), depthZero);
433+ assertEquals(row.getUDTValue("c"), depthOne);
434+ assertEquals(row.getUDTValue("d"), depthTwo);
435+ assertEquals(row.getUDTValue("e"), depthThree);
436+ assertEquals(row.getUDTValue("f"), depthFour);
485437 }
486438
487439 /**
@@ -492,51 +444,45 @@
492444 */
493445 @Test(groups = "short")
494446 public void testUdtsWithNulls() throws Exception {
495- try {
496- // create keyspace
497- session.execute("CREATE KEYSPACE testUdtsWithNulls " +
498- "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
499- session.execute("USE testUdtsWithNulls");
500-
501- // create UDT
502- session.execute("CREATE TYPE user (a text, b int, c uuid, d blob)");
503- session.execute("CREATE TABLE mytable (a int PRIMARY KEY, b frozen<user>)");
447+ // create keyspace
448+ session.execute("CREATE KEYSPACE testUdtsWithNulls " +
449+ "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
450+ session.execute("USE testUdtsWithNulls");
504451
505- // insert UDT data
506- UserType userTypeDef = cluster.getMetadata().getKeyspace("testUdtsWithNulls").getUserType("user");
507- UDTValue userType = userTypeDef.newValue().setString("a", null).setInt("b", 0).setUUID("c", null).setBytes("d", null);
452+ // create UDT
453+ session.execute("CREATE TYPE user (a text, b int, c uuid, d blob)");
454+ session.execute("CREATE TABLE mytable (a int PRIMARY KEY, b frozen<user>)");
508455
509- PreparedStatement ins = session.prepare("INSERT INTO mytable (a, b) VALUES (?, ?)");
510- session.execute(ins.bind(0, userType));
456+ // insert UDT data
457+ UserType userTypeDef = cluster.getMetadata().getKeyspace("testUdtsWithNulls").getUserType("user");
458+ UDTValue userType = userTypeDef.newValue().setString("a", null).setInt("b", 0).setUUID("c", null).setBytes("d", null);
511459
512- // retrieve and verify data
513- ResultSet rs = session.execute("SELECT * FROM mytable");
514- List<Row> rows = rs.all();
515- assertEquals(1, rows.size());
460+ PreparedStatement ins = session.prepare("INSERT INTO mytable (a, b) VALUES (?, ?)");
461+ session.execute(ins.bind(0, userType));
516462
517- Row row = rows.get(0);
463+ // retrieve and verify data
464+ ResultSet rs = session.execute("SELECT * FROM mytable");
465+ List<Row> rows = rs.all();
466+ assertEquals(1, rows.size());
518467
519- assertEquals(row.getInt("a"), 0);
520- assertEquals(row.getUDTValue("b"), userType);
468+ Row row = rows.get(0);
521469
522- // test empty strings
523- userType = userTypeDef.newValue().setString("a", "").setInt("b", 0).setUUID("c", null).setBytes("d", ByteBuffer.allocate(0));
524- session.execute(ins.bind(0, userType));
470+ assertEquals(row.getInt("a"), 0);
471+ assertEquals(row.getUDTValue("b"), userType);
525472
526- // retrieve and verify data
527- rs = session.execute("SELECT * FROM mytable");
528- rows = rs.all();
529- assertEquals(1, rows.size());
473+ // test empty strings
474+ userType = userTypeDef.newValue().setString("a", "").setInt("b", 0).setUUID("c", null).setBytes("d", ByteBuffer.allocate(0));
475+ session.execute(ins.bind(0, userType));
530476
531- row = rows.get(0);
477+ // retrieve and verify data
478+ rs = session.execute("SELECT * FROM mytable");
479+ rows = rs.all();
480+ assertEquals(1, rows.size());
532481
533- assertEquals(row.getInt("a"), 0);
534- assertEquals(row.getUDTValue("b"), userType);
482+ row = rows.get(0);
535483
536- } catch (Exception e) {
537- errorOut();
538- throw e;
539- }
484+ assertEquals(row.getInt("a"), 0);
485+ assertEquals(row.getUDTValue("b"), userType);
540486 }
541487
542488 /**
@@ -546,52 +492,46 @@
546492 */
547493 @Test(groups = "short")
548494 public void testUdtsWithCollectionNulls() throws Exception {
549- try {
550- // create keyspace
551- session.execute("CREATE KEYSPACE testUdtsWithCollectionNulls " +
552- "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
553- session.execute("USE testUdtsWithCollectionNulls");
554-
555- // create UDT
556- session.execute("CREATE TYPE user (a List<text>, b Set<text>, c Map<text, text>, d frozen<Tuple<text>>)");
557- session.execute("CREATE TABLE mytable (a int PRIMARY KEY, b frozen<user>)");
558-
559- // insert null UDT data
560- PreparedStatement ins = session.prepare("INSERT INTO mytable (a, b) " +
561- "VALUES (0, { a: ?, b: ?, c: ?, d: ? })");
562- session.execute(ins.bind().setList(0, null).setSet(1, null).setMap(2, null).setTupleValue(3, null));
563-
564- // retrieve and verify data
565- ResultSet rs = session.execute("SELECT * FROM mytable");
566- List<Row> rows = rs.all();
567- assertEquals(1, rows.size());
568-
569- Row row = rows.get(0);
570- assertEquals(row.getInt("a"), 0);
571-
572- UserType userTypeDef = cluster.getMetadata().getKeyspace("testUdtsWithCollectionNulls").getUserType("user");
573- UDTValue userType = userTypeDef.newValue().setList("a", null).setSet("b", null).setMap("c", null).setTupleValue("d", null);
574- assertEquals(row.getUDTValue("b"), userType);
575-
576- // test missing UDT args
577- ins = session.prepare("INSERT INTO mytable (a, b) " +
578- "VALUES (1, { a: ? })");
579- session.execute(ins.bind().setList(0, new ArrayList<Object>()));
580-
581- // retrieve and verify data
582- rs = session.execute("SELECT * FROM mytable");
583- rows = rs.all();
584- assertEquals(2, rows.size());
585-
586- row = rows.get(0);
587- assertEquals(row.getInt("a"), 1);
588-
589- userType = userTypeDef.newValue().setList(0, new ArrayList<Object>());
590- assertEquals(row.getUDTValue("b"), userType);
591-
592- } catch (Exception e) {
593- errorOut();
594- throw e;
595- }
495+ // create keyspace
496+ session.execute("CREATE KEYSPACE testUdtsWithCollectionNulls " +
497+ "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
498+ session.execute("USE testUdtsWithCollectionNulls");
499+
500+ // create UDT
501+ session.execute("CREATE TYPE user (a List<text>, b Set<text>, c Map<text, text>, d frozen<Tuple<text>>)");
502+ session.execute("CREATE TABLE mytable (a int PRIMARY KEY, b frozen<user>)");
503+
504+ // insert null UDT data
505+ PreparedStatement ins = session.prepare("INSERT INTO mytable (a, b) " +
506+ "VALUES (0, { a: ?, b: ?, c: ?, d: ? })");
507+ session.execute(ins.bind().setList(0, null).setSet(1, null).setMap(2, null).setTupleValue(3, null));
508+
509+ // retrieve and verify data
510+ ResultSet rs = session.execute("SELECT * FROM mytable");
511+ List<Row> rows = rs.all();
512+ assertEquals(1, rows.size());
513+
514+ Row row = rows.get(0);
515+ assertEquals(row.getInt("a"), 0);
516+
517+ UserType userTypeDef = cluster.getMetadata().getKeyspace("testUdtsWithCollectionNulls").getUserType("user");
518+ UDTValue userType = userTypeDef.newValue().setList("a", null).setSet("b", null).setMap("c", null).setTupleValue("d", null);
519+ assertEquals(row.getUDTValue("b"), userType);
520+
521+ // test missing UDT args
522+ ins = session.prepare("INSERT INTO mytable (a, b) " +
523+ "VALUES (1, { a: ? })");
524+ session.execute(ins.bind().setList(0, new ArrayList<Object>()));
525+
526+ // retrieve and verify data
527+ rs = session.execute("SELECT * FROM mytable");
528+ rows = rs.all();
529+ assertEquals(2, rows.size());
530+
531+ row = rows.get(0);
532+ assertEquals(row.getInt("a"), 1);
533+
534+ userType = userTypeDef.newValue().setList(0, new ArrayList<Object>());
535+ assertEquals(row.getUDTValue("b"), userType);
596536 }
597537 }
modified driver-core/src/test/java/com/datastax/driver/core/WarningsTest.java +2 −2
@@ -25,7 +25,7 @@
2525
2626 import static org.assertj.core.api.Assertions.assertThat;
2727
28-public class WarningsTest extends CCMBridge.PerClassSingleNodeCluster {
28+public class WarningsTest extends CCMTestsSupport {
2929
3030 /**
3131 * This is Cassandra's default value, found in o.a.c.config.Config
@@ -33,7 +33,7 @@
3333 private static final int BATCH_SIZE_WARN_THRESHOLD_IN_BYTES = 5 * 1024;
3434
3535 @Override
36- protected Collection<String> getTableDefinitions() {
36+ public Collection<String> createTestFixtures() {
3737 return Lists.newArrayList(
3838 "CREATE TABLE foo(k int primary key, v text)"
3939 );
modified driver-core/src/test/java/com/datastax/driver/core/exceptions/ExceptionsScassandraTest.java +4 −3
@@ -48,7 +48,8 @@
4848 @BeforeMethod(groups = "short")
4949 public void beforeMethod() {
5050 cluster = Cluster.builder()
51- .addContactPoint(CCMBridge.ipOfNode(1))
51+ .addContactPointsWithPorts(scassandras.address(1))
52+ .withAddressTranslator(scassandras.addressTranslator())
5253 .withRetryPolicy(FallthroughRetryPolicy.INSTANCE)
5354 .build();
5455 session = cluster.connect();
@@ -129,7 +130,7 @@
129130 return session.execute("mock query");
130131 }
131132
132- @AfterMethod(groups = "short")
133+ @AfterMethod(groups = "short", alwaysRun = true)
133134 public void afterMethod() {
134135 for (Scassandra node : scassandras.nodes()) {
135136 node.primingClient().clearAllPrimes();
@@ -138,7 +139,7 @@
138139 cluster.close();
139140 }
140141
141- @AfterClass(groups = "short")
142+ @AfterClass(groups = "short", alwaysRun = true)
142143 public void afterClass() {
143144 if (scassandras != null)
144145 scassandras.stop();
modified driver-core/src/test/java/com/datastax/driver/core/exceptions/ExceptionsTest.java +40 −50
@@ -15,16 +15,14 @@
1515 */
1616 package com.datastax.driver.core.exceptions;
1717
18-import com.datastax.driver.core.CCMBridge;
18+import com.datastax.driver.core.CCMTestsSupport;
1919 import com.datastax.driver.core.Cluster;
2020 import com.datastax.driver.core.TestUtils;
2121 import com.datastax.driver.core.WriteType;
2222 import org.testng.annotations.Test;
2323
24-import java.net.InetAddress;
2524 import java.net.InetSocketAddress;
2625
27-import static com.datastax.driver.core.CCMBridge.ipOfNode;
2826 import static com.datastax.driver.core.ConsistencyLevel.LOCAL_QUORUM;
2927 import static org.assertj.core.api.Assertions.assertThat;
3028 import static org.testng.Assert.assertEquals;
@@ -33,7 +31,7 @@
3331 /**
3432 * Tests Exception classes with separate clusters per test, when applicable
3533 */
36-public class ExceptionsTest {
34+public class ExceptionsTest extends CCMTestsSupport {
3735
3836 private InetSocketAddress address1 = new InetSocketAddress("127.0.0.1", 9042);
3937 private InetSocketAddress address2 = new InetSocketAddress("127.0.0.2", 9042);
@@ -45,53 +43,45 @@
4543 */
4644 @Test(groups = "short")
4745 public void alreadyExistsException() throws Throwable {
48- Cluster.Builder builder = Cluster.builder();
49- CCMBridge.CCMCluster c = CCMBridge.buildCluster(1, builder);
46+ String keyspace = "TestKeyspace";
47+ String table = "TestTable";
48+
49+ String[] cqlCommands = new String[]{
50+ String.format(TestUtils.CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, 1),
51+ "USE " + keyspace,
52+ String.format("CREATE TABLE %s (k text PRIMARY KEY, t text, i int, f float)", table)
53+ };
54+
55+ // Create the schema once
56+ session.execute(cqlCommands[0]);
57+ session.execute(cqlCommands[1]);
58+ session.execute(cqlCommands[2]);
59+
60+ // Try creating the keyspace again
5061 try {
51- String keyspace = "TestKeyspace";
52- String table = "TestTable";
53-
54- String[] cqlCommands = new String[]{
55- String.format(TestUtils.CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, 1),
56- "USE " + keyspace,
57- String.format("CREATE TABLE %s (k text PRIMARY KEY, t text, i int, f float)", table)
58- };
59-
60- // Create the schema once
61- c.session.execute(cqlCommands[0]);
62- c.session.execute(cqlCommands[1]);
63- c.session.execute(cqlCommands[2]);
64-
65- // Try creating the keyspace again
66- try {
67- c.session.execute(cqlCommands[0]);
68- } catch (AlreadyExistsException e) {
69- String expected = String.format("Keyspace %s already exists", keyspace.toLowerCase());
70- assertEquals(e.getMessage(), expected);
71- assertEquals(e.getKeyspace(), keyspace.toLowerCase());
72- assertEquals(e.getTable(), null);
73- assertEquals(e.wasTableCreation(), false);
74- assertEquals(e.getHost(), InetAddress.getByName(ipOfNode(1)));
75- assertEquals(e.getAddress(), new InetSocketAddress(ipOfNode(1), 9042));
76- }
77-
78- c.session.execute(cqlCommands[1]);
79-
80- // Try creating the table again
81- try {
82- c.session.execute(cqlCommands[2]);
83- } catch (AlreadyExistsException e) {
84- // is released
85- assertEquals(e.getKeyspace(), keyspace.toLowerCase());
86- assertEquals(e.getTable(), table.toLowerCase());
87- assertEquals(e.wasTableCreation(), true);
88- assertEquals(e.getHost(), InetAddress.getByName(ipOfNode(1)));
89- assertEquals(e.getAddress(), new InetSocketAddress(ipOfNode(1), 9042));
90- }
91- } catch (Throwable e) {
92- throw e;
93- } finally {
94- c.discard();
62+ session.execute(cqlCommands[0]);
63+ } catch (AlreadyExistsException e) {
64+ String expected = String.format("Keyspace %s already exists", keyspace.toLowerCase());
65+ assertEquals(e.getMessage(), expected);
66+ assertEquals(e.getKeyspace(), keyspace.toLowerCase());
67+ assertEquals(e.getTable(), null);
68+ assertEquals(e.wasTableCreation(), false);
69+ assertEquals(e.getHost(), getHostAddress(1).getAddress());
70+ assertEquals(e.getAddress(), getHostAddress(1));
71+ }
72+
73+ session.execute(cqlCommands[1]);
74+
75+ // Try creating the table again
76+ try {
77+ session.execute(cqlCommands[2]);
78+ } catch (AlreadyExistsException e) {
79+ // is released
80+ assertEquals(e.getKeyspace(), keyspace.toLowerCase());
81+ assertEquals(e.getTable(), table.toLowerCase());
82+ assertEquals(e.wasTableCreation(), true);
83+ assertEquals(e.getHost(), getHostAddress(1).getAddress());
84+ assertEquals(e.getAddress(), getHostAddress(1));
9585 }
9686 }
9787
modified driver-core/src/test/java/com/datastax/driver/core/exceptions/FunctionExecutionExceptionTest.java +3 −3
@@ -15,7 +15,7 @@
1515 */
1616 package com.datastax.driver.core.exceptions;
1717
18-import com.datastax.driver.core.CCMBridge;
18+import com.datastax.driver.core.CCMTestsSupport;
1919 import com.datastax.driver.core.utils.CassandraVersion;
2020 import com.google.common.collect.Lists;
2121 import org.testng.annotations.Test;
@@ -23,10 +23,10 @@
2323 import java.util.Collection;
2424
2525 @CassandraVersion(major = 2.2)
26-public class FunctionExecutionExceptionTest extends CCMBridge.PerClassSingleNodeCluster {
26+public class FunctionExecutionExceptionTest extends CCMTestsSupport {
2727
2828 @Override
29- protected Collection<String> getTableDefinitions() {
29+ public Collection<String> createTestFixtures() {
3030 return Lists.newArrayList(
3131 "CREATE TABLE foo (k int primary key, i int, l list<int>)",
3232 "INSERT INTO foo (k, i, l) VALUES (1, 1, [1])",
modified driver-core/src/test/java/com/datastax/driver/core/policies/AbstractRetryPolicyIntegrationTest.java +4 −3
@@ -77,10 +77,11 @@
7777 scassandras.init();
7878
7979 cluster = Cluster.builder()
80- .addContactPoint(CCMBridge.ipOfNode(1))
80+ .addContactPointsWithPorts(scassandras.address(1))
81+ .withAddressTranslator(scassandras.addressTranslator())
8182 .withRetryPolicy(retryPolicy)
8283 .withLoadBalancingPolicy(new SortingLoadBalancingPolicy())
83- // Scassandra does not support V3 nor V4 yet, and V4 may cause the server to crash
84+ // Scassandra does not support V3 nor V4 yet, and V4 may cause the server to crash
8485 .withProtocolVersion(ProtocolVersion.V2)
8586 .withPoolingOptions(new PoolingOptions()
8687 .setCoreConnectionsPerHost(HostDistance.LOCAL, 1)
@@ -163,7 +164,7 @@
163164 assertThat(scassandras.node(hostNumber).activityClient().retrieveQueries()).hasSize(times);
164165 }
165166
166- @AfterMethod(groups = "short")
167+ @AfterMethod(groups = "short", alwaysRun = true)
167168 public void afterMethod() {
168169 if (cluster != null)
169170 cluster.close();
modified driver-core/src/test/java/com/datastax/driver/core/policies/CloseableLoadBalancingPolicyTest.java +17 −15
@@ -15,32 +15,34 @@
1515 */
1616 package com.datastax.driver.core.policies;
1717
18-import com.datastax.driver.core.CCMBridge;
18+import com.datastax.driver.core.CCMConfig;
19+import com.datastax.driver.core.CCMTestsSupport;
1920 import com.datastax.driver.core.Cluster;
2021 import org.testng.annotations.Test;
2122
2223 import static org.assertj.core.api.Assertions.assertThat;
2324
24-public class CloseableLoadBalancingPolicyTest {
25+@CCMConfig(createSession = false)
26+public class CloseableLoadBalancingPolicyTest extends CCMTestsSupport {
27+
28+ private CloseMonitoringPolicy policy;
29+
2530 @Test(groups = "short")
2631 public void should_be_invoked_at_shutdown() {
27- CloseMonitoringPolicy policy = new CloseMonitoringPolicy(Policies.defaultLoadBalancingPolicy());
28- CCMBridge ccm = null;
29- Cluster cluster = null;
3032 try {
31- ccm = CCMBridge.builder("test").withNodes(1).build();
32- cluster = Cluster.builder()
33- .addContactPoint(CCMBridge.ipOfNode(1))
34- .withLoadBalancingPolicy(policy)
35- .build();
3633 cluster.connect();
34+ cluster.close();
3735 } finally {
38- if (cluster != null)
39- cluster.close();
40- if (ccm != null)
41- ccm.remove();
36+ assertThat(policy.wasClosed).isTrue();
4237 }
43- assertThat(policy.wasClosed).isTrue();
38+ }
39+
40+ @Override
41+ public Cluster.Builder createClusterBuilder() {
42+ policy = new CloseMonitoringPolicy(Policies.defaultLoadBalancingPolicy());
43+ return Cluster.builder()
44+ .addContactPointsWithPorts(getHostAddress(1))
45+ .withLoadBalancingPolicy(policy);
4446 }
4547
4648 static class CloseMonitoringPolicy extends DelegatingLoadBalancingPolicy {
modified driver-core/src/test/java/com/datastax/driver/core/policies/DCAwareRoundRobinPolicyTest.java +26 −13
@@ -41,6 +41,7 @@
4141 public class DCAwareRoundRobinPolicyTest {
4242
4343 Logger policyLogger = Logger.getLogger(DCAwareRoundRobinPolicy.class);
44+ Level originalLevel;
4445 MemoryAppender logs;
4546 QueryTracker queryTracker;
4647
@@ -50,15 +51,16 @@
5051 @BeforeMethod(groups = "short")
5152 public void setUp() {
5253 initMocks(this);
54+ originalLevel = policyLogger.getLevel();
5355 policyLogger.setLevel(Level.WARN);
5456 logs = new MemoryAppender();
5557 policyLogger.addAppender(logs);
5658 queryTracker = new QueryTracker();
5759 }
5860
59- @AfterMethod(groups = "short")
61+ @AfterMethod(groups = "short", alwaysRun = true)
6062 public void tearDown() {
61- policyLogger.setLevel(null);
63+ policyLogger.setLevel(originalLevel);
6264 policyLogger.removeAppender(logs);
6365 }
6466
@@ -79,7 +81,8 @@
7981 // given: a 10 node 2 DC cluster.
8082 ScassandraCluster sCluster = ScassandraCluster.builder().withNodes(5, 5).build();
8183 Cluster cluster = builder()
82- .addContactPoint(sCluster.address(1, 1))
84+ .addContactPointsWithPorts(sCluster.address(1, 1))
85+ .withAddressTranslator(sCluster.addressTranslator())
8386 .withLoadBalancingPolicy(DCAwareRoundRobinPolicy.builder().withLocalDc(datacenter(1)).build())
8487 .build();
8588 try {
@@ -111,7 +114,8 @@
111114 // given: a 10 node 2 DC cluster with DC policy with 2 remote hosts.
112115 ScassandraCluster sCluster = ScassandraCluster.builder().withNodes(5, 5).build();
113116 Cluster cluster = builder()
114- .addContactPoint(sCluster.address(1, 1))
117+ .addContactPointsWithPorts(sCluster.address(1, 1))
118+ .withAddressTranslator(sCluster.addressTranslator())
115119 .withLoadBalancingPolicy(DCAwareRoundRobinPolicy.builder().withLocalDc(datacenter(1)).withUsedHostsPerRemoteDc(2).build())
116120 .build();
117121
@@ -153,7 +157,8 @@
153157 // given: a 10 node 2 DC cluster with DC policy with 2 remote hosts.
154158 ScassandraCluster sCluster = ScassandraCluster.builder().withNodes(5, 5).build();
155159 Cluster cluster = builder()
156- .addContactPoint(sCluster.address(1, 1))
160+ .addContactPointsWithPorts(sCluster.address(1, 1))
161+ .withAddressTranslator(sCluster.addressTranslator())
157162 .withLoadBalancingPolicy(DCAwareRoundRobinPolicy.builder().withUsedHostsPerRemoteDc(2).build())
158163 .build();
159164
@@ -196,7 +201,8 @@
196201 // a local consistency level.
197202 ScassandraCluster sCluster = ScassandraCluster.builder().withNodes(2, 2).build();
198203 Cluster cluster = builder()
199- .addContactPoint(sCluster.address(1, 1))
204+ .addContactPointsWithPorts(sCluster.address(1, 1))
205+ .withAddressTranslator(sCluster.addressTranslator())
200206 .withLoadBalancingPolicy(DCAwareRoundRobinPolicy.builder().withUsedHostsPerRemoteDc(2).build())
201207 .build();
202208
@@ -241,7 +247,8 @@
241247 // a local consistency level.
242248 ScassandraCluster sCluster = ScassandraCluster.builder().withNodes(2, 2).build();
243249 Cluster cluster = builder()
244- .addContactPoint(sCluster.address(1, 1))
250+ .addContactPointsWithPorts(sCluster.address(1, 1))
251+ .withAddressTranslator(sCluster.addressTranslator())
245252 .withLoadBalancingPolicy(DCAwareRoundRobinPolicy.builder()
246253 .allowRemoteDCsForLocalConsistencyLevel()
247254 .withUsedHostsPerRemoteDc(2).build())
@@ -286,7 +293,8 @@
286293 DCAwareRoundRobinPolicy.builder().withUsedHostsPerRemoteDc(2).build(),
287294 Lists.newArrayList(datacenter(2)));
288295 Cluster cluster = builder()
289- .addContactPoint(sCluster.address(1, 1))
296+ .addContactPointsWithPorts(sCluster.address(1, 1))
297+ .withAddressTranslator(sCluster.addressTranslator())
290298 .withLoadBalancingPolicy(loadBalancingPolicy)
291299 .build();
292300
@@ -339,7 +347,8 @@
339347 DCAwareRoundRobinPolicy.builder().withUsedHostsPerRemoteDc(2).build(),
340348 Lists.newArrayList(datacenter(1), datacenter(2)));
341349 Cluster cluster = builder()
342- .addContactPoint(sCluster.address(1, 1))
350+ .addContactPointsWithPorts(sCluster.address(1, 1))
351+ .withAddressTranslator(sCluster.addressTranslator())
343352 .withLoadBalancingPolicy(loadBalancingPolicy)
344353 .build();
345354
@@ -390,7 +399,8 @@
390399 DCAwareRoundRobinPolicy policy = spy(DCAwareRoundRobinPolicy.builder().build());
391400 ScassandraCluster sCluster = ScassandraCluster.builder().withNodes(2, 2).build();
392401 Cluster cluster = builder()
393- .addContactPoint(sCluster.address(1, 1))
402+ .addContactPointsWithPorts(sCluster.address(1, 1))
403+ .withAddressTranslator(sCluster.addressTranslator())
394404 .withLoadBalancingPolicy(policy)
395405 .build();
396406
@@ -429,7 +439,8 @@
429439 DCAwareRoundRobinPolicy policy = spy(DCAwareRoundRobinPolicy.builder().build());
430440 ScassandraCluster sCluster = ScassandraCluster.builder().withNodes(2, 2).build();
431441 Cluster cluster = builder()
432- .addContactPoints(sCluster.address(1, 1), sCluster.address(2, 1))
442+ .addContactPointsWithPorts(sCluster.address(1, 1), sCluster.address(2, 1))
443+ .withAddressTranslator(sCluster.addressTranslator())
433444 .withLoadBalancingPolicy(policy)
434445 .build();
435446
@@ -467,7 +478,8 @@
467478 ScassandraCluster sCluster = ScassandraCluster.builder().withNodes(2, 2).build();
468479 DCAwareRoundRobinPolicy policy = spy(DCAwareRoundRobinPolicy.builder().withLocalDc(datacenter(1)).build());
469480 Cluster cluster = builder()
470- .addContactPoints(sCluster.address(1, 1))
481+ .addContactPointsWithPorts(sCluster.address(1, 1))
482+ .withAddressTranslator(sCluster.addressTranslator())
471483 .withLoadBalancingPolicy(policy)
472484 .build();
473485
@@ -506,7 +518,8 @@
506518 ScassandraCluster sCluster = ScassandraCluster.builder().withNodes(2, 2).build();
507519 DCAwareRoundRobinPolicy policy = spy(DCAwareRoundRobinPolicy.builder().withLocalDc(datacenter(3)).build());
508520 Cluster cluster = builder()
509- .addContactPoints(sCluster.address(1, 1), sCluster.address(2, 1))
521+ .addContactPointsWithPorts(sCluster.address(1, 1), sCluster.address(2, 1))
522+ .withAddressTranslator(sCluster.addressTranslator())
510523 .withLoadBalancingPolicy(policy)
511524 .build();
512525
modified driver-core/src/test/java/com/datastax/driver/core/policies/DefaultRetryPolicyIntegrationTest.java +3 −2
@@ -113,8 +113,9 @@
113113 Collections.singletonList(host1.getSocketAddress()));
114114
115115 Cluster whiteListedCluster = Cluster.builder()
116- .addContactPoint(CCMBridge.ipOfNode(1))
117- // Scassandra does not support V3 nor V4 yet, and V4 may cause the server to crash
116+ .addContactPointsWithPorts(scassandras.address(1))
117+ .withAddressTranslator(scassandras.addressTranslator())
118+ // Scassandra does not support V3 nor V4 yet, and V4 may cause the server to crash
118119 .withProtocolVersion(ProtocolVersion.V2)
119120 .withRetryPolicy(retryPolicy)
120121 .withLoadBalancingPolicy(firstHostOnlyPolicy)
modified driver-core/src/test/java/com/datastax/driver/core/policies/RoundRobinPolicyTest.java +10 −5
@@ -30,18 +30,20 @@
3030 Logger policyLogger = Logger.getLogger(RoundRobinPolicy.class);
3131 MemoryAppender logs;
3232 QueryTracker queryTracker;
33+ Level originalLevel;
3334
3435 @BeforeMethod(groups = "short")
3536 public void setUp() {
3637 queryTracker = new QueryTracker();
38+ originalLevel = policyLogger.getLevel();
3739 policyLogger.setLevel(Level.WARN);
3840 logs = new MemoryAppender();
3941 policyLogger.addAppender(logs);
4042 }
4143
42- @AfterMethod(groups = "short")
44+ @AfterMethod(groups = "short", alwaysRun = true)
4345 public void tearDown() {
44- policyLogger.setLevel(null);
46+ policyLogger.setLevel(originalLevel);
4547 policyLogger.removeAppender(logs);
4648 }
4749
@@ -57,7 +59,8 @@
5759 ScassandraCluster sCluster = ScassandraCluster.builder().withNodes(5).build();
5860
5961 Cluster cluster = Cluster.builder()
60- .addContactPoint(sCluster.address(1))
62+ .addContactPointsWithPorts(sCluster.address(1))
63+ .withAddressTranslator(sCluster.addressTranslator())
6164 .withLoadBalancingPolicy(new RoundRobinPolicy())
6265 .withNettyOptions(nonQuietClusterCloseOptions)
6366 .build();
@@ -92,7 +95,8 @@
9295 ScassandraCluster sCluster = ScassandraCluster.builder().withNodes(2, 2, 2, 2, 2).build();
9396
9497 Cluster cluster = Cluster.builder()
95- .addContactPoint(sCluster.address(1))
98+ .addContactPointsWithPorts(sCluster.address(1))
99+ .withAddressTranslator(sCluster.addressTranslator())
96100 .withLoadBalancingPolicy(new RoundRobinPolicy())
97101 .withNettyOptions(nonQuietClusterCloseOptions)
98102 .build();
@@ -130,7 +134,8 @@
130134 ScassandraCluster sCluster = ScassandraCluster.builder().withNodes(1, 1).build();
131135
132136 Cluster cluster = Cluster.builder()
133- .addContactPoint(sCluster.address(1))
137+ .addContactPointsWithPorts(sCluster.address(1))
138+ .withAddressTranslator(sCluster.addressTranslator())
134139 .withLoadBalancingPolicy(new RoundRobinPolicy())
135140 .withNettyOptions(nonQuietClusterCloseOptions)
136141 .build();
modified driver-core/src/test/java/com/datastax/driver/core/policies/TokenAwarePolicyTest.java +15 −6
@@ -69,7 +69,9 @@
6969 loadBalancingPolicy = new TokenAwarePolicy(new RoundRobinPolicy(), shuffleReplicas);
7070 }
7171
72- Cluster cluster = Cluster.builder().addContactPoints(sCluster.address(1))
72+ Cluster cluster = Cluster.builder()
73+ .addContactPointsWithPorts(sCluster.address(1))
74+ .withAddressTranslator(sCluster.addressTranslator())
7375 .withNettyOptions(nonQuietClusterCloseOptions)
7476 .withLoadBalancingPolicy(loadBalancingPolicy)
7577 .build();
@@ -137,7 +139,9 @@
137139 .withNodes(3)
138140 .withSimpleKeyspace("keyspace", 1)
139141 .build();
140- Cluster cluster = Cluster.builder().addContactPoints(sCluster.address(1))
142+ Cluster cluster = Cluster.builder()
143+ .addContactPointsWithPorts(sCluster.address(1))
144+ .withAddressTranslator(sCluster.addressTranslator())
141145 .withNettyOptions(nonQuietClusterCloseOptions)
142146 .withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy()))
143147 .build();
@@ -180,7 +184,9 @@
180184 .withNodes(3, 3)
181185 .withNetworkTopologyKeyspace("keyspace", ImmutableMap.of(1, 1, 2, 1))
182186 .build();
183- Cluster cluster = Cluster.builder().addContactPoints(sCluster.address(2, 1))
187+ Cluster cluster = Cluster.builder()
188+ .addContactPointsWithPorts(sCluster.address(1))
189+ .withAddressTranslator(sCluster.addressTranslator())
184190 .withNettyOptions(nonQuietClusterCloseOptions)
185191 .withLoadBalancingPolicy(new TokenAwarePolicy(DCAwareRoundRobinPolicy.builder()
186192 .withLocalDc(ScassandraCluster.datacenter(2))
@@ -225,7 +231,9 @@
225231 .withNodes(4)
226232 .withSimpleKeyspace("keyspace", 2)
227233 .build();
228- Cluster cluster = Cluster.builder().addContactPoints(sCluster.address(2))
234+ Cluster cluster = Cluster.builder()
235+ .addContactPointsWithPorts(sCluster.address(2))
236+ .withAddressTranslator(sCluster.addressTranslator())
229237 .withNettyOptions(nonQuietClusterCloseOptions)
230238 // Don't shuffle replicas just to keep test deterministic.
231239 .withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy(), false))
@@ -311,11 +319,12 @@
311319 @Test(groups = "long")
312320 public void should_properly_generate_and_use_routing_key_for_composite_partition_key() {
313321 // given: a 3 node cluster with a keyspace with RF 1.
314- CCMBridge ccm = CCMBridge.builder("TokenAwarePolicyTest").withNodes(3).notStarted().build();
322+ CCMBridge ccm = CCMBridge.builder().withNodes(3).notStarted().build();
315323
316324 Cluster cluster = Cluster.builder()
317325 .withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy()))
318- .addContactPoint(CCMBridge.ipOfNode(1))
326+ .addContactPointsWithPorts(ccm.addressOfNode(1))
327+ .withAddressTranslator(ccm.addressTranslator())
319328 .build();
320329
321330 try {
modified driver-core/src/test/java/com/datastax/driver/core/policies/WhiteListPolicyTest.java +5 −8
@@ -21,7 +21,6 @@
2121 import org.testng.annotations.BeforeMethod;
2222 import org.testng.annotations.Test;
2323
24-import java.net.InetAddress;
2524 import java.net.InetSocketAddress;
2625 import java.util.List;
2726
@@ -51,12 +50,11 @@
5150 public void should_only_query_hosts_in_white_list() throws Exception {
5251 // given: a 5 node cluster with a WhiteListPolicy targeting nodes 3 and 5.
5352 ScassandraCluster sCluster = ScassandraCluster.builder().withNodes(5).build();
54- List<InetSocketAddress> whiteList = Lists.newArrayList(
55- new InetSocketAddress(InetAddress.getByName(sCluster.address(3)), 9042),
56- new InetSocketAddress(InetAddress.getByName(sCluster.address(5)), 9042));
53+ List<InetSocketAddress> whiteList = Lists.newArrayList(sCluster.address(3), sCluster.address(5));
5754
5855 Cluster cluster = Cluster.builder()
59- .addContactPoint(sCluster.address(5))
56+ .addContactPointsWithPorts(sCluster.address(5))
57+ .withAddressTranslator(sCluster.addressTranslator())
6058 .withLoadBalancingPolicy(new WhiteListPolicy(new RoundRobinPolicy(), whiteList))
6159 .withNettyOptions(nonQuietClusterCloseOptions)
6260 .build();
@@ -108,10 +106,9 @@
108106
109107 // when: using a Cluster instance with none of the contact points in the declared
110108 // WhiteListPolicy.
111- List<InetSocketAddress> whiteList = Lists.newArrayList(
112- new InetSocketAddress(InetAddress.getByName(sCluster.address(2)), 9042));
109+ List<InetSocketAddress> whiteList = Lists.newArrayList(sCluster.address(2));
113110 Cluster cluster = Cluster.builder()
114- .addContactPoint(sCluster.address(3))
111+ .addContactPointsWithPorts(sCluster.address(3))
115112 .withLoadBalancingPolicy(new WhiteListPolicy(new RoundRobinPolicy(), whiteList))
116113 .withNettyOptions(nonQuietClusterCloseOptions)
117114 .build();
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilder21ExecutionTest.java +3 −3
@@ -15,7 +15,7 @@
1515 */
1616 package com.datastax.driver.core.querybuilder;
1717
18-import com.datastax.driver.core.CCMBridge;
18+import com.datastax.driver.core.CCMTestsSupport;
1919 import com.datastax.driver.core.PreparedStatement;
2020 import com.datastax.driver.core.ResultSet;
2121 import com.datastax.driver.core.Row;
@@ -29,10 +29,10 @@
2929 import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
3030
3131 @CassandraVersion(major = 2.1)
32-public class QueryBuilder21ExecutionTest extends CCMBridge.PerClassSingleNodeCluster {
32+public class QueryBuilder21ExecutionTest extends CCMTestsSupport {
3333
3434 @Override
35- protected Collection<String> getTableDefinitions() {
35+ public Collection<String> createTestFixtures() {
3636 // Taken from http://www.datastax.com/dev/blog/cql-in-2-1
3737 return Arrays.asList(
3838 "CREATE TABLE products (id int PRIMARY KEY, description text, price int, categories set<text>, buyers list<int>, features_keys map<text, text>, features_values map<text, text>)",
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderExecutionTest.java +2 −2
@@ -25,12 +25,12 @@
2525 import static org.assertj.core.data.MapEntry.entry;
2626 import static org.testng.Assert.*;
2727
28-public class QueryBuilderExecutionTest extends CCMBridge.PerClassSingleNodeCluster {
28+public class QueryBuilderExecutionTest extends CCMTestsSupport {
2929
3030 private static final String TABLE1 = "test1";
3131
3232 @Override
33- protected Collection<String> getTableDefinitions() {
33+ public Collection<String> createTestFixtures() {
3434 return Arrays.asList(
3535 String.format("CREATE TABLE %s (k text PRIMARY KEY, t text, i int, f float)", TABLE1),
3636 "CREATE TABLE dateTest (t timestamp PRIMARY KEY)",
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderITest.java +3 −11
@@ -27,26 +27,18 @@
2727 import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
2828 import static org.testng.Assert.*;
2929
30-public class QueryBuilderITest extends CCMBridge.PerClassSingleNodeCluster {
30+@CCMConfig(clusterProvider = "createClusterBuilderNoDebouncing")
31+public class QueryBuilderITest extends CCMTestsSupport {
3132
3233 private static final String TABLE_TEXT = "test_text";
3334 private static final String TABLE_INT = "test_int";
3435
3536 @Override
36- protected Collection<String> getTableDefinitions() {
37+ public Collection<String> createTestFixtures() {
3738 return Arrays.asList(String.format("CREATE TABLE %s (k text PRIMARY KEY, a int, b int)", TABLE_TEXT),
3839 String.format("CREATE TABLE %s (k int PRIMARY KEY, a int, b int)", TABLE_INT));
3940 }
4041
41- @Override
42- protected Cluster.Builder configure(Cluster.Builder builder) {
43- return builder.withQueryOptions(new QueryOptions()
44- .setRefreshNodeIntervalMillis(0)
45- .setRefreshNodeListIntervalMillis(0)
46- .setRefreshSchemaIntervalMillis(0)
47- );
48- }
49-
5042 @Test(groups = "short")
5143 public void remainingDeleteTests() throws Exception {
5244
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderRoutingKeyTest.java +3 −11
@@ -26,26 +26,18 @@
2626 import static org.testng.Assert.assertEquals;
2727 import static org.testng.Assert.assertNotNull;
2828
29-public class QueryBuilderRoutingKeyTest extends CCMBridge.PerClassSingleNodeCluster {
29+@CCMConfig(clusterProvider = "createClusterBuilderNoDebouncing")
30+public class QueryBuilderRoutingKeyTest extends CCMTestsSupport {
3031
3132 private static final String TABLE_TEXT = "test_text";
3233 private static final String TABLE_INT = "test_int";
3334
3435 @Override
35- protected Collection<String> getTableDefinitions() {
36+ public Collection<String> createTestFixtures() {
3637 return Arrays.asList(String.format("CREATE TABLE %s (k text PRIMARY KEY, a int, b int)", TABLE_TEXT),
3738 String.format("CREATE TABLE %s (k int PRIMARY KEY, a int, b int)", TABLE_INT));
3839 }
3940
40- @Override
41- protected Cluster.Builder configure(Cluster.Builder builder) {
42- return builder.withQueryOptions(new QueryOptions()
43- .setRefreshNodeIntervalMillis(0)
44- .setRefreshNodeListIntervalMillis(0)
45- .setRefreshSchemaIntervalMillis(0)
46- );
47- }
48-
4941 @Test(groups = "short")
5042 public void textRoutingKeyTest() throws Exception {
5143
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderTupleExecutionTest.java +2 −9
@@ -15,15 +15,13 @@
1515 */
1616 package com.datastax.driver.core.querybuilder;
1717
18-import com.datastax.driver.core.CCMBridge;
18+import com.datastax.driver.core.CCMTestsSupport;
1919 import com.datastax.driver.core.TupleType;
2020 import com.datastax.driver.core.TupleValue;
2121 import com.datastax.driver.core.utils.CassandraVersion;
2222 import com.google.common.collect.ImmutableList;
2323 import org.testng.annotations.Test;
2424
25-import java.util.Collection;
26-import java.util.Collections;
2725 import java.util.List;
2826
2927 import static com.datastax.driver.core.DataType.cint;
@@ -32,12 +30,7 @@
3230 import static org.testng.Assert.assertEquals;
3331
3432 @CassandraVersion(major = 2.1, minor = 3)
35-public class QueryBuilderTupleExecutionTest extends CCMBridge.PerClassSingleNodeCluster {
36-
37- @Override
38- protected Collection<String> getTableDefinitions() {
39- return Collections.emptyList();
40- }
33+public class QueryBuilderTupleExecutionTest extends CCMTestsSupport {
4134
4235 @Test(groups = "short")
4336 public void should_handle_tuple() throws Exception {
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderUDTExecutionTest.java +2 −2
@@ -32,10 +32,10 @@
3232 import static org.testng.Assert.assertEquals;
3333
3434 @CassandraVersion(major = 2.1, minor = 3)
35-public class QueryBuilderUDTExecutionTest extends CCMBridge.PerClassSingleNodeCluster {
35+public class QueryBuilderUDTExecutionTest extends CCMTestsSupport {
3636
3737 @Override
38- protected Collection<String> getTableDefinitions() {
38+ public Collection<String> createTestFixtures() {
3939 return Arrays.asList("CREATE TYPE udt (i int, a inet)",
4040 "CREATE TABLE udtTest(k int PRIMARY KEY, t frozen<udt>, l list<frozen<udt>>, m map<int, frozen<udt>>)");
4141 }
modified driver-core/src/test/java/com/datastax/driver/core/schemabuilder/SchemaBuilderIT.java +5 −12
@@ -15,7 +15,7 @@
1515 */
1616 package com.datastax.driver.core.schemabuilder;
1717
18-import com.datastax.driver.core.CCMBridge;
18+import com.datastax.driver.core.CCMTestsSupport;
1919 import com.datastax.driver.core.DataType;
2020 import com.datastax.driver.core.ResultSet;
2121 import com.datastax.driver.core.Row;
@@ -23,20 +23,13 @@
2323 import com.datastax.driver.core.utils.CassandraVersion;
2424 import org.testng.annotations.Test;
2525
26-import java.util.ArrayList;
27-import java.util.Collection;
2826 import java.util.Iterator;
2927
3028 import static com.datastax.driver.core.schemabuilder.SchemaBuilder.*;
3129 import static org.assertj.core.api.Assertions.assertThat;
3230 import static org.assertj.core.api.Assertions.fail;
3331
34-public class SchemaBuilderIT extends CCMBridge.PerClassSingleNodeCluster {
35-
36- @Override
37- protected Collection<String> getTableDefinitions() {
38- return new ArrayList<String>();
39- }
32+public class SchemaBuilderIT extends CCMTestsSupport {
4033
4134 @Test(groups = "short")
4235 @CassandraVersion(major = 2.1, minor = 2)
@@ -297,16 +290,16 @@
297290 );
298291
299292 // Verify that the PK index and the secondary indexes both exist
300- assertThat(numberOfIndexedColumns("ks", "dropindex")).isEqualTo(1);
293+ assertThat(numberOfIndexedColumns()).isEqualTo(1);
301294
302295 // Delete the index
303296 session.execute(SchemaBuilder.dropIndex("ks", "ks_index"));
304297
305298 // Verify that only the PK index exists
306- assertThat(numberOfIndexedColumns("ks", "dropindex")).isEqualTo(0);
299+ assertThat(numberOfIndexedColumns()).isEqualTo(0);
307300 }
308301
309- private int numberOfIndexedColumns(String keyspace, String table) {
302+ private int numberOfIndexedColumns() {
310303 ResultSet columns = session.execute(
311304 "SELECT * "
312305 + "FROM system.schema_columns "
modified driver-core/src/test/java/com/datastax/driver/core/utils/SocketChannelMonitor.java +15 −8
@@ -27,11 +27,10 @@
2727 import org.slf4j.Logger;
2828 import org.slf4j.LoggerFactory;
2929
30+import java.io.Closeable;
31+import java.io.IOException;
3032 import java.net.InetSocketAddress;
31-import java.util.Collection;
32-import java.util.Collections;
33-import java.util.Comparator;
34-import java.util.List;
33+import java.util.*;
3534 import java.util.concurrent.Executors;
3635 import java.util.concurrent.ScheduledExecutorService;
3736 import java.util.concurrent.TimeUnit;
@@ -41,7 +40,7 @@
4140 * Utility that observes {@link SocketChannel}s. Helpful for ensuring that Sockets are actually closed
4241 * when they should be. Utilizes {@link NettyOptions} to monitor created {@link SocketChannel}s.
4342 */
44-public class SocketChannelMonitor implements Runnable {
43+public class SocketChannelMonitor implements Runnable, Closeable {
4544
4645 private static final Logger logger = LoggerFactory.getLogger(SocketChannelMonitor.class);
4746
@@ -76,11 +75,17 @@
7675 }
7776 }
7877
78+ @Override
79+ public void close() throws IOException {
80+ stop();
81+ }
82+
7983 public void stop() {
8084 executor.shutdown();
8185 try {
8286 executor.awaitTermination(1, TimeUnit.SECONDS);
8387 } catch (InterruptedException e) {
88+ // ok
8489 }
8590 }
8691
@@ -152,11 +157,14 @@
152157 // Should not be null as these are filtered previously in matchingChannels.
153158 assert t0 != null && t0.remoteAddress() != null;
154159 assert t1 != null && t1.remoteAddress() != null;
155- ;
156160 return t0.remoteAddress().toString().compareTo(t1.remoteAddress().toString());
157161 }
158162 };
159163
164+ public Collection<SocketChannel> openChannels(InetSocketAddress... addresses) {
165+ return openChannels(Arrays.asList(addresses));
166+ }
167+
160168 /**
161169 * @param addresses The addresses to include.
162170 * @return Open channels matching the given socket addresses.
@@ -168,9 +176,7 @@
168176 return input.isOpen() && input.remoteAddress() != null && addresses.contains(input.remoteAddress());
169177 }
170178 }));
171-
172179 Collections.sort(channels, BY_REMOTE_ADDRESS);
173-
174180 return channels;
175181 }
176182
@@ -181,4 +187,5 @@
181187 public Iterable<SocketChannel> matchingChannels(final Predicate<SocketChannel> channelFilter) {
182188 return Iterables.filter(Lists.newArrayList(channels), Predicates.and(Predicates.notNull(), channelFilter));
183189 }
190+
184191 }
modified driver-core/src/test/resources/log4j.properties +26 −1
@@ -20,10 +20,35 @@
2020 # Adjust Scassandra's log level
2121 # (it seems some messages are conditioned by log4j.properties and others by reference.conf, so we need both)
2222 log4j.logger.org.scassandra=ERROR
23+# Useful loggers when debugging Scassandra tests
24+#log4j.logger.org.scassandra.cql=ERROR
25+#log4j.logger.org.scassandra.server.cqlmessages=ERROR
26+#log4j.logger.org.scassandra.server.priming=ERROR
27+#log4j.logger.org.scassandra.server.priming.ActivityLog=ERROR
28+#log4j.logger.org.scassandra.server.priming.PrimingServerHttpService=ERROR
29+#log4j.logger.org.scassandra.server.priming.query.PrimeQueryStore=ERROR
30+#log4j.logger.org.scassandra.http.client=ERROR
31+
32+# These loggers can be quite verbose
33+log4j.logger.com.datastax.driver.core.Cluster=ERROR
34+log4j.logger.com.datastax.driver.core.policies.DCAwareRoundRobinPolicy=ERROR
35+
36+# Useful loggers when debugging core functionality
37+#log4j.logger.com.datastax.driver.core.ControlConnection=ERROR
38+#log4j.logger.com.datastax.driver.core.HostConnectionPool=ERROR
39+#log4j.logger.com.datastax.driver.core.Host.STATES=ERROR
40+#log4j.logger.com.datastax.driver.core.Connection=ERROR
41+
42+# Adjust log levels for CCM tests
43+#log4j.logger.com.datastax.driver.core.CCMTestsSupport=DEBUG
44+#log4j.logger.com.datastax.driver.core.CCMBridge=DEBUG
2345
2446 # A1 is set to be a ConsoleAppender.
2547 log4j.appender.A1=org.apache.log4j.ConsoleAppender
2648
2749 # A1 uses PatternLayout.
2850 log4j.appender.A1.layout=org.apache.log4j.PatternLayout
29-log4j.appender.A1.layout.ConversionPattern=\ %-6r [%t] %-5p %c %x - %m%n
51+log4j.appender.A1.layout.ConversionPattern=\ %-6r [%t] %-5p %c %x- %m%n
52+# less verbose layout
53+#log4j.appender.A1.layout.ConversionPattern=%-5p%x %m%n
54+
modified driver-core/src/test/resources/reference.conf +1 −1
@@ -2,4 +2,4 @@
22 # (it seems some messages are conditioned by log4j.properties and others by reference.conf, so we need both)
33 akka {
44 loglevel = "ERROR"
5-}
No newline at the end of the file
5+}
modified driver-examples/osgi/src/test/java/com/datastax/driver/osgi/BundleOptions.java +2 −2
@@ -15,7 +15,7 @@
1515 */
1616 package com.datastax.driver.osgi;
1717
18-import com.datastax.driver.core.CCMBridge;
18+import com.datastax.driver.core.TestUtils;
1919 import org.ops4j.pax.exam.Option;
2020 import org.ops4j.pax.exam.options.CompositeOption;
2121 import org.ops4j.pax.exam.options.MavenArtifactProvisionOption;
@@ -70,7 +70,7 @@
7070 // Delegate javax.security.cert to the parent classloader. javax.security.cert.X509Certificate is used in
7171 // io.netty.util.internal.EmptyArrays, but not directly by the driver.
7272 bootDelegationPackage("javax.security.cert"),
73- systemProperty("cassandra.contactpoints").value(CCMBridge.IP_PREFIX + 1),
73+ systemProperty("cassandra.contactpoints").value(TestUtils.IP_PREFIX + 1),
7474 systemProperty("logback.configurationFile").value("file:" + PathUtils.getBaseDir() + "/src/test/resources/logback.xml"),
7575 mavenBundle("org.slf4j", "slf4j-api", "1.7.5"),
7676 mavenBundle("ch.qos.logback", "logback-classic", "1.1.3"),
modified driver-examples/osgi/src/test/java/com/datastax/driver/osgi/CCMBridgeListener.java +1 −1
@@ -33,7 +33,7 @@
3333
3434 @Override
3535 public void onStart(ITestContext context) {
36- ccm = CCMBridge.builder("test").withNodes(1).build();
36+ ccm = CCMBridge.builder().withNodes(1).withBinaryPort(9042).build();
3737 }
3838
3939 @Override
modified driver-extras/src/test/java/com/datastax/driver/extras/codecs/arrays/ArrayCodecsTest.java +4 −4
@@ -31,7 +31,7 @@
3131
3232 import static org.assertj.core.api.Assertions.assertThat;
3333
34-public class ArrayCodecsTest extends CCMBridge.PerClassSingleNodeCluster {
34+public class ArrayCodecsTest extends CCMTestsSupport {
3535
3636 private static final ObjectArrayCodec<String> stringArrayCodec = new ObjectArrayCodec<String>(
3737 DataType.list(DataType.varchar()),
@@ -39,7 +39,7 @@
3939 TypeCodec.varchar());
4040
4141 @Override
42- protected Collection<String> getTableDefinitions() {
42+ public Collection<String> createTestFixtures() {
4343 return Lists.newArrayList(
4444 "CREATE TABLE lists ("
4545 + "pk int PRIMARY KEY, "
@@ -60,8 +60,8 @@
6060 }
6161
6262 @Override
63- protected Cluster.Builder configure(Cluster.Builder builder) {
64- return builder.withCodecRegistry(
63+ public Cluster.Builder createClusterBuilder() {
64+ return Cluster.builder().withCodecRegistry(
6565 new CodecRegistry()
6666 .register(IntArrayCodec.instance)
6767 .register(LongArrayCodec.instance)
modified driver-extras/src/test/java/com/datastax/driver/extras/codecs/date/SimpleDateCodecsTest.java +2 −2
@@ -32,10 +32,10 @@
3232 import static org.assertj.core.api.Assertions.assertThat;
3333
3434 @CassandraVersion(major = 2.2)
35-public class SimpleDateCodecsTest extends CCMBridge.PerClassSingleNodeCluster {
35+public class SimpleDateCodecsTest extends CCMTestsSupport {
3636
3737 @Override
38- protected Collection<String> getTableDefinitions() {
38+ public Collection<String> createTestFixtures() {
3939 return Collections.singletonList(
4040 "CREATE TABLE IF NOT EXISTS foo ("
4141 + "c1 text PRIMARY KEY, "
modified driver-extras/src/test/java/com/datastax/driver/extras/codecs/enums/EnumCodecsTest.java +4 −4
@@ -45,7 +45,7 @@
4545 * It also validates that both codecs may coexist in the same CodecRegistry.
4646 */
4747 @CassandraVersion(major = 2.1)
48-public class EnumCodecsTest extends CCMBridge.PerClassSingleNodeCluster {
48+public class EnumCodecsTest extends CCMTestsSupport {
4949
5050 private final String insertQuery = "INSERT INTO t1 (pk, foo, foos, bar, bars, foobars, tup, udt) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
5151 private final String selectQuery = "SELECT pk, foo, foos, bar, bars, foobars, tup, udt FROM t1 WHERE pk = ?";
@@ -60,7 +60,7 @@
6060 private UDTValue udtValue;
6161
6262 @Override
63- protected Collection<String> getTableDefinitions() {
63+ public Collection<String> createTestFixtures() {
6464 return newArrayList(
6565 "CREATE TYPE IF NOT EXISTS udt1 ("
6666 + "foo int,"
@@ -79,8 +79,8 @@
7979 }
8080
8181 @Override
82- protected Cluster.Builder configure(Cluster.Builder builder) {
83- return builder.withCodecRegistry(
82+ public Cluster.Builder createClusterBuilder() {
83+ return Cluster.builder().withCodecRegistry(
8484 new CodecRegistry()
8585 .register(new EnumOrdinalCodec<Foo>(Foo.class))
8686 .register(new EnumNameCodec<Bar>(Bar.class))
modified driver-extras/src/test/java/com/datastax/driver/extras/codecs/guava/OptionalCodecTest.java +4 −5
@@ -16,7 +16,6 @@
1616 package com.datastax.driver.extras.codecs.guava;
1717
1818 import com.datastax.driver.core.*;
19-import com.datastax.driver.core.CCMBridge.PerClassSingleNodeCluster;
2019 import com.datastax.driver.core.querybuilder.BuiltStatement;
2120 import com.datastax.driver.core.utils.CassandraVersion;
2221 import com.google.common.base.Optional;
@@ -33,7 +32,7 @@
3332 import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
3433 import static org.assertj.core.api.Assertions.assertThat;
3534
36-public class OptionalCodecTest extends PerClassSingleNodeCluster {
35+public class OptionalCodecTest extends CCMTestsSupport {
3736
3837 private final OptionalCodec<List<String>> optionalCodec = new OptionalCodec<List<String>>(list(varchar()));
3938
@@ -44,13 +43,13 @@
4443 private BuiltStatement selectStmt;
4544
4645 @Override
47- protected Collection<String> getTableDefinitions() {
46+ public Collection<String> createTestFixtures() {
4847 return Collections.singletonList("CREATE TABLE foo (c1 text, c2 text, c3 list<text>, c4 bigint, c5 decimal, PRIMARY KEY (c1, c2))");
4948 }
5049
5150 @Override
52- protected Cluster.Builder configure(Cluster.Builder builder) {
53- return builder.withCodecRegistry(registry);
51+ public Cluster.Builder createClusterBuilder() {
52+ return Cluster.builder().withCodecRegistry(registry);
5453 }
5554
5655 @BeforeMethod(groups = "short")
modified driver-extras/src/test/java/com/datastax/driver/extras/codecs/jdk8/Jdk8TimeCodecsTest.java +2 −2
@@ -39,10 +39,10 @@
3939 import static org.assertj.core.api.Assertions.assertThat;
4040
4141 @CassandraVersion(major = 2.2)
42-public class Jdk8TimeCodecsTest extends CCMBridge.PerClassSingleNodeCluster {
42+public class Jdk8TimeCodecsTest extends CCMTestsSupport {
4343
4444 @Override
45- protected Collection<String> getTableDefinitions() {
45+ public Collection<String> createTestFixtures() {
4646 return Collections.singletonList(
4747 "CREATE TABLE IF NOT EXISTS foo ("
4848 + "c1 text PRIMARY KEY, "
modified driver-extras/src/test/java/com/datastax/driver/extras/codecs/jdk8/OptionalCodecTest.java +4 −5
@@ -16,7 +16,6 @@
1616 package com.datastax.driver.extras.codecs.jdk8;
1717
1818 import com.datastax.driver.core.*;
19-import com.datastax.driver.core.CCMBridge.PerClassSingleNodeCluster;
2019 import com.datastax.driver.core.querybuilder.BuiltStatement;
2120 import com.datastax.driver.core.utils.CassandraVersion;
2221 import com.google.common.collect.Lists;
@@ -33,7 +32,7 @@
3332 import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
3433 import static org.assertj.core.api.Assertions.assertThat;
3534
36-public class OptionalCodecTest extends PerClassSingleNodeCluster {
35+public class OptionalCodecTest extends CCMTestsSupport {
3736
3837 private final OptionalCodec<List<String>> optionalCodec = new OptionalCodec<List<String>>(list(varchar()));
3938
@@ -44,13 +43,13 @@
4443 private BuiltStatement selectStmt;
4544
4645 @Override
47- protected Collection<String> getTableDefinitions() {
46+ public Collection<String> createTestFixtures() {
4847 return Collections.singletonList("CREATE TABLE foo (c1 text, c2 text, c3 list<text>, c4 bigint, c5 decimal, PRIMARY KEY (c1, c2))");
4948 }
5049
5150 @Override
52- protected Cluster.Builder configure(Cluster.Builder builder) {
53- return builder.withCodecRegistry(registry);
51+ public Cluster.Builder createClusterBuilder() {
52+ return Cluster.builder().withCodecRegistry(registry);
5453 }
5554
5655 @BeforeMethod(groups = "short")
modified driver-extras/src/test/java/com/datastax/driver/extras/codecs/joda/JodaTimeCodecsTest.java +2 −2
@@ -41,10 +41,10 @@
4141 import static org.assertj.core.api.Assertions.assertThat;
4242
4343 @CassandraVersion(major = 2.2)
44-public class JodaTimeCodecsTest extends CCMBridge.PerClassSingleNodeCluster {
44+public class JodaTimeCodecsTest extends CCMTestsSupport {
4545
4646 @Override
47- protected Collection<String> getTableDefinitions() {
47+ public Collection<String> createTestFixtures() {
4848 return Collections.singletonList(
4949 "CREATE TABLE IF NOT EXISTS foo ("
5050 + "c1 text PRIMARY KEY, "
modified driver-extras/src/test/java/com/datastax/driver/extras/codecs/json/JacksonJsonCodecTest.java +4 −4
@@ -30,7 +30,7 @@
3030 import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
3131 import static org.assertj.core.api.Assertions.assertThat;
3232
33-public class JacksonJsonCodecTest extends CCMBridge.PerClassSingleNodeCluster {
33+public class JacksonJsonCodecTest extends CCMTestsSupport {
3434
3535 private static final JacksonJsonCodec<User> jsonCodec = new JacksonJsonCodec<User>(User.class);
3636
@@ -50,15 +50,15 @@
5050 private static final String notAJsonString = "this text is not json";
5151
5252 @Override
53- protected Collection<String> getTableDefinitions() {
53+ public Collection<String> createTestFixtures() {
5454 return Lists.newArrayList(
5555 "CREATE TABLE t1 (c1 text, c2 text, c3 list<text>, PRIMARY KEY (c1, c2))"
5656 );
5757 }
5858
5959 @Override
60- protected Cluster.Builder configure(Cluster.Builder builder) {
61- return builder.withCodecRegistry(
60+ public Cluster.Builder createClusterBuilder() {
61+ return Cluster.builder().withCodecRegistry(
6262 new CodecRegistry().register(jsonCodec) // global User <-> varchar codec
6363 );
6464 }
modified driver-extras/src/test/java/com/datastax/driver/extras/codecs/json/Jsr353JsonCodecTest.java +4 −4
@@ -30,7 +30,7 @@
3030 import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
3131 import static org.assertj.core.api.Assertions.assertThat;
3232
33-public class Jsr353JsonCodecTest extends CCMBridge.PerClassSingleNodeCluster {
33+public class Jsr353JsonCodecTest extends CCMTestsSupport {
3434
3535 private static final Jsr353JsonCodec jsonCodec = new Jsr353JsonCodec();
3636
@@ -46,15 +46,15 @@
4646 private static final String notAJsonString = "this text is not json";
4747
4848 @Override
49- protected Collection<String> getTableDefinitions() {
49+ public Collection<String> createTestFixtures() {
5050 return Lists.newArrayList(
5151 "CREATE TABLE t1 (c1 text, c2 text, PRIMARY KEY (c1, c2))"
5252 );
5353 }
5454
5555 @Override
56- protected Cluster.Builder configure(Cluster.Builder builder) {
57- return builder.withCodecRegistry(
56+ public Cluster.Builder createClusterBuilder() {
57+ return Cluster.builder().withCodecRegistry(
5858 new CodecRegistry().register(jsonCodec) // global User <-> varchar codec
5959 );
6060 }
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperAccessorParamsTest.java +5 −3
@@ -15,7 +15,7 @@
1515 */
1616 package com.datastax.driver.mapping;
1717
18-import com.datastax.driver.core.CCMBridge;
18+import com.datastax.driver.core.CCMTestsSupport;
1919 import com.datastax.driver.core.Row;
2020 import com.datastax.driver.core.utils.CassandraVersion;
2121 import com.datastax.driver.mapping.annotations.*;
@@ -26,9 +26,11 @@
2626
2727 import static org.assertj.core.api.Assertions.assertThat;
2828
29-public class MapperAccessorParamsTest extends CCMBridge.PerClassSingleNodeCluster {
29+@SuppressWarnings("unused")
30+public class MapperAccessorParamsTest extends CCMTestsSupport {
31+
3032 @Override
31- protected Collection<String> getTableDefinitions() {
33+ public Collection<String> createTestFixtures() {
3234 return Lists.newArrayList(
3335 "CREATE TABLE user ( key int primary key, gender int, home_phone text, work_phone text)",
3436 "CREATE INDEX on user(gender)",
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperAccessorTest.java +4 −3
@@ -15,7 +15,7 @@
1515 */
1616 package com.datastax.driver.mapping;
1717
18-import com.datastax.driver.core.CCMBridge;
18+import com.datastax.driver.core.CCMTestsSupport;
1919 import com.datastax.driver.core.ResultSet;
2020 import com.datastax.driver.core.Row;
2121 import com.datastax.driver.core.utils.CassandraVersion;
@@ -29,10 +29,10 @@
2929
3030 import static org.assertj.core.api.Assertions.assertThat;
3131
32-public class MapperAccessorTest extends CCMBridge.PerClassSingleNodeCluster {
32+public class MapperAccessorTest extends CCMTestsSupport {
3333
3434 @Override
35- protected Collection<String> getTableDefinitions() {
35+ public Collection<String> createTestFixtures() {
3636 return Lists.newArrayList("CREATE TABLE foo (k int primary key, v text)");
3737 }
3838
@@ -87,6 +87,7 @@
8787 assertThat(row.getString("v")).isEqualTo("bar");
8888 }
8989
90+ @SuppressWarnings("unused")
9091 @Accessor
9192 public interface SystemAccessor {
9293 @Query("select release_version from system.local")
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperCompositeKeyTest.java +8 −6
@@ -15,24 +15,26 @@
1515 */
1616 package com.datastax.driver.mapping;
1717
18-import com.datastax.driver.core.CCMBridge;
18+import com.datastax.driver.core.CCMTestsSupport;
1919 import com.datastax.driver.mapping.annotations.ClusteringColumn;
2020 import com.datastax.driver.mapping.annotations.PartitionKey;
2121 import com.datastax.driver.mapping.annotations.Table;
2222 import org.testng.annotations.Test;
2323
24-import java.util.Arrays;
2524 import java.util.Collection;
25+import java.util.Collections;
2626
2727 /**
2828 * Tests for the mapper with composite partition keys and multiple clustering columns.
2929 */
30-public class MapperCompositeKeyTest extends CCMBridge.PerClassSingleNodeCluster {
31-
32- protected Collection<String> getTableDefinitions() {
33- return Arrays.asList("CREATE TABLE test_table (pk1 int, pk2 int, cc1 int, cc2 int, PRIMARY KEY ((pk1, pk2), cc1, cc2))");
30+public class MapperCompositeKeyTest extends CCMTestsSupport {
31+
32+ @Override
33+ public Collection<String> createTestFixtures() {
34+ return Collections.singletonList("CREATE TABLE test_table (pk1 int, pk2 int, cc1 int, cc2 int, PRIMARY KEY ((pk1, pk2), cc1, cc2))");
3435 }
3536
37+ @SuppressWarnings("unused")
3638 @Table(keyspace = "ks", name = "test_table")
3739 public static class TestTable {
3840 @PartitionKey(0)
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperComputedFieldsTest.java +2 −2
@@ -36,10 +36,10 @@
3636 * annotation to map computed fields.
3737 */
3838 @SuppressWarnings("unused")
39-public class MapperComputedFieldsTest extends CCMBridge.PerClassSingleNodeCluster {
39+public class MapperComputedFieldsTest extends CCMTestsSupport {
4040
4141 @Override
42- protected Collection<String> getTableDefinitions() {
42+ public Collection<String> createTestFixtures() {
4343 return Lists.newArrayList(
4444 "CREATE TABLE user (login text primary key, name text)",
4545 "INSERT INTO user (login, name) VALUES ('testlogin', 'test name')");
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperCustomCodecTest.java +7 −6
@@ -35,10 +35,11 @@
3535 import static org.assertj.core.api.Assertions.fail;
3636
3737 @CassandraVersion(major = 2.1)
38-public class MapperCustomCodecTest extends CCMBridge.PerClassSingleNodeCluster {
38+@SuppressWarnings("unused")
39+public class MapperCustomCodecTest extends CCMTestsSupport {
3940
4041 @Override
41- protected Collection<String> getTableDefinitions() {
42+ public Collection<String> createTestFixtures() {
4243 return Lists.newArrayList(
4344 // Columns mapped to custom types
4445 "CREATE TABLE data1 (i int PRIMARY KEY, l bigint)",
@@ -57,8 +58,8 @@
5758 }
5859
5960 @Override
60- protected Cluster.Builder configure(Cluster.Builder builder) {
61- return builder.withCodecRegistry(new CodecRegistry()
61+ public Cluster.Builder createClusterBuilder() {
62+ return Cluster.builder().withCodecRegistry(new CodecRegistry()
6263 .register(new CustomInt.Codec()));
6364 }
6465
@@ -160,7 +161,7 @@
160161
161162 // Get should return an InvalidTypeException.
162163 try {
163- Data1InvalidCodecTypeMapping data1 = mapper.get(1);
164+ mapper.get(1);
164165 fail("Should not have been able to retrieve.");
165166 } catch (InvalidTypeException e) {
166167 // expected.
@@ -184,7 +185,7 @@
184185
185186 // Get should return an InvalidTypeException.
186187 try {
187- Data1InvalidCodecTypeMapping data1 = accessor.get(1);
188+ accessor.get(1);
188189 fail("Should not have been able to retrieve.");
189190 } catch (InvalidTypeException e) {
190191 // expected.
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperDefaultKeyspaceTest.java +7 −5
@@ -15,7 +15,7 @@
1515 */
1616 package com.datastax.driver.mapping;
1717
18-import com.datastax.driver.core.CCMBridge;
18+import com.datastax.driver.core.CCMTestsSupport;
1919 import com.datastax.driver.core.Session;
2020 import com.datastax.driver.core.utils.CassandraVersion;
2121 import com.datastax.driver.core.utils.UUIDs;
@@ -34,11 +34,13 @@
3434 * Tests usage of mapping annotations without specifying a keyspace.
3535 */
3636 @CassandraVersion(major = 2.1)
37-public class MapperDefaultKeyspaceTest extends CCMBridge.PerClassSingleNodeCluster {
37+@SuppressWarnings("unused")
38+public class MapperDefaultKeyspaceTest extends CCMTestsSupport {
3839
3940 private static final String KEYSPACE = "mapper_default_keyspace_test_ks";
4041
41- protected Collection<String> getTableDefinitions() {
42+ @Override
43+ public Collection<String> createTestFixtures() {
4244 return Arrays.asList(
4345 String.format("CREATE KEYSPACE IF NOT EXISTS %s WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 }", KEYSPACE),
4446 String.format("CREATE TYPE IF NOT EXISTS %s.group_name (name text)", KEYSPACE),
@@ -201,7 +203,7 @@
201203 if (other == null || other.getClass() != this.getClass())
202204 return false;
203205
204- Group that = (Group) other;
206+ Group2 that = (Group2) other;
205207 return Objects.equal(groupId, that.groupId)
206208 && Objects.equal(name, that.name);
207209 }
@@ -239,7 +241,7 @@
239241 public boolean equals(Object other) {
240242 if (other instanceof GroupName) {
241243 GroupName that = (GroupName) other;
242- return this.name == that.name;
244+ return this.name.equals(that.name);
243245 }
244246 return false;
245247 }
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperMaterializedViewTest.java +3 −3
@@ -15,7 +15,7 @@
1515 */
1616 package com.datastax.driver.mapping;
1717
18-import com.datastax.driver.core.CCMBridge;
18+import com.datastax.driver.core.CCMTestsSupport;
1919 import com.datastax.driver.core.utils.CassandraVersion;
2020 import com.datastax.driver.mapping.annotations.Accessor;
2121 import com.datastax.driver.mapping.annotations.Param;
@@ -31,10 +31,10 @@
3131 import static org.assertj.core.api.Assertions.assertThat;
3232
3333 @CassandraVersion(major = 3.0)
34-public class MapperMaterializedViewTest extends CCMBridge.PerClassSingleNodeCluster {
34+public class MapperMaterializedViewTest extends CCMTestsSupport {
3535
3636 @Override
37- protected Collection<String> getTableDefinitions() {
37+ public Collection<String> createTestFixtures() {
3838 // Example schema taken from: http://www.datastax.com/dev/blog/new-in-cassandra-3-0-materialized-views
3939 return newArrayList(
4040 "CREATE TABLE scores (user TEXT, game TEXT, year INT, month INT, day INT, score INT, PRIMARY KEY(user, game, year, month, day))",
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperNestedCollectionsTest.java +6 −9
@@ -15,7 +15,7 @@
1515 */
1616 package com.datastax.driver.mapping;
1717
18-import com.datastax.driver.core.CCMBridge;
18+import com.datastax.driver.core.CCMTestsSupport;
1919 import com.datastax.driver.core.ResultSet;
2020 import com.datastax.driver.core.utils.CassandraVersion;
2121 import com.datastax.driver.mapping.annotations.*;
@@ -29,10 +29,11 @@
2929 import static com.datastax.driver.core.Assertions.assertThat;
3030
3131 @CassandraVersion(major = 2.1, minor = 3)
32-public class MapperNestedCollectionsTest extends CCMBridge.PerClassSingleNodeCluster {
32+@SuppressWarnings("unused")
33+public class MapperNestedCollectionsTest extends CCMTestsSupport {
3334
3435 @Override
35- protected Collection<String> getTableDefinitions() {
36+ public Collection<String> createTestFixtures() {
3637 return Lists.newArrayList(
3738 "CREATE TYPE testType(i int, ls list<frozen<set<int>>>)",
3839 "CREATE TABLE testTable (k int primary key, "
@@ -130,12 +131,8 @@
130131
131132 TestType testType = (TestType) o;
132133
133- if (i != testType.i)
134- return false;
135- if (!ls.equals(testType.ls))
136- return false;
134+ return i == testType.i && ls.equals(testType.ls);
137135
138- return true;
139136 }
140137
141138 @Override
@@ -183,7 +180,7 @@
183180 }
184181
185182 @Accessor
186- public static interface TestAccessor {
183+ public interface TestAccessor {
187184 @Query("UPDATE testTable SET m1 = :m1 WHERE k = :k")
188185 ResultSet setM1(@Param("k") int k, @Param("m1") Map<String, Map<Integer, Integer>> m1);
189186
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperOptionTest.java +3 −2
@@ -35,13 +35,14 @@
3535 import static org.assertj.core.api.Assertions.assertThat;
3636 import static org.assertj.core.api.Assertions.fail;
3737
38-public class MapperOptionTest extends CCMBridge.PerClassSingleNodeCluster {
38+@SuppressWarnings("unused")
39+public class MapperOptionTest extends CCMTestsSupport {
3940
4041 ProtocolVersion protocolVersion;
4142 Mapper<User> mapper;
4243
4344 @Override
44- protected Collection<String> getTableDefinitions() {
45+ public Collection<String> createTestFixtures() {
4546 return Lists.newArrayList("CREATE TABLE user (key int primary key, v text)");
4647 }
4748
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperPrimitiveTypes22Test.java +5 −5
@@ -15,7 +15,7 @@
1515 */
1616 package com.datastax.driver.mapping;
1717
18-import com.datastax.driver.core.CCMBridge;
18+import com.datastax.driver.core.CCMTestsSupport;
1919 import com.datastax.driver.core.LocalDate;
2020 import com.datastax.driver.core.utils.Bytes;
2121 import com.datastax.driver.core.utils.CassandraVersion;
@@ -24,16 +24,16 @@
2424 import org.testng.annotations.Test;
2525
2626 import java.nio.ByteBuffer;
27-import java.util.Arrays;
2827 import java.util.Collection;
28+import java.util.Collections;
2929
3030 import static org.testng.Assert.assertEquals;
3131
3232 @CassandraVersion(major = 2.2)
33-public class MapperPrimitiveTypes22Test extends CCMBridge.PerClassSingleNodeCluster {
33+public class MapperPrimitiveTypes22Test extends CCMTestsSupport {
3434
35- protected Collection<String> getTableDefinitions() {
36- return Arrays.asList("CREATE TABLE primitiveTypes22 ("
35+ public Collection<String> createTestFixtures() {
36+ return Collections.singletonList("CREATE TABLE primitiveTypes22 ("
3737 + "byteBufferCol blob primary key,"
3838 + "localDateCol date,"
3939 + "timeCol time, timeWrapperCol time,"
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperPrimitiveTypesTest.java +5 −5
@@ -15,7 +15,7 @@
1515 */
1616 package com.datastax.driver.mapping;
1717
18-import com.datastax.driver.core.CCMBridge;
18+import com.datastax.driver.core.CCMTestsSupport;
1919 import com.datastax.driver.core.utils.Bytes;
2020 import com.datastax.driver.core.utils.UUIDs;
2121 import com.datastax.driver.mapping.annotations.PartitionKey;
@@ -26,8 +26,8 @@
2626 import java.math.BigInteger;
2727 import java.net.InetAddress;
2828 import java.nio.ByteBuffer;
29-import java.util.Arrays;
3029 import java.util.Collection;
30+import java.util.Collections;
3131 import java.util.Date;
3232 import java.util.UUID;
3333
@@ -36,10 +36,10 @@
3636 /**
3737 * Tests the mapping of all primitive types as Java fields.
3838 */
39-public class MapperPrimitiveTypesTest extends CCMBridge.PerClassSingleNodeCluster {
39+public class MapperPrimitiveTypesTest extends CCMTestsSupport {
4040
41- protected Collection<String> getTableDefinitions() {
42- return Arrays.asList("CREATE TABLE primitiveTypes ("
41+ public Collection<String> createTestFixtures() {
42+ return Collections.singletonList("CREATE TABLE primitiveTypes ("
4343 + "byteBufferCol blob primary key,"
4444 + "intCol int, intWrapperCol int,"
4545 + "longCol bigint, longWrapperCol bigint,"
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperSaveNullFieldsTest.java +4 −3
@@ -16,7 +16,7 @@
1616 package com.datastax.driver.mapping;
1717
1818 import com.datastax.driver.core.BoundStatement;
19-import com.datastax.driver.core.CCMBridge;
19+import com.datastax.driver.core.CCMTestsSupport;
2020 import com.datastax.driver.mapping.Mapper.Option;
2121 import com.datastax.driver.mapping.annotations.PartitionKey;
2222 import com.datastax.driver.mapping.annotations.Table;
@@ -28,12 +28,13 @@
2828
2929 import static org.assertj.core.api.Assertions.assertThat;
3030
31-public class MapperSaveNullFieldsTest extends CCMBridge.PerClassSingleNodeCluster {
31+@SuppressWarnings("unused")
32+public class MapperSaveNullFieldsTest extends CCMTestsSupport {
3233
3334 Mapper<User> mapper;
3435
3536 @Override
36- protected Collection<String> getTableDefinitions() {
37+ public Collection<String> createTestFixtures() {
3738 return Lists.newArrayList("CREATE TABLE user (login text primary key, name text, phone text)");
3839 }
3940
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperTest.java +3 −2
@@ -33,10 +33,11 @@
3333 /**
3434 * Basic tests for the mapping module.
3535 */
36-public class MapperTest extends CCMBridge.PerClassSingleNodeCluster {
36+@SuppressWarnings("unused")
37+public class MapperTest extends CCMTestsSupport {
3738
3839 @Override
39- protected Collection<String> getTableDefinitions() {
40+ public Collection<String> createTestFixtures() {
4041 // We'll allow to generate those create statement from the annotated entities later, but it's currently
4142 // a TODO
4243 return Arrays.asList("CREATE TABLE users (user_id uuid PRIMARY KEY, name text, email text, year int, gender text)",
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperUDTCollectionsTest.java +6 −4
@@ -15,7 +15,7 @@
1515 */
1616 package com.datastax.driver.mapping;
1717
18-import com.datastax.driver.core.CCMBridge;
18+import com.datastax.driver.core.CCMTestsSupport;
1919 import com.datastax.driver.mapping.annotations.*;
2020 import com.google.common.base.Objects;
2121 import com.google.common.collect.ImmutableMap;
@@ -30,9 +30,11 @@
3030 /**
3131 * Tests mapping of collections of UDTs.
3232 */
33-public class MapperUDTCollectionsTest extends CCMBridge.PerClassSingleNodeCluster {
34-
35- protected Collection<String> getTableDefinitions() {
33+@SuppressWarnings("unused")
34+public class MapperUDTCollectionsTest extends CCMTestsSupport {
35+
36+ @Override
37+ public Collection<String> createTestFixtures() {
3638 return Arrays.asList("CREATE TYPE \"Sub\"(i int)",
3739 "CREATE TABLE collection_examples (id int PRIMARY KEY, " +
3840 "l list<frozen<\"Sub\">>, " +
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperUDTTest.java +66 −67
@@ -31,9 +31,11 @@
3131 import static org.assertj.core.api.Assertions.fail;
3232 import static org.testng.Assert.*;
3333
34-public class MapperUDTTest extends CCMBridge.PerClassSingleNodeCluster {
35-
36- protected Collection<String> getTableDefinitions() {
34+@SuppressWarnings("unused")
35+public class MapperUDTTest extends CCMTestsSupport {
36+
37+ @Override
38+ public Collection<String> createTestFixtures() {
3739 return Arrays.asList("CREATE TYPE address (street text, city text, \"ZIP_code\" int, phones set<text>)",
3840 "CREATE TABLE users (user_id uuid PRIMARY KEY, name text, mainaddress frozen<address>, other_addresses map<text,frozen<address>>)");
3941 }
@@ -161,9 +163,7 @@
161163 this.city = city;
162164 this.zipCode = zipCode;
163165 this.phones = new HashSet<String>();
164- for (String phone : phones) {
165- this.phones.add(phone);
166- }
166+ Collections.addAll(this.phones, phones);
167167 }
168168
169169 public String getStreet() {
@@ -240,7 +240,7 @@
240240 ResultSet setOtherAddresses(@Param("id") UUID id, @Param("addresses") Map<String, Address> addresses);
241241
242242 @Query("SELECT * FROM users")
243- public Result<User> getAll();
243+ Result<User> getAll();
244244 }
245245
246246 @Test(groups = "short")
@@ -308,66 +308,65 @@
308308 @Test(groups = "short")
309309 public void should_be_able_to_use_udtCodec_standalone() {
310310 // Create a separate Cluster/Session to start with a CodecRegistry from scratch (so not already registered).
311- Cluster cluster = Cluster.builder().addContactPointsWithPorts(Collections.singleton(hostAddress)).build();
311+ Cluster cluster = register(Cluster.builder()
312+ .addContactPointsWithPorts(getInitialContactPoints())
313+ .withAddressTranslator(getAddressTranslator())
314+ .build());
315+ CodecRegistry registry = cluster.getConfiguration().getCodecRegistry();
316+ Session session = cluster.connect(keyspace);
317+
318+ UUID userId = UUIDs.random();
319+
320+ // Create a user.
321+ session.execute("update users SET other_addresses['condo']={street: '101 Ocean Ln', city: 'Jacksonville, FL', \"ZIP_code\": 89898, phones: {'8675309'}} " +
322+ " WHERE user_id=" + TypeCodec.uuid().format(userId));
323+ session.execute("update users SET mainaddress={street: '42 Middle of Nowhere', city: 'Lake of the Woods', \"ZIP_code\": 49553, phones: {'8675039'}} " +
324+ " WHERE user_Id=" + TypeCodec.uuid().format(userId));
325+
326+ // Get the user.
327+ Row row = session.execute("select * from users where user_id=?", userId).one();
328+
329+ UDTValue udtValue = row.getUDTValue("mainaddress");
330+ assertThat(udtValue.getString("street")).isEqualTo("42 Middle of Nowhere");
331+
332+ Object udtObject = row.getObject("mainaddress");
333+ assertThat(udtObject).isEqualTo(udtValue);
334+
335+ // There shouldn't be a codec for address.
312336 try {
313- CodecRegistry registry = cluster.getConfiguration().getCodecRegistry();
314- Session session = cluster.connect(keyspace);
315-
316- UUID userId = UUIDs.random();
317-
318- // Create a user.
319- session.execute("update users SET other_addresses['condo']={street: '101 Ocean Ln', city: 'Jacksonville, FL', \"ZIP_code\": 89898, phones: {'8675309'}} " +
320- " WHERE user_id=" + TypeCodec.uuid().format(userId));
321- session.execute("update users SET mainaddress={street: '42 Middle of Nowhere', city: 'Lake of the Woods', \"ZIP_code\": 49553, phones: {'8675039'}} " +
322- " WHERE user_Id=" + TypeCodec.uuid().format(userId));
323-
324- // Get the user.
325- Row row = session.execute("select * from users where user_id=?", userId).one();
326-
327- UDTValue udtValue = row.getUDTValue("mainaddress");
328- assertThat(udtValue.getString("street")).isEqualTo("42 Middle of Nowhere");
329-
330- Object udtObject = row.getObject("mainaddress");
331- assertThat(udtObject).isEqualTo(udtValue);
332-
333- // There shouldn't be a codec for address.
334- try {
335- assertThat(registry.codecFor(udtValue.getType(), Address.class));
336- fail("Didn't expect to find codec for udtType <-> Address");
337- } catch (CodecNotFoundException e) {
338- // expected.
339- }
340-
341- // Expect a this_udt <-> UDTValue codec to exist. This is a pretty safe bet or else we wouldn't get
342- // this value back.
343- TypeCodec<UDTValue> udtCodec = registry.codecFor(udtValue.getType());
344- assertThat(udtCodec.getCqlType()).isEqualTo(udtValue.getType());
345- assertThat(udtCodec.getJavaType().getRawType()).isEqualTo(UDTValue.class);
346-
347- // Retrieve codec for Address, if it can be mapped it will be created, if already registered it'll be used.
348- TypeCodec<Address> codec = new MappingManager(session).udtCodec(Address.class);
349-
350- // The codec should be registered after we call udtCodec.
351- assertThat(registry.codecFor(udtValue.getType(), Address.class)).isEqualTo(codec);
352-
353- // Should be able to retrieve as an Address.
354- Address mainAddress = row.get("mainaddress", Address.class);
355- assertThat(mainAddress.getCity()).isEqualTo("Lake of the Woods");
356- assertThat(mainAddress.getStreet()).isEqualTo("42 Middle of Nowhere");
357- assertThat(mainAddress.getZipCode()).isEqualTo(49553);
358- assertThat(mainAddress.getPhones()).containsExactly("8675039");
359-
360- // Should be able to retrieve within a Map.
361- Address expectedOtherAddress = new Address();
362- expectedOtherAddress.setStreet("101 Ocean Ln");
363- expectedOtherAddress.setCity("Jacksonville, FL");
364- expectedOtherAddress.setZipCode(89898);
365- expectedOtherAddress.setPhones(Collections.singleton("8675309"));
366-
367- Map<String, Address> otherAddresses = row.getMap("other_addresses", String.class, Address.class);
368- assertThat(otherAddresses).containsOnly(MapEntry.entry("condo", expectedOtherAddress));
369- } finally {
370- cluster.close();
371- }
337+ assertThat(registry.codecFor(udtValue.getType(), Address.class));
338+ fail("Didn't expect to find codec for udtType <-> Address");
339+ } catch (CodecNotFoundException e) {
340+ // expected.
341+ }
342+
343+ // Expect a this_udt <-> UDTValue codec to exist. This is a pretty safe bet or else we wouldn't get
344+ // this value back.
345+ TypeCodec<UDTValue> udtCodec = registry.codecFor(udtValue.getType());
346+ assertThat(udtCodec.getCqlType()).isEqualTo(udtValue.getType());
347+ assertThat(udtCodec.getJavaType().getRawType()).isEqualTo(UDTValue.class);
348+
349+ // Retrieve codec for Address, if it can be mapped it will be created, if already registered it'll be used.
350+ TypeCodec<Address> codec = new MappingManager(session).udtCodec(Address.class);
351+
352+ // The codec should be registered after we call udtCodec.
353+ assertThat(registry.codecFor(udtValue.getType(), Address.class)).isEqualTo(codec);
354+
355+ // Should be able to retrieve as an Address.
356+ Address mainAddress = row.get("mainaddress", Address.class);
357+ assertThat(mainAddress.getCity()).isEqualTo("Lake of the Woods");
358+ assertThat(mainAddress.getStreet()).isEqualTo("42 Middle of Nowhere");
359+ assertThat(mainAddress.getZipCode()).isEqualTo(49553);
360+ assertThat(mainAddress.getPhones()).containsExactly("8675039");
361+
362+ // Should be able to retrieve within a Map.
363+ Address expectedOtherAddress = new Address();
364+ expectedOtherAddress.setStreet("101 Ocean Ln");
365+ expectedOtherAddress.setCity("Jacksonville, FL");
366+ expectedOtherAddress.setZipCode(89898);
367+ expectedOtherAddress.setPhones(Collections.singleton("8675309"));
368+
369+ Map<String, Address> otherAddresses = row.getMap("other_addresses", String.class, Address.class);
370+ assertThat(otherAddresses).containsOnly(MapEntry.entry("condo", expectedOtherAddress));
372371 }
373372 }
modified driver-mapping/src/test/java/com/datastax/driver/mapping/SyntheticFieldsMapperTest.java +8 −7
@@ -15,7 +15,7 @@
1515 */
1616 package com.datastax.driver.mapping;
1717
18-import com.datastax.driver.core.CCMBridge;
18+import com.datastax.driver.core.CCMTestsSupport;
1919 import com.datastax.driver.mapping.annotations.PartitionKey;
2020 import com.datastax.driver.mapping.annotations.Table;
2121 import com.google.common.io.Closeables;
@@ -25,15 +25,17 @@
2525 import java.io.IOException;
2626 import java.io.InputStream;
2727 import java.lang.reflect.Constructor;
28-import java.util.Arrays;
2928 import java.util.Collection;
29+import java.util.Collections;
3030
3131 import static org.testng.Assert.assertEquals;
3232
33-public class SyntheticFieldsMapperTest extends CCMBridge.PerClassSingleNodeCluster {
33+@SuppressWarnings("unused")
34+public class SyntheticFieldsMapperTest extends CCMTestsSupport {
3435
35- protected Collection<String> getTableDefinitions() {
36- return Arrays.asList("CREATE TABLE synthetic_fields (id int PRIMARY KEY)");
36+ @Override
37+ public Collection<String> createTestFixtures() {
38+ return Collections.singletonList("CREATE TABLE synthetic_fields (id int PRIMARY KEY)");
3739 }
3840
3941 /**
@@ -141,9 +143,8 @@
141143
142144 ClassWithSyntheticField that = (ClassWithSyntheticField) o;
143145
144- if (id != that.id) return false;
146+ return id == that.id;
145147
146- return true;
147148 }
148149
149150 @Override
modified driver-mapping/src/test/java/com/datastax/driver/mapping/UDTFieldMapperTest.java +19 −6
@@ -27,6 +27,7 @@
2727 import java.util.Map;
2828
2929 @CassandraVersion(major = 2.1)
30+@SuppressWarnings("unused")
3031 public class UDTFieldMapperTest {
3132
3233 @Test(groups = "short")
@@ -36,8 +37,11 @@
3637
3738 try {
3839 // Create type and table
39- ccm = CCMBridge.builder("test").build();
40- cluster = Cluster.builder().addContactPoint(CCMBridge.ipOfNode(1)).build();
40+ ccm = CCMBridge.builder().build();
41+ cluster = Cluster.builder()
42+ .addContactPointsWithPorts(ccm.addressOfNode(1))
43+ .withAddressTranslator(ccm.addressTranslator())
44+ .build();
4145 Session session1 = cluster.connect();
4246 session1.execute("create schema if not exists java_509 " +
4347 "with replication = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 };");
@@ -50,7 +54,10 @@
5054 cluster.close();
5155
5256 // Create entities with another connection
53- cluster = Cluster.builder().addContactPoint(CCMBridge.ipOfNode(1)).build();
57+ cluster = Cluster.builder()
58+ .addContactPointsWithPorts(ccm.addressOfNode(1))
59+ .withAddressTranslator(ccm.addressTranslator())
60+ .build();
5461 Session session2 = cluster.newSession();
5562 Mapper<MyHashWithKeyspace> hashMapper = new MappingManager(session2).mapper(MyHashWithKeyspace.class);
5663 hashMapper.save(new MyHashWithKeyspace(
@@ -83,8 +90,11 @@
8390
8491 try {
8592 // Create type and table
86- ccm = CCMBridge.builder("test").build();
87- cluster = Cluster.builder().addContactPoint(CCMBridge.ipOfNode(1)).build();
93+ ccm = CCMBridge.builder().build();
94+ cluster = Cluster.builder()
95+ .addContactPointsWithPorts(ccm.addressOfNode(1))
96+ .withAddressTranslator(ccm.addressTranslator())
97+ .build();
8898 Session session1 = cluster.connect();
8999 session1.execute("create schema if not exists java_509 " +
90100 "with replication = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 };");
@@ -98,7 +108,10 @@
98108 cluster.close();
99109
100110 // Create entities with another connection
101- cluster = Cluster.builder().addContactPoint(CCMBridge.ipOfNode(1)).build();
111+ cluster = Cluster.builder()
112+ .addContactPointsWithPorts(ccm.addressOfNode(1))
113+ .withAddressTranslator(ccm.addressTranslator())
114+ .build();
102115 Session session2 = cluster.newSession();
103116
104117 session2.execute("use java_509");