Elffuss BraidHub

kikocis/java-driver public

Refactor CCM tests.

This commit contains contributions by Andrew Tolbert (@tolbertam).

It only affects tests, except for
- the new method Cluster.Builder.addContactPointsWithPorts(InetSocketAddress[]).
- AbstractReconnectionHandler does not set the future to null when canceled while running.
Changeset8dda5388dd39f2b318afbc01211d59fb90a7baf5532b31a4556ddb66770ad803
AuthorAlexandre Dutra <alexandre.dutra@datastax.com> · 2015-12-30 13:05 +01:00
CommitterAlexandre Dutra <alexandre.dutra@datastax.com> · 2016-01-14 16:02 +01:00
Parentsfb3eea0b45a2

Browse the files at this changeset

128 files changed

modified build.yaml +2 −0
@@ -20,6 +20,7 @@
2020 ccm.path=$CCM_JAVA_HOME/bin
2121 failIfNoTests=false
2222 maven.test.failure.ignore=true
23+ maven.javadoc.skip=true
2324 - type: maven
2425 version: 3.2.5
2526 goals: verify --fail-never -Pisolated
@@ -31,6 +32,7 @@
3132 ccm.path=$CCM_JAVA_HOME/bin
3233 failIfNoTests=false
3334 maven.test.failure.ignore=true
35+ maven.javadoc.skip=true
3436 - xunit:
3537 - "**/target/surefire-reports/TEST-*.xml"
3638 - "**/target/failsafe-reports/TEST-*.xml"
modified driver-core/src/main/java/com/datastax/driver/core/AbstractReconnectionHandler.java +2 −2
@@ -48,7 +48,8 @@
4848 */
4949 private final AtomicReference<ListenableFuture<?>> currentAttempt;
5050
51- private final HandlerFuture handlerFuture = new HandlerFuture();
51+ @VisibleForTesting
52+ final HandlerFuture handlerFuture = new HandlerFuture();
5253
5354 private final long initialDelayMs;
5455
@@ -131,7 +132,6 @@
131132
132133 if (handlerFuture.isCancelled()) {
133134 logger.debug("Got cancelled, stopping");
134- currentAttempt.compareAndSet(handlerFuture, null);
135135 return;
136136 }
137137
modified driver-core/src/main/java/com/datastax/driver/core/Cluster.java +28 −2
@@ -937,10 +937,36 @@
937937 * points. Contrarily to other {@code addContactPoints} methods, this method
938938 * allow to provide a different port for each contact points. Since Cassandra
939939 * nodes must always all listen on the same port, this is rarelly what you
940- * want and most use should prefer other {@code addContactPoints} methods to
940+ * want and most users should prefer other {@code addContactPoints} methods to
941941 * this one. However, this can be useful if the Cassandra nodes are behind
942942 * a router and are not accessed directly. Note that if you are in this
943- * situtation (Cassandra nodes are behind a router, not directly accessible),
943+ * situation (Cassandra nodes are behind a router, not directly accessible),
944+ * you almost surely want to provide a specific {@code AddressTranslater}
945+ * (through {@link #withAddressTranslater}) to translate actual Cassandra node
946+ * addresses to the addresses the driver should use, otherwise the driver
947+ * will not be able to auto-detect new nodes (and will generally not function
948+ * optimally).
949+ *
950+ * @param addresses addresses of the nodes to add as contact point
951+ * @return this Builder
952+ * @see Builder#addContactPoint
953+ */
954+ public Builder addContactPointsWithPorts(InetSocketAddress... addresses) {
955+ Collections.addAll(this.addresses, addresses);
956+ return this;
957+ }
958+
959+ /**
960+ * Adds contact points.
961+ * <p/>
962+ * See {@link Builder#addContactPoint} for more details on contact
963+ * points. Contrarily to other {@code addContactPoints} methods, this method
964+ * allow to provide a different port for each contact points. Since Cassandra
965+ * nodes must always all listen on the same port, this is rarelly what you
966+ * want and most users should prefer other {@code addContactPoints} methods to
967+ * this one. However, this can be useful if the Cassandra nodes are behind
968+ * a router and are not accessed directly. Note that if you are in this
969+ * situation (Cassandra nodes are behind a router, not directly accessible),
944970 * you almost surely want to provide a specific {@code AddressTranslater}
945971 * (through {@link #withAddressTranslater}) to translate actual Cassandra node
946972 * addresses to the addresses the driver should use, otherwise the driver
modified driver-core/src/main/java/com/datastax/driver/core/Connection.java +1 −0
@@ -739,6 +739,7 @@
739739 * Same as open, but associate the created connection to the provided connection pool.
740740 */
741741 public Connection open(HostConnectionPool pool) throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
742+
742743 pool.host.convictionPolicy.signalConnectionsOpening(1);
743744 Connection connection = new Connection(buildConnectionName(pool.host), pool.host.getSocketAddress(), this, pool);
744745 try {
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/ProtocolVersion.java +1 −1
@@ -28,7 +28,7 @@
2828
2929 V1("1.2.0", 1),
3030 V2("2.0.0", 2),
31- V3("2.1.0", 3),;
31+ V3("2.1.0", 3);
3232
3333 /**
3434 * The most recent protocol version supported by the driver.
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
@@ -21,7 +21,6 @@
2121 import com.google.common.util.concurrent.Futures;
2222 import com.google.common.util.concurrent.ListenableFuture;
2323 import com.google.common.util.concurrent.SettableFuture;
24-import com.google.common.util.concurrent.Uninterruptibles;
2524 import org.slf4j.Logger;
2625 import org.slf4j.LoggerFactory;
2726 import org.testng.annotations.AfterMethod;
@@ -29,10 +28,7 @@
2928 import org.testng.annotations.Test;
3029
3130 import java.net.InetSocketAddress;
32-import java.util.concurrent.CyclicBarrier;
33-import java.util.concurrent.Executors;
34-import java.util.concurrent.ScheduledExecutorService;
35-import java.util.concurrent.TimeUnit;
31+import java.util.concurrent.*;
3632 import java.util.concurrent.atomic.AtomicReference;
3733
3834 import static org.assertj.core.api.Assertions.assertThat;
@@ -67,7 +63,7 @@
6763 };
6864 }
6965
70- @AfterMethod(groups = {"unit", "short"})
66+ @AfterMethod(groups = {"unit", "short"}, alwaysRun = true)
7167 public void tearDown() {
7268 if (future.get() != null)
7369 future.get().cancel(false);
@@ -136,7 +132,7 @@
136132 handler.start();
137133
138134 // Wait for the initial schedule of a reconnect.
139- verify(executor, timeout(1000)).schedule(handler, 0, TimeUnit.MILLISECONDS);
135+ verify(executor, timeout(10000)).schedule(handler, 0, TimeUnit.MILLISECONDS);
140136
141137 // Force a failed reconnect.
142138 schedule.tick();
@@ -150,10 +146,16 @@
150146
151147 // Ensure reconnect is scheduled (slight timing window after handling failed reconnect
152148 // and scheduling next reconnect).
153- verify(executor, timeout(1000)).schedule(handler, schedule.delay, TimeUnit.MILLISECONDS);
149+ verify(executor, timeout(10000)).schedule(handler, schedule.delay, TimeUnit.MILLISECONDS);
150+
151+ // Wait until nextTry is assigned after schedule completes.
152+ ConditionChecker.awaitUntil(new Callable<Boolean>() {
153+ @Override
154+ public Boolean call() throws Exception {
155+ return handler.handlerFuture.nextTry != null;
156+ }
157+ }, 10000);
154158
155- // Add a short delay to account for nextTry being assigned after schedule completes.
156- Uninterruptibles.sleepUninterruptibly(5, TimeUnit.MILLISECONDS);
157159 future.get().cancel(false);
158160
159161 // Should immediately return as the future was cancelled while the task was scheduled.
@@ -165,6 +167,7 @@
165167
166168 // The future will be marked cancelled and thus not executed.
167169 ListenableFuture<?> currentAttempt = future.get();
170+
168171 assertThat(currentAttempt).isInstanceOf(HandlerFuture.class);
169172 HandlerFuture handlerFuture = (HandlerFuture) currentAttempt;
170173 assertThat(handlerFuture.isCancelled());
@@ -327,8 +330,6 @@
327330 SUCCEED, THROW_EXCEPTION
328331 }
329332
330- ;
331-
332333 private final CyclicBarrier barrier = new CyclicBarrier(2);
333334
334335 volatile ReconnectBehavior nextReconnect;
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/AuthenticationTest.java +32 −58
@@ -16,84 +16,58 @@
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;
26+
2827 /**
2928 * Tests for authenticated cluster access
3029 */
31-public class AuthenticationTest {
32-
33- private static final Logger logger = LoggerFactory.getLogger(AuthenticationTest.class);
34-
35- private CCMBridge ccm;
36-
37- /**
38- * creates a cluster and turns on password authentication before starting it.
39- */
40- @BeforeClass(groups = "short")
41- public void setupClusterWithAuthentication() throws InterruptedException {
42- ccm = CCMBridge.builder("test")
43- .withCassandraConfiguration("authenticator", "PasswordAuthenticator")
44- .notStarted()
45- .build();
46- ccm.start(1, "-Dcassandra.superuser_setup_delay_ms=0");
47-
48- // Even though we've override the default user setup delay, still wait
49- // one second to make sure we don't race
50- TimeUnit.SECONDS.sleep(1);
51- }
52-
53- @AfterClass(groups = "short")
54- public void shutdownCluster() {
55- if (ccm != null)
56- ccm.stop();
30+@CreateCCM(PER_METHOD)
31+@CCMConfig(
32+ config = "authenticator:PasswordAuthenticator",
33+ jvmArgs = "-Dcassandra.superuser_setup_delay_ms=0",
34+ createCluster = false)
35+public class AuthenticationTest extends CCMTestsSupport {
36+
37+
38+ @BeforeMethod(groups = "short")
39+ public void sleepIf12() {
40+ // For C* 1.2, sleep before attempting to connect as there is a small delay between
41+ // user being created.
42+ if (ccm.getVersion().getMajor() < 2) {
43+ Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
44+ }
5745 }
5846
5947 @Test(groups = "short")
6048 public void should_connect_with_credentials() throws InterruptedException {
61- Cluster cluster = Cluster.builder().addContactPoint(CCMBridge.IP_PREFIX + '1')
49+ Cluster cluster = register(Cluster.builder()
50+ .addContactPointsWithPorts(getInitialContactPoints())
6251 .withCredentials("cassandra", "cassandra")
63- .build();
64- try {
65- cluster.connect();
66- } catch (NoHostAvailableException e) {
67- logger.error(e.getCustomMessage(1, true, true));
68- } finally {
69- cluster.close();
70- }
52+ .build());
53+ cluster.connect();
7154 }
7255
7356 @Test(groups = "short", expectedExceptions = AuthenticationException.class)
7457 public void should_fail_to_connect_with_wrong_credentials() throws InterruptedException {
75- Cluster cluster = Cluster.builder().addContactPoint(CCMBridge.IP_PREFIX + '1')
58+ Cluster cluster = register(Cluster.builder()
59+ .addContactPointsWithPorts(getInitialContactPoints())
7660 .withCredentials("bogus", "bogus")
77- .build();
78- try {
79- cluster.connect();
80- } catch (NoHostAvailableException e) {
81- logger.error(e.getCustomMessage(1, true, true));
82- } finally {
83- cluster.close();
84- }
61+ .build());
62+ cluster.connect();
8563 }
8664
8765 @Test(groups = "short", expectedExceptions = AuthenticationException.class)
8866 public void should_fail_to_connect_without_credentials() throws InterruptedException {
89- Cluster cluster = Cluster.builder().addContactPoint(CCMBridge.IP_PREFIX + '1')
90- .build();
91- try {
92- cluster.connect();
93- } catch (NoHostAvailableException e) {
94- logger.error(e.getCustomMessage(1, true, true));
95- } finally {
96- cluster.close();
97- }
67+ Cluster cluster = register(Cluster.builder()
68+ .addContactPointsWithPorts(getInitialContactPoints())
69+ .build());
70+ cluster.connect();
9871 }
72+
9973 }
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().getProtocolVersionEnum() != ProtocolVersion.V1)
74- throw e;
75- } catch (Throwable t) {
76- errorOut();
77- throw t;
72+ assertEquals(cluster.getConfiguration().getProtocolOptions().getProtocolVersionEnum(), 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().getProtocolVersionEnum() != 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 +464 −435
@@ -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.AddressTranslater;
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
@@ -153,7 +141,7 @@
153141 installArgs.append("-v git:");
154142 installArgs.append(branch.trim().replaceAll("\"", ""));
155143 } else {
156- installArgs.append("-v");
144+ installArgs.append("-v ");
157145 installArgs.append(CASSANDRA_VERSION);
158146 }
159147
@@ -163,12 +151,6 @@
163151
164152 CASSANDRA_INSTALL_ARGS = installArgs.toString();
165153
166- String ip_prefix = System.getProperty("ipprefix");
167- if (ip_prefix == null || ip_prefix.isEmpty()) {
168- ip_prefix = "127.0.1.";
169- }
170- IP_PREFIX = ip_prefix;
171-
172154 // Inherit the current environment.
173155 Map<String, String> envMap = Maps.newHashMap(new ProcessBuilder().environment());
174156 // If ccm.path is set, override the PATH variable with it.
@@ -214,13 +196,38 @@
214196 return osName != null && osName.startsWith("Windows");
215197 }
216198
199+ private final String clusterName;
200+
201+ private final VersionNumber version;
202+
203+ private final int storagePort;
204+
205+ private final int thriftPort;
206+
207+ private final int binaryPort;
208+
217209 private final File ccmDir;
218210
219211 private final boolean isDSE;
220212
221- private CCMBridge(boolean isDSE) {
222- this.ccmDir = Files.createTempDir();
213+ private final String jvmArgs;
214+
215+ private final int initialNumberOfNodes;
216+
217+ private boolean keepLogs = false;
218+
219+ private boolean closed = false;
220+
221+ private CCMBridge(String clusterName, boolean isDSE, VersionNumber version, int storagePort, int thriftPort, int binaryPort, String jvmArgs, int initialNumberOfNodes) {
222+ this.clusterName = clusterName;
223+ this.version = version;
224+ this.storagePort = storagePort;
225+ this.thriftPort = thriftPort;
226+ this.binaryPort = binaryPort;
223227 this.isDSE = isDSE;
228+ this.jvmArgs = jvmArgs;
229+ this.initialNumberOfNodes = initialNumberOfNodes;
230+ this.ccmDir = Files.createTempDir();
224231 }
225232
226233 /**
@@ -280,153 +287,232 @@
280287 return CASSANDRA_INSTALL_ARGS;
281288 }
282289
290+ public static Builder builder() {
291+ return new Builder();
292+ }
293+
283294 /**
284- * <p>
285- * Extracts a keystore from the classpath into a temporary file.
286- * </p>
295+ * Returns the address of the {@code nth} host in the CCM cluster (counting from 1, i.e.,
296+ * {@code getHostAddress(1)} returns the address of the first node.
287297 * <p/>
288- * <p>
289- * This is needed as the keystore could be part of a built test jar used by other
290- * projects, and they need to be extracted to a file system so cassandra may use them.
291- * </p>
298+ * In multi-DC setups, nodes are numbered in ascending order of their datacenter number.
299+ * E.g. with 2 DCs and 3 nodes in each DC, the first node in DC 2 is number 4.
292300 *
293- * @param storePath Path in classpath where the keystore exists.
294- * @return The generated File.
301+ * @return the address of the {@code nth} host in the cluster.
295302 */
296- private static File createTempStore(String storePath) {
297- File f = null;
298- Closer closer = Closer.create();
299- try {
300- InputStream trustStoreIs = CCMBridge.class.getResourceAsStream(storePath);
301- closer.register(trustStoreIs);
302- f = File.createTempFile("server", ".store");
303- logger.debug("Created store file {} for {}.", f, storePath);
304- OutputStream trustStoreOs = new FileOutputStream(f);
305- closer.register(trustStoreOs);
306- ByteStreams.copy(trustStoreIs, trustStoreOs);
307- } catch (IOException e) {
308- logger.warn("Failure to write keystore, SSL-enabled servers may fail to start.", e);
309- } finally {
310- try {
311- closer.close();
312- } catch (IOException e) {
313- logger.warn("Failure closing streams.", e);
303+ public InetSocketAddress addressOfNode(int n) {
304+ return new InetSocketAddress(TestUtils.ipOfNode(n), binaryPort);
305+ }
306+
307+ /**
308+ * Returns an {@link AddressTranslater} to use when tests must manually create
309+ * {@link Cluster} instances.
310+ * <p/>
311+ * This translator is necessary because hosts in this cluster do not necessarily use standard ports.
312+ *
313+ * @return an {@link AddressTranslater} to use when tests must manually create
314+ * {@link Cluster} instances.
315+ */
316+ public AddressTranslater addressTranslator() {
317+ return new AddressTranslater() {
318+ @Override
319+ public InetSocketAddress translate(InetSocketAddress address) {
320+ return new InetSocketAddress(address.getAddress(), getBinaryPort());
314321 }
315- }
316- return f;
322+ };
323+ }
324+
325+ /**
326+ * Returns the Cassandra version of this CCM cluster.
327+ * <p/>
328+ * By default the version is equal to {@link #getCassandraVersion()}.
329+ *
330+ * @return The version of this CCM cluster.
331+ */
332+ public VersionNumber getVersion() {
333+ return version;
334+ }
335+
336+ /**
337+ * The number of nodes that were initially created with this CCM instance.
338+ * <p/>
339+ * This does not account for nodes created or removed during the cluster's lifecycle.
340+ *
341+ * @return The number of nodes that were initially created with this CCM instance.
342+ */
343+ public int getInitialNumberOfNodes() {
344+ return initialNumberOfNodes;
345+ }
346+
347+ public File getCcmDir() {
348+ return ccmDir;
349+ }
350+
351+ public File getClusterDir() {
352+ return new File(ccmDir, clusterName);
353+ }
354+
355+ public File getNodeDir(int n) {
356+ return new File(getClusterDir(), "node" + n);
317357 }
318358
319- public static Builder builder(String clusterName) {
320- return new Builder(clusterName);
359+ public File getNodeConfDir(int n) {
360+ return new File(getNodeDir(n), "conf");
321361 }
322362
323- public static CCMBridge.CCMCluster buildCluster(int nbNodes, Cluster.Builder builder) {
324- return CCMCluster.create(nbNodes, builder);
363+ public int getStoragePort() {
364+ return storagePort;
325365 }
326366
327- public static CCMBridge.CCMCluster buildCluster(int nbNodesDC1, int nbNodesDC2, Cluster.Builder builder) {
328- return CCMCluster.create(nbNodesDC1, nbNodesDC2, builder);
367+ public int getThriftPort() {
368+ return thriftPort;
369+ }
370+
371+ public int getBinaryPort() {
372+ return binaryPort;
373+ }
374+
375+ public void setKeepLogs(boolean keepLogs) {
376+ this.keepLogs = keepLogs;
377+ }
378+
379+ @Override
380+ public synchronized void close() {
381+ if (closed)
382+ return;
383+ logger.debug("Closing: " + this);
384+ if (keepLogs) {
385+ executeNoFail(new Runnable() {
386+ @Override
387+ public void run() {
388+ stop();
389+ }
390+ }, false);
391+ logger.info("Error during tests, kept C* logs in " + getCcmDir());
392+ } else {
393+ executeNoFail(new Runnable() {
394+ @Override
395+ public void run() {
396+ remove();
397+ }
398+ }, false);
399+ executeNoFail(new Runnable() {
400+ @Override
401+ public void run() {
402+ org.assertj.core.util.Files.delete(getCcmDir());
403+ }
404+ }, false);
405+ }
406+ closed = true;
407+ logger.debug("Closed: " + this);
329408 }
330409
331410 public void start() {
332- execute(CCM_COMMAND + " start --wait-other-notice --wait-for-binary-proto");
411+ logger.debug("Starting: " + this);
412+ execute(CCM_COMMAND + " start --wait-other-notice --wait-for-binary-proto" + jvmArgs);
333413 }
334414
335- public void stop() {
415+ public synchronized void stop() {
416+ if (closed)
417+ return;
418+ logger.debug("Stopping: " + this);
336419 execute(CCM_COMMAND + " stop");
420+ closed = true;
337421 }
338422
339- public void forceStop() {
423+ public synchronized void forceStop() {
424+ if (closed)
425+ return;
426+ logger.debug("Force stopping: " + this);
340427 execute(CCM_COMMAND + " stop --not-gently");
428+ closed = true;
341429 }
342430
343431 public void start(int n) {
344- logger.info("Starting: " + IP_PREFIX + n);
345- execute(CCM_COMMAND + " node%d start --wait-other-notice --wait-for-binary-proto", n);
346- }
347-
348- public void start(int n, String... jvmArg) {
349- StringBuilder jvmArgs = new StringBuilder("");
350- for (int i = 0; i < jvmArg.length; i++) {
351- jvmArgs.append(" --jvm_arg=");
352- jvmArgs.append(jvmArg[i]);
353- }
354- logger.info("Starting: " + IP_PREFIX + n + " with " + jvmArgs);
355- execute(CCM_COMMAND + " node%d start --wait-other-notice --wait-for-binary-proto %s", n, jvmArgs.toString());
432+ logger.debug(String.format("Starting: node %s (%s%s:%s) in %s", n, TestUtils.IP_PREFIX, n, binaryPort, this));
433+ execute(CCM_COMMAND + " node%d start --wait-other-notice --wait-for-binary-proto" + jvmArgs, n);
356434 }
357435
358436 public void stop(int n) {
359- logger.info("Stopping: " + IP_PREFIX + n);
437+ logger.debug(String.format("Stopping: node %s (%s%s:%s) in %s", n, TestUtils.IP_PREFIX, n, binaryPort, this));
360438 execute(CCM_COMMAND + " node%d stop", n);
361439 }
362440
363- public void stop(String clusterName) {
364- logger.info("Stopping Cluster : " + clusterName);
365- execute(CCM_COMMAND + " stop " + clusterName);
366- }
367-
368441 public void forceStop(int n) {
369- logger.info("Force stopping: " + IP_PREFIX + n);
442+ logger.debug(String.format("Force stopping: node %s (%s%s:%s) in %s", n, TestUtils.IP_PREFIX, n, binaryPort, this));
370443 execute(CCM_COMMAND + " node%d stop --not-gently", n);
371444 }
372445
373- public void remove() {
446+ public synchronized void remove() {
374447 stop();
448+ logger.debug("Removing: " + this);
375449 execute(CCM_COMMAND + " remove");
376450 }
377451
378- public void remove(String clusterName) {
379- stop(clusterName);
380- execute(CCM_COMMAND + " remove " + clusterName);
381- }
382-
383452 public void remove(int n) {
384- logger.info("Removing: " + IP_PREFIX + n);
453+ logger.debug(String.format("Removing: node %s (%s%s:%s) from %s", n, TestUtils.IP_PREFIX, n, binaryPort, this));
385454 execute(CCM_COMMAND + " node%d remove", n);
386455 }
387456
388- public void bootstrapNode(int n) {
389- bootstrapNode(n, null);
390- }
391-
392- public void bootstrapNode(int n, String dc) {
393- if (dc == null)
394- 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);
395- else
396- 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);
397- execute(CCM_COMMAND + " node%d start --wait-other-notice --wait-for-binary-proto", n);
457+ public void add(int n) {
458+ add(1, n);
398459 }
399460
400- public void bootstrapNodeWithPorts(int n, int thriftPort, int storagePort, int binaryPort, int jmxPort, int remoteDebugPort) {
401- String thriftItf = IP_PREFIX + n + ":" + thriftPort;
402- String storageItf = IP_PREFIX + n + ":" + storagePort;
403- String binaryItf = IP_PREFIX + n + ":" + binaryPort;
404- String remoteLogItf = IP_PREFIX + n + ":" + remoteDebugPort;
405- execute(CCM_COMMAND + " add node%d -i %s%d -b -t %s -l %s --binary-itf %s -j %d -r %s -s" + (isDSE ? " --dse" : ""),
406- n, IP_PREFIX, n, thriftItf, storageItf, binaryItf, jmxPort, remoteLogItf);
407- execute(CCM_COMMAND + " node%d start --wait-other-notice --wait-for-binary-proto", n);
461+ public void add(int dc, int n) {
462+ logger.debug(String.format("Adding: node %s (%s%s:%s) to %s", n, TestUtils.IP_PREFIX, n, binaryPort, this));
463+ String thriftItf = TestUtils.ipOfNode(n) + ":" + thriftPort;
464+ String storageItf = TestUtils.ipOfNode(n) + ":" + storagePort;
465+ String binaryItf = TestUtils.ipOfNode(n) + ":" + binaryPort;
466+ String remoteLogItf = TestUtils.ipOfNode(n) + ":" + TestUtils.findAvailablePort();
467+ 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" : ""),
468+ n, dc, TestUtils.IP_PREFIX, n, thriftItf, storageItf, binaryItf, TestUtils.findAvailablePort(), remoteLogItf);
408469 }
409470
410471 public void decommissionNode(int n) {
472+ logger.debug(String.format("Decommissioning: node %s (%s%s:%s) from %s", n, TestUtils.IP_PREFIX, n, binaryPort, this));
411473 execute(CCM_COMMAND + " node%d decommission", n);
412474 }
413475
414- public void updateConfig(Map<String, String> configs) {
476+ public void updateConfig(Map<String, Object> configs) {
415477 StringBuilder confStr = new StringBuilder();
416- for (Map.Entry<String, String> entry : configs.entrySet()) {
417- confStr.append(entry.getKey() + ":" + entry.getValue() + " ");
478+ for (Map.Entry<String, Object> entry : configs.entrySet()) {
479+ confStr
480+ .append(entry.getKey())
481+ .append(":")
482+ .append(entry.getValue())
483+ .append(" ");
418484 }
419485 execute(CCM_COMMAND + " updateconf " + confStr);
420486 }
421487
422- public void updateDSEConfig(Map<String, String> configs) {
488+ public void updateDSEConfig(Map<String, Object> configs) {
423489 StringBuilder confStr = new StringBuilder();
424- for (Map.Entry<String, String> entry : configs.entrySet()) {
425- confStr.append(entry.getKey() + ":" + entry.getValue() + " ");
490+ for (Map.Entry<String, Object> entry : configs.entrySet()) {
491+ confStr
492+ .append(entry.getKey())
493+ .append(":")
494+ .append(entry.getValue())
495+ .append(" ");
426496 }
427497 execute(CCM_COMMAND + " updatedseconf " + confStr);
428498 }
429499
500+ public void updateNodeConfig(int n, String key, Object value) {
501+ updateNodeConfig(n, ImmutableMap.<String, Object>builder().put(key, value).build());
502+ }
503+
504+ public void updateNodeConfig(int n, Map<String, Object> configs) {
505+ StringBuilder confStr = new StringBuilder();
506+ for (Map.Entry<String, Object> entry : configs.entrySet()) {
507+ confStr
508+ .append(entry.getKey())
509+ .append(":")
510+ .append(entry.getValue())
511+ .append(" ");
512+ }
513+ execute(CCM_COMMAND + " node%s updateconf %s", n, confStr);
514+ }
515+
430516 public void setWorkload(int node, String workload) {
431517 execute(CCM_COMMAND + " node%d setworkload %s", node, workload);
432518 }
@@ -434,6 +520,9 @@
434520 private void execute(String command, Object... args) {
435521
436522 String fullCommand = String.format(command, args) + " --config-dir=" + ccmDir;
523+ Closer closer = Closer.create();
524+ // 5 minutes timeout
525+ ExecuteWatchdog watchDog = new ExecuteWatchdog(5 * 60 * 1000);
437526 try {
438527 logger.debug("Executing: " + fullCommand);
439528 CommandLine cli = CommandLine.parse(fullCommand);
@@ -451,9 +540,11 @@
451540 logger.error("ccmerr> " + line);
452541 }
453542 };
454-
543+ closer.register(outStream);
544+ closer.register(errStream);
455545 ExecuteStreamHandler streamHandler = new PumpStreamHandler(outStream, errStream);
456546 executor.setStreamHandler(streamHandler);
547+ executor.setWatchdog(watchDog);
457548
458549 int retValue = executor.execute(cli, ENVIRONMENT_MAP);
459550 if (retValue != 0) {
@@ -461,7 +552,15 @@
461552 throw new RuntimeException();
462553 }
463554 } catch (IOException e) {
555+ if (watchDog.killedProcess())
556+ logger.error("The command {} was killed after 5 minutes", fullCommand);
464557 throw new RuntimeException(String.format("The command %s failed to execute", fullCommand), e);
558+ } finally {
559+ try {
560+ closer.close();
561+ } catch (IOException e) {
562+ Throwables.propagate(e);
563+ }
465564 }
466565 }
467566
@@ -469,319 +568,83 @@
469568 * Waits for a host to be up by pinging the TCP socket directly, without using the Java driver's API.
470569 */
471570 public void waitForUp(int node) {
472- try {
473- InetAddress address = InetAddress.getByName(ipOfNode(node));
474- CCMBridge.busyWaitForPort(address, 9042, true);
475- } catch (UnknownHostException e) {
476- fail("Unknown host " + ipOfNode(node) + "( node " + node + " of CCMBridge)");
477- }
571+ TestUtils.waitUntilPortIsUp(addressOfNode(node));
478572 }
479573
480574 /**
481575 * Waits for a host to be down by pinging the TCP socket directly, without using the Java driver's API.
482576 */
483577 public void waitForDown(int node) {
484- try {
485- InetAddress address = InetAddress.getByName(ipOfNode(node));
486- CCMBridge.busyWaitForPort(address, 9042, false);
487- } catch (UnknownHostException e) {
488- fail("Unknown host " + ipOfNode(node) + "( node " + node + " of CCMBridge)");
489- }
490- }
491-
492- private static void busyWaitForPort(InetAddress address, int port, boolean expectedConnectionState) {
493- long maxAcceptableWaitTime = TimeUnit.SECONDS.toMillis(10);
494- long waitQuantum = TimeUnit.MILLISECONDS.toMillis(500);
495- long waitTimeSoFar = 0;
496- boolean connectionState = !expectedConnectionState;
497-
498- while (connectionState != expectedConnectionState && waitTimeSoFar < maxAcceptableWaitTime) {
499- connectionState = CCMBridge.pingPort(address, port);
500- try {
501- Thread.sleep(waitQuantum);
502- waitTimeSoFar += waitQuantum;
503- } catch (InterruptedException e) {
504- throw new RuntimeException("Interrupted while pinging " + address + ":" + port, e);
505- }
506- }
578+ TestUtils.waitUntilPortIsDown(addressOfNode(node));
507579 }
508580
509- private static boolean pingPort(InetAddress address, int port) {
510- logger.debug("Trying {}:{}...", address, port);
511- boolean connectionSuccessful = false;
512- Socket socket = null;
581+ /**
582+ * <p>
583+ * Extracts a keystore from the classpath into a temporary file.
584+ * </p>
585+ * <p/>
586+ * <p>
587+ * This is needed as the keystore could be part of a built test jar used by other
588+ * projects, and they need to be extracted to a file system so cassandra may use them.
589+ * </p>
590+ *
591+ * @param storePath Path in classpath where the keystore exists.
592+ * @return The generated File.
593+ */
594+ private static File createTempStore(String storePath) {
595+ File f = null;
596+ Closer closer = Closer.create();
513597 try {
514- socket = new Socket(address, port);
515- connectionSuccessful = true;
516- logger.debug("Successfully connected");
598+ InputStream trustStoreIs = CCMBridge.class.getResourceAsStream(storePath);
599+ closer.register(trustStoreIs);
600+ f = File.createTempFile("server", ".store");
601+ logger.debug("Created store file {} for {}.", f, storePath);
602+ OutputStream trustStoreOs = new FileOutputStream(f);
603+ closer.register(trustStoreOs);
604+ ByteStreams.copy(trustStoreIs, trustStoreOs);
517605 } catch (IOException e) {
518- logger.debug("Connection failed");
606+ logger.warn("Failure to write keystore, SSL-enabled servers may fail to start.", e);
519607 } finally {
520- if (socket != null)
521- try {
522- socket.close();
523- } catch (IOException e) {
524- logger.warn("Error closing socket to " + address);
525- }
526- }
527- return connectionSuccessful;
528- }
529-
530- public static String ipOfNode(int nodeNumber) {
531- return IP_PREFIX + Integer.toString(nodeNumber);
532- }
533-
534- public static class terminationHook extends Thread {
535- @Override
536- public void run() {
537- logger.debug("shut down hook task..");
538-
539- if (PerClassSingleNodeCluster.cluster != null) {
540- PerClassSingleNodeCluster.cluster.close();
541- }
542- if (PerClassSingleNodeCluster.ccmBridge == null) {
543- logger.error("No cluster to discard");
544- } else if (PerClassSingleNodeCluster.erroredOut) {
545- PerClassSingleNodeCluster.ccmBridge.remove("test-class");
546- logger.info("Error during tests, kept C* logs in " + PerClassSingleNodeCluster.ccmBridge.ccmDir);
547- } else {
548- PerClassSingleNodeCluster.ccmBridge.remove("test-class");
549- PerClassSingleNodeCluster.ccmBridge.ccmDir.delete();
550- }
551-
552- }
553- }
554-
555- // One cluster for the whole test class
556- public static abstract class PerClassSingleNodeCluster {
557-
558- protected static CCMBridge ccmBridge;
559- private static boolean erroredOut;
560- private static boolean clusterInitialized = false;
561- private static AtomicLong ksNumber;
562- protected String keyspace;
563-
564- protected static InetSocketAddress hostAddress;
565- protected static int[] ports;
566-
567- protected static Cluster cluster;
568- protected static Session session;
569-
570- protected final VersionNumber cassandraVersion = VersionNumber.parse(System.getProperty("cassandra.version"));
571-
572- protected abstract Collection<String> getTableDefinitions();
573-
574- // Give individual tests a chance to customize the cluster configuration
575- protected Cluster.Builder configure(Cluster.Builder builder) {
576- return builder;
577- }
578-
579- public void errorOut() {
580- erroredOut = true;
581- }
582-
583- @BeforeClass(groups = {"isolated", "short", "long"})
584- public void beforeClass() {
585- maybeInitCluster();
586- initKeyspace();
587- }
588-
589- @AfterClass(groups = {"isolated", "short", "long"})
590- public void afterClass() {
591- try {
592- clearSimpleKeyspace();
593- } finally {
594- if (cluster != null) {
595- cluster.close();
596- }
597- }
598- }
599-
600- private void maybeInitCluster() {
601- if (!clusterInitialized) {
602- try {
603- //launch ccm cluster
604- ccmBridge = CCMBridge.builder("test-class").withoutNodes().notStarted().build();
605-
606- ports = new int[5];
607- for (int i = 0; i < 5; i++) {
608- ports[i] = TestUtils.findAvailablePort(11000 + i);
609- }
610-
611- ccmBridge.bootstrapNodeWithPorts(1, ports[0], ports[1], ports[2], ports[3], ports[4]);
612- ksNumber = new AtomicLong(0);
613- erroredOut = false;
614- hostAddress = new InetSocketAddress(InetAddress.getByName(IP_PREFIX + 1), ports[2]);
615-
616- Runtime r = Runtime.getRuntime();
617- r.addShutdownHook(new terminationHook());
618- clusterInitialized = true;
619-
620- } catch (UnknownHostException e) {
621- throw new RuntimeException(e);
622- }
623- }
624-
625- }
626-
627-
628- private void initKeyspace() {
629608 try {
630- Cluster.Builder builder = Cluster.builder();
631-
632- builder = configure(builder);
633-
634- cluster = builder.addContactPointsWithPorts(Collections.singletonList(hostAddress))
635- .withNettyOptions(TestUtils.nonQuietClusterCloseOptions)
636- .build();
637- session = cluster.connect();
638- keyspace = SIMPLE_KEYSPACE + "_" + ksNumber.incrementAndGet();
639- session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, 1));
640-
641- session.execute("USE " + keyspace);
642- for (String tableDef : getTableDefinitions()) {
643- try {
644- session.execute(tableDef);
645- } catch (AlreadyExistsException e) {
646- // It's ok, ignore
647- }
648- }
649- } catch (AlreadyExistsException e) {
650- // It's ok, ignore (not supposed to go there)
651- } catch (NoHostAvailableException e) {
652- erroredOut = true;
653- for (Map.Entry<InetSocketAddress, Throwable> entry : e.getErrors().entrySet())
654- logger.info("Error connecting to " + entry.getKey() + ": " + entry.getValue());
655- throw new RuntimeException(e);
656- } catch (DriverException e) {
657- erroredOut = true;
658- throw e;
659- }
660- }
661-
662- private void clearSimpleKeyspace() {
663- if (keyspace != null) {
664- logger.debug("Removing keyspace {}.", keyspace);
665- // Temporarily extend read timeout to 1 minute to accommodate dropping keyspaces and
666- // tables being slow, particularly in a CI environment.
667- int currentTimeout = cluster.getConfiguration().getSocketOptions().getReadTimeoutMillis();
668- cluster.getConfiguration().getSocketOptions().setReadTimeoutMillis(60000);
669- try {
670- KeyspaceMetadata ksm = cluster.getMetadata().getKeyspace(keyspace);
671- if (ksm != null) {
672- // drop each table individually as this seems to be more dependable than dropping
673- // the entire keyspace at once if it has many tables.
674- if (ksm.getTables().size() > 10) {
675- for (TableMetadata table : ksm.getTables()) {
676- logger.debug("Dropping table {}.{}.", keyspace, table.getName());
677- session.execute("DROP TABLE " + keyspace + "." + table.getName());
678- }
679- }
680- }
681- logger.debug("Dropping keyspace {}.", keyspace);
682- session.execute("DROP KEYSPACE " + keyspace);
683- } finally {
684- cluster.getConfiguration().getSocketOptions().setReadTimeoutMillis(currentTimeout);
685- }
609+ closer.close();
610+ } catch (IOException e) {
611+ logger.warn("Failure closing streams.", e);
686612 }
687613 }
614+ return f;
688615 }
689616
690- public static class CCMCluster {
691-
692- public final Cluster cluster;
693- public final Session session;
694-
695- public final CCMBridge cassandraCluster;
696-
697- private boolean erroredOut;
698-
699- public static CCMCluster create(int nbNodes, Cluster.Builder builder) {
700- if (nbNodes == 0)
701- throw new IllegalArgumentException();
702-
703- CCMBridge ccm = CCMBridge.builder("test").withNodes(nbNodes).build();
704- return new CCMCluster(ccm, builder, nbNodes);
705- }
706-
707- public static CCMCluster create(int nbNodesDC1, int nbNodesDC2, Cluster.Builder builder) {
708- if (nbNodesDC1 == 0)
709- throw new IllegalArgumentException();
710-
711- CCMBridge ccm = CCMBridge.builder("test").withNodes(nbNodesDC1, nbNodesDC2).build();
712- return new CCMCluster(ccm, builder, nbNodesDC1 + nbNodesDC2);
713- }
714-
715- public static CCMCluster create(CCMBridge cassandraCluster, Cluster.Builder builder, int totalNodes) {
716- return new CCMCluster(cassandraCluster, builder, totalNodes);
717- }
718-
719- private CCMCluster(CCMBridge cassandraCluster, Cluster.Builder builder, int totalNodes) {
720- this.cassandraCluster = cassandraCluster;
721- try {
722- String[] contactPoints = new String[totalNodes];
723- for (int i = 0; i < totalNodes; i++)
724- contactPoints[i] = IP_PREFIX + (i + 1);
725-
726- try {
727- Thread.sleep(1000);
728- } catch (InterruptedException e) {
729- fail("Unexpected interruption");
730- }
731- this.cluster = builder.addContactPoints(contactPoints).build();
732- this.session = cluster.connect();
733- } catch (NoHostAvailableException e) {
734- for (Map.Entry<InetSocketAddress, Throwable> entry : e.getErrors().entrySet())
735- logger.info("Error connecting to " + entry.getKey() + ": " + entry.getValue());
736- discard();
737- throw new RuntimeException(e);
738- }
739- }
740-
741- public void errorOut() {
742- erroredOut = true;
743- }
744-
745- public void discard() {
746- if (cluster != null)
747- cluster.close();
748-
749- if (cassandraCluster == null) {
750- logger.error("No cluster to discard");
751- } else if (erroredOut) {
752- cassandraCluster.stop();
753- logger.info("Error during tests, kept C* logs in " + cassandraCluster.ccmDir);
754- } else {
755- cassandraCluster.remove();
756- cassandraCluster.ccmDir.delete();
757- }
758- }
617+ @Override
618+ public String toString() {
619+ return "CCM cluster " + clusterName;
759620 }
760621
761622 /**
762- * use {@link #builder(String)} to get an instance
623+ * use {@link #builder()} to get an instance
763624 */
764625 public static class Builder {
765- private final String clusterName;
766- private Integer[] nodes = {1};
626+ private static final AtomicInteger COUNTER = new AtomicInteger(0);
627+ private final String clusterName = "test_" + COUNTER.incrementAndGet();
628+ int[] nodes = {1};
767629 private boolean start = true;
768- private boolean isDSE = IS_DSE;
769- private String cassandraInstallArgs = CASSANDRA_INSTALL_ARGS;
770- private String[] startOptions = new String[0];
771-
772- private Map<String, String> cassandraConfiguration = Maps.newHashMap();
773-
774- private Map<String, String> dseConfiguration = Maps.newHashMap();
775-
776-
777- Builder(String clusterName) {
778- this.clusterName = clusterName;
630+ private boolean isDSE = isDSE();
631+ private String cassandraVersion = getCassandraVersion();
632+ private Set<String> createOptions = new LinkedHashSet<String>();
633+ private Set<String> jvmArgs = new LinkedHashSet<String>();
634+ private final Map<String, Object> cassandraConfiguration = Maps.newHashMap();
635+ private final Map<String, Object> dseConfiguration = Maps.newHashMap();
636+ // -1 means random
637+ private int thriftPort = -1;
638+ private int binaryPort = -1;
639+ private int storagePort = -1;
640+
641+ private Builder() {
779642 }
780643
781644 /**
782- * Number of nodes for each DC. Defaults to [1] (1 DC with 1 node)
645+ * Number of hosts for each DC. Defaults to [1] (1 DC with 1 node)
783646 */
784- public Builder withNodes(Integer... nodes) {
647+ public Builder withNodes(int... nodes) {
785648 this.nodes = nodes;
786649 return this;
787650 }
@@ -790,21 +653,30 @@
790653 return withNodes();
791654 }
792655
793- public Builder withSSL(boolean requireClientAuth) {
656+ /**
657+ * Enables SSL encryption.
658+ */
659+ public Builder withSSL() {
794660 cassandraConfiguration.put("client_encryption_options.enabled", "true");
795661 cassandraConfiguration.put("client_encryption_options.keystore", DEFAULT_SERVER_KEYSTORE_FILE.getAbsolutePath());
796662 cassandraConfiguration.put("client_encryption_options.keystore_password", DEFAULT_SERVER_KEYSTORE_PASSWORD);
663+ return this;
664+ }
797665
798- if (requireClientAuth) {
799- cassandraConfiguration.put("client_encryption_options.require_client_auth", "true");
800- cassandraConfiguration.put("client_encryption_options.truststore", DEFAULT_SERVER_TRUSTSTORE_FILE.getAbsolutePath());
801- cassandraConfiguration.put("client_encryption_options.truststore_password", DEFAULT_SERVER_TRUSTSTORE_PASSWORD);
802- }
666+ /**
667+ * Enables client authentication.
668+ * This also enables encryption ({@link #withSSL()}.
669+ */
670+ public Builder withAuth() {
671+ withSSL();
672+ cassandraConfiguration.put("client_encryption_options.require_client_auth", "true");
673+ cassandraConfiguration.put("client_encryption_options.truststore", DEFAULT_SERVER_TRUSTSTORE_FILE.getAbsolutePath());
674+ cassandraConfiguration.put("client_encryption_options.truststore_password", DEFAULT_SERVER_TRUSTSTORE_PASSWORD);
803675 return this;
804676 }
805677
806678 /**
807- * Whether to start the cluster immediately (defaults to true if this is never called)
679+ * Whether to start the cluster immediately (defaults to true if this is never called).
808680 */
809681 public Builder notStarted() {
810682 this.start = false;
@@ -812,46 +684,96 @@
812684 }
813685
814686 /**
815- * Defaults to system property cassandra.version
687+ * Sets this cluster to be a DSE cluster (defaults to {@link #isDSE()} if this is never called).
816688 */
817- public Builder withCassandraVersion(String cassandraVersion) {
818- this.cassandraInstallArgs = "-v " + cassandraVersion;
819- this.isDSE = false;
689+ public Builder withDSE() {
690+ this.isDSE = true;
820691 return this;
821692 }
822693
823- public Builder withDSEVersion(String dseVersion) {
824- this.cassandraInstallArgs = "-v " + dseVersion + " --dse";
825- this.isDSE = true;
694+ /**
695+ * The Cassandra or DSE version to use.
696+ *
697+ * Defaults to {@link #getCassandraVersion()}.
698+ */
699+ public Builder withVersion(String cassandraVersion) {
700+ this.cassandraVersion = cassandraVersion;
826701 return this;
827702 }
828703
829704 /**
830- * Free-form options that will be added at the end of the start command
705+ * Free-form options that will be added at the end of the {@code ccm create} command.
831706 */
832- public Builder withStartOptions(String... options) {
833- this.startOptions = options;
707+ public Builder withCreateOptions(String... createOptions) {
708+ Collections.addAll(this.createOptions, createOptions);
834709 return this;
835710 }
836711
837712 /**
838713 * Customizes entries in cassandra.yaml (can be called multiple times)
839714 */
840- public Builder withCassandraConfiguration(String key, String value) {
715+ public Builder withCassandraConfiguration(String key, Object value) {
841716 this.cassandraConfiguration.put(key, value);
842717 return this;
843718 }
844719
845- public Builder withDSEConfiguration(String key, String value) {
720+ /**
721+ * Customizes entries in dse.yaml (can be called multiple times)
722+ */
723+ public Builder withDSEConfiguration(String key, Object value) {
846724 this.dseConfiguration.put(key, value);
847725 return this;
848726 }
849727
728+ /**
729+ * JVM args to use when starting hosts.
730+ * System properties should be provided one by one, as a string in the form:
731+ * {@code -Dname=value}.
732+ */
733+ public Builder withJvmArgs(String... jvmArgs) {
734+ Collections.addAll(this.jvmArgs, jvmArgs);
735+ return this;
736+ }
737+
738+ public Builder withStoragePort(int port) {
739+ storagePort = port;
740+ return this;
741+ }
742+
743+ public Builder withThriftPort(int port) {
744+ thriftPort = port;
745+ return this;
746+ }
747+
748+ public Builder withBinaryPort(int port) {
749+ binaryPort = port;
750+ return this;
751+ }
752+
850753 public CCMBridge build() {
851- CCMBridge ccm = new CCMBridge(isDSE);
754+ // be careful NOT to alter internal state (hashCode/equals) during build!
755+ int initialNumberOfNodes = 0;
756+ for (int nodesPerDc : nodes) {
757+ initialNumberOfNodes += nodesPerDc;
758+ }
759+ int storagePort = this.storagePort == -1 ? findAvailablePort() : this.storagePort;
760+ int thriftPort = this.thriftPort == -1 ? findAvailablePort() : this.thriftPort;
761+ int binaryPort = this.binaryPort == -1 ? findAvailablePort() : this.binaryPort;
762+ VersionNumber version = VersionNumber.parse(cassandraVersion);
763+ final CCMBridge ccm = new CCMBridge(clusterName, isDSE, version, storagePort, thriftPort, binaryPort, joinJvmArgs(), initialNumberOfNodes);
764+ Runtime.getRuntime().addShutdownHook(new Thread() {
765+ @Override
766+ public void run() {
767+ ccm.close();
768+ }
769+ });
852770 ccm.execute(buildCreateCommand());
853- if (!cassandraConfiguration.isEmpty())
854- ccm.updateConfig(cassandraConfiguration);
771+ updateNodeConf(ccm);
772+ HashMap<String, Object> config = new HashMap<String, Object>(cassandraConfiguration);
773+ config.put("storage_port", storagePort);
774+ config.put("rpc_port", thriftPort);
775+ config.put("native_transport_port", binaryPort);
776+ ccm.updateConfig(config);
855777 if (!dseConfiguration.isEmpty())
856778 ccm.updateDSEConfig(dseConfiguration);
857779 if (start)
@@ -859,16 +781,123 @@
859781 return ccm;
860782 }
861783
784+ private String joinJvmArgs() {
785+ StringBuilder allJvmArgs = new StringBuilder("");
786+ for (String jvmArg : jvmArgs) {
787+ allJvmArgs.append(" --jvm_arg=");
788+ allJvmArgs.append(jvmArg);
789+ }
790+ return allJvmArgs.toString();
791+ }
792+
862793 private String buildCreateCommand() {
863794 StringBuilder result = new StringBuilder(CCM_COMMAND + " create");
864- result.append(" " + clusterName);
865- result.append(" -i" + IP_PREFIX);
866- result.append(" " + cassandraInstallArgs);
867- if (nodes.length > 0)
868- result.append(" -n " + Joiner.on(":").join(nodes));
869- if (startOptions.length > 0)
870- result.append(" " + Joiner.on(" ").join(startOptions));
795+ result.append(" ").append(clusterName);
796+ result.append(" -i ").append(TestUtils.IP_PREFIX);
797+ result.append(" ");
798+ if (cassandraVersion != null)
799+ result.append("-v ").append(cassandraVersion);
800+ else
801+ result.append(CASSANDRA_INSTALL_ARGS);
802+ if (nodes.length > 0) {
803+ result.append(" -n ");
804+ for (int i = 0; i < nodes.length; i++) {
805+ int node = nodes[i];
806+ if (i > 0)
807+ result.append(':');
808+ result.append(node);
809+ }
810+ }
811+ if (!createOptions.isEmpty())
812+ result.append(" ").append(Joiner.on(" ").join(createOptions));
871813 return result.toString();
872814 }
815+
816+ /**
817+ * This is a workaround for an oddity in CCM:
818+ * when we create a cluster with -n option and
819+ * non-standard ports, the node.conf files are not updated accordingly.
820+ */
821+ private void updateNodeConf(CCMBridge ccm) {
822+ int n = 1;
823+ Closer closer = Closer.create();
824+ try {
825+ for (int dc = 1; dc <= nodes.length; dc++) {
826+ int nodesInDc = nodes[dc - 1];
827+ for (int i = 0; i < nodesInDc; i++) {
828+ int jmxPort = findAvailablePort();
829+ int debugPort = findAvailablePort();
830+ logger.debug("Node {} in cluster {} using JMX port {} and debug port {}", n, clusterName, jmxPort, debugPort);
831+ File nodeConf = new File(ccm.getNodeDir(n), "node.conf");
832+ File nodeConf2 = new File(ccm.getNodeDir(n), "node.conf.tmp");
833+ BufferedReader br = closer.register(new BufferedReader(new FileReader(nodeConf)));
834+ PrintWriter pw = closer.register(new PrintWriter(new FileWriter(nodeConf2)));
835+ String line;
836+ while ((line = br.readLine()) != null) {
837+ line = line
838+ .replace("9042", Integer.toString(ccm.binaryPort))
839+ .replace("9160", Integer.toString(ccm.thriftPort))
840+ .replace("7000", Integer.toString(ccm.storagePort));
841+ if (line.startsWith("jmx_port")) {
842+ line = String.format("jmx_port: '%s'", jmxPort);
843+ } else if (line.startsWith("remote_debug_port")) {
844+ line = String.format("remote_debug_port: %s:%s", TestUtils.ipOfNode(n), debugPort);
845+ }
846+ pw.println(line);
847+ }
848+ pw.flush();
849+ pw.close();
850+ Files.move(nodeConf2, nodeConf);
851+ n++;
852+ }
853+ }
854+ } catch (IOException e) {
855+ Throwables.propagate(e);
856+ } finally {
857+ try {
858+ closer.close();
859+ } catch (IOException e) {
860+ Throwables.propagate(e);
861+ }
862+ }
863+ }
864+
865+ @Override
866+ @SuppressWarnings("SimplifiableIfStatement")
867+ public boolean equals(Object o) {
868+ // do not include cluster name and start, only
869+ // properties relevant to the settings of the cluster
870+ if (this == o) return true;
871+ if (o == null || getClass() != o.getClass()) return false;
872+ Builder builder = (Builder) o;
873+ if (isDSE != builder.isDSE) return false;
874+ if (thriftPort != builder.thriftPort) return false;
875+ if (binaryPort != builder.binaryPort) return false;
876+ if (storagePort != builder.storagePort) return false;
877+ if (!Arrays.equals(nodes, builder.nodes)) return false;
878+ if (!createOptions.equals(builder.createOptions)) return false;
879+ if (!jvmArgs.equals(builder.jvmArgs)) return false;
880+ if (!dseConfiguration.equals(builder.dseConfiguration)) return false;
881+ if (!cassandraConfiguration.equals(builder.cassandraConfiguration)) return false;
882+ return cassandraVersion.equals(builder.cassandraVersion);
883+ }
884+
885+ @Override
886+ public int hashCode() {
887+ // do not include cluster name and start, only
888+ // properties relevant to the settings of the cluster
889+ int result = Arrays.hashCode(nodes);
890+ result = 31 * result + (isDSE ? 1 : 0);
891+ result = 31 * result + createOptions.hashCode();
892+ result = 31 * result + jvmArgs.hashCode();
893+ result = 31 * result + cassandraConfiguration.hashCode();
894+ result = 31 * result + dseConfiguration.hashCode();
895+ result = 31 * result + thriftPort;
896+ result = 31 * result + binaryPort;
897+ result = 31 * result + storagePort;
898+ result = 31 * result + cassandraVersion.hashCode();
899+ return result;
900+ }
873901 }
902+
874903 }
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 +749 −0
@@ -0,0 +1,749 @@
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.AddressTranslater;
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+
46+@SuppressWarnings("unused")
47+public class CCMTestsSupport {
48+
49+ private static final Logger LOGGER = LoggerFactory.getLogger(CCMTestsSupport.class);
50+
51+ private static final AtomicInteger CCM_COUNTER = new AtomicInteger(1);
52+
53+ private static final List<String> TEST_GROUPS = Lists.newArrayList("isolated", "short", "long", "stress", "duration");
54+
55+ private static class CCMTestConfig {
56+
57+ private final List<CCMConfig> annotations;
58+
59+ private CCMBridge.Builder ccmBuilder;
60+
61+ public CCMTestConfig(List<CCMConfig> annotations) {
62+ this.annotations = annotations;
63+ }
64+
65+ private int[] numberOfNodes() {
66+ for (CCMConfig ann : annotations) {
67+ if (ann != null && ann.numberOfNodes().length > 0)
68+ return ann.numberOfNodes();
69+ }
70+ return new int[]{1};
71+ }
72+
73+ @SuppressWarnings("SimplifiableIfStatement")
74+ private String version() {
75+ for (CCMConfig ann : annotations) {
76+ if (ann != null && !ann.version().isEmpty())
77+ return ann.version();
78+ }
79+ return null;
80+ }
81+
82+ @SuppressWarnings("SimplifiableIfStatement")
83+ private boolean dse() {
84+ for (CCMConfig ann : annotations) {
85+ if (ann != null && ann.dse().length > 0)
86+ return ann.dse()[0];
87+ }
88+ return false;
89+ }
90+
91+ @SuppressWarnings("SimplifiableIfStatement")
92+ private boolean ssl() {
93+ for (CCMConfig ann : annotations) {
94+ if (ann != null && ann.ssl().length > 0)
95+ return ann.ssl()[0];
96+ }
97+ return false;
98+ }
99+
100+ @SuppressWarnings("SimplifiableIfStatement")
101+ private boolean auth() {
102+ for (CCMConfig ann : annotations) {
103+ if (ann != null && ann.auth().length > 0)
104+ return ann.auth()[0];
105+ }
106+ return false;
107+ }
108+
109+ @SuppressWarnings("SimplifiableIfStatement")
110+ private Map<String, Object> config() {
111+ Map<String, Object> config = new HashMap<String, Object>();
112+ for (int i = annotations.size() - 1; i == 0; i--) {
113+ CCMConfig ann = annotations.get(i);
114+ addConfigOptions(ann.config(), config);
115+ }
116+ return config;
117+ }
118+
119+ @SuppressWarnings("SimplifiableIfStatement")
120+ private Map<String, Object> dseConfig() {
121+ Map<String, Object> config = new HashMap<String, Object>();
122+ for (int i = annotations.size() - 1; i >= 0; i--) {
123+ CCMConfig ann = annotations.get(i);
124+ addConfigOptions(ann.dseConfig(), config);
125+ }
126+ return config;
127+ }
128+
129+ private void addConfigOptions(String[] conf, Map<String, Object> config) {
130+ for (String aConf : conf) {
131+ String[] tokens = aConf.split(":");
132+ String key = tokens[0];
133+ String value = tokens[1];
134+ config.put(key, value);
135+ }
136+ }
137+
138+ @SuppressWarnings("SimplifiableIfStatement")
139+ private Set<String> jvmArgs() {
140+ Set<String> args = new LinkedHashSet<String>();
141+ for (int i = annotations.size() - 1; i >= 0; i--) {
142+ CCMConfig ann = annotations.get(i);
143+ Collections.addAll(args, ann.jvmArgs());
144+ }
145+ return args;
146+ }
147+
148+ @SuppressWarnings("SimplifiableIfStatement")
149+ private Set<String> startOptions() {
150+ Set<String> args = new LinkedHashSet<String>();
151+ for (int i = annotations.size() - 1; i >= 0; i--) {
152+ CCMConfig ann = annotations.get(i);
153+ Collections.addAll(args, ann.options());
154+ }
155+ return args;
156+ }
157+
158+ @SuppressWarnings("SimplifiableIfStatement")
159+ private boolean createCcm() {
160+ for (CCMConfig ann : annotations) {
161+ if (ann != null && ann.createCcm().length > 0)
162+ return ann.createCcm()[0];
163+ }
164+ return true;
165+ }
166+
167+ @SuppressWarnings("SimplifiableIfStatement")
168+ private boolean createCluster() {
169+ for (CCMConfig ann : annotations) {
170+ if (ann != null && ann.createCluster().length > 0)
171+ return ann.createCluster()[0];
172+ }
173+ return true;
174+ }
175+
176+ @SuppressWarnings("SimplifiableIfStatement")
177+ private boolean createSession() {
178+ for (CCMConfig ann : annotations) {
179+ if (ann != null && ann.createSession().length > 0)
180+ return ann.createSession()[0];
181+ }
182+ return true;
183+ }
184+
185+ @SuppressWarnings("SimplifiableIfStatement")
186+ private boolean createKeyspace() {
187+ for (CCMConfig ann : annotations) {
188+ if (ann != null && ann.createKeyspace().length > 0)
189+ return ann.createKeyspace()[0];
190+ }
191+ return true;
192+ }
193+
194+ @SuppressWarnings("SimplifiableIfStatement")
195+ private boolean dirtiesContext() {
196+ for (CCMConfig ann : annotations) {
197+ if (ann != null && ann.dirtiesContext().length > 0)
198+ return ann.dirtiesContext()[0];
199+ }
200+ return false;
201+ }
202+
203+ private CCMBridge.Builder ccmBuilder() {
204+ if (ccmBuilder == null) {
205+ ccmBuilder = CCMBridge.builder()
206+ .withNodes(numberOfNodes());
207+ if (version() != null)
208+ ccmBuilder.withVersion(version());
209+ if (dse())
210+ ccmBuilder.withDSE();
211+ if (ssl())
212+ ccmBuilder.withSSL();
213+ if (auth())
214+ ccmBuilder.withAuth();
215+ for (Map.Entry<String, Object> entry : config().entrySet()) {
216+ ccmBuilder.withCassandraConfiguration(entry.getKey(), entry.getValue());
217+ }
218+ for (Map.Entry<String, Object> entry : dseConfig().entrySet()) {
219+ ccmBuilder.withDSEConfiguration(entry.getKey(), entry.getValue());
220+ }
221+ for (String option : startOptions()) {
222+ ccmBuilder.withCreateOptions(option);
223+ }
224+ for (String arg : jvmArgs()) {
225+ ccmBuilder.withJvmArgs(arg);
226+ }
227+ }
228+ return ccmBuilder;
229+ }
230+
231+ private Cluster.Builder clusterBuilder(Object testInstance) throws Exception {
232+ String methodName = null;
233+ Class<?> clazz = null;
234+ for (int i = annotations.size() - 1; i >= 0; i--) {
235+ CCMConfig ann = annotations.get(i);
236+ if (!ann.clusterProvider().isEmpty()) {
237+ methodName = ann.clusterProvider();
238+ }
239+ if (!ann.clusterProviderClass().equals(CCMConfig.Undefined.class)) {
240+ clazz = ann.clusterProviderClass();
241+ }
242+ }
243+ if (methodName == null)
244+ methodName = "createClusterBuilder";
245+ if (clazz == null)
246+ clazz = testInstance.getClass();
247+ Method method = locateMethod(methodName, clazz);
248+ assert Cluster.Builder.class.isAssignableFrom(method.getReturnType());
249+ if (Modifier.isStatic(method.getModifiers())) {
250+ return (Cluster.Builder) method.invoke(null);
251+ } else {
252+ Object receiver = testInstance.getClass().equals(clazz) ? testInstance : instantiate(clazz);
253+ return (Cluster.Builder) method.invoke(receiver);
254+ }
255+ }
256+
257+ @SuppressWarnings("unchecked")
258+ private Collection<String> fixtures(Object testInstance) throws Exception {
259+ String methodName = null;
260+ Class<?> clazz = null;
261+ for (int i = annotations.size() - 1; i >= 0; i--) {
262+ CCMConfig ann = annotations.get(i);
263+ if (!ann.fixturesProvider().isEmpty()) {
264+ methodName = ann.fixturesProvider();
265+ }
266+ if (!ann.fixturesProviderClass().equals(CCMConfig.Undefined.class)) {
267+ clazz = ann.fixturesProviderClass();
268+ }
269+ }
270+ if (methodName == null)
271+ methodName = "createTestFixtures";
272+ if (clazz == null)
273+ clazz = testInstance.getClass();
274+ Method method = locateMethod(methodName, clazz);
275+ assert Collection.class.isAssignableFrom(method.getReturnType());
276+ assert method.getGenericReturnType() instanceof ParameterizedType;
277+ assert String.class.equals(((ParameterizedType) method.getGenericReturnType()).getActualTypeArguments()[0]);
278+ if (Modifier.isStatic(method.getModifiers())) {
279+ return (Collection<String>) method.invoke(null);
280+ } else {
281+ Object receiver = testInstance.getClass().equals(clazz) ? testInstance : instantiate(clazz);
282+ return (Collection<String>) method.invoke(receiver);
283+ }
284+ }
285+
286+ }
287+
288+ private static class CCMTestContextLoader extends CacheLoader<CCMBridge.Builder, CCMBridge> {
289+
290+ @Override
291+ public CCMBridge load(CCMBridge.Builder builder) {
292+ return builder.build();
293+ }
294+
295+ }
296+
297+ private static class CCMTestContextWeigher implements Weigher<CCMBridge.Builder, CCMBridge> {
298+ @Override
299+ public int weigh(CCMBridge.Builder key, CCMBridge value) {
300+ return value.getInitialNumberOfNodes();
301+ }
302+ }
303+
304+ private static class CCMTestContextRemovalListener implements RemovalListener<CCMBridge.Builder, CCMBridge> {
305+
306+ @Override
307+ public void onRemoval(RemovalNotification<CCMBridge.Builder, CCMBridge> notification) {
308+ if (notification.getValue() != null) {
309+ LOGGER.debug("Evicting: " + notification.getValue());
310+ notification.getValue().close();
311+ }
312+ }
313+
314+ }
315+
316+ /**
317+ * A LoadingCache that stores running CCM clusters.
318+ */
319+ private static final LoadingCache<CCMBridge.Builder, CCMBridge> CACHE;
320+
321+ static {
322+ long maximumWeight;
323+ String numberOfNodes = System.getProperty("ccm.maxNumberOfNodes");
324+ if (numberOfNodes == null) {
325+ long freeMemoryMB = TestUtils.getFreeMemoryMB();
326+ if (freeMemoryMB < 1000)
327+ LOGGER.warn("Available memory below 1GB: {}MB, CCM clusters might fail to start", freeMemoryMB);
328+ // CCM nodes are started with -Xms500M -Xmx500M
329+ // leave at least 500 MB out, with a minimum of 1 node and a maximum of 10 nodes
330+ maximumWeight = Math.min(10, Math.max(1, (freeMemoryMB / 500) - 1));
331+ } else {
332+ maximumWeight = Integer.parseInt(numberOfNodes);
333+ }
334+ LOGGER.info("Maximum number of running CCM nodes: {}", maximumWeight);
335+ CACHE = CacheBuilder.newBuilder()
336+ .initialCapacity(1)
337+ .maximumWeight(maximumWeight)
338+ .weigher(new CCMTestContextWeigher())
339+ .removalListener(new CCMTestContextRemovalListener())
340+ .build(new CCMTestContextLoader());
341+ }
342+ private TestMode testMode;
343+
344+ private CCMTestConfig ccmTestConfig;
345+
346+ protected CCMBridge ccm;
347+
348+ protected Cluster cluster;
349+
350+ protected Session session;
351+
352+ protected String keyspace;
353+
354+ private boolean erroredOut = false;
355+
356+ private Closer closer;
357+
358+ /**
359+ * Hook invoked at the beginning of a test class to initialize CCM test context.
360+ *
361+ * @throws Exception
362+ */
363+ @BeforeClass(groups = {"isolated", "short", "long", "stress", "duration"})
364+ public void beforeTestClass() throws Exception {
365+ beforeTestClass(this);
366+ }
367+
368+ /**
369+ * Hook invoked at the beginning of a test class to initialize CCM test context.
370+ * <p/>
371+ * Useful when this class is not a superclass of the test being run.
372+ *
373+ * @throws Exception
374+ */
375+ public void beforeTestClass(Object testInstance) throws Exception {
376+ testMode = determineTestMode(testInstance.getClass());
377+ if (testMode == PER_CLASS) {
378+ closer = Closer.create();
379+ initTestContext(testInstance, null);
380+ initTestCluster(testInstance);
381+ initTestSession();
382+ initTestKeyspace();
383+ initTestFixtures(testInstance);
384+ }
385+ }
386+
387+ /**
388+ * Hook executed before each test method.
389+ *
390+ * @throws Exception
391+ */
392+ @BeforeMethod(groups = {"isolated", "short", "long", "stress", "duration"})
393+ public void beforeTestMethod(Method testMethod) throws Exception {
394+ beforeTestMethod(this, testMethod);
395+ }
396+
397+ /**
398+ * Hook executed before each test method.
399+ * <p/>
400+ * Useful when this class is not a superclass of the test being run.
401+ *
402+ * @throws Exception
403+ */
404+ public void beforeTestMethod(Object testInstance, Method testMethod) throws Exception {
405+ if (isCcmEnabled(testMethod)) {
406+ if (closer == null)
407+ closer = Closer.create();
408+ if (testMode == PER_METHOD || erroredOut) {
409+ initTestContext(testInstance, testMethod);
410+ initTestCluster(testInstance);
411+ initTestSession();
412+ initTestKeyspace();
413+ initTestFixtures(testInstance);
414+ }
415+ assert ccmTestConfig != null;
416+ assert !ccmTestConfig.createCcm() || ccm != null;
417+ }
418+ }
419+
420+ /**
421+ * Hook executed after each test method.
422+ */
423+ @AfterMethod(groups = {"isolated", "short", "long", "stress", "duration"}, alwaysRun = true)
424+ public void afterTestMethod(ITestResult tr) {
425+ if (isCcmEnabled(tr.getMethod().getConstructorOrMethod().getMethod())) {
426+ if (tr.getStatus() == ITestResult.FAILURE) {
427+ errorOut();
428+ }
429+ if (erroredOut || testMode == PER_METHOD) {
430+ closeCloseables();
431+ closeTestCluster();
432+ }
433+ if (testMode == PER_METHOD)
434+ closeTestContext();
435+ }
436+ }
437+ /**
438+ * Hook executed after each test class.
439+ */
440+ @AfterClass(groups = {"isolated", "short", "long", "stress", "duration"}, alwaysRun = true)
441+ public void afterTestClass() {
442+ if (testMode == PER_CLASS) {
443+ closeCloseables();
444+ closeTestCluster();
445+ closeTestContext();
446+ }
447+ }
448+
449+ /**
450+ * Returns the cluster builder to use for this test.
451+ * <p/>
452+ * The default implementation returns a vanilla builder.
453+ * <p/>
454+ * It's not required to call {@link com.datastax.driver.core.Cluster.Builder#addContactPointsWithPorts},
455+ * it will be done automatically.
456+ *
457+ * @return The cluster builder to use for the tests.
458+ */
459+ public Cluster.Builder createClusterBuilder() {
460+ return Cluster.builder();
461+ }
462+
463+ /**
464+ * Returns an alternate cluster builder to use for this test,
465+ * with no event debouncing.
466+ * <p/>
467+ * It's not required to call {@link com.datastax.driver.core.Cluster.Builder#addContactPointsWithPorts},
468+ * it will be done automatically.
469+ *
470+ * @return The cluster builder to use for the tests.
471+ */
472+ public Cluster.Builder createClusterBuilderNoDebouncing() {
473+ return Cluster.builder().withQueryOptions(TestUtils.nonDebouncingQueryOptions());
474+ }
475+
476+ /**
477+ * The CQL statements to execute before the tests in this class.
478+ * Useful to create tables or other objects inside the test keyspace,
479+ * or to insert test data.
480+ * <p/>
481+ * Statements do not need to be qualified with keyspace name.
482+ * <p/>
483+ * The default implementation returns an empty list (no fixtures required).
484+ *
485+ * @return The DDL statements to execute before the tests.
486+ */
487+ public Collection<String> createTestFixtures() {
488+ return Collections.emptyList();
489+ }
490+
491+ /**
492+ * Signals that the test has encountered an unexpected error.
493+ * <p/>
494+ * This method is automatically called when a test finishes with an unexpected exception
495+ * being thrown, but it is also possible to manually invoke it.
496+ * <p/>
497+ * Calling this method will close the current cluster and session.
498+ * The CCM data directory will be kept after the test session is finished,
499+ * for debugging purposes
500+ * <p/>
501+ * This method should not be called before the test has started, nor after the test is finished.
502+ */
503+ public void errorOut() {
504+ erroredOut = true;
505+ if (ccm != null)
506+ ccm.setKeepLogs(true);
507+ }
508+
509+ /**
510+ * Returns the contact points to use to contact the CCM cluster.
511+ * <p/>
512+ * This method returns as many contact points as the number of nodes initially present in the CCM cluster,
513+ * according to {@link CCMConfig} annotations.
514+ * <p/>
515+ * On a multi-DC setup, this will include nodes in all data centers.
516+ * <p/>
517+ * This method should not be called before the test has started, nor after the test is finished.
518+ *
519+ * @return the contact points to use to contact the CCM cluster.
520+ */
521+ public List<InetSocketAddress> getInitialContactPoints() {
522+ assert ccmTestConfig != null;
523+ List<InetSocketAddress> contactPoints = new ArrayList<InetSocketAddress>();
524+ int n = 1;
525+ int[] numberOfNodes = ccmTestConfig.numberOfNodes();
526+ for (int dc = 1; dc <= numberOfNodes.length; dc++) {
527+ int nodesInDc = numberOfNodes[dc - 1];
528+ for (int i = 0; i < nodesInDc; i++) {
529+ contactPoints.add(new InetSocketAddress(ipOfNode(n), ccm.getBinaryPort()));
530+ n++;
531+ }
532+ }
533+ return contactPoints;
534+ }
535+
536+ /**
537+ * Returns the address of the {@code nth} host in the CCM cluster (counting from 1, i.e.,
538+ * {@code getHostAddress(1)} returns the address of the first node.
539+ * <p/>
540+ * In multi-DC setups, nodes are numbered in ascending order of their datacenter number.
541+ * E.g. with 2 DCs and 3 nodes in each DC, the first node in DC 2 is number 4.
542+ * <p/>
543+ * This method should not be called before the test has started, nor after the test is finished.
544+ *
545+ * @return the address of the {@code nth} host in the cluster.
546+ */
547+ public InetSocketAddress getHostAddress(int n) {
548+ return ccm.addressOfNode(n);
549+ }
550+
551+ /**
552+ * Returns an {@link AddressTranslater} to use when tests must manually create
553+ * {@link Cluster} instances.
554+ * <p/>
555+ * This translator is necessary because hosts create with this class do not use standard ports.
556+ * <p/>
557+ * This method should not be called before the test has started, nor after the test is finished.
558+ *
559+ * @return an {@link AddressTranslater} to use when tests must manually create
560+ * {@link Cluster} instances.
561+ */
562+ public AddressTranslater getAddressTranslator() {
563+ return ccm.addressTranslator();
564+ }
565+
566+ /**
567+ * Registers the given {@link Closeable} to be closed at the end of the current test method.
568+ * <p/>
569+ * This method should not be called before the test has started, nor after the test is finished.
570+ *
571+ * @param closeable The closeable to close
572+ * @return The closeable to close
573+ */
574+ public <T extends Closeable> T register(T closeable) {
575+ closer.register(closeable);
576+ return closeable;
577+ }
578+
579+ private void initTestContext(Object testInstance, Method testMethod) throws Exception {
580+ erroredOut = false;
581+ ccmTestConfig = createCCMTestConfig(testInstance, testMethod);
582+ assert ccmTestConfig != null;
583+ if (ccmTestConfig.createCcm()) {
584+ if (ccmTestConfig.dirtiesContext()) {
585+ ccm = ccmTestConfig.ccmBuilder().build();
586+ LOGGER.debug("Using dedicated {}", ccm);
587+ } else {
588+ CCMBridge.Builder key = ccmTestConfig.ccmBuilder();
589+ ccm = CACHE.getIfPresent(key);
590+ if (ccm != null) {
591+ LOGGER.debug("Reusing {}", ccm);
592+ } else {
593+ try {
594+ ccm = CACHE.get(ccmTestConfig.ccmBuilder());
595+ LOGGER.debug("Using newly-created {}", ccm);
596+ } catch (ExecutionException e) {
597+ Throwables.propagate(e);
598+ }
599+ }
600+ }
601+ assert ccm != null;
602+ }
603+ }
604+
605+ private void initTestCluster(Object testInstance) throws Exception {
606+ if (ccmTestConfig.createCcm() && ccmTestConfig.createCluster()) {
607+ Cluster.Builder builder = ccmTestConfig.clusterBuilder(testInstance);
608+ // add contact points only if the provided builder didn't do so
609+ if (builder.getContactPoints().isEmpty())
610+ builder.addContactPointsWithPorts(getInitialContactPoints());
611+ builder.withAddressTranslater(ccm.addressTranslator());
612+ cluster = register(builder.build());
613+ cluster.init();
614+ }
615+ }
616+
617+ private void initTestSession() throws Exception {
618+ if (ccmTestConfig.createCcm() && ccmTestConfig.createCluster() && ccmTestConfig.createSession())
619+ session = register(cluster.connect());
620+ }
621+
622+ private void initTestKeyspace() {
623+ if (ccmTestConfig.createCcm() && ccmTestConfig.createCluster() && ccmTestConfig.createSession() && ccmTestConfig.createKeyspace()) {
624+ try {
625+ keyspace = TestUtils.getAvailableKeyspaceName();
626+ LOGGER.debug("Using keyspace " + keyspace);
627+ session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, 1));
628+ session.execute("USE " + keyspace);
629+ } catch (Exception e) {
630+ errorOut();
631+ LOGGER.error("Could not create test keyspace", e);
632+ Throwables.propagate(e);
633+ }
634+ }
635+ }
636+
637+ private void initTestFixtures(Object testInstance) throws Exception {
638+ if (ccmTestConfig.createCcm() && ccmTestConfig.createCluster() && ccmTestConfig.createSession()) {
639+ for (String stmt : ccmTestConfig.fixtures(testInstance)) {
640+ try {
641+ session.execute(stmt);
642+ } catch (Exception e) {
643+ errorOut();
644+ LOGGER.error("Could not execute statement: " + stmt, e);
645+ Throwables.propagate(e);
646+ }
647+ }
648+ }
649+ }
650+
651+ private void closeTestContext() {
652+ if (ccmTestConfig != null && ccm != null && ccmTestConfig.dirtiesContext()) {
653+ ccm.close();
654+ }
655+ ccmTestConfig = null;
656+ ccm = null;
657+ }
658+
659+ private void closeTestCluster() {
660+ if (cluster != null && !cluster.isClosed())
661+ executeNoFail(new Runnable() {
662+ @Override
663+ public void run() {
664+ cluster.close();
665+ }
666+ }, false);
667+ cluster = null;
668+ session = null;
669+ keyspace = null;
670+ }
671+
672+ private void closeCloseables() {
673+ if (closer != null)
674+ executeNoFail(new Callable<Void>() {
675+ @Override
676+ public Void call() throws IOException {
677+ closer.close();
678+ return null;
679+ }
680+ }, false);
681+ }
682+
683+ private static boolean isCcmEnabled(Method testMethod) {
684+ Test ann = locateAnnotation(testMethod, Test.class);
685+ return !Collections.disjoint(Arrays.asList(ann.groups()), TEST_GROUPS);
686+ }
687+
688+ private static CCMTestConfig createCCMTestConfig(Object testInstance, Method testMethod) throws Exception {
689+ ArrayList<CCMConfig> annotations = new ArrayList<CCMConfig>();
690+ CCMConfig ann = locateAnnotation(testMethod, CCMConfig.class);
691+ if (ann != null)
692+ annotations.add(ann);
693+ locateClassAnnotations(testInstance.getClass(), CCMConfig.class, annotations);
694+ return new CCMTestConfig(annotations);
695+ }
696+
697+ private static TestMode determineTestMode(Class<?> testClass) {
698+ List<CreateCCM> annotations = locateClassAnnotations(testClass, CreateCCM.class, new ArrayList<CreateCCM>());
699+ if (!annotations.isEmpty())
700+ return annotations.get(0).value();
701+ return PER_CLASS;
702+ }
703+
704+ private static <A extends Annotation> A locateAnnotation(Method testMethod, Class<? extends A> clazz) {
705+ if (testMethod == null)
706+ return null;
707+ testMethod.setAccessible(true);
708+ return testMethod.getAnnotation(clazz);
709+ }
710+
711+ private static <A extends Annotation> List<A> locateClassAnnotations(Class<?> clazz, Class<? extends A> annotationClass, List<A> annotations) {
712+ A ann = clazz.getAnnotation(annotationClass);
713+ if (ann != null)
714+ annotations.add(ann);
715+ clazz = clazz.getSuperclass();
716+ if (clazz == null)
717+ return annotations;
718+ return locateClassAnnotations(clazz, annotationClass, annotations);
719+ }
720+
721+ private static Method locateMethod(String methodName, Class<?> clazz) throws NoSuchMethodException {
722+ try {
723+ Method method = clazz.getDeclaredMethod(methodName);
724+ method.setAccessible(true);
725+ return method;
726+ } catch (NoSuchMethodException e) {
727+ clazz = clazz.getSuperclass();
728+ if (clazz == null)
729+ throw e;
730+ return locateMethod(methodName, clazz);
731+ }
732+ }
733+
734+ @SuppressWarnings("unchecked")
735+ private static <T> T instantiate(Class<? extends T> clazz) throws NoSuchMethodException, InstantiationException, IllegalAccessException, java.lang.reflect.InvocationTargetException {
736+ if (clazz.getEnclosingClass() == null || Modifier.isStatic(clazz.getModifiers())) {
737+ Constructor<?> constructor = clazz.getDeclaredConstructor();
738+ constructor.setAccessible(true);
739+ return (T) constructor.newInstance();
740+ } else {
741+ Class<?> enclosingClass = clazz.getEnclosingClass();
742+ Object enclosingInstance = enclosingClass.newInstance();
743+ Constructor<?> constructor = clazz.getDeclaredConstructor(enclosingClass);
744+ constructor.setAccessible(true);
745+ return (T) constructor.newInstance(enclosingInstance);
746+ }
747+ }
748+
749+}
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+ .withAddressTranslater(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(new DCAwareRoundRobinPolicy("dc2"), 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 +65 −83
@@ -28,6 +28,7 @@
2828 import org.testng.annotations.Test;
2929
3030 import java.net.InetAddress;
31+import java.net.InetSocketAddress;
3132 import java.util.Collection;
3233 import java.util.Iterator;
3334 import java.util.Map;
@@ -35,18 +36,21 @@
3536 import java.util.concurrent.atomic.AtomicInteger;
3637
3738 import static com.datastax.driver.core.Assertions.assertThat;
39+import static com.datastax.driver.core.CreateCCM.TestMode.PER_METHOD;
3840 import static com.datastax.driver.core.TestUtils.nonDebouncingQueryOptions;
3941 import static com.datastax.driver.core.TestUtils.nonQuietClusterCloseOptions;
4042 import static com.google.common.collect.Lists.newArrayList;
4143
42-public class ControlConnectionTest {
44+@CreateCCM(PER_METHOD)
45+@CCMConfig(dirtiesContext = true, createCluster = false)
46+public class ControlConnectionTest extends CCMTestsSupport {
4347
4448 static final Logger logger = LoggerFactory.getLogger(ControlConnectionTest.class);
4549
4650 @Test(groups = "short")
51+ @CCMConfig(numberOfNodes = 2)
4752 public void should_prevent_simultaneous_reconnection_attempts() throws InterruptedException {
48- CCMBridge ccm = null;
49- Cluster cluster = null;
53+ Cluster cluster;
5054
5155 // Custom load balancing policy that counts the number of calls to newQueryPlan().
5256 // Since we don't open any session from our Cluster, only the control connection reattempts are calling this
@@ -68,31 +72,23 @@
6872 }
6973 };
7074
71- try {
72- ccm = CCMBridge.builder("test").withNodes(2).build();
73- // We pass only the first host as contact point, so we know the control connection will be on this host
74- cluster = Cluster.builder()
75- .addContactPoint(CCMBridge.ipOfNode(1))
76- .withReconnectionPolicy(reconnectionPolicy)
77- .withLoadBalancingPolicy(loadBalancingPolicy)
78- .build();
79- cluster.init();
80-
81- // Kill the control connection host, there should be exactly one reconnection attempt
82- ccm.stop(1);
83- TimeUnit.SECONDS.sleep(1); // Sleep for a while to make sure our final count is not the result of lucky timing
84- assertThat(reconnectionAttempts.get()).isEqualTo(1);
85-
86- ccm.stop(2);
87- TimeUnit.SECONDS.sleep(1);
88- assertThat(reconnectionAttempts.get()).isEqualTo(2);
89-
90- } finally {
91- if (cluster != null)
92- cluster.close();
93- if (ccm != null)
94- ccm.remove();
95- }
75+ // We pass only the first host as contact point, so we know the control connection will be on this host
76+ cluster = register(Cluster.builder()
77+ .addContactPointsWithPorts(getHostAddress(1))
78+ .withAddressTranslater(getAddressTranslator())
79+ .withReconnectionPolicy(reconnectionPolicy)
80+ .withLoadBalancingPolicy(loadBalancingPolicy)
81+ .build());
82+ cluster.init();
83+
84+ // Kill the control connection host, there should be exactly one reconnection attempt
85+ ccm.stop(1);
86+ TimeUnit.SECONDS.sleep(1); // Sleep for a while to make sure our final count is not the result of lucky timing
87+ assertThat(reconnectionAttempts.get()).isEqualTo(1);
88+
89+ ccm.stop(2);
90+ TimeUnit.SECONDS.sleep(1);
91+ assertThat(reconnectionAttempts.get()).isEqualTo(2);
9692 }
9793
9894 /**
@@ -104,30 +100,23 @@
104100 @Test(groups = "short")
105101 @CassandraVersion(major = 2.1)
106102 public void should_parse_UDT_definitions_when_using_default_protocol_version() {
107- CCMBridge ccm = null;
108- Cluster cluster = null;
109-
110- try {
111- ccm = CCMBridge.builder("test").build();
112-
113- // First driver instance: create UDT
114- cluster = Cluster.builder().addContactPoint(CCMBridge.ipOfNode(1)).build();
115- Session session = cluster.connect();
116- session.execute("create keyspace ks WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}");
117- session.execute("create type ks.foo (i int)");
118- cluster.close();
119-
120- // Second driver instance: read UDT definition
121- cluster = Cluster.builder().addContactPoint(CCMBridge.ipOfNode(1)).build();
122- UserType fooType = cluster.getMetadata().getKeyspace("ks").getUserType("foo");
123-
124- assertThat(fooType.getFieldNames()).containsExactly("i");
125- } finally {
126- if (cluster != null)
127- cluster.close();
128- if (ccm != null)
129- ccm.remove();
130- }
103+ Cluster cluster;
104+ InetSocketAddress firstHost = getHostAddress(1);
105+ // First driver instance: create UDT
106+ cluster = register(Cluster.builder()
107+ .addContactPointsWithPorts(firstHost)
108+ .withAddressTranslater(getAddressTranslator())
109+ .build());
110+ Session session = cluster.connect();
111+ session.execute("create keyspace ks WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}");
112+ session.execute("create type ks.foo (i int)");
113+ cluster.close();
114+
115+ // Second driver instance: read UDT definition
116+ cluster = register(Cluster.builder().addContactPointsWithPorts(firstHost).build());
117+ UserType fooType = cluster.getMetadata().getKeyspace("ks").getUserType("foo");
118+
119+ assertThat(fooType.getFieldNames()).containsExactly("i");
131120 }
132121
133122 /**
@@ -140,36 +129,27 @@
140129 * @since 2.0.9
141130 */
142131 @Test(groups = "long")
132+ @CCMConfig(numberOfNodes = 3)
143133 public void should_reestablish_if_control_node_decommissioned() throws InterruptedException {
144- CCMBridge ccm = null;
145- Cluster cluster = null;
146-
147- try {
148- ccm = CCMBridge.builder("test").withNodes(3).build();
149-
150- cluster = Cluster.builder()
151- .addContactPoint(CCMBridge.ipOfNode(1))
152- .withQueryOptions(nonDebouncingQueryOptions())
153- .build();
154- cluster.init();
155-
156- // Ensure the control connection host is that of the first node.
157- String controlHost = cluster.manager.controlConnection.connectedHost().getAddress().getHostAddress();
158- assertThat(controlHost).isEqualTo(CCMBridge.ipOfNode(1));
159-
160- // Decommission the node.
161- ccm.decommissionNode(1);
162-
163- // Ensure that the new control connection is not null and it's host is not equal to the decommissioned node.
164- Host newHost = cluster.manager.controlConnection.connectedHost();
165- assertThat(newHost).isNotNull();
166- assertThat(newHost.getAddress().getHostAddress()).isNotEqualTo(controlHost);
167- } finally {
168- if (cluster != null)
169- cluster.close();
170- if (ccm != null)
171- ccm.remove();
172- }
134+ InetSocketAddress firstHost = getHostAddress(1);
135+ Cluster cluster = register(Cluster.builder()
136+ .addContactPointsWithPorts(firstHost)
137+ .withAddressTranslater(getAddressTranslator())
138+ .withQueryOptions(nonDebouncingQueryOptions())
139+ .build());
140+ cluster.init();
141+
142+ // Ensure the control connection host is that of the first node.
143+ InetAddress controlHost = cluster.manager.controlConnection.connectedHost().getAddress();
144+ assertThat(controlHost).isEqualTo(firstHost.getAddress());
145+
146+ // Decommission the node.
147+ ccm.decommissionNode(1);
148+
149+ // Ensure that the new control connection is not null and it's host is not equal to the decommissioned node.
150+ Host newHost = cluster.manager.controlConnection.connectedHost();
151+ assertThat(newHost).isNotNull();
152+ assertThat(newHost.getAddress()).isNotEqualTo(controlHost);
173153 }
174154
175155 /**
@@ -186,6 +166,7 @@
186166 * @since 2.0.11, 2.1.8, 2.2.0
187167 */
188168 @Test(groups = "short")
169+ @CCMConfig(createCcm = false)
189170 public void should_randomize_contact_points_when_determining_control_connection() {
190171 int hostCount = 5;
191172 int iterations = 100;
@@ -193,14 +174,15 @@
193174 scassandras.init();
194175
195176 try {
196- Collection<String> contactPoints = newArrayList();
177+ Collection<InetSocketAddress> contactPoints = newArrayList();
197178 for (int i = 1; i <= hostCount; i++) {
198179 contactPoints.add(scassandras.address(i));
199180 }
200181 final HashMultiset<InetAddress> occurrencesByHost = HashMultiset.create(hostCount);
201182 for (int i = 0; i < iterations; i++) {
202183 Cluster cluster = Cluster.builder()
203- .addContactPoints(contactPoints.toArray(new String[hostCount]))
184+ .addContactPointsWithPorts(contactPoints)
185+ .withAddressTranslater(scassandras.addressTranslator())
204186 .withNettyOptions(nonQuietClusterCloseOptions)
205187 .build();
206188
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/CustomTypeTest.java +2 −3
@@ -28,10 +28,10 @@
2828 /**
2929 * Test we "support" custom types.
3030 */
31-public class CustomTypeTest extends CCMBridge.PerClassSingleNodeCluster {
31+public class CustomTypeTest extends CCMTestsSupport {
3232
3333 @Override
34- protected Collection<String> getTableDefinitions() {
34+ public Collection<String> createTestFixtures() {
3535 return Collections.singleton(
3636 "CREATE TABLE test ("
3737 + " k int,"
@@ -43,7 +43,6 @@
4343 }
4444
4545 private ByteBuffer serializeForDynamicType(Object... params) {
46-
4746 List<ByteBuffer> l = new ArrayList<ByteBuffer>();
4847 int size = 0;
4948 for (Object p : params) {
modified driver-core/src/test/java/com/datastax/driver/core/DataTypeIntegrationTest.java +3 −2
@@ -35,7 +35,8 @@
3535 * (protocol > v2 only) and a prepared statement.
3636 * This is repeated with a large number of datatypes.
3737 */
38-public class DataTypeIntegrationTest extends CCMBridge.PerClassSingleNodeCluster {
38+@CCMConfig(clusterProvider = "createClusterBuilderNoDebouncing")
39+public class DataTypeIntegrationTest extends CCMTestsSupport {
3940 private static final Logger logger = LoggerFactory.getLogger(DataTypeIntegrationTest.class);
4041
4142 List<TestTable> tables = allTables();
@@ -44,7 +45,7 @@
4445 enum StatementType {RAW_STRING, SIMPLE_WITH_PARAM, PREPARED}
4546
4647 @Override
47- protected Collection<String> getTableDefinitions() {
48+ public Collection<String> createTestFixtures() {
4849 Host host = cluster.getMetadata().getAllHosts().iterator().next();
4950 cassandraVersion = host.getCassandraVersion().nextStable();
5051
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+ .withAddressTranslater(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().getProtocolVersionEnum() != ProtocolVersion.V1)
65- throw e;
66- } catch (Throwable e) {
67- errorOut();
68- throw e;
62+ assertEquals(cluster.getConfiguration().getProtocolOptions().getProtocolVersionEnum(), ProtocolVersion.V1);
6963 }
7064 }
7165 }
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+ .withAddressTranslater(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+ .withAddressTranslater(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+ .withAddressTranslater(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
@@ -17,7 +17,7 @@
1717
1818 import com.codahale.metrics.Gauge;
1919 import com.datastax.driver.core.policies.ConstantReconnectionPolicy;
20-import com.google.common.util.concurrent.Uninterruptibles;
20+import com.google.common.util.concurrent.*;
2121 import org.scassandra.cql.PrimitiveType;
2222 import org.scassandra.http.client.PrimingRequest;
2323 import org.testng.annotations.BeforeClass;
@@ -41,7 +41,6 @@
4141
4242 public class HostConnectionPoolTest extends ScassandraTestBase.PerClassCluster {
4343
44-
4544 @BeforeClass(groups = {"short", "long"})
4645 public void reinitializeCluster() {
4746 // Don't use the provided cluster, each test will create its own instead.
@@ -574,6 +573,9 @@
574573 Connection.Factory factory = spy(cluster.manager.connectionFactory);
575574 cluster.manager.connectionFactory = factory;
576575
576+ TestExecutorService blockingExecutor = new TestExecutorService(cluster.manager.blockingExecutor);
577+ cluster.manager.blockingExecutor = blockingExecutor;
578+
577579 HostConnectionPool pool = createPool(cluster, 3, 3);
578580 Connection core0 = pool.connections.get(0);
579581 Connection core1 = pool.connections.get(1);
@@ -602,12 +604,14 @@
602604 Uninterruptibles.sleepUninterruptibly(reconnectInterval, TimeUnit.MILLISECONDS);
603605
604606 // Attempt to borrow connection, this should trigger ensureCoreConnections thus spawning a new connection.
607+ blockingExecutor.reset();
605608 request = MockRequest.send(pool);
606609 requests.add(request);
607610 assertThat(request.connection).isEqualTo(core1);
608611
609612 // Should have tried to open up to core connections as result of borrowing a connection past reconnect time and not being at core.
610- verify(factory, timeout(reconnectInterval).times(1)).open(any(HostConnectionPool.class));
613+ blockingExecutor.blockUntilNextTaskCompleted();
614+ verify(factory).open(any(HostConnectionPool.class));
611615 reset(factory);
612616
613617 // Sleep for reconnect interval to allow reconnection time to elapse.
@@ -619,13 +623,17 @@
619623 Uninterruptibles.sleepUninterruptibly(reconnectInterval, TimeUnit.MILLISECONDS);
620624
621625 // Try to borrow a connection, the pool should grow.
626+ blockingExecutor.reset();
622627 requests.add(MockRequest.send(pool));
623- verify(factory, timeout((reconnectInterval + readTimeout) * 2).times(1)).open(any(HostConnectionPool.class));
628+ blockingExecutor.blockUntilNextTaskCompleted();
629+ verify(factory).open(any(HostConnectionPool.class));
624630 reset(factory);
625631
626632 // Another core connection should be opened as result of another request to get us up to core connections.
633+ blockingExecutor.reset();
627634 requests.add(MockRequest.send(pool));
628- verify(factory, timeout((reconnectInterval + readTimeout) * 2).times(1)).open(any(HostConnectionPool.class));
635+ blockingExecutor.blockUntilNextTaskCompleted();
636+ verify(factory).open(any(HostConnectionPool.class));
629637 reset(factory);
630638
631639 // Sending another request should not grow the pool any more, since we are now at core connections.
@@ -1103,4 +1111,45 @@
11031111 return 0; // value not important for this test class
11041112 }
11051113 }
1114+
1115+ static class TestExecutorService extends ForwardingListeningExecutorService {
1116+
1117+ private final ListeningExecutorService delegate;
1118+
1119+ private final Semaphore semaphore = new Semaphore(0);
1120+
1121+ TestExecutorService(ListeningExecutorService delegate) {
1122+ this.delegate = delegate;
1123+ }
1124+
1125+ @Override
1126+ protected ListeningExecutorService delegate() {
1127+ return delegate;
1128+ }
1129+
1130+ public void reset() {
1131+ semaphore.drainPermits();
1132+ }
1133+
1134+ public void blockUntilNextTaskCompleted() throws InterruptedException {
1135+ semaphore.tryAcquire(1, 1, TimeUnit.MINUTES);
1136+ }
1137+
1138+ @Override
1139+ public ListenableFuture<?> submit(Runnable task) {
1140+ ListenableFuture<?> future = super.submit(task);
1141+ Futures.addCallback(future, new FutureCallback<Object>() {
1142+ @Override
1143+ public void onSuccess(Object result) {
1144+ semaphore.release(1);
1145+ }
1146+
1147+ @Override
1148+ public void onFailure(Throwable t) {
1149+ semaphore.release(1);
1150+ }
1151+ });
1152+ return future;
1153+ }
1154+ }
11061155 }
modified driver-core/src/test/java/com/datastax/driver/core/IndexMetadataTest.java +3 −3
@@ -33,7 +33,7 @@
3333
3434 @CassandraVersion(
3535 major = 1.2)
36-public class IndexMetadataTest extends CCMBridge.PerClassSingleNodeCluster {
36+public class IndexMetadataTest extends CCMTestsSupport {
3737
3838 /**
3939 * Column definitions for schema_columns table.
@@ -49,7 +49,7 @@
4949 });
5050
5151 @Override
52- protected Collection<String> getTableDefinitions() {
52+ public Collection<String> createTestFixtures() {
5353 String createTable = "CREATE TABLE indexing ("
5454 + "id int primary key,"
5555 + "map_values map<text, int>,"
@@ -58,7 +58,7 @@
5858 + "text_column text"
5959 +
6060 // Frozen collections was introduced only in C* 2.1.3
61- (cassandraVersion.compareTo(VersionNumber.parse("2.1.3")) >= 0
61+ (ccm.getVersion().compareTo(VersionNumber.parse("2.1.3")) >= 0
6262 ?
6363 ", map_full frozen<map<text, int>>,"
6464 + "set_full frozen<set<text>>,"
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 < 10000; ++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+ .withAddressTranslater(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+ .withAddressTranslater(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(InetAddress.getByName(TestUtils.IP_PREFIX + '1')))
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/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+ .withAddressTranslater(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 +4 −4
@@ -25,12 +25,12 @@
2525
2626 import static org.testng.Assert.assertEquals;
2727
28-public class MetricsTest extends CCMBridge.PerClassSingleNodeCluster {
28+public class MetricsTest extends CCMTestsSupport {
2929 private volatile RetryDecision retryDecision;
3030
3131 @Override
32- protected Cluster.Builder configure(Cluster.Builder builder) {
33- return builder.withRetryPolicy(new RetryPolicy() {
32+ public Cluster.Builder createClusterBuilder() {
33+ return Cluster.builder().withRetryPolicy(new RetryPolicy() {
3434 @Override
3535 public RetryDecision onReadTimeout(Statement statement, ConsistencyLevel cl, int requiredResponses, int receivedResponses, boolean dataRetrieved, int nbRetry) {
3636 return retryDecision;
@@ -49,7 +49,7 @@
4949 }
5050
5151 @Override
52- protected Collection<String> getTableDefinitions() {
52+ public Collection<String> createTestFixtures() {
5353 return Lists.newArrayList("CREATE TABLE test (k int primary key, v int)",
5454 "INSERT INTO test (k, v) VALUES (1, 1)");
5555 }
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+ .withAddressTranslater(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+ .withAddressTranslater(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 = "long", 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+ .withAddressTranslater(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 +23 −34
@@ -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,33 +40,28 @@
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+ .withAddressTranslater(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 onAdd should be called, since stop and start should be discarded.
68- verify(listener, timeout(refreshNodeInterval + TimeUnit.MILLISECONDS.convert(Cluster.NEW_NODE_DELAY_SECONDS, TimeUnit.SECONDS)).only()).onAdd(captor.capture());
69-
70- // The hosts state should be UP.
71- assertThat(captor.getValue().getState()).isEqualTo("UP");
72- assertThat(cluster).host(2).hasState(Host.State.UP);
73- } finally {
74- cluster.close();
75- ccm.remove();
76- }
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 onAdd should be called, since stop and start should be discarded.
61+ verify(listener, timeout(refreshNodeInterval + TimeUnit.MILLISECONDS.convert(Cluster.NEW_NODE_DELAY_SECONDS, TimeUnit.SECONDS)).only()).onAdd(captor.capture());
62+
63+ // The hosts state should be UP.
64+ assertThat(captor.getValue().getState()).isEqualTo("UP");
65+ assertThat(cluster).host(2).hasState(Host.State.UP);
7766 }
7867 }
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/PreparedStatementTest.java +5 −10
@@ -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";
@@ -47,7 +47,7 @@
4747 }
4848
4949 @Override
50- protected Collection<String> getTableDefinitions() {
50+ public Collection<String> createTestFixtures() {
5151
5252 List<String> defs = new ArrayList<String>(4);
5353
@@ -105,11 +105,6 @@
105105 return defs;
106106 }
107107
108- @Override
109- protected Cluster.Builder configure(Cluster.Builder builder) {
110- return builder.withQueryOptions(TestUtils.nonDebouncingQueryOptions());
111- }
112-
113108 @Test(groups = "short")
114109 public void preparedNativeTest() {
115110 // Test preparing/bounding for all native types
@@ -346,7 +341,7 @@
346341 */
347342 @Test(groups = {"docs"})
348343 public void printTableDefinitions() {
349- for (String definition : getTableDefinitions()) {
344+ for (String definition : createTestFixtures()) {
350345 System.out.println(definition);
351346 }
352347 }
@@ -424,7 +419,7 @@
424419 @Test(groups = "short", expectedExceptions = InvalidQueryException.class)
425420 public void should_fail_when_prepared_on_another_cluster() throws Exception {
426421 Cluster otherCluster = Cluster.builder()
427- .addContactPointsWithPorts(ImmutableList.of(hostAddress))
422+ .addContactPointsWithPorts(getInitialContactPoints())
428423 .build();
429424 try {
430425 PreparedStatement pst = otherCluster.connect().prepare("select * from system.peers where inet = ?");
modified driver-core/src/test/java/com/datastax/driver/core/QueryLoggerErrorsTest.java +9 −4
@@ -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
@@ -194,4 +199,4 @@
194199 .contains(loggedException.getName());
195200 }
196201
197-}
No newline at the end of the file
202+}
modified driver-core/src/test/java/com/datastax/driver/core/QueryLoggerTest.java +19 −16
@@ -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>(Sets.filter(DataType.allPrimitiveTypes(), new Predicate<DataType>() {
5253 @Override
@@ -92,32 +93,34 @@
9293 private MemoryAppender errorAppender;
9394
9495 private QueryLogger queryLogger;
96+ private Level originalNormal;
97+ private Level originalSlow;
98+ private Level originalError;
9599
96100 @BeforeMethod(groups = {"short", "unit"})
97101 public void startCapturingLogs() {
102+ originalNormal = normal.getLevel();
103+ originalSlow = slow.getLevel();
104+ originalError = error.getLevel();
105+ normal.setLevel(INFO);
106+ slow.setLevel(INFO);
107+ error.setLevel(INFO);
98108 normal.addAppender(normalAppender = new MemoryAppender());
99109 slow.addAppender(slowAppender = new MemoryAppender());
100110 error.addAppender(errorAppender = new MemoryAppender());
101111 }
102112
103- @AfterMethod(groups = {"short", "unit"})
113+ @AfterMethod(groups = {"short", "unit"}, alwaysRun = true)
104114 public void stopCapturingLogs() {
105- normal.setLevel(null);
106- slow.setLevel(null);
107- error.setLevel(null);
115+ normal.setLevel(originalNormal);
116+ slow.setLevel(originalSlow);
117+ error.setLevel(originalError);
108118 normal.removeAppender(normalAppender);
109119 slow.removeAppender(slowAppender);
110120 error.removeAppender(errorAppender);
111121 }
112122
113- @BeforeMethod(groups = {"short", "unit"})
114- public void resetLogLevels() {
115- normal.setLevel(INFO);
116- slow.setLevel(INFO);
117- error.setLevel(INFO);
118- }
119-
120- @AfterMethod(groups = {"short", "unit"})
123+ @AfterMethod(groups = {"short", "unit"}, alwaysRun = true)
121124 public void unregisterQueryLogger() {
122125 if (cluster != null && queryLogger != null) {
123126 cluster.unregister(queryLogger);
@@ -714,8 +717,8 @@
714717 }
715718
716719 @Override
717- protected List<String> getTableDefinitions() {
720+ public List<String> createTestFixtures() {
718721 return Lists.newArrayList("CREATE TABLE test (pk int PRIMARY KEY, " + definitions + ")");
719722 }
720723
721-}
No newline at the end of the file
724+}
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+ .withAddressTranslater(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+ .withAddressTranslater(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+ .withAddressTranslater(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+ .withAddressTranslater(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+ .withAddressTranslater(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 −224
@@ -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,267 +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;
37-import static org.assertj.core.api.Assertions.assertThat;
3839 import static org.mockito.Mockito.*;
3940
4041 /**
4142 * Scenarios where a Cluster loses connection to a host and reconnects.
4243 */
43-public class ReconnectionTest {
44+@CreateCCM(PER_METHOD)
45+public class ReconnectionTest extends CCMTestsSupport {
4446
47+ private final int reconnectionDelayMillis = 1000;
48+
49+ @CCMConfig(dirtiesContext = true, numberOfNodes = 2, createCluster = false)
4550 @Test(groups = "long")
4651 public void should_reconnect_after_full_connectivity_loss() throws InterruptedException {
47- CCMBridge ccm = null;
48- Cluster cluster = null;
49- try {
50- ccm = CCMBridge.builder("test").withNodes(2).build();
51- int reconnectionDelay = 1000;
52- cluster = Cluster.builder()
53- .addContactPoint(CCMBridge.ipOfNode(1))
54- .withReconnectionPolicy(new ConstantReconnectionPolicy(reconnectionDelay))
55- .build();
56- cluster.connect();
57-
58- assertThat(cluster).usesControlHost(1);
59-
60- // Stop all nodes. We won't get notifications anymore, so the only mechanism to
61- // reconnect is the background reconnection attempts.
62- ccm.stop(2);
63- ccm.stop(1);
64-
65- ccm.waitForDown(2);
66- ccm.start(2);
67- ccm.waitForUp(2);
68-
69- assertThat(cluster).host(2).comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS * 2, SECONDS);
70-
71- // Give the control connection a few moments to reconnect
72- TimeUnit.MILLISECONDS.sleep(reconnectionDelay * 2);
73- assertThat(cluster).usesControlHost(2);
74- } finally {
75- if (cluster != null)
76- cluster.close();
77- if (ccm != null)
78- ccm.remove();
79- }
52+ Cluster cluster = register(Cluster.builder()
53+ .addContactPointsWithPorts(ccm.addressOfNode(1))
54+ .withAddressTranslater(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);
8075 }
8176
77+ @CCMConfig(
78+ dirtiesContext = true,
79+ config = "authenticator:PasswordAuthenticator",
80+ jvmArgs = "-Dcassandra.superuser_setup_delay_ms=0",
81+ createCluster = false)
8282 @Test(groups = "long")
8383 public void should_keep_reconnecting_on_authentication_error() throws InterruptedException {
84- CCMBridge ccm = null;
85- Cluster cluster = null;
86- try {
87- ccm = CCMBridge.builder("test")
88- .withCassandraConfiguration("authenticator", "PasswordAuthenticator") // default credentials: cassandra / cassandra
89- .notStarted()
90- .build();
91- ccm.start(1, "-Dcassandra.superuser_setup_delay_ms=0");
92-
93- CountingAuthProvider authProvider = new CountingAuthProvider("cassandra", "cassandra");
94- int reconnectionDelayMs = 1000;
95- CountingReconnectionPolicy reconnectionPolicy = new CountingReconnectionPolicy(new ConstantReconnectionPolicy(reconnectionDelayMs));
96-
97- cluster = Cluster.builder()
98- .addContactPoint(CCMBridge.ipOfNode(1))
99- // Start with the correct auth so that we can initialize the server
100- .withAuthProvider(authProvider)
101- .withReconnectionPolicy(reconnectionPolicy)
102- .build();
103-
104- cluster.init();
105- assertThat(cluster).usesControlHost(1);
106-
107- // Stop the server, set wrong credentials and restart
108- ccm.stop(1);
109- ccm.waitForDown(1);
110- authProvider.setPassword("wrongPassword");
111- ccm.start(1);
112- ccm.waitForUp(1);
113-
114- // Wait a few iterations to ensure that our authProvider has returned the wrong credentials at least once
115- // NB: authentication errors show up in the logs
116- int initialCount = authProvider.count.get();
117- int iterations = 0, maxIterations = 12; // make sure we don't wait indefinitely
118- do {
119- iterations += 1;
120- TimeUnit.SECONDS.sleep(5);
121- } while (iterations < maxIterations && authProvider.count.get() <= initialCount);
122- assertThat(iterations).isLessThan(maxIterations);
123-
124- // Fix the credentials
125- authProvider.setPassword("cassandra");
126-
127- // The driver should eventually reconnect to the node
128- assertThat(cluster).host(1).comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS * 2, SECONDS);
129- } finally {
130- if (cluster != null)
131- cluster.close();
132- if (ccm != null)
133- 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);
13488 }
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+ .withAddressTranslater(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);
135124 }
136125
126+ @CCMConfig(dirtiesContext = true, numberOfNodes = 2, createCluster = false)
137127 @Test(groups = "long")
138128 public void should_cancel_reconnection_attempts() throws InterruptedException {
139- CCMBridge ccm = null;
140- Cluster cluster = null;
141-
142- long reconnectionDelayMillis = 1000;
129+ // Stop a node and cancel the reconnection attempts to it
143130 CountingReconnectionPolicy reconnectionPolicy = new CountingReconnectionPolicy(new ConstantReconnectionPolicy(reconnectionDelayMillis));
144131
145- try {
146- ccm = CCMBridge.builder("test").withNodes(2).build();
147- cluster = Cluster.builder()
148- .addContactPoint(CCMBridge.ipOfNode(1))
149- .withReconnectionPolicy(reconnectionPolicy)
150- .build();
151- cluster.connect();
152-
153- // Stop a node and cancel the reconnection attempts to it
154- ccm.stop(2);
155- Host host2 = TestUtils.findHost(cluster, 2);
156- host2.getReconnectionAttemptFuture().cancel(false);
157-
158- // The reconnection count should not vary over time anymore
159- int initialCount = reconnectionPolicy.count.get();
160- TimeUnit.MILLISECONDS.sleep(reconnectionDelayMillis * 2);
161- assertThat(reconnectionPolicy.count.get()).isEqualTo(initialCount);
162-
163- // Restart the node, which will trigger an UP notification
164- ccm.start(2);
165- ccm.waitForUp(2);
166-
167- // The driver should now see the node as UP again
168- assertThat(cluster).host(2).comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS * 2, SECONDS);
169-
170- } finally {
171- if (cluster != null)
172- cluster.close();
173- if (ccm != null)
174- ccm.remove();
175- }
132+ Cluster cluster = register(Cluster.builder()
133+ .addContactPointsWithPorts(ccm.addressOfNode(1))
134+ .withAddressTranslater(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);
176154 }
177155
156+ @CCMConfig(dirtiesContext = true, createCluster = false)
178157 @Test(groups = "long")
179158 public void should_trigger_one_time_reconnect() throws InterruptedException, IOException {
180- CCMBridge ccm = null;
181- Cluster cluster = null;
182-
183- long reconnectionDelayMillis = 1000;
184159 TogglabePolicy loadBalancingPolicy = new TogglabePolicy(new RoundRobinPolicy());
185-
186- try {
187- ccm = CCMBridge.builder("test").withNodes(1).build();
188- cluster = Cluster.builder()
189- .addContactPoint(CCMBridge.ipOfNode(1))
190- .withLoadBalancingPolicy(loadBalancingPolicy)
191- .withReconnectionPolicy(new ConstantReconnectionPolicy(reconnectionDelayMillis))
192- .build();
193- cluster.connect();
194-
195- // Tweak the LBP so that the control connection never reconnects, otherwise
196- // it would interfere with the rest of the test (this is a bit of a hack)
197- loadBalancingPolicy.returnEmptyQueryPlan = true;
198-
199- // Stop the node, ignore it and cancel reconnection attempts to it
200- ccm.stop(1);
201- ccm.waitForDown(1);
202- assertThat(cluster).host(1).goesDownWithin(20, SECONDS);
203- Host host1 = TestUtils.findHost(cluster, 1);
204- loadBalancingPolicy.setDistance(TestUtils.findHost(cluster, 1), HostDistance.IGNORED);
205- ListenableFuture<?> reconnectionAttemptFuture = host1.getReconnectionAttemptFuture();
206- if (reconnectionAttemptFuture != null)
207- reconnectionAttemptFuture.cancel(false);
208-
209- // Trigger a one-time reconnection attempt (this will fail)
210- host1.tryReconnectOnce();
211-
212- // Wait for a few reconnection cycles before checking
213- TimeUnit.MILLISECONDS.sleep(reconnectionDelayMillis * 2);
214- assertThat(cluster).host(1).hasState(State.DOWN);
215-
216- // Restart the node (this will not trigger an UP notification thanks to our
217- // hack to disable the control connection reconnects). The host should stay
218- // down for the driver.
219- ccm.start(1);
220- ccm.waitForUp(1);
221- assertThat(cluster).host(1).hasState(State.DOWN);
222-
223- TimeUnit.SECONDS.sleep(Cluster.NEW_NODE_DELAY_SECONDS);
224- assertThat(cluster).host(1).hasState(State.DOWN);
225-
226- // Trigger another one-time reconnection attempt (this will succeed). The
227- // host should be back up.
228- host1.tryReconnectOnce();
229- assertThat(cluster).host(1).comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS * 2, SECONDS);
230- } finally {
231- if (cluster != null)
232- cluster.close();
233- if (ccm != null)
234- ccm.remove();
235- }
160+ Cluster cluster = register(Cluster.builder()
161+ .addContactPointsWithPorts(ccm.addressOfNode(1))
162+ .withAddressTranslater(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);
236203 }
237204
238205 /**
239206 * The connection established by a successful reconnection attempt should be reused in one of the
240207 * connection pools (JAVA-505).
241208 */
209+ @CCMConfig(dirtiesContext = true, createCluster = false)
242210 @Test(groups = "long")
243211 public void should_use_connection_from_reconnection_in_pool() {
244- CCMBridge ccm = null;
245- Cluster cluster = null;
246-
247212 TogglabePolicy loadBalancingPolicy = new TogglabePolicy(new RoundRobinPolicy());
248213
249214 // Spy SocketOptions.getKeepAlive to count how many connections were instantiated.
250215 SocketOptions socketOptions = spy(new SocketOptions());
251-
252- try {
253- ccm = CCMBridge.builder("test").withNodes(1).build();
254- cluster = Cluster.builder()
255- .addContactPoint(CCMBridge.ipOfNode(1))
256- .withReconnectionPolicy(new ConstantReconnectionPolicy(5000))
257- .withLoadBalancingPolicy(loadBalancingPolicy)
258- .withSocketOptions(socketOptions)
259- .withProtocolVersion(TestUtils.getDesiredProtocolVersion())
260- .build();
261- // Create two sessions to have multiple pools
262- cluster.connect();
263- cluster.connect();
264-
265- int corePoolSize = TestUtils.numberOfLocalCoreConnections(cluster);
266-
267- // Right after init, 1 connection has been opened by the control connection, and the core size for each pool.
268- verify(socketOptions, times(1 + corePoolSize * 2)).getKeepAlive();
269-
270- // Tweak the LBP so that the control connection never reconnects. This makes it easier
271- // to reason about the number of connection attempts.
272- loadBalancingPolicy.returnEmptyQueryPlan = true;
273-
274- // Stop the node and cancel the reconnection attempts to it
275- ccm.stop(1);
276- ccm.waitForDown(1);
277- assertThat(cluster).host(1).goesDownWithin(20, SECONDS);
278- Host host1 = TestUtils.findHost(cluster, 1);
279- host1.getReconnectionAttemptFuture().cancel(false);
280-
281- ccm.start(1);
282- ccm.waitForUp(1);
283-
284- // Reset the spy and count the number of connections attempts for 1 reconnect
285- reset(socketOptions);
286- host1.tryReconnectOnce();
287- assertThat(cluster).host(1).comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS * 2, SECONDS);
288- // Expect 1 connection from the reconnection attempt 3 for the pools (we need 4
289- // but the one from the reconnection attempt gets reused).
290- verify(socketOptions, times(corePoolSize * 2)).getKeepAlive();
291- } finally {
292- if (cluster != null)
293- cluster.close();
294- if (ccm != null)
295- ccm.remove();
296- }
216+ Cluster cluster = register(Cluster.builder()
217+ .addContactPointsWithPorts(ccm.addressOfNode(1))
218+ .withAddressTranslater(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();
297254 }
298255
299256 /**
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+ .withAddressTranslater(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 −1
@@ -43,7 +43,9 @@
4343 .build()
4444 );
4545
46- cluster = Cluster.builder().addContactPoint("127.0.0.1").withPort(scassandra.getBinaryPort())
46+ cluster = Cluster.builder()
47+ .addContactPoint(TestUtils.ipOfNode(1))
48+ .withPort(scassandra.getBinaryPort())
4749 .withPoolingOptions(new PoolingOptions()
4850 .setCoreConnectionsPerHost(HostDistance.LOCAL, 1)
4951 .setMaxConnectionsPerHost(HostDistance.LOCAL, 1)
modified driver-core/src/test/java/com/datastax/driver/core/SSLAuthenticatedEncryptionTest.java +13 −6
@@ -21,12 +21,9 @@
2121
2222 import static com.datastax.driver.core.CCMBridge.*;
2323
24+@CCMConfig(auth = true)
2425 public class SSLAuthenticatedEncryptionTest extends SSLTestBase {
2526
26- public SSLAuthenticatedEncryptionTest() {
27- super(true);
28- }
29-
3027 /**
3128 * <p>
3229 * Validates that an SSL connection can be established with client auth if the target
@@ -72,7 +69,17 @@
7269 System.setProperty("javax.net.ssl.keyStorePassword", DEFAULT_CLIENT_KEYSTORE_PASSWORD);
7370 System.setProperty("javax.net.ssl.trustStore", DEFAULT_CLIENT_TRUSTSTORE_FILE.getAbsolutePath());
7471 System.setProperty("javax.net.ssl.trustStorePassword", DEFAULT_CLIENT_TRUSTSTORE_PASSWORD);
75-
76- connectWithSSL();
72+ try {
73+ connectWithSSL();
74+ } finally {
75+ try {
76+ System.clearProperty("javax.net.ssl.keyStore");
77+ System.clearProperty("javax.net.ssl.keyStorePassword");
78+ System.clearProperty("javax.net.ssl.trustStore");
79+ System.clearProperty("javax.net.ssl.trustStorePassword");
80+ } catch (SecurityException e) {
81+ // ok
82+ }
83+ }
7784 }
7885 }
modified driver-core/src/test/java/com/datastax/driver/core/SSLEncryptionTest.java +26 −31
@@ -24,12 +24,9 @@
2424 import static com.datastax.driver.core.Assertions.assertThat;
2525 import static com.datastax.driver.core.CCMBridge.*;
2626
27+@CCMConfig(auth = false)
2728 public class SSLEncryptionTest extends SSLTestBase {
2829
29- public SSLEncryptionTest() {
30- super(false);
31- }
32-
3330 /**
3431 * <p>
3532 * Validates that an SSL connection can be established without client auth if the target
@@ -74,17 +71,11 @@
7471 */
7572 @Test(groups = "short", expectedExceptions = {NoHostAvailableException.class})
7673 public void should_not_connect_without_ssl_but_node_uses_ssl() throws Exception {
77- Cluster cluster = null;
78- try {
79- cluster = Cluster.builder()
80- .addContactPoint(CCMBridge.IP_PREFIX + '1')
81- .build();
82-
83- cluster.connect();
84- } finally {
85- if (cluster != null)
86- cluster.close();
87- }
74+ Cluster cluster = register(Cluster.builder()
75+ .addContactPointsWithPorts(this.getInitialContactPoints())
76+ .withAddressTranslater(ccm.addressTranslator())
77+ .build());
78+ cluster.connect();
8879 }
8980
9081 /**
@@ -96,25 +87,21 @@
9687 * @test_category connection:ssl
9788 * @expected_result Connection is re-established within a sufficient amount of time after a node comes back online.
9889 */
90+ @CCMConfig(dirtiesContext = true)
9991 @Test(groups = "long")
10092 public void should_reconnect_with_ssl_on_node_up() throws Exception {
101- Cluster cluster = null;
102- try {
103- cluster = Cluster.builder()
104- .addContactPoint(CCMBridge.IP_PREFIX + '1')
105- .withSSL(getSSLOptions(Optional.of(DEFAULT_CLIENT_KEYSTORE_PATH), Optional.of(DEFAULT_CLIENT_TRUSTSTORE_PATH)))
106- .build();
93+ Cluster cluster = register(Cluster.builder()
94+ .addContactPointsWithPorts(this.getInitialContactPoints())
95+ .withAddressTranslater(ccm.addressTranslator())
96+ .withSSL(getSSLOptions(Optional.of(DEFAULT_CLIENT_KEYSTORE_PATH), Optional.of(DEFAULT_CLIENT_TRUSTSTORE_PATH)))
97+ .build());
10798
108- cluster.connect();
99+ cluster.connect();
109100
110- ccm.stop(1);
111- ccm.start(1);
101+ ccm.stop(1);
102+ ccm.start(1);
112103
113- assertThat(cluster).host(1).comesUpWithin(TestUtils.TEST_BASE_NODE_WAIT, TimeUnit.SECONDS);
114- } finally {
115- if (cluster != null)
116- cluster.close();
117- }
104+ assertThat(cluster).host(1).comesUpWithin(TestUtils.TEST_BASE_NODE_WAIT, TimeUnit.SECONDS);
118105 }
119106
120107 /**
@@ -129,7 +116,15 @@
129116 public void should_use_system_properties_with_default_ssl_options() throws Exception {
130117 System.setProperty("javax.net.ssl.trustStore", DEFAULT_CLIENT_TRUSTSTORE_FILE.getAbsolutePath());
131118 System.setProperty("javax.net.ssl.trustStorePassword", DEFAULT_CLIENT_TRUSTSTORE_PASSWORD);
132-
133- connectWithSSL();
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+ }
134129 }
135130 }
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 com.google.common.base.Optional;
19-import org.testng.annotations.AfterClass;
20-import org.testng.annotations.BeforeClass;
2119
2220 import javax.net.ssl.KeyManagerFactory;
2321 import javax.net.ssl.SSLContext;
@@ -28,27 +26,8 @@
2826 import static com.datastax.driver.core.CCMBridge.DEFAULT_CLIENT_KEYSTORE_PASSWORD;
2927 import static com.datastax.driver.core.CCMBridge.DEFAULT_CLIENT_TRUSTSTORE_PASSWORD;
3028
31-public abstract class SSLTestBase {
32-
33- private final boolean requireClientAuth;
34-
35- protected CCMBridge ccm;
36-
37- public SSLTestBase(boolean requireClientAuth) {
38- this.requireClientAuth = requireClientAuth;
39- }
40-
41- @BeforeClass(groups = {"isolated", "short", "long"})
42- public void beforeClass() {
43- ccm = CCMBridge.builder("test")
44- .withSSL(requireClientAuth)
45- .build();
46- }
47-
48- @AfterClass(groups = {"isolated", "short", "long"})
49- public void afterClass() {
50- ccm.remove();
51- }
29+@CCMConfig(ssl = true, createCluster = false)
30+public abstract class SSLTestBase extends CCMTestsSupport {
5231
5332 /**
5433 * <p>
@@ -61,18 +40,12 @@
6140 * raised here if connection cannot be established.
6241 */
6342 protected void connectWithSSLOptions(SSLOptions sslOptions) throws Exception {
64- Cluster cluster = null;
65- try {
66- cluster = Cluster.builder()
67- .addContactPoint(CCMBridge.IP_PREFIX + '1')
68- .withSSL(sslOptions)
69- .build();
70-
71- cluster.connect();
72- } finally {
73- if (cluster != null)
74- cluster.close();
75- }
43+ Cluster cluster = register(Cluster.builder()
44+ .addContactPointsWithPorts(this.getInitialContactPoints())
45+ .withAddressTranslater(ccm.addressTranslator())
46+ .withSSL(sslOptions)
47+ .build());
48+ cluster.connect();
7649 }
7750
7851 /**
@@ -85,18 +58,12 @@
8558 * raised here if connection cannot be established.
8659 */
8760 protected void connectWithSSL() throws Exception {
88- Cluster cluster = null;
89- try {
90- cluster = Cluster.builder()
91- .addContactPoint(CCMBridge.IP_PREFIX + '1')
92- .withSSL()
93- .build();
94-
95- cluster.connect();
96- } finally {
97- if (cluster != null)
98- cluster.close();
99- }
61+ Cluster cluster = register(Cluster.builder()
62+ .addContactPointsWithPorts(this.getInitialContactPoints())
63+ .withAddressTranslater(ccm.addressTranslator())
64+ .withSSL()
65+ .build());
66+ cluster.connect();
10067 }
10168
10269 /**
modified driver-core/src/test/java/com/datastax/driver/core/ScassandraCluster.java +43 −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.AddressTranslater;
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,43 @@
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 AddressTranslater} 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 AddressTranslater} to use when tests must manually create
139+ * {@link Cluster} instances.
140+ */
141+ public AddressTranslater addressTranslator() {
142+ return new AddressTranslater() {
143+ @Override
144+ public InetSocketAddress translate(InetSocketAddress address) {
145+ return new InetSocketAddress(address.getAddress(), binaryPort);
146+ }
147+ };
119148 }
120149
150+
121151 public Host host(Cluster cluster, int dc, int node) {
122- String address = address(dc, node);
152+ InetAddress address = address(dc, node).getAddress();
123153 for (Host host : cluster.getMetadata().getAllHosts()) {
124- if (host.getAddress().getHostAddress().equals(address)) {
154+ if (host.getAddress().equals(address)) {
125155 return host;
126156 }
127157 }
@@ -441,8 +471,8 @@
441471 public static class ScassandraClusterBuilder {
442472
443473 private Integer nodes[] = {1};
444- private String ipPrefix = CCMBridge.IP_PREFIX;
445- private final List<Map<String, ? extends Object>> keyspaceRows = Lists.newArrayList();
474+ private String ipPrefix = TestUtils.IP_PREFIX;
475+ private final List<Map<String, ?>> keyspaceRows = Lists.newArrayList();
446476 private final Map<Integer, Map<Integer, Map<String, Object>>> forcedPeerInfos = Maps.newHashMap();
447477
448478 public ScassandraClusterBuilder withNodes(Integer... nodes) {
@@ -506,7 +536,7 @@
506536 }
507537
508538 public ScassandraCluster build() {
509- return new ScassandraCluster(nodes, ipPrefix, 9042, 9052, keyspaceRows, forcedPeerInfos);
539+ return new ScassandraCluster(nodes, ipPrefix, TestUtils.findAvailablePort(), TestUtils.findAvailablePort(), keyspaceRows, forcedPeerInfos);
510540 }
511541 }
512542 }
modified driver-core/src/test/java/com/datastax/driver/core/ScassandraTestBase.java +12 −8
@@ -15,8 +15,8 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.datastax.driver.core.policies.AddressTranslater;
1819 import org.scassandra.Scassandra;
19-import org.scassandra.ScassandraFactory;
2020 import org.scassandra.http.client.ActivityClient;
2121 import org.scassandra.http.client.CurrentClient;
2222 import org.scassandra.http.client.PrimingClient;
@@ -41,8 +41,6 @@
4141 * consider using {@link com.datastax.driver.core.ScassandraTestBase.PerClassCluster} instead.
4242 */
4343 public abstract class ScassandraTestBase {
44- private static final int BINARY_PORT = 9042;
45- private static final int ADMIN_PORT = 9052;
4644
4745 private static final Logger logger = LoggerFactory.getLogger(ScassandraTestBase.class);
4846
@@ -56,11 +54,11 @@
5654
5755 protected CurrentClient currentClient;
5856
59- protected static String ip = CCMBridge.IP_PREFIX + "1";
57+ protected static String ip = TestUtils.ipOfNode(1);
6058
6159 @BeforeClass(groups = {"short", "long"})
6260 public void startScassandra() {
63- scassandra = ScassandraFactory.createServer(ip, BINARY_PORT, ip, ADMIN_PORT);
61+ scassandra = TestUtils.createScassandraServer();
6462 scassandra.start();
6563 primingClient = scassandra.primingClient();
6664 activityClient = scassandra.activityClient();
@@ -85,6 +83,12 @@
8583 protected Cluster.Builder createClusterBuilder() {
8684 Cluster.Builder builder = Cluster.builder()
8785 .addContactPointsWithPorts(Collections.singletonList(hostAddress))
86+ .withAddressTranslater(new AddressTranslater() {
87+ @Override
88+ public InetSocketAddress translate(InetSocketAddress address) {
89+ return new InetSocketAddress(address.getAddress(), scassandra.getBinaryPort());
90+ }
91+ })
8892 .withPoolingOptions(new PoolingOptions()
8993 .setCoreConnectionsPerHost(HostDistance.LOCAL, 1)
9094 .setMaxConnectionsPerHost(HostDistance.LOCAL, 1)
@@ -132,13 +136,13 @@
132136 session = cluster.connect();
133137 }
134138
135- @AfterClass(groups = {"short", "long"})
139+ @AfterClass(groups = {"short", "long"}, alwaysRun = true)
136140 public void closeCluster() {
137141 if (cluster != null)
138142 cluster.close();
139143 }
140144
141- @AfterClass(groups = {"short", "long"}, dependsOnMethods = "closeCluster")
145+ @AfterClass(groups = {"short", "long"}, dependsOnMethods = "closeCluster", alwaysRun = true)
142146 @Override
143147 public void stopScassandra() {
144148 super.stopScassandra();
@@ -146,4 +150,4 @@
146150
147151 }
148152
149-}
No newline at the end of the file
153+}
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 DataType.uuid().format(schemaVersion), DataType.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+ .withAddressTranslater(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+ .withAddressTranslater(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 +56 −62
@@ -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)
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,39 +228,35 @@
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 = "newKeyspaceName")
269251 public void should_notify_of_keyspace_creation(String keyspace) throws InterruptedException {
270252 execute(CREATE_KEYSPACE, keyspace);
271- for (Metadata m : metadatas)
272- assertThat(m.getKeyspace(keyspace)).isNotNull();
273253 for (SchemaChangeListener listener : listeners) {
274254 ArgumentCaptor<KeyspaceMetadata> added = ArgumentCaptor.forClass(KeyspaceMetadata.class);
275255 verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onKeyspaceAdded(added.capture());
276256 assertThat(added.getValue()).hasName(handleId(keyspace));
277257 }
258+ for (Metadata m : metadatas())
259+ assertThat(m.getKeyspace(keyspace)).isNotNull();
278260 }
279261
280262 @Test(groups = "short", dataProvider = "newKeyspaceName")
@@ -286,7 +268,8 @@
286268 verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onKeyspaceAdded(added.capture());
287269 assertThat(added.getValue()).hasName(handleId(keyspace));
288270 }
289- for (Metadata m : metadatas)
271+ assert added != null;
272+ for (Metadata m : metadatas())
290273 assertThat(m.getKeyspace(keyspace).isDurableWrites()).isTrue();
291274 execute(ALTER_KEYSPACE, keyspace);
292275 for (SchemaChangeListener listener : listeners) {
@@ -300,14 +283,21 @@
300283 .hasName(handleId(keyspace))
301284 .isNotDurableWrites();
302285 }
303- for (Metadata m : metadatas)
286+ for (Metadata m : metadatas())
304287 assertThat(m.getKeyspace(keyspace)).isNotDurableWrites();
305288 }
306289
307290 @Test(groups = "short", dataProvider = "newKeyspaceName")
308291 public void should_notify_of_keyspace_drop(String keyspace) throws InterruptedException {
309292 execute(CREATE_KEYSPACE, keyspace);
310- for (Metadata m : metadatas)
293+ ArgumentCaptor<KeyspaceMetadata> added = null;
294+ for (SchemaChangeListener listener : listeners) {
295+ added = ArgumentCaptor.forClass(KeyspaceMetadata.class);
296+ verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onKeyspaceAdded(added.capture());
297+ assertThat(added.getValue()).hasName(handleId(keyspace));
298+ }
299+ assert added != null;
300+ for (Metadata m : metadatas())
311301 assertThat(m.getReplicas(keyspace, Bytes.fromHexString("0xCAFEBABE"))).isNotEmpty();
312302 execute(CREATE_TABLE, keyspace); // to test table drop notifications
313303 execute(DROP_KEYSPACE, keyspace);
@@ -317,13 +307,12 @@
317307 assertThat(table.getValue())
318308 .hasName("table1")
319309 .isInKeyspace(handleId(keyspace));
320-
321310 ArgumentCaptor<KeyspaceMetadata> ks = ArgumentCaptor.forClass(KeyspaceMetadata.class);
322311 verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onKeyspaceRemoved(ks.capture());
323312 assertThat(ks.getValue())
324313 .hasName(handleId(keyspace));
325314 }
326- for (Metadata m : metadatas) {
315+ for (Metadata m : metadatas()) {
327316 assertThat(m.getKeyspace(keyspace)).isNull();
328317 assertThat(m.getReplicas(keyspace, Bytes.fromHexString("0xCAFEBABE"))).isEmpty();
329318 }
@@ -339,8 +328,8 @@
339328 */
340329 @Test(groups = "short", expectedExceptions = IllegalStateException.class)
341330 public void should_throw_illegal_state_exception_on_newToken_with_metadata_disabled() {
342- Cluster cluster = configure(Cluster.builder())
343- .addContactPointsWithPorts(Collections.singletonList(hostAddress))
331+ Cluster cluster = Cluster.builder()
332+ .addContactPointsWithPorts(getInitialContactPoints())
344333 .withQueryOptions(nonDebouncingQueryOptions()
345334 .setMetadataEnabled(false)
346335 ).build();
@@ -363,8 +352,8 @@
363352 */
364353 @Test(groups = "short", expectedExceptions = IllegalStateException.class)
365354 public void should_throw_illegal_state_exception_on_newTokenRange_with_metadata_disabled() {
366- Cluster cluster = configure(Cluster.builder())
367- .addContactPointsWithPorts(Collections.singletonList(hostAddress))
355+ Cluster cluster = Cluster.builder()
356+ .addContactPointsWithPorts(getInitialContactPoints())
368357 .withQueryOptions(nonDebouncingQueryOptions()
369358 .setMetadataEnabled(false)
370359 ).build();
@@ -386,8 +375,8 @@
386375 * @jira_ticket JAVA-858
387376 * @since 2.0.11
388377 */
389- @Test(groups = "short")
390- public void should_not_refresh_schema_on_schema_change_response() throws InterruptedException {
378+ @Test(groups = "short", dataProvider = "existingKeyspaceName")
379+ public void should_not_refresh_schema_on_schema_change_response(String keyspace) throws InterruptedException {
391380 ResultSet rs = schemaDisabledSession.execute(String.format(CREATE_TABLE, keyspace));
392381
393382 // Should still wait on schema agreement.
@@ -405,8 +394,8 @@
405394 * @jira_ticket JAVA-858
406395 * @since 2.0.11
407396 */
408- @Test(groups = "short")
409- public void should_refresh_schema_and_token_map_if_schema_metadata_reenabled() throws Exception {
397+ @Test(groups = "short", dataProvider = "existingKeyspaceName")
398+ public void should_refresh_schema_and_token_map_if_schema_metadata_reenabled(String keyspace) throws Exception {
410399 try {
411400 schemaDisabledCluster.getConfiguration().getQueryOptions().setMetadataEnabled(true);
412401
@@ -435,7 +424,7 @@
435424 }
436425 }
437426
438- @AfterMethod(groups = "short")
427+ @AfterMethod(groups = "short", alwaysRun = true)
439428 public void cleanup() throws InterruptedException {
440429 ListenableFuture<List<ResultSet>> f = Futures.successfulAsList(Lists.newArrayList(
441430 session1.executeAsync("DROP TABLE lowercase.table1"),
@@ -451,4 +440,9 @@
451440 private void execute(String cql, String keyspace) throws InterruptedException {
452441 session1.execute(String.format(cql, keyspace));
453442 }
443+
444+ private List<Metadata> metadatas() {
445+ return Lists.newArrayList(cluster1.getMetadata(), cluster2.getMetadata());
446+ }
447+
454448 }
modified driver-core/src/test/java/com/datastax/driver/core/SchemaRefreshDebouncerTest.java +8 −33
@@ -16,23 +16,22 @@
1616 package com.datastax.driver.core;
1717
1818 import org.mockito.ArgumentCaptor;
19-import org.testng.annotations.AfterClass;
2019 import org.testng.annotations.AfterMethod;
21-import org.testng.annotations.BeforeClass;
20+import org.testng.annotations.BeforeMethod;
2221 import org.testng.annotations.Test;
2322
24-import java.util.Collection;
25-
2623 import static com.datastax.driver.core.Assertions.assertThat;
24+import static com.datastax.driver.core.CreateCCM.TestMode.PER_METHOD;
2725 import static com.datastax.driver.core.SchemaElement.KEYSPACE;
2826 import static com.datastax.driver.core.SchemaElement.TABLE;
2927 import static com.datastax.driver.core.TestUtils.CREATE_KEYSPACE_SIMPLE_FORMAT;
3028 import static com.datastax.driver.core.TestUtils.CREATE_TABLE_SIMPLE_FORMAT;
31-import static com.google.common.collect.Lists.newArrayList;
3229 import static org.mockito.ArgumentCaptor.forClass;
3330 import static org.mockito.Mockito.*;
3431
35-public class SchemaRefreshDebouncerTest extends CCMBridge.PerClassSingleNodeCluster {
32+@CreateCCM(PER_METHOD)
33+@CCMConfig(dirtiesContext = true, createKeyspace = false)
34+public class SchemaRefreshDebouncerTest extends CCMTestsSupport {
3635
3736 // This may need to be tweaked depending on the reliability of the test environment.
3837 private static final int DEBOUNCE_TIME = 5000;
@@ -47,22 +46,14 @@
4746 private Session session2;
4847 private Cluster cluster2;
4948
50- // Keyspaces to drop after test completes.
51- private Collection<String> keyspaces = newArrayList();
52-
53- @Override
54- protected Collection<String> getTableDefinitions() {
55- return newArrayList();
56- }
57-
58- @BeforeClass(groups = "short")
49+ @BeforeMethod(groups = "short")
5950 public void setup() {
6051 QueryOptions queryOptions = new QueryOptions();
6152 queryOptions.setRefreshSchemaIntervalMillis(DEBOUNCE_TIME);
6253 queryOptions.setMaxPendingRefreshSchemaRequests(5);
6354 // Create a separate cluster that will receive the schema events on its control connection.
64- cluster2 = this.configure(Cluster.builder())
65- .addContactPointsWithPorts(newArrayList(hostAddress))
55+ cluster2 = Cluster.builder()
56+ .addContactPointsWithPorts(getInitialContactPoints())
6657 .withQueryOptions(queryOptions)
6758 .build();
6859 session2 = cluster2.connect();
@@ -81,17 +72,7 @@
8172
8273 @AfterMethod(groups = "short")
8374 public void beforeMethod() {
84- reset(listener);
85- reset(controlConnection);
86- }
87-
88- @AfterClass(groups = "short")
89- public void teardown() {
9075 cluster2.close();
91- // drop all keyspaces
92- for (String keyspace : keyspaces) {
93- session.execute("DROP KEYSPACE " + keyspace);
94- }
9576 }
9677
9778 /**
@@ -107,7 +88,6 @@
10788 public void should_debounce_and_coalesce_create_and_alter_keyspace_into_refresh_keyspace() throws Exception {
10889 String keyspace = "sdaccaak";
10990 session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, 1));
110- keyspaces.add(keyspace);
11191 session.execute(String.format("ALTER KEYSPACE %s WITH DURABLE_WRITES=false", keyspace));
11292
11393 ArgumentCaptor<KeyspaceMetadata> captor = forClass(KeyspaceMetadata.class);
@@ -140,7 +120,6 @@
140120 String keyspace = "sdacckt";
141121 String table = "tbl1";
142122 session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, 1));
143- keyspaces.add(keyspace);
144123 session.execute(String.format(CREATE_TABLE_SIMPLE_FORMAT, keyspace + "." + table));
145124
146125 ArgumentCaptor<KeyspaceMetadata> keyspaceCaptor = forClass(KeyspaceMetadata.class);
@@ -175,7 +154,6 @@
175154 public void should_debounce_and_coalesce_tables_in_same_keyspace_into_refresh_keyspace() throws Exception {
176155 String keyspace = "sdactisk";
177156 session2.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, 1));
178- keyspaces.add(keyspace);
179157 // Reset invocations as creating keyspace causes a keyspace refresh.
180158 reset(controlConnection);
181159 reset(listener);
@@ -220,7 +198,6 @@
220198 String columnName = "added_column";
221199 // Execute on session 2 which refreshes schema as part of processing responses.
222200 session2.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, 1));
223- keyspaces.add(keyspace);
224201 session2.execute(String.format(CREATE_TABLE_SIMPLE_FORMAT, keyspace + "." + table));
225202 reset(controlConnection);
226203 reset(listener);
@@ -271,7 +248,6 @@
271248 String prefix = "sdacmkc";
272249 for (int i = 0; i < 3; i++) {
273250 session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, prefix + i, 1));
274- keyspaces.add(prefix + i);
275251 }
276252
277253 verify(listener, timeout(DEBOUNCE_TIME * 3).times(3)).onKeyspaceAdded(any(KeyspaceMetadata.class));
@@ -298,7 +274,6 @@
298274 String prefix = "srwmprr";
299275 for (int i = 0; i < 5; i++) {
300276 session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, prefix + i, 1));
301- keyspaces.add(prefix + i);
302277 }
303278
304279 // Event should be processed immediately as we hit our threshold.
modified driver-core/src/test/java/com/datastax/driver/core/SchemaTest.java +3 −11
@@ -26,7 +26,8 @@
2626 /**
2727 * Test we correctly process and print schema.
2828 */
29-public class SchemaTest extends CCMBridge.PerClassSingleNodeCluster {
29+@CCMConfig(clusterProvider = "createClusterBuilderNoDebouncing")
30+public class SchemaTest extends CCMTestsSupport {
3031 static final Logger logger = LoggerFactory.getLogger(SchemaTest.class);
3132
3233 private static final Map<String, String> cql3 = new HashMap<String, String>();
@@ -35,16 +36,7 @@
3536 private static String withOptions;
3637
3738 @Override
38- protected Cluster.Builder configure(Cluster.Builder builder) {
39- return builder.withQueryOptions(new QueryOptions()
40- .setRefreshNodeIntervalMillis(0)
41- .setRefreshNodeListIntervalMillis(0)
42- .setRefreshSchemaIntervalMillis(0)
43- );
44- }
45-
46- @Override
47- protected Collection<String> getTableDefinitions() {
39+ public Collection<String> createTestFixtures() {
4840
4941 String sparse = String.format("CREATE TABLE %s.sparse (\n"
5042 + " k text,\n"
modified driver-core/src/test/java/com/datastax/driver/core/SessionLeakTest.java +68 −97
@@ -17,138 +17,109 @@
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- assertThat(cluster).host(2).comesUpWithin(2, MINUTES);
77-
78- assertThat(cluster.manager.sessions.size()).isEqualTo(0);
79- assertOpenConnections(1);
80-
81- // ensure a new session gets registered and core connections are established
82- // there should be corePoolSize more connections to accommodate for the new host.
83- Session thisSession = cluster.connect();
84- assertThat(cluster.manager.sessions.size()).isEqualTo(1);
85- assertOpenConnections(1 + (corePoolSize * 2));
86-
87- // ensure bootstrapping a node does not create additional connections that won't get cleaned up
88- thisSession.close();
89-
90- assertThat(cluster.manager.sessions.size()).isEqualTo(0);
91- assertOpenConnections(1);
92- } finally {
93- if (cluster != null) {
94- cluster.close();
95- }
96- if (ccmBridge != null) {
97- ccmBridge.remove();
98- }
99- // Ensure no channels remain open.
100- channelMonitor.stop();
101- channelMonitor.report();
102- assertThat(channelMonitor.openChannels(nodes).size()).isEqualTo(0);
103- }
42+ cluster = register(Cluster.builder()
43+ .addContactPointsWithPorts(getHostAddress(1))
44+ .withAddressTranslater(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+ assertThat(cluster).host(2).comesUpWithin(2, MINUTES);
71+
72+ assertThat(cluster.manager.sessions.size()).isEqualTo(0);
73+ assertOpenConnections(1);
74+
75+ // ensure a new session gets registered and core connections are established
76+ // there should be corePoolSize more connections to accommodate for the new host.
77+ Session thisSession = cluster.connect();
78+ assertThat(cluster.manager.sessions.size()).isEqualTo(1);
79+ assertOpenConnections(1 + (corePoolSize * 2));
80+
81+ // ensure bootstrapping a node does not create additional connections that won't get cleaned up
82+ thisSession.close();
83+
84+ assertThat(cluster.manager.sessions.size()).isEqualTo(0);
85+ assertOpenConnections(1);
86+ cluster.close();
87+ // Ensure no channels remain open.
88+ channelMonitor.stop();
89+ channelMonitor.report();
90+ assertThat(channelMonitor.openChannels(newArrayList(ccm.addressOfNode(1), ccm.addressOfNode(2))).size()).isEqualTo(0);
10491 }
10592
10693 @Test(groups = "short")
10794 public void should_not_leak_session_when_wrong_keyspace() throws Exception {
10895 // Checking for JAVA-806
109- CCMBridge ccmBridge;
110- ccmBridge = CCMBridge.builder("test").withNodes(1).build();
11196 channelMonitor = new SocketChannelMonitor();
11297 channelMonitor.reportAtFixedInterval(1, TimeUnit.SECONDS);
98+ cluster = register(Cluster.builder()
99+ .addContactPointsWithPorts(getHostAddress(1))
100+ .withAddressTranslater(getAddressTranslator())
101+ .withNettyOptions(channelMonitor.nettyOptions())
102+ .build());
103+ cluster.init();
104+ assertThat(cluster.manager.sessions.size()).isEqualTo(0);
113105 try {
114- cluster = Cluster.builder()
115- .addContactPointsWithPorts(Collections.singletonList(
116- new InetSocketAddress(CCMBridge.IP_PREFIX + '1', 9042)))
117- .withNettyOptions(channelMonitor.nettyOptions()).build();
118-
119- cluster.init();
120-
121- assertThat(cluster.manager.sessions.size()).isEqualTo(0);
122106 // Should be 1 control connection after initialization.
123107 assertOpenConnections(1);
124-
125108 cluster.connect("wrong_keyspace");
126-
127109 fail("Should not have connected to a wrong keyspace");
128-
129110 } catch (InvalidQueryException e) {
130-
131111 // ok
132-
133- } finally {
134-
135- assertThat(cluster.manager.sessions.size()).isEqualTo(0);
136-
137- if (cluster != null) {
138- cluster.close();
139- }
140- if (ccmBridge != null) {
141- ccmBridge.remove();
142- }
143- // Ensure no channels remain open.
144- channelMonitor.stop();
145- channelMonitor.report();
146- assertThat(channelMonitor.openChannels(nodes).size()).isEqualTo(0);
147112 }
113+ assertThat(cluster.manager.sessions.size()).isEqualTo(0);
114+ cluster.close();
115+ // Ensure no channels remain open.
116+ channelMonitor.stop();
117+ channelMonitor.report();
118+ assertThat(channelMonitor.openChannels(ccm.addressOfNode(1), ccm.addressOfNode(2)).size()).isEqualTo(0);
148119 }
149120
150121 private void assertOpenConnections(int expected) {
151122 assertThat((cluster.getMetrics().getOpenConnections().getValue())).isEqualTo(expected);
152- assertThat(channelMonitor.openChannels(nodes).size()).isEqualTo(expected);
123+ assertThat(channelMonitor.openChannels(ccm.addressOfNode(1), ccm.addressOfNode(2)).size()).isEqualTo(expected);
153124 }
154125 }
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(TestUtils.CREATE_TABLE_SIMPLE_FORMAT, TABLE1),
4746 String.format(TestUtils.CREATE_TABLE_SIMPLE_FORMAT, TABLE2),
4847 String.format(TestUtils.CREATE_TABLE_SIMPLE_FORMAT, 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 +5 −3
@@ -50,7 +50,8 @@
5050
5151 loadBalancingPolicy = new SortingLoadBalancingPolicy();
5252 cluster = Cluster.builder()
53- .addContactPoint(scassandras.address(2))
53+ .addContactPointsWithPorts(scassandras.address(2))
54+ .withAddressTranslater(scassandras.addressTranslator())
5455 .withLoadBalancingPolicy(loadBalancingPolicy)
5556 .withSpeculativeExecutionPolicy(new ConstantSpeculativeExecutionPolicy(speculativeExecutionDelay, 1))
5657 .withQueryOptions(new QueryOptions().setDefaultIdempotence(true))
@@ -67,7 +68,7 @@
6768 errors = cluster.getMetrics().getErrorMetrics();
6869 }
6970
70- @AfterMethod(groups = "short")
71+ @AfterMethod(groups = "short", alwaysRun = true)
7172 public void afterMethod() {
7273 if (cluster != null)
7374 cluster.close();
@@ -200,7 +201,8 @@
200201 SpeculativeExecutionPolicy mockPolicy = mock(SpeculativeExecutionPolicy.class);
201202
202203 Cluster cluster = Cluster.builder()
203- .addContactPoint(CCMBridge.ipOfNode(2))
204+ .addContactPointsWithPorts(scassandras.address(2))
205+ .withAddressTranslater(scassandras.addressTranslator())
204206 .withSpeculativeExecutionPolicy(mockPolicy)
205207 .build();
206208
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 +4 −10
@@ -16,28 +16,22 @@
1616 package com.datastax.driver.core;
1717
1818 import com.datastax.driver.core.policies.*;
19-import com.google.common.collect.Lists;
2019 import org.testng.annotations.Test;
2120
22-import java.util.Collection;
2321 import java.util.Iterator;
2422 import java.util.concurrent.atomic.AtomicInteger;
2523
2624 import static org.assertj.core.api.Assertions.assertThat;
2725
28-public class StatementWrapperTest extends CCMBridge.PerClassSingleNodeCluster {
29- @Override
30- protected Collection<String> getTableDefinitions() {
31- return Lists.newArrayList();
32- }
26+public class StatementWrapperTest extends CCMTestsSupport {
3327
3428 CustomLoadBalancingPolicy loadBalancingPolicy = new CustomLoadBalancingPolicy();
3529 CustomSpeculativeExecutionPolicy speculativeExecutionPolicy = new CustomSpeculativeExecutionPolicy();
3630 CustomRetryPolicy retryPolicy = new CustomRetryPolicy();
3731
3832 @Override
39- protected Cluster.Builder configure(Cluster.Builder builder) {
40- return builder
33+ public Cluster.Builder createClusterBuilder() {
34+ return Cluster.builder()
4135 .withLoadBalancingPolicy(loadBalancingPolicy)
4236 .withSpeculativeExecutionPolicy(speculativeExecutionPolicy)
4337 .withRetryPolicy(retryPolicy);
@@ -151,4 +145,4 @@
151145 return RetryDecision.rethrow();
152146 }
153147 }
154-}
No newline at the end of the file
148+}
modified driver-core/src/test/java/com/datastax/driver/core/TableMetadataTest.java +3 −11
@@ -22,9 +22,10 @@
2222
2323 import static org.assertj.core.api.Assertions.assertThat;
2424
25-public class TableMetadataTest extends CCMBridge.PerClassSingleNodeCluster {
25+@CCMConfig(clusterProvider = "createClusterBuilderNoDebouncing")
26+public class TableMetadataTest extends CCMTestsSupport {
2627 @Override
27- protected Collection<String> getTableDefinitions() {
28+ public Collection<String> createTestFixtures() {
2829 return Lists.newArrayList(
2930 "CREATE TABLE single_quote (\n"
3031 + " c1 int PRIMARY KEY\n"
@@ -32,15 +33,6 @@
3233 );
3334 }
3435
35- @Override
36- protected Cluster.Builder configure(Cluster.Builder builder) {
37- return builder.withQueryOptions(new QueryOptions()
38- .setRefreshNodeIntervalMillis(0)
39- .setRefreshNodeListIntervalMillis(0)
40- .setRefreshSchemaIntervalMillis(0)
41- );
42- }
43-
4436 @Test(groups = "short")
4537 public void should_escape_single_quote_table_comment() {
4638 TableMetadata table = cluster.getMetadata().getKeyspace(keyspace).getTable("single_quote");
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 +187 −92
@@ -17,8 +17,10 @@
1717
1818 import com.datastax.driver.core.policies.RoundRobinPolicy;
1919 import com.datastax.driver.core.policies.WhiteListPolicy;
20+import com.google.common.base.Predicate;
2021 import com.google.common.util.concurrent.Futures;
2122 import com.google.common.util.concurrent.Uninterruptibles;
23+import com.sun.management.OperatingSystemMXBean;
2224 import io.netty.channel.EventLoopGroup;
2325 import org.scassandra.Scassandra;
2426 import org.scassandra.ScassandraFactory;
@@ -26,21 +28,36 @@
2628 import org.slf4j.LoggerFactory;
2729
2830 import java.io.IOException;
31+import java.lang.management.ManagementFactory;
2932 import java.math.BigDecimal;
3033 import java.math.BigInteger;
3134 import java.net.InetAddress;
3235 import java.net.InetSocketAddress;
3336 import java.net.ServerSocket;
37+import java.net.Socket;
3438 import java.nio.ByteBuffer;
3539 import java.util.*;
40+import java.util.concurrent.Callable;
3641 import java.util.concurrent.CountDownLatch;
3742 import java.util.concurrent.TimeUnit;
43+import java.util.concurrent.atomic.AtomicInteger;
44+import java.util.concurrent.locks.ReentrantLock;
3845
3946 /**
4047 * A number of static fields/methods handy for tests.
4148 */
4249 public abstract class TestUtils {
4350
51+ public static final String IP_PREFIX;
52+
53+ static {
54+ String ip_prefix = System.getProperty("ipprefix");
55+ if (ip_prefix == null || ip_prefix.isEmpty()) {
56+ ip_prefix = "127.0.1.";
57+ }
58+ IP_PREFIX = ip_prefix;
59+ }
60+
4461 private static final Logger logger = LoggerFactory.getLogger(TestUtils.class);
4562
4663 public static final String CREATE_KEYSPACE_SIMPLE_FORMAT = "CREATE KEYSPACE %s WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor' : %d }";
@@ -56,6 +73,8 @@
5673
5774 public static final int TEST_BASE_NODE_WAIT = SystemProperties.getInt("com.datastax.driver.TEST_BASE_NODE_WAIT", 60);
5875
76+ private static final AtomicInteger KS_COUNTER = new AtomicInteger(1);
77+
5978 @SuppressWarnings({"unchecked", "rawtypes"})
6079 public static BoundStatement setBoundValue(BoundStatement bs, String name, DataType type, Object value) {
6180 switch (type.getName()) {
@@ -286,114 +305,99 @@
286305 // This is used because there is some delay between when a node has been
287306 // added through ccm and when it's actually available for querying
288307 public static void waitFor(String node, Cluster cluster) {
289- waitFor(node, cluster, TEST_BASE_NODE_WAIT, false, false);
308+ waitFor(node, cluster, TEST_BASE_NODE_WAIT, false);
290309 }
291310
292311 public static void waitFor(String node, Cluster cluster, int maxTry) {
293- waitFor(node, cluster, maxTry, false, false);
312+ waitFor(node, cluster, maxTry, false);
294313 }
295314
296315 public static void waitForDown(String node, Cluster cluster) {
297- waitFor(node, cluster, TEST_BASE_NODE_WAIT * 3, true, false);
298- }
299-
300- public static void waitForDownWithWait(String node, Cluster cluster, int waitTime) {
301- waitForDown(node, cluster);
302-
303- // FIXME: Once stop() works, remove this line
304- try {
305- Thread.sleep(waitTime * 1000);
306- } catch (InterruptedException e) {
307- e.printStackTrace();
308- }
316+ waitFor(node, cluster, TEST_BASE_NODE_WAIT * 3, true);
309317 }
310318
311319 public static void waitForDown(String node, Cluster cluster, int maxTry) {
312- waitFor(node, cluster, maxTry, true, false);
313- }
314-
315- public static void stopAndWait(CCMBridge.CCMCluster c, int node) {
316- c.cassandraCluster.stop(node);
317- waitForDownWithWait(CCMBridge.IP_PREFIX + node, c.cluster, 5);
320+ waitFor(node, cluster, maxTry, true);
318321 }
319322
320323 public static void waitForDecommission(String node, Cluster cluster) {
321- waitFor(node, cluster, TEST_BASE_NODE_WAIT / 2, true, true);
324+ waitFor(node, cluster, TEST_BASE_NODE_WAIT / 2, true);
322325 }
323326
324327 public static void waitForDecommission(String node, Cluster cluster, int maxTry) {
325- waitFor(node, cluster, maxTry, true, true);
328+ waitFor(node, cluster, maxTry, true);
326329 }
327330
328- private static void waitFor(String node, Cluster cluster, int maxTry, boolean waitForDead, boolean waitForOut) {
329- if (waitForDead || waitForOut)
330- if (waitForDead)
331- logger.info("Waiting for stopped node: " + node);
332- else if (waitForOut)
333- logger.info("Waiting for decommissioned node: " + node);
334- else
335- logger.info("Waiting for upcoming node: " + node);
336-
331+ private static void waitFor(String node, Cluster cluster, int timeoutSeconds, boolean waitForDown) {
332+ if (waitForDown)
333+ logger.debug("Waiting for node to leave: {}", node);
334+ else
335+ logger.debug("Waiting for upcoming node: {}", node);
337336 // In the case where the we've killed the last node in the cluster, if we haven't
338337 // tried doing an actual query, the driver won't realize that last node is dead until
339338 // keep alive kicks in, but that's a fairly long time. So we cheat and trigger a force
340339 // the detection by forcing a request.
341- if (waitForDead || waitForOut) {
340+ if (waitForDown) {
342341 Futures.getUnchecked(cluster.manager.submitSchemaRefresh(null, null, null));
343342 }
343+ if (waitForDown) {
344+ ConditionChecker.awaitUntil(new HostIsDownCondition(cluster, node), timeoutSeconds * 1000);
345+ } else {
346+ ConditionChecker.awaitUntil(new HostIsUpCondition(cluster, node), timeoutSeconds * 1000);
347+ }
348+ }
344349
345- InetAddress address;
346- try {
347- address = InetAddress.getByName(node);
348- } catch (Exception e) {
349- // That's a problem but that's not *our* problem
350- return;
350+ private static class HostIsDownCondition implements Callable<Boolean> {
351+
352+ private final Cluster cluster;
353+
354+ private final String ip;
355+
356+ public HostIsDownCondition(Cluster cluster, String ip) {
357+ this.cluster = cluster;
358+ this.ip = ip;
351359 }
352360
353- Metadata metadata = cluster.getMetadata();
354- for (int i = 0; i < maxTry; ++i) {
355- for (Host host : metadata.getAllHosts()) {
356- if (host.getAddress().equals(address) && testHost(host, waitForDead)) {
357- try {
358- Thread.sleep(10000);
359- } catch (Exception e) {
360- }
361- return;
362- }
363- }
364- try {
365- Thread.sleep(1000);
366- } catch (Exception e) {
367- }
361+ @Override
362+ public Boolean call() throws Exception {
363+ final Host host = findHost(cluster, ip);
364+ return host == null || !host.isUp();
368365 }
366+ }
369367
370- for (Host host : metadata.getAllHosts()) {
371- if (host.getAddress().equals(address)) {
372- if (testHost(host, waitForDead)) {
373- return;
374- } else {
375- // logging it because this give use the timestamp of when this happens
376- logger.info(node + " is not " + (waitForDead ? "DOWN" : "UP") + " after " + maxTry + 's');
377- throw new IllegalStateException(node + " is not " + (waitForDead ? "DOWN" : "UP") + " after " + maxTry + 's');
378- }
379- }
368+ private static class HostIsUpCondition implements Callable<Boolean> {
369+
370+ private final Cluster cluster;
371+
372+ private final String ip;
373+
374+ public HostIsUpCondition(Cluster cluster, String ip) {
375+ this.cluster = cluster;
376+ this.ip = ip;
380377 }
381378
382- if (waitForOut) {
383- return;
384- } else {
385- logger.info(node + " is not part of the cluster after " + maxTry + 's');
386- throw new IllegalStateException(node + " is not part of the cluster after " + maxTry + 's');
379+ @Override
380+ public Boolean call() throws Exception {
381+ final Host host = findHost(cluster, ip);
382+ return host != null && host.isUp();
387383 }
388384 }
389385
390- private static boolean testHost(Host host, boolean testForDown) {
391- return testForDown ? !host.isUp() : host.isUp();
386+ /**
387+ * Returns the IP of the {@code nth} host in the CCM cluster (counting from 1, i.e.,
388+ * {@code ipOfNode(1)} returns the IP of the first node.
389+ * <p/>
390+ * In multi-DC setups, nodes are numbered in ascending order of their datacenter number.
391+ * E.g. with 2 DCs and 3 nodes in each DC, the first node in DC 2 is number 4.
392+ *
393+ * @return the IP of the {@code nth} host in the cluster.
394+ */
395+ public static String ipOfNode(int n) {
396+ return IP_PREFIX + n;
392397 }
393398
394-
395399 public static Host findOrWaitForHost(Cluster cluster, int node, long duration, TimeUnit unit) {
396- return findOrWaitForHost(cluster, CCMBridge.ipOfNode(node), duration, unit);
400+ return findOrWaitForHost(cluster, ipOfNode(node), duration, unit);
397401 }
398402
399403 public static Host findOrWaitForHost(final Cluster cluster, final String address, long duration, TimeUnit unit) {
@@ -425,7 +429,7 @@
425429 }
426430
427431 public static Host findHost(Cluster cluster, int hostNumber) {
428- return findHost(cluster, CCMBridge.ipOfNode(hostNumber));
432+ return findHost(cluster, ipOfNode(hostNumber));
429433 }
430434
431435 public static Host findHost(Cluster cluster, String address) {
@@ -467,29 +471,95 @@
467471 * 8052-8152.
468472 */
469473 public static Scassandra createScassandraServer() {
470- int binaryPort = findAvailablePort(8042);
471- int adminPort = findAvailablePort(8052);
472- return ScassandraFactory.createServer(binaryPort, adminPort);
474+ int binaryPort = findAvailablePort();
475+ int adminPort = findAvailablePort();
476+ return ScassandraFactory.createServer(ipOfNode(1), binaryPort, ipOfNode(1), adminPort);
477+ }
478+
479+ public static String getAvailableKeyspaceName() {
480+ return SIMPLE_KEYSPACE + "_" + KS_COUNTER.getAndIncrement();
473481 }
474482
483+ // use ports in the ephemeral range
484+ private static int nextPort = 50000;
485+
486+ private static final ReentrantLock PORT_LOCK = new ReentrantLock();
487+
475488 /**
476- * @param startingWith The first port to try, if unused will keep trying the next port until one is found up to
477- * 100 subsequent ports.
489+ * Find an available port in the ephemeral range.
490+ *
478491 * @return A local port that is currently unused.
479492 */
480- public static int findAvailablePort(int startingWith) {
481- IOException last = null;
482- for (int port = startingWith; port < startingWith + 100; port++) {
483- try {
484- ServerSocket s = new ServerSocket(port);
485- s.close();
486- return port;
487- } catch (IOException e) {
488- last = e;
493+ public static int findAvailablePort() {
494+ PORT_LOCK.lock();
495+ try {
496+ for (int i = 0; i < 3; i++) {
497+ int port = nextPort;
498+ ServerSocket s = null;
499+ for (int j = 0; j < 100; j++) {
500+ try {
501+ s = new ServerSocket(port);
502+ s.close();
503+ nextPort = port + 1;
504+ return port;
505+ } catch (IOException e) {
506+ // ok
507+ } finally {
508+ port++;
509+ if (s != null) {
510+ try {
511+ s.close();
512+ } catch (IOException e) {
513+ // ok
514+ }
515+ }
516+ }
517+ }
518+ logger.warn("Could not acquire an available port after 100 attempts, sleeping for 1 minute");
519+ Uninterruptibles.sleepUninterruptibly(1, TimeUnit.MINUTES);
489520 }
521+ throw new RuntimeException(String.format("Could not acquire an available port within range: %s-%s", nextPort, nextPort + 100));
522+ } finally {
523+ PORT_LOCK.unlock();
524+ }
525+ }
526+
527+ private static final Predicate<InetSocketAddress> PORT_IS_UP = new Predicate<InetSocketAddress>() {
528+
529+ @Override
530+ public boolean apply(InetSocketAddress address) {
531+ return pingPort(address.getAddress(), address.getPort());
532+ }
533+
534+ };
535+
536+ public static void waitUntilPortIsUp(InetSocketAddress address) {
537+ ConditionChecker.awaitUntil(address, PORT_IS_UP, TimeUnit.SECONDS.toMillis(10));
538+ }
539+
540+ public static void waitUntilPortIsDown(InetSocketAddress address) {
541+ ConditionChecker.awaitWhile(address, PORT_IS_UP, TimeUnit.SECONDS.toMillis(10));
542+ }
543+
544+ public static boolean pingPort(InetAddress address, int port) {
545+ logger.debug("Trying {}:{}...", address, port);
546+ boolean connectionSuccessful = false;
547+ Socket socket = null;
548+ try {
549+ socket = new Socket(address, port);
550+ connectionSuccessful = true;
551+ logger.debug("Successfully connected");
552+ } catch (IOException e) {
553+ logger.debug("Connection failed");
554+ } finally {
555+ if (socket != null)
556+ try {
557+ socket.close();
558+ } catch (IOException e) {
559+ logger.warn("Error closing socket to " + address);
560+ }
490561 }
491- // If for whatever reason a port could not be acquired throw the last encountered exception.
492- throw new RuntimeException("Could not acquire an available port", last);
562+ return connectionSuccessful;
493563 }
494564
495565 /**
@@ -509,19 +579,20 @@
509579 }
510580
511581 /**
512- * @return a {@Cluster} instance that connects only to the control host of the given cluster.
582+ * @return a {@link Cluster} instance that connects only to the control host of the given cluster.
513583 */
514- public static Cluster buildControlCluster(Cluster cluster) {
584+ public static Cluster buildControlCluster(Cluster cluster, CCMBridge ccm) {
515585 Host controlHost = cluster.manager.controlConnection.connectedHost();
516586 List<InetSocketAddress> singleAddress = Collections.singletonList(controlHost.getSocketAddress());
517587 return Cluster.builder()
518588 .addContactPointsWithPorts(singleAddress)
589+ .withAddressTranslater(ccm.addressTranslator())
519590 .withLoadBalancingPolicy(new WhiteListPolicy(new RoundRobinPolicy(), singleAddress))
520591 .build();
521592 }
522593
523594 /**
524- * @return a {@QueryOptions} that disables debouncing by setting intervals to 0ms.
595+ * @return a {@link QueryOptions} that disables debouncing by setting intervals to 0ms.
525596 */
526597 public static QueryOptions nonDebouncingQueryOptions() {
527598 return new QueryOptions().setRefreshNodeIntervalMillis(0)
@@ -540,4 +611,28 @@
540611 eventLoopGroup.shutdownGracefully(0, 15, TimeUnit.SECONDS).syncUninterruptibly();
541612 }
542613 };
614+
615+ public static void executeNoFail(Runnable task, boolean logException) {
616+ try {
617+ task.run();
618+ } catch (Exception e) {
619+ if (logException)
620+ logger.error(e.getMessage(), e);
621+ }
622+ }
623+
624+ public static void executeNoFail(Callable<?> task, boolean logException) {
625+ try {
626+ task.call();
627+ } catch (Exception e) {
628+ if (logException)
629+ logger.error(e.getMessage(), e);
630+ }
631+ }
632+
633+ public static long getFreeMemoryMB() {
634+ OperatingSystemMXBean bean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
635+ return (bean.getFreePhysicalMemorySize() + bean.getFreeSwapSpaceSize()) / 1024 / 1024;
636+ }
637+
543638 }
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 +36 −63
@@ -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", DataType.cint().serialize(testKey, cluster.getConfiguration().getProtocolOptions().getProtocolVersionEnum()));
96+ Set<Host> replicas = metadata.getReplicas(ks1, DataType.cint().serialize(testKey, cluster.getConfiguration().getProtocolOptions().getProtocolVersionEnum()));
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
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
@@ -27,11 +27,11 @@
2727 import static org.testng.Assert.fail;
2828
2929 @CassandraVersion(major = 2.1)
30-public class TupleTest extends CCMBridge.PerClassSingleNodeCluster {
30+public class TupleTest extends CCMTestsSupport {
3131
3232 @Override
33- protected Collection<String> getTableDefinitions() {
34- return Arrays.asList("CREATE TABLE t (k int PRIMARY KEY, v frozen<tuple<int, text, float>>)");
33+ public Collection<String> createTestFixtures() {
34+ return Collections.singleton("CREATE TABLE t (k int PRIMARY KEY, v frozen<tuple<int, text, float>>)");
3535 }
3636
3737 @Test(groups = "short")
@@ -46,7 +46,6 @@
4646 assertEquals(v.getType().getComponentTypes().get(0), DataType.cint());
4747 assertEquals(v.getType().getComponentTypes().get(1), DataType.text());
4848 assertEquals(v.getType().getComponentTypes().get(2), DataType.cfloat());
49-
5049 assertEquals(v.getInt(0), 1);
5150 assertEquals(v.getString(1), "a");
5251 assertEquals(v.getFloat(2), 1.0f);
@@ -56,33 +55,28 @@
5655
5756 @Test(groups = "short")
5857 public void simpleWriteReadTest() throws Exception {
59- try {
60- session.execute("USE " + keyspace);
61- PreparedStatement ins = session.prepare("INSERT INTO t(k, v) VALUES (?, ?)");
62- PreparedStatement sel = session.prepare("SELECT * FROM t WHERE k=?");
58+ session.execute("USE " + keyspace);
59+ PreparedStatement ins = session.prepare("INSERT INTO t(k, v) VALUES (?, ?)");
60+ PreparedStatement sel = session.prepare("SELECT * FROM t WHERE k=?");
6361
64- TupleType t = TupleType.of(DataType.cint(), DataType.text(), DataType.cfloat());
62+ TupleType t = TupleType.of(DataType.cint(), DataType.text(), DataType.cfloat());
6563
66- int k = 1;
67- TupleValue v = t.newValue(1, "a", 1.0f);
64+ int k = 1;
65+ TupleValue v = t.newValue(1, "a", 1.0f);
6866
69- session.execute(ins.bind(k, v));
70- TupleValue v2 = session.execute(sel.bind(k)).one().getTupleValue("v");
67+ session.execute(ins.bind(k, v));
68+ TupleValue v2 = session.execute(sel.bind(k)).one().getTupleValue("v");
7169
72- assertEquals(v2, v);
70+ assertEquals(v2, v);
7371
74- // Test simple statement interpolation
75- k = 2;
76- v = t.newValue(2, "b", 2.0f);
72+ // Test simple statement interpolation
73+ k = 2;
74+ v = t.newValue(2, "b", 2.0f);
7775
78- session.execute("INSERT INTO t(k, v) VALUES (?, ?)", k, v);
79- v2 = session.execute(sel.bind(k)).one().getTupleValue("v");
76+ session.execute("INSERT INTO t(k, v) VALUES (?, ?)", k, v);
77+ v2 = session.execute(sel.bind(k)).one().getTupleValue("v");
8078
81- assertEquals(v2, v);
82- } catch (Exception e) {
83- errorOut();
84- throw e;
85- }
79+ assertEquals(v2, v);
8680 }
8781
8882 /**
@@ -93,65 +87,61 @@
9387 */
9488 @Test(groups = "short")
9589 public void tupleTypeTest() throws Exception {
90+ session.execute("CREATE KEYSPACE test_tuple_type " +
91+ "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
92+ session.execute("USE test_tuple_type");
93+ session.execute("CREATE TABLE mytable (a int PRIMARY KEY, b frozen<tuple<ascii, int, boolean>>)");
94+
95+ TupleType t = TupleType.of(DataType.ascii(), DataType.cint(), DataType.cboolean());
96+
97+ // test non-prepared statement
98+ TupleValue complete = t.newValue("foo", 123, true);
99+ session.execute("INSERT INTO mytable (a, b) VALUES (0, ?)", complete);
100+ TupleValue r = session.execute("SELECT b FROM mytable WHERE a=0").one().getTupleValue("b");
101+ assertEquals(r, complete);
102+
103+ // test incomplete tuples
96104 try {
97- session.execute("CREATE KEYSPACE test_tuple_type " +
98- "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
99- session.execute("USE test_tuple_type");
100- session.execute("CREATE TABLE mytable (a int PRIMARY KEY, b frozen<tuple<ascii, int, boolean>>)");
101-
102- TupleType t = TupleType.of(DataType.ascii(), DataType.cint(), DataType.cboolean());
103-
104- // test non-prepared statement
105- TupleValue complete = t.newValue("foo", 123, true);
106- session.execute("INSERT INTO mytable (a, b) VALUES (0, ?)", complete);
107- TupleValue r = session.execute("SELECT b FROM mytable WHERE a=0").one().getTupleValue("b");
108- assertEquals(r, complete);
109-
110- // test incomplete tuples
111- try {
112- TupleValue partial = t.newValue("bar", 456);
113- fail();
114- } catch (IllegalArgumentException e) {
115- }
116-
117- // test incomplete tuples with new TupleType
118- TupleType t1 = TupleType.of(DataType.ascii(), DataType.cint());
119- TupleValue partial = t1.newValue("bar", 456);
120- TupleValue partionResult = t.newValue("bar", 456, null);
121- session.execute("INSERT INTO mytable (a, b) VALUES (0, ?)", partial);
122- r = session.execute("SELECT b FROM mytable WHERE a=0").one().getTupleValue("b");
123- assertEquals(r, partionResult);
124-
125- // test single value tuples
126- try {
127- TupleValue subpartial = t.newValue("zoo");
128- fail();
129- } catch (IllegalArgumentException e) {
130- }
105+ t.newValue("bar", 456);
106+ fail();
107+ } catch (IllegalArgumentException e) {
108+ //ok
109+ }
131110
132- // test single value tuples with new TupleType
133- TupleType t2 = TupleType.of(DataType.ascii());
134- TupleValue subpartial = t2.newValue("zoo");
135- TupleValue subpartialResult = t.newValue("zoo", null, null);
136- session.execute("INSERT INTO mytable (a, b) VALUES (0, ?)", subpartial);
137- r = session.execute("SELECT b FROM mytable WHERE a=0").one().getTupleValue("b");
138- assertEquals(r, subpartialResult);
139-
140- // test prepared statements
141- PreparedStatement prepared = session.prepare("INSERT INTO mytable (a, b) VALUES (?, ?)");
142- session.execute(prepared.bind(3, complete));
143- session.execute(prepared.bind(4, partial));
144- session.execute(prepared.bind(5, subpartial));
145-
146- prepared = session.prepare("SELECT b FROM mytable WHERE a=?");
147- assertEquals(session.execute(prepared.bind(3)).one().getTupleValue("b"), complete);
148- assertEquals(session.execute(prepared.bind(4)).one().getTupleValue("b"), partionResult);
149- assertEquals(session.execute(prepared.bind(5)).one().getTupleValue("b"), subpartialResult);
150-
151- } catch (Exception e) {
152- errorOut();
153- throw e;
111+ // test incomplete tuples with new TupleType
112+ TupleType t1 = TupleType.of(DataType.ascii(), DataType.cint());
113+ TupleValue partial = t1.newValue("bar", 456);
114+ TupleValue partionResult = t.newValue("bar", 456, null);
115+ session.execute("INSERT INTO mytable (a, b) VALUES (0, ?)", partial);
116+ r = session.execute("SELECT b FROM mytable WHERE a=0").one().getTupleValue("b");
117+ assertEquals(r, partionResult);
118+
119+ // test single value tuples
120+ try {
121+ t.newValue("zoo");
122+ fail();
123+ } catch (IllegalArgumentException e) {
124+ //ok
154125 }
126+
127+ // test single value tuples with new TupleType
128+ TupleType t2 = TupleType.of(DataType.ascii());
129+ TupleValue subpartial = t2.newValue("zoo");
130+ TupleValue subpartialResult = t.newValue("zoo", null, null);
131+ session.execute("INSERT INTO mytable (a, b) VALUES (0, ?)", subpartial);
132+ r = session.execute("SELECT b FROM mytable WHERE a=0").one().getTupleValue("b");
133+ assertEquals(r, subpartialResult);
134+
135+ // test prepared statements
136+ PreparedStatement prepared = session.prepare("INSERT INTO mytable (a, b) VALUES (?, ?)");
137+ session.execute(prepared.bind(3, complete));
138+ session.execute(prepared.bind(4, partial));
139+ session.execute(prepared.bind(5, subpartial));
140+
141+ prepared = session.prepare("SELECT b FROM mytable WHERE a=?");
142+ assertEquals(session.execute(prepared.bind(3)).one().getTupleValue("b"), complete);
143+ assertEquals(session.execute(prepared.bind(4)).one().getTupleValue("b"), partionResult);
144+ assertEquals(session.execute(prepared.bind(5)).one().getTupleValue("b"), subpartialResult);
155145 }
156146
157147 /**
@@ -163,47 +153,41 @@
163153 */
164154 @Test(groups = "short")
165155 public void tupleTestTypeVaryingLengths() throws Exception {
166- try {
167- session.execute("CREATE KEYSPACE test_tuple_type_varying_lengths " +
168- "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
169- session.execute("USE test_tuple_type_varying_lengths");
170-
171- // programmatically create the table with tuples of said sizes
172- int[] lengths = {1, 2, 3, 384};
173- ArrayList<String> valueSchema = new ArrayList<String>();
174- for (int i : lengths) {
175- ArrayList<String> ints = new ArrayList<String>();
176- for (int j = 0; j < i; ++j) {
177- ints.add("int");
178- }
179- valueSchema.add(String.format(" v_%d frozen<tuple<%s>>", i, Joiner.on(',').join(ints)));
156+ session.execute("CREATE KEYSPACE test_tuple_type_varying_lengths " +
157+ "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
158+ session.execute("USE test_tuple_type_varying_lengths");
159+
160+ // programmatically create the table with tuples of said sizes
161+ int[] lengths = {1, 2, 3, 384};
162+ ArrayList<String> valueSchema = new ArrayList<String>();
163+ for (int i : lengths) {
164+ ArrayList<String> ints = new ArrayList<String>();
165+ for (int j = 0; j < i; ++j) {
166+ ints.add("int");
180167 }
181- session.execute(String.format("CREATE TABLE mytable (k int PRIMARY KEY, %s)", Joiner.on(',').join(valueSchema)));
182-
183- // insert tuples into same key using different columns
184- // and verify the results
185- for (int i : lengths) {
186- // create tuple
187- ArrayList<DataType> dataTypes = new ArrayList<DataType>();
188- ArrayList<Integer> values = new ArrayList<Integer>();
189- for (int j = 0; j < i; ++j) {
190- dataTypes.add(DataType.cint());
191- values.add(j);
192- }
193- TupleType t = new TupleType(dataTypes);
194- TupleValue createdTuple = t.newValue(values.toArray());
195-
196- // write tuple
197- session.execute(String.format("INSERT INTO mytable (k, v_%s) VALUES (0, ?)", i), createdTuple);
198-
199- // read tuple
200- TupleValue r = session.execute(String.format("SELECT v_%s FROM mytable WHERE k=0", i)).one().getTupleValue(String.format("v_%s", i));
201- assertEquals(r, createdTuple);
168+ valueSchema.add(String.format(" v_%d frozen<tuple<%s>>", i, Joiner.on(',').join(ints)));
169+ }
170+ session.execute(String.format("CREATE TABLE mytable (k int PRIMARY KEY, %s)", Joiner.on(',').join(valueSchema)));
171+
172+ // insert tuples into same key using different columns
173+ // and verify the results
174+ for (int i : lengths) {
175+ // create tuple
176+ ArrayList<DataType> dataTypes = new ArrayList<DataType>();
177+ ArrayList<Integer> values = new ArrayList<Integer>();
178+ for (int j = 0; j < i; ++j) {
179+ dataTypes.add(DataType.cint());
180+ values.add(j);
202181 }
203-
204- } catch (Exception e) {
205- errorOut();
206- throw e;
182+ TupleType t = new TupleType(dataTypes);
183+ TupleValue createdTuple = t.newValue(values.toArray());
184+
185+ // write tuple
186+ session.execute(String.format("INSERT INTO mytable (k, v_%s) VALUES (0, ?)", i), createdTuple);
187+
188+ // read tuple
189+ TupleValue r = session.execute(String.format("SELECT v_%s FROM mytable WHERE k=0", i)).one().getTupleValue(String.format("v_%s", i));
190+ assertEquals(r, createdTuple);
207191 }
208192 }
209193
@@ -217,59 +201,52 @@
217201 public void tupleSubtypesTest() throws Exception {
218202
219203 List<DataType> DATA_TYPE_PRIMITIVES = Lists.newArrayList(PrimitiveTypeSamples.ALL.keySet());
204+ session.execute("CREATE KEYSPACE test_tuple_subtypes " +
205+ "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
206+ session.execute("USE test_tuple_subtypes");
207+
208+ // programmatically create the table with a tuple of all datatypes
209+ session.execute(String.format("CREATE TABLE mytable (k int PRIMARY KEY, v frozen<tuple<%s>>)", Joiner.on(',').join(DATA_TYPE_PRIMITIVES)));
210+
211+ // insert tuples into same key using different columns
212+ // and verify the results
213+ int i = 1;
214+ for (DataType ignored : DATA_TYPE_PRIMITIVES) {
215+ // create tuples to be written and ensure they match with the expected response
216+ // responses have trailing None values for every element that has not been written
217+ ArrayList<DataType> dataTypes = new ArrayList<DataType>();
218+ ArrayList<DataType> completeDataTypes = new ArrayList<DataType>();
219+ ArrayList<Object> createdValues = new ArrayList<Object>();
220+ ArrayList<Object> completeValues = new ArrayList<Object>();
221+
222+ // create written portion of the arrays
223+ for (int j = 0; j < i; ++j) {
224+ dataTypes.add(DATA_TYPE_PRIMITIVES.get(j));
225+ completeDataTypes.add(DATA_TYPE_PRIMITIVES.get(j));
226+ createdValues.add(PrimitiveTypeSamples.ALL.get(DATA_TYPE_PRIMITIVES.get(j)));
227+ completeValues.add(PrimitiveTypeSamples.ALL.get(DATA_TYPE_PRIMITIVES.get(j)));
228+ }
220229
221- try {
222- session.execute("CREATE KEYSPACE test_tuple_subtypes " +
223- "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
224- session.execute("USE test_tuple_subtypes");
225-
226- // programmatically create the table with a tuple of all datatypes
227- session.execute(String.format("CREATE TABLE mytable (k int PRIMARY KEY, v frozen<tuple<%s>>)", Joiner.on(',').join(DATA_TYPE_PRIMITIVES)));
228-
229- // insert tuples into same key using different columns
230- // and verify the results
231- int i = 1;
232- for (DataType datatype : DATA_TYPE_PRIMITIVES) {
233- // create tuples to be written and ensure they match with the expected response
234- // responses have trailing None values for every element that has not been written
235- ArrayList<DataType> dataTypes = new ArrayList<DataType>();
236- ArrayList<DataType> completeDataTypes = new ArrayList<DataType>();
237- ArrayList<Object> createdValues = new ArrayList<Object>();
238- ArrayList<Object> completeValues = new ArrayList<Object>();
239-
240- // create written portion of the arrays
241- for (int j = 0; j < i; ++j) {
242- dataTypes.add(DATA_TYPE_PRIMITIVES.get(j));
243- completeDataTypes.add(DATA_TYPE_PRIMITIVES.get(j));
244- createdValues.add(PrimitiveTypeSamples.ALL.get(DATA_TYPE_PRIMITIVES.get(j)));
245- completeValues.add(PrimitiveTypeSamples.ALL.get(DATA_TYPE_PRIMITIVES.get(j)));
246- }
247-
248- // complete portion of the arrays needed for trailing nulls
249- for (int j = 0; j < DATA_TYPE_PRIMITIVES.size() - i; ++j) {
250- completeDataTypes.add(DATA_TYPE_PRIMITIVES.get(i + j));
251- completeValues.add(null);
252- }
253-
254- // actually create the tuples
255- TupleType t = new TupleType(dataTypes);
256- TupleType t2 = new TupleType(completeDataTypes);
257- TupleValue createdTuple = t.newValue(createdValues.toArray());
258- TupleValue completeTuple = t2.newValue(completeValues.toArray());
259-
260- // write tuple
261- session.execute(String.format("INSERT INTO mytable (k, v) VALUES (%s, ?)", i), createdTuple);
262-
263- // read tuple
264- TupleValue r = session.execute("SELECT v FROM mytable WHERE k=?", i).one().getTupleValue("v");
265-
266- assertEquals(r, completeTuple);
267- ++i;
230+ // complete portion of the arrays needed for trailing nulls
231+ for (int j = 0; j < DATA_TYPE_PRIMITIVES.size() - i; ++j) {
232+ completeDataTypes.add(DATA_TYPE_PRIMITIVES.get(i + j));
233+ completeValues.add(null);
268234 }
269235
270- } catch (Exception e) {
271- errorOut();
272- throw e;
236+ // actually create the tuples
237+ TupleType t = new TupleType(dataTypes);
238+ TupleType t2 = new TupleType(completeDataTypes);
239+ TupleValue createdTuple = t.newValue(createdValues.toArray());
240+ TupleValue completeTuple = t2.newValue(completeValues.toArray());
241+
242+ // write tuple
243+ session.execute(String.format("INSERT INTO mytable (k, v) VALUES (%s, ?)", i), createdTuple);
244+
245+ // read tuple
246+ TupleValue r = session.execute("SELECT v FROM mytable WHERE k=?", i).one().getTupleValue("v");
247+
248+ assertEquals(r, completeTuple);
249+ ++i;
273250 }
274251 }
275252
@@ -283,116 +260,107 @@
283260 public void tupleNonPrimitiveSubTypesTest() throws Exception {
284261
285262 List<DataType> DATA_TYPE_PRIMITIVES = Lists.newArrayList(PrimitiveTypeSamples.ALL.keySet());
263+ session.execute("CREATE KEYSPACE test_tuple_non_primitive_subtypes " +
264+ "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
265+ session.execute("USE test_tuple_non_primitive_subtypes");
266+
267+ ArrayList<String> values = new ArrayList<String>();
268+
269+ //create list values
270+ for (DataType datatype : DATA_TYPE_PRIMITIVES) {
271+ values.add(String.format("v_%s frozen<tuple<list<%s>>>", values.size(), datatype));
272+ }
286273
287- try {
288- session.execute("CREATE KEYSPACE test_tuple_non_primitive_subtypes " +
289- "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
290- session.execute("USE test_tuple_non_primitive_subtypes");
291-
292- ArrayList<String> values = new ArrayList<String>();
293-
294- //create list values
295- for (DataType datatype : DATA_TYPE_PRIMITIVES) {
296- values.add(String.format("v_%s frozen<tuple<list<%s>>>", values.size(), datatype));
297- }
298-
299- // create set values
300- for (DataType datatype : DATA_TYPE_PRIMITIVES) {
301- values.add(String.format("v_%s frozen<tuple<set<%s>>>", values.size(), datatype));
302- }
274+ // create set values
275+ for (DataType datatype : DATA_TYPE_PRIMITIVES) {
276+ values.add(String.format("v_%s frozen<tuple<set<%s>>>", values.size(), datatype));
277+ }
303278
304- // create map values
305- for (DataType datatype : DATA_TYPE_PRIMITIVES) {
306- values.add(String.format("v_%s frozen<tuple<map<%s, %s>>>", values.size(), datatype, datatype));
307- }
279+ // create map values
280+ for (DataType datatype : DATA_TYPE_PRIMITIVES) {
281+ values.add(String.format("v_%s frozen<tuple<map<%s, %s>>>", values.size(), datatype, datatype));
282+ }
308283
309- // create table
310- session.execute(String.format("CREATE TABLE mytable (k int PRIMARY KEY, %s)", Joiner.on(',').join(values)));
284+ // create table
285+ session.execute(String.format("CREATE TABLE mytable (k int PRIMARY KEY, %s)", Joiner.on(',').join(values)));
311286
312287
313- int i = 0;
314- // test tuple<list<datatype>>
315- for (DataType datatype : DATA_TYPE_PRIMITIVES) {
316- // create tuple
317- ArrayList<DataType> dataTypes = new ArrayList<DataType>();
318- ArrayList<Object> createdValues = new ArrayList<Object>();
288+ int i = 0;
289+ // test tuple<list<datatype>>
290+ for (DataType datatype : DATA_TYPE_PRIMITIVES) {
291+ // create tuple
292+ ArrayList<DataType> dataTypes = new ArrayList<DataType>();
293+ ArrayList<Object> createdValues = new ArrayList<Object>();
319294
320- dataTypes.add(DataType.list(datatype));
321- createdValues.add(Arrays.asList(PrimitiveTypeSamples.ALL.get(datatype)));
295+ dataTypes.add(DataType.list(datatype));
296+ createdValues.add(Collections.singletonList(PrimitiveTypeSamples.ALL.get(datatype)));
322297
323- TupleType t = new TupleType(dataTypes);
324- TupleValue createdTuple = t.newValue(createdValues.toArray());
298+ TupleType t = new TupleType(dataTypes);
299+ TupleValue createdTuple = t.newValue(createdValues.toArray());
325300
326- // write tuple
327- session.execute(String.format("INSERT INTO mytable (k, v_%s) VALUES (0, ?)", i), createdTuple);
301+ // write tuple
302+ session.execute(String.format("INSERT INTO mytable (k, v_%s) VALUES (0, ?)", i), createdTuple);
328303
329- // read tuple
330- TupleValue r = session.execute(String.format("SELECT v_%s FROM mytable WHERE k=0", i))
331- .one().getTupleValue(String.format("v_%s", i));
304+ // read tuple
305+ TupleValue r = session.execute(String.format("SELECT v_%s FROM mytable WHERE k=0", i))
306+ .one().getTupleValue(String.format("v_%s", i));
332307
333- assertEquals(r, createdTuple);
334- ++i;
335- }
308+ assertEquals(r, createdTuple);
309+ ++i;
310+ }
336311
337- // test tuple<set<datatype>>
338- for (DataType datatype : DATA_TYPE_PRIMITIVES) {
339- // create tuple
340- ArrayList<DataType> dataTypes = new ArrayList<DataType>();
341- ArrayList<Object> createdValues = new ArrayList<Object>();
312+ // test tuple<set<datatype>>
313+ for (DataType datatype : DATA_TYPE_PRIMITIVES) {
314+ // create tuple
315+ ArrayList<DataType> dataTypes = new ArrayList<DataType>();
316+ ArrayList<Object> createdValues = new ArrayList<Object>();
342317
343- dataTypes.add(DataType.set(datatype));
344- createdValues.add(new HashSet<Object>(Arrays.asList(PrimitiveTypeSamples.ALL.get(datatype))));
318+ dataTypes.add(DataType.set(datatype));
319+ createdValues.add(new HashSet<Object>(Collections.singletonList(PrimitiveTypeSamples.ALL.get(datatype))));
345320
346- TupleType t = new TupleType(dataTypes);
347- TupleValue createdTuple = t.newValue(createdValues.toArray());
321+ TupleType t = new TupleType(dataTypes);
322+ TupleValue createdTuple = t.newValue(createdValues.toArray());
348323
349- // write tuple
350- session.execute(String.format("INSERT INTO mytable (k, v_%s) VALUES (0, ?)", i), createdTuple);
324+ // write tuple
325+ session.execute(String.format("INSERT INTO mytable (k, v_%s) VALUES (0, ?)", i), createdTuple);
351326
352- // read tuple
353- TupleValue r = session.execute(String.format("SELECT v_%s FROM mytable WHERE k=0", i))
354- .one().getTupleValue(String.format("v_%s", i));
327+ // read tuple
328+ TupleValue r = session.execute(String.format("SELECT v_%s FROM mytable WHERE k=0", i))
329+ .one().getTupleValue(String.format("v_%s", i));
355330
356- assertEquals(r, createdTuple);
357- ++i;
358- }
331+ assertEquals(r, createdTuple);
332+ ++i;
333+ }
359334
360- // test tuple<map<datatype, datatype>>
361- for (DataType datatype : DATA_TYPE_PRIMITIVES) {
362- // create tuple
363- ArrayList<DataType> dataTypes = new ArrayList<DataType>();
364- ArrayList<Object> createdValues = new ArrayList<Object>();
335+ // test tuple<map<datatype, datatype>>
336+ for (DataType datatype : DATA_TYPE_PRIMITIVES) {
337+ // create tuple
338+ ArrayList<DataType> dataTypes = new ArrayList<DataType>();
339+ ArrayList<Object> createdValues = new ArrayList<Object>();
365340
366- HashMap<Object, Object> hm = new HashMap<Object, Object>();
367- hm.put(PrimitiveTypeSamples.ALL.get(datatype), PrimitiveTypeSamples.ALL.get(datatype));
341+ HashMap<Object, Object> hm = new HashMap<Object, Object>();
342+ hm.put(PrimitiveTypeSamples.ALL.get(datatype), PrimitiveTypeSamples.ALL.get(datatype));
368343
369- dataTypes.add(DataType.map(datatype, datatype));
370- createdValues.add(hm);
344+ dataTypes.add(DataType.map(datatype, datatype));
345+ createdValues.add(hm);
371346
372- TupleType t = new TupleType(dataTypes);
373- TupleValue createdTuple = t.newValue(createdValues.toArray());
347+ TupleType t = new TupleType(dataTypes);
348+ TupleValue createdTuple = t.newValue(createdValues.toArray());
374349
375- // write tuple
376- session.execute(String.format("INSERT INTO mytable (k, v_%s) VALUES (0, ?)", i), createdTuple);
350+ // write tuple
351+ session.execute(String.format("INSERT INTO mytable (k, v_%s) VALUES (0, ?)", i), createdTuple);
377352
378- // read tuple
379- TupleValue r = session.execute(String.format("SELECT v_%s FROM mytable WHERE k=0", i))
380- .one().getTupleValue(String.format("v_%s", i));
353+ // read tuple
354+ TupleValue r = session.execute(String.format("SELECT v_%s FROM mytable WHERE k=0", i))
355+ .one().getTupleValue(String.format("v_%s", i));
381356
382- assertEquals(r, createdTuple);
383- ++i;
384- }
385- } catch (Exception e) {
386- errorOut();
387- throw e;
357+ assertEquals(r, createdTuple);
358+ ++i;
388359 }
389360 }
390361
391362 /**
392363 * Helper method for creating nested tuple schema
393- *
394- * @param depth
395- * @return
396364 */
397365 private String nestedTuplesSchemaHelper(int depth) {
398366 if (depth == 0)
@@ -403,9 +371,6 @@
403371
404372 /**
405373 * Helper method for creating nested tuples
406- *
407- * @param depth
408- * @return
409374 */
410375 private TupleValue nestedTuplesCreatorHelper(int depth) {
411376 if (depth == 1) {
@@ -426,39 +391,33 @@
426391 */
427392 @Test(groups = "short")
428393 public void nestedTuplesTest() throws Exception {
429-
430- try {
431- session.execute("CREATE KEYSPACE test_nested_tuples " +
432- "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
433- session.execute("USE test_nested_tuples");
434-
435- // create a table with multiple sizes of nested tuples
436- session.execute(String.format("CREATE TABLE mytable (" +
437- "k int PRIMARY KEY, " +
438- "v_1 %s, " +
439- "v_2 %s, " +
440- "v_3 %s, " +
441- "v_128 %s)", nestedTuplesSchemaHelper(1),
442- nestedTuplesSchemaHelper(2),
443- nestedTuplesSchemaHelper(3),
444- nestedTuplesSchemaHelper(128)));
445-
446- for (int i : Arrays.asList(1, 2, 3, 128)) {
447- // create tuple
448- TupleValue createdTuple = nestedTuplesCreatorHelper(i);
449-
450- // write tuple
451- session.execute(String.format("INSERT INTO mytable (k, v_%s) VALUES (?, ?)", i), i, createdTuple);
452-
453- // verify tuple was written and read correctly
454- TupleValue r = session.execute(String.format("SELECT v_%s FROM mytable WHERE k=?", i), i)
455- .one().getTupleValue(String.format("v_%s", i));
456-
457- assertEquals(r, createdTuple);
458- }
459- } catch (Exception e) {
460- errorOut();
461- throw e;
394+ session.execute("CREATE KEYSPACE test_nested_tuples " +
395+ "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
396+ session.execute("USE test_nested_tuples");
397+
398+ // create a table with multiple sizes of nested tuples
399+ session.execute(String.format("CREATE TABLE mytable (" +
400+ "k int PRIMARY KEY, " +
401+ "v_1 %s, " +
402+ "v_2 %s, " +
403+ "v_3 %s, " +
404+ "v_32 %s)", nestedTuplesSchemaHelper(1),
405+ nestedTuplesSchemaHelper(2),
406+ nestedTuplesSchemaHelper(3),
407+ nestedTuplesSchemaHelper(32)));
408+
409+ for (int i : Arrays.asList(1, 2, 3, 32)) {
410+ // create tuple
411+ TupleValue createdTuple = nestedTuplesCreatorHelper(i);
412+
413+ // write tuple
414+ session.execute(String.format("INSERT INTO mytable (k, v_%s) VALUES (?, ?)", i), i, createdTuple);
415+
416+ // verify tuple was written and read correctly
417+ TupleValue r = session.execute(String.format("SELECT v_%s FROM mytable WHERE k=?", i), i)
418+ .one().getTupleValue(String.format("v_%s", i));
419+
420+ assertEquals(r, createdTuple);
462421 }
463422 }
464423
@@ -470,55 +429,49 @@
470429 */
471430 @Test(groups = "short")
472431 public void testTuplesWithNulls() throws Exception {
473- try {
474- // create keyspace
475- session.execute("CREATE KEYSPACE testTuplesWithNulls " +
476- "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
477- session.execute("USE testTuplesWithNulls");
432+ // create keyspace
433+ session.execute("CREATE KEYSPACE testTuplesWithNulls " +
434+ "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
435+ session.execute("USE testTuplesWithNulls");
478436
479- // create UDT
480- session.execute("CREATE TYPE user (a text, b frozen<tuple<text, int, uuid, blob>>)");
481- session.execute("CREATE TABLE mytable (a int PRIMARY KEY, b frozen<user>)");
437+ // create UDT
438+ session.execute("CREATE TYPE user (a text, b frozen<tuple<text, int, uuid, blob>>)");
439+ session.execute("CREATE TABLE mytable (a int PRIMARY KEY, b frozen<user>)");
482440
483- // insert UDT data
484- UserType userTypeDef = cluster.getMetadata().getKeyspace("testTuplesWithNulls").getUserType("user");
485- UDTValue userType = userTypeDef.newValue();
441+ // insert UDT data
442+ UserType userTypeDef = cluster.getMetadata().getKeyspace("testTuplesWithNulls").getUserType("user");
443+ UDTValue userType = userTypeDef.newValue();
486444
487- TupleType t = TupleType.of(DataType.text(), DataType.cint(), DataType.uuid(), DataType.blob());
488- TupleValue v = t.newValue(null, null, null, null);
489- userType.setTupleValue("b", v);
445+ TupleType t = TupleType.of(DataType.text(), DataType.cint(), DataType.uuid(), DataType.blob());
446+ TupleValue v = t.newValue(null, null, null, null);
447+ userType.setTupleValue("b", v);
490448
491- PreparedStatement ins = session.prepare("INSERT INTO mytable (a, b) VALUES (?, ?)");
492- session.execute(ins.bind(0, userType));
449+ PreparedStatement ins = session.prepare("INSERT INTO mytable (a, b) VALUES (?, ?)");
450+ session.execute(ins.bind(0, userType));
493451
494- // retrieve and verify data
495- ResultSet rs = session.execute("SELECT * FROM mytable");
496- List<Row> rows = rs.all();
497- assertEquals(1, rows.size());
452+ // retrieve and verify data
453+ ResultSet rs = session.execute("SELECT * FROM mytable");
454+ List<Row> rows = rs.all();
455+ assertEquals(1, rows.size());
498456
499- Row row = rows.get(0);
457+ Row row = rows.get(0);
500458
501- assertEquals(row.getInt("a"), 0);
502- assertEquals(row.getUDTValue("b"), userType);
459+ assertEquals(row.getInt("a"), 0);
460+ assertEquals(row.getUDTValue("b"), userType);
503461
504- // test empty strings
505- v = t.newValue("", null, null, ByteBuffer.allocate(0));
506- userType.setTupleValue("b", v);
507- session.execute(ins.bind(0, userType));
462+ // test empty strings
463+ v = t.newValue("", null, null, ByteBuffer.allocate(0));
464+ userType.setTupleValue("b", v);
465+ session.execute(ins.bind(0, userType));
508466
509- // retrieve and verify data
510- rs = session.execute("SELECT * FROM mytable");
511- rows = rs.all();
512- assertEquals(1, rows.size());
467+ // retrieve and verify data
468+ rs = session.execute("SELECT * FROM mytable");
469+ rows = rs.all();
470+ assertEquals(1, rows.size());
513471
514- row = rows.get(0);
472+ row = rows.get(0);
515473
516- assertEquals(row.getInt("a"), 0);
517- assertEquals(row.getUDTValue("b"), userType);
518-
519- } catch (Exception e) {
520- errorOut();
521- throw e;
522- }
474+ assertEquals(row.getInt("a"), 0);
475+ assertEquals(row.getUDTValue("b"), userType);
523476 }
524477 }
modified driver-core/src/test/java/com/datastax/driver/core/UserTypesTest.java +333 −394
@@ -34,19 +34,17 @@
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());
4040 private final static List<DataType.Name> DATA_TYPE_NON_PRIMITIVE_NAMES =
4141 new ArrayList<DataType.Name>(EnumSet.of(DataType.Name.LIST, DataType.Name.SET, DataType.Name.MAP, DataType.Name.TUPLE));
4242
4343 @Override
44- protected Collection<String> getTableDefinitions() {
44+ public Collection<String> createTestFixtures() {
4545 String type1 = "CREATE TYPE phone (alias text, number text)";
4646 String type2 = "CREATE TYPE address (street text, \"ZIP\" int, phones set<frozen<phone>>)";
47-
4847 String table = "CREATE TABLE user (id int PRIMARY KEY, addr frozen<address>)";
49-
5048 return Arrays.asList(type1, type2, table);
5149 }
5250
@@ -58,30 +56,23 @@
5856 @Test(groups = "short")
5957 public void simpleWriteReadTest() throws Exception {
6058 int userId = 0;
59+ PreparedStatement ins = session.prepare("INSERT INTO user(id, addr) VALUES (?, ?)");
60+ PreparedStatement sel = session.prepare("SELECT * FROM user WHERE id=?");
6161
62- try {
63- session.execute("USE " + keyspace);
64- PreparedStatement ins = session.prepare("INSERT INTO user(id, addr) VALUES (?, ?)");
65- PreparedStatement sel = session.prepare("SELECT * FROM user WHERE id=?");
66-
67- UserType addrDef = cluster.getMetadata().getKeyspace(keyspace).getUserType("address");
68- UserType phoneDef = cluster.getMetadata().getKeyspace(keyspace).getUserType("phone");
62+ UserType addrDef = cluster.getMetadata().getKeyspace(keyspace).getUserType("address");
63+ UserType phoneDef = cluster.getMetadata().getKeyspace(keyspace).getUserType("phone");
6964
70- UDTValue phone1 = phoneDef.newValue().setString("alias", "home").setString("number", "0123548790");
71- UDTValue phone2 = phoneDef.newValue().setString("alias", "work").setString("number", "0698265251");
65+ UDTValue phone1 = phoneDef.newValue().setString("alias", "home").setString("number", "0123548790");
66+ UDTValue phone2 = phoneDef.newValue().setString("alias", "work").setString("number", "0698265251");
7267
73- UDTValue addr = addrDef.newValue().setString("street", "1600 Pennsylvania Ave NW").setInt(quote("ZIP"), 20500).setSet("phones", ImmutableSet.of(phone1, phone2));
68+ UDTValue addr = addrDef.newValue().setString("street", "1600 Pennsylvania Ave NW").setInt(quote("ZIP"), 20500).setSet("phones", ImmutableSet.of(phone1, phone2));
7469
75- session.execute(ins.bind(userId, addr));
70+ session.execute(ins.bind(userId, addr));
7671
77- Row r = session.execute(sel.bind(userId)).one();
72+ Row r = session.execute(sel.bind(userId)).one();
7873
79- assertEquals(r.getInt("id"), 0);
80- assertEquals(r.getUDTValue("addr"), addr);
81- } catch (Exception e) {
82- errorOut();
83- throw e;
84- }
74+ assertEquals(r.getInt("id"), 0);
75+ assertEquals(r.getUDTValue("addr"), addr);
8576 }
8677
8778 /**
@@ -92,27 +83,20 @@
9283 @Test(groups = "short")
9384 public void simpleUnpreparedWriteReadTest() throws Exception {
9485 int userId = 1;
86+ UserType addrDef = cluster.getMetadata().getKeyspace(keyspace).getUserType("address");
87+ UserType phoneDef = cluster.getMetadata().getKeyspace(keyspace).getUserType("phone");
9588
96- try {
97- session.execute("USE " + keyspace);
98- UserType addrDef = cluster.getMetadata().getKeyspace(keyspace).getUserType("address");
99- UserType phoneDef = cluster.getMetadata().getKeyspace(keyspace).getUserType("phone");
89+ UDTValue phone1 = phoneDef.newValue().setString("alias", "home").setString("number", "0123548790");
90+ UDTValue phone2 = phoneDef.newValue().setString("alias", "work").setString("number", "0698265251");
10091
101- UDTValue phone1 = phoneDef.newValue().setString("alias", "home").setString("number", "0123548790");
102- UDTValue phone2 = phoneDef.newValue().setString("alias", "work").setString("number", "0698265251");
92+ UDTValue addr = addrDef.newValue().setString("street", "1600 Pennsylvania Ave NW").setInt(quote("ZIP"), 20500).setSet("phones", ImmutableSet.of(phone1, phone2));
10393
104- UDTValue addr = addrDef.newValue().setString("street", "1600 Pennsylvania Ave NW").setInt(quote("ZIP"), 20500).setSet("phones", ImmutableSet.of(phone1, phone2));
94+ session.execute("INSERT INTO user(id, addr) VALUES (?, ?)", userId, addr);
10595
106- session.execute("INSERT INTO user(id, addr) VALUES (?, ?)", userId, addr);
96+ Row r = session.execute("SELECT * FROM user WHERE id=?", userId).one();
10797
108- Row r = session.execute("SELECT * FROM user WHERE id=?", userId).one();
109-
110- assertEquals(r.getInt("id"), 1);
111- assertEquals(r.getUDTValue("addr"), addr);
112- } catch (Exception e) {
113- errorOut();
114- throw e;
115- }
98+ assertEquals(r.getInt("id"), 1);
99+ assertEquals(r.getUDTValue("addr"), addr);
116100 }
117101
118102 /**
@@ -122,41 +106,33 @@
122106 */
123107 @Test(groups = "short")
124108 public void nonExistingTypesTest() throws Exception {
125- try {
126- session.execute("USE " + keyspace);
127-
128- UserType addrDef = cluster.getMetadata().getKeyspace(keyspace).getUserType("address1");
129- UserType phoneDef = cluster.getMetadata().getKeyspace(keyspace).getUserType("phone1");
130- assertEquals(addrDef, null);
131- assertEquals(phoneDef, null);
132-
133- addrDef = cluster.getMetadata().getKeyspace(keyspace).getUserType("address");
134- phoneDef = cluster.getMetadata().getKeyspace(keyspace).getUserType("phone");
135- assertNotEquals(addrDef, null);
136- assertNotEquals(phoneDef, null);
137-
138- // create keyspace
139- String nonExistingKeyspace = keyspace + "_nonEx";
140- session.execute("CREATE KEYSPACE " + nonExistingKeyspace + " " +
141- "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
142- session.execute("USE " + nonExistingKeyspace);
143-
144- addrDef = cluster.getMetadata().getKeyspace(nonExistingKeyspace).getUserType("address");
145- phoneDef = cluster.getMetadata().getKeyspace(nonExistingKeyspace).getUserType("phone");
146- assertEquals(addrDef, null);
147- assertEquals(phoneDef, null);
148-
149- session.execute("USE " + keyspace);
150-
151- addrDef = cluster.getMetadata().getKeyspace(keyspace).getUserType("address");
152- phoneDef = cluster.getMetadata().getKeyspace(keyspace).getUserType("phone");
153- assertNotEquals(addrDef, null);
154- assertNotEquals(phoneDef, null);
155-
156- } catch (Exception e) {
157- errorOut();
158- throw e;
159- }
109+ UserType addrDef = cluster.getMetadata().getKeyspace(keyspace).getUserType("address1");
110+ UserType phoneDef = cluster.getMetadata().getKeyspace(keyspace).getUserType("phone1");
111+ assertEquals(addrDef, null);
112+ assertEquals(phoneDef, null);
113+
114+ addrDef = cluster.getMetadata().getKeyspace(keyspace).getUserType("address");
115+ phoneDef = cluster.getMetadata().getKeyspace(keyspace).getUserType("phone");
116+ assertNotEquals(addrDef, null);
117+ assertNotEquals(phoneDef, null);
118+
119+ // create keyspace
120+ String nonExistingKeyspace = keyspace + "_nonEx";
121+ session.execute("CREATE KEYSPACE " + nonExistingKeyspace + " " +
122+ "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
123+ session.execute("USE " + nonExistingKeyspace);
124+
125+ addrDef = cluster.getMetadata().getKeyspace(nonExistingKeyspace).getUserType("address");
126+ phoneDef = cluster.getMetadata().getKeyspace(nonExistingKeyspace).getUserType("phone");
127+ assertEquals(addrDef, null);
128+ assertEquals(phoneDef, null);
129+
130+ session.execute("USE " + keyspace);
131+
132+ addrDef = cluster.getMetadata().getKeyspace(keyspace).getUserType("address");
133+ phoneDef = cluster.getMetadata().getKeyspace(keyspace).getUserType("phone");
134+ assertNotEquals(addrDef, null);
135+ assertNotEquals(phoneDef, null);
160136 }
161137
162138 /**
@@ -168,48 +144,42 @@
168144 @Test(groups = "short")
169145 public void udtSizesTest() throws Exception {
170146 int MAX_TEST_LENGTH = 1024;
171-
172- try {
173- // create keyspace
174- session.execute("CREATE KEYSPACE test_udt_sizes " +
175- "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
176- session.execute("USE test_udt_sizes");
177-
178- // create the seed udt
179- StringBuilder sb = new StringBuilder();
180- for (int i = 0; i < MAX_TEST_LENGTH; ++i) {
181- sb.append(String.format("v_%s int", i));
182-
183- if (i + 1 < MAX_TEST_LENGTH)
184- sb.append(",");
147+ // create keyspace
148+ session.execute("CREATE KEYSPACE test_udt_sizes " +
149+ "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
150+ session.execute("USE test_udt_sizes");
151+
152+ // create the seed udt
153+ StringBuilder sb = new StringBuilder();
154+ for (int i = 0; i < MAX_TEST_LENGTH; ++i) {
155+ sb.append(String.format("v_%s int", i));
156+
157+ if (i + 1 < MAX_TEST_LENGTH)
158+ sb.append(",");
159+ }
160+ session.execute(String.format("CREATE TYPE lengthy_udt (%s)", sb.toString()));
161+
162+ // create a table with multiple sizes of udts
163+ session.execute("CREATE TABLE mytable (k int PRIMARY KEY, v frozen<lengthy_udt>)");
164+
165+ // hold onto the UserType for future use
166+ UserType udtDef = cluster.getMetadata().getKeyspace("test_udt_sizes").getUserType("lengthy_udt");
167+
168+ // verify inserts and reads
169+ for (int i : Arrays.asList(0, 1, 2, 3, MAX_TEST_LENGTH)) {
170+ // create udt
171+ UDTValue createdUDT = udtDef.newValue();
172+ for (int j = 0; j < i; ++j) {
173+ createdUDT.setInt(j, j);
185174 }
186- session.execute(String.format("CREATE TYPE lengthy_udt (%s)", sb.toString()));
187-
188- // create a table with multiple sizes of udts
189- session.execute("CREATE TABLE mytable (k int PRIMARY KEY, v frozen<lengthy_udt>)");
190-
191- // hold onto the UserType for future use
192- UserType udtDef = cluster.getMetadata().getKeyspace("test_udt_sizes").getUserType("lengthy_udt");
193-
194- // verify inserts and reads
195- for (int i : Arrays.asList(0, 1, 2, 3, MAX_TEST_LENGTH)) {
196- // create udt
197- UDTValue createdUDT = udtDef.newValue();
198- for (int j = 0; j < i; ++j) {
199- createdUDT.setInt(j, j);
200- }
201175
202- // write udt
203- session.execute("INSERT INTO mytable (k, v) VALUES (0, ?)", createdUDT);
176+ // write udt
177+ session.execute("INSERT INTO mytable (k, v) VALUES (0, ?)", createdUDT);
204178
205- // verify udt was written and read correctly
206- UDTValue r = session.execute("SELECT v FROM mytable WHERE k=0")
207- .one().getUDTValue("v");
208- assertEquals(r.toString(), createdUDT.toString());
209- }
210- } catch (Exception e) {
211- errorOut();
212- throw e;
179+ // verify udt was written and read correctly
180+ UDTValue r = session.execute("SELECT v FROM mytable WHERE k=0")
181+ .one().getUDTValue("v");
182+ assertEquals(r.toString(), createdUDT.toString());
213183 }
214184 }
215185
@@ -221,98 +191,92 @@
221191 */
222192 @Test(groups = "short")
223193 public void testPrimitiveDatatypes() throws Exception {
224- try {
225- // create keyspace
226- session.execute("CREATE KEYSPACE testPrimitiveDatatypes " +
227- "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
228- session.execute("USE testPrimitiveDatatypes");
229-
230- // create UDT
231- List<String> alpha_type_list = new ArrayList<String>();
232- int startIndex = (int) 'a';
233- for (int i = 0; i < DATA_TYPE_PRIMITIVES.size(); i++) {
234- alpha_type_list.add(String.format("%s %s", Character.toString((char) (startIndex + i)),
235- DATA_TYPE_PRIMITIVES.get(i).getName()));
236- }
237-
238- session.execute(String.format("CREATE TYPE alldatatypes (%s)", Joiner.on(',').join(alpha_type_list)));
239- session.execute("CREATE TABLE mytable (a int PRIMARY KEY, b frozen<alldatatypes>)");
240-
241- // insert UDT data
242- UserType alldatatypesDef = cluster.getMetadata().getKeyspace("testPrimitiveDatatypes").getUserType("alldatatypes");
243- UDTValue alldatatypes = alldatatypesDef.newValue();
244-
245- for (int i = 0; i < DATA_TYPE_PRIMITIVES.size(); i++) {
246- DataType dataType = DATA_TYPE_PRIMITIVES.get(i);
247- String index = Character.toString((char) (startIndex + i));
248- Object sampleData = PrimitiveTypeSamples.ALL.get(dataType);
194+ // create keyspace
195+ session.execute("CREATE KEYSPACE testPrimitiveDatatypes " +
196+ "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
197+ session.execute("USE testPrimitiveDatatypes");
198+
199+ // create UDT
200+ List<String> alpha_type_list = new ArrayList<String>();
201+ int startIndex = (int) 'a';
202+ for (int i = 0; i < DATA_TYPE_PRIMITIVES.size(); i++) {
203+ alpha_type_list.add(String.format("%s %s", Character.toString((char) (startIndex + i)),
204+ DATA_TYPE_PRIMITIVES.get(i).getName()));
205+ }
249206
250- switch (dataType.getName()) {
251- case ASCII:
252- alldatatypes.setString(index, (String) sampleData);
253- break;
254- case BIGINT:
255- alldatatypes.setLong(index, ((Long) sampleData).longValue());
256- break;
257- case BLOB:
258- alldatatypes.setBytes(index, (ByteBuffer) sampleData);
259- break;
260- case BOOLEAN:
261- alldatatypes.setBool(index, ((Boolean) sampleData).booleanValue());
262- break;
263- case DECIMAL:
264- alldatatypes.setDecimal(index, (BigDecimal) sampleData);
265- break;
266- case DOUBLE:
267- alldatatypes.setDouble(index, ((Double) sampleData).doubleValue());
268- break;
269- case FLOAT:
270- alldatatypes.setFloat(index, ((Float) sampleData).floatValue());
271- break;
272- case INET:
273- alldatatypes.setInet(index, (InetAddress) sampleData);
274- break;
275- case INT:
276- alldatatypes.setInt(index, ((Integer) sampleData).intValue());
277- break;
278- case TEXT:
279- alldatatypes.setString(index, (String) sampleData);
280- break;
281- case TIMESTAMP:
282- alldatatypes.setDate(index, ((Date) sampleData));
283- break;
284- case TIMEUUID:
285- alldatatypes.setUUID(index, (UUID) sampleData);
286- break;
287- case UUID:
288- alldatatypes.setUUID(index, (UUID) sampleData);
289- break;
290- case VARCHAR:
291- alldatatypes.setString(index, (String) sampleData);
292- break;
293- case VARINT:
294- alldatatypes.setVarint(index, (BigInteger) sampleData);
295- break;
296- }
207+ session.execute(String.format("CREATE TYPE alldatatypes (%s)", Joiner.on(',').join(alpha_type_list)));
208+ session.execute("CREATE TABLE mytable (a int PRIMARY KEY, b frozen<alldatatypes>)");
209+
210+ // insert UDT data
211+ UserType alldatatypesDef = cluster.getMetadata().getKeyspace("testPrimitiveDatatypes").getUserType("alldatatypes");
212+ UDTValue alldatatypes = alldatatypesDef.newValue();
213+
214+ for (int i = 0; i < DATA_TYPE_PRIMITIVES.size(); i++) {
215+ DataType dataType = DATA_TYPE_PRIMITIVES.get(i);
216+ String index = Character.toString((char) (startIndex + i));
217+ Object sampleData = PrimitiveTypeSamples.ALL.get(dataType);
218+
219+ switch (dataType.getName()) {
220+ case ASCII:
221+ alldatatypes.setString(index, (String) sampleData);
222+ break;
223+ case BIGINT:
224+ alldatatypes.setLong(index, (Long) sampleData);
225+ break;
226+ case BLOB:
227+ alldatatypes.setBytes(index, (ByteBuffer) sampleData);
228+ break;
229+ case BOOLEAN:
230+ alldatatypes.setBool(index, (Boolean) sampleData);
231+ break;
232+ case DECIMAL:
233+ alldatatypes.setDecimal(index, (BigDecimal) sampleData);
234+ break;
235+ case DOUBLE:
236+ alldatatypes.setDouble(index, (Double) sampleData);
237+ break;
238+ case FLOAT:
239+ alldatatypes.setFloat(index, (Float) sampleData);
240+ break;
241+ case INET:
242+ alldatatypes.setInet(index, (InetAddress) sampleData);
243+ break;
244+ case INT:
245+ alldatatypes.setInt(index, (Integer) sampleData);
246+ break;
247+ case TEXT:
248+ alldatatypes.setString(index, (String) sampleData);
249+ break;
250+ case TIMESTAMP:
251+ alldatatypes.setDate(index, ((Date) sampleData));
252+ break;
253+ case TIMEUUID:
254+ alldatatypes.setUUID(index, (UUID) sampleData);
255+ break;
256+ case UUID:
257+ alldatatypes.setUUID(index, (UUID) sampleData);
258+ break;
259+ case VARCHAR:
260+ alldatatypes.setString(index, (String) sampleData);
261+ break;
262+ case VARINT:
263+ alldatatypes.setVarint(index, (BigInteger) sampleData);
264+ break;
297265 }
266+ }
298267
299- PreparedStatement ins = session.prepare("INSERT INTO mytable (a, b) VALUES (?, ?)");
300- session.execute(ins.bind(0, alldatatypes));
301-
302- // retrieve and verify data
303- ResultSet rs = session.execute("SELECT * FROM mytable");
304- List<Row> rows = rs.all();
305- assertEquals(1, rows.size());
268+ PreparedStatement ins = session.prepare("INSERT INTO mytable (a, b) VALUES (?, ?)");
269+ session.execute(ins.bind(0, alldatatypes));
306270
307- Row row = rows.get(0);
271+ // retrieve and verify data
272+ ResultSet rs = session.execute("SELECT * FROM mytable");
273+ List<Row> rows = rs.all();
274+ assertEquals(1, rows.size());
308275
309- assertEquals(row.getInt("a"), 0);
310- assertEquals(row.getUDTValue("b"), alldatatypes);
276+ Row row = rows.get(0);
311277
312- } catch (Exception e) {
313- errorOut();
314- throw e;
315- }
278+ assertEquals(row.getInt("a"), 0);
279+ assertEquals(row.getUDTValue("b"), alldatatypes);
316280 }
317281
318282 /**
@@ -323,83 +287,77 @@
323287 */
324288 @Test(groups = "short")
325289 public void testNonPrimitiveDatatypes() throws Exception {
326- try {
327- // create keyspace
328- session.execute("CREATE KEYSPACE test_nonprimitive_datatypes " +
329- "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
330- session.execute("USE test_nonprimitive_datatypes");
331-
332- // counters are not allowed inside collections
333- DATA_TYPE_PRIMITIVES.remove(DataType.counter());
334-
335- // create UDT
336- List<String> alpha_type_list = new ArrayList<String>();
337- int startIndex = (int) 'a';
338- for (int i = 0; i < DATA_TYPE_NON_PRIMITIVE_NAMES.size(); i++)
339- for (int j = 0; j < DATA_TYPE_PRIMITIVES.size(); j++) {
340- String typeString;
341- if (DATA_TYPE_NON_PRIMITIVE_NAMES.get(i) == DataType.Name.MAP) {
342- typeString = (String.format("%s_%s %s<%s, %s>", Character.toString((char) (startIndex + i)),
343- Character.toString((char) (startIndex + j)), DATA_TYPE_NON_PRIMITIVE_NAMES.get(i),
344- DATA_TYPE_PRIMITIVES.get(j).getName(), DATA_TYPE_PRIMITIVES.get(j).getName()));
345- } else if (DATA_TYPE_NON_PRIMITIVE_NAMES.get(i) == DataType.Name.TUPLE) {
346- typeString = (String.format("%s_%s frozen<%s<%s>>", Character.toString((char) (startIndex + i)),
347- Character.toString((char) (startIndex + j)), DATA_TYPE_NON_PRIMITIVE_NAMES.get(i),
348- DATA_TYPE_PRIMITIVES.get(j).getName()));
349- } else {
350- typeString = (String.format("%s_%s %s<%s>", Character.toString((char) (startIndex + i)),
351- Character.toString((char) (startIndex + j)), DATA_TYPE_NON_PRIMITIVE_NAMES.get(i),
352- DATA_TYPE_PRIMITIVES.get(j).getName()));
353- }
354- alpha_type_list.add(typeString);
290+ // create keyspace
291+ session.execute("CREATE KEYSPACE test_nonprimitive_datatypes " +
292+ "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
293+ session.execute("USE test_nonprimitive_datatypes");
294+
295+ // counters are not allowed inside collections
296+ DATA_TYPE_PRIMITIVES.remove(DataType.counter());
297+
298+ // create UDT
299+ List<String> alpha_type_list = new ArrayList<String>();
300+ int startIndex = (int) 'a';
301+ for (int i = 0; i < DATA_TYPE_NON_PRIMITIVE_NAMES.size(); i++)
302+ for (int j = 0; j < DATA_TYPE_PRIMITIVES.size(); j++) {
303+ String typeString;
304+ if (DATA_TYPE_NON_PRIMITIVE_NAMES.get(i) == DataType.Name.MAP) {
305+ typeString = (String.format("%s_%s %s<%s, %s>", Character.toString((char) (startIndex + i)),
306+ Character.toString((char) (startIndex + j)), DATA_TYPE_NON_PRIMITIVE_NAMES.get(i),
307+ DATA_TYPE_PRIMITIVES.get(j).getName(), DATA_TYPE_PRIMITIVES.get(j).getName()));
308+ } else if (DATA_TYPE_NON_PRIMITIVE_NAMES.get(i) == DataType.Name.TUPLE) {
309+ typeString = (String.format("%s_%s frozen<%s<%s>>", Character.toString((char) (startIndex + i)),
310+ Character.toString((char) (startIndex + j)), DATA_TYPE_NON_PRIMITIVE_NAMES.get(i),
311+ DATA_TYPE_PRIMITIVES.get(j).getName()));
312+ } else {
313+ typeString = (String.format("%s_%s %s<%s>", Character.toString((char) (startIndex + i)),
314+ Character.toString((char) (startIndex + j)), DATA_TYPE_NON_PRIMITIVE_NAMES.get(i),
315+ DATA_TYPE_PRIMITIVES.get(j).getName()));
355316 }
317+ alpha_type_list.add(typeString);
318+ }
356319
357- session.execute(String.format("CREATE TYPE alldatatypes (%s)", Joiner.on(',').join(alpha_type_list)));
358- session.execute("CREATE TABLE mytable (a int PRIMARY KEY, b frozen<alldatatypes>)");
359-
360- // insert UDT data
361- UserType alldatatypesDef = cluster.getMetadata().getKeyspace("test_nonprimitive_datatypes").getUserType("alldatatypes");
362- UDTValue alldatatypes = alldatatypesDef.newValue();
363-
364- for (int i = 0; i < DATA_TYPE_NON_PRIMITIVE_NAMES.size(); i++)
365- for (int j = 0; j < DATA_TYPE_PRIMITIVES.size(); j++) {
366- DataType.Name name = DATA_TYPE_NON_PRIMITIVE_NAMES.get(i);
367- DataType dataType = DATA_TYPE_PRIMITIVES.get(j);
368-
369- String index = Character.toString((char) (startIndex + i)) + "_" + Character.toString((char) (startIndex + j));
370- Object sampleElement = PrimitiveTypeSamples.ALL.get(dataType);
371- switch (name) {
372- case LIST:
373- alldatatypes.setList(index, Lists.newArrayList(sampleElement));
374- break;
375- case SET:
376- alldatatypes.setSet(index, Sets.newHashSet(sampleElement));
377- break;
378- case MAP:
379- alldatatypes.setMap(index, ImmutableMap.of(sampleElement, sampleElement));
380- break;
381- case TUPLE:
382- alldatatypes.setTupleValue(index, TupleType.of(dataType).newValue(sampleElement));
383- }
320+ session.execute(String.format("CREATE TYPE alldatatypes (%s)", Joiner.on(',').join(alpha_type_list)));
321+ session.execute("CREATE TABLE mytable (a int PRIMARY KEY, b frozen<alldatatypes>)");
322+
323+ // insert UDT data
324+ UserType alldatatypesDef = cluster.getMetadata().getKeyspace("test_nonprimitive_datatypes").getUserType("alldatatypes");
325+ UDTValue alldatatypes = alldatatypesDef.newValue();
326+
327+ for (int i = 0; i < DATA_TYPE_NON_PRIMITIVE_NAMES.size(); i++)
328+ for (int j = 0; j < DATA_TYPE_PRIMITIVES.size(); j++) {
329+ DataType.Name name = DATA_TYPE_NON_PRIMITIVE_NAMES.get(i);
330+ DataType dataType = DATA_TYPE_PRIMITIVES.get(j);
331+
332+ String index = Character.toString((char) (startIndex + i)) + "_" + Character.toString((char) (startIndex + j));
333+ Object sampleElement = PrimitiveTypeSamples.ALL.get(dataType);
334+ switch (name) {
335+ case LIST:
336+ alldatatypes.setList(index, Lists.newArrayList(sampleElement));
337+ break;
338+ case SET:
339+ alldatatypes.setSet(index, Sets.newHashSet(sampleElement));
340+ break;
341+ case MAP:
342+ alldatatypes.setMap(index, ImmutableMap.of(sampleElement, sampleElement));
343+ break;
344+ case TUPLE:
345+ alldatatypes.setTupleValue(index, TupleType.of(dataType).newValue(sampleElement));
384346 }
347+ }
385348
386- PreparedStatement ins = session.prepare("INSERT INTO mytable (a, b) VALUES (?, ?)");
387- session.execute(ins.bind(0, alldatatypes));
388-
389- // retrieve and verify data
390- ResultSet rs = session.execute("SELECT * FROM mytable");
391- List<Row> rows = rs.all();
392- assertEquals(1, rows.size());
349+ PreparedStatement ins = session.prepare("INSERT INTO mytable (a, b) VALUES (?, ?)");
350+ session.execute(ins.bind(0, alldatatypes));
393351
394- Row row = rows.get(0);
352+ // retrieve and verify data
353+ ResultSet rs = session.execute("SELECT * FROM mytable");
354+ List<Row> rows = rs.all();
355+ assertEquals(1, rows.size());
395356
396- assertEquals(row.getInt("a"), 0);
397- assertEquals(row.getUDTValue("b"), alldatatypes);
357+ Row row = rows.get(0);
398358
399- } catch (Exception e) {
400- errorOut();
401- throw e;
402- }
359+ assertEquals(row.getInt("a"), 0);
360+ assertEquals(row.getUDTValue("b"), alldatatypes);
403361 }
404362
405363 /**
@@ -411,60 +369,53 @@
411369 @Test(groups = "short")
412370 public void udtNestedTest() throws Exception {
413371 final int MAX_NESTING_DEPTH = 4;
372+ // create keyspace
373+ session.execute("CREATE KEYSPACE udtNestedTest " +
374+ "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
375+ session.execute("USE udtNestedTest");
376+
377+ // create UDT
378+ session.execute("CREATE TYPE depth_0 (age int, name text)");
379+
380+ for (int i = 1; i <= MAX_NESTING_DEPTH; i++) {
381+ session.execute(String.format("CREATE TYPE depth_%s (value frozen<depth_%s>)", String.valueOf(i), String.valueOf(i - 1)));
382+ }
414383
415- try {
416- // create keyspace
417- session.execute("CREATE KEYSPACE udtNestedTest " +
418- "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
419- session.execute("USE udtNestedTest");
420-
421- // create UDT
422- session.execute("CREATE TYPE depth_0 (age int, name text)");
423-
424- for (int i = 1; i <= MAX_NESTING_DEPTH; i++) {
425- session.execute(String.format("CREATE TYPE depth_%s (value frozen<depth_%s>)", String.valueOf(i), String.valueOf(i - 1)));
426- }
427-
428- 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>," +
429- "f frozen<depth_%s>)", MAX_NESTING_DEPTH));
430-
431- // insert UDT data
432- UserType depthZeroDef = cluster.getMetadata().getKeyspace("udtNestedTest").getUserType("depth_0");
433- UDTValue depthZero = depthZeroDef.newValue().setInt("age", 42).setString("name", "Bob");
384+ 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>," +
385+ "f frozen<depth_%s>)", MAX_NESTING_DEPTH));
434386
435- UserType depthOneDef = cluster.getMetadata().getKeyspace("udtNestedTest").getUserType("depth_1");
436- UDTValue depthOne = depthOneDef.newValue().setUDTValue("value", depthZero);
387+ // insert UDT data
388+ UserType depthZeroDef = cluster.getMetadata().getKeyspace("udtNestedTest").getUserType("depth_0");
389+ UDTValue depthZero = depthZeroDef.newValue().setInt("age", 42).setString("name", "Bob");
437390
438- UserType depthTwoDef = cluster.getMetadata().getKeyspace("udtNestedTest").getUserType("depth_2");
439- UDTValue depthTwo = depthTwoDef.newValue().setUDTValue("value", depthOne);
391+ UserType depthOneDef = cluster.getMetadata().getKeyspace("udtNestedTest").getUserType("depth_1");
392+ UDTValue depthOne = depthOneDef.newValue().setUDTValue("value", depthZero);
440393
441- UserType depthThreeDef = cluster.getMetadata().getKeyspace("udtNestedTest").getUserType("depth_3");
442- UDTValue depthThree = depthThreeDef.newValue().setUDTValue("value", depthTwo);
394+ UserType depthTwoDef = cluster.getMetadata().getKeyspace("udtNestedTest").getUserType("depth_2");
395+ UDTValue depthTwo = depthTwoDef.newValue().setUDTValue("value", depthOne);
443396
444- UserType depthFourDef = cluster.getMetadata().getKeyspace("udtNestedTest").getUserType("depth_4");
445- UDTValue depthFour = depthFourDef.newValue().setUDTValue("value", depthThree);
397+ UserType depthThreeDef = cluster.getMetadata().getKeyspace("udtNestedTest").getUserType("depth_3");
398+ UDTValue depthThree = depthThreeDef.newValue().setUDTValue("value", depthTwo);
446399
447- PreparedStatement ins = session.prepare("INSERT INTO mytable (a, b, c, d, e, f) VALUES (?, ?, ?, ?, ?, ?)");
448- session.execute(ins.bind(0, depthZero, depthOne, depthTwo, depthThree, depthFour));
400+ UserType depthFourDef = cluster.getMetadata().getKeyspace("udtNestedTest").getUserType("depth_4");
401+ UDTValue depthFour = depthFourDef.newValue().setUDTValue("value", depthThree);
449402
450- // retrieve and verify data
451- ResultSet rs = session.execute("SELECT * FROM mytable");
452- List<Row> rows = rs.all();
453- assertEquals(1, rows.size());
403+ PreparedStatement ins = session.prepare("INSERT INTO mytable (a, b, c, d, e, f) VALUES (?, ?, ?, ?, ?, ?)");
404+ session.execute(ins.bind(0, depthZero, depthOne, depthTwo, depthThree, depthFour));
454405
455- Row row = rows.get(0);
406+ // retrieve and verify data
407+ ResultSet rs = session.execute("SELECT * FROM mytable");
408+ List<Row> rows = rs.all();
409+ assertEquals(1, rows.size());
456410
457- assertEquals(row.getInt("a"), 0);
458- assertEquals(row.getUDTValue("b"), depthZero);
459- assertEquals(row.getUDTValue("c"), depthOne);
460- assertEquals(row.getUDTValue("d"), depthTwo);
461- assertEquals(row.getUDTValue("e"), depthThree);
462- assertEquals(row.getUDTValue("f"), depthFour);
411+ Row row = rows.get(0);
463412
464- } catch (Exception e) {
465- errorOut();
466- throw e;
467- }
413+ assertEquals(row.getInt("a"), 0);
414+ assertEquals(row.getUDTValue("b"), depthZero);
415+ assertEquals(row.getUDTValue("c"), depthOne);
416+ assertEquals(row.getUDTValue("d"), depthTwo);
417+ assertEquals(row.getUDTValue("e"), depthThree);
418+ assertEquals(row.getUDTValue("f"), depthFour);
468419 }
469420
470421 /**
@@ -475,51 +426,45 @@
475426 */
476427 @Test(groups = "short")
477428 public void testUdtsWithNulls() throws Exception {
478- try {
479- // create keyspace
480- session.execute("CREATE KEYSPACE testUdtsWithNulls " +
481- "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
482- session.execute("USE testUdtsWithNulls");
483-
484- // create UDT
485- session.execute("CREATE TYPE user (a text, b int, c uuid, d blob)");
486- session.execute("CREATE TABLE mytable (a int PRIMARY KEY, b frozen<user>)");
429+ // create keyspace
430+ session.execute("CREATE KEYSPACE testUdtsWithNulls " +
431+ "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
432+ session.execute("USE testUdtsWithNulls");
487433
488- // insert UDT data
489- UserType userTypeDef = cluster.getMetadata().getKeyspace("testUdtsWithNulls").getUserType("user");
490- UDTValue userType = userTypeDef.newValue().setString("a", null).setInt("b", 0).setUUID("c", null).setBytes("d", null);
434+ // create UDT
435+ session.execute("CREATE TYPE user (a text, b int, c uuid, d blob)");
436+ session.execute("CREATE TABLE mytable (a int PRIMARY KEY, b frozen<user>)");
491437
492- PreparedStatement ins = session.prepare("INSERT INTO mytable (a, b) VALUES (?, ?)");
493- session.execute(ins.bind(0, userType));
438+ // insert UDT data
439+ UserType userTypeDef = cluster.getMetadata().getKeyspace("testUdtsWithNulls").getUserType("user");
440+ UDTValue userType = userTypeDef.newValue().setString("a", null).setInt("b", 0).setUUID("c", null).setBytes("d", null);
494441
495- // retrieve and verify data
496- ResultSet rs = session.execute("SELECT * FROM mytable");
497- List<Row> rows = rs.all();
498- assertEquals(1, rows.size());
442+ PreparedStatement ins = session.prepare("INSERT INTO mytable (a, b) VALUES (?, ?)");
443+ session.execute(ins.bind(0, userType));
499444
500- Row row = rows.get(0);
445+ // retrieve and verify data
446+ ResultSet rs = session.execute("SELECT * FROM mytable");
447+ List<Row> rows = rs.all();
448+ assertEquals(1, rows.size());
501449
502- assertEquals(row.getInt("a"), 0);
503- assertEquals(row.getUDTValue("b"), userType);
450+ Row row = rows.get(0);
504451
505- // test empty strings
506- userType = userTypeDef.newValue().setString("a", "").setInt("b", 0).setUUID("c", null).setBytes("d", ByteBuffer.allocate(0));
507- session.execute(ins.bind(0, userType));
452+ assertEquals(row.getInt("a"), 0);
453+ assertEquals(row.getUDTValue("b"), userType);
508454
509- // retrieve and verify data
510- rs = session.execute("SELECT * FROM mytable");
511- rows = rs.all();
512- assertEquals(1, rows.size());
455+ // test empty strings
456+ userType = userTypeDef.newValue().setString("a", "").setInt("b", 0).setUUID("c", null).setBytes("d", ByteBuffer.allocate(0));
457+ session.execute(ins.bind(0, userType));
513458
514- row = rows.get(0);
459+ // retrieve and verify data
460+ rs = session.execute("SELECT * FROM mytable");
461+ rows = rs.all();
462+ assertEquals(1, rows.size());
515463
516- assertEquals(row.getInt("a"), 0);
517- assertEquals(row.getUDTValue("b"), userType);
464+ row = rows.get(0);
518465
519- } catch (Exception e) {
520- errorOut();
521- throw e;
522- }
466+ assertEquals(row.getInt("a"), 0);
467+ assertEquals(row.getUDTValue("b"), userType);
523468 }
524469
525470 /**
@@ -529,52 +474,46 @@
529474 */
530475 @Test(groups = "short")
531476 public void testUdtsWithCollectionNulls() throws Exception {
532- try {
533- // create keyspace
534- session.execute("CREATE KEYSPACE testUdtsWithCollectionNulls " +
535- "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
536- session.execute("USE testUdtsWithCollectionNulls");
537-
538- // create UDT
539- session.execute("CREATE TYPE user (a List<text>, b Set<text>, c Map<text, text>, d frozen<Tuple<text>>)");
540- session.execute("CREATE TABLE mytable (a int PRIMARY KEY, b frozen<user>)");
541-
542- // insert null UDT data
543- PreparedStatement ins = session.prepare("INSERT INTO mytable (a, b) " +
544- "VALUES (0, { a: ?, b: ?, c: ?, d: ? })");
545- session.execute(ins.bind().setList(0, null).setSet(1, null).setMap(2, null).setTupleValue(3, null));
546-
547- // retrieve and verify data
548- ResultSet rs = session.execute("SELECT * FROM mytable");
549- List<Row> rows = rs.all();
550- assertEquals(1, rows.size());
551-
552- Row row = rows.get(0);
553- assertEquals(row.getInt("a"), 0);
554-
555- UserType userTypeDef = cluster.getMetadata().getKeyspace("testUdtsWithCollectionNulls").getUserType("user");
556- UDTValue userType = userTypeDef.newValue().setList("a", null).setSet("b", null).setMap("c", null).setTupleValue("d", null);
557- assertEquals(row.getUDTValue("b"), userType);
558-
559- // test missing UDT args
560- ins = session.prepare("INSERT INTO mytable (a, b) " +
561- "VALUES (1, { a: ? })");
562- session.execute(ins.bind().setList(0, new ArrayList<Object>()));
563-
564- // retrieve and verify data
565- rs = session.execute("SELECT * FROM mytable");
566- rows = rs.all();
567- assertEquals(2, rows.size());
568-
569- row = rows.get(0);
570- assertEquals(row.getInt("a"), 1);
571-
572- userType = userTypeDef.newValue().setList(0, new ArrayList<Object>());
573- assertEquals(row.getUDTValue("b"), userType);
574-
575- } catch (Exception e) {
576- errorOut();
577- throw e;
578- }
477+ // create keyspace
478+ session.execute("CREATE KEYSPACE testUdtsWithCollectionNulls " +
479+ "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
480+ session.execute("USE testUdtsWithCollectionNulls");
481+
482+ // create UDT
483+ session.execute("CREATE TYPE user (a List<text>, b Set<text>, c Map<text, text>, d frozen<Tuple<text>>)");
484+ session.execute("CREATE TABLE mytable (a int PRIMARY KEY, b frozen<user>)");
485+
486+ // insert null UDT data
487+ PreparedStatement ins = session.prepare("INSERT INTO mytable (a, b) " +
488+ "VALUES (0, { a: ?, b: ?, c: ?, d: ? })");
489+ session.execute(ins.bind().setList(0, null).setSet(1, null).setMap(2, null).setTupleValue(3, null));
490+
491+ // retrieve and verify data
492+ ResultSet rs = session.execute("SELECT * FROM mytable");
493+ List<Row> rows = rs.all();
494+ assertEquals(1, rows.size());
495+
496+ Row row = rows.get(0);
497+ assertEquals(row.getInt("a"), 0);
498+
499+ UserType userTypeDef = cluster.getMetadata().getKeyspace("testUdtsWithCollectionNulls").getUserType("user");
500+ UDTValue userType = userTypeDef.newValue().setList("a", null).setSet("b", null).setMap("c", null).setTupleValue("d", null);
501+ assertEquals(row.getUDTValue("b"), userType);
502+
503+ // test missing UDT args
504+ ins = session.prepare("INSERT INTO mytable (a, b) " +
505+ "VALUES (1, { a: ? })");
506+ session.execute(ins.bind().setList(0, new ArrayList<Object>()));
507+
508+ // retrieve and verify data
509+ rs = session.execute("SELECT * FROM mytable");
510+ rows = rs.all();
511+ assertEquals(2, rows.size());
512+
513+ row = rows.get(0);
514+ assertEquals(row.getInt("a"), 1);
515+
516+ userType = userTypeDef.newValue().setList(0, new ArrayList<Object>());
517+ assertEquals(row.getUDTValue("b"), userType);
579518 }
580519 }
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+ .withAddressTranslater(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(TestUtils.CREATE_TABLE_SIMPLE_FORMAT, 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(TestUtils.CREATE_TABLE_SIMPLE_FORMAT, 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/policies/AbstractRetryPolicyIntegrationTest.java +3 −2
@@ -61,7 +61,8 @@
6161 scassandras.init();
6262
6363 cluster = Cluster.builder()
64- .addContactPoint(CCMBridge.ipOfNode(1))
64+ .addContactPointsWithPorts(scassandras.address(1))
65+ .withAddressTranslater(scassandras.addressTranslator())
6566 .withRetryPolicy(retryPolicy)
6667 .withLoadBalancingPolicy(new SortingLoadBalancingPolicy())
6768 .withNettyOptions(nonQuietClusterCloseOptions)
@@ -128,7 +129,7 @@
128129 assertThat(scassandras.node(hostNumber).activityClient().retrieveQueries()).hasSize(times);
129130 }
130131
131- @AfterMethod(groups = "short")
132+ @AfterMethod(groups = "short", alwaysRun = true)
132133 public void afterMethod() {
133134 if (cluster != null)
134135 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+ .withAddressTranslater(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+ .withAddressTranslater(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+ .withAddressTranslater(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+ .withAddressTranslater(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+ .withAddressTranslater(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+ .withAddressTranslater(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+ .withAddressTranslater(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+ .withAddressTranslater(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+ .withAddressTranslater(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+ .withAddressTranslater(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+ .withAddressTranslater(sCluster.addressTranslator())
510523 .withLoadBalancingPolicy(policy)
511524 .build();
512525
modified driver-core/src/test/java/com/datastax/driver/core/policies/DefaultRetryPolicyIntegrationTest.java +2 −2
@@ -15,7 +15,6 @@
1515 */
1616 package com.datastax.driver.core.policies;
1717
18-import com.datastax.driver.core.CCMBridge;
1918 import com.datastax.driver.core.Cluster;
2019 import com.datastax.driver.core.Metrics;
2120 import com.datastax.driver.core.Session;
@@ -107,7 +106,8 @@
107106 Collections.singletonList(host1.getSocketAddress()));
108107
109108 Cluster whiteListedCluster = Cluster.builder()
110- .addContactPoint(CCMBridge.ipOfNode(1))
109+ .addContactPointsWithPorts(scassandras.address(1))
110+ .withAddressTranslater(scassandras.addressTranslator())
111111 .withRetryPolicy(retryPolicy)
112112 .withLoadBalancingPolicy(firstHostOnlyPolicy)
113113 .build();
modified driver-core/src/test/java/com/datastax/driver/core/policies/DowngradingConsistencyRetryPolicyIntegrationTest.java +47 −44
@@ -17,11 +17,15 @@
1717
1818 import com.datastax.driver.core.*;
1919 import com.google.common.base.Objects;
20+import com.google.common.util.concurrent.Uninterruptibles;
2021 import org.mockito.Mockito;
2122 import org.mockito.verification.VerificationMode;
2223 import org.testng.annotations.Test;
2324
25+import java.util.concurrent.TimeUnit;
26+
2427 import static com.datastax.driver.core.ConsistencyLevel.*;
28+import static com.datastax.driver.core.TestUtils.ipOfNode;
2529 import static org.assertj.core.api.Assertions.assertThat;
2630 import static org.mockito.Matchers.any;
2731 import static org.mockito.Matchers.anyInt;
@@ -33,59 +37,58 @@
3337 * receivedResponses in primed responses.
3438 * If that becomes possible in the future, we could refactor this test.
3539 */
36-public class DowngradingConsistencyRetryPolicyIntegrationTest {
40+@CCMConfig(dirtiesContext = true, createCluster = false, numberOfNodes = 3)
41+public class DowngradingConsistencyRetryPolicyIntegrationTest extends CCMTestsSupport {
3742
3843 @Test(groups = "long")
3944 public void should_downgrade_if_not_enough_replicas_for_requested_CL() {
40- CCMBridge ccm = null;
41- Cluster cluster = null;
42- try {
43- // 3-node cluster, keyspace with RF = 3
44- ccm = CCMBridge.builder(this.getClass().getName()).withNodes(3).build();
45- cluster = Cluster.builder()
46- .addContactPoint(CCMBridge.ipOfNode(1))
47- .withRetryPolicy(Mockito.spy(DowngradingConsistencyRetryPolicy.INSTANCE))
48- .build();
49- Session session = cluster.connect();
50-
51- session.execute("CREATE KEYSPACE test WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 3}");
52- session.execute("CREATE TABLE test.foo(k int primary key)");
53- session.execute("INSERT INTO test.foo(k) VALUES (0)");
54-
55- // All replicas up: should achieve all levels without downgrading
56- checkAchievedConsistency(ALL, ALL, session);
57- checkAchievedConsistency(QUORUM, QUORUM, session);
58- checkAchievedConsistency(ONE, ONE, session);
59-
60- ccm.stop(1);
61- ccm.waitForDown(1);
62- // Two replicas remaining: should downgrade to 2 when CL > 2
63- checkAchievedConsistency(ALL, TWO, session);
64- checkAchievedConsistency(QUORUM, QUORUM, session); // since RF = 3, quorum is still achievable with two nodes
65- checkAchievedConsistency(TWO, TWO, session);
66- checkAchievedConsistency(ONE, ONE, session);
67-
68- ccm.stop(2);
69- ccm.waitForDown(2);
70- // One replica remaining: should downgrade to 1 when CL > 1
71- checkAchievedConsistency(ALL, ONE, session);
72- checkAchievedConsistency(QUORUM, ONE, session);
73- checkAchievedConsistency(TWO, ONE, session);
74- checkAchievedConsistency(ONE, ONE, session);
75-
76- } finally {
77- if (cluster != null)
78- cluster.close();
79- if (ccm != null)
80- ccm.remove();
81- }
45+ Cluster cluster = register(Cluster.builder()
46+ .addContactPointsWithPorts(getHostAddress(1))
47+ .withAddressTranslater(getAddressTranslator())
48+ .withRetryPolicy(Mockito.spy(DowngradingConsistencyRetryPolicy.INSTANCE))
49+ .build());
50+ Session session = cluster.connect();
51+
52+ String ks = TestUtils.getAvailableKeyspaceName();
53+ session.execute(String.format("CREATE KEYSPACE %s WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 3}", ks));
54+ // tests fail randomly here with InvalidQueryException: Keyspace 'xxx' does not exist
55+ Uninterruptibles.sleepUninterruptibly(5, TimeUnit.SECONDS);
56+ session.execute(String.format("USE %s", ks));
57+ session.execute("CREATE TABLE foo(k int primary key)");
58+ session.execute("INSERT INTO foo(k) VALUES (0)");
59+
60+ // All replicas up: should achieve all levels without downgrading
61+ checkAchievedConsistency(ALL, ALL, session);
62+ checkAchievedConsistency(QUORUM, QUORUM, session);
63+ checkAchievedConsistency(ONE, ONE, session);
64+
65+ stopAndWait(1, cluster);
66+ // Two replicas remaining: should downgrade to 2 when CL > 2
67+ checkAchievedConsistency(ALL, TWO, session);
68+ checkAchievedConsistency(QUORUM, QUORUM, session); // since RF = 3, quorum is still achievable with two nodes
69+ checkAchievedConsistency(TWO, TWO, session);
70+ checkAchievedConsistency(ONE, ONE, session);
71+
72+ stopAndWait(2, cluster);
73+ // One replica remaining: should downgrade to 1 when CL > 1
74+ checkAchievedConsistency(ALL, ONE, session);
75+ checkAchievedConsistency(QUORUM, ONE, session);
76+ checkAchievedConsistency(TWO, ONE, session);
77+ checkAchievedConsistency(ONE, ONE, session);
78+
79+ }
80+
81+ private void stopAndWait(int node, Cluster cluster) {
82+ ccm.stop(node);
83+ ccm.waitForDown(node);// this uses port ping
84+ TestUtils.waitForDown(ipOfNode(node), cluster, 10); // this uses UP/DOWN events
8285 }
8386
8487 private void checkAchievedConsistency(ConsistencyLevel requested, ConsistencyLevel expected, Session session) {
8588 RetryPolicy retryPolicy = session.getCluster().getConfiguration().getPolicies().getRetryPolicy();
8689 Mockito.reset(retryPolicy);
8790
88- Statement s = new SimpleStatement("SELECT * FROM test.foo WHERE k = 0")
91+ Statement s = new SimpleStatement("SELECT * FROM foo WHERE k = 0")
8992 .setConsistencyLevel(requested);
9093
9194 ResultSet rs = session.execute(s);
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+ .withAddressTranslater(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+ .withAddressTranslater(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+ .withAddressTranslater(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+ .withAddressTranslater(sCluster.addressTranslator())
7375 .withNettyOptions(nonQuietClusterCloseOptions)
7476 .withLoadBalancingPolicy(loadBalancingPolicy)
7577 .build();
@@ -134,7 +136,9 @@
134136 .withNodes(3)
135137 .withSimpleKeyspace("keyspace", 1)
136138 .build();
137- Cluster cluster = Cluster.builder().addContactPoints(sCluster.address(1))
139+ Cluster cluster = Cluster.builder()
140+ .addContactPointsWithPorts(sCluster.address(1))
141+ .withAddressTranslater(sCluster.addressTranslator())
138142 .withNettyOptions(nonQuietClusterCloseOptions)
139143 .withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy()))
140144 .build();
@@ -177,7 +181,9 @@
177181 .withNodes(3, 3)
178182 .withNetworkTopologyKeyspace("keyspace", ImmutableMap.of(1, 1, 2, 1))
179183 .build();
180- Cluster cluster = Cluster.builder().addContactPoints(sCluster.address(2, 1))
184+ Cluster cluster = Cluster.builder()
185+ .addContactPointsWithPorts(sCluster.address(1))
186+ .withAddressTranslater(sCluster.addressTranslator())
181187 .withNettyOptions(nonQuietClusterCloseOptions)
182188 .withLoadBalancingPolicy(new TokenAwarePolicy(DCAwareRoundRobinPolicy.builder()
183189 .withLocalDc(ScassandraCluster.datacenter(2))
@@ -223,7 +229,9 @@
223229 .withNodes(4)
224230 .withSimpleKeyspace("keyspace", 2)
225231 .build();
226- Cluster cluster = Cluster.builder().addContactPoints(sCluster.address(2))
232+ Cluster cluster = Cluster.builder()
233+ .addContactPointsWithPorts(sCluster.address(2))
234+ .withAddressTranslater(sCluster.addressTranslator())
227235 .withNettyOptions(nonQuietClusterCloseOptions)
228236 // Don't shuffle replicas just to keep test deterministic.
229237 .withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy(), false))
@@ -309,11 +317,12 @@
309317 @Test(groups = "long")
310318 public void should_properly_generate_and_use_routing_key_for_composite_partition_key() {
311319 // given: a 3 node cluster with a keyspace with RF 1.
312- CCMBridge ccm = CCMBridge.builder("TokenAwarePolicyTest").withNodes(3).notStarted().build();
320+ CCMBridge ccm = CCMBridge.builder().withNodes(3).notStarted().build();
313321
314322 Cluster cluster = Cluster.builder()
315323 .withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy()))
316- .addContactPoint(CCMBridge.ipOfNode(1))
324+ .addContactPointsWithPorts(ccm.addressOfNode(1))
325+ .withAddressTranslater(ccm.addressTranslator())
317326 .build();
318327
319328 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+ .withAddressTranslater(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(TestUtils.CREATE_TABLE_SIMPLE_FORMAT, 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 −12
@@ -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
@@ -99,7 +91,6 @@
9991
10092 String batch_query;
10193 Statement batch;
102- ResultSet rs;
10394
10495 query = select().from(table).where(eq("k", 42));
10596
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/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-examples/osgi/src/test/java/com/datastax/driver/osgi/MailboxServiceIT.java +3 −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 com.datastax.driver.osgi.api.MailboxException;
2020 import com.datastax.driver.osgi.api.MailboxMessage;
2121 import com.datastax.driver.osgi.api.MailboxService;
@@ -79,8 +79,9 @@
7979 @Override
8080 public Option[] getOptions() {
8181 return options(
82- systemProperty("cassandra.contactpoints").value(CCMBridge.IP_PREFIX + 1),
82+ systemProperty("cassandra.contactpoints").value(TestUtils.IP_PREFIX + 1),
8383 bundle("reference:file:target/classes"),
84+ bootDelegationPackages("javax.security.*"),
8485 mavenBundle("com.codahale.metrics", "metrics-core", "3.0.2"),
8586 mavenBundle("org.slf4j", "slf4j-api", "1.7.5"),
8687 mavenBundle("org.slf4j", "slf4j-simple", "1.7.5").noStart(),
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperAccessorParamsTest.java +4 −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.core.ResultSet;
2020 import com.datastax.driver.core.Row;
2121 import com.datastax.driver.core.utils.CassandraVersion;
@@ -27,9 +27,9 @@
2727
2828 import static org.assertj.core.api.Assertions.assertThat;
2929
30-public class MapperAccessorParamsTest extends CCMBridge.PerClassSingleNodeCluster {
30+public class MapperAccessorParamsTest extends CCMTestsSupport {
3131 @Override
32- protected Collection<String> getTableDefinitions() {
32+ public Collection<String> createTestFixtures() {
3333 return Lists.newArrayList(
3434 "CREATE TABLE user ( key int primary key, gender int, home_phone text, work_phone text)",
3535 "CREATE INDEX on user(gender)",
@@ -246,4 +246,4 @@
246246 this.gender = val;
247247 }
248248 }
249-}
No newline at the end of the file
249+}
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
@@ -35,10 +35,10 @@
3535 * annotation to map computed fields.
3636 */
3737 @SuppressWarnings("unused")
38-public class MapperComputedFieldsTest extends CCMBridge.PerClassSingleNodeCluster {
38+public class MapperComputedFieldsTest extends CCMTestsSupport {
3939
4040 @Override
41- protected Collection<String> getTableDefinitions() {
41+ public Collection<String> createTestFixtures() {
4242 return Lists.newArrayList(
4343 "CREATE TABLE user (login text primary key, name text)",
4444 "INSERT INTO user (login, name) VALUES ('testlogin', 'test name')");
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperDefaultKeyspaceTest.java +9 −6
@@ -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,12 +34,15 @@
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- return Arrays.asList("CREATE TABLE groups (group_id uuid PRIMARY KEY, name text)",
42+ @Override
43+ public Collection<String> createTestFixtures() {
44+ return Arrays.asList(
45+ "CREATE TABLE groups (group_id uuid PRIMARY KEY, name text)",
4346 "CREATE TYPE IF NOT EXISTS group_name (name text)");
4447 }
4548
@@ -157,7 +160,7 @@
157160 if (other == null || other.getClass() != this.getClass())
158161 return false;
159162
160- Group that = (Group) other;
163+ Group2 that = (Group2) other;
161164 return Objects.equal(groupId, that.groupId)
162165 && Objects.equal(name, that.name);
163166 }
@@ -195,7 +198,7 @@
195198 public boolean equals(Object other) {
196199 if (other instanceof GroupName) {
197200 GroupName that = (GroupName) other;
198- return this.name == that.name;
201+ return this.name.equals(that.name);
199202 }
200203 return false;
201204 }
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperEnumTest.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.mapping.annotations.Enumerated;
2020 import com.datastax.driver.mapping.annotations.PartitionKey;
2121 import com.datastax.driver.mapping.annotations.Table;
@@ -29,10 +29,11 @@
2929 /**
3030 * Covers handling of enum fields by the mapper.
3131 */
32-public class MapperEnumTest extends CCMBridge.PerClassSingleNodeCluster {
32+@SuppressWarnings("unused")
33+public class MapperEnumTest extends CCMTestsSupport {
3334
3435 @Override
35- protected Collection<String> getTableDefinitions() {
36+ public Collection<String> createTestFixtures() {
3637 return Lists.newArrayList("CREATE TABLE asOrdinal (k int primary key, v int)",
3738 "CREATE TABLE asString (k int primary key, v text)");
3839 }
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperInvalidCollectionTypesTest.java +6 −3
@@ -15,15 +15,18 @@
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 org.testng.annotations.Test;
2222
2323 import java.util.*;
2424
25-public class MapperInvalidCollectionTypesTest extends CCMBridge.PerClassSingleNodeCluster {
26- protected Collection<String> getTableDefinitions() {
25+@SuppressWarnings("unused")
26+public class MapperInvalidCollectionTypesTest extends CCMTestsSupport {
27+
28+ @Override
29+ public Collection<String> createTestFixtures() {
2730 return Arrays.asList(
2831 "CREATE TABLE table_list (id int PRIMARY KEY, l list<int>)",
2932 "CREATE TABLE table_set (id int PRIMARY KEY, s set<int>)",
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/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 +10 −8
@@ -33,9 +33,11 @@
3333 /**
3434 * Basic tests for the mapping module.
3535 */
36-public class MapperTest extends CCMBridge.PerClassSingleNodeCluster {
37-
38- protected Collection<String> getTableDefinitions() {
36+@SuppressWarnings("unused")
37+public class MapperTest extends CCMTestsSupport {
38+
39+ @Override
40+ public Collection<String> createTestFixtures() {
3941 // We'll allow to generate those create statement from the annotated entities later, but it's currently
4042 // a TODO
4143 return Arrays.asList("CREATE TABLE users (user_id uuid PRIMARY KEY, name text, email text, year int, gender text)",
@@ -267,24 +269,24 @@
267269 // harcoded arg0, arg1, .... A big annoying, and apparently Java 8 will fix that
268270 // somehow, but well, not a huge deal.
269271 @Query("SELECT * FROM posts WHERE user_id=:userId AND post_id=:postId")
270- public Post getOne(@Param("userId") UUID userId,
271- @Param("postId") UUID postId);
272+ Post getOne(@Param("userId") UUID userId,
273+ @Param("postId") UUID postId);
272274
273275 // Note that the following method will be asynchronous (it will use executeAsync
274276 // underneath) because it's return type is a ListenableFuture. Similarly, we know
275277 // that we need to map the result to the Post entity thanks to the return type.
276278 @Query("SELECT * FROM posts WHERE user_id=?")
277279 @QueryParameters(consistency = "QUORUM")
278- public ListenableFuture<Result<Post>> getAllAsync(UUID userId);
280+ ListenableFuture<Result<Post>> getAllAsync(UUID userId);
279281
280282 // The method above actually query stuff, but if a method is declared to return
281283 // a Statement, it will not execute anything, but just return you the BoundStatement
282284 // ready for execution. That way, you can batch stuff for instance (see usage below).
283285 @Query("UPDATE posts SET content=? WHERE user_id=? AND post_id=?")
284- public Statement updateContentQuery(String newContent, UUID userId, UUID postId);
286+ Statement updateContentQuery(String newContent, UUID userId, UUID postId);
285287
286288 @Query("SELECT * FROM posts")
287- public Result<Post> getAll();
289+ Result<Post> getAll();
288290 }
289291
290292 @Accessor
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, l list<frozen<sub>>, s set<frozen<sub>>, m1 map<int,frozen<sub>>, m2 map<frozen<sub>,int>, m3 map<frozen<sub>,frozen<sub>>)");
3840 }
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperUDTTest.java +7 −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.core.ResultSet;
2020 import com.datastax.driver.core.utils.UUIDs;
2121 import com.datastax.driver.mapping.annotations.*;
@@ -29,9 +29,11 @@
2929 import static org.assertj.core.api.Assertions.assertThat;
3030 import static org.testng.Assert.*;
3131
32-public class MapperUDTTest extends CCMBridge.PerClassSingleNodeCluster {
32+@SuppressWarnings("unused")
33+public class MapperUDTTest extends CCMTestsSupport {
3334
34- protected Collection<String> getTableDefinitions() {
35+ @Override
36+ public Collection<String> createTestFixtures() {
3537 return Arrays.asList("CREATE TYPE address (street text, city text, zip_code int, phones set<text>)",
3638 "CREATE TABLE users (user_id uuid PRIMARY KEY, name text, mainaddress frozen<address>, other_addresses map<text,frozen<address>>)");
3739 }
@@ -141,9 +143,7 @@
141143 this.city = city;
142144 this.zipCode = zipCode;
143145 this.phones = new HashSet<String>();
144- for (String phone : phones) {
145- this.phones.add(phone);
146- }
146+ Collections.addAll(this.phones, phones);
147147 }
148148
149149 public String getStreet() {
@@ -203,7 +203,7 @@
203203 ResultSet setOtherAddresses(@Param("id") UUID id, @Param("addresses") Map<String, Address> addresses);
204204
205205 @Query("SELECT * FROM users")
206- public Result<User> getAll();
206+ Result<User> getAll();
207207 }
208208
209209 @Test(groups = "short")
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+ .withAddressTranslater(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+ .withAddressTranslater(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+ .withAddressTranslater(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+ .withAddressTranslater(ccm.addressTranslator())
114+ .build();
102115 Session session2 = cluster.newSession();
103116
104117 session2.execute("use java_509");