Elffuss BraidHub

kikocis/java-driver public

Merge pull request #578 from datastax/2.1-test-fixes

More CCM test fixes
Changesetb1d245a67292f2db7317f3d4cdcbdc796eee60f3b37f96746ece8fb195d6552b
AuthorAlexandre Dutra <adutra@users.noreply.github.com> · 2016-01-27 18:54 +01:00
CommitterAlexandre Dutra <adutra@users.noreply.github.com> · 2016-01-27 18:54 +01:00
Parentsd3d82a63787d, 61311abbf098

Browse the files at this changeset

93 files changed

modified driver-core/src/test/java/com/datastax/driver/core/AbstractPoliciesTest.java +53 −86
@@ -15,6 +15,10 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.google.common.util.concurrent.Uninterruptibles;
19+import org.slf4j.Logger;
20+import org.slf4j.LoggerFactory;
21+import org.testng.annotations.AfterMethod;
1822 import org.testng.annotations.BeforeMethod;
1923
2024 import java.net.InetAddress;
@@ -23,45 +27,53 @@
2327 import java.util.Map;
2428 import java.util.concurrent.Callable;
2529
26-import static com.datastax.driver.core.TestUtils.*;
30+import static com.datastax.driver.core.ConditionChecker.check;
31+import static com.datastax.driver.core.TestUtils.CREATE_KEYSPACE_GENERIC_FORMAT;
32+import static com.datastax.driver.core.TestUtils.CREATE_KEYSPACE_SIMPLE_FORMAT;
2733 import static com.datastax.driver.core.querybuilder.QueryBuilder.batch;
2834 import static com.datastax.driver.core.querybuilder.QueryBuilder.insertInto;
29-import static org.testng.Assert.*;
35+import static java.util.concurrent.TimeUnit.MINUTES;
36+import static org.testng.Assert.assertEquals;
3037
3138 public abstract class AbstractPoliciesTest extends CCMTestsSupport {
3239
33- private static final boolean DEBUG = false;
40+ private static final Logger logger = LoggerFactory.getLogger(AbstractPoliciesTest.class);
41+ private String tableName;
42+
43+ private static class SchemaInAgreement implements Callable<Boolean> {
44+
45+ private final Cluster cluster;
46+
47+ private SchemaInAgreement(Cluster cluster) {
48+ this.cluster = cluster;
49+ }
50+
51+ @Override
52+ public Boolean call() throws Exception {
53+ return cluster.getMetadata().checkSchemaAgreement();
54+ }
55+ }
3456
3557 protected Map<InetAddress, Integer> coordinators = new HashMap<InetAddress, Integer>();
3658
3759 protected PreparedStatement prepared;
3860
3961 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);
50- session.execute(String.format("CREATE TABLE %s (k int PRIMARY KEY, i int)", SIMPLE_TABLE));
62+ final String ks = TestUtils.generateIdentifier("ks_");
63+ tableName = TestUtils.generateIdentifier("table_");
64+ session().execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, ks, replicationFactor));
65+ useKeyspace(ks);
66+ session().execute(String.format("CREATE TABLE %s (k int PRIMARY KEY, i int)", tableName));
67+ check().before(5, MINUTES).that(new SchemaInAgreement(cluster())).becomesTrue();
5168 }
5269
5370 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);
64- session.execute(String.format("CREATE TABLE %s (k int PRIMARY KEY, i int)", SIMPLE_TABLE));
71+ final String ks = TestUtils.generateIdentifier("ks_");
72+ tableName = TestUtils.generateIdentifier("table_");
73+ session().execute(String.format(CREATE_KEYSPACE_GENERIC_FORMAT, ks, "NetworkTopologyStrategy", String.format("'dc1' : %d, 'dc2' : %d", dc1RF, dc2RF)));
74+ useKeyspace(ks);
75+ session().execute(String.format("CREATE TABLE %s (k int PRIMARY KEY, i int)", tableName));
76+ check().before(5, MINUTES).that(new SchemaInAgreement(cluster())).becomesTrue();
6577 }
6678
6779 /**
@@ -78,6 +90,12 @@
7890 coordinators = new HashMap<InetAddress, Integer>();
7991 }
8092
93+ @AfterMethod(groups = "long")
94+ protected void pause() {
95+ // pause before engaging in another expensive CCM cluster creation
96+ Uninterruptibles.sleepUninterruptibly(1, MINUTES);
97+ }
98+
8199 private String queriedMapString() {
82100 StringBuilder sb = new StringBuilder();
83101 sb.append("{");
@@ -92,67 +110,15 @@
92110 protected void assertQueried(String host, int n) {
93111 try {
94112 Integer queried = coordinators.get(InetAddress.getByName(host));
95- if (DEBUG)
96- System.out.println(String.format("Expected: %s\tReceived: %s", n, queried));
97- else {
98- assertEquals(queried == null ? 0 : queried, n, queriedMapString());
99- }
100- } catch (Exception e) {
101- throw new RuntimeException(e);
102- }
103- }
104-
105- protected void assertQueriedAtLeast(String host, int n) {
106- try {
107- Integer queried = coordinators.get(InetAddress.getByName(host));
108- queried = queried == null ? 0 : queried;
109- if (DEBUG)
110- System.out.println(String.format("Expected > %s\tReceived: %s", n, queried));
113+ if (logger.isDebugEnabled())
114+ logger.debug(String.format("Expected: %s\tReceived: %s", n, queried));
111115 else
112- assertTrue(queried >= n, "For " + host);
113- } catch (Exception e) {
114- throw new RuntimeException(e);
115- }
116- }
117-
118- /**
119- * Assert that one of the nodes in the list was queried with n, no matter which one
120- */
121- protected void assertOneNodeQueried(int n, String... hosts) {
122- try {
123- boolean found = false;
124- for (String host : hosts) {
125- InetAddress addr = InetAddress.getByName(host);
126- int queried = coordinators.containsKey(addr) ? coordinators.get(addr) : 0;
127- if (DEBUG)
128- System.out.println(String.format("Expected: %s\tReceived: %s", n, queried));
129- else {
130-
131- if (n == queried) {
132- if (found)
133- throw new AssertionError(String.format("Found 2 nodes with %s queries in %s", n, queriedMapString()));
134- found = true;
135- } else {
136- if (queried != 0)
137- throw new AssertionError(String.format("Host %s should have be queried: %s", addr, queriedMapString()));
138- }
139- }
140- }
141- if (!found)
142- throw new AssertionError("Found no host queried exactly " + n + " times in " + queriedMapString());
116+ assertEquals(queried == null ? 0 : queried, n, queriedMapString());
143117 } catch (Exception e) {
144118 throw new RuntimeException(e);
145119 }
146120 }
147121
148- protected void failDebug(String message) {
149- if (DEBUG)
150- System.out.println(message);
151- else
152- fail(message);
153- }
154-
155-
156122 /**
157123 * Init methods that handle writes using batch and consistency options.
158124 */
@@ -170,7 +136,7 @@
170136
171137 protected void init(int n, boolean batch, ConsistencyLevel cl) {
172138 write(n, batch, cl);
173- prepared = session.prepare("SELECT * FROM " + SIMPLE_TABLE + " WHERE k = ?").setConsistencyLevel(cl);
139+ prepared = session().prepare("SELECT * FROM " + tableName + " WHERE k = ?").setConsistencyLevel(cl);
174140 }
175141
176142 protected void write(int n) {
@@ -191,11 +157,11 @@
191157 for (int i = 0; i < n; ++i)
192158 if (batch)
193159 // BUG: WriteType == SIMPLE
194- session.execute(batch()
195- .add(insertInto(SIMPLE_TABLE).values(new String[]{"k", "i"}, new Object[]{0, 0}))
160+ session().execute(batch()
161+ .add(insertInto(tableName).values(new String[]{"k", "i"}, new Object[]{0, 0}))
196162 .setConsistencyLevel(cl));
197163 else
198- session.execute(new SimpleStatement(String.format("INSERT INTO %s(k, i) VALUES (0, 0)", SIMPLE_TABLE)).setConsistencyLevel(cl));
164+ session().execute(new SimpleStatement(String.format("INSERT INTO %s(k, i) VALUES (0, 0)", tableName)).setConsistencyLevel(cl));
199165 }
200166
201167
@@ -218,12 +184,13 @@
218184 if (usePrepared) {
219185 BoundStatement bs = prepared.bind(0);
220186 for (int i = 0; i < n; ++i)
221- addCoordinator(session.execute(bs));
187+ addCoordinator(session().execute(bs));
222188 } else {
223189 ByteBuffer routingKey = ByteBuffer.allocate(4);
224190 routingKey.putInt(0, 0);
225191 for (int i = 0; i < n; ++i)
226- addCoordinator(session.execute(new SimpleStatement(String.format("SELECT * FROM %s WHERE k = 0", SIMPLE_TABLE)).setRoutingKey(routingKey).setConsistencyLevel(cl)));
192+ addCoordinator(session().execute(new SimpleStatement(String.format("SELECT * FROM %s WHERE k = 0", tableName)).setRoutingKey(routingKey).setConsistencyLevel(cl)));
227193 }
228194 }
195+
229196 }
modified driver-core/src/test/java/com/datastax/driver/core/AbstractReconnectionHandlerTest.java +13 −11
@@ -31,6 +31,7 @@
3131 import java.util.concurrent.*;
3232 import java.util.concurrent.atomic.AtomicReference;
3333
34+import static com.datastax.driver.core.ConditionChecker.check;
3435 import static org.assertj.core.api.Assertions.assertThat;
3536 import static org.mockito.Mockito.*;
3637 import static org.testng.Assert.fail;
@@ -41,8 +42,14 @@
4142 ScheduledExecutorService executor;
4243 MockReconnectionSchedule schedule;
4344 MockReconnectionWork work;
44- final AtomicReference<ListenableFuture<?>> future = new AtomicReference<ListenableFuture<?>>();
45+ AtomicReference<ListenableFuture<?>> future = new AtomicReference<ListenableFuture<?>>();
4546 AbstractReconnectionHandler handler;
47+ Callable<Boolean> nextTryAssigned = new Callable<Boolean>() {
48+ @Override
49+ public Boolean call() throws Exception {
50+ return handler.handlerFuture.nextTry != null;
51+ }
52+ };
4653
4754 @BeforeMethod(groups = {"unit", "short"})
4855 public void setup() {
@@ -58,7 +65,7 @@
5865
5966 @Override
6067 protected void onReconnection(Connection connection) {
61- work.onReconnection(connection);
68+ work.onReconnection();
6269 }
6370 };
6471 }
@@ -149,12 +156,7 @@
149156 verify(executor, timeout(10000)).schedule(handler, schedule.delay, TimeUnit.MILLISECONDS);
150157
151158 // 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);
159+ check().before(10000).that(nextTryAssigned).becomesTrue();
158160
159161 future.get().cancel(false);
160162
@@ -341,7 +343,7 @@
341343 tries += 1;
342344 logger.debug("in reconnection work, wait for tick from main thread");
343345 try {
344- barrier.await(10, TimeUnit.SECONDS);
346+ barrier.await(60, TimeUnit.SECONDS);
345347 logger.debug("in reconnection work, got tick from main thread, proceeding");
346348 } catch (Exception e) {
347349 fail("Error while waiting for tick", e);
@@ -362,14 +364,14 @@
362364 public void tick() {
363365 logger.debug("send tick to reconnection work");
364366 try {
365- barrier.await(10, TimeUnit.SECONDS);
367+ barrier.await(60, TimeUnit.SECONDS);
366368 } catch (Exception e) {
367369 fail("Error while sending tick, no thread was waiting", e);
368370 }
369371 barrier.reset();
370372 }
371373
372- protected void onReconnection(Connection connection) {
374+ protected void onReconnection() {
373375 success = true;
374376 }
375377 }
modified driver-core/src/test/java/com/datastax/driver/core/AsyncQueryTest.java +10 −14
@@ -23,7 +23,6 @@
2323 import org.testng.annotations.Test;
2424
2525 import java.util.Collection;
26-import java.util.List;
2726 import java.util.concurrent.*;
2827
2928 import static org.assertj.core.api.Assertions.assertThat;
@@ -38,18 +37,15 @@
3837 }
3938
4039 @Override
41- public Collection<String> createTestFixtures() {
42- List<String> definitions = Lists.newArrayList();
43-
40+ public void onTestContextInitialized() {
4441 for (Object[] objects : keyspace()) {
4542 String keyspace = (String) objects[0];
46-
47- definitions.add(String.format("create keyspace %s WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}", keyspace));
48- definitions.add(String.format("create table %s.foo(k int primary key, v int)", keyspace));
49- definitions.add(String.format("insert into %s.foo (k, v) values (1, 1)", keyspace));
43+ execute(
44+ String.format("create keyspace %s WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}", keyspace),
45+ String.format("create table %s.foo(k int primary key, v int)", keyspace),
46+ String.format("insert into %s.foo (k, v) values (1, 1)", keyspace)
47+ );
5048 }
51-
52- return definitions;
5349 }
5450
5551 /**
@@ -57,13 +53,13 @@
5753 */
5854 @Test(groups = "short")
5955 public void cancelled_query_should_release_the_connection() throws InterruptedException {
60- ResultSetFuture future = session.executeAsync("select release_version from system.local");
56+ ResultSetFuture future = session().executeAsync("select release_version from system.local");
6157 future.cancel(true);
6258 assertTrue(future.isCancelled());
6359
6460 TimeUnit.MILLISECONDS.sleep(100);
6561
66- HostConnectionPool pool = getPool(session);
62+ HostConnectionPool pool = getPool(session());
6763 for (Connection connection : pool.connections) {
6864 assertEquals(connection.inFlight.get(), 0);
6965 }
@@ -73,7 +69,7 @@
7369 public void should_init_cluster_and_session_if_needed() throws Exception {
7470 // For this test we need an uninitialized cluster, so we can't reuse the one provided by the
7571 // parent class. Rebuild a new one with the same (unique) host.
76- Host host = cluster.getMetadata().allHosts().iterator().next();
72+ Host host = cluster().getMetadata().allHosts().iterator().next();
7773
7874 Cluster cluster2 = null;
7975 try {
@@ -130,7 +126,7 @@
130126 }
131127
132128 private ListenableFuture<Integer> connectAndQuery(String keyspace, Executor executor) {
133- ListenableFuture<Session> sessionFuture = cluster.connectAsync(keyspace);
129+ ListenableFuture<Session> sessionFuture = cluster().connectAsync(keyspace);
134130 ListenableFuture<ResultSet> queryFuture = Futures.transform(sessionFuture, new AsyncFunction<Session, ResultSet>() {
135131 @Override
136132 public ListenableFuture<ResultSet> apply(Session session) throws Exception {
modified driver-core/src/test/java/com/datastax/driver/core/AuthenticationTest.java +7 −4
@@ -39,7 +39,7 @@
3939 public void sleepIf12() {
4040 // For C* 1.2, sleep before attempting to connect as there is a small delay between
4141 // user being created.
42- if (ccm.getVersion().getMajor() < 2) {
42+ if (ccm().getVersion().getMajor() < 2) {
4343 Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
4444 }
4545 }
@@ -47,7 +47,8 @@
4747 @Test(groups = "short")
4848 public void should_connect_with_credentials() throws InterruptedException {
4949 Cluster cluster = register(Cluster.builder()
50- .addContactPointsWithPorts(getInitialContactPoints())
50+ .addContactPoints(getContactPoints())
51+ .withPort(ccm().getBinaryPort())
5152 .withCredentials("cassandra", "cassandra")
5253 .build());
5354 cluster.connect();
@@ -56,7 +57,8 @@
5657 @Test(groups = "short", expectedExceptions = AuthenticationException.class)
5758 public void should_fail_to_connect_with_wrong_credentials() throws InterruptedException {
5859 Cluster cluster = register(Cluster.builder()
59- .addContactPointsWithPorts(getInitialContactPoints())
60+ .addContactPoints(getContactPoints())
61+ .withPort(ccm().getBinaryPort())
6062 .withCredentials("bogus", "bogus")
6163 .build());
6264 cluster.connect();
@@ -65,7 +67,8 @@
6567 @Test(groups = "short", expectedExceptions = AuthenticationException.class)
6668 public void should_fail_to_connect_without_credentials() throws InterruptedException {
6769 Cluster cluster = register(Cluster.builder()
68- .addContactPointsWithPorts(getInitialContactPoints())
70+ .addContactPoints(getContactPoints())
71+ .withPort(ccm().getBinaryPort())
6972 .build());
7073 cluster.connect();
7174 }
modified driver-core/src/test/java/com/datastax/driver/core/BatchStatementTest.java +9 −12
@@ -19,9 +19,6 @@
1919 import com.datastax.driver.core.utils.CassandraVersion;
2020 import org.testng.annotations.Test;
2121
22-import java.util.Collection;
23-import java.util.Collections;
24-
2522 import static com.datastax.driver.core.CreateCCM.TestMode.PER_METHOD;
2623 import static org.testng.Assert.assertEquals;
2724 import static org.testng.Assert.assertTrue;
@@ -30,14 +27,14 @@
3027 public class BatchStatementTest extends CCMTestsSupport {
3128
3229 @Override
33- public Collection<String> createTestFixtures() {
34- return Collections.singletonList("CREATE TABLE test (k text, v int, PRIMARY KEY (k, v))");
30+ public void onTestContextInitialized() {
31+ execute("CREATE TABLE test (k text, v int, PRIMARY KEY (k, v))");
3532 }
3633
3734 @Test(groups = "short")
3835 public void simpleBatchTest() {
3936 try {
40- PreparedStatement st = session.prepare("INSERT INTO test (k, v) VALUES (?, ?)");
37+ PreparedStatement st = session().prepare("INSERT INTO test (k, v) VALUES (?, ?)");
4138
4239 BatchStatement batch = new BatchStatement();
4340
@@ -47,9 +44,9 @@
4744
4845 assertEquals(3, batch.size());
4946
50- session.execute(batch);
47+ session().execute(batch);
5148
52- ResultSet rs = session.execute("SELECT * FROM test");
49+ ResultSet rs = session().execute("SELECT * FROM test");
5350
5451 Row r;
5552
@@ -69,14 +66,14 @@
6966
7067 } catch (UnsupportedFeatureException e) {
7168 // This is expected when testing the protocol v1
72- assertEquals(cluster.getConfiguration().getProtocolOptions().getProtocolVersionEnum(), ProtocolVersion.V1);
69+ assertEquals(cluster().getConfiguration().getProtocolOptions().getProtocolVersionEnum(), ProtocolVersion.V1);
7370 }
7471 }
7572
7673 @Test(groups = "short")
7774 @CassandraVersion(major = 2.0, minor = 9, description = "This will only work with C* 2.0.9 (CASSANDRA-7337)")
7875 public void casBatchTest() {
79- PreparedStatement st = session.prepare("INSERT INTO test (k, v) VALUES (?, ?) IF NOT EXISTS");
76+ PreparedStatement st = session().prepare("INSERT INTO test (k, v) VALUES (?, ?) IF NOT EXISTS");
8077
8178 BatchStatement batch = new BatchStatement();
8279
@@ -86,12 +83,12 @@
8683
8784 assertEquals(3, batch.size());
8885
89- ResultSet rs = session.execute(batch);
86+ ResultSet rs = session().execute(batch);
9087 Row r = rs.one();
9188 assertTrue(!r.isNull("[applied]"));
9289 assertEquals(r.getBool("[applied]"), true);
9390
94- rs = session.execute(batch);
91+ rs = session().execute(batch);
9592 r = rs.one();
9693 assertTrue(!r.isNull("[applied]"));
9794 assertEquals(r.getBool("[applied]"), false);
modified driver-core/src/test/java/com/datastax/driver/core/BoundStatementTest.java +3 −5
@@ -20,8 +20,6 @@
2020 import org.testng.annotations.BeforeClass;
2121 import org.testng.annotations.Test;
2222
23-import java.util.Collection;
24-
2523 import static org.assertj.core.api.Assertions.assertThat;
2624 import static org.assertj.core.api.Assertions.fail;
2725
@@ -30,13 +28,13 @@
3028 PreparedStatement prepared;
3129
3230 @Override
33- public Collection<String> createTestFixtures() {
34- return Lists.newArrayList("CREATE TABLE foo (k int primary key, v1 text, v2 list<int>)");
31+ public void onTestContextInitialized() {
32+ execute("CREATE TABLE foo (k int primary key, v1 text, v2 list<int>)");
3533 }
3634
3735 @BeforeClass(groups = "short")
3836 public void setup() {
39- prepared = session.prepare("INSERT INTO foo (k, v1, v2) VALUES (?, ?, ?)");
37+ prepared = session().prepare("INSERT INTO foo (k, v1, v2) VALUES (?, ?, ?)");
4038 }
4139
4240 @Test(groups = "short")
modified driver-core/src/test/java/com/datastax/driver/core/CCMAccess.java +7 −1
@@ -22,6 +22,8 @@
2222
2323 public interface CCMAccess extends Closeable {
2424
25+ enum Workload {cassandra, solr, hadoop, spark, cfs, graph}
26+
2527 // Inspection methods
2628
2729 /**
@@ -130,6 +132,10 @@
130132 */
131133 void updateDSEConfig(Map<String, Object> configs);
132134
135+ /**
136+ * Checks for errors in the logs of all nodes in the cluster.
137+ */
138+ String checkForErrors();
133139
134140 // Methods altering nodes
135141
@@ -201,7 +207,7 @@
201207 *
202208 * @param n the node number (starting from 1).
203209 */
204- void setWorkload(int n, String workload);
210+ void setWorkload(int n, Workload workload);
205211
206212
207213 // Methods blocking until nodes are up or down
modified driver-core/src/test/java/com/datastax/driver/core/CCMBridge.java +78 −25
@@ -31,7 +31,6 @@
3131 import java.net.InetSocketAddress;
3232 import java.util.*;
3333 import java.util.concurrent.TimeUnit;
34-import java.util.concurrent.atomic.AtomicInteger;
3534
3635 import static com.datastax.driver.core.TestUtils.executeNoFail;
3736 import static com.datastax.driver.core.TestUtils.findAvailablePort;
@@ -380,7 +379,17 @@
380379 return;
381380 if (logger.isDebugEnabled())
382381 logger.debug("Starting: {} - free memory: {} MB", this, TestUtils.getFreeMemoryMB());
383- execute(CCM_COMMAND + " start --wait-other-notice --wait-for-binary-proto" + jvmArgs);
382+ try {
383+ execute(CCM_COMMAND + " start --wait-other-notice --wait-for-binary-proto" + jvmArgs);
384+ } catch (CCMException e) {
385+ logger.error("Could not start " + this, e);
386+ logger.error("CCM output:\n{}", e.getOut());
387+ setKeepLogs(true);
388+ String errors = checkForErrors();
389+ if (errors != null)
390+ logger.error("CCM check errors:\n{}", errors);
391+ throw e;
392+ }
384393 if (logger.isDebugEnabled())
385394 logger.debug("Started: {} - Free memory: {} MB", this, TestUtils.getFreeMemoryMB());
386395 started = true;
@@ -392,7 +401,6 @@
392401 return;
393402 if (logger.isDebugEnabled())
394403 logger.debug("Stopping: {} - free memory: {} MB", this, TestUtils.getFreeMemoryMB());
395- execute(CCM_COMMAND + " stop");
396404 if (logger.isDebugEnabled())
397405 logger.debug("Stopped: {} - free memory: {} MB", this, TestUtils.getFreeMemoryMB());
398406 closed = true;
@@ -407,10 +415,38 @@
407415 closed = true;
408416 }
409417
418+ @Override
419+ public synchronized void remove() {
420+ stop();
421+ logger.debug("Removing: {}", this);
422+ execute(CCM_COMMAND + " remove");
423+ }
424+
425+ @Override
426+ public String checkForErrors() {
427+ logger.debug("Checking for errors in: {}", this);
428+ try {
429+ return execute(CCM_COMMAND + " checklogerror");
430+ } catch (CCMException e) {
431+ logger.warn("Check for errors failed");
432+ return null;
433+ }
434+ }
435+
410436 @Override
411437 public void start(int n) {
412438 logger.debug(String.format("Starting: node %s (%s%s:%s) in %s", n, TestUtils.IP_PREFIX, n, binaryPort, this));
413- execute(CCM_COMMAND + " node%d start --wait-other-notice --wait-for-binary-proto" + jvmArgs, n);
439+ try {
440+ execute(CCM_COMMAND + " node%d start --wait-other-notice --wait-for-binary-proto" + jvmArgs, n);
441+ } catch (CCMException e) {
442+ logger.error(String.format("Could not start node %s in %s", n, this), e);
443+ logger.error("CCM output:\n{}", e.getOut());
444+ setKeepLogs(true);
445+ String errors = checkForErrors();
446+ if (errors != null)
447+ logger.error("CCM check errors:\n{}", errors);
448+ throw e;
449+ }
414450 }
415451
416452 @Override
@@ -425,13 +461,6 @@
425461 execute(CCM_COMMAND + " node%d stop --not-gently", n);
426462 }
427463
428- @Override
429- public synchronized void remove() {
430- stop();
431- logger.debug("Removing: {}", this);
432- execute(CCM_COMMAND + " remove");
433- }
434-
435464 @Override
436465 public void remove(int n) {
437466 logger.debug(String.format("Removing: node %s (%s%s:%s) from %s", n, TestUtils.IP_PREFIX, n, binaryPort, this));
@@ -505,31 +534,36 @@
505534 }
506535
507536 @Override
508- public void setWorkload(int node, String workload) {
537+ public void setWorkload(int node, Workload workload) {
509538 execute(CCM_COMMAND + " node%d setworkload %s", node, workload);
510539 }
511540
512- private void execute(String command, Object... args) {
513-
541+ private String execute(String command, Object... args) {
514542 String fullCommand = String.format(command, args) + " --config-dir=" + ccmDir;
515543 Closer closer = Closer.create();
516544 // 10 minutes timeout
517545 ExecuteWatchdog watchDog = new ExecuteWatchdog(TimeUnit.MINUTES.toMillis(10));
546+ StringWriter sw = new StringWriter();
547+ final PrintWriter pw = new PrintWriter(sw);
548+ closer.register(pw);
518549 try {
519550 logger.trace("Executing: " + fullCommand);
520551 CommandLine cli = CommandLine.parse(fullCommand);
521552 Executor executor = new DefaultExecutor();
522-
523553 LogOutputStream outStream = new LogOutputStream() {
524554 @Override
525555 protected void processLine(String line, int logLevel) {
526- logger.debug("ccmout> " + line);
556+ String out = "ccmout> " + line;
557+ logger.debug(out);
558+ pw.println(out);
527559 }
528560 };
529561 LogOutputStream errStream = new LogOutputStream() {
530562 @Override
531563 protected void processLine(String line, int logLevel) {
532- logger.error("ccmerr> " + line);
564+ String err = "ccmerr> " + line;
565+ logger.error(err);
566+ pw.println(err);
533567 }
534568 };
535569 closer.register(outStream);
@@ -537,16 +571,17 @@
537571 ExecuteStreamHandler streamHandler = new PumpStreamHandler(outStream, errStream);
538572 executor.setStreamHandler(streamHandler);
539573 executor.setWatchdog(watchDog);
540-
541574 int retValue = executor.execute(cli, ENVIRONMENT_MAP);
542575 if (retValue != 0) {
543576 logger.error("Non-zero exit code ({}) returned from executing ccm command: {}", retValue, fullCommand);
544- throw new RuntimeException();
577+ pw.flush();
578+ throw new CCMException(String.format("Non-zero exit code (%s) returned from executing ccm command: %s", retValue, fullCommand), sw.toString());
545579 }
546580 } catch (IOException e) {
547581 if (watchDog.killedProcess())
548- logger.error("The command {} was killed after 5 minutes", fullCommand);
549- throw new RuntimeException(String.format("The command %s failed to execute", fullCommand), e);
582+ logger.error("The command {} was killed after 10 minutes", fullCommand);
583+ pw.flush();
584+ throw new CCMException(String.format("The command %s failed to execute", fullCommand), sw.toString(), e);
550585 } finally {
551586 try {
552587 closer.close();
@@ -554,6 +589,7 @@
554589 Throwables.propagate(e);
555590 }
556591 }
592+ return sw.toString();
557593 }
558594
559595 /**
@@ -622,8 +658,7 @@
622658 * use {@link #builder()} to get an instance
623659 */
624660 public static class Builder {
625- private static final AtomicInteger COUNTER = new AtomicInteger(0);
626- private final String clusterName = "test_" + COUNTER.incrementAndGet();
661+ private final String clusterName = TestUtils.generateIdentifier("cluster_");
627662 int[] nodes = {1};
628663 private boolean start = true;
629664 private boolean isDSE = isDSE();
@@ -636,6 +671,7 @@
636671 private int thriftPort = -1;
637672 private int binaryPort = -1;
638673 private int storagePort = -1;
674+ private Map<Integer, Workload> workloads = new HashMap<Integer, Workload>();
639675
640676 private Builder() {
641677 }
@@ -710,7 +746,7 @@
710746
711747 /**
712748 * Free-form options that will be added at the end of the {@code ccm create} command
713- * (defaults to {@link #getInstallArguments()} if this is never called).
749+ * (defaults to {@link #getInstallArguments()} if this is never called).
714750 */
715751 public Builder withCreateOptions(String... createOptions) {
716752 Collections.addAll(this.createOptions, createOptions);
@@ -758,6 +794,18 @@
758794 return this;
759795 }
760796
797+ /**
798+ * Sets the DSE workload for a given node.
799+ *
800+ * @param node The node to set the workload for (starting with 1).
801+ * @param workload The workload (e.g. solr, spark, hadoop)
802+ * @return This builder
803+ */
804+ public Builder withWorkload(int node, Workload workload) {
805+ this.workloads.put(node, workload);
806+ return this;
807+ }
808+
761809 public CCMBridge build() {
762810 // be careful NOT to alter internal state (hashCode/equals) during build!
763811 int storagePort = this.storagePort == -1 ? findAvailablePort() : this.storagePort;
@@ -781,6 +829,9 @@
781829 ccm.updateConfig(config);
782830 if (!dseConfiguration.isEmpty())
783831 ccm.updateDSEConfig(dseConfiguration);
832+ for (Map.Entry<Integer, Workload> entry : workloads.entrySet()) {
833+ ccm.setWorkload(entry.getKey(), entry.getValue());
834+ }
784835 if (start)
785836 ccm.start();
786837 return ccm;
@@ -886,8 +937,9 @@
886937 if (!Arrays.equals(nodes, builder.nodes)) return false;
887938 if (!createOptions.equals(builder.createOptions)) return false;
888939 if (!jvmArgs.equals(builder.jvmArgs)) return false;
889- if (!dseConfiguration.equals(builder.dseConfiguration)) return false;
890940 if (!cassandraConfiguration.equals(builder.cassandraConfiguration)) return false;
941+ if (!dseConfiguration.equals(builder.dseConfiguration)) return false;
942+ if (!workloads.equals(builder.workloads)) return false;
891943 return version.equals(builder.version);
892944 }
893945
@@ -901,6 +953,7 @@
901953 result = 31 * result + jvmArgs.hashCode();
902954 result = 31 * result + cassandraConfiguration.hashCode();
903955 result = 31 * result + dseConfiguration.hashCode();
956+ result = 31 * result + workloads.hashCode();
904957 result = 31 * result + thriftPort;
905958 result = 31 * result + binaryPort;
906959 result = 31 * result + storagePort;
modified driver-core/src/test/java/com/datastax/driver/core/CCMCache.java +6 −1
@@ -139,6 +139,11 @@
139139 ccm.updateDSEConfig(configs);
140140 }
141141
142+ @Override
143+ public String checkForErrors() {
144+ return ccm.checkForErrors();
145+ }
146+
142147 @Override
143148 public void start(int n) {
144149 ccm.start(n);
@@ -185,7 +190,7 @@
185190 }
186191
187192 @Override
188- public void setWorkload(int n, String workload) {
193+ public void setWorkload(int n, Workload workload) {
189194 ccm.setWorkload(n, workload);
190195 }
191196
modified driver-core/src/test/java/com/datastax/driver/core/CCMConfig.java +84 −22
@@ -34,7 +34,9 @@
3434
3535 /**
3636 * 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.
37+ * If not set, this defaults to {@code {1}}, i.e., one data center with one node.
38+ * <p/>
39+ * This attribute is ignored if {@link #ccmProvider()} is defined.
3840 *
3941 * @return The number of nodes to create, per data center.
4042 */
@@ -44,9 +46,11 @@
4446 * The C* or DSE version to use; defaults to the version defined by
4547 * the System property {@code cassandra.version}.
4648 * <p/>
47- * Note that setting this property completely
49+ * Note that setting this attribute completely
4850 * overrides the System properties {@code cassandra.version}
4951 * and {@code cassandra.directory}.
52+ * <p/>
53+ * This attribute is ignored if {@link #ccmProvider()} is defined.
5054 *
5155 * @return The C* or DSE version to use
5256 * @see CCMBridge#getCassandraVersion()
@@ -56,8 +60,10 @@
5660 /**
5761 * Whether to launch a DSE instance rather than an OSS C*.
5862 * <p/>
59- * Note that setting this property completely
63+ * Note that setting this attribute completely
6064 * overrides the System property {@code dse}.
65+ * <p/>
66+ * This attribute is ignored if {@link #ccmProvider()} is defined.
6167 *
6268 * @return {@code true} to launch a DSE instance, {@code false} to launch an OSS C* instance (default).
6369 */
@@ -66,6 +72,8 @@
6672 /**
6773 * Configuration items to add to cassandra.yaml configuration file.
6874 * Each configuration item must be in the form {@code key:value}.
75+ * <p/>
76+ * This attribute is ignored if {@link #ccmProvider()} is defined.
6977 *
7078 * @return Configuration items to add to cassandra.yaml configuration file.
7179 */
@@ -74,6 +82,8 @@
7482 /**
7583 * Configuration items to add to dse.yaml configuration file.
7684 * Each configuration item must be in the form {@code key:value}.
85+ * <p/>
86+ * This attribute is ignored if {@link #ccmProvider()} is defined.
7787 *
7888 * @return Configuration items to add to dse.yaml configuration file.
7989 */
@@ -83,6 +93,8 @@
8393 * JVM args to use when starting hosts.
8494 * System properties should be provided one by one, in the form
8595 * {@code -Dname=value}.
96+ * <p/>
97+ * This attribute is ignored if {@link #ccmProvider()} is defined.
8698 *
8799 * @return JVM args to use when starting hosts.
88100 */
@@ -90,6 +102,8 @@
90102
91103 /**
92104 * Free-form options that will be added at the end of the {@code ccm create} command.
105+ * <p/>
106+ * This attribute is ignored if {@link #ccmProvider()} is defined.
93107 *
94108 * @return Free-form options that will be added at the end of the {@code ccm create} command.
95109 */
@@ -97,6 +111,8 @@
97111
98112 /**
99113 * Whether to use SSL encryption.
114+ * <p/>
115+ * This attribute is ignored if {@link #ccmProvider()} is defined.
100116 *
101117 * @return {@code true} to use encryption, {@code false} to use unencrypted communication (default).
102118 */
@@ -104,11 +120,23 @@
104120
105121 /**
106122 * Whether to use authentication. Implies the use of SSL encryption.
123+ * <p/>
124+ * This attribute is ignored if {@link #ccmProvider()} is defined.
107125 *
108126 * @return {@code true} to use authentication, {@code false} to use unauthenticated communication (default).
109127 */
110128 boolean[] auth() default {};
111129
130+ /**
131+ * The workloads to assign to each node. If this attribute is defined,
132+ * the number of its elements must be lesser than or equal to the number of nodes in the cluster.
133+ * <p/>
134+ * This attribute is ignored if {@link #ccmProvider()} is defined.
135+ *
136+ * @return The workloads to assign to each node.
137+ */
138+ CCMAccess.Workload[] workloads() default {};
139+
112140 /**
113141 * Returns {@code true} if a {@link CCMBridge} instance should be automatically created, {@code false} otherwise.
114142 * <p/>
@@ -160,10 +188,10 @@
160188 * and this session will be used to create the test keyspace.
161189 * <p/>
162190 * The keyspace will be created once for the whole class if CCM test mode is {@link CreateCCM.TestMode#PER_CLASS},
163- * or once per test method, if the CCM test mode is {@link CreateCCM.TestMode#PER_METHOD},
191+ * or once per test method, if the CCM test mode is {@link CreateCCM.TestMode#PER_METHOD}.
164192 * <p/>
165193 * The test keyspace will be automatically populated upon creation with fixtures provided by
166- * {@link #fixturesProvider()} and {@link #fixturesProviderClass()}.
194+ * {@link #testInitializer()} and {@link #testInitializerClass()}.
167195 *
168196 * @return {@code true} if a test keyspace should be automatically created, {@code false} otherwise.
169197 */
@@ -183,12 +211,44 @@
183211 */
184212 boolean[] dirtiesContext() default {};
185213
214+ /**
215+ * Returns the name of the method that should be invoked to obtain
216+ * a {@link com.datastax.driver.core.CCMBridge.Builder} instance.
217+ * <p/>
218+ * This method should be declared in {@link #ccmProviderClass()},
219+ * or if that attribute is not set,
220+ * it will be looked up on the test class itself.
221+ * <p/>
222+ * The method should not have parameters. It can be static or not,
223+ * and have any visibility.
224+ * <p/>
225+ * By default, a {@link com.datastax.driver.core.CCMBridge.Builder} instance
226+ * is obtained by parsing other attributes of this annotation.
227+ *
228+ * @return The name of the method that should be invoked to obtain a
229+ * {@link com.datastax.driver.core.CCMBridge.Builder} instance.
230+ */
231+ String ccmProvider() default "";
232+
233+ /**
234+ * Returns the name of the class that should be invoked to obtain
235+ * a {@link com.datastax.driver.core.CCMBridge.Builder} instance.
236+ * <p/>
237+ * This class should contain a method named after {@link #ccmProvider()};
238+ * if this attribute is not set,
239+ * it will default to the test class itself.
240+ *
241+ * @return The name of the class that should be invoked to obtain a
242+ * {@link com.datastax.driver.core.CCMBridge.Builder} instance.
243+ */
244+ Class<?> ccmProviderClass() default Undefined.class;
245+
186246 /**
187247 * Returns the name of the method that should be invoked to obtain
188248 * a {@link com.datastax.driver.core.Cluster.Builder} instance.
189249 * <p/>
190250 * This method should be declared in {@link #clusterProviderClass()},
191- * or if that property is not set,
251+ * or if that attribute is not set,
192252 * it will be looked up on the test class itself.
193253 * <p/>
194254 * The method should not have parameters. It can be static or not,
@@ -206,7 +266,7 @@
206266 * a {@link com.datastax.driver.core.Cluster.Builder} instance.
207267 * <p/>
208268 * This class should contain a method named after {@link #clusterProvider()};
209- * if this property is not set,
269+ * if this attribute is not set,
210270 * it will default to the test class itself.
211271 *
212272 * @return The name of the class that should be invoked to obtain a
@@ -215,33 +275,35 @@
215275 Class<?> clusterProviderClass() default Undefined.class;
216276
217277 /**
218- * Returns the name of the method that should be invoked to obtain
219- * the test fixtures to use.
278+ * Returns the name of the method that should be invoked once the test context
279+ * is initialized.
220280 * <p/>
221- * This method should return {@code Collection<String>}.
222- * <p/>
223- * This method should be declared in {@link #fixturesProviderClass()},
224- * or if that property is not set,
281+ * This method should be declared in {@link #testInitializerClass()},
282+ * or if that attribute is not set,
225283 * it will be looked up on the test class itself.
226284 * <p/>
227285 * The method should not have parameters. It can be static or not,
228286 * and have any visibility.
287+ * <p/>
288+ * By default, the framework will look for a method named
289+ * {@code onTestContextInitialized}.
229290 *
230- * @return The name of the method that should be invoked to obtain the test fixtures to use.
291+ * @return The name of the method that should be invoked once the test context
292+ * is initialized.
231293 */
232- String fixturesProvider() default "";
294+ String testInitializer() default "";
233295
234296 /**
235- * Returns the name of the class that should be invoked to obtain
236- * the test fixtures to use.
297+ * Returns the name of the class that should be invoked once the test context
298+ * is initialized.
237299 * <p/>
238- * This class should contain a method named after {@link #fixturesProvider()};
239- * if this property is not set,
300+ * This class should contain a method named after {@link #testInitializer()};
301+ * if this attribute is not set,
240302 * it will default to the test class itself.
241303 *
242- * @return The name of the class that should be invoked to obtain a
243- * {@link com.datastax.driver.core.Cluster.Builder} instance.
304+ * @return The name of the class that should be invoked once the test context
305+ * is initialized.
244306 */
245- Class<?> fixturesProviderClass() default Undefined.class;
307+ Class<?> testInitializerClass() default Undefined.class;
246308
247309 }
added driver-core/src/test/java/com/datastax/driver/core/CCMException.java +36 −0
@@ -0,0 +1,36 @@
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+public class CCMException extends RuntimeException {
19+
20+ private final String out;
21+
22+ public CCMException(String message, String out) {
23+ super(message);
24+ this.out = out;
25+ }
26+
27+ public CCMException(String message, String out, Throwable cause) {
28+ super(message, cause);
29+ this.out = out;
30+ }
31+
32+ public String getOut() {
33+ return out;
34+ }
35+
36+}
modified driver-core/src/test/java/com/datastax/driver/core/CCMTestsSupport.java +275 −95
@@ -15,11 +15,14 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.datastax.driver.core.CCMAccess.Workload;
1819 import com.datastax.driver.core.CreateCCM.TestMode;
20+import com.datastax.driver.core.exceptions.InvalidQueryException;
1921 import com.google.common.base.Throwables;
2022 import com.google.common.collect.ImmutableMap;
2123 import com.google.common.collect.Lists;
2224 import com.google.common.io.Closer;
25+import com.google.common.util.concurrent.Uninterruptibles;
2326 import org.slf4j.Logger;
2427 import org.slf4j.LoggerFactory;
2528 import org.testng.ITestResult;
@@ -32,10 +35,12 @@
3235 import java.lang.reflect.Constructor;
3336 import java.lang.reflect.Method;
3437 import java.lang.reflect.Modifier;
35-import java.lang.reflect.ParameterizedType;
38+import java.net.InetAddress;
3639 import java.net.InetSocketAddress;
40+import java.net.UnknownHostException;
3741 import java.util.*;
3842 import java.util.concurrent.Callable;
43+import java.util.concurrent.TimeUnit;
3944 import java.util.concurrent.atomic.AtomicInteger;
4045
4146 import static com.datastax.driver.core.CreateCCM.TestMode.PER_CLASS;
@@ -59,12 +64,11 @@
5964 .put("enable_user_defined_functions", VersionNumber.parse("2.2.0"))
6065 .build();
6166
62-
63- private static class ReadOnlyCCMBridge implements CCMAccess {
67+ private static class ReadOnlyCCMAccess implements CCMAccess {
6468
6569 private final CCMAccess delegate;
6670
67- private ReadOnlyCCMBridge(CCMAccess delegate) {
71+ private ReadOnlyCCMAccess(CCMAccess delegate) {
6872 this.delegate = delegate;
6973 }
7074
@@ -123,6 +127,11 @@
123127 delegate.setKeepLogs(keepLogs);
124128 }
125129
130+ @Override
131+ public String checkForErrors() {
132+ return delegate.checkForErrors();
133+ }
134+
126135 @Override
127136 public void close() {
128137 throw new UnsupportedOperationException("This CCM cluster is read-only");
@@ -204,7 +213,7 @@
204213 }
205214
206215 @Override
207- public void setWorkload(int node, String workload) {
216+ public void setWorkload(int node, Workload workload) {
208217 throw new UnsupportedOperationException("This CCM cluster is read-only");
209218 }
210219
@@ -281,7 +290,7 @@
281290 @SuppressWarnings("SimplifiableIfStatement")
282291 private Map<String, Object> config() {
283292 Map<String, Object> config = new HashMap<String, Object>();
284- for (int i = annotations.size() - 1; i == 0; i--) {
293+ for (int i = annotations.size() - 1; i >= 0; i--) {
285294 CCMConfig ann = annotations.get(i);
286295 addConfigOptions(ann.config(), config);
287296 }
@@ -342,6 +351,22 @@
342351 return args;
343352 }
344353
354+ private List<Workload> workloads() {
355+ int total = 0;
356+ for (int perDc : numberOfNodes())
357+ total += perDc;
358+ List<Workload> workloads = new ArrayList<Workload>(Collections.<Workload>nCopies(total, null));
359+ for (int i = annotations.size() - 1; i >= 0; i--) {
360+ CCMConfig ann = annotations.get(i);
361+ Workload[] annWorkloads = ann.workloads();
362+ for (int j = 0; j < annWorkloads.length; j++) {
363+ Workload workload = annWorkloads[j];
364+ workloads.set(j, workload);
365+ }
366+ }
367+ return workloads;
368+ }
369+
345370 @SuppressWarnings("SimplifiableIfStatement")
346371 private boolean createCcm() {
347372 for (CCMConfig ann : annotations) {
@@ -387,34 +412,69 @@
387412 return false;
388413 }
389414
390- private CCMBridge.Builder ccmBuilder() {
415+ private CCMBridge.Builder ccmBuilder(Object testInstance) throws Exception {
391416 if (ccmBuilder == null) {
392- ccmBuilder = CCMBridge.builder().withNodes(numberOfNodes()).notStarted();
393- if (version() != null)
394- ccmBuilder.withVersion(version());
395- if (dse())
396- ccmBuilder.withDSE();
397- if (ssl())
398- ccmBuilder.withSSL();
399- if (auth())
400- ccmBuilder.withAuth();
401- for (Map.Entry<String, Object> entry : config().entrySet()) {
402- ccmBuilder.withCassandraConfiguration(entry.getKey(), entry.getValue());
403- }
404- for (Map.Entry<String, Object> entry : dseConfig().entrySet()) {
405- ccmBuilder.withDSEConfiguration(entry.getKey(), entry.getValue());
417+ ccmBuilder = ccmProvider(testInstance);
418+ if (ccmBuilder == null) {
419+ ccmBuilder = CCMBridge.builder().withNodes(numberOfNodes()).notStarted();
420+ if (version() != null)
421+ ccmBuilder.withVersion(version());
422+ if (dse())
423+ ccmBuilder.withDSE();
424+ if (ssl())
425+ ccmBuilder.withSSL();
426+ if (auth())
427+ ccmBuilder.withAuth();
428+ for (Map.Entry<String, Object> entry : config().entrySet()) {
429+ ccmBuilder.withCassandraConfiguration(entry.getKey(), entry.getValue());
430+ }
431+ for (Map.Entry<String, Object> entry : dseConfig().entrySet()) {
432+ ccmBuilder.withDSEConfiguration(entry.getKey(), entry.getValue());
433+ }
434+ for (String option : startOptions()) {
435+ ccmBuilder.withCreateOptions(option);
436+ }
437+ for (String arg : jvmArgs()) {
438+ ccmBuilder.withJvmArgs(arg);
439+ }
440+ List<Workload> workloads = workloads();
441+ for (int i = 0; i < workloads.size(); i++) {
442+ Workload workload = workloads.get(i);
443+ if (workload != null)
444+ ccmBuilder.withWorkload(i + 1, workload);
445+ }
406446 }
407- for (String option : startOptions()) {
408- ccmBuilder.withCreateOptions(option);
447+ }
448+ return ccmBuilder;
449+ }
450+
451+ private CCMBridge.Builder ccmProvider(Object testInstance) throws Exception {
452+ String methodName = null;
453+ Class<?> clazz = null;
454+ for (int i = annotations.size() - 1; i >= 0; i--) {
455+ CCMConfig ann = annotations.get(i);
456+ if (!ann.ccmProvider().isEmpty()) {
457+ methodName = ann.ccmProvider();
409458 }
410- for (String arg : jvmArgs()) {
411- ccmBuilder.withJvmArgs(arg);
459+ if (!ann.ccmProviderClass().equals(CCMConfig.Undefined.class)) {
460+ clazz = ann.ccmProviderClass();
412461 }
413462 }
414- return ccmBuilder;
463+ if (methodName == null)
464+ return null;
465+ if (clazz == null)
466+ clazz = testInstance.getClass();
467+ Method method = locateMethod(methodName, clazz);
468+ assert CCMBridge.Builder.class.isAssignableFrom(method.getReturnType());
469+ if (Modifier.isStatic(method.getModifiers())) {
470+ return (CCMBridge.Builder) method.invoke(null);
471+ } else {
472+ Object receiver = testInstance.getClass().equals(clazz) ? testInstance : instantiate(clazz);
473+ return (CCMBridge.Builder) method.invoke(receiver);
474+ }
415475 }
416476
417- private Cluster.Builder clusterBuilder(Object testInstance) throws Exception {
477+ private Cluster.Builder clusterProvider(Object testInstance) throws Exception {
418478 String methodName = null;
419479 Class<?> clazz = null;
420480 for (int i = annotations.size() - 1; i >= 0; i--) {
@@ -441,31 +501,28 @@
441501 }
442502
443503 @SuppressWarnings("unchecked")
444- private Collection<String> fixtures(Object testInstance) throws Exception {
504+ private void invokeInitTest(Object testInstance) throws Exception {
445505 String methodName = null;
446506 Class<?> clazz = null;
447507 for (int i = annotations.size() - 1; i >= 0; i--) {
448508 CCMConfig ann = annotations.get(i);
449- if (!ann.fixturesProvider().isEmpty()) {
450- methodName = ann.fixturesProvider();
509+ if (!ann.testInitializer().isEmpty()) {
510+ methodName = ann.testInitializer();
451511 }
452- if (!ann.fixturesProviderClass().equals(CCMConfig.Undefined.class)) {
453- clazz = ann.fixturesProviderClass();
512+ if (!ann.testInitializerClass().equals(CCMConfig.Undefined.class)) {
513+ clazz = ann.testInitializerClass();
454514 }
455515 }
456516 if (methodName == null)
457- methodName = "createTestFixtures";
517+ methodName = "onTestContextInitialized";
458518 if (clazz == null)
459519 clazz = testInstance.getClass();
460520 Method method = locateMethod(methodName, clazz);
461- assert Collection.class.isAssignableFrom(method.getReturnType());
462- assert method.getGenericReturnType() instanceof ParameterizedType;
463- assert String.class.equals(((ParameterizedType) method.getGenericReturnType()).getActualTypeArguments()[0]);
464521 if (Modifier.isStatic(method.getModifiers())) {
465- return (Collection<String>) method.invoke(null);
522+ method.invoke(null);
466523 } else {
467524 Object receiver = testInstance.getClass().equals(clazz) ? testInstance : instantiate(clazz);
468- return (Collection<String>) method.invoke(receiver);
525+ method.invoke(receiver);
469526 }
470527 }
471528
@@ -473,13 +530,15 @@
473530
474531 private TestMode testMode;
475532
476- private CCMTestConfig ccmTestConfig;
533+ protected CCMTestConfig ccmTestConfig;
534+
535+ private CCMAccess ccm;
477536
478- protected CCMAccess ccm;
537+ private CCMBridge.Builder ccmBuilder;
479538
480- protected Cluster cluster;
539+ private Cluster cluster;
481540
482- protected Session session;
541+ private Session session;
483542
484543 protected String keyspace;
485544
@@ -508,11 +567,18 @@
508567 testMode = determineTestMode(testInstance.getClass());
509568 if (testMode == PER_CLASS) {
510569 closer = Closer.create();
511- initTestContext(testInstance, null);
512- initTestCluster(testInstance);
513- initTestSession();
514- initTestKeyspace();
515- initTestFixtures(testInstance);
570+ try {
571+ initTestContext(testInstance, null);
572+ initTestCluster(testInstance);
573+ initTestSession();
574+ initTestKeyspace();
575+ initTest(testInstance);
576+ } catch (Exception e) {
577+ LOGGER.error(e.getMessage(), e);
578+ errorOut();
579+ fail(e.getMessage());
580+
581+ }
516582 }
517583 }
518584
@@ -538,11 +604,17 @@
538604 if (closer == null)
539605 closer = Closer.create();
540606 if (testMode == PER_METHOD || erroredOut) {
541- initTestContext(testInstance, testMethod);
542- initTestCluster(testInstance);
543- initTestSession();
544- initTestKeyspace();
545- initTestFixtures(testInstance);
607+ try {
608+ initTestContext(testInstance, testMethod);
609+ initTestCluster(testInstance);
610+ initTestSession();
611+ initTestKeyspace();
612+ initTest(testInstance);
613+ } catch (Exception e) {
614+ LOGGER.error(e.getMessage(), e);
615+ errorOut();
616+ fail(e.getMessage());
617+ }
546618 }
547619 assert ccmTestConfig != null;
548620 assert !ccmTestConfig.createCcm() || ccm != null;
@@ -553,7 +625,7 @@
553625 * Hook executed after each test method.
554626 */
555627 @AfterMethod(groups = {"isolated", "short", "long", "stress", "duration"}, alwaysRun = true)
556- public void afterTestMethod(ITestResult tr) {
628+ public void afterTestMethod(ITestResult tr) throws Exception {
557629 if (isCcmEnabled(tr.getMethod().getConstructorOrMethod().getMethod())) {
558630 if (tr.getStatus() == ITestResult.FAILURE) {
559631 errorOut();
@@ -571,7 +643,7 @@
571643 * Hook executed after each test class.
572644 */
573645 @AfterClass(groups = {"isolated", "short", "long", "stress", "duration"}, alwaysRun = true)
574- public void afterTestClass() {
646+ public void afterTestClass() throws Exception {
575647 if (testMode == PER_CLASS) {
576648 closeCloseables();
577649 closeTestCluster();
@@ -607,20 +679,85 @@
607679 }
608680
609681 /**
610- * The CQL statements to execute before the tests in this class.
611- * Useful to create tables or other objects inside the test keyspace,
612- * or to insert test data.
682+ * Hook invoked when the test context is ready, but before the test itself.
683+ * Useful to create fixtures or to insert test data.
684+ * <p/>
685+ * This method is invoked once per class is the {@link TestMode} is {@link TestMode#PER_CLASS}
686+ * or before each test method, if the {@link TestMode} is {@link TestMode#PER_METHOD}.
687+ * <p/>
688+ * When this method is called, the cluster and the session are ready
689+ * to be used (unless the configuration specifies that such objects
690+ * should not be created).
691+ * <p/>
692+ * Statements executed inside this method do not need to be qualified with a keyspace name,
693+ * in which case they are executed with the default keyspace for the test
694+ * (unless the configuration specifies that no keyspace should be creaed for the test).
695+ * <p/>
696+ * The default implementation does nothing (no fixtures required).
697+ */
698+ public void onTestContextInitialized() {
699+ // nothing to do by default
700+ }
701+
702+ /**
703+ * @return The {@link CCMAccess} instance to use with this test.
704+ */
705+ public CCMAccess ccm() {
706+ return ccm;
707+ }
708+
709+ /**
710+ * @return The {@link Cluster} instance to use with this test.
711+ * Can be null if CCM configuration specifies {@code createCluster = false}.
712+ */
713+ public Cluster cluster() {
714+ return cluster;
715+ }
716+
717+ /**
718+ * @return The {@link Session} instance to use with this test.
719+ * Can be null if CCM configuration specifies {@code createSession = false}.
720+ */
721+ public Session session() {
722+ return session;
723+ }
724+
725+ /**
726+ * Executes the given statements with the test's session object.
613727 * <p/>
614- * Statements do not need to be qualified with keyspace name.
728+ * Useful to create test fixtures and/or load data before tests.
615729 * <p/>
616- * The default implementation returns an empty list (no fixtures required).
730+ * This method should not be called if a session object hasn't been created
731+ * (if CCM configuration specifies {@code createSession = false})
617732 *
618- * @return The DDL statements to execute before the tests.
733+ * @param statements The statements to execute.
619734 */
620- public Collection<String> createTestFixtures() {
621- return Collections.emptyList();
735+ public void execute(String... statements) {
736+ execute(Arrays.asList(statements));
622737 }
623738
739+ /**
740+ * Executes the given statements with the test's session object.
741+ * <p/>
742+ * Useful to create test fixtures and/or load data before tests.
743+ * <p/>
744+ * This method should not be called if a session object hasn't been created
745+ * (if CCM configuration specifies {@code createSession = false})
746+ *
747+ * @param statements The statements to execute.
748+ */
749+ public void execute(Collection<String> statements) {
750+ assert session != null;
751+ for (String stmt : statements) {
752+ try {
753+ session.execute(stmt);
754+ } catch (Exception e) {
755+ errorOut();
756+ LOGGER.error("Could not execute statement: " + stmt, e);
757+ Throwables.propagate(e);
758+ }
759+ }
760+ }
624761 /**
625762 * Signals that the test has encountered an unexpected error.
626763 * <p/>
@@ -635,8 +772,40 @@
635772 */
636773 public void errorOut() {
637774 erroredOut = true;
638- if (ccm != null)
775+ if (ccm != null) {
639776 ccm.setKeepLogs(true);
777+ }
778+ }
779+
780+ /**
781+ * Returns the contact points to use to contact the CCM cluster.
782+ * <p/>
783+ * This method returns as many contact points as the number of nodes initially present in the CCM cluster,
784+ * according to {@link CCMConfig} annotations.
785+ * <p/>
786+ * On a multi-DC setup, this will include nodes in all data centers.
787+ * <p/>
788+ * This method should not be called before the test has started, nor after the test is finished.
789+ *
790+ * @return the contact points to use to contact the CCM cluster.
791+ */
792+ public List<InetAddress> getContactPoints() {
793+ assert ccmTestConfig != null;
794+ List<InetAddress> contactPoints = new ArrayList<InetAddress>();
795+ int n = 1;
796+ int[] numberOfNodes = ccmTestConfig.numberOfNodes();
797+ for (int dc = 1; dc <= numberOfNodes.length; dc++) {
798+ int nodesInDc = numberOfNodes[dc - 1];
799+ for (int i = 0; i < nodesInDc; i++) {
800+ try {
801+ contactPoints.add(InetAddress.getByName(ipOfNode(n)));
802+ } catch (UnknownHostException e) {
803+ Throwables.propagate(e);
804+ }
805+ n++;
806+ }
807+ }
808+ return contactPoints;
640809 }
641810
642811 /**
@@ -651,7 +820,7 @@
651820 *
652821 * @return the contact points to use to contact the CCM cluster.
653822 */
654- public List<InetSocketAddress> getInitialContactPoints() {
823+ public List<InetSocketAddress> getContactPointsWithPorts() {
655824 assert ccmTestConfig != null;
656825 List<InetSocketAddress> contactPoints = new ArrayList<InetSocketAddress>();
657826 int n = 1;
@@ -679,52 +848,73 @@
679848 return closeable;
680849 }
681850
682- private void initTestContext(Object testInstance, Method testMethod) throws Exception {
851+ /**
852+ * Tests fail randomly with InvalidQueryException: Keyspace 'xxx' does not exist;
853+ * this method tries at most 3 times to issue a successful USE statement.
854+ *
855+ * @param ks The keyspace to use
856+ */
857+ public void useKeyspace(String ks) {
858+ final int maxTries = 3;
859+ for (int i = 1; i <= maxTries; i++) {
860+ try {
861+ session.execute("USE " + ks);
862+ } catch (InvalidQueryException e) {
863+ if (i == maxTries)
864+ throw e;
865+ LOGGER.error("Could not USE keyspace, retrying");
866+ Uninterruptibles.sleepUninterruptibly(1, TimeUnit.MINUTES);
867+ }
868+ }
869+ }
870+
871+ protected void initTestContext(Object testInstance, Method testMethod) throws Exception {
683872 erroredOut = false;
684873 ccmTestConfig = createCCMTestConfig(testInstance, testMethod);
685874 assert ccmTestConfig != null;
686875 if (ccmTestConfig.createCcm()) {
687- CCMAccess ccm = CCMCache.get(ccmTestConfig.ccmBuilder());
876+ ccmBuilder = ccmTestConfig.ccmBuilder(testInstance);
877+ CCMAccess ccm = CCMCache.get(ccmBuilder);
688878 assert ccm != null;
689879 if (ccmTestConfig.dirtiesContext()) {
690880 this.ccm = ccm;
691881 } else {
692- this.ccm = new ReadOnlyCCMBridge(ccm);
882+ this.ccm = new ReadOnlyCCMAccess(ccm);
693883 }
694884 try {
695885 ccm.start();
696- } catch (RuntimeException e) {
697- LOGGER.error("Could not start " + ccm, e);
886+ } catch (CCMException e) {
887+ errorOut();
698888 fail(e.getMessage());
699889 }
700890 LOGGER.debug("Using {}", ccm);
701891 }
702892 }
703893
704- private void initTestCluster(Object testInstance) throws Exception {
894+ protected void initTestCluster(Object testInstance) throws Exception {
705895 if (ccmTestConfig.createCcm() && ccmTestConfig.createCluster()) {
706- Cluster.Builder builder = ccmTestConfig.clusterBuilder(testInstance);
896+ Cluster.Builder builder = ccmTestConfig.clusterProvider(testInstance);
707897 // add contact points only if the provided builder didn't do so
708898 if (builder.getContactPoints().isEmpty())
709- builder.addContactPointsWithPorts(getInitialContactPoints());
899+ builder.addContactPoints(getContactPoints());
710900 builder.withPort(ccm.getBinaryPort());
711901 cluster = register(builder.build());
712902 cluster.init();
713903 }
714904 }
715905
716- private void initTestSession() throws Exception {
906+ protected void initTestSession() throws Exception {
717907 if (ccmTestConfig.createCcm() && ccmTestConfig.createCluster() && ccmTestConfig.createSession())
718908 session = register(cluster.connect());
719909 }
720910
721- private void initTestKeyspace() {
911+ protected void initTestKeyspace() {
722912 if (ccmTestConfig.createCcm() && ccmTestConfig.createCluster() && ccmTestConfig.createSession() && ccmTestConfig.createKeyspace()) {
723913 try {
724- keyspace = TestUtils.getAvailableKeyspaceName();
914+ keyspace = TestUtils.generateIdentifier("ks_");
725915 LOGGER.debug("Using keyspace " + keyspace);
726916 session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, 1));
727- session.execute("USE " + keyspace);
917+ useKeyspace(keyspace);
728918 } catch (Exception e) {
729919 errorOut();
730920 LOGGER.error("Could not create test keyspace", e);
@@ -733,35 +923,25 @@
733923 }
734924 }
735925
736- private void initTestFixtures(Object testInstance) throws Exception {
737- if (ccmTestConfig.createCcm() && ccmTestConfig.createCluster() && ccmTestConfig.createSession()) {
738- for (String stmt : ccmTestConfig.fixtures(testInstance)) {
739- try {
740- session.execute(stmt);
741- } catch (Exception e) {
742- errorOut();
743- LOGGER.error("Could not execute statement: " + stmt, e);
744- Throwables.propagate(e);
745- }
746- }
747- }
926+ protected void initTest(Object testInstance) throws Exception {
927+ ccmTestConfig.invokeInitTest(testInstance);
748928 }
749929
750- private void closeTestContext() {
751- if (ccmTestConfig != null && ccm != null) {
752- CCMBridge.Builder key = ccmTestConfig.ccmBuilder();
930+ protected void closeTestContext() throws Exception {
931+ if (ccmTestConfig != null && ccmBuilder != null && ccm != null) {
753932 if (ccmTestConfig.dirtiesContext()) {
754- CCMCache.remove(key);
933+ CCMCache.remove(ccmBuilder);
755934 ccm.close();
756935 } else {
757- ((ReadOnlyCCMBridge) ccm).delegate.close();
936+ ((ReadOnlyCCMAccess) ccm).delegate.close();
758937 }
759938 }
760939 ccmTestConfig = null;
940+ ccmBuilder = null;
761941 ccm = null;
762942 }
763943
764- private void closeTestCluster() {
944+ protected void closeTestCluster() {
765945 if (cluster != null && !cluster.isClosed())
766946 executeNoFail(new Runnable() {
767947 @Override
@@ -774,7 +954,7 @@
774954 keyspace = null;
775955 }
776956
777- private void closeCloseables() {
957+ protected void closeCloseables() {
778958 if (closer != null)
779959 executeNoFail(new Callable<Void>() {
780960 @Override
modified driver-core/src/test/java/com/datastax/driver/core/CaseSensitivityTest.java +4 −4
@@ -26,7 +26,7 @@
2626 @Test(groups = "short")
2727 public void testCaseInsensitiveKeyspace() throws Throwable {
2828 String ksName = "MyKeyspace1";
29- session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, ksName, 1));
29+ session().execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, ksName, 1));
3030 assertExists(ksName, "mykeyspace1");
3131 assertExists("mykeyspace1", "mykeyspace1");
3232 assertExists("MYKEYSPACE1", "mykeyspace1");
@@ -35,7 +35,7 @@
3535 @Test(groups = "short")
3636 public void testCaseSensitiveKeyspace() throws Throwable {
3737 String ksName = "\"MyKeyspace2\"";
38- session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, ksName, 1));
38+ session().execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, ksName, 1));
3939 assertExists(ksName, "MyKeyspace2");
4040 assertExists(Metadata.quote("MyKeyspace2"), "MyKeyspace2");
4141 assertNotExists("mykeyspace2");
@@ -44,13 +44,13 @@
4444 }
4545
4646 private void assertExists(String fetchName, String realName) {
47- KeyspaceMetadata km = cluster.getMetadata().getKeyspace(fetchName);
47+ KeyspaceMetadata km = cluster().getMetadata().getKeyspace(fetchName);
4848 assertNotNull(km);
4949 assertEquals(realName, km.getName());
5050 }
5151
5252 private void assertNotExists(String name) {
53- assertNull(cluster.getMetadata().getKeyspace(name));
53+ assertNull(cluster().getMetadata().getKeyspace(name));
5454 }
5555
5656
modified driver-core/src/test/java/com/datastax/driver/core/ClusterDelegateTest.java +1 −1
@@ -23,7 +23,7 @@
2323
2424 @Test(groups = "short")
2525 public void should_allow_subclass_to_delegate_to_other_instance() {
26- SimpleDelegatingCluster delegatingCluster = new SimpleDelegatingCluster(cluster);
26+ SimpleDelegatingCluster delegatingCluster = new SimpleDelegatingCluster(cluster());
2727
2828 ResultSet rs = delegatingCluster.connect().execute("select * from system.local");
2929
modified driver-core/src/test/java/com/datastax/driver/core/ClusterStressTest.java +7 −5
@@ -172,7 +172,9 @@
172172
173173 CreateClusterAndCheckConnections(CountDownLatch startSignal) {
174174 this.startSignal = startSignal;
175- this.cluster = Cluster.builder().addContactPointsWithPorts(getInitialContactPoints())
175+ this.cluster = Cluster.builder()
176+ .addContactPoints(getContactPoints())
177+ .withPort(ccm().getBinaryPort())
176178 .withPoolingOptions(new PoolingOptions().setCoreConnectionsPerHost(HostDistance.LOCAL, 1))
177179 .withNettyOptions(channelMonitor.nettyOptions()).build();
178180 }
@@ -186,19 +188,19 @@
186188 cluster.init();
187189 assertEquals(cluster.manager.sessions.size(), 0);
188190 assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1);
189- assertEquals(channelMonitor.openChannels(getInitialContactPoints()).size(), 1);
191+ assertEquals(channelMonitor.openChannels(getContactPointsWithPorts()).size(), 1);
190192
191193 // The first session initializes the cluster and its control connection
192194 Session session = cluster.connect();
193195 assertEquals(cluster.manager.sessions.size(), 1);
194196 assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1 + TestUtils.numberOfLocalCoreConnections(cluster));
195- assertEquals(channelMonitor.openChannels(getInitialContactPoints()).size(), 1 + TestUtils.numberOfLocalCoreConnections(cluster));
197+ assertEquals(channelMonitor.openChannels(getContactPointsWithPorts()).size(), 1 + TestUtils.numberOfLocalCoreConnections(cluster));
196198
197199 // Closing the session keeps the control connection opened
198200 session.close();
199201 assertEquals(cluster.manager.sessions.size(), 0);
200202 assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1);
201- assertEquals(channelMonitor.openChannels(getInitialContactPoints()).size(), 1);
203+ assertEquals(channelMonitor.openChannels(getContactPointsWithPorts()).size(), 1);
202204
203205 return this;
204206 } catch (AssertionError e) {
@@ -230,7 +232,7 @@
230232 try {
231233 cluster.close();
232234 assertEquals(cluster.manager.sessions.size(), 0);
233- assertEquals(channelMonitor.openChannels(getInitialContactPoints()).size(), 0);
235+ assertEquals(channelMonitor.openChannels(getContactPointsWithPorts()).size(), 0);
234236 } finally {
235237 channelMonitor.stop();
236238 cluster = null;
modified driver-core/src/test/java/com/datastax/driver/core/ConditionChecker.java +78 −57
@@ -23,83 +23,106 @@
2323 import java.util.Timer;
2424 import java.util.TimerTask;
2525 import java.util.concurrent.Callable;
26+import java.util.concurrent.TimeUnit;
2627 import java.util.concurrent.locks.Condition;
2728 import java.util.concurrent.locks.Lock;
2829 import java.util.concurrent.locks.ReentrantLock;
2930
30-import static com.google.common.base.Preconditions.checkState;
31-import static java.util.concurrent.TimeUnit.MILLISECONDS;
3231 import static org.assertj.core.api.Fail.fail;
3332
3433 public class ConditionChecker {
3534
36- private static final Logger logger = LoggerFactory.getLogger(ConditionChecker.class);
37-
3835 private static final int DEFAULT_PERIOD_MILLIS = 500;
3936
40- public static <T> void awaitUntil(T input, Predicate<? super T> predicate, long timeoutMillis) {
41- new ConditionChecker(input, predicate).await(timeoutMillis);
42- }
37+ private static final int DEFAULT_TIMEOUT_MILLIS = 60000;
4338
44- public static void awaitUntil(final Callable<Boolean> condition, long timeoutMillis) {
45- new ConditionChecker(condition).await(timeoutMillis);
46- }
39+ public static class ConditionCheckerBuilder {
4740
48- public static <T> void awaitWhile(T input, Predicate<? super T> predicate, long timeoutMillis) {
49- new ConditionChecker(input, Predicates.not(predicate)).await(timeoutMillis);
50- }
41+ private long timeout = DEFAULT_TIMEOUT_MILLIS;
5142
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- }
43+ private TimeUnit timeoutUnit = TimeUnit.MILLISECONDS;
6044
61- private final Object input;
45+ private long period = DEFAULT_PERIOD_MILLIS;
6246
63- private final Predicate<Object> predicate;
47+ private TimeUnit periodUnit = TimeUnit.MILLISECONDS;
6448
65- private final Lock lock;
49+ private Object input;
6650
67- private final Condition condition;
51+ private Predicate<?> predicate;
6852
69- private final Timer timer;
53+ public ConditionCheckerBuilder every(long period, TimeUnit unit) {
54+ this.period = period;
55+ periodUnit = unit;
56+ return this;
57+ }
7058
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- }
59+ public ConditionCheckerBuilder every(long periodMillis) {
60+ period = periodMillis;
61+ periodUnit = TimeUnit.MILLISECONDS;
62+ return this;
63+ }
7864
79- public ConditionChecker(Callable<Boolean> condition) {
80- this(condition, DEFAULT_PERIOD_MILLIS);
81- }
65+ public ConditionCheckerBuilder before(long timeout, TimeUnit unit) {
66+ this.timeout = timeout;
67+ timeoutUnit = unit;
68+ return this;
69+ }
8270
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;
71+ public ConditionCheckerBuilder before(long timeoutMillis) {
72+ timeout = timeoutMillis;
73+ timeoutUnit = TimeUnit.MILLISECONDS;
74+ return this;
75+ }
76+
77+ public <T> ConditionCheckerBuilder that(T input, Predicate<? super T> predicate) {
78+ this.input = input;
79+ this.predicate = predicate;
80+ return this;
81+ }
82+
83+ public ConditionCheckerBuilder that(final Callable<Boolean> condition) {
84+ this.input = null;
85+ this.predicate = new Predicate<Void>() {
86+ @Override
87+ public boolean apply(Void input) {
88+ try {
89+ return condition.call();
90+ } catch (Exception e) {
91+ logger.error("Evaluation of condition threw exception", e);
92+ return false;
93+ }
9294 }
93- }
94- }, periodMillis);
95+ };
96+ return this;
97+ }
98+
99+ @SuppressWarnings("unchecked")
100+ public void becomesTrue() {
101+ new ConditionChecker(input, (Predicate<Object>) predicate, period, periodUnit).await(timeout, timeoutUnit);
102+ }
103+
104+ @SuppressWarnings("unchecked")
105+ public void becomesFalse() {
106+ this.predicate = Predicates.not(predicate);
107+ new ConditionChecker(input, (Predicate<Object>) predicate, period, periodUnit).await(timeout, timeoutUnit);
108+ }
109+
95110 }
96111
97- public <T> ConditionChecker(T input, Predicate<? super T> predicate) {
98- this(input, predicate, DEFAULT_PERIOD_MILLIS);
112+ private static final Logger logger = LoggerFactory.getLogger(ConditionChecker.class);
113+
114+ public static ConditionCheckerBuilder check() {
115+ return new ConditionCheckerBuilder();
99116 }
100117
118+ private final Object input;
119+ private final Predicate<Object> predicate;
120+ private final Lock lock;
121+ private final Condition condition;
122+ private final Timer timer;
123+
101124 @SuppressWarnings("unchecked")
102- public <T> ConditionChecker(T input, Predicate<? super T> predicate, int periodMillis) {
125+ public <T> ConditionChecker(T input, Predicate<? super T> predicate, long period, TimeUnit periodUnit) {
103126 this.input = input;
104127 this.predicate = (Predicate<Object>) predicate;
105128 lock = new ReentrantLock();
@@ -110,23 +133,21 @@
110133 public void run() {
111134 checkCondition();
112135 }
113- }, 0, periodMillis);
136+ }, 0, periodUnit.toMillis(period));
114137 }
115138
116139 /**
117140 * Waits until the predicate becomes true,
118141 * or a timeout occurs, whichever happens first.
119- *
120- * @param timeoutMillis timeout in milliseconds
121142 */
122- public void await(long timeoutMillis) {
143+ public void await(long timeout, TimeUnit unit) {
123144 boolean interrupted = false;
124- long nanos = MILLISECONDS.toNanos(timeoutMillis);
145+ long nanos = unit.toNanos(timeout);
125146 lock.lock();
126147 try {
127148 while (!evalCondition()) {
128149 if (nanos <= 0L)
129- fail(String.format("Timeout after %s milliseconds while waiting for condition", timeoutMillis));
150+ fail(String.format("Timeout after %s %s while waiting for condition", timeout, unit.toString().toLowerCase()));
130151 try {
131152 nanos = condition.awaitNanos(nanos);
132153 } catch (InterruptedException e) {
@@ -151,7 +172,7 @@
151172 }
152173 }
153174
154- protected boolean evalCondition() {
175+ private boolean evalCondition() {
155176 return predicate.apply(input);
156177 }
157178
modified driver-core/src/test/java/com/datastax/driver/core/ConditionalUpdateTest.java +24 −27
@@ -18,9 +18,6 @@
1818 import com.datastax.driver.core.utils.CassandraVersion;
1919 import org.testng.annotations.Test;
2020
21-import java.util.Collection;
22-import java.util.Collections;
23-
2421 import static org.testng.Assert.assertFalse;
2522 import static org.testng.Assert.assertTrue;
2623
@@ -31,55 +28,55 @@
3128 public class ConditionalUpdateTest extends CCMTestsSupport {
3229
3330 @Override
34- public Collection<String> createTestFixtures() {
35- return Collections.singletonList("CREATE TABLE test(k1 int, k2 int, v int, PRIMARY KEY (k1, k2))");
31+ public void onTestContextInitialized() {
32+ execute("CREATE TABLE test(k1 int, k2 int, v int, PRIMARY KEY (k1, k2))");
3633 }
3734
3835 @Test(groups = "short")
3936 public void singleUpdateTest() {
40- session.execute("TRUNCATE test");
41- session.execute("INSERT INTO test (k1, k2, v) VALUES (1, 1, 1)");
37+ session().execute("TRUNCATE test");
38+ session().execute("INSERT INTO test (k1, k2, v) VALUES (1, 1, 1)");
4239
43- ResultSet rs = session.execute("UPDATE test SET v = 3 WHERE k1 = 1 AND k2 = 1 IF v = 2");
40+ ResultSet rs = session().execute("UPDATE test SET v = 3 WHERE k1 = 1 AND k2 = 1 IF v = 2");
4441 assertFalse(rs.wasApplied());
4542 // Ensure that reading the status does not consume a row:
4643 assertFalse(rs.isExhausted());
4744
48- rs = session.execute("UPDATE test SET v = 3 WHERE k1 = 1 AND k2 = 1 IF v = 1");
45+ rs = session().execute("UPDATE test SET v = 3 WHERE k1 = 1 AND k2 = 1 IF v = 1");
4946 assertTrue(rs.wasApplied());
5047 assertFalse(rs.isExhausted());
5148
5249 // Non-conditional statement
53- rs = session.execute("UPDATE test SET v = 4 WHERE k1 = 1 AND k2 = 1");
50+ rs = session().execute("UPDATE test SET v = 4 WHERE k1 = 1 AND k2 = 1");
5451 assertTrue(rs.wasApplied());
5552 }
5653
5754 @Test(groups = "short")
5855 public void batchUpdateTest() {
59- session.execute("TRUNCATE test");
60- session.execute("INSERT INTO test (k1, k2, v) VALUES (1, 1, 1)");
61- session.execute("INSERT INTO test (k1, k2, v) VALUES (1, 2, 1)");
62-
63- PreparedStatement ps = session.prepare("UPDATE test SET v = :new WHERE k1 = :k1 AND k2 = :k2 IF v = :old");
56+ session().execute("TRUNCATE test");
57+ session().execute("INSERT INTO test (k1, k2, v) VALUES (1, 1, 1)");
58+ session().execute("INSERT INTO test (k1, k2, v) VALUES (1, 2, 1)");
59+
60+ PreparedStatement ps = session().prepare("UPDATE test SET v = :new WHERE k1 = :k1 AND k2 = :k2 IF v = :old");
6461 BatchStatement batch = new BatchStatement();
6562 batch.add(ps.bind().setInt("k1", 1).setInt("k2", 1).setInt("old", 2).setInt("new", 3)); // will fail
6663 batch.add(ps.bind().setInt("k1", 1).setInt("k2", 2).setInt("old", 1).setInt("new", 3));
6764
6865
69- ResultSet rs = session.execute(batch);
66+ ResultSet rs = session().execute(batch);
7067 assertFalse(rs.wasApplied());
7168 }
7269
7370
7471 @Test(groups = "short")
7572 public void multipageResultSetTest() {
76- session.execute("TRUNCATE test");
77- session.execute("INSERT INTO test (k1, k2, v) VALUES (1, 1, 1)");
78- session.execute("INSERT INTO test (k1, k2, v) VALUES (1, 2, 1)");
73+ session().execute("TRUNCATE test");
74+ session().execute("INSERT INTO test (k1, k2, v) VALUES (1, 1, 1)");
75+ session().execute("INSERT INTO test (k1, k2, v) VALUES (1, 2, 1)");
7976
8077 // This is really contrived, we just want to cover the code path in ArrayBackedResultSet#MultiPage.
8178 // Currently CAS update results are never multipage, so it's hard to come up with a meaningful example.
82- ResultSet rs = session.execute(new SimpleStatement("SELECT * FROM test WHERE k1 = 1").setFetchSize(1));
79+ ResultSet rs = session().execute(new SimpleStatement("SELECT * FROM test WHERE k1 = 1").setFetchSize(1));
8380
8481 assertTrue(rs.wasApplied());
8582 }
@@ -95,13 +92,13 @@
9592 @Test(groups = "short")
9693 public void insert_if_not_exist_should_support_wasApplied_boolean() {
9794 // First, make sure the test table and the row exist
98- session.execute("CREATE TABLE IF NOT EXISTS Java358 (key int primary key, value int)");
95+ session().execute("CREATE TABLE IF NOT EXISTS Java358 (key int primary key, value int)");
9996 ResultSet rs;
100- rs = session.execute("INSERT INTO Java358(key, value) VALUES (42, 42) IF NOT EXISTS");
97+ rs = session().execute("INSERT INTO Java358(key, value) VALUES (42, 42) IF NOT EXISTS");
10198 assertTrue(rs.wasApplied());
10299
103100 // Then, make sure the flag reports correctly that we did not create a new row
104- rs = session.execute("INSERT INTO Java358(key, value) VALUES (42, 42) IF NOT EXISTS");
101+ rs = session().execute("INSERT INTO Java358(key, value) VALUES (42, 42) IF NOT EXISTS");
105102 assertFalse(rs.wasApplied());
106103 }
107104
@@ -116,16 +113,16 @@
116113 @Test(groups = "short")
117114 public void delete_if_not_exist_should_support_wasApplied_boolean() {
118115 // First, make sure the test table and the row exist
119- session.execute("CREATE TABLE IF NOT EXISTS Java358 (key int primary key, value int)");
120- session.execute("INSERT INTO Java358(key, value) VALUES (42, 42)");
116+ session().execute("CREATE TABLE IF NOT EXISTS Java358 (key int primary key, value int)");
117+ session().execute("INSERT INTO Java358(key, value) VALUES (42, 42)");
121118
122119 // Then, make sure the flag reports correctly that we did delete the row
123120 ResultSet rs;
124- rs = session.execute("DELETE FROM Java358 WHERE KEY=42 IF EXISTS");
121+ rs = session().execute("DELETE FROM Java358 WHERE KEY=42 IF EXISTS");
125122 assertTrue(rs.wasApplied());
126123
127124 // Finally, make sure the flag reports correctly that we did did not delete an non-existing row
128- rs = session.execute("DELETE FROM Java358 WHERE KEY=42 IF EXISTS");
125+ rs = session().execute("DELETE FROM Java358 WHERE KEY=42 IF EXISTS");
129126 assertFalse(rs.wasApplied());
130127 }
131128 }
modified driver-core/src/test/java/com/datastax/driver/core/ConsistencyTest.java +7 −5
@@ -48,10 +48,12 @@
4848 dirtiesContext = true,
4949 createKeyspace = false,
5050 config = {
51+ // tests fail often with write or read timeouts
5152 "hinted_handoff_enabled:true",
52- "phi_convict_threshold:1",
53+ "phi_convict_threshold:5",
5354 "read_request_timeout_in_ms:100000",
54- "write_request_timeout_in_ms:100000"}
55+ "write_request_timeout_in_ms:100000"
56+ }
5557 )
5658 public class ConsistencyTest extends AbstractPoliciesTest {
5759
@@ -719,9 +721,9 @@
719721
720722 private void stopAndWait(int node) {
721723 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
724+ ccm().stop(node);
725+ ccm().waitForDown(node);// this uses port ping
726+ TestUtils.waitForDown(ipOfNode(node), cluster()); // this uses UP/DOWN events
725727 logger.debug("Node " + node + " stopped, sleeping one extra minute to allow nodes to gossip");
726728 Uninterruptibles.sleepUninterruptibly(1, TimeUnit.MINUTES);
727729 }
modified driver-core/src/test/java/com/datastax/driver/core/ControlConnectionTest.java +9 −9
@@ -74,19 +74,19 @@
7474
7575 // We pass only the first host as contact point, so we know the control connection will be on this host
7676 cluster = register(Cluster.builder()
77- .addContactPoints(ccm.addressOfNode(1).getAddress())
78- .withPort(ccm.getBinaryPort())
77+ .addContactPoints(getContactPoints().get(0))
78+ .withPort(ccm().getBinaryPort())
7979 .withReconnectionPolicy(reconnectionPolicy)
8080 .withLoadBalancingPolicy(loadBalancingPolicy)
8181 .build());
8282 cluster.init();
8383
8484 // Kill the control connection host, there should be exactly one reconnection attempt
85- ccm.stop(1);
85+ ccm().stop(1);
8686 TimeUnit.SECONDS.sleep(1); // Sleep for a while to make sure our final count is not the result of lucky timing
8787 assertThat(reconnectionAttempts.get()).isEqualTo(1);
8888
89- ccm.stop(2);
89+ ccm().stop(2);
9090 TimeUnit.SECONDS.sleep(1);
9191 assertThat(reconnectionAttempts.get()).isEqualTo(2);
9292 }
@@ -101,11 +101,11 @@
101101 @CassandraVersion(major = 2.1)
102102 public void should_parse_UDT_definitions_when_using_default_protocol_version() {
103103 Cluster cluster;
104- InetSocketAddress firstHost = ccm.addressOfNode(1);
104+ InetSocketAddress firstHost = ccm().addressOfNode(1);
105105 // First driver instance: create UDT
106106 cluster = register(Cluster.builder()
107107 .addContactPointsWithPorts(firstHost)
108- .withPort(ccm.getBinaryPort())
108+ .withPort(ccm().getBinaryPort())
109109 .build());
110110 Session session = cluster.connect();
111111 session.execute("create keyspace ks WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}");
@@ -131,10 +131,10 @@
131131 @Test(groups = "long")
132132 @CCMConfig(numberOfNodes = 3)
133133 public void should_reestablish_if_control_node_decommissioned() throws InterruptedException {
134- InetSocketAddress firstHost = ccm.addressOfNode(1);
134+ InetSocketAddress firstHost = ccm().addressOfNode(1);
135135 Cluster cluster = register(Cluster.builder()
136136 .addContactPointsWithPorts(firstHost)
137- .withPort(ccm.getBinaryPort())
137+ .withPort(ccm().getBinaryPort())
138138 .withQueryOptions(nonDebouncingQueryOptions())
139139 .build());
140140 cluster.init();
@@ -144,7 +144,7 @@
144144 assertThat(controlHost).isEqualTo(firstHost.getAddress());
145145
146146 // Decommission the node.
147- ccm.decommission(1);
147+ ccm().decommission(1);
148148
149149 // Ensure that the new control connection is not null and it's host is not equal to the decommissioned node.
150150 Host newHost = cluster.manager.controlConnection.connectedHost();
modified driver-core/src/test/java/com/datastax/driver/core/CustomTypeTest.java +6 −8
@@ -19,8 +19,6 @@
1919
2020 import java.nio.ByteBuffer;
2121 import java.util.ArrayList;
22-import java.util.Collection;
23-import java.util.Collections;
2422 import java.util.List;
2523
2624 import static org.testng.Assert.assertEquals;
@@ -31,8 +29,8 @@
3129 public class CustomTypeTest extends CCMTestsSupport {
3230
3331 @Override
34- public Collection<String> createTestFixtures() {
35- return Collections.singleton(
32+ public void onTestContextInitialized() {
33+ execute(
3634 "CREATE TABLE test ("
3735 + " k int,"
3836 + " c 'DynamicCompositeType(s => UTF8Type, i => Int32Type)',"
@@ -79,11 +77,11 @@
7977 @Test(groups = "short")
8078 public void DynamicCompositeTypeTest() {
8179
82- session.execute("INSERT INTO test(k, c, v) VALUES (0, 's@foo:i@32', 1)");
83- session.execute("INSERT INTO test(k, c, v) VALUES (0, 'i@42', 2)");
84- session.execute("INSERT INTO test(k, c, v) VALUES (0, 'i@12:i@3', 3)");
80+ session().execute("INSERT INTO test(k, c, v) VALUES (0, 's@foo:i@32', 1)");
81+ session().execute("INSERT INTO test(k, c, v) VALUES (0, 'i@42', 2)");
82+ session().execute("INSERT INTO test(k, c, v) VALUES (0, 'i@12:i@3', 3)");
8583
86- ResultSet rs = session.execute("SELECT * FROM test");
84+ ResultSet rs = session().execute("SELECT * FROM test");
8785
8886 Row r = rs.one();
8987 assertEquals(r.getInt("k"), 0);
modified driver-core/src/test/java/com/datastax/driver/core/DataTypeIntegrationTest.java +10 −12
@@ -45,10 +45,9 @@
4545 enum StatementType {RAW_STRING, SIMPLE_WITH_PARAM, PREPARED}
4646
4747 @Override
48- public Collection<String> createTestFixtures() {
49- Host host = cluster.getMetadata().getAllHosts().iterator().next();
48+ public void onTestContextInitialized() {
49+ Host host = cluster().getMetadata().getAllHosts().iterator().next();
5050 cassandraVersion = host.getCassandraVersion().nextStable();
51-
5251 List<String> statements = Lists.newArrayList();
5352 for (TestTable table : tables) {
5453 if (cassandraVersion.compareTo(table.minCassandraVersion) < 0)
@@ -57,8 +56,7 @@
5756 else
5857 statements.add(table.createStatement);
5958 }
60-
61- return statements;
59+ execute(statements);
6260 }
6361
6462 @Test(groups = "long")
@@ -78,7 +76,7 @@
7876 }
7977
8078 protected void should_insert_and_retrieve_data(StatementType statementType) {
81- ProtocolVersion protocolVersion = cluster.getConfiguration().getProtocolOptions().getProtocolVersionEnum();
79+ ProtocolVersion protocolVersion = cluster().getConfiguration().getProtocolOptions().getProtocolVersionEnum();
8280
8381 for (TestTable table : tables) {
8482 if (cassandraVersion.compareTo(table.minCassandraVersion) < 0)
@@ -86,20 +84,20 @@
8684
8785 switch (statementType) {
8886 case RAW_STRING:
89- session.execute(table.insertStatement.replace("?", table.testColumnType.format(table.sampleValue)));
87+ session().execute(table.insertStatement.replace("?", table.testColumnType.format(table.sampleValue)));
9088 break;
9189 case SIMPLE_WITH_PARAM:
92- session.execute(table.insertStatement, table.sampleValue);
90+ session().execute(table.insertStatement, table.sampleValue);
9391 break;
9492 case PREPARED:
95- PreparedStatement ps = session.prepare(table.insertStatement);
93+ PreparedStatement ps = session().prepare(table.insertStatement);
9694 BoundStatement bs = ps.bind(table.sampleValue);
9795 checkGetterReturnsBoundValue(bs, table);
98- session.execute(bs);
96+ session().execute(bs);
9997 break;
10098 }
10199
102- Row row = session.execute(table.selectStatement).one();
100+ Row row = session().execute(table.selectStatement).one();
103101 Object queriedValue = table.testColumnType.deserialize(row.getBytesUnsafe("v"), protocolVersion);
104102
105103 assertThat(queriedValue)
@@ -110,7 +108,7 @@
110108 table.insertStatement)
111109 .isEqualTo(table.sampleValue);
112110
113- session.execute(table.truncateStatement);
111+ session().execute(table.truncateStatement);
114112 }
115113 }
116114
modified driver-core/src/test/java/com/datastax/driver/core/DseCCMClusterTest.java +7 −0
@@ -59,6 +59,13 @@
5959 * dse_username = myusername
6060 * dse_password = mypassword
6161 * </pre>
62+ * <p/>
63+ * <h3>Other requirements</h3>
64+ * <p/>
65+ * DSE requires your {@code PATH} variable to provide access
66+ * to super-user executables in {@code /usr/sbin}.
67+ * <p/>
68+ * A correct example is as follows: {@code /usr/bin:/usr/local/bin:/bin:/usr/sbin:$JAVA_HOME/bin:$PATH}.
6269 */
6370 @Test(enabled = false)
6471 @CCMConfig(dse = true, version = "4.8.3")
modified driver-core/src/test/java/com/datastax/driver/core/EventDebouncerIntegrationTest.java +4 −4
@@ -44,8 +44,8 @@
4444 public void should_wait_until_load_balancing_policy_is_fully_initialized() throws InterruptedException {
4545 TestLoadBalancingPolicy policy = new TestLoadBalancingPolicy();
4646 final Cluster cluster = register(createClusterBuilderNoDebouncing()
47- .addContactPoints(ccm.addressOfNode(1).getAddress())
48- .withPort(ccm.getBinaryPort())
47+ .addContactPoints(getContactPoints().get(0))
48+ .withPort(ccm().getBinaryPort())
4949 .withLoadBalancingPolicy(policy).build());
5050 new Thread() {
5151 @Override
@@ -59,8 +59,8 @@
5959 // because the debouncers are not started
6060 // note: a graceful stop notify other nodes which send a topology change event to the driver right away
6161 // while forceStop kills the node so other nodes take much more time to detect node failure
62- ccm.stop(3);
63- ccm.waitForDown(3);
62+ ccm().stop(3);
63+ ccm().waitForDown(3);
6464 // finish cluster initialization and deliver the DOWN event
6565 policy.proceed();
6666 assertThat(policy.onDownCalledBeforeInit).isFalse();
modified driver-core/src/test/java/com/datastax/driver/core/FetchingTest.java +5 −8
@@ -18,9 +18,6 @@
1818 import com.datastax.driver.core.exceptions.UnsupportedFeatureException;
1919 import org.testng.annotations.Test;
2020
21-import java.util.Collection;
22-import java.util.Collections;
23-
2421 import static org.testng.Assert.*;
2522
2623 /**
@@ -29,8 +26,8 @@
2926 public class FetchingTest extends CCMTestsSupport {
3027
3128 @Override
32- public Collection<String> createTestFixtures() {
33- return Collections.singletonList("CREATE TABLE test (k text, v int, PRIMARY KEY (k, v))");
29+ public void onTestContextInitialized() {
30+ execute("CREATE TABLE test (k text, v int, PRIMARY KEY (k, v))");
3431 }
3532
3633 @Test(groups = "short")
@@ -39,11 +36,11 @@
3936 // Insert data
4037 String key = "paging_test";
4138 for (int i = 0; i < 100; i++)
42- session.execute(String.format("INSERT INTO test (k, v) VALUES ('%s', %d)", key, i));
39+ session().execute(String.format("INSERT INTO test (k, v) VALUES ('%s', %d)", key, i));
4340
4441 SimpleStatement st = new SimpleStatement(String.format("SELECT v FROM test WHERE k='%s'", key));
4542 st.setFetchSize(5); // Ridiculously small fetch size for testing purpose. Don't do at home.
46- ResultSet rs = session.execute(st);
43+ ResultSet rs = session().execute(st);
4744
4845 assertFalse(rs.isFullyFetched());
4946
@@ -59,7 +56,7 @@
5956
6057 } catch (UnsupportedFeatureException e) {
6158 // This is expected when testing the protocol v1
62- assertEquals(cluster.getConfiguration().getProtocolOptions().getProtocolVersionEnum(), ProtocolVersion.V1);
59+ assertEquals(cluster().getConfiguration().getProtocolOptions().getProtocolVersionEnum(), ProtocolVersion.V1);
6360 }
6461 }
6562 }
modified driver-core/src/test/java/com/datastax/driver/core/HeartbeatTest.java +4 −4
@@ -57,8 +57,8 @@
5757 @Test(groups = "long")
5858 public void should_send_heartbeat_when_connection_is_inactive() throws InterruptedException {
5959 Cluster cluster = register(Cluster.builder()
60- .addContactPoints(ccm.addressOfNode(1).getAddress())
61- .withPort(ccm.getBinaryPort())
60+ .addContactPoints(getContactPoints().get(0))
61+ .withPort(ccm().getBinaryPort())
6262 .withPoolingOptions(new PoolingOptions()
6363 .setHeartbeatIntervalSeconds(3))
6464 .build());
@@ -113,8 +113,8 @@
113113 @Test(groups = "long")
114114 public void should_not_send_heartbeat_when_disabled() throws InterruptedException {
115115 Cluster cluster = register(Cluster.builder()
116- .addContactPoints(ccm.addressOfNode(1).getAddress())
117- .withPort(ccm.getBinaryPort())
116+ .addContactPoints(getContactPoints().get(0))
117+ .withPort(ccm().getBinaryPort())
118118 .withPoolingOptions(new PoolingOptions()
119119 .setHeartbeatIntervalSeconds(0))
120120 .build());
modified driver-core/src/test/java/com/datastax/driver/core/HostConnectionPoolTest.java +0 −1
@@ -432,7 +432,6 @@
432432 // On returning of the connection, should detect that there are no available streams and trash it.
433433 assertThat(pool.trash).hasSize(0);
434434 pool.returnConnection(extra1);
435- assertThat(pool.connections).hasSize(1);
436435 assertThat(pool.trash).hasSize(1);
437436 } finally {
438437 completeRequests(requests);
modified driver-core/src/test/java/com/datastax/driver/core/IndexMetadataTest.java +11 −12
@@ -23,7 +23,6 @@
2323 import org.testng.annotations.Test;
2424
2525 import java.nio.ByteBuffer;
26-import java.util.Collection;
2726 import java.util.List;
2827
2928 import static com.datastax.driver.core.Assertions.assertThat;
@@ -49,7 +48,7 @@
4948 });
5049
5150 @Override
52- public Collection<String> createTestFixtures() {
51+ public void onTestContextInitialized() {
5352 String createTable = "CREATE TABLE indexing ("
5453 + "id int primary key,"
5554 + "map_values map<text, int>,"
@@ -58,21 +57,21 @@
5857 + "text_column text"
5958 +
6059 // Frozen collections was introduced only in C* 2.1.3
61- (ccm.getVersion().compareTo(VersionNumber.parse("2.1.3")) >= 0
60+ (ccm().getVersion().compareTo(VersionNumber.parse("2.1.3")) >= 0
6261 ?
6362 ", map_full frozen<map<text, int>>,"
6463 + "set_full frozen<set<text>>,"
6564 + "list_full frozen<list<text>>);"
6665 :
6766 ")");
68- return ImmutableList.of(createTable);
67+ execute(createTable);
6968 }
7069
7170 @Test(
7271 groups = "short")
7372 public void should_not_flag_text_column_index_type() {
7473 String createValuesIndex = String.format("CREATE INDEX text_column_index ON %s.indexing (text_column);", keyspace);
75- session.execute(createValuesIndex);
74+ session().execute(createValuesIndex);
7675 IndexMetadata index = getIndexForColumn("text_column");
7776 assertThat(index).hasName("text_column_index")
7877 .isNotKeys()
@@ -88,7 +87,7 @@
8887 major = 2.1)
8988 public void should_not_flag_map_index_type() {
9089 String createValuesIndex = String.format("CREATE INDEX map_values_index ON %s.indexing (map_values);", keyspace);
91- session.execute(createValuesIndex);
90+ session().execute(createValuesIndex);
9291 IndexMetadata index = getIndexForColumn("map_values");
9392 assertThat(index).hasName("map_values_index")
9493 .isNotKeys()
@@ -104,7 +103,7 @@
104103 major = 2.1)
105104 public void should_flag_map_index_type_as_keys() {
106105 String createKeysIndex = String.format("CREATE INDEX map_keys_index ON %s.indexing (KEYS(map_keys));", keyspace);
107- session.execute(createKeysIndex);
106+ session().execute(createKeysIndex);
108107 IndexMetadata index = getIndexForColumn("map_keys");
109108 assertThat(index).hasName("map_keys_index")
110109 .isKeys()
@@ -121,7 +120,7 @@
121120 minor = 3)
122121 public void should_flag_map_index_type_as_full() {
123122 String createFullIndex = String.format("CREATE INDEX map_full_index ON %s.indexing (FULL(map_full));", keyspace);
124- session.execute(createFullIndex);
123+ session().execute(createFullIndex);
125124 IndexMetadata index = getIndexForColumn("map_full");
126125 assertThat(index).hasName("map_full_index")
127126 .isNotKeys()
@@ -138,7 +137,7 @@
138137 minor = 3)
139138 public void should_flag_set_index_type_as_full() {
140139 String createFullIndex = String.format("CREATE INDEX set_full_index ON %s.indexing (FULL(set_full));", keyspace);
141- session.execute(createFullIndex);
140+ session().execute(createFullIndex);
142141 IndexMetadata index = getIndexForColumn("set_full");
143142 assertThat(index).hasName("set_full_index")
144143 .isNotKeys()
@@ -155,7 +154,7 @@
155154 minor = 3)
156155 public void should_flag_list_index_type_as_full() {
157156 String createFullIndex = String.format("CREATE INDEX list_full_index ON %s.indexing (FULL(list_full));", keyspace);
158- session.execute(createFullIndex);
157+ session().execute(createFullIndex);
159158 IndexMetadata index = getIndexForColumn("list_full");
160159 assertThat(index).hasName("list_full_index")
161160 .isNotKeys()
@@ -171,7 +170,7 @@
171170 major = 3.0)
172171 public void should_flag_map_index_type_as_entries() {
173172 String createEntriesIndex = String.format("CREATE INDEX map_entries_index ON %s.indexing (ENTRIES(map_entries));", keyspace);
174- session.execute(createEntriesIndex);
173+ session().execute(createEntriesIndex);
175174 IndexMetadata index = getIndexForColumn("map_entries");
176175 assertThat(index).hasName("map_entries_index")
177176 .isNotKeys()
@@ -265,7 +264,7 @@
265264 }
266265
267266 private TableMetadata getTable(String name) {
268- return cluster.getMetadata().getKeyspace(keyspace).getTable(name);
267+ return cluster().getMetadata().getKeyspace(keyspace).getTable(name);
269268 }
270269
271270 }
modified driver-core/src/test/java/com/datastax/driver/core/LargeDataTest.java +32 −32
@@ -43,11 +43,11 @@
4343 private void testWideRows(int key) throws Throwable {
4444 // Write data
4545 for (int i = 0; i < 1000000; ++i) {
46- 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));
4747 }
4848
4949 // Read data
50- ResultSet rs = 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)));
5151
5252 // Verify data
5353 int i = 0;
@@ -68,10 +68,10 @@
6868 for (int i = 0; i < 10000; ++i) {
6969 q = q.add(insertInto("wide_batch_rows").value("k", key).value("i", i));
7070 }
71- session.execute(q.setConsistencyLevel(ConsistencyLevel.QUORUM));
71+ session().execute(q.setConsistencyLevel(ConsistencyLevel.QUORUM));
7272
7373 // Read data
74- ResultSet rs = 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)));
7575
7676 // Verify data
7777 int i = 0;
@@ -94,11 +94,11 @@
9494
9595 // Write data
9696 for (int i = 0; i < 1000000; ++i) {
97- 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));
9898 }
9999
100100 // Read data
101- ResultSet rs = 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)));
102102
103103 // Verify data
104104 for (Row row : rs) {
@@ -119,10 +119,10 @@
119119 // Create ultra-long text
120120 b.append(i);
121121 }
122- 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));
123123
124124 // Read data
125- Row row = 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();
126126
127127 // Verify data
128128 assertTrue(b.toString().equals(row.getString("txt")));
@@ -166,10 +166,10 @@
166166 for (int i = 0; i < 330; ++i) {
167167 insertStatement = insertStatement.value(createColumnName(i), i);
168168 }
169- session.execute(insertStatement.setConsistencyLevel(ConsistencyLevel.QUORUM));
169+ session().execute(insertStatement.setConsistencyLevel(ConsistencyLevel.QUORUM));
170170
171171 // Read data
172- Row row = 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();
173173
174174 // Verify data
175175 for (int i = 0; i < 330; ++i) {
@@ -186,9 +186,9 @@
186186 @Test(groups = "stress")
187187 @CassandraVersion(major = 2.0, minor = 0, description = "< 2.0 is skipped as 1.2 does not handle reading wide rows well.")
188188 public void wideRows() throws Throwable {
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"));
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"));
192192 testWideRows(0);
193193 }
194194
@@ -200,9 +200,9 @@
200200 @Test(groups = "stress")
201201 @CassandraVersion(major = 2.0, minor = 0, description = "< 2.0 is skipped as 1.2 does not handle large batches well.")
202202 public void wideBatchRows() throws Throwable {
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"));
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"));
206206 testWideBatchRows(0);
207207 }
208208
@@ -213,9 +213,9 @@
213213 */
214214 @Test(groups = "stress")
215215 public void wideByteRows() throws Throwable {
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"));
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"));
219219 testByteRows(0);
220220 }
221221
@@ -226,9 +226,9 @@
226226 */
227227 @Test(groups = "stress")
228228 public void largeText() throws Throwable {
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"));
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"));
232232 testLargeText(0);
233233 }
234234
@@ -239,8 +239,8 @@
239239 */
240240 @Test(groups = "stress")
241241 public void wideTable() throws Throwable {
242- session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, "large_data", 1));
243- session.execute("USE large_data");
242+ session().execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, "large_data", 1));
243+ session().execute("USE large_data");
244244 // Create the extra wide table definition
245245 StringBuilder tableDeclaration = new StringBuilder();
246246 tableDeclaration.append("CREATE TABLE wide_table (");
@@ -249,7 +249,7 @@
249249 tableDeclaration.append(String.format(", %s INT", createColumnName(i)));
250250 }
251251 tableDeclaration.append(')');
252- session.execute(tableDeclaration.toString());
252+ session().execute(tableDeclaration.toString());
253253 testWideTable(0);
254254 }
255255
@@ -261,12 +261,12 @@
261261 @Test(groups = "duration")
262262 @CCMConfig(numberOfNodes = 3)
263263 public void mixedDurationTest() throws Throwable {
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"));
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"));
270270 // Create the extra wide table definition
271271 StringBuilder tableDeclaration = new StringBuilder();
272272 tableDeclaration.append("CREATE TABLE wide_table (");
@@ -275,7 +275,7 @@
275275 tableDeclaration.append(String.format(", %s INT", createColumnName(i)));
276276 }
277277 tableDeclaration.append(')');
278- session.execute(tableDeclaration.toString());
278+ session().execute(tableDeclaration.toString());
279279 for (int i = 0; i < 10; ++i) {
280280 switch ((int) (Math.random() * 5)) {
281281 case 0:
modified driver-core/src/test/java/com/datastax/driver/core/LoadBalancingPolicyBootstrapTest.java +8 −8
@@ -48,8 +48,8 @@
4848 HistoryPolicy policy = new HistoryPolicy(new RoundRobinPolicy());
4949
5050 Cluster cluster = register(Cluster.builder()
51- .addContactPointsWithPorts(getInitialContactPoints())
52- .withPort(ccm.getBinaryPort())
51+ .addContactPoints(getContactPoints())
52+ .withPort(ccm().getBinaryPort())
5353 .withLoadBalancingPolicy(policy)
5454 .build());
5555
@@ -85,13 +85,13 @@
8585 nodeToStop = (nodeToStop == 1) ? 2 : 1; // switch nodes at each try
8686 int activeNode = nodeToStop == 2 ? 1 : 2;
8787
88- ccm.stop(nodeToStop);
89- ccm.waitForDown(nodeToStop);
88+ ccm().stop(nodeToStop);
89+ ccm().waitForDown(nodeToStop);
9090
9191 HistoryPolicy policy = new HistoryPolicy(new RoundRobinPolicy());
9292 Cluster cluster = register(Cluster.builder()
93- .addContactPointsWithPorts(getInitialContactPoints())
94- .withPort(ccm.getBinaryPort())
93+ .addContactPoints(getContactPoints())
94+ .withPort(ccm().getBinaryPort())
9595 .withLoadBalancingPolicy(policy)
9696 .build());
9797
@@ -114,8 +114,8 @@
114114
115115 cluster.close();
116116
117- ccm.start(nodeToStop);
118- ccm.waitForUp(nodeToStop);
117+ ccm().start(nodeToStop);
118+ ccm().waitForUp(nodeToStop);
119119 }
120120 }
121121
modified driver-core/src/test/java/com/datastax/driver/core/LoadBalancingPolicyRefreshTest.java +5 −5
@@ -82,20 +82,20 @@
8282 public void refreshTest() throws Throwable {
8383 // Ugly
8484 Host[] hosts = new Host[2];
85- for (Host h : cluster.getMetadata().getAllHosts()) {
85+ for (Host h : cluster().getMetadata().getAllHosts()) {
8686 if (h.getAddress().equals(InetAddress.getByName(TestUtils.IP_PREFIX + '1')))
8787 hosts[0] = h;
8888 else
8989 hosts[1] = h;
9090 }
9191
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());
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());
9494
9595 policy.changeTheHost(hosts[1]);
9696
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());
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());
9999 }
100100
101101 @SuppressWarnings("unused")
modified driver-core/src/test/java/com/datastax/driver/core/MetadataTest.java +8 −8
@@ -23,7 +23,7 @@
2323 import static com.datastax.driver.core.Assertions.assertThat;
2424 import static com.datastax.driver.core.CreateCCM.TestMode.PER_METHOD;
2525 import static com.datastax.driver.core.TestUtils.nonDebouncingQueryOptions;
26-import static com.datastax.driver.core.TestUtils.waitFor;
26+import static com.datastax.driver.core.TestUtils.waitForUp;
2727
2828 @CreateCCM(PER_METHOD)
2929 public class MetadataTest extends CCMTestsSupport {
@@ -55,8 +55,8 @@
5555 @CCMConfig(numberOfNodes = 3, dirtiesContext = true, createCluster = false)
5656 public void should_update_metadata_on_topology_change() {
5757 Cluster cluster = register(Cluster.builder()
58- .addContactPoints(ccm.addressOfNode(1).getAddress())
59- .withPort(ccm.getBinaryPort())
58+ .addContactPoints(getContactPoints().get(0))
59+ .withPort(ccm().getBinaryPort())
6060 .withQueryOptions(nonDebouncingQueryOptions())
6161 .build());
6262 Session session = cluster.connect();
@@ -73,8 +73,8 @@
7373 Host host3 = TestUtils.findHost(cluster, 3);
7474 Token host3Token = tokensForHost.get(host3);
7575
76- ccm.decommission(3);
77- ccm.remove(3);
76+ ccm().decommission(3);
77+ ccm().remove(3);
7878
7979 // Ensure that the token ranges were updated, there should only be 2 ranges now.
8080 assertThat(metadata.getTokenRanges()).hasSize(2);
@@ -87,9 +87,9 @@
8787 assertThat(cluster).hasValidTokenRanges();
8888
8989 // Add an additional node.
90- ccm.add(4);
91- ccm.start(4);
92- waitFor(TestUtils.IP_PREFIX + '4', cluster);
90+ ccm().add(4);
91+ ccm().start(4);
92+ waitForUp(TestUtils.IP_PREFIX + '4', cluster);
9393
9494 // Ensure that the token ranges were updated, there should only be 3 ranges now.
9595 assertThat(metadata.getTokenRanges()).hasSize(3);
modified driver-core/src/test/java/com/datastax/driver/core/MetricsTest.java +5 −8
@@ -18,11 +18,8 @@
1818 import com.datastax.driver.core.Metrics.Errors;
1919 import com.datastax.driver.core.policies.RetryPolicy;
2020 import com.datastax.driver.core.policies.RetryPolicy.RetryDecision;
21-import com.google.common.collect.Lists;
2221 import org.testng.annotations.Test;
2322
24-import java.util.Collection;
25-
2623 import static org.testng.Assert.assertEquals;
2724
2825 public class MetricsTest extends CCMTestsSupport {
@@ -49,8 +46,8 @@
4946 }
5047
5148 @Override
52- public Collection<String> createTestFixtures() {
53- return Lists.newArrayList("CREATE TABLE test (k int primary key, v int)",
49+ public void onTestContextInitialized() {
50+ execute("CREATE TABLE test (k int primary key, v int)",
5451 "INSERT INTO test (k, v) VALUES (1, 1)");
5552 }
5653
@@ -60,15 +57,15 @@
6057
6158 // We only have one node, this will throw an unavailable exception
6259 Statement statement = new SimpleStatement("SELECT v FROM test WHERE k = 1").setConsistencyLevel(ConsistencyLevel.TWO);
63- session.execute(statement);
60+ session().execute(statement);
6461
65- Errors errors = cluster.getMetrics().getErrorMetrics();
62+ Errors errors = cluster().getMetrics().getErrorMetrics();
6663 assertEquals(errors.getUnavailables().getCount(), 1);
6764 assertEquals(errors.getRetries().getCount(), 1);
6865 assertEquals(errors.getRetriesOnUnavailable().getCount(), 1);
6966
7067 retryDecision = RetryDecision.ignore();
71- session.execute(statement);
68+ session().execute(statement);
7269
7370 assertEquals(errors.getUnavailables().getCount(), 2);
7471 assertEquals(errors.getIgnores().getCount(), 1);
modified driver-core/src/test/java/com/datastax/driver/core/MissingRpcAddressTest.java +5 −5
@@ -42,22 +42,22 @@
4242 deleteNode2RpcAddressFromNode1();
4343 // Use only one contact point to make sure that the control connection is on node1
4444 Cluster cluster = register(Cluster.builder()
45- .addContactPoints(ccm.addressOfNode(1).getAddress())
46- .withPort(ccm.getBinaryPort())
45+ .addContactPoints(getContactPoints().get(0))
46+ .withPort(ccm().getBinaryPort())
4747 .build());
4848 cluster.connect();
4949
5050 // Since node2's RPC address is unknown on our control host, it should have been ignored
5151 assertEquals(cluster.getMetrics().getConnectedToHosts().getValue().intValue(), 1);
52- assertNull(cluster.getMetadata().getHost(getInitialContactPoints().get(1)));
52+ assertNull(cluster.getMetadata().getHost(getContactPointsWithPorts().get(1)));
5353 }
5454
5555 // Artificially modify the system tables to simulate the missing rpc_address.
5656 private void deleteNode2RpcAddressFromNode1() throws Exception {
57- InetSocketAddress firstHost = ccm.addressOfNode(1);
57+ InetSocketAddress firstHost = ccm().addressOfNode(1);
5858 Cluster cluster = register(Cluster.builder()
5959 .addContactPointsWithPorts(singleton(firstHost))
60- .withPort(ccm.getBinaryPort())
60+ .withPort(ccm().getBinaryPort())
6161 // ensure we will only connect to node1
6262 .withLoadBalancingPolicy(new WhiteListPolicy(Policies.defaultLoadBalancingPolicy(),
6363 Lists.newArrayList(firstHost)))
modified driver-core/src/test/java/com/datastax/driver/core/NettyOptionsTest.java +2 −2
@@ -65,8 +65,8 @@
6565 }
6666 }).when(nettyOptions).afterChannelInitialized(any(SocketChannel.class));
6767 Cluster cluster = register(Cluster.builder()
68- .addContactPointsWithPorts(ccm.addressOfNode(1))
69- .withPort(ccm.getBinaryPort())
68+ .addContactPoints(getContactPoints().get(0))
69+ .withPort(ccm().getBinaryPort())
7070 .withPoolingOptions(new PoolingOptions()
7171 .setConnectionsPerHost(HostDistance.LOCAL, coreConnections, coreConnections)
7272 )
modified driver-core/src/test/java/com/datastax/driver/core/NodeListRefreshDebouncerTest.java +6 −11
@@ -15,7 +15,6 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import org.testng.annotations.AfterMethod;
1918 import org.testng.annotations.BeforeMethod;
2019 import org.testng.annotations.Test;
2120
@@ -51,10 +50,11 @@
5150 queryOptions.setMaxPendingRefreshNodeListRequests(5);
5251 queryOptions.setRefreshSchemaIntervalMillis(0);
5352 // Create a separate cluster that will receive the schema events on its control connection.
54- cluster2 = Cluster.builder()
55- .addContactPointsWithPorts(getInitialContactPoints())
53+ cluster2 = register(Cluster.builder()
54+ .addContactPoints(getContactPoints())
55+ .withPort(ccm().getBinaryPort())
5656 .withQueryOptions(queryOptions)
57- .build();
57+ .build());
5858 session2 = cluster2.connect();
5959
6060 // Create a spy of the Cluster's control connection and replace it with the spy.
@@ -63,11 +63,6 @@
6363 reset(controlConnection);
6464 }
6565
66- @AfterMethod(groups = "short")
67- public void teardown() {
68- cluster2.close();
69- }
70-
7166 /**
7267 * Ensures that when a keyspace is created that refresh node list request
7368 * is debounced and processed within {@link QueryOptions#getRefreshSchemaIntervalMillis()}
@@ -79,7 +74,7 @@
7974 @Test(groups = "short")
8075 public void should_debounce_refresh_when_keyspace_created() {
8176 String keyspace = "sdrwkc";
82- session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, 1));
77+ session().execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, 1));
8378 keyspaces.add(keyspace);
8479
8580 verify(controlConnection, timeout(DEBOUNCE_TIME + queryOptions.getRefreshSchemaIntervalMillis())).refreshNodeListAndTokenMap();
@@ -100,7 +95,7 @@
10095 String prefix = "srwmprr";
10196 for (int i = 0; i < 5; i++) {
10297 String keyspace = prefix + i;
103- session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, 1));
98+ session().execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, 1));
10499 keyspaces.add(keyspace);
105100 }
106101
modified driver-core/src/test/java/com/datastax/driver/core/NodeRefreshDebouncerTest.java +6 −6
@@ -43,17 +43,17 @@
4343 int refreshNodeInterval = 30000;
4444 QueryOptions queryOptions = new QueryOptions().setRefreshNodeIntervalMillis(refreshNodeInterval);
4545 Cluster cluster = register(Cluster.builder()
46- .addContactPoints(ccm.addressOfNode(1).getAddress())
47- .withPort(ccm.getBinaryPort())
46+ .addContactPoints(getContactPoints().get(0))
47+ .withPort(ccm().getBinaryPort())
4848 .withQueryOptions(queryOptions)
4949 .build());
5050 cluster.connect();
5151 Host.StateListener listener = mock(Host.StateListener.class);
5252 cluster.register(listener);
53- ccm.add(2);
54- ccm.start(2);
55- ccm.stop(2);
56- ccm.start(2);
53+ ccm().add(2);
54+ ccm().start(2);
55+ ccm().stop(2);
56+ ccm().start(2);
5757
5858 ArgumentCaptor<Host> captor = forClass(Host.class);
5959
modified driver-core/src/test/java/com/datastax/driver/core/PagingStateTest.java +16 −23
@@ -19,11 +19,8 @@
1919 import com.datastax.driver.core.utils.CassandraVersion;
2020 import org.slf4j.Logger;
2121 import org.slf4j.LoggerFactory;
22-import org.testng.annotations.BeforeClass;
2322 import org.testng.annotations.Test;
2423
25-import java.util.Collection;
26-import java.util.Collections;
2724 import java.util.Iterator;
2825
2926 import static org.assertj.core.api.Assertions.assertThat;
@@ -36,14 +33,10 @@
3633 public static final String KEY = "paging_test";
3734
3835 @Override
39- public Collection<String> createTestFixtures() {
40- return Collections.singletonList("CREATE TABLE test (k text, v int, PRIMARY KEY (k, v))");
41- }
42-
43- @BeforeClass(groups = "short")
44- public void initData() {
36+ public void onTestContextInitialized() {
37+ execute("CREATE TABLE test (k text, v int, PRIMARY KEY (k, v))");
4538 for (int i = 0; i < 100; i++) {
46- session.execute(String.format("INSERT INTO test (k, v) VALUES ('%s', %d)", KEY, i));
39+ execute(String.format("INSERT INTO test (k, v) VALUES ('%s', %d)", KEY, i));
4740 }
4841 }
4942
@@ -57,12 +50,12 @@
5750 @Test(groups = "short")
5851 public void should_complete_when_using_paging_state() {
5952 SimpleStatement st = new SimpleStatement(String.format("SELECT v FROM test WHERE k='%s'", KEY));
60- ResultSet result = session.execute(st.setFetchSize(20));
53+ ResultSet result = session().execute(st.setFetchSize(20));
6154 int pageSize = result.getAvailableWithoutFetching();
6255 String savedPagingStateString = result.getExecutionInfo().getPagingState().toString();
6356
6457 st = new SimpleStatement(String.format("SELECT v FROM test WHERE k='%s'", KEY));
65- result = session.execute(st.setFetchSize(20).setPagingState(PagingState.fromString(savedPagingStateString)));
58+ result = session().execute(st.setFetchSize(20).setPagingState(PagingState.fromString(savedPagingStateString)));
6659
6760 //We have the result starting from the next page we stopped
6861 assertThat(result.one().getInt("v")).isEqualTo(pageSize);
@@ -87,7 +80,7 @@
8780 boolean setWithWrongStatement = false;
8881
8982 SimpleStatement st = new SimpleStatement(String.format("SELECT v FROM test WHERE k='%s'", KEY));
90- ResultSet result = session.execute(st.setFetchSize(20));
83+ ResultSet result = session().execute(st.setFetchSize(20));
9184
9285 PagingState savedPagingState = result.getExecutionInfo().getPagingState();
9386 byte[] savedPagingStateBuffer = savedPagingState.toBytes();
@@ -129,14 +122,14 @@
129122 @Test(groups = "short")
130123 @CassandraVersion(major = 2.0)
131124 public void should_be_able_to_use_state_with_bound_statement() {
132- PreparedStatement prepared = session.prepare("SELECT v from test where k=?");
125+ PreparedStatement prepared = session().prepare("SELECT v from test where k=?");
133126 BoundStatement bs = prepared.bind(KEY);
134127
135- ResultSet result = session.execute(bs.setFetchSize(20));
128+ ResultSet result = session().execute(bs.setFetchSize(20));
136129 int pageSize = result.getAvailableWithoutFetching();
137130 PagingState pagingState = result.getExecutionInfo().getPagingState();
138131
139- result = session.execute(bs.setFetchSize(20).setPagingState(pagingState));
132+ result = session().execute(bs.setFetchSize(20).setPagingState(pagingState));
140133
141134 //We have the result starting from the next page we stopped
142135 assertThat(result.one().getInt("v")).isEqualTo(pageSize);
@@ -152,14 +145,14 @@
152145 @Test(groups = "short", expectedExceptions = {PagingStateException.class})
153146 @CassandraVersion(major = 2.0)
154147 public void should_not_be_able_to_use_state_with_different_bound_statement() {
155- PreparedStatement prepared = session.prepare("SELECT v from test where k=?");
148+ PreparedStatement prepared = session().prepare("SELECT v from test where k=?");
156149 BoundStatement bs0 = prepared.bind(KEY);
157150
158- ResultSet result = session.execute(bs0.setFetchSize(20));
151+ ResultSet result = session().execute(bs0.setFetchSize(20));
159152 PagingState pagingState = result.getExecutionInfo().getPagingState();
160153
161154 BoundStatement bs1 = prepared.bind("different_key");
162- session.execute(bs1.setFetchSize(20).setPagingState(pagingState));
155+ session().execute(bs1.setFetchSize(20).setPagingState(pagingState));
163156 }
164157
165158 /**
@@ -172,7 +165,7 @@
172165 @Test(groups = "short")
173166 public void should_return_no_rows_when_paged_to_end() {
174167 SimpleStatement st = new SimpleStatement(String.format("SELECT v FROM test WHERE k='%s'", KEY));
175- ResultSet result = session.execute(st.setFetchSize(20));
168+ ResultSet result = session().execute(st.setFetchSize(20));
176169
177170 // Consume enough of the iterator to cause all the results to be paged in.
178171 Iterator<Row> rowIt = result.iterator();
@@ -183,7 +176,7 @@
183176 String savedPagingStateString = result.getExecutionInfo().getPagingState().toString();
184177
185178 st = new SimpleStatement(String.format("SELECT v FROM test WHERE k='%s'", KEY));
186- result = session.execute(st.setFetchSize(20).setPagingState(PagingState.fromString(savedPagingStateString)));
179+ result = session().execute(st.setFetchSize(20).setPagingState(PagingState.fromString(savedPagingStateString)));
187180
188181 assertThat(result.one()).isNull();
189182 }
@@ -220,12 +213,12 @@
220213 @Test(groups = "short")
221214 public void should_complete_when_using_unsafe_paging_state() {
222215 SimpleStatement st = new SimpleStatement(String.format("SELECT v FROM test WHERE k='%s'", KEY));
223- ResultSet result = session.execute(st.setFetchSize(20));
216+ ResultSet result = session().execute(st.setFetchSize(20));
224217 int pageSize = result.getAvailableWithoutFetching();
225218 byte[] savedPagingState = result.getExecutionInfo().getPagingStateUnsafe();
226219
227220 st = new SimpleStatement(String.format("SELECT v FROM test WHERE k='%s'", KEY));
228- result = session.execute(st.setFetchSize(20).setPagingStateUnsafe(savedPagingState));
221+ result = session().execute(st.setFetchSize(20).setPagingStateUnsafe(savedPagingState));
229222
230223 //We have the result starting from the next page we stopped
231224 assertThat(result.one().getInt("v")).isEqualTo(pageSize);
modified driver-core/src/test/java/com/datastax/driver/core/PoolingOptionsIntegrationTest.java +5 −5
@@ -58,21 +58,21 @@
5858 */
5959 @Test(groups = "short")
6060 public void should_be_able_to_use_custom_initialization_executor() {
61- cluster.init();
61+ cluster().init();
6262 // Ensure executor used.
6363 verify(executor, atLeastOnce()).execute(any(Runnable.class));
6464
6565 // Reset invocation count.
6666 reset();
6767
68- Session session = cluster.connect();
68+ Session session = cluster().connect();
6969
7070 // Ensure executor used again to establish core connections.
7171 verify(executor, atLeastOnce()).execute(any(Runnable.class));
7272
7373 // Expect core connections + control connection.
74- assertThat(cluster.getMetrics().getOpenConnections().getValue()).isEqualTo(
75- TestUtils.numberOfLocalCoreConnections(cluster) + 1);
74+ assertThat(cluster().getMetrics().getOpenConnections().getValue()).isEqualTo(
75+ TestUtils.numberOfLocalCoreConnections(cluster()) + 1);
7676
7777 reset();
7878
@@ -82,6 +82,6 @@
8282 verify(executor, atLeastOnce()).execute(any(Runnable.class));
8383
8484 // Only the control connection should remain.
85- assertThat(cluster.getMetrics().getOpenConnections().getValue()).isEqualTo(1);
85+ assertThat(cluster().getMetrics().getOpenConnections().getValue()).isEqualTo(1);
8686 }
8787 }
modified driver-core/src/test/java/com/datastax/driver/core/PreparedStatementTest.java +64 −58
@@ -21,7 +21,10 @@
2121 import org.testng.annotations.Test;
2222
2323 import java.net.InetAddress;
24-import java.util.*;
24+import java.util.ArrayList;
25+import java.util.List;
26+import java.util.Map;
27+import java.util.Set;
2528
2629 import static com.datastax.driver.core.TestUtils.*;
2730 import static org.assertj.core.api.Assertions.assertThat;
@@ -47,8 +50,11 @@
4750 }
4851
4952 @Override
50- public Collection<String> createTestFixtures() {
53+ public void onTestContextInitialized() {
54+ execute(createTestFixtures());
55+ }
5156
57+ private List<String> createTestFixtures() {
5258 List<String> defs = new ArrayList<String>(4);
5359
5460 StringBuilder sb = new StringBuilder();
@@ -101,7 +107,6 @@
101107
102108 defs.add(String.format("CREATE TABLE %s (k text PRIMARY KEY, i int)", SIMPLE_TABLE));
103109 defs.add(String.format("CREATE TABLE %s (k text PRIMARY KEY, v text)", SIMPLE_TABLE2));
104-
105110 return defs;
106111 }
107112
@@ -114,11 +119,11 @@
114119 continue;
115120
116121 String name = "c_" + type;
117- PreparedStatement ps = session.prepare(String.format("INSERT INTO %s(k, %s) VALUES ('prepared_native', ?)", ALL_NATIVE_TABLE, name));
122+ PreparedStatement ps = session().prepare(String.format("INSERT INTO %s(k, %s) VALUES ('prepared_native', ?)", ALL_NATIVE_TABLE, name));
118123 BoundStatement bs = ps.bind();
119- session.execute(setBoundValue(bs, name, type, getFixedValue(type)));
124+ session().execute(setBoundValue(bs, name, type, getFixedValue(type)));
120125
121- Row row = session.execute(String.format("SELECT %s FROM %s WHERE k='prepared_native'", name, ALL_NATIVE_TABLE)).one();
126+ Row row = session().execute(String.format("SELECT %s FROM %s WHERE k='prepared_native'", name, ALL_NATIVE_TABLE)).one();
122127 assertEquals(getValue(row, name, type), getFixedValue(type), "For type " + type);
123128 }
124129 }
@@ -135,11 +140,11 @@
135140 continue;
136141
137142 String name = "c_" + type;
138- PreparedStatement ps = session.prepare(String.format("INSERT INTO %s(k, %s) VALUES ('prepared_native', ?)", ALL_NATIVE_TABLE, name));
143+ PreparedStatement ps = session().prepare(String.format("INSERT INTO %s(k, %s) VALUES ('prepared_native', ?)", ALL_NATIVE_TABLE, name));
139144 BoundStatement bs = ps.bind();
140- session.execute(setBoundValue(bs, name, type, getFixedValue2(type)));
145+ session().execute(setBoundValue(bs, name, type, getFixedValue2(type)));
141146
142- Row row = session.execute(String.format("SELECT %s FROM %s WHERE k='prepared_native'", name, ALL_NATIVE_TABLE)).one();
147+ Row row = session().execute(String.format("SELECT %s FROM %s WHERE k='prepared_native'", name, ALL_NATIVE_TABLE)).one();
143148 assertEquals(getValue(row, name, type), getFixedValue2(type), "For type " + type);
144149 }
145150 }
@@ -156,12 +161,12 @@
156161 String name = "c_list_" + rawType;
157162 DataType type = DataType.list(rawType);
158163 List<Object> value = (List<Object>) getFixedValue(type);
159- ;
160- PreparedStatement ps = session.prepare(String.format("INSERT INTO %s(k, %s) VALUES ('prepared_list', ?)", ALL_LIST_TABLE, name));
164+
165+ PreparedStatement ps = session().prepare(String.format("INSERT INTO %s(k, %s) VALUES ('prepared_list', ?)", ALL_LIST_TABLE, name));
161166 BoundStatement bs = ps.bind();
162- session.execute(setBoundValue(bs, name, type, value));
167+ session().execute(setBoundValue(bs, name, type, value));
163168
164- Row row = session.execute(String.format("SELECT %s FROM %s WHERE k='prepared_list'", name, ALL_LIST_TABLE)).one();
169+ Row row = session().execute(String.format("SELECT %s FROM %s WHERE k='prepared_list'", name, ALL_LIST_TABLE)).one();
165170 assertEquals(getValue(row, name, type), value, "For type " + type);
166171 }
167172 }
@@ -181,12 +186,12 @@
181186 String name = "c_list_" + rawType;
182187 DataType type = DataType.list(rawType);
183188 List<Object> value = (List<Object>) getFixedValue2(type);
184- ;
185- PreparedStatement ps = session.prepare(String.format("INSERT INTO %s(k, %s) VALUES ('prepared_list', ?)", ALL_LIST_TABLE, name));
189+
190+ PreparedStatement ps = session().prepare(String.format("INSERT INTO %s(k, %s) VALUES ('prepared_list', ?)", ALL_LIST_TABLE, name));
186191 BoundStatement bs = ps.bind();
187- session.execute(setBoundValue(bs, name, type, value));
192+ session().execute(setBoundValue(bs, name, type, value));
188193
189- Row row = session.execute(String.format("SELECT %s FROM %s WHERE k='prepared_list'", name, ALL_LIST_TABLE)).one();
194+ Row row = session().execute(String.format("SELECT %s FROM %s WHERE k='prepared_list'", name, ALL_LIST_TABLE)).one();
190195 assertEquals(getValue(row, name, type), value, "For type " + type);
191196 }
192197 }
@@ -203,12 +208,12 @@
203208 String name = "c_set_" + rawType;
204209 DataType type = DataType.set(rawType);
205210 Set<Object> value = (Set<Object>) getFixedValue(type);
206- ;
207- PreparedStatement ps = session.prepare(String.format("INSERT INTO %s(k, %s) VALUES ('prepared_set', ?)", ALL_SET_TABLE, name));
211+
212+ PreparedStatement ps = session().prepare(String.format("INSERT INTO %s(k, %s) VALUES ('prepared_set', ?)", ALL_SET_TABLE, name));
208213 BoundStatement bs = ps.bind();
209- session.execute(setBoundValue(bs, name, type, value));
214+ session().execute(setBoundValue(bs, name, type, value));
210215
211- Row row = session.execute(String.format("SELECT %s FROM %s WHERE k='prepared_set'", name, ALL_SET_TABLE)).one();
216+ Row row = session().execute(String.format("SELECT %s FROM %s WHERE k='prepared_set'", name, ALL_SET_TABLE)).one();
212217 assertEquals(getValue(row, name, type), value, "For type " + type);
213218 }
214219 }
@@ -228,12 +233,12 @@
228233 String name = "c_set_" + rawType;
229234 DataType type = DataType.set(rawType);
230235 Set<Object> value = (Set<Object>) getFixedValue2(type);
231- ;
232- PreparedStatement ps = session.prepare(String.format("INSERT INTO %s(k, %s) VALUES ('prepared_set', ?)", ALL_SET_TABLE, name));
236+
237+ PreparedStatement ps = session().prepare(String.format("INSERT INTO %s(k, %s) VALUES ('prepared_set', ?)", ALL_SET_TABLE, name));
233238 BoundStatement bs = ps.bind();
234- session.execute(setBoundValue(bs, name, type, value));
239+ session().execute(setBoundValue(bs, name, type, value));
235240
236- Row row = session.execute(String.format("SELECT %s FROM %s WHERE k='prepared_set'", name, ALL_SET_TABLE)).one();
241+ Row row = session().execute(String.format("SELECT %s FROM %s WHERE k='prepared_set'", name, ALL_SET_TABLE)).one();
237242 assertEquals(getValue(row, name, type), value, "For type " + type);
238243 }
239244 }
@@ -255,12 +260,12 @@
255260 String name = "c_map_" + rawKeyType + '_' + rawValueType;
256261 DataType type = DataType.map(rawKeyType, rawValueType);
257262 Map<Object, Object> value = (Map<Object, Object>) getFixedValue(type);
258- ;
259- PreparedStatement ps = session.prepare(String.format("INSERT INTO %s(k, %s) VALUES ('prepared_map', ?)", ALL_MAP_TABLE, name));
263+
264+ PreparedStatement ps = session().prepare(String.format("INSERT INTO %s(k, %s) VALUES ('prepared_map', ?)", ALL_MAP_TABLE, name));
260265 BoundStatement bs = ps.bind();
261- session.execute(setBoundValue(bs, name, type, value));
266+ session().execute(setBoundValue(bs, name, type, value));
262267
263- Row row = session.execute(String.format("SELECT %s FROM %s WHERE k='prepared_map'", name, ALL_MAP_TABLE)).one();
268+ Row row = session().execute(String.format("SELECT %s FROM %s WHERE k='prepared_map'", name, ALL_MAP_TABLE)).one();
264269 assertEquals(getValue(row, name, type), value, "For type " + type);
265270 }
266271 }
@@ -286,12 +291,12 @@
286291 String name = "c_map_" + rawKeyType + '_' + rawValueType;
287292 DataType type = DataType.map(rawKeyType, rawValueType);
288293 Map<Object, Object> value = (Map<Object, Object>) getFixedValue2(type);
289- ;
290- PreparedStatement ps = session.prepare(String.format("INSERT INTO %s(k, %s) VALUES ('prepared_map', ?)", ALL_MAP_TABLE, name));
294+
295+ PreparedStatement ps = session().prepare(String.format("INSERT INTO %s(k, %s) VALUES ('prepared_map', ?)", ALL_MAP_TABLE, name));
291296 BoundStatement bs = ps.bind();
292- session.execute(setBoundValue(bs, name, type, value));
297+ session().execute(setBoundValue(bs, name, type, value));
293298
294- Row row = session.execute(String.format("SELECT %s FROM %s WHERE k='prepared_map'", name, ALL_MAP_TABLE)).one();
299+ Row row = session().execute(String.format("SELECT %s FROM %s WHERE k='prepared_map'", name, ALL_MAP_TABLE)).one();
295300 assertEquals(getValue(row, name, type), value, "For type " + type);
296301 }
297302 }
@@ -300,16 +305,16 @@
300305 @Test(groups = "short")
301306 public void prepareWithNullValuesTest() throws Exception {
302307
303- PreparedStatement ps = session.prepare("INSERT INTO " + SIMPLE_TABLE2 + "(k, v) VALUES (?, ?)");
308+ PreparedStatement ps = session().prepare("INSERT INTO " + SIMPLE_TABLE2 + "(k, v) VALUES (?, ?)");
304309
305- session.execute(ps.bind("prepWithNull1", null));
310+ session().execute(ps.bind("prepWithNull1", null));
306311
307312 BoundStatement bs = ps.bind();
308313 bs.setString("k", "prepWithNull2");
309314 bs.setString("v", null);
310- session.execute(bs);
315+ session().execute(bs);
311316
312- ResultSet rs = session.execute("SELECT * FROM " + SIMPLE_TABLE2 + " WHERE k IN ('prepWithNull1', 'prepWithNull2')");
317+ ResultSet rs = session().execute("SELECT * FROM " + SIMPLE_TABLE2 + " WHERE k IN ('prepWithNull1', 'prepWithNull2')");
313318 Row r1 = rs.one();
314319 Row r2 = rs.one();
315320 assertTrue(rs.isExhausted());
@@ -328,7 +333,7 @@
328333 toPrepare.setConsistencyLevel(ConsistencyLevel.QUORUM);
329334 toPrepare.enableTracing();
330335
331- PreparedStatement prepared = session.prepare(toPrepare);
336+ PreparedStatement prepared = session().prepare(toPrepare);
332337 BoundStatement bs = prepared.bind("someValue");
333338
334339 assertEquals(ConsistencyLevel.QUORUM, bs.getConsistencyLevel());
@@ -350,17 +355,17 @@
350355 public void batchTest() throws Exception {
351356
352357 try {
353- PreparedStatement ps1 = session.prepare("INSERT INTO " + SIMPLE_TABLE2 + "(k, v) VALUES (?, ?)");
354- PreparedStatement ps2 = session.prepare("INSERT INTO " + SIMPLE_TABLE2 + "(k, v) VALUES (?, 'bar')");
358+ PreparedStatement ps1 = session().prepare("INSERT INTO " + SIMPLE_TABLE2 + "(k, v) VALUES (?, ?)");
359+ PreparedStatement ps2 = session().prepare("INSERT INTO " + SIMPLE_TABLE2 + "(k, v) VALUES (?, 'bar')");
355360
356361 BatchStatement bs = new BatchStatement();
357362 bs.add(ps1.bind("one", "foo"));
358363 bs.add(ps2.bind("two"));
359364 bs.add(new SimpleStatement("INSERT INTO " + SIMPLE_TABLE2 + " (k, v) VALUES ('three', 'foobar')"));
360365
361- session.execute(bs);
366+ session().execute(bs);
362367
363- List<Row> all = session.execute("SELECT * FROM " + SIMPLE_TABLE2).all();
368+ List<Row> all = session().execute("SELECT * FROM " + SIMPLE_TABLE2).all();
364369
365370 assertEquals("three", all.get(0).getString("k"));
366371 assertEquals("foobar", all.get(0).getString("v"));
@@ -372,46 +377,46 @@
372377 assertEquals("bar", all.get(2).getString("v"));
373378 } catch (UnsupportedFeatureException e) {
374379 // This is expected when testing the protocol v1
375- if (cluster.getConfiguration().getProtocolOptions().getProtocolVersionEnum() != ProtocolVersion.V1)
380+ if (cluster().getConfiguration().getProtocolOptions().getProtocolVersionEnum() != ProtocolVersion.V1)
376381 throw e;
377382 }
378383 }
379384
380385 @Test(groups = "short", expectedExceptions = {IllegalStateException.class})
381386 public void unboundVariableInBoundStatementTest() {
382- PreparedStatement ps = session.prepare("INSERT INTO " + SIMPLE_TABLE + " (k, i) VALUES (?, ?)");
387+ PreparedStatement ps = session().prepare("INSERT INTO " + SIMPLE_TABLE + " (k, i) VALUES (?, ?)");
383388 BoundStatement bs = ps.bind("k");
384389 assertFalse(bs.isSet("i"));
385- session.execute(bs);
390+ session().execute(bs);
386391 }
387392
388393 @Test(groups = "short", expectedExceptions = {IllegalStateException.class})
389394 @CassandraVersion(major = 2.0)
390395 public void unboundVariableInBatchStatementTest() {
391- PreparedStatement ps = session.prepare("INSERT INTO " + SIMPLE_TABLE + " (k, i) VALUES (?, ?)");
396+ PreparedStatement ps = session().prepare("INSERT INTO " + SIMPLE_TABLE + " (k, i) VALUES (?, ?)");
392397 BatchStatement batch = new BatchStatement();
393398 batch.add(ps.bind("k"));
394- session.execute(batch);
399+ session().execute(batch);
395400 }
396401
397402 @Test(groups = "short")
398403 public void should_set_routing_key_on_case_insensitive_keyspace_and_table() {
399- session.execute(String.format("CREATE TABLE %s.foo (i int PRIMARY KEY)", keyspace));
404+ session().execute(String.format("CREATE TABLE %s.foo (i int PRIMARY KEY)", keyspace));
400405
401- PreparedStatement ps = session.prepare(String.format("INSERT INTO %s.foo (i) VALUES (?)", keyspace));
406+ PreparedStatement ps = session().prepare(String.format("INSERT INTO %s.foo (i) VALUES (?)", keyspace));
402407 BoundStatement bs = ps.bind(1);
403408 assertThat(bs.getRoutingKey()).isNotNull();
404409 }
405410
406411 @Test(groups = "short")
407412 public void should_set_routing_key_on_case_sensitive_keyspace_and_table() {
408- session.execute("CREATE KEYSPACE \"Test\" WITH replication = { "
413+ session().execute("CREATE KEYSPACE \"Test\" WITH replication = { "
409414 + " 'class': 'SimpleStrategy',"
410415 + " 'replication_factor': '1'"
411416 + "}");
412- session.execute("CREATE TABLE \"Test\".\"Foo\" (i int PRIMARY KEY)");
417+ session().execute("CREATE TABLE \"Test\".\"Foo\" (i int PRIMARY KEY)");
413418
414- PreparedStatement ps = session.prepare("INSERT INTO \"Test\".\"Foo\" (i) VALUES (?)");
419+ PreparedStatement ps = session().prepare("INSERT INTO \"Test\".\"Foo\" (i) VALUES (?)");
415420 BoundStatement bs = ps.bind(1);
416421 assertThat(bs.getRoutingKey()).isNotNull();
417422 }
@@ -419,14 +424,15 @@
419424 @Test(groups = "short", expectedExceptions = InvalidQueryException.class)
420425 public void should_fail_when_prepared_on_another_cluster() throws Exception {
421426 Cluster otherCluster = Cluster.builder()
422- .addContactPointsWithPorts(getInitialContactPoints())
427+ .addContactPoints(getContactPoints())
428+ .withPort(ccm().getBinaryPort())
423429 .build();
424430 try {
425431 PreparedStatement pst = otherCluster.connect().prepare("select * from system.peers where inet = ?");
426432 BoundStatement bs = pst.bind().setInet(0, InetAddress.getByName("localhost"));
427433
428434 // We expect that the error gets detected without a roundtrip to the server, so use executeAsync
429- session.executeAsync(bs);
435+ session().executeAsync(bs);
430436 } finally {
431437 otherCluster.close();
432438 }
@@ -434,7 +440,7 @@
434440
435441 @Test(groups = "short")
436442 public void should_propagate_idempotence_in_statements() {
437- session.execute(String.format("CREATE TABLE %s.idempotencetest (i int PRIMARY KEY)", keyspace));
443+ session().execute(String.format("CREATE TABLE %s.idempotencetest (i int PRIMARY KEY)", keyspace));
438444
439445 SimpleStatement statement;
440446 IdempotenceAwarePreparedStatement prepared;
@@ -442,21 +448,21 @@
442448
443449 statement = new SimpleStatement(String.format("SELECT * FROM %s.idempotencetest WHERE i = ?", keyspace));
444450
445- prepared = (IdempotenceAwarePreparedStatement) session.prepare(statement);
451+ prepared = (IdempotenceAwarePreparedStatement) session().prepare(statement);
446452 bound = prepared.bind(1);
447453
448454 assertThat(prepared.isIdempotent()).isNull();
449455 assertThat(bound.isIdempotent()).isNull();
450456
451457 statement.setIdempotent(true);
452- prepared = (IdempotenceAwarePreparedStatement) session.prepare(statement);
458+ prepared = (IdempotenceAwarePreparedStatement) session().prepare(statement);
453459 bound = prepared.bind(1);
454460
455461 assertThat(prepared.isIdempotent()).isTrue();
456462 assertThat(bound.isIdempotent()).isTrue();
457463
458464 statement.setIdempotent(false);
459- prepared = (IdempotenceAwarePreparedStatement) session.prepare(statement);
465+ prepared = (IdempotenceAwarePreparedStatement) session().prepare(statement);
460466 bound = prepared.bind(1);
461467
462468 assertThat(prepared.isIdempotent()).isFalse();
modified driver-core/src/test/java/com/datastax/driver/core/QueryLoggerTest.java +88 −88
@@ -122,8 +122,8 @@
122122
123123 @AfterMethod(groups = {"short", "unit"}, alwaysRun = true)
124124 public void unregisterQueryLogger() {
125- if (cluster != null && queryLogger != null) {
126- cluster.unregister(queryLogger);
125+ if (cluster() != null && queryLogger != null) {
126+ cluster().unregister(queryLogger);
127127 }
128128 }
129129
@@ -133,12 +133,12 @@
133133 public void should_log_regular_statements() throws Exception {
134134 // given
135135 normal.setLevel(DEBUG);
136- queryLogger = QueryLogger.builder(cluster)
136+ queryLogger = QueryLogger.builder(cluster())
137137 .withConstantThreshold(Long.MAX_VALUE)
138138 .build();
139- cluster.register(queryLogger);
139+ cluster().register(queryLogger);
140140 String query = "SELECT c_text FROM test WHERE pk = 42";
141- session.execute(query);
141+ session().execute(query);
142142 // then
143143 String line = normalAppender.waitAndGet(10000);
144144 assertThat(line)
@@ -152,14 +152,14 @@
152152 public void should_log_bound_statements() throws Exception {
153153 // given
154154 normal.setLevel(DEBUG);
155- queryLogger = QueryLogger.builder(cluster)
155+ queryLogger = QueryLogger.builder(cluster())
156156 .withConstantThreshold(Long.MAX_VALUE)
157157 .build();
158- cluster.register(queryLogger);
158+ cluster().register(queryLogger);
159159 String query = "SELECT * FROM test where pk = ?";
160- PreparedStatement ps = session.prepare(query);
160+ PreparedStatement ps = session().prepare(query);
161161 BoundStatement bs = ps.bind(42);
162- session.execute(bs);
162+ session().execute(bs);
163163 // then
164164 String line = normalAppender.waitAndGet(10000);
165165 assertThat(line)
@@ -174,20 +174,20 @@
174174 public void should_log_batch_statements() throws Exception {
175175 // given
176176 normal.setLevel(DEBUG);
177- queryLogger = QueryLogger.builder(cluster)
177+ queryLogger = QueryLogger.builder(cluster())
178178 .withConstantThreshold(Long.MAX_VALUE)
179179 .withMaxQueryStringLength(Integer.MAX_VALUE)
180180 .build();
181- cluster.register(queryLogger);
181+ cluster().register(queryLogger);
182182 // when
183183 String query1 = "INSERT INTO test (pk) VALUES (?)";
184184 String query2 = "UPDATE test SET c_int = ? WHERE pk = 42";
185- PreparedStatement ps1 = session.prepare(query1);
186- PreparedStatement ps2 = session.prepare(query2);
185+ PreparedStatement ps1 = session().prepare(query1);
186+ PreparedStatement ps2 = session().prepare(query2);
187187 BatchStatement batch = new BatchStatement();
188188 batch.add(ps1.bind(42));
189189 batch.add(ps2.bind(1234));
190- session.execute(batch);
190+ session().execute(batch);
191191 // then
192192 String line = normalAppender.waitAndGet(10000);
193193 assertThat(line)
@@ -205,20 +205,20 @@
205205 public void should_log_unlogged_batch_statements() throws Exception {
206206 // given
207207 normal.setLevel(DEBUG);
208- queryLogger = QueryLogger.builder(cluster)
208+ queryLogger = QueryLogger.builder(cluster())
209209 .withConstantThreshold(Long.MAX_VALUE)
210210 .withMaxQueryStringLength(Integer.MAX_VALUE)
211211 .build();
212- cluster.register(queryLogger);
212+ cluster().register(queryLogger);
213213 // when
214214 String query1 = "INSERT INTO test (pk) VALUES (?)";
215215 String query2 = "UPDATE test SET c_int = ? WHERE pk = 42";
216- PreparedStatement ps1 = session.prepare(query1);
217- PreparedStatement ps2 = session.prepare(query2);
216+ PreparedStatement ps1 = session().prepare(query1);
217+ PreparedStatement ps2 = session().prepare(query2);
218218 BatchStatement batch = new BatchStatement(UNLOGGED);
219219 batch.add(ps1.bind(42));
220220 batch.add(ps2.bind(1234));
221- session.execute(batch);
221+ session().execute(batch);
222222 // then
223223 String line = normalAppender.waitAndGet(10000);
224224 assertThat(line)
@@ -235,25 +235,25 @@
235235 @CassandraVersion(major = 2.0)
236236 public void should_log_counter_batch_statements() throws Exception {
237237 // Create a special table for testing with counters.
238- session.execute(
238+ session().execute(
239239 "CREATE TABLE IF NOT EXISTS counter_test (pk int PRIMARY KEY, c_count COUNTER, c_count2 COUNTER)");
240240
241241 // given
242242 normal.setLevel(DEBUG);
243- queryLogger = QueryLogger.builder(cluster)
243+ queryLogger = QueryLogger.builder(cluster())
244244 .withConstantThreshold(Long.MAX_VALUE)
245245 .withMaxQueryStringLength(Integer.MAX_VALUE)
246246 .build();
247- cluster.register(queryLogger);
247+ cluster().register(queryLogger);
248248 // when
249249 String query1 = "UPDATE counter_test SET c_count = c_count + ? WHERE pk = 42";
250250 String query2 = "UPDATE counter_test SET c_count2 = c_count2 + ? WHERE pk = 42";
251- PreparedStatement ps1 = session.prepare(query1);
252- PreparedStatement ps2 = session.prepare(query2);
251+ PreparedStatement ps1 = session().prepare(query1);
252+ PreparedStatement ps2 = session().prepare(query2);
253253 BatchStatement batch = new BatchStatement(COUNTER);
254254 batch.add(ps1.bind(1234L));
255255 batch.add(ps2.bind(5678L));
256- session.execute(batch);
256+ session().execute(batch);
257257 // then
258258 String line = normalAppender.waitAndGet(10000);
259259 assertThat(line)
@@ -347,16 +347,16 @@
347347 public void should_log_normal_queries() throws Exception {
348348 // given
349349 normal.setLevel(DEBUG);
350- queryLogger = QueryLogger.builder(cluster)
350+ queryLogger = QueryLogger.builder(cluster())
351351 .withConstantThreshold(Long.MAX_VALUE)
352352 .withMaxQueryStringLength(Integer.MAX_VALUE)
353353 .build();
354- cluster.register(queryLogger);
354+ cluster().register(queryLogger);
355355 // when
356356 String query = "SELECT * FROM test where pk = ?";
357- PreparedStatement ps = session.prepare(query);
357+ PreparedStatement ps = session().prepare(query);
358358 BoundStatement bs = ps.bind(42);
359- session.execute(bs);
359+ session().execute(bs);
360360 // then
361361 String line = normalAppender.waitAndGet(10000);
362362 assertThat(line)
@@ -375,18 +375,18 @@
375375 public void should_log_non_null_named_parameter() throws Exception {
376376 // given
377377 normal.setLevel(TRACE);
378- queryLogger = QueryLogger.builder(cluster)
378+ queryLogger = QueryLogger.builder(cluster())
379379 .withConstantThreshold(Long.MAX_VALUE)
380380 .withMaxQueryStringLength(Integer.MAX_VALUE)
381381 .build();
382- cluster.register(queryLogger);
382+ cluster().register(queryLogger);
383383 // when
384384 String query = "UPDATE test SET c_text = :param1 WHERE pk = :param2";
385- PreparedStatement ps = session.prepare(query);
385+ PreparedStatement ps = session().prepare(query);
386386 BoundStatement bs = ps.bind();
387387 bs.setString("param1", "foo");
388388 bs.setInt("param2", 42);
389- session.execute(bs);
389+ session().execute(bs);
390390 // then
391391 String line = normalAppender.waitAndGet(10000);
392392 assertThat(line)
@@ -401,15 +401,15 @@
401401 public void should_log_non_null_positional_parameter() throws Exception {
402402 // given
403403 normal.setLevel(TRACE);
404- queryLogger = QueryLogger.builder(cluster).build();
405- cluster.register(queryLogger);
404+ queryLogger = QueryLogger.builder(cluster()).build();
405+ cluster().register(queryLogger);
406406 // when
407407 String query = "UPDATE test SET c_text = ? WHERE pk = ?";
408- PreparedStatement ps = session.prepare(query);
408+ PreparedStatement ps = session().prepare(query);
409409 BoundStatement bs = ps.bind();
410410 bs.setString("c_text", "foo");
411411 bs.setInt("pk", 42);
412- session.execute(bs);
412+ session().execute(bs);
413413 // then
414414 String line = normalAppender.waitAndGet(10000);
415415 assertThat(line)
@@ -424,15 +424,15 @@
424424 public void should_log_null_parameter() throws Exception {
425425 // given
426426 normal.setLevel(TRACE);
427- queryLogger = QueryLogger.builder(cluster).build();
428- cluster.register(queryLogger);
427+ queryLogger = QueryLogger.builder(cluster()).build();
428+ cluster().register(queryLogger);
429429 // when
430430 String query = "UPDATE test SET c_text = ? WHERE pk = ?";
431- PreparedStatement ps = session.prepare(query);
431+ PreparedStatement ps = session().prepare(query);
432432 BoundStatement bs = ps.bind();
433433 bs.setString("c_text", null);
434434 bs.setInt("pk", 42);
435- session.execute(bs);
435+ session().execute(bs);
436436 // then
437437 String line = normalAppender.waitAndGet(10000);
438438 assertThat(line)
@@ -448,15 +448,15 @@
448448 public void should_log_bound_statement_parameters_inside_batch_statement() throws Exception {
449449 // given
450450 normal.setLevel(TRACE);
451- queryLogger = QueryLogger.builder(cluster).build();
452- cluster.register(queryLogger);
451+ queryLogger = QueryLogger.builder(cluster()).build();
452+ cluster().register(queryLogger);
453453 // when
454454 String query1 = "UPDATE test SET c_text = ? WHERE pk = ?";
455455 String query2 = "UPDATE test SET c_int = ? WHERE pk = ?";
456456 BatchStatement batch = new BatchStatement();
457- batch.add(session.prepare(query1).bind("foo", 42));
458- batch.add(session.prepare(query2).bind(12345, 43));
459- session.execute(batch);
457+ batch.add(session().prepare(query1).bind("foo", 42));
458+ batch.add(session().prepare(query2).bind(12345, 43));
459+ session().execute(batch);
460460 // then
461461 String line = normalAppender.waitAndGet(10000);
462462 assertThat(line)
@@ -475,15 +475,15 @@
475475 public void should_log_all_parameter_types() throws Exception {
476476 // given
477477 normal.setLevel(TRACE);
478- queryLogger = QueryLogger.builder(cluster)
478+ queryLogger = QueryLogger.builder(cluster())
479479 .withMaxParameterValueLength(Integer.MAX_VALUE)
480480 .build();
481- cluster.register(queryLogger);
481+ cluster().register(queryLogger);
482482 // when
483483 String query = "UPDATE test SET " + assignments + " WHERE pk = 42";
484- PreparedStatement ps = session.prepare(query);
484+ PreparedStatement ps = session().prepare(query);
485485 BoundStatement bs = ps.bind(values.toArray());
486- session.execute(bs);
486+ session().execute(bs);
487487 // then
488488 String line = normalAppender.waitAndGet(10000);
489489 assertThat(line)
@@ -501,13 +501,13 @@
501501 public void should_truncate_query_when_max_length_exceeded() throws Exception {
502502 // given
503503 normal.setLevel(DEBUG);
504- queryLogger = QueryLogger.builder(cluster)
504+ queryLogger = QueryLogger.builder(cluster())
505505 .withMaxQueryStringLength(5)
506506 .build();
507- cluster.register(queryLogger);
507+ cluster().register(queryLogger);
508508 // when
509509 String query = "SELECT * FROM test WHERE pk = 42";
510- session.execute(query);
510+ session().execute(query);
511511 // then
512512 String line = normalAppender.waitAndGet(10000);
513513 assertThat(line)
@@ -522,17 +522,17 @@
522522 public void should_show_total_statements_for_batches_even_if_query_truncated() throws Exception {
523523 // given
524524 normal.setLevel(DEBUG);
525- queryLogger = QueryLogger.builder(cluster)
525+ queryLogger = QueryLogger.builder(cluster())
526526 .withMaxQueryStringLength(5)
527527 .build();
528- cluster.register(queryLogger);
528+ cluster().register(queryLogger);
529529 // when
530530 String query1 = "UPDATE test SET c_text = ? WHERE pk = ?";
531531 String query2 = "UPDATE test SET c_int = ? WHERE pk = ?";
532532 BatchStatement batch = new BatchStatement();
533- batch.add(session.prepare(query1).bind("foo", 42));
534- batch.add(session.prepare(query2).bind(12345, 43));
535- session.execute(batch);
533+ batch.add(session().prepare(query1).bind("foo", 42));
534+ batch.add(session().prepare(query2).bind(12345, 43));
535+ session().execute(batch);
536536 // then
537537 String line = normalAppender.waitAndGet(10000);
538538 assertThat(line)
@@ -548,13 +548,13 @@
548548 public void should_not_truncate_query_when_max_length_unlimited() throws Exception {
549549 // given
550550 normal.setLevel(DEBUG);
551- queryLogger = QueryLogger.builder(cluster)
551+ queryLogger = QueryLogger.builder(cluster())
552552 .withMaxQueryStringLength(-1)
553553 .build();
554- cluster.register(queryLogger);
554+ cluster().register(queryLogger);
555555 // when
556556 String query = "SELECT * FROM test WHERE pk = 42";
557- session.execute(query);
557+ session().execute(query);
558558 // then
559559 String line = normalAppender.waitAndGet(10000);
560560 assertThat(line)
@@ -569,17 +569,17 @@
569569 public void should_truncate_parameter_when_max_length_exceeded() throws Exception {
570570 // given
571571 normal.setLevel(TRACE);
572- queryLogger = QueryLogger.builder(cluster)
572+ queryLogger = QueryLogger.builder(cluster())
573573 .withMaxParameterValueLength(5)
574574 .build();
575- cluster.register(queryLogger);
575+ cluster().register(queryLogger);
576576 // when
577577 String query = "UPDATE test SET c_int = ? WHERE pk = ?";
578- PreparedStatement ps = session.prepare(query);
578+ PreparedStatement ps = session().prepare(query);
579579 BoundStatement bs = ps.bind();
580580 bs.setInt("c_int", 123456);
581581 bs.setInt("pk", 42);
582- session.execute(bs);
582+ session().execute(bs);
583583 // then
584584 String line = normalAppender.waitAndGet(10000);
585585 assertThat(line)
@@ -593,17 +593,17 @@
593593 public void should_truncate_blob_parameter_when_max_length_exceeded() throws Exception {
594594 // given
595595 normal.setLevel(TRACE);
596- queryLogger = QueryLogger.builder(cluster)
596+ queryLogger = QueryLogger.builder(cluster())
597597 .withMaxParameterValueLength(6)
598598 .build();
599- cluster.register(queryLogger);
599+ cluster().register(queryLogger);
600600 // when
601601 String query = "UPDATE test SET c_blob = ? WHERE pk = ?";
602- PreparedStatement ps = session.prepare(query);
602+ PreparedStatement ps = session().prepare(query);
603603 BoundStatement bs = ps.bind();
604604 bs.setBytes("c_blob", ByteBuffer.wrap(Bytes.toArray(Lists.newArrayList(1, 2, 3))));
605605 bs.setInt("pk", 42);
606- session.execute(bs);
606+ session().execute(bs);
607607 // then
608608 String line = normalAppender.waitAndGet(10000);
609609 assertThat(line)
@@ -617,17 +617,17 @@
617617 public void should_not_truncate_parameter_when_max_length_unlimited() throws Exception {
618618 // given
619619 normal.setLevel(TRACE);
620- queryLogger = QueryLogger.builder(cluster)
620+ queryLogger = QueryLogger.builder(cluster())
621621 .withMaxParameterValueLength(-1)
622622 .build();
623- cluster.register(queryLogger);
623+ cluster().register(queryLogger);
624624 // when
625625 String query = "UPDATE test SET c_int = ? WHERE pk = ?";
626- PreparedStatement ps = session.prepare(query);
626+ PreparedStatement ps = session().prepare(query);
627627 BoundStatement bs = ps.bind();
628628 bs.setInt("c_int", 123456);
629629 bs.setInt("pk", 42);
630- session.execute(bs);
630+ session().execute(bs);
631631 // then
632632 String line = normalAppender.waitAndGet(10000);
633633 assertThat(line)
@@ -641,17 +641,17 @@
641641 public void should_not_log_exceeding_number_of_parameters() throws Exception {
642642 // given
643643 normal.setLevel(TRACE);
644- queryLogger = QueryLogger.builder(cluster)
644+ queryLogger = QueryLogger.builder(cluster())
645645 .withMaxLoggedParameters(1)
646646 .build();
647- cluster.register(queryLogger);
647+ cluster().register(queryLogger);
648648 // when
649649 String query = "UPDATE test SET c_int = ? WHERE pk = ?";
650- PreparedStatement ps = session.prepare(query);
650+ PreparedStatement ps = session().prepare(query);
651651 BoundStatement bs = ps.bind();
652652 bs.setInt("c_int", 123456);
653653 bs.setInt("pk", 42);
654- session.execute(bs);
654+ session().execute(bs);
655655 // then
656656 String line = normalAppender.waitAndGet(10000);
657657 assertThat(line)
@@ -667,17 +667,17 @@
667667 public void should_not_log_exceeding_number_of_parameters_in_batch_statement() throws Exception {
668668 // given
669669 normal.setLevel(TRACE);
670- queryLogger = QueryLogger.builder(cluster)
670+ queryLogger = QueryLogger.builder(cluster())
671671 .withMaxLoggedParameters(1)
672672 .build();
673- cluster.register(queryLogger);
673+ cluster().register(queryLogger);
674674 // when
675675 String query1 = "UPDATE test SET c_text = ? WHERE pk = ?";
676676 String query2 = "UPDATE test SET c_int = ? WHERE pk = ?";
677677 BatchStatement batch = new BatchStatement();
678- batch.add(session.prepare(query1).bind("foo", 42));
679- batch.add(session.prepare(query2).bind(12345, 43));
680- session.execute(batch);
678+ batch.add(session().prepare(query1).bind("foo", 42));
679+ batch.add(session().prepare(query2).bind(12345, 43));
680+ session().execute(batch);
681681 // then
682682 String line = normalAppender.waitAndGet(10000);
683683 assertThat(line)
@@ -696,17 +696,17 @@
696696 public void should_log_all_parameters_when_max_unlimited() throws Exception {
697697 // given
698698 normal.setLevel(TRACE);
699- queryLogger = QueryLogger.builder(cluster)
699+ queryLogger = QueryLogger.builder(cluster())
700700 .withMaxLoggedParameters(-1)
701701 .build();
702- cluster.register(queryLogger);
702+ cluster().register(queryLogger);
703703 // when
704704 String query = "UPDATE test SET c_int = ? WHERE pk = ?";
705- PreparedStatement ps = session.prepare(query);
705+ PreparedStatement ps = session().prepare(query);
706706 BoundStatement bs = ps.bind();
707707 bs.setInt("c_int", 123456);
708708 bs.setInt("pk", 42);
709- session.execute(bs);
709+ session().execute(bs);
710710 // then
711711 String line = normalAppender.waitAndGet(10000);
712712 assertThat(line)
@@ -717,8 +717,8 @@
717717 }
718718
719719 @Override
720- public List<String> createTestFixtures() {
721- return Lists.newArrayList("CREATE TABLE test (pk int PRIMARY KEY, " + definitions + ")");
720+ public void onTestContextInitialized() {
721+ execute("CREATE TABLE test (pk int PRIMARY KEY, " + definitions + ")");
722722 }
723723
724724 }
modified driver-core/src/test/java/com/datastax/driver/core/QueryTimestampTest.java +25 −28
@@ -18,12 +18,9 @@
1818 import com.datastax.driver.core.Metrics.Errors;
1919 import com.datastax.driver.core.policies.DowngradingConsistencyRetryPolicy;
2020 import com.datastax.driver.core.utils.CassandraVersion;
21-import com.google.common.collect.Lists;
2221 import org.testng.annotations.BeforeMethod;
2322 import org.testng.annotations.Test;
2423
25-import java.util.Collection;
26-
2724 import static org.testng.Assert.assertEquals;
2825 import static org.testng.Assert.assertTrue;
2926
@@ -33,13 +30,13 @@
3330 @CassandraVersion(major = 2.1)
3431 public class QueryTimestampTest extends CCMTestsSupport {
3532
33+ private volatile long timestampFromGenerator;
34+
3635 @Override
37- public Collection<String> createTestFixtures() {
38- return Lists.newArrayList("CREATE TABLE foo (k int PRIMARY KEY, v int)");
36+ public void onTestContextInitialized() {
37+ execute("CREATE TABLE foo (k int PRIMARY KEY, v int)");
3938 }
4039
41- private volatile long timestampFromGenerator;
42-
4340 @Override
4441 public Cluster.Builder createClusterBuilder() {
4542 return Cluster.builder()
@@ -54,16 +51,16 @@
5451
5552 @BeforeMethod(groups = "short")
5653 public void cleanData() {
57- session.execute("TRUNCATE foo");
54+ session().execute("TRUNCATE foo");
5855 }
5956
6057 @Test(groups = "short")
6158 public void should_use_CQL_timestamp_over_anything_else() {
6259 timestampFromGenerator = 10;
6360 String query = "INSERT INTO foo (k, v) VALUES (1, 1) USING TIMESTAMP 20";
64- session.execute(new SimpleStatement(query).setDefaultTimestamp(30));
61+ session().execute(new SimpleStatement(query).setDefaultTimestamp(30));
6562
66- long writeTime = session.execute("SELECT writeTime(v) FROM foo WHERE k = 1").one().getLong(0);
63+ long writeTime = session().execute("SELECT writeTime(v) FROM foo WHERE k = 1").one().getLong(0);
6764 assertEquals(writeTime, 20);
6865 }
6966
@@ -71,9 +68,9 @@
7168 public void should_use_statement_timestamp_over_generator() {
7269 timestampFromGenerator = 10;
7370 String query = "INSERT INTO foo (k, v) VALUES (1, 1)";
74- session.execute(new SimpleStatement(query).setDefaultTimestamp(30));
71+ session().execute(new SimpleStatement(query).setDefaultTimestamp(30));
7572
76- long writeTime = session.execute("SELECT writeTime(v) FROM foo WHERE k = 1").one().getLong(0);
73+ long writeTime = session().execute("SELECT writeTime(v) FROM foo WHERE k = 1").one().getLong(0);
7774 assertEquals(writeTime, 30);
7875 }
7976
@@ -81,9 +78,9 @@
8178 public void should_use_generator_timestamp_if_none_other_specified() {
8279 timestampFromGenerator = 10;
8380 String query = "INSERT INTO foo (k, v) VALUES (1, 1)";
84- session.execute(query);
81+ session().execute(query);
8582
86- long writeTime = session.execute("SELECT writeTime(v) FROM foo WHERE k = 1").one().getLong(0);
83+ long writeTime = session().execute("SELECT writeTime(v) FROM foo WHERE k = 1").one().getLong(0);
8784 assertEquals(writeTime, 10);
8885 }
8986
@@ -92,9 +89,9 @@
9289 timestampFromGenerator = Long.MIN_VALUE;
9390 long clientTime = System.currentTimeMillis() * 1000;
9491 String query = "INSERT INTO foo (k, v) VALUES (1, 1)";
95- session.execute(query);
92+ session().execute(query);
9693
97- long writeTime = session.execute("SELECT writeTime(v) FROM foo WHERE k = 1").one().getLong(0);
94+ long writeTime = session().execute("SELECT writeTime(v) FROM foo WHERE k = 1").one().getLong(0);
9895 assertTrue(writeTime >= clientTime);
9996 }
10097
@@ -104,10 +101,10 @@
104101 batch.add(new SimpleStatement("INSERT INTO foo (k, v) VALUES (1, 1)"));
105102 batch.add(new SimpleStatement("INSERT INTO foo (k, v) VALUES (2, 1) USING TIMESTAMP 20"));
106103 batch.setDefaultTimestamp(10);
107- session.execute(batch);
104+ session().execute(batch);
108105
109- long writeTime1 = session.execute("SELECT writeTime(v) FROM foo WHERE k = 1").one().getLong(0);
110- long writeTime2 = session.execute("SELECT writeTime(v) FROM foo WHERE k = 2").one().getLong(0);
106+ long writeTime1 = session().execute("SELECT writeTime(v) FROM foo WHERE k = 1").one().getLong(0);
107+ long writeTime2 = session().execute("SELECT writeTime(v) FROM foo WHERE k = 2").one().getLong(0);
111108 assertEquals(writeTime1, 10);
112109 assertEquals(writeTime2, 20);
113110 }
@@ -118,10 +115,10 @@
118115 BatchStatement batch = new BatchStatement();
119116 batch.add(new SimpleStatement("INSERT INTO foo (k, v) VALUES (1, 1)"));
120117 batch.add(new SimpleStatement("INSERT INTO foo (k, v) VALUES (2, 1) USING TIMESTAMP 20"));
121- session.execute(batch);
118+ session().execute(batch);
122119
123- long writeTime1 = session.execute("SELECT writeTime(v) FROM foo WHERE k = 1").one().getLong(0);
124- long writeTime2 = session.execute("SELECT writeTime(v) FROM foo WHERE k = 2").one().getLong(0);
120+ long writeTime1 = session().execute("SELECT writeTime(v) FROM foo WHERE k = 1").one().getLong(0);
121+ long writeTime2 = session().execute("SELECT writeTime(v) FROM foo WHERE k = 2").one().getLong(0);
125122 assertEquals(writeTime1, 10);
126123 assertEquals(writeTime2, 20);
127124 }
@@ -133,10 +130,10 @@
133130 BatchStatement batch = new BatchStatement();
134131 batch.add(new SimpleStatement("INSERT INTO foo (k, v) VALUES (1, 1)"));
135132 batch.add(new SimpleStatement("INSERT INTO foo (k, v) VALUES (2, 1) USING TIMESTAMP 20"));
136- session.execute(batch);
133+ session().execute(batch);
137134
138- long writeTime1 = session.execute("SELECT writeTime(v) FROM foo WHERE k = 1").one().getLong(0);
139- long writeTime2 = session.execute("SELECT writeTime(v) FROM foo WHERE k = 2").one().getLong(0);
135+ long writeTime1 = session().execute("SELECT writeTime(v) FROM foo WHERE k = 1").one().getLong(0);
136+ long writeTime2 = session().execute("SELECT writeTime(v) FROM foo WHERE k = 2").one().getLong(0);
140137 assertTrue(writeTime1 >= clientTime);
141138 assertEquals(writeTime2, 20);
142139 }
@@ -149,12 +146,12 @@
149146 // will retry it at ONE.
150147 statement.setConsistencyLevel(ConsistencyLevel.TWO);
151148
152- session.execute(statement);
149+ session().execute(statement);
153150
154- Errors metrics = session.getCluster().getMetrics().getErrorMetrics();
151+ Errors metrics = session().getCluster().getMetrics().getErrorMetrics();
155152 assertEquals(metrics.getRetriesOnUnavailable().getCount(), 1);
156153
157- long writeTime = session.execute("SELECT writeTime(v) FROM foo WHERE k = 1").one().getLong(0);
154+ long writeTime = session().execute("SELECT writeTime(v) FROM foo WHERE k = 1").one().getLong(0);
158155 assertEquals(writeTime, 10);
159156 }
160157 }
modified driver-core/src/test/java/com/datastax/driver/core/RecommissionedNodeTest.java +8 −16
@@ -45,9 +45,8 @@
4545
4646 @Test(groups = "long")
4747 public void should_ignore_recommissioned_node_on_reconnection_attempt() throws Exception {
48- mainCcmBuilder = CCMBridge.builder().withNodes(3).notStarted();
48+ mainCcmBuilder = CCMBridge.builder().withNodes(3);
4949 mainCcm = CCMCache.get(mainCcmBuilder);
50- mainCcm.start();
5150
5251 // node1 will be our "recommissioned" node, for now we just stop it so that it stays in the peers table.
5352 mainCcm.stop(1);
@@ -67,9 +66,8 @@
6766 .withStoragePort(mainCcm.getStoragePort())
6867 .withThriftPort(mainCcm.getThriftPort())
6968 .withBinaryPort(mainCcm.getBinaryPort())
70- .withNodes(1).notStarted();
69+ .withNodes(1);
7170 otherCcm = CCMCache.get(otherCcmBuilder);
72- otherCcm.start();
7371 otherCcm.waitForUp(1);
7472
7573 // Give the driver the time to notice the node is back up and try to connect to it.
@@ -80,9 +78,8 @@
8078
8179 @Test(groups = "long")
8280 public void should_ignore_recommissioned_node_on_control_connection_reconnect() throws Exception {
83- mainCcmBuilder = CCMBridge.builder().withNodes(2).notStarted();
81+ mainCcmBuilder = CCMBridge.builder().withNodes(2);
8482 mainCcm = CCMCache.get(mainCcmBuilder);
85- mainCcm.start();
8683 mainCcm.stop(1);
8784 mainCcm.waitForDown(1);
8885
@@ -99,9 +96,8 @@
9996 .withStoragePort(mainCcm.getStoragePort())
10097 .withThriftPort(mainCcm.getThriftPort())
10198 .withBinaryPort(mainCcm.getBinaryPort())
102- .withNodes(1).notStarted();
99+ .withNodes(1);
103100 otherCcm = CCMCache.get(otherCcmBuilder);
104- otherCcm.start();
105101 otherCcm.waitForUp(1);
106102
107103 // Stop node2, the control connection gets defunct
@@ -115,9 +111,8 @@
115111 @Test(groups = "long")
116112 public void should_ignore_recommissioned_node_on_session_init() throws Exception {
117113 // Simulate the bug before starting the cluster
118- mainCcmBuilder = CCMBridge.builder().withNodes(2).notStarted();
114+ mainCcmBuilder = CCMBridge.builder().withNodes(2);
119115 mainCcm = CCMCache.get(mainCcmBuilder);
120- mainCcm.start();
121116 mainCcm.stop(1);
122117 mainCcm.waitForDown(1);
123118
@@ -125,9 +120,8 @@
125120 .withStoragePort(mainCcm.getStoragePort())
126121 .withThriftPort(mainCcm.getThriftPort())
127122 .withBinaryPort(mainCcm.getBinaryPort())
128- .withNodes(1).notStarted();
123+ .withNodes(1);
129124 otherCcm = CCMCache.get(otherCcmBuilder);
130- otherCcm.start();
131125 otherCcm.waitForUp(1);
132126
133127 // Start the driver, it should only connect to node 2
@@ -154,9 +148,8 @@
154148 @CassandraVersion(major = 2.0)
155149 public void should_ignore_node_that_does_not_support_protocol_version_on_session_init() throws Exception {
156150 // Simulate the bug before starting the cluster
157- mainCcmBuilder = CCMBridge.builder().withNodes(2).notStarted();
151+ mainCcmBuilder = CCMBridge.builder().withNodes(2);
158152 mainCcm = CCMCache.get(mainCcmBuilder);
159- mainCcm.start();
160153 mainCcm.stop(1);
161154 mainCcm.waitForDown(1);
162155
@@ -164,9 +157,8 @@
164157 .withStoragePort(mainCcm.getStoragePort())
165158 .withThriftPort(mainCcm.getThriftPort())
166159 .withBinaryPort(mainCcm.getBinaryPort())
167- .withVersion("1.2.19").notStarted();
160+ .withVersion("1.2.19");
168161 otherCcm = CCMCache.get(otherCcmBuilder);
169- otherCcm.start();
170162 otherCcm.waitForUp(1);
171163
172164 // Start the driver, it should only connect to node 2
modified driver-core/src/test/java/com/datastax/driver/core/ReconnectionPolicyTest.java +8 −8
@@ -46,12 +46,12 @@
4646 public void exponentialReconnectionPolicyTest() throws Throwable {
4747
4848 // Ensure that ExponentialReconnectionPolicy is what we should be testing
49- if (!(cluster.getConfiguration().getPolicies().getReconnectionPolicy() instanceof ExponentialReconnectionPolicy)) {
49+ if (!(cluster().getConfiguration().getPolicies().getReconnectionPolicy() instanceof ExponentialReconnectionPolicy)) {
5050 fail("Set policy does not match retrieved policy.");
5151 }
5252
5353 // Test basic getters
54- ExponentialReconnectionPolicy reconnectionPolicy = (ExponentialReconnectionPolicy) cluster.getConfiguration().getPolicies().getReconnectionPolicy();
54+ ExponentialReconnectionPolicy reconnectionPolicy = (ExponentialReconnectionPolicy) cluster().getConfiguration().getPolicies().getReconnectionPolicy();
5555 assertTrue(reconnectionPolicy.getBaseDelayMs() == 2 * 1000);
5656 assertTrue(reconnectionPolicy.getMaxDelayMs() == 5 * 60 * 1000);
5757
@@ -112,12 +112,12 @@
112112 public void constantReconnectionPolicyTest() throws Throwable {
113113
114114 // Ensure that ConstantReconnectionPolicy is what we should be testing
115- if (!(cluster.getConfiguration().getPolicies().getReconnectionPolicy() instanceof ConstantReconnectionPolicy)) {
115+ if (!(cluster().getConfiguration().getPolicies().getReconnectionPolicy() instanceof ConstantReconnectionPolicy)) {
116116 fail("Set policy does not match retrieved policy.");
117117 }
118118
119119 // Test basic getters
120- ConstantReconnectionPolicy reconnectionPolicy = (ConstantReconnectionPolicy) cluster.getConfiguration().getPolicies().getReconnectionPolicy();
120+ ConstantReconnectionPolicy reconnectionPolicy = (ConstantReconnectionPolicy) cluster().getConfiguration().getPolicies().getReconnectionPolicy();
121121 assertTrue(reconnectionPolicy.getConstantDelayMs() == 10 * 1000);
122122
123123 // Test erroneous instantiations
@@ -153,7 +153,7 @@
153153 // Ensure a basic test works
154154 assertQueried(TestUtils.IP_PREFIX + '1', 12);
155155 resetCoordinators();
156- ccm.forceStop(1);
156+ ccm().forceStop(1);
157157
158158 // Start timing and ensure that the node is down
159159 long startTime = 0;
@@ -172,7 +172,7 @@
172172
173173 // Restart node at restartTime
174174 if (!restarted && thisTime - startTime > restartTime) {
175- ccm.start(1);
175+ ccm().start(1);
176176 restarted = true;
177177 }
178178
@@ -197,7 +197,7 @@
197197 resetCoordinators();
198198
199199 // Ensure the reconnection times reset
200- ccm.forceStop(1);
200+ ccm().forceStop(1);
201201
202202 // Start timing and ensure that the node is down
203203 startTime = 0;
@@ -215,7 +215,7 @@
215215
216216 // Restart node at restartTime
217217 if (!restarted && thisTime - startTime > restartTime) {
218- ccm.start(1);
218+ ccm().start(1);
219219 restarted = true;
220220 }
221221
modified driver-core/src/test/java/com/datastax/driver/core/ReconnectionTest.java +31 −31
@@ -50,8 +50,8 @@
5050 @Test(groups = "long")
5151 public void should_reconnect_after_full_connectivity_loss() throws InterruptedException {
5252 Cluster cluster = register(Cluster.builder()
53- .addContactPointsWithPorts(ccm.addressOfNode(1))
54- .withPort(ccm.getBinaryPort())
53+ .addContactPoints(getContactPoints().get(0))
54+ .withPort(ccm().getBinaryPort())
5555 .withReconnectionPolicy(new ConstantReconnectionPolicy(reconnectionDelayMillis))
5656 .build());
5757 cluster.connect();
@@ -60,12 +60,12 @@
6060
6161 // Stop all nodes. We won't get notifications anymore, so the only mechanism to
6262 // reconnect is the background reconnection attempts.
63- ccm.stop(2);
64- ccm.stop(1);
63+ ccm().stop(2);
64+ ccm().stop(1);
6565
66- ccm.waitForDown(2);
67- ccm.start(2);
68- ccm.waitForUp(2);
66+ ccm().waitForDown(2);
67+ ccm().start(2);
68+ ccm().waitForUp(2);
6969
7070 assertThat(cluster).host(2).comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS * 2, SECONDS);
7171
@@ -83,14 +83,14 @@
8383 public void should_keep_reconnecting_on_authentication_error() throws InterruptedException {
8484 // For C* 1.2, sleep before attempting to connect as there is a small delay between
8585 // user being created.
86- if (ccm.getVersion().getMajor() < 2) {
86+ if (ccm().getVersion().getMajor() < 2) {
8787 Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
8888 }
8989 CountingReconnectionPolicy reconnectionPolicy = new CountingReconnectionPolicy(new ConstantReconnectionPolicy(reconnectionDelayMillis));
9090 CountingAuthProvider authProvider = new CountingAuthProvider("cassandra", "cassandra");
9191 Cluster cluster = register(Cluster.builder()
92- .addContactPointsWithPorts(ccm.addressOfNode(1))
93- .withPort(ccm.getBinaryPort())
92+ .addContactPointsWithPorts(ccm().addressOfNode(1))
93+ .withPort(ccm().getBinaryPort())
9494 // Start with the correct auth so that we can initialize the server
9595 .withAuthProvider(authProvider)
9696 .withReconnectionPolicy(reconnectionPolicy)
@@ -100,11 +100,11 @@
100100 assertThat(cluster).usesControlHost(1);
101101
102102 // Stop the server, set wrong credentials and restart
103- ccm.stop(1);
104- ccm.waitForDown(1);
103+ ccm().stop(1);
104+ ccm().waitForDown(1);
105105 authProvider.setPassword("wrongPassword");
106- ccm.start(1);
107- ccm.waitForUp(1);
106+ ccm().start(1);
107+ ccm().waitForUp(1);
108108
109109 // Wait a few iterations to ensure that our authProvider has returned the wrong credentials at least once
110110 // NB: authentication errors show up in the logs
@@ -130,13 +130,13 @@
130130 CountingReconnectionPolicy reconnectionPolicy = new CountingReconnectionPolicy(new ConstantReconnectionPolicy(reconnectionDelayMillis));
131131
132132 Cluster cluster = register(Cluster.builder()
133- .addContactPointsWithPorts(ccm.addressOfNode(1))
134- .withPort(ccm.getBinaryPort())
133+ .addContactPointsWithPorts(ccm().addressOfNode(1))
134+ .withPort(ccm().getBinaryPort())
135135 .withReconnectionPolicy(reconnectionPolicy).build());
136136 cluster.connect();
137137
138138 // Stop a node and cancel the reconnection attempts to it
139- ccm.stop(2);
139+ ccm().stop(2);
140140 Host host2 = TestUtils.findHost(cluster, 2);
141141 host2.getReconnectionAttemptFuture().cancel(false);
142142
@@ -146,8 +146,8 @@
146146 assertThat(reconnectionPolicy.count.get()).isEqualTo(initialCount);
147147
148148 // Restart the node, which will trigger an UP notification
149- ccm.start(2);
150- ccm.waitForUp(2);
149+ ccm().start(2);
150+ ccm().waitForUp(2);
151151
152152 // The driver should now see the node as UP again
153153 assertThat(cluster).host(2).comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS * 2, SECONDS);
@@ -158,8 +158,8 @@
158158 public void should_trigger_one_time_reconnect() throws InterruptedException, IOException {
159159 TogglabePolicy loadBalancingPolicy = new TogglabePolicy(new RoundRobinPolicy());
160160 Cluster cluster = register(Cluster.builder()
161- .addContactPointsWithPorts(ccm.addressOfNode(1))
162- .withPort(ccm.getBinaryPort())
161+ .addContactPointsWithPorts(ccm().addressOfNode(1))
162+ .withPort(ccm().getBinaryPort())
163163 .withLoadBalancingPolicy(loadBalancingPolicy)
164164 .withReconnectionPolicy(new ConstantReconnectionPolicy(reconnectionDelayMillis))
165165 .build());
@@ -170,8 +170,8 @@
170170 loadBalancingPolicy.returnEmptyQueryPlan = true;
171171
172172 // Stop the node, ignore it and cancel reconnection attempts to it
173- ccm.stop(1);
174- ccm.waitForDown(1);
173+ ccm().stop(1);
174+ ccm().waitForDown(1);
175175 assertThat(cluster).host(1).goesDownWithin(20, SECONDS);
176176 Host host1 = TestUtils.findHost(cluster, 1);
177177 loadBalancingPolicy.setDistance(TestUtils.findHost(cluster, 1), HostDistance.IGNORED);
@@ -189,8 +189,8 @@
189189 // Restart the node (this will not trigger an UP notification thanks to our
190190 // hack to disable the control connection reconnects). The host should stay
191191 // down for the driver.
192- ccm.start(1);
193- ccm.waitForUp(1);
192+ ccm().start(1);
193+ ccm().waitForUp(1);
194194 assertThat(cluster).host(1).hasState(State.DOWN);
195195
196196 TimeUnit.SECONDS.sleep(Cluster.NEW_NODE_DELAY_SECONDS);
@@ -214,8 +214,8 @@
214214 // Spy SocketOptions.getKeepAlive to count how many connections were instantiated.
215215 SocketOptions socketOptions = spy(new SocketOptions());
216216 Cluster cluster = register(Cluster.builder()
217- .addContactPointsWithPorts(ccm.addressOfNode(1))
218- .withPort(ccm.getBinaryPort())
217+ .addContactPointsWithPorts(ccm().addressOfNode(1))
218+ .withPort(ccm().getBinaryPort())
219219 .withReconnectionPolicy(new ConstantReconnectionPolicy(5000))
220220 .withLoadBalancingPolicy(loadBalancingPolicy)
221221 .withSocketOptions(socketOptions)
@@ -235,14 +235,14 @@
235235 loadBalancingPolicy.returnEmptyQueryPlan = true;
236236
237237 // Stop the node and cancel the reconnection attempts to it
238- ccm.stop(1);
239- ccm.waitForDown(1);
238+ ccm().stop(1);
239+ ccm().waitForDown(1);
240240 assertThat(cluster).host(1).goesDownWithin(20, SECONDS);
241241 Host host1 = TestUtils.findHost(cluster, 1);
242242 host1.getReconnectionAttemptFuture().cancel(false);
243243
244- ccm.start(1);
245- ccm.waitForUp(1);
244+ ccm().start(1);
245+ ccm().waitForUp(1);
246246
247247 // Reset the spy and count the number of connections attempts for 1 reconnect
248248 reset(socketOptions);
modified driver-core/src/test/java/com/datastax/driver/core/RefreshConnectedHostTest.java +8 −8
@@ -41,9 +41,9 @@
4141 LimitingLoadBalancingPolicy loadBalancingPolicy = new LimitingLoadBalancingPolicy(new RoundRobinPolicy(), 2, 1);
4242
4343 PoolingOptions poolingOptions = Mockito.spy(new PoolingOptions());
44- cluster = register(Cluster.builder()
45- .addContactPointsWithPorts(ccm.addressOfNode(1))
46- .withPort(ccm.getBinaryPort())
44+ Cluster cluster = register(Cluster.builder()
45+ .addContactPoints(getContactPoints().get(0))
46+ .withPort(ccm().getBinaryPort())
4747 .withPoolingOptions(poolingOptions)
4848 .withLoadBalancingPolicy(loadBalancingPolicy)
4949 .withReconnectionPolicy(new ConstantReconnectionPolicy(1000))
@@ -63,9 +63,9 @@
6363 .isAtDistance(HostDistance.LOCAL);
6464
6565 // 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);
66+ ccm().add(3);
67+ ccm().start(3);
68+ ccm().waitForUp(3);
6969
7070 assertThat(cluster).host(1)
7171 .hasState(State.UP)
@@ -81,8 +81,8 @@
8181 assertThat(session).hasNoPoolFor(3);
8282
8383 // Kill host 2, host 3 should take its place
84- ccm.stop(2);
85- TestUtils.waitFor(TestUtils.ipOfNode(3), cluster);
84+ ccm().stop(2);
85+ TestUtils.waitForUp(TestUtils.ipOfNode(3), cluster);
8686
8787 assertThat(cluster).host(1)
8888 .hasState(State.UP)
modified driver-core/src/test/java/com/datastax/driver/core/SSLEncryptionTest.java +6 −6
@@ -74,8 +74,8 @@
7474 @Test(groups = "short", expectedExceptions = {NoHostAvailableException.class})
7575 public void should_not_connect_without_ssl_but_node_uses_ssl() throws Exception {
7676 Cluster cluster = register(Cluster.builder()
77- .addContactPointsWithPorts(this.getInitialContactPoints())
78- .withPort(ccm.getBinaryPort())
77+ .addContactPoints(getContactPoints())
78+ .withPort(ccm().getBinaryPort())
7979 .build());
8080 cluster.connect();
8181 }
@@ -93,15 +93,15 @@
9393 @Test(groups = "long")
9494 public void should_reconnect_with_ssl_on_node_up() throws Exception {
9595 Cluster cluster = register(Cluster.builder()
96- .addContactPointsWithPorts(this.getInitialContactPoints())
97- .withPort(ccm.getBinaryPort())
96+ .addContactPoints(getContactPoints())
97+ .withPort(ccm().getBinaryPort())
9898 .withSSL(getSSLOptions(Optional.of(DEFAULT_CLIENT_KEYSTORE_PATH), Optional.of(DEFAULT_CLIENT_TRUSTSTORE_PATH)))
9999 .build());
100100
101101 cluster.connect();
102102
103- ccm.stop(1);
104- ccm.start(1);
103+ ccm().stop(1);
104+ ccm().start(1);
105105
106106 assertThat(cluster).host(1).comesUpWithin(TestUtils.TEST_BASE_NODE_WAIT, TimeUnit.SECONDS);
107107 }
modified driver-core/src/test/java/com/datastax/driver/core/SSLTestBase.java +4 −4
@@ -41,8 +41,8 @@
4141 */
4242 protected void connectWithSSLOptions(SSLOptions sslOptions) throws Exception {
4343 Cluster cluster = register(Cluster.builder()
44- .addContactPointsWithPorts(this.getInitialContactPoints())
45- .withPort(ccm.getBinaryPort())
44+ .addContactPoints(getContactPoints())
45+ .withPort(ccm().getBinaryPort())
4646 .withSSL(sslOptions)
4747 .build());
4848 cluster.connect();
@@ -59,8 +59,8 @@
5959 */
6060 protected void connectWithSSL() throws Exception {
6161 Cluster cluster = register(Cluster.builder()
62- .addContactPointsWithPorts(this.getInitialContactPoints())
63- .withPort(ccm.getBinaryPort())
62+ .addContactPoints(getContactPoints())
63+ .withPort(ccm().getBinaryPort())
6464 .withSSL()
6565 .build());
6666 cluster.connect();
modified driver-core/src/test/java/com/datastax/driver/core/SchemaAgreementTest.java +9 −9
@@ -34,32 +34,32 @@
3434
3535 @Test(groups = "short")
3636 public void should_set_flag_on_successful_agreement() {
37- ProtocolOptions protocolOptions = cluster.getConfiguration().getProtocolOptions();
37+ ProtocolOptions protocolOptions = cluster().getConfiguration().getProtocolOptions();
3838 protocolOptions.maxSchemaAgreementWaitSeconds = 10;
39- ResultSet rs = session.execute(String.format(CREATE_TABLE, COUNTER.getAndIncrement()));
39+ ResultSet rs = session().execute(String.format(CREATE_TABLE, COUNTER.getAndIncrement()));
4040 assertThat(rs.getExecutionInfo().isSchemaInAgreement()).isTrue();
4141 }
4242
4343 @Test(groups = "short")
4444 public void should_set_flag_on_non_schema_altering_statement() {
45- ProtocolOptions protocolOptions = cluster.getConfiguration().getProtocolOptions();
45+ ProtocolOptions protocolOptions = cluster().getConfiguration().getProtocolOptions();
4646 protocolOptions.maxSchemaAgreementWaitSeconds = 10;
47- ResultSet rs = session.execute("select release_version from system.local");
47+ ResultSet rs = session().execute("select release_version from system.local");
4848 assertThat(rs.getExecutionInfo().isSchemaInAgreement()).isTrue();
4949 }
5050
5151 @Test(groups = "short")
5252 public void should_unset_flag_on_failed_agreement() {
5353 // Setting to 0 results in no query being set, so agreement fails
54- ProtocolOptions protocolOptions = cluster.getConfiguration().getProtocolOptions();
54+ ProtocolOptions protocolOptions = cluster().getConfiguration().getProtocolOptions();
5555 protocolOptions.maxSchemaAgreementWaitSeconds = 0;
56- ResultSet rs = session.execute(String.format(CREATE_TABLE, COUNTER.getAndIncrement()));
56+ ResultSet rs = session().execute(String.format(CREATE_TABLE, COUNTER.getAndIncrement()));
5757 assertThat(rs.getExecutionInfo().isSchemaInAgreement()).isFalse();
5858 }
5959
6060 @Test(groups = "short")
6161 public void should_check_agreement_through_cluster_metadata() {
62- Cluster controlCluster = register(TestUtils.buildControlCluster(cluster, ccm));
62+ Cluster controlCluster = register(TestUtils.buildControlCluster(cluster(), ccm()));
6363 Session controlSession = controlCluster.connect();
6464
6565 Row localRow = controlSession.execute("SELECT schema_version FROM system.local").one();
@@ -71,11 +71,11 @@
7171 assertThat(localVersion).isEqualTo(peerVersion);
7272
7373 // Now check the method under test:
74- assertThat(cluster.getMetadata().checkSchemaAgreement()).isTrue();
74+ assertThat(cluster().getMetadata().checkSchemaAgreement()).isTrue();
7575
7676 // Insert a fake version to simulate a disagreement:
7777 forceSchemaVersion(controlSession, peerAddress, UUIDs.random());
78- assertThat(cluster.getMetadata().checkSchemaAgreement()).isFalse();
78+ assertThat(cluster().getMetadata().checkSchemaAgreement()).isFalse();
7979
8080 forceSchemaVersion(controlSession, peerAddress, peerVersion);
8181 }
modified driver-core/src/test/java/com/datastax/driver/core/SchemaChangesCCTest.java +5 −5
@@ -56,15 +56,15 @@
5656 Cluster cluster = register(
5757 Cluster.builder()
5858 .withLoadBalancingPolicy(lbPolicy)
59- .addContactPointsWithPorts(ccm.addressOfNode(1))
60- .withPort(ccm.getBinaryPort())
59+ .addContactPointsWithPorts(ccm().addressOfNode(1))
60+ .withPort(ccm().getBinaryPort())
6161 .build());
6262 // Put cluster2 control connection on node 2 so it doesn't go down (to prevent noise for debugging).
6363 Cluster cluster2 = register(
6464 Cluster.builder()
6565 .withLoadBalancingPolicy(lbPolicy)
66- .addContactPointsWithPorts(ccm.addressOfNode(2))
67- .withPort(ccm.getBinaryPort())
66+ .addContactPointsWithPorts(ccm().addressOfNode(2))
67+ .withPort(ccm().getBinaryPort())
6868 .build());
6969 SchemaChangeListener listener = mock(SchemaChangeListener.class);
7070
@@ -93,7 +93,7 @@
9393 lbPolicy.returnEmptyQueryPlan = true;
9494
9595 // Stop node 1, which hosts the control connection.
96- ccm.stop(1);
96+ ccm().stop(1);
9797 assertThat(cluster).host(1).goesDownWithin(20, TimeUnit.SECONDS);
9898
9999 // Ensure control connection is down.
modified driver-core/src/test/java/com/datastax/driver/core/SchemaChangesTest.java +10 −5
@@ -24,6 +24,7 @@
2424 import org.testng.annotations.*;
2525
2626 import java.util.List;
27+import java.util.concurrent.TimeUnit;
2728
2829 import static com.datastax.driver.core.Assertions.assertThat;
2930 import static com.datastax.driver.core.Metadata.handleId;
@@ -45,7 +46,7 @@
4546 /**
4647 * The maximum time that the test will wait to check that listeners have been notified
4748 */
48- private static final int NOTIF_TIMEOUT_MS = 120000;
49+ private static final long NOTIF_TIMEOUT_MS = TimeUnit.MINUTES.toMillis(1);
4950
5051 Cluster cluster1;
5152 Cluster cluster2; // a second cluster to check that other clients also get notified
@@ -66,12 +67,14 @@
6667 @BeforeClass(groups = "short")
6768 public void setup() throws InterruptedException {
6869 Cluster.Builder builder = Cluster.builder()
69- .addContactPointsWithPorts(getInitialContactPoints())
70+ .addContactPoints(getContactPoints())
71+ .withPort(ccm().getBinaryPort())
7072 .withQueryOptions(nonDebouncingQueryOptions());
7173 cluster1 = builder.build();
7274 cluster2 = builder.build();
7375 schemaDisabledCluster = spy(Cluster.builder()
74- .addContactPointsWithPorts(getInitialContactPoints())
76+ .addContactPoints(getContactPoints())
77+ .withPort(ccm().getBinaryPort())
7578 .withClusterName("schema-disabled")
7679 .withQueryOptions(nonDebouncingQueryOptions()
7780 .setMetadataEnabled(false)
@@ -343,7 +346,8 @@
343346 @Test(groups = "short", expectedExceptions = IllegalStateException.class)
344347 public void should_throw_illegal_state_exception_on_newToken_with_metadata_disabled() {
345348 Cluster cluster = Cluster.builder()
346- .addContactPointsWithPorts(getInitialContactPoints())
349+ .addContactPoints(getContactPoints())
350+ .withPort(ccm().getBinaryPort())
347351 .withQueryOptions(nonDebouncingQueryOptions()
348352 .setMetadataEnabled(false)
349353 ).build();
@@ -367,7 +371,8 @@
367371 @Test(groups = "short", expectedExceptions = IllegalStateException.class)
368372 public void should_throw_illegal_state_exception_on_newTokenRange_with_metadata_disabled() {
369373 Cluster cluster = Cluster.builder()
370- .addContactPointsWithPorts(getInitialContactPoints())
374+ .addContactPoints(getContactPoints())
375+ .withPort(ccm().getBinaryPort())
371376 .withQueryOptions(nonDebouncingQueryOptions()
372377 .setMetadataEnabled(false)
373378 ).build();
modified driver-core/src/test/java/com/datastax/driver/core/SchemaRefreshDebouncerTest.java +20 −25
@@ -16,7 +16,6 @@
1616 package com.datastax.driver.core;
1717
1818 import org.mockito.ArgumentCaptor;
19-import org.testng.annotations.AfterMethod;
2019 import org.testng.annotations.BeforeMethod;
2120 import org.testng.annotations.Test;
2221
@@ -52,10 +51,11 @@
5251 queryOptions.setRefreshSchemaIntervalMillis(DEBOUNCE_TIME);
5352 queryOptions.setMaxPendingRefreshSchemaRequests(5);
5453 // Create a separate cluster that will receive the schema events on its control connection.
55- cluster2 = Cluster.builder()
56- .addContactPointsWithPorts(getInitialContactPoints())
54+ cluster2 = register(Cluster.builder()
55+ .addContactPoints(getContactPoints())
56+ .withPort(ccm().getBinaryPort())
5757 .withQueryOptions(queryOptions)
58- .build();
58+ .build());
5959 session2 = cluster2.connect();
6060
6161 // Create a spy of the Cluster's control connection and replace it with the spy.
@@ -70,11 +70,6 @@
7070 reset(controlConnection);
7171 }
7272
73- @AfterMethod(groups = "short")
74- public void beforeMethod() {
75- cluster2.close();
76- }
77-
7873 /**
7974 * Ensures that when a CREATED and UPDATED schema_change events are received on a control
8075 * connection for the same keyspace within {@link QueryOptions#getRefreshSchemaIntervalMillis()}
@@ -86,9 +81,9 @@
8681 */
8782 @Test(groups = "short")
8883 public void should_debounce_and_coalesce_create_and_alter_keyspace_into_refresh_keyspace() throws Exception {
89- String keyspace = "sdaccaak";
90- session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, 1));
91- session.execute(String.format("ALTER KEYSPACE %s WITH DURABLE_WRITES=false", keyspace));
84+ String keyspace = TestUtils.generateIdentifier("ks_");
85+ session().execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, 1));
86+ session().execute(String.format("ALTER KEYSPACE %s WITH DURABLE_WRITES=false", keyspace));
9287
9388 ArgumentCaptor<KeyspaceMetadata> captor = forClass(KeyspaceMetadata.class);
9489 verify(listener, timeout(DEBOUNCE_TIME * 2).only()).onKeyspaceAdded(captor.capture());
@@ -117,17 +112,17 @@
117112 */
118113 @Test(groups = "short")
119114 public void should_debounce_and_coalesce_create_keyspace_and_table_into_refresh_keyspace() throws Exception {
120- String keyspace = "sdacckt";
115+ String keyspace = TestUtils.generateIdentifier("ks_");
121116 String table = "tbl1";
122- session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, 1));
123- session.execute(String.format(CREATE_TABLE_SIMPLE_FORMAT, keyspace + "." + table));
117+ session().execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, 1));
118+ session().execute(String.format(CREATE_TABLE_SIMPLE_FORMAT, keyspace + "." + table));
124119
125120 ArgumentCaptor<KeyspaceMetadata> keyspaceCaptor = forClass(KeyspaceMetadata.class);
126121 verify(listener, timeout(DEBOUNCE_TIME * 2).times(1)).onKeyspaceAdded(keyspaceCaptor.capture());
127122 assertThat(keyspaceCaptor.getValue()).hasName(keyspace);
128123
129124 ArgumentCaptor<TableMetadata> tableCaptor = forClass(TableMetadata.class);
130- verify(listener, times(1)).onTableAdded(tableCaptor.capture());
125+ verify(listener, timeout(DEBOUNCE_TIME * 2).times(1)).onTableAdded(tableCaptor.capture());
131126 assertThat(tableCaptor.getValue()).hasName(table);
132127
133128 // Verify the schema refresh was debounced and coalesced when a keyspace event and table event
@@ -152,7 +147,7 @@
152147 */
153148 @Test(groups = "short")
154149 public void should_debounce_and_coalesce_tables_in_same_keyspace_into_refresh_keyspace() throws Exception {
155- String keyspace = "sdactisk";
150+ String keyspace = TestUtils.generateIdentifier("ks_");
156151 session2.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, 1));
157152 // Reset invocations as creating keyspace causes a keyspace refresh.
158153 reset(controlConnection);
@@ -160,7 +155,7 @@
160155
161156 int tableCount = 3;
162157 for (int i = 0; i < tableCount; i++) {
163- session.execute(String.format(CREATE_TABLE_SIMPLE_FORMAT, keyspace + "." + "tbl" + i));
158+ session().execute(String.format(CREATE_TABLE_SIMPLE_FORMAT, keyspace + "." + "tbl" + i));
164159 }
165160
166161 verify(listener, timeout(DEBOUNCE_TIME * 3).times(3)).onTableAdded(any(TableMetadata.class));
@@ -192,7 +187,7 @@
192187 */
193188 @Test(groups = "short")
194189 public void should_debounce_and_coalesce_multiple_alter_events_on_same_table_into_refresh_table() throws Exception {
195- String keyspace = "sdacmaeost";
190+ String keyspace = TestUtils.generateIdentifier("ks_");
196191 String table = "tbl1";
197192 String comment = "I am changing this table.";
198193 String columnName = "added_column";
@@ -202,8 +197,8 @@
202197 reset(controlConnection);
203198 reset(listener);
204199
205- session.execute(String.format("ALTER TABLE %s.%s WITH comment = '%s'", keyspace, table, comment));
206- session.execute(String.format("ALTER TABLE %s.%s ADD %s int", keyspace, table, columnName));
200+ session().execute(String.format("ALTER TABLE %s.%s WITH comment = '%s'", keyspace, table, comment));
201+ session().execute(String.format("ALTER TABLE %s.%s ADD %s int", keyspace, table, columnName));
207202
208203 ArgumentCaptor<TableMetadata> original = forClass(TableMetadata.class);
209204 ArgumentCaptor<TableMetadata> captor = forClass(TableMetadata.class);
@@ -245,9 +240,9 @@
245240 */
246241 @Test(groups = "short")
247242 public void should_debounce_and_coalesce_multiple_keyspace_creates_into_refresh_entire_schema() throws Exception {
248- String prefix = "sdacmkc";
243+ String prefix = TestUtils.generateIdentifier("ks_");
249244 for (int i = 0; i < 3; i++) {
250- session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, prefix + i, 1));
245+ session().execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, prefix + i, 1));
251246 }
252247
253248 verify(listener, timeout(DEBOUNCE_TIME * 3).times(3)).onKeyspaceAdded(any(KeyspaceMetadata.class));
@@ -271,9 +266,9 @@
271266 */
272267 @Test(groups = "short")
273268 public void should_refresh_when_max_pending_requests_reached() throws Exception {
274- String prefix = "srwmprr";
269+ String prefix = TestUtils.generateIdentifier("ks_");
275270 for (int i = 0; i < 5; i++) {
276- session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, prefix + i, 1));
271+ session().execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, prefix + i, 1));
277272 }
278273
279274 // Event should be processed immediately as we hit our threshold.
modified driver-core/src/test/java/com/datastax/driver/core/SchemaTest.java +5 −5
@@ -36,7 +36,7 @@
3636 private static String withOptions;
3737
3838 @Override
39- public Collection<String> createTestFixtures() {
39+ public void onTestContextInitialized() {
4040
4141 String sparse = String.format("CREATE TABLE %s.sparse (\n"
4242 + " k text,\n"
@@ -131,7 +131,7 @@
131131 allDefs.addAll(cql3.values());
132132 allDefs.addAll(compact.values());
133133 allDefs.add(withOptions);
134- return allDefs;
134+ execute(allDefs);
135135 }
136136
137137 private static String stripOptions(String def, boolean keepFirst) {
@@ -149,7 +149,7 @@
149149 @Test(groups = "short")
150150 public void schemaExportTest() {
151151
152- KeyspaceMetadata metadata = cluster.getMetadata().getKeyspace(keyspace);
152+ KeyspaceMetadata metadata = cluster().getMetadata().getKeyspace(keyspace);
153153
154154 for (Map.Entry<String, String> tableEntry : cql3.entrySet()) {
155155 String table = tableEntry.getKey();
@@ -167,10 +167,10 @@
167167 // Same remark as the preceding test
168168 @Test(groups = "short")
169169 public void schemaExportOptionsTest() {
170- TableMetadata metadata = cluster.getMetadata().getKeyspace(keyspace).getTable("with_options");
170+ TableMetadata metadata = cluster().getMetadata().getKeyspace(keyspace).getTable("with_options");
171171
172172 String withOpts = withOptions;
173- VersionNumber version = TestUtils.findHost(cluster, 1).getCassandraVersion();
173+ VersionNumber version = TestUtils.findHost(cluster(), 1).getCassandraVersion();
174174
175175 if (version.getMajor() == 2) {
176176 // Strip the last ';'
modified driver-core/src/test/java/com/datastax/driver/core/SessionLeakTest.java +20 −20
@@ -39,9 +39,9 @@
3939 // Checking for JAVA-342
4040 channelMonitor = new SocketChannelMonitor();
4141 channelMonitor.reportAtFixedInterval(1, TimeUnit.SECONDS);
42- cluster = register(Cluster.builder()
43- .addContactPoints(ccm.addressOfNode(1).getAddress())
44- .withPort(ccm.getBinaryPort())
42+ Cluster cluster = register(Cluster.builder()
43+ .addContactPoints(getContactPoints().get(0))
44+ .withPort(ccm().getBinaryPort())
4545 .withNettyOptions(channelMonitor.nettyOptions())
4646 .withQueryOptions(nonDebouncingQueryOptions())
4747 .build());
@@ -50,44 +50,44 @@
5050
5151 assertThat(cluster.manager.sessions.size()).isEqualTo(0);
5252 // Should be 1 control connection after initialization.
53- assertOpenConnections(1);
53+ assertOpenConnections(1, cluster);
5454
5555 // ensure sessions.size() returns with 1 control connection + core pool size.
5656 int corePoolSize = TestUtils.numberOfLocalCoreConnections(cluster);
5757 Session session = cluster.connect();
5858
5959 assertThat(cluster.manager.sessions.size()).isEqualTo(1);
60- assertOpenConnections(1 + corePoolSize);
60+ assertOpenConnections(1 + corePoolSize, cluster);
6161
6262 // ensure sessions.size() returns to 0 with only 1 active connection (the control connection)
6363 session.close();
6464 assertThat(cluster.manager.sessions.size()).isEqualTo(0);
65- assertOpenConnections(1);
65+ assertOpenConnections(1, cluster);
6666
6767 // ensure bootstrapping a node does not create additional connections
68- ccm.add(2);
69- ccm.start(2);
68+ ccm().add(2);
69+ ccm().start(2);
7070 assertThat(cluster).host(2).comesUpWithin(2, MINUTES);
7171
7272 assertThat(cluster.manager.sessions.size()).isEqualTo(0);
73- assertOpenConnections(1);
73+ assertOpenConnections(1, cluster);
7474
7575 // ensure a new session gets registered and core connections are established
7676 // there should be corePoolSize more connections to accommodate for the new host.
7777 Session thisSession = cluster.connect();
7878 assertThat(cluster.manager.sessions.size()).isEqualTo(1);
79- assertOpenConnections(1 + (corePoolSize * 2));
79+ assertOpenConnections(1 + (corePoolSize * 2), cluster);
8080
8181 // ensure bootstrapping a node does not create additional connections that won't get cleaned up
8282 thisSession.close();
8383
8484 assertThat(cluster.manager.sessions.size()).isEqualTo(0);
85- assertOpenConnections(1);
85+ assertOpenConnections(1, cluster);
8686 cluster.close();
8787 // Ensure no channels remain open.
8888 channelMonitor.stop();
8989 channelMonitor.report();
90- assertThat(channelMonitor.openChannels(newArrayList(ccm.addressOfNode(1), ccm.addressOfNode(2))).size()).isEqualTo(0);
90+ assertThat(channelMonitor.openChannels(newArrayList(ccm().addressOfNode(1), ccm().addressOfNode(2))).size()).isEqualTo(0);
9191 }
9292
9393 @Test(groups = "short")
@@ -95,16 +95,16 @@
9595 // Checking for JAVA-806
9696 channelMonitor = new SocketChannelMonitor();
9797 channelMonitor.reportAtFixedInterval(1, TimeUnit.SECONDS);
98- cluster = register(Cluster.builder()
99- .addContactPoints(ccm.addressOfNode(1).getAddress())
100- .withPort(ccm.getBinaryPort())
98+ Cluster cluster = register(Cluster.builder()
99+ .addContactPoints(getContactPoints().get(0))
100+ .withPort(ccm().getBinaryPort())
101101 .withNettyOptions(channelMonitor.nettyOptions())
102102 .build());
103103 cluster.init();
104104 assertThat(cluster.manager.sessions.size()).isEqualTo(0);
105105 try {
106106 // Should be 1 control connection after initialization.
107- assertOpenConnections(1);
107+ assertOpenConnections(1, cluster);
108108 cluster.connect("wrong_keyspace");
109109 fail("Should not have connected to a wrong keyspace");
110110 } catch (InvalidQueryException e) {
@@ -115,11 +115,11 @@
115115 // Ensure no channels remain open.
116116 channelMonitor.stop();
117117 channelMonitor.report();
118- assertThat(channelMonitor.openChannels(ccm.addressOfNode(1), ccm.addressOfNode(2)).size()).isEqualTo(0);
118+ assertThat(channelMonitor.openChannels(ccm().addressOfNode(1), ccm().addressOfNode(2)).size()).isEqualTo(0);
119119 }
120120
121- private void assertOpenConnections(int expected) {
122- assertThat((cluster.getMetrics().getOpenConnections().getValue())).isEqualTo(expected);
123- assertThat(channelMonitor.openChannels(ccm.addressOfNode(1), ccm.addressOfNode(2)).size()).isEqualTo(expected);
121+ private void assertOpenConnections(int expected, Cluster cluster) {
122+ assertThat(cluster.getMetrics().getOpenConnections().getValue()).isEqualTo(expected);
123+ assertThat(channelMonitor.openChannels(ccm().addressOfNode(1), ccm().addressOfNode(2)).size()).isEqualTo(expected);
124124 }
125125 }
modified driver-core/src/test/java/com/datastax/driver/core/SessionStressTest.java +10 −8
@@ -92,7 +92,9 @@
9292 public void sessions_should_not_leak_connections() {
9393 // override inherited field with a new cluster object and ensure 0 sessions and connections
9494 channelMonitor.reportAtFixedInterval(1, TimeUnit.SECONDS);
95- stressCluster = Cluster.builder().addContactPointsWithPorts(getInitialContactPoints())
95+ stressCluster = Cluster.builder()
96+ .addContactPoints(getContactPoints())
97+ .withPort(ccm().getBinaryPort())
9698 .withPoolingOptions(new PoolingOptions().setCoreConnectionsPerHost(HostDistance.LOCAL, 1))
9799 .withNettyOptions(channelMonitor.nettyOptions()).build();
98100
@@ -109,13 +111,13 @@
109111 assertEquals(stressCluster.manager.sessions.size(), 1);
110112 int coreConnections = TestUtils.numberOfLocalCoreConnections(stressCluster);
111113 assertEquals((int) stressCluster.getMetrics().getOpenConnections().getValue(), 1 + coreConnections);
112- assertEquals(channelMonitor.openChannels(getInitialContactPoints()).size(), 1 + coreConnections);
114+ assertEquals(channelMonitor.openChannels(getContactPointsWithPorts()).size(), 1 + coreConnections);
113115
114116 // Closing the session keeps the control connection opened
115117 session.close();
116118 assertEquals(stressCluster.manager.sessions.size(), 0);
117119 assertEquals((int) stressCluster.getMetrics().getOpenConnections().getValue(), 1);
118- assertEquals(channelMonitor.openChannels(getInitialContactPoints()).size(), 1);
120+ assertEquals(channelMonitor.openChannels(getContactPointsWithPorts()).size(), 1);
119121
120122 int nbOfSessions = 2000;
121123 int halfOfTheSessions = nbOfSessions / 2;
@@ -132,7 +134,7 @@
132134 assertEquals(stressCluster.manager.sessions.size(), nbOfSessions);
133135 assertEquals((int) stressCluster.getMetrics().getOpenConnections().getValue(),
134136 coreConnections * nbOfSessions + 1);
135- assertEquals(channelMonitor.openChannels(getInitialContactPoints()).size(), coreConnections * nbOfSessions + 1);
137+ assertEquals(channelMonitor.openChannels(getContactPointsWithPorts()).size(), coreConnections * nbOfSessions + 1);
136138
137139 // Close half of the sessions asynchronously
138140 logger.info("Closing {}/{} sessions.", halfOfTheSessions, nbOfSessions);
@@ -142,7 +144,7 @@
142144 assertEquals(stressCluster.manager.sessions.size(), halfOfTheSessions);
143145 assertEquals((int) stressCluster.getMetrics().getOpenConnections().getValue(),
144146 coreConnections * (nbOfSessions / 2) + 1);
145- assertEquals(channelMonitor.openChannels(getInitialContactPoints()).size(),
147+ assertEquals(channelMonitor.openChannels(getContactPointsWithPorts()).size(),
146148 coreConnections * (nbOfSessions / 2) + 1);
147149
148150 // Close and open the same number of sessions concurrently
@@ -160,7 +162,7 @@
160162 assertEquals(stressCluster.manager.sessions.size(), halfOfTheSessions);
161163 assertEquals((int) stressCluster.getMetrics().getOpenConnections().getValue(),
162164 coreConnections * (nbOfSessions / 2) + 1);
163- assertEquals(channelMonitor.openChannels(getInitialContactPoints()).size(),
165+ assertEquals(channelMonitor.openChannels(getContactPointsWithPorts()).size(),
164166 coreConnections * (nbOfSessions / 2) + 1);
165167
166168 // Close the remaining sessions
@@ -170,7 +172,7 @@
170172 // Check that we have a clean state
171173 assertEquals(stressCluster.manager.sessions.size(), 0);
172174 assertEquals((int) stressCluster.getMetrics().getOpenConnections().getValue(), 1);
173- assertEquals(channelMonitor.openChannels(getInitialContactPoints()).size(), 1);
175+ assertEquals(channelMonitor.openChannels(getContactPointsWithPorts()).size(), 1);
174176
175177 // On OSX, the TCP connections are released after 15s by default (sysctl -a net.inet.tcp.msl)
176178 logger.info("Sleeping {} seconds so that TCP connections are released by the OS", sleepTime);
@@ -181,7 +183,7 @@
181183 stressCluster = null;
182184
183185 // Ensure no channels remain open.
184- assertEquals(channelMonitor.openChannels(getInitialContactPoints()).size(), 0);
186+ assertEquals(channelMonitor.openChannels(getContactPointsWithPorts()).size(), 0);
185187
186188 channelMonitor.stop();
187189 channelMonitor.report();
modified driver-core/src/test/java/com/datastax/driver/core/SessionTest.java +24 −25
@@ -18,8 +18,6 @@
1818 import com.datastax.driver.core.utils.CassandraVersion;
1919 import org.testng.annotations.Test;
2020
21-import java.util.Arrays;
22-import java.util.Collection;
2321 import java.util.List;
2422 import java.util.Locale;
2523 import java.util.concurrent.CountDownLatch;
@@ -41,8 +39,8 @@
4139 private static final String COUNTER_TABLE = "counters";
4240
4341 @Override
44- public Collection<String> createTestFixtures() {
45- return Arrays.asList(String.format(TestUtils.CREATE_TABLE_SIMPLE_FORMAT, TABLE1),
42+ public void onTestContextInitialized() {
43+ execute(String.format(TestUtils.CREATE_TABLE_SIMPLE_FORMAT, TABLE1),
4644 String.format(TestUtils.CREATE_TABLE_SIMPLE_FORMAT, TABLE2),
4745 String.format(TestUtils.CREATE_TABLE_SIMPLE_FORMAT, TABLE3),
4846 String.format("CREATE TABLE %s (k text PRIMARY KEY, c counter)", COUNTER_TABLE));
@@ -52,16 +50,16 @@
5250 public void executeTest() throws Exception {
5351 // Simple calls to all versions of the execute/executeAsync methods
5452 String key = "execute_test";
55- ResultSet rs = session.execute(String.format(Locale.US, TestUtils.INSERT_FORMAT, TABLE1, key, "foo", 42, 24.03f));
53+ ResultSet rs = session().execute(String.format(Locale.US, TestUtils.INSERT_FORMAT, TABLE1, key, "foo", 42, 24.03f));
5654 assertTrue(rs.isExhausted());
5755
5856 // execute
59- checkExecuteResultSet(session.execute(String.format(TestUtils.SELECT_ALL_FORMAT, TABLE1)), key);
60- checkExecuteResultSet(session.execute(new SimpleStatement(String.format(TestUtils.SELECT_ALL_FORMAT, TABLE1)).setConsistencyLevel(ConsistencyLevel.ONE)), key);
57+ checkExecuteResultSet(session().execute(String.format(TestUtils.SELECT_ALL_FORMAT, TABLE1)), key);
58+ checkExecuteResultSet(session().execute(new SimpleStatement(String.format(TestUtils.SELECT_ALL_FORMAT, TABLE1)).setConsistencyLevel(ConsistencyLevel.ONE)), key);
6159
6260 // executeAsync
63- checkExecuteResultSet(session.executeAsync(String.format(TestUtils.SELECT_ALL_FORMAT, TABLE1)).getUninterruptibly(), key);
64- checkExecuteResultSet(session.executeAsync(new SimpleStatement(String.format(TestUtils.SELECT_ALL_FORMAT, TABLE1)).setConsistencyLevel(ConsistencyLevel.ONE)).getUninterruptibly(), key);
61+ checkExecuteResultSet(session().executeAsync(String.format(TestUtils.SELECT_ALL_FORMAT, TABLE1)).getUninterruptibly(), key);
62+ checkExecuteResultSet(session().executeAsync(new SimpleStatement(String.format(TestUtils.SELECT_ALL_FORMAT, TABLE1)).setConsistencyLevel(ConsistencyLevel.ONE)).getUninterruptibly(), key);
6563 }
6664
6765 @Test(groups = "short")
@@ -69,19 +67,19 @@
6967 // Simple calls to all versions of the execute/executeAsync methods for prepared statements
7068 // Note: the goal is only to exercice the Session methods, PreparedStatementTest have better prepared statement tests.
7169 String key = "execute_prepared_test";
72- ResultSet rs = session.execute(String.format(Locale.US, TestUtils.INSERT_FORMAT, TABLE2, key, "foo", 42, 24.03f));
70+ ResultSet rs = session().execute(String.format(Locale.US, TestUtils.INSERT_FORMAT, TABLE2, key, "foo", 42, 24.03f));
7371 assertTrue(rs.isExhausted());
7472
75- PreparedStatement p = session.prepare(String.format(TestUtils.SELECT_ALL_FORMAT + " WHERE k = ?", TABLE2));
73+ PreparedStatement p = session().prepare(String.format(TestUtils.SELECT_ALL_FORMAT + " WHERE k = ?", TABLE2));
7674 BoundStatement bs = p.bind(key);
7775
7876 // executePrepared
79- checkExecuteResultSet(session.execute(bs), key);
80- checkExecuteResultSet(session.execute(bs.setConsistencyLevel(ConsistencyLevel.ONE)), key);
77+ checkExecuteResultSet(session().execute(bs), key);
78+ checkExecuteResultSet(session().execute(bs.setConsistencyLevel(ConsistencyLevel.ONE)), key);
8179
8280 // executePreparedAsync
83- checkExecuteResultSet(session.executeAsync(bs).getUninterruptibly(), key);
84- checkExecuteResultSet(session.executeAsync(bs.setConsistencyLevel(ConsistencyLevel.ONE)).getUninterruptibly(), key);
81+ checkExecuteResultSet(session().executeAsync(bs).getUninterruptibly(), key);
82+ checkExecuteResultSet(session().executeAsync(bs.setConsistencyLevel(ConsistencyLevel.ONE)).getUninterruptibly(), key);
8583 }
8684
8785 private static void checkExecuteResultSet(ResultSet rs, String key) {
@@ -96,12 +94,12 @@
9694
9795 @Test(groups = "short")
9896 public void executePreparedCounterTest() throws Exception {
99- PreparedStatement p = session.prepare("UPDATE " + COUNTER_TABLE + " SET c = c + ? WHERE k = ?");
97+ PreparedStatement p = session().prepare("UPDATE " + COUNTER_TABLE + " SET c = c + ? WHERE k = ?");
10098
101- session.execute(p.bind(1L, "row"));
102- session.execute(p.bind(1L, "row"));
99+ session().execute(p.bind(1L, "row"));
100+ session().execute(p.bind(1L, "row"));
103101
104- ResultSet rs = session.execute("SELECT * FROM " + COUNTER_TABLE);
102+ ResultSet rs = session().execute("SELECT * FROM " + COUNTER_TABLE);
105103 List<Row> rows = rs.all();
106104 assertEquals(rows.size(), 1);
107105 assertEquals(rows.get(0).getLong("c"), 2L);
@@ -109,7 +107,7 @@
109107
110108 /**
111109 * Validates that a session can be established using snappy compression and executes some queries that inserts and
112- * retrieves data using that session.
110+ * retrieves data using that session().
113111 *
114112 * @test_category connection:compression
115113 * @expected_result session established and queries made successfully using it.
@@ -121,7 +119,7 @@
121119
122120 /**
123121 * Validates that a session can be established using lz4 compression and executes some queries that inserts and
124- * retrieves data using that session.
122+ * retrieves data using that session().
125123 *
126124 * @test_category connection:compression
127125 * @expected_result session established and queries made successfully using it.
@@ -133,9 +131,9 @@
133131 }
134132
135133 public void compressionTest(ProtocolOptions.Compression compression) {
136- cluster.getConfiguration().getProtocolOptions().setCompression(compression);
134+ cluster().getConfiguration().getProtocolOptions().setCompression(compression);
137135 try {
138- Session compressedSession = cluster.connect(keyspace);
136+ Session compressedSession = cluster().connect(keyspace);
139137
140138 // Simple calls to all versions of the execute/executeAsync methods
141139 String key = "execute_compressed_test_" + compression;
@@ -153,7 +151,7 @@
153151 checkExecuteResultSet(compressedSession.executeAsync(new SimpleStatement(SELECT_ALL).setConsistencyLevel(ConsistencyLevel.ONE)).getUninterruptibly(), key);
154152
155153 } finally {
156- cluster.getConfiguration().getProtocolOptions().setCompression(ProtocolOptions.Compression.NONE);
154+ cluster().getConfiguration().getProtocolOptions().setCompression(ProtocolOptions.Compression.NONE);
157155 }
158156 }
159157
@@ -167,7 +165,8 @@
167165 // Use our own cluster and session (not the ones provided by the parent class) because we want an uninitialized cluster
168166 // (note the use of newSession below)
169167 final Cluster cluster = Cluster.builder()
170- .addContactPointsWithPorts(getInitialContactPoints())
168+ .addContactPoints(getContactPoints())
169+ .withPort(ccm().getBinaryPort())
171170 .withNettyOptions(nonQuietClusterCloseOptions)
172171 .build();
173172 try {
modified driver-core/src/test/java/com/datastax/driver/core/SingleConnectionPoolTest.java +4 −4
@@ -32,17 +32,17 @@
3232 public void should_throttle_requests() {
3333 // Throttle to a very low value. Even a single thread can generate a higher throughput.
3434 final int maxRequests = 10;
35- cluster.getConfiguration().getPoolingOptions()
35+ cluster().getConfiguration().getPoolingOptions()
3636 .setMaxRequestsPerConnection(HostDistance.LOCAL, maxRequests);
3737
3838 // Track in flight requests in a dedicated thread every second
3939 final AtomicBoolean excessInflightQueriesSpotted = new AtomicBoolean(false);
40- final Host host = cluster.getMetadata().getHost(ccm.addressOfNode(1));
40+ final Host host = cluster().getMetadata().getHost(ccm().addressOfNode(1));
4141 ScheduledExecutorService openConnectionsWatcherExecutor = Executors.newScheduledThreadPool(1);
4242 final Runnable openConnectionsWatcher = new Runnable() {
4343 @Override
4444 public void run() {
45- int inFlight = session.getState().getInFlightQueries(host);
45+ int inFlight = session().getState().getInFlightQueries(host);
4646 if (inFlight > maxRequests)
4747 excessInflightQueriesSpotted.set(true);
4848 }
@@ -51,7 +51,7 @@
5151
5252 // Generate the load
5353 for (int i = 0; i < 10000; i++)
54- session.executeAsync("SELECT release_version FROM system.local");
54+ session().executeAsync("SELECT release_version FROM system.local");
5555
5656 openConnectionsWatcherExecutor.shutdownNow();
5757 if (excessInflightQueriesSpotted.get()) {
modified driver-core/src/test/java/com/datastax/driver/core/SingleTokenIntegrationTest.java +3 −2
@@ -35,7 +35,8 @@
3535 */
3636 @Test(groups = "short")
3737 public void should_return_single_non_empty_range_when_cluster_has_one_single_token() {
38- Metadata metadata = cluster.getMetadata();
38+ cluster().manager.controlConnection.refreshNodeListAndTokenMap();
39+ Metadata metadata = cluster().getMetadata();
3940 Set<TokenRange> tokenRanges = metadata.getTokenRanges();
4041 assertThat(tokenRanges).hasSize(1);
4142 TokenRange tokenRange = tokenRanges.iterator().next();
@@ -46,7 +47,7 @@
4647 .isNotWrappedAround();
4748
4849 Set<Host> hostsForRange = metadata.getReplicas(keyspace, tokenRange);
49- Host host1 = TestUtils.findHost(cluster, 1);
50+ Host host1 = TestUtils.findHost(cluster(), 1);
5051 assertThat(hostsForRange).containsOnly(host1);
5152
5253 ByteBuffer randomPartitionKey = Bytes.fromHexString("0xCAFEBABE");
modified driver-core/src/test/java/com/datastax/driver/core/SpeculativeExecutionIntegrationTest.java +4 −7
@@ -17,12 +17,9 @@
1717
1818 import com.datastax.driver.core.policies.ConstantSpeculativeExecutionPolicy;
1919 import com.datastax.driver.core.utils.CassandraVersion;
20-import com.google.common.collect.Lists;
2120 import org.mockito.Mockito;
2221 import org.testng.annotations.Test;
2322
24-import java.util.Collection;
25-
2623 import static org.assertj.core.api.Assertions.assertThat;
2724 import static org.mockito.Mockito.times;
2825
@@ -35,8 +32,8 @@
3532 TimestampGenerator timestampGenerator;
3633
3734 @Override
38- public Collection<String> createTestFixtures() {
39- return Lists.newArrayList("create table foo(k int primary key, v int)");
35+ public void onTestContextInitialized() {
36+ execute("create table foo(k int primary key, v int)");
4037 }
4138
4239 @Override
@@ -59,7 +56,7 @@
5956 @Test(groups = "short")
6057 @CassandraVersion(major = 2.1)
6158 public void should_use_same_default_timestamp_for_all_executions() {
62- Metrics.Errors errors = cluster.getMetrics().getErrorMetrics();
59+ Metrics.Errors errors = cluster().getMetrics().getErrorMetrics();
6360
6461 Mockito.reset(timestampGenerator);
6562 long execStartCount = errors.getSpeculativeExecutions().getCount();
@@ -68,7 +65,7 @@
6865 for (int k = 0; k < 1000; k++) {
6966 batch.add(new SimpleStatement("insert into foo(k,v) values (?,1)", k));
7067 }
71- session.execute(batch);
68+ session().execute(batch);
7269
7370 assertThat(errors.getSpeculativeExecutions().getCount()).isEqualTo(execStartCount + 1);
7471 Mockito.verify(timestampGenerator, times(1)).next();
modified driver-core/src/test/java/com/datastax/driver/core/StateListenerTest.java +6 −6
@@ -35,23 +35,23 @@
3535 @Test(groups = "long")
3636 public void should_receive_events_when_node_states_change() throws InterruptedException {
3737 TestListener listener = new TestListener();
38- cluster.register(listener);
38+ cluster().register(listener);
3939
4040 listener.setExpectedEvent(ADD);
41- ccm.add(2);
42- ccm.start(2);
41+ ccm().add(2);
42+ ccm().start(2);
4343 listener.waitForEvent();
4444
4545 listener.setExpectedEvent(DOWN);
46- ccm.forceStop(1);
46+ ccm().forceStop(1);
4747 listener.waitForEvent();
4848
4949 listener.setExpectedEvent(UP);
50- ccm.start(1);
50+ ccm().start(1);
5151 listener.waitForEvent();
5252
5353 listener.setExpectedEvent(REMOVE);
54- ccm.decommission(2);
54+ ccm().decommission(2);
5555 listener.waitForEvent();
5656 }
5757
modified driver-core/src/test/java/com/datastax/driver/core/StatementWrapperTest.java +6 −6
@@ -42,10 +42,10 @@
4242 loadBalancingPolicy.customStatementsHandled.set(0);
4343
4444 SimpleStatement s = new SimpleStatement("select * from system.local");
45- session.execute(s);
45+ session().execute(s);
4646 assertThat(loadBalancingPolicy.customStatementsHandled.get()).isEqualTo(0);
4747
48- session.execute(new CustomStatement(s));
48+ session().execute(new CustomStatement(s));
4949 assertThat(loadBalancingPolicy.customStatementsHandled.get()).isEqualTo(1);
5050 }
5151
@@ -54,10 +54,10 @@
5454 speculativeExecutionPolicy.customStatementsHandled.set(0);
5555
5656 SimpleStatement s = new SimpleStatement("select * from system.local");
57- session.execute(s);
57+ session().execute(s);
5858 assertThat(speculativeExecutionPolicy.customStatementsHandled.get()).isEqualTo(0);
5959
60- session.execute(new CustomStatement(s));
60+ session().execute(new CustomStatement(s));
6161 assertThat(speculativeExecutionPolicy.customStatementsHandled.get()).isEqualTo(1);
6262 }
6363
@@ -70,10 +70,10 @@
7070 Statement s = new SimpleStatement("select * from system.local")
7171 .setConsistencyLevel(ConsistencyLevel.TWO);
7272
73- session.execute(s);
73+ session().execute(s);
7474 assertThat(retryPolicy.customStatementsHandled.get()).isEqualTo(0);
7575
76- session.execute(new CustomStatement(s));
76+ session().execute(new CustomStatement(s));
7777 assertThat(retryPolicy.customStatementsHandled.get()).isEqualTo(1);
7878 }
7979
modified driver-core/src/test/java/com/datastax/driver/core/TableMetadataTest.java +3 −6
@@ -15,18 +15,15 @@
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
2522 @CCMConfig(clusterProvider = "createClusterBuilderNoDebouncing")
2623 public class TableMetadataTest extends CCMTestsSupport {
2724 @Override
28- public Collection<String> createTestFixtures() {
29- return Lists.newArrayList(
25+ public void onTestContextInitialized() {
26+ execute(
3027 "CREATE TABLE single_quote (\n"
3128 + " c1 int PRIMARY KEY\n"
3229 + ") WITH comment = 'comment with single quote '' should work'"
@@ -35,7 +32,7 @@
3532
3633 @Test(groups = "short")
3734 public void should_escape_single_quote_table_comment() {
38- TableMetadata table = cluster.getMetadata().getKeyspace(keyspace).getTable("single_quote");
35+ TableMetadata table = cluster().getMetadata().getKeyspace(keyspace).getTable("single_quote");
3936 assertThat(table.asCQLQuery()).contains("comment with single quote '' should work");
4037 }
4138 }
modified driver-core/src/test/java/com/datastax/driver/core/TestUtils.java +60 −34
@@ -37,12 +37,14 @@
3737 import java.net.Socket;
3838 import java.nio.ByteBuffer;
3939 import java.util.*;
40-import java.util.concurrent.Callable;
41-import java.util.concurrent.CountDownLatch;
42-import java.util.concurrent.TimeUnit;
40+import java.util.concurrent.*;
4341 import java.util.concurrent.atomic.AtomicInteger;
4442 import java.util.concurrent.locks.ReentrantLock;
4543
44+import static com.datastax.driver.core.ConditionChecker.check;
45+import static java.util.concurrent.TimeUnit.MINUTES;
46+import static java.util.concurrent.TimeUnit.SECONDS;
47+
4648 /**
4749 * A number of static fields/methods handy for tests.
4850 */
@@ -63,18 +65,14 @@
6365 public static final String CREATE_KEYSPACE_SIMPLE_FORMAT = "CREATE KEYSPACE %s WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor' : %d }";
6466 public static final String CREATE_KEYSPACE_GENERIC_FORMAT = "CREATE KEYSPACE %s WITH replication = { 'class' : '%s', %s }";
6567
66- public static final String SIMPLE_KEYSPACE = "ks";
67- public static final String SIMPLE_TABLE = "test";
68-
6968 public static final String CREATE_TABLE_SIMPLE_FORMAT = "CREATE TABLE %s (k text PRIMARY KEY, t text, i int, f float)";
7069
7170 public static final String INSERT_FORMAT = "INSERT INTO %s (k, t, i, f) VALUES ('%s', '%s', %d, %f)";
71+
7272 public static final String SELECT_ALL_FORMAT = "SELECT * FROM %s";
7373
7474 public static final int TEST_BASE_NODE_WAIT = SystemProperties.getInt("com.datastax.driver.TEST_BASE_NODE_WAIT", 60);
7575
76- private static final AtomicInteger KS_COUNTER = new AtomicInteger(1);
77-
7876 @SuppressWarnings({"unchecked", "rawtypes"})
7977 public static BoundStatement setBoundValue(BoundStatement bs, String name, DataType type, Object value) {
8078 switch (type.getName()) {
@@ -304,28 +302,20 @@
304302 // Wait for a node to be up and running
305303 // This is used because there is some delay between when a node has been
306304 // added through ccm and when it's actually available for querying
307- public static void waitFor(String node, Cluster cluster) {
305+ public static void waitForUp(String node, Cluster cluster) {
308306 waitFor(node, cluster, TEST_BASE_NODE_WAIT, false);
309307 }
310308
311- public static void waitFor(String node, Cluster cluster, int maxTry) {
312- waitFor(node, cluster, maxTry, false);
309+ public static void waitForUp(String node, Cluster cluster, int timeoutSeconds) {
310+ waitFor(node, cluster, timeoutSeconds, false);
313311 }
314312
315313 public static void waitForDown(String node, Cluster cluster) {
316314 waitFor(node, cluster, TEST_BASE_NODE_WAIT * 3, true);
317315 }
318316
319- public static void waitForDown(String node, Cluster cluster, int maxTry) {
320- waitFor(node, cluster, maxTry, true);
321- }
322-
323- public static void waitForDecommission(String node, Cluster cluster) {
324- waitFor(node, cluster, TEST_BASE_NODE_WAIT / 2, true);
325- }
326-
327- public static void waitForDecommission(String node, Cluster cluster, int maxTry) {
328- waitFor(node, cluster, maxTry, true);
317+ public static void waitForDown(String node, Cluster cluster, int timeoutSeconds) {
318+ waitFor(node, cluster, timeoutSeconds, true);
329319 }
330320
331321 private static void waitFor(String node, Cluster cluster, int timeoutSeconds, boolean waitForDown) {
@@ -337,23 +327,30 @@
337327 // tried doing an actual query, the driver won't realize that last node is dead until
338328 // keep alive kicks in, but that's a fairly long time. So we cheat and trigger a force
339329 // the detection by forcing a request.
340- if (waitForDown) {
330+ if (waitForDown)
341331 Futures.getUnchecked(cluster.manager.submitSchemaRefresh(null, null, null));
342- }
343332 if (waitForDown) {
344- ConditionChecker.awaitUntil(new HostIsDownCondition(cluster, node), timeoutSeconds * 1000);
333+ check()
334+ .every(1, SECONDS)
335+ .before(timeoutSeconds, SECONDS)
336+ .that(new HostIsDown(cluster, node))
337+ .becomesTrue();
345338 } else {
346- ConditionChecker.awaitUntil(new HostIsUpCondition(cluster, node), timeoutSeconds * 1000);
339+ check()
340+ .every(1, SECONDS)
341+ .before(timeoutSeconds, SECONDS)
342+ .that(new HostIsUp(cluster, node))
343+ .becomesTrue();
347344 }
348345 }
349346
350- private static class HostIsDownCondition implements Callable<Boolean> {
347+ private static class HostIsDown implements Callable<Boolean> {
351348
352349 private final Cluster cluster;
353350
354351 private final String ip;
355352
356- public HostIsDownCondition(Cluster cluster, String ip) {
353+ public HostIsDown(Cluster cluster, String ip) {
357354 this.cluster = cluster;
358355 this.ip = ip;
359356 }
@@ -365,13 +362,13 @@
365362 }
366363 }
367364
368- private static class HostIsUpCondition implements Callable<Boolean> {
365+ private static class HostIsUp implements Callable<Boolean> {
369366
370367 private final Cluster cluster;
371368
372369 private final String ip;
373370
374- public HostIsUpCondition(Cluster cluster, String ip) {
371+ public HostIsUp(Cluster cluster, String ip) {
375372 this.cluster = cluster;
376373 this.ip = ip;
377374 }
@@ -476,8 +473,20 @@
476473 return ScassandraFactory.createServer(ipOfNode(1), binaryPort, ipOfNode(1), adminPort);
477474 }
478475
479- public static String getAvailableKeyspaceName() {
480- return SIMPLE_KEYSPACE + "_" + KS_COUNTER.getAndIncrement();
476+ private static final ConcurrentMap<String, AtomicInteger> IDENTIFIERS = new ConcurrentHashMap<String, AtomicInteger>();
477+
478+ /**
479+ * Generates a unique CQL identifier with the given prefix.
480+ *
481+ * @param prefix The prefix for the identifier
482+ * @return a unique CQL identifier.
483+ */
484+ public static String generateIdentifier(String prefix) {
485+ AtomicInteger seq = new AtomicInteger(0);
486+ AtomicInteger previous = IDENTIFIERS.putIfAbsent(prefix, seq);
487+ if (previous != null)
488+ seq = previous;
489+ return prefix + seq.incrementAndGet();
481490 }
482491
483492 // use ports in the ephemeral range
@@ -534,11 +543,11 @@
534543 };
535544
536545 public static void waitUntilPortIsUp(InetSocketAddress address) {
537- ConditionChecker.awaitUntil(address, PORT_IS_UP, TimeUnit.SECONDS.toMillis(10));
546+ check().before(5, MINUTES).that(address, PORT_IS_UP).becomesTrue();
538547 }
539548
540549 public static void waitUntilPortIsDown(InetSocketAddress address) {
541- ConditionChecker.awaitWhile(address, PORT_IS_UP, TimeUnit.SECONDS.toMillis(10));
550+ check().before(5, MINUTES).that(address, PORT_IS_UP).becomesFalse();
542551 }
543552
544553 public static boolean pingPort(InetAddress address, int port) {
@@ -608,10 +617,16 @@
608617 public static NettyOptions nonQuietClusterCloseOptions = new NettyOptions() {
609618 @Override
610619 public void onClusterClose(EventLoopGroup eventLoopGroup) {
611- eventLoopGroup.shutdownGracefully(0, 15, TimeUnit.SECONDS).syncUninterruptibly();
620+ eventLoopGroup.shutdownGracefully(0, 15, SECONDS).syncUninterruptibly();
612621 }
613622 };
614623
624+ /**
625+ * Executes a task and catches any exception.
626+ *
627+ * @param task The task to execute.
628+ * @param logException Whether to log the exception, if any.
629+ */
615630 public static void executeNoFail(Runnable task, boolean logException) {
616631 try {
617632 task.run();
@@ -621,6 +636,12 @@
621636 }
622637 }
623638
639+ /**
640+ * Executes a task and catches any exception.
641+ *
642+ * @param task The task to execute.
643+ * @param logException Whether to log the exception, if any.
644+ */
624645 public static void executeNoFail(Callable<?> task, boolean logException) {
625646 try {
626647 task.call();
@@ -630,6 +651,11 @@
630651 }
631652 }
632653
654+ /**
655+ * Returns the system's free memory in megabytes.
656+ * <p/>
657+ * This includes the free physical memory + the free swap memory.
658+ */
633659 public static long getFreeMemoryMB() {
634660 OperatingSystemMXBean bean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
635661 return (bean.getFreePhysicalMemorySize() + bean.getFreeSwapSpaceSize()) / 1024 / 1024;
modified driver-core/src/test/java/com/datastax/driver/core/TimeoutStressTest.java +20 −21
@@ -18,7 +18,6 @@
1818 import com.datastax.driver.core.exceptions.NoHostAvailableException;
1919 import com.datastax.driver.core.policies.ConstantReconnectionPolicy;
2020 import com.datastax.driver.core.utils.SocketChannelMonitor;
21-import com.google.common.collect.Lists;
2221 import com.google.common.util.concurrent.FutureCallback;
2322 import com.google.common.util.concurrent.Futures;
2423 import com.google.common.util.concurrent.ThreadFactoryBuilder;
@@ -71,8 +70,8 @@
7170 }
7271
7372 @Override
74- public Collection<String> createTestFixtures() {
75- return Lists.newArrayList(
73+ public void onTestContextInitialized() {
74+ execute(
7675 "create table record (\n"
7776 + " name text,\n"
7877 + " phone text,\n"
@@ -109,13 +108,13 @@
109108 @Test(groups = "stress")
110109 public void host_state_should_be_maintained_with_timeouts() throws Exception {
111110 insertRecords();
112- session.close();
111+ session().close();
113112
114113 // Set very low timeouts.
115- cluster.getConfiguration().getSocketOptions().setConnectTimeoutMillis(CONNECTION_TIMEOUT_IN_MS);
116- cluster.getConfiguration().getSocketOptions().setReadTimeoutMillis(READ_TIMEOUT_IN_MS);
117- session = cluster.connect(keyspace);
118- PreparedStatement statement = session.prepare("select * from record where name=? limit 1000;");
114+ cluster().getConfiguration().getSocketOptions().setConnectTimeoutMillis(CONNECTION_TIMEOUT_IN_MS);
115+ cluster().getConfiguration().getSocketOptions().setReadTimeoutMillis(READ_TIMEOUT_IN_MS);
116+ Session newSession = cluster().connect(keyspace);
117+ PreparedStatement statement = newSession.prepare("select * from record where name=? limit 1000;");
119118
120119 int workers = Runtime.getRuntime().availableProcessors();
121120 ExecutorService workerPool = Executors.newFixedThreadPool(workers,
@@ -124,12 +123,12 @@
124123 AtomicBoolean stopped = new AtomicBoolean(false);
125124
126125 // Ensure that we never exceed MaxConnectionsPerHost * nodes + 1 control connection.
127- int maxConnections = TestUtils.numberOfLocalCoreConnections(cluster) * getInitialContactPoints().size() + 1;
126+ int maxConnections = TestUtils.numberOfLocalCoreConnections(cluster()) * getContactPoints().size() + 1;
128127
129128 try {
130129 Semaphore concurrentQueries = new Semaphore(CONCURRENT_QUERIES);
131130 for (int i = 0; i < workers; i++) {
132- workerPool.submit(new TimeoutStressWorker(session, statement, concurrentQueries, stopped));
131+ workerPool.submit(new TimeoutStressWorker(newSession, statement, concurrentQueries, stopped));
133132 }
134133
135134 long startTime = System.currentTimeMillis();
@@ -138,7 +137,7 @@
138137 channelMonitor.report();
139138 // Some connections that are being closed may have had active requests which are delegated to the
140139 // reaper for cleanup later.
141- Collection<SocketChannel> openChannels = channelMonitor.openChannels(getInitialContactPoints());
140+ Collection<SocketChannel> openChannels = channelMonitor.openChannels(getContactPointsWithPorts());
142141
143142 // Ensure that we don't exceed maximum connections. Log as warning as there will be a bit of a timing
144143 // factor between retrieving open connections and checking the reaper.
@@ -152,28 +151,28 @@
152151 stopped.set(true);
153152
154153 // Reset socket timeouts to allow pool to recover.
155- cluster.getConfiguration().getSocketOptions()
154+ cluster().getConfiguration().getSocketOptions()
156155 .setConnectTimeoutMillis(SocketOptions.DEFAULT_CONNECT_TIMEOUT_MILLIS);
157- cluster.getConfiguration().getSocketOptions()
156+ cluster().getConfiguration().getSocketOptions()
158157 .setReadTimeoutMillis(SocketOptions.DEFAULT_READ_TIMEOUT_MILLIS);
159158
160159 logger.debug("Sleeping 20 seconds to allow connection reaper to clean up connections " +
161160 "and for the pools to recover.");
162161 Uninterruptibles.sleepUninterruptibly(20, TimeUnit.SECONDS);
163162
164- Collection<SocketChannel> openChannels = channelMonitor.openChannels(getInitialContactPoints());
163+ Collection<SocketChannel> openChannels = channelMonitor.openChannels(getContactPointsWithPorts());
165164 assertThat(openChannels.size())
166165 .as("Number of open connections does not meet expected: %s", openChannels)
167166 .isLessThanOrEqualTo(maxConnections);
168167
169168 // Each host should be in an up state.
170- assertThat(cluster).host(1).comesUpWithin(0, TimeUnit.SECONDS);
171- assertThat(cluster).host(2).comesUpWithin(0, TimeUnit.SECONDS);
172- assertThat(cluster).host(3).comesUpWithin(0, TimeUnit.SECONDS);
169+ assertThat(cluster()).host(1).comesUpWithin(0, TimeUnit.SECONDS);
170+ assertThat(cluster()).host(2).comesUpWithin(0, TimeUnit.SECONDS);
171+ assertThat(cluster()).host(3).comesUpWithin(0, TimeUnit.SECONDS);
173172
174- session.close();
173+ newSession.close();
175174
176- openChannels = channelMonitor.openChannels(getInitialContactPoints());
175+ openChannels = channelMonitor.openChannels(getContactPointsWithPorts());
177176 assertThat(openChannels.size())
178177 .as("Number of open connections does not meet expected: %s", openChannels)
179178 .isEqualTo(1);
@@ -184,12 +183,12 @@
184183
185184 private void insertRecords() {
186185 int records = 30000;
187- PreparedStatement insertStmt = session.prepare("insert into record (name, phone, value) values (?, ?, ?)");
186+ PreparedStatement insertStmt = session().prepare("insert into record (name, phone, value) values (?, ?, ?)");
188187
189188 for (int i = 0; i < records; i++) {
190189 if (i % 1000 == 0)
191190 logger.debug("Inserting record {}.", i);
192- session.execute(insertStmt.bind("0", Integer.toString(i), "test"));
191+ session().execute(insertStmt.bind("0", Integer.toString(i), "test"));
193192 }
194193 logger.debug("Inserts complete.");
195194 }
modified driver-core/src/test/java/com/datastax/driver/core/TokenIntegrationTest.java +33 −30
@@ -25,7 +25,10 @@
2525 import com.google.common.collect.Lists;
2626 import org.testng.annotations.Test;
2727
28-import java.util.*;
28+import java.util.Collections;
29+import java.util.HashSet;
30+import java.util.List;
31+import java.util.Set;
2932
3033 import static com.datastax.driver.core.Assertions.assertThat;
3134
@@ -54,18 +57,18 @@
5457 public Cluster.Builder createClusterBuilder() {
5558 // Only connect to node 1, which makes it easier to query system tables in should_expose_tokens_per_host()
5659 LoadBalancingPolicy lbp = new WhiteListPolicy(new RoundRobinPolicy(),
57- Collections.singleton(ccm.addressOfNode(1)));
60+ Collections.singleton(ccm().addressOfNode(1)));
5861 return Cluster.builder()
59- .addContactPointsWithPorts(ccm.addressOfNode(1))
62+ .addContactPointsWithPorts(ccm().addressOfNode(1))
6063 .withLoadBalancingPolicy(lbp)
6164 .withQueryOptions(TestUtils.nonDebouncingQueryOptions());
6265 }
6366
6467 @Override
65- public Collection<String> createTestFixtures() {
66- ks1 = TestUtils.getAvailableKeyspaceName();
67- ks2 = TestUtils.getAvailableKeyspaceName();
68- return Lists.newArrayList(
68+ public void onTestContextInitialized() {
69+ ks1 = TestUtils.generateIdentifier("ks_");
70+ ks2 = TestUtils.generateIdentifier("ks_");
71+ execute(
6972 String.format("CREATE KEYSPACE %s WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}", ks1),
7073 String.format("CREATE KEYSPACE %s WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 2}", ks2),
7174 String.format("USE %s", ks1),
@@ -89,18 +92,18 @@
8992 */
9093 @Test(groups = "short")
9194 public void should_expose_token_ranges() throws Exception {
92- Metadata metadata = cluster.getMetadata();
95+ Metadata metadata = cluster().getMetadata();
9396
9497 // Find the replica for a given partition key
9598 int testKey = 1;
96- Set<Host> replicas = metadata.getReplicas(ks1, DataType.cint().serialize(testKey, cluster.getConfiguration().getProtocolOptions().getProtocolVersionEnum()));
99+ Set<Host> replicas = metadata.getReplicas(ks1, DataType.cint().serialize(testKey, cluster().getConfiguration().getProtocolOptions().getProtocolVersionEnum()));
97100 assertThat(replicas).hasSize(1);
98101 Host replica = replicas.iterator().next();
99102
100103 // Iterate the cluster's token ranges. For each one, use a range query to ask Cassandra which partition keys
101104 // are in this range.
102105
103- PreparedStatement rangeStmt = session.prepare("SELECT i FROM foo WHERE token(i) > ? and token(i) <= ?");
106+ PreparedStatement rangeStmt = session().prepare("SELECT i FROM foo WHERE token(i) > ? and token(i) <= ?");
104107
105108 TokenRange foundRange = null;
106109 for (TokenRange range : metadata.getTokenRanges()) {
@@ -124,7 +127,7 @@
124127 List<Row> rows = Lists.newArrayList();
125128 for (TokenRange subRange : range.unwrap()) {
126129 Statement statement = rangeStmt.bind(subRange.getStart(), subRange.getEnd());
127- rows.addAll(session.execute(statement).all());
130+ rows.addAll(session().execute(statement).all());
128131 }
129132 return rows;
130133 }
@@ -154,7 +157,7 @@
154157 @Test(groups = "short")
155158 public void should_get_token_from_row_and_set_token_in_query() {
156159 // get by index:
157- Row row = session.execute("SELECT token(i) FROM foo WHERE i = 1").one();
160+ Row row = session().execute("SELECT token(i) FROM foo WHERE i = 1").one();
158161 Token token = row.getToken(0);
159162 assertThat(token.getType()).isEqualTo(expectedTokenType);
160163
@@ -162,14 +165,14 @@
162165 row.getPartitionKeyToken()
163166 ).isEqualTo(token);
164167
165- PreparedStatement pst = session.prepare("SELECT * FROM foo WHERE token(i) = ?");
166- row = session.execute(pst.bind(token)).one();
168+ PreparedStatement pst = session().prepare("SELECT * FROM foo WHERE token(i) = ?");
169+ row = session().execute(pst.bind(token)).one();
167170 assertThat(row.getInt(0)).isEqualTo(1);
168171
169- row = session.execute(pst.bind().setToken(0, token)).one();
172+ row = session().execute(pst.bind().setToken(0, token)).one();
170173 assertThat(row.getInt(0)).isEqualTo(1);
171174
172- row = session.execute(pst.bind().setPartitionKeyToken(token)).one();
175+ row = session().execute(pst.bind().setPartitionKeyToken(token)).one();
173176 assertThat(row.getInt(0)).isEqualTo(1);
174177 }
175178
@@ -190,15 +193,15 @@
190193 @Test(groups = "short")
191194 @CassandraVersion(major = 2)
192195 public void should_get_token_from_row_and_set_token_in_query_with_binding_and_aliasing() {
193- Row row = session.execute("SELECT token(i) AS t FROM foo WHERE i = 1").one();
196+ Row row = session().execute("SELECT token(i) AS t FROM foo WHERE i = 1").one();
194197 Token token = row.getToken("t");
195198 assertThat(token.getType()).isEqualTo(expectedTokenType);
196199
197- PreparedStatement pst = session.prepare("SELECT * FROM foo WHERE token(i) = :myToken");
198- row = session.execute(pst.bind().setToken("myToken", token)).one();
200+ PreparedStatement pst = session().prepare("SELECT * FROM foo WHERE token(i) = :myToken");
201+ row = session().execute(pst.bind().setToken("myToken", token)).one();
199202 assertThat(row.getInt(0)).isEqualTo(1);
200203
201- row = session.execute("SELECT * FROM foo WHERE token(i) = ?", token).one();
204+ row = session().execute("SELECT * FROM foo WHERE token(i) = ?", token).one();
202205 assertThat(row.getInt(0)).isEqualTo(1);
203206 }
204207
@@ -214,7 +217,7 @@
214217 */
215218 @Test(groups = "short", expectedExceptions = InvalidTypeException.class)
216219 public void should_raise_exception_when_get_token_on_non_token() {
217- Row row = session.execute("SELECT i FROM foo WHERE i = 1").one();
220+ Row row = session().execute("SELECT i FROM foo WHERE i = 1").one();
218221 row.getToken(0);
219222 }
220223
@@ -238,7 +241,7 @@
238241 public void should_expose_token_ranges_per_host() {
239242 checkRangesPerHost(ks1, 1);
240243 checkRangesPerHost(ks2, 2);
241- assertThat(cluster).hasValidTokenRanges();
244+ assertThat(cluster()).hasValidTokenRanges();
242245 }
243246
244247 private void checkRangesPerHost(String keyspace, int replicationFactor) {
@@ -246,8 +249,8 @@
246249
247250 // Get each host's ranges, the count should match the replication factor
248251 for (int i = 1; i <= 3; i++) {
249- Host host = TestUtils.findHost(cluster, i);
250- Set<TokenRange> hostRanges = cluster.getMetadata().getTokenRanges(keyspace, host);
252+ Host host = TestUtils.findHost(cluster(), i);
253+ Set<TokenRange> hostRanges = cluster().getMetadata().getTokenRanges(keyspace, host);
251254 // Special case: When using vnodes the tokens are not evenly assigned to each replica.
252255 if (!useVnodes) {
253256 assertThat(hostRanges).hasSize(replicationFactor * numTokens);
@@ -263,7 +266,7 @@
263266 assertThat(allRanges).hasSize(3 * numTokens);
264267
265268 // And the ranges should cover the whole ring and no ranges intersect.
266- assertThat(cluster).hasValidTokenRanges(keyspace);
269+ assertThat(cluster()).hasValidTokenRanges(keyspace);
267270 }
268271
269272 /**
@@ -282,15 +285,15 @@
282285 */
283286 @Test(groups = "short")
284287 public void should_expose_tokens_per_host() {
285- for (Host host : cluster.getMetadata().allHosts()) {
288+ for (Host host : cluster().getMetadata().allHosts()) {
286289 assertThat(host.getTokens()).hasSize(numTokens);
287290
288291 // Check against the info in the system tables, which is a bit weak since it's exactly how the metadata is
289292 // constructed in the first place, but there's not much else we can do.
290293 // Note that this relies on all queries going to node 1, which is why we use a WhiteList LBP in setup().
291294 Row row = (host.listenAddress == null)
292- ? session.execute("select tokens from system.local").one()
293- : session.execute("select tokens from system.peers where peer = '" + host.listenAddress.getHostAddress() + "'").one();
295+ ? session().execute("select tokens from system.local").one()
296+ : session().execute("select tokens from system.peers where peer = '" + host.listenAddress.getHostAddress() + "'").one();
294297 Set<String> tokenStrings = row.getSet("tokens", String.class);
295298 assertThat(tokenStrings).hasSize(numTokens);
296299 Iterable<Token> tokensFromSystemTable = Iterables.transform(tokenStrings, new Function<String, Token>() {
@@ -318,7 +321,7 @@
318321 */
319322 @Test(groups = "short")
320323 public void should_only_unwrap_one_range_for_all_ranges() {
321- Set<TokenRange> ranges = cluster.getMetadata().getTokenRanges();
324+ Set<TokenRange> ranges = cluster().getMetadata().getTokenRanges();
322325
323326 assertOnlyOneWrapped(ranges);
324327
@@ -358,7 +361,7 @@
358361
359362 @Test(groups = "short")
360363 public void should_expose_token_and_range_creation_methods() {
361- Metadata metadata = cluster.getMetadata();
364+ Metadata metadata = cluster().getMetadata();
362365
363366 // Pick a random range
364367 TokenRange range = metadata.getTokenRanges().iterator().next();
modified driver-core/src/test/java/com/datastax/driver/core/TracingTest.java +5 −12
@@ -18,11 +18,8 @@
1818 import com.datastax.driver.core.policies.DowngradingConsistencyRetryPolicy;
1919 import com.datastax.driver.core.utils.CassandraVersion;
2020 import com.google.common.util.concurrent.Uninterruptibles;
21-import org.testng.annotations.BeforeClass;
2221 import org.testng.annotations.Test;
2322
24-import java.util.Collection;
25-import java.util.Collections;
2623 import java.util.List;
2724 import java.util.UUID;
2825 import java.util.concurrent.TimeUnit;
@@ -40,14 +37,10 @@
4037 }
4138
4239 @Override
43- public Collection<String> createTestFixtures() {
44- return Collections.singletonList("CREATE TABLE test (k text, v int, PRIMARY KEY (k, v))");
45- }
46-
47- @BeforeClass(groups = "short")
48- public void initData() {
40+ public void onTestContextInitialized() {
41+ execute("CREATE TABLE test (k text, v int, PRIMARY KEY (k, v))");
4942 for (int i = 0; i < 100; i++) {
50- session.execute(String.format("INSERT INTO test (k, v) VALUES ('%s', %d)", KEY, i));
43+ execute(String.format("INSERT INTO test (k, v) VALUES ('%s', %d)", KEY, i));
5144 }
5245 }
5346
@@ -61,7 +54,7 @@
6154 @Test(groups = "short")
6255 public void should_have_a_different_tracingId_for_each_page() {
6356 SimpleStatement st = new SimpleStatement(String.format("SELECT v FROM test WHERE k='%s'", KEY));
64- ResultSet result = session.execute(st.setFetchSize(40).enableTracing());
57+ ResultSet result = session().execute(st.setFetchSize(40).enableTracing());
6558 result.all();
6659 // sleep 10 seconds to make sure the trace will be complete
6760 Uninterruptibles.sleepUninterruptibly(10, TimeUnit.SECONDS);
@@ -93,7 +86,7 @@
9386 SimpleStatement st = new SimpleStatement(String.format("SELECT v FROM test WHERE k='%s'", KEY));
9487 st.setConsistencyLevel(ConsistencyLevel.THREE).enableTracing();
9588
96- ResultSet result = session.execute(st);
89+ ResultSet result = session().execute(st);
9790 // sleep 10 seconds to make sure the trace will be complete
9891 Uninterruptibles.sleepUninterruptibly(10, TimeUnit.SECONDS);
9992
modified driver-core/src/test/java/com/datastax/driver/core/TupleTest.java +61 −61
@@ -30,8 +30,8 @@
3030 public class TupleTest extends CCMTestsSupport {
3131
3232 @Override
33- public Collection<String> createTestFixtures() {
34- return Collections.singleton("CREATE TABLE t (k int PRIMARY KEY, v frozen<tuple<int, text, float>>)");
33+ public void onTestContextInitialized() {
34+ execute("CREATE TABLE t (k int PRIMARY KEY, v frozen<tuple<int, text, float>>)");
3535 }
3636
3737 @Test(groups = "short")
@@ -55,17 +55,17 @@
5555
5656 @Test(groups = "short")
5757 public void simpleWriteReadTest() throws Exception {
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=?");
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=?");
6161
6262 TupleType t = TupleType.of(DataType.cint(), DataType.text(), DataType.cfloat());
6363
6464 int k = 1;
6565 TupleValue v = t.newValue(1, "a", 1.0f);
6666
67- session.execute(ins.bind(k, v));
68- 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");
6969
7070 assertEquals(v2, v);
7171
@@ -73,8 +73,8 @@
7373 k = 2;
7474 v = t.newValue(2, "b", 2.0f);
7575
76- session.execute("INSERT INTO t(k, v) VALUES (?, ?)", k, v);
77- 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");
7878
7979 assertEquals(v2, v);
8080 }
@@ -87,17 +87,17 @@
8787 */
8888 @Test(groups = "short")
8989 public void tupleTypeTest() throws Exception {
90- session.execute("CREATE KEYSPACE test_tuple_type " +
90+ session().execute("CREATE KEYSPACE test_tuple_type " +
9191 "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>>)");
92+ session().execute("USE test_tuple_type");
93+ session().execute("CREATE TABLE mytable (a int PRIMARY KEY, b frozen<tuple<ascii, int, boolean>>)");
9494
9595 TupleType t = TupleType.of(DataType.ascii(), DataType.cint(), DataType.cboolean());
9696
9797 // test non-prepared statement
9898 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");
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");
101101 assertEquals(r, complete);
102102
103103 // test incomplete tuples
@@ -112,8 +112,8 @@
112112 TupleType t1 = TupleType.of(DataType.ascii(), DataType.cint());
113113 TupleValue partial = t1.newValue("bar", 456);
114114 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");
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");
117117 assertEquals(r, partionResult);
118118
119119 // test single value tuples
@@ -128,20 +128,20 @@
128128 TupleType t2 = TupleType.of(DataType.ascii());
129129 TupleValue subpartial = t2.newValue("zoo");
130130 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");
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");
133133 assertEquals(r, subpartialResult);
134134
135135 // 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);
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);
145145 }
146146
147147 /**
@@ -153,9 +153,9 @@
153153 */
154154 @Test(groups = "short")
155155 public void tupleTestTypeVaryingLengths() throws Exception {
156- session.execute("CREATE KEYSPACE test_tuple_type_varying_lengths " +
156+ session().execute("CREATE KEYSPACE test_tuple_type_varying_lengths " +
157157 "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
158- session.execute("USE test_tuple_type_varying_lengths");
158+ session().execute("USE test_tuple_type_varying_lengths");
159159
160160 // programmatically create the table with tuples of said sizes
161161 int[] lengths = {1, 2, 3, 384};
@@ -167,7 +167,7 @@
167167 }
168168 valueSchema.add(String.format(" v_%d frozen<tuple<%s>>", i, Joiner.on(',').join(ints)));
169169 }
170- session.execute(String.format("CREATE TABLE mytable (k int PRIMARY KEY, %s)", Joiner.on(',').join(valueSchema)));
170+ session().execute(String.format("CREATE TABLE mytable (k int PRIMARY KEY, %s)", Joiner.on(',').join(valueSchema)));
171171
172172 // insert tuples into same key using different columns
173173 // and verify the results
@@ -183,10 +183,10 @@
183183 TupleValue createdTuple = t.newValue(values.toArray());
184184
185185 // write tuple
186- session.execute(String.format("INSERT INTO mytable (k, v_%s) VALUES (0, ?)", i), createdTuple);
186+ session().execute(String.format("INSERT INTO mytable (k, v_%s) VALUES (0, ?)", i), createdTuple);
187187
188188 // 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));
189+ TupleValue r = session().execute(String.format("SELECT v_%s FROM mytable WHERE k=0", i)).one().getTupleValue(String.format("v_%s", i));
190190 assertEquals(r, createdTuple);
191191 }
192192 }
@@ -201,12 +201,12 @@
201201 public void tupleSubtypesTest() throws Exception {
202202
203203 List<DataType> DATA_TYPE_PRIMITIVES = Lists.newArrayList(PrimitiveTypeSamples.ALL.keySet());
204- session.execute("CREATE KEYSPACE test_tuple_subtypes " +
204+ session().execute("CREATE KEYSPACE test_tuple_subtypes " +
205205 "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
206- session.execute("USE test_tuple_subtypes");
206+ session().execute("USE test_tuple_subtypes");
207207
208208 // 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)));
209+ session().execute(String.format("CREATE TABLE mytable (k int PRIMARY KEY, v frozen<tuple<%s>>)", Joiner.on(',').join(DATA_TYPE_PRIMITIVES)));
210210
211211 // insert tuples into same key using different columns
212212 // and verify the results
@@ -240,10 +240,10 @@
240240 TupleValue completeTuple = t2.newValue(completeValues.toArray());
241241
242242 // write tuple
243- session.execute(String.format("INSERT INTO mytable (k, v) VALUES (%s, ?)", i), createdTuple);
243+ session().execute(String.format("INSERT INTO mytable (k, v) VALUES (%s, ?)", i), createdTuple);
244244
245245 // read tuple
246- TupleValue r = session.execute("SELECT v FROM mytable WHERE k=?", i).one().getTupleValue("v");
246+ TupleValue r = session().execute("SELECT v FROM mytable WHERE k=?", i).one().getTupleValue("v");
247247
248248 assertEquals(r, completeTuple);
249249 ++i;
@@ -260,9 +260,9 @@
260260 public void tupleNonPrimitiveSubTypesTest() throws Exception {
261261
262262 List<DataType> DATA_TYPE_PRIMITIVES = Lists.newArrayList(PrimitiveTypeSamples.ALL.keySet());
263- session.execute("CREATE KEYSPACE test_tuple_non_primitive_subtypes " +
263+ session().execute("CREATE KEYSPACE test_tuple_non_primitive_subtypes " +
264264 "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
265- session.execute("USE test_tuple_non_primitive_subtypes");
265+ session().execute("USE test_tuple_non_primitive_subtypes");
266266
267267 ArrayList<String> values = new ArrayList<String>();
268268
@@ -282,7 +282,7 @@
282282 }
283283
284284 // create table
285- session.execute(String.format("CREATE TABLE mytable (k int PRIMARY KEY, %s)", Joiner.on(',').join(values)));
285+ session().execute(String.format("CREATE TABLE mytable (k int PRIMARY KEY, %s)", Joiner.on(',').join(values)));
286286
287287
288288 int i = 0;
@@ -299,10 +299,10 @@
299299 TupleValue createdTuple = t.newValue(createdValues.toArray());
300300
301301 // write tuple
302- session.execute(String.format("INSERT INTO mytable (k, v_%s) VALUES (0, ?)", i), createdTuple);
302+ session().execute(String.format("INSERT INTO mytable (k, v_%s) VALUES (0, ?)", i), createdTuple);
303303
304304 // read tuple
305- TupleValue r = session.execute(String.format("SELECT v_%s FROM mytable WHERE k=0", i))
305+ TupleValue r = session().execute(String.format("SELECT v_%s FROM mytable WHERE k=0", i))
306306 .one().getTupleValue(String.format("v_%s", i));
307307
308308 assertEquals(r, createdTuple);
@@ -322,10 +322,10 @@
322322 TupleValue createdTuple = t.newValue(createdValues.toArray());
323323
324324 // write tuple
325- session.execute(String.format("INSERT INTO mytable (k, v_%s) VALUES (0, ?)", i), createdTuple);
325+ session().execute(String.format("INSERT INTO mytable (k, v_%s) VALUES (0, ?)", i), createdTuple);
326326
327327 // read tuple
328- TupleValue r = session.execute(String.format("SELECT v_%s FROM mytable WHERE k=0", i))
328+ TupleValue r = session().execute(String.format("SELECT v_%s FROM mytable WHERE k=0", i))
329329 .one().getTupleValue(String.format("v_%s", i));
330330
331331 assertEquals(r, createdTuple);
@@ -348,10 +348,10 @@
348348 TupleValue createdTuple = t.newValue(createdValues.toArray());
349349
350350 // write tuple
351- session.execute(String.format("INSERT INTO mytable (k, v_%s) VALUES (0, ?)", i), createdTuple);
351+ session().execute(String.format("INSERT INTO mytable (k, v_%s) VALUES (0, ?)", i), createdTuple);
352352
353353 // read tuple
354- TupleValue r = session.execute(String.format("SELECT v_%s FROM mytable WHERE k=0", i))
354+ TupleValue r = session().execute(String.format("SELECT v_%s FROM mytable WHERE k=0", i))
355355 .one().getTupleValue(String.format("v_%s", i));
356356
357357 assertEquals(r, createdTuple);
@@ -391,12 +391,12 @@
391391 */
392392 @Test(groups = "short")
393393 public void nestedTuplesTest() throws Exception {
394- session.execute("CREATE KEYSPACE test_nested_tuples " +
394+ session().execute("CREATE KEYSPACE test_nested_tuples " +
395395 "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
396- session.execute("USE test_nested_tuples");
396+ session().execute("USE test_nested_tuples");
397397
398398 // create a table with multiple sizes of nested tuples
399- session.execute(String.format("CREATE TABLE mytable (" +
399+ session().execute(String.format("CREATE TABLE mytable (" +
400400 "k int PRIMARY KEY, " +
401401 "v_1 %s, " +
402402 "v_2 %s, " +
@@ -411,10 +411,10 @@
411411 TupleValue createdTuple = nestedTuplesCreatorHelper(i);
412412
413413 // write tuple
414- session.execute(String.format("INSERT INTO mytable (k, v_%s) VALUES (?, ?)", i), i, createdTuple);
414+ session().execute(String.format("INSERT INTO mytable (k, v_%s) VALUES (?, ?)", i), i, createdTuple);
415415
416416 // verify tuple was written and read correctly
417- TupleValue r = session.execute(String.format("SELECT v_%s FROM mytable WHERE k=?", i), i)
417+ TupleValue r = session().execute(String.format("SELECT v_%s FROM mytable WHERE k=?", i), i)
418418 .one().getTupleValue(String.format("v_%s", i));
419419
420420 assertEquals(r, createdTuple);
@@ -430,27 +430,27 @@
430430 @Test(groups = "short")
431431 public void testTuplesWithNulls() throws Exception {
432432 // create keyspace
433- session.execute("CREATE KEYSPACE testTuplesWithNulls " +
433+ session().execute("CREATE KEYSPACE testTuplesWithNulls " +
434434 "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
435- session.execute("USE testTuplesWithNulls");
435+ session().execute("USE testTuplesWithNulls");
436436
437437 // 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>)");
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>)");
440440
441441 // insert UDT data
442- UserType userTypeDef = cluster.getMetadata().getKeyspace("testTuplesWithNulls").getUserType("user");
442+ UserType userTypeDef = cluster().getMetadata().getKeyspace("testTuplesWithNulls").getUserType("user");
443443 UDTValue userType = userTypeDef.newValue();
444444
445445 TupleType t = TupleType.of(DataType.text(), DataType.cint(), DataType.uuid(), DataType.blob());
446446 TupleValue v = t.newValue(null, null, null, null);
447447 userType.setTupleValue("b", v);
448448
449- PreparedStatement ins = session.prepare("INSERT INTO mytable (a, b) VALUES (?, ?)");
450- session.execute(ins.bind(0, userType));
449+ PreparedStatement ins = session().prepare("INSERT INTO mytable (a, b) VALUES (?, ?)");
450+ session().execute(ins.bind(0, userType));
451451
452452 // retrieve and verify data
453- ResultSet rs = session.execute("SELECT * FROM mytable");
453+ ResultSet rs = session().execute("SELECT * FROM mytable");
454454 List<Row> rows = rs.all();
455455 assertEquals(1, rows.size());
456456
@@ -462,10 +462,10 @@
462462 // test empty strings
463463 v = t.newValue("", null, null, ByteBuffer.allocate(0));
464464 userType.setTupleValue("b", v);
465- session.execute(ins.bind(0, userType));
465+ session().execute(ins.bind(0, userType));
466466
467467 // retrieve and verify data
468- rs = session.execute("SELECT * FROM mytable");
468+ rs = session().execute("SELECT * FROM mytable");
469469 rows = rs.all();
470470 assertEquals(1, rows.size());
471471
modified driver-core/src/test/java/com/datastax/driver/core/UserTypesTest.java +80 −80
@@ -41,11 +41,11 @@
4141 new ArrayList<DataType.Name>(EnumSet.of(DataType.Name.LIST, DataType.Name.SET, DataType.Name.MAP, DataType.Name.TUPLE));
4242
4343 @Override
44- public Collection<String> createTestFixtures() {
44+ public void onTestContextInitialized() {
4545 String type1 = "CREATE TYPE phone (alias text, number text)";
4646 String type2 = "CREATE TYPE address (street text, \"ZIP\" int, phones set<frozen<phone>>)";
4747 String table = "CREATE TABLE user (id int PRIMARY KEY, addr frozen<address>)";
48- return Arrays.asList(type1, type2, table);
48+ execute(type1, type2, table);
4949 }
5050
5151 /**
@@ -56,20 +56,20 @@
5656 @Test(groups = "short")
5757 public void simpleWriteReadTest() throws Exception {
5858 int userId = 0;
59- PreparedStatement ins = session.prepare("INSERT INTO user(id, addr) VALUES (?, ?)");
60- PreparedStatement sel = session.prepare("SELECT * FROM user WHERE id=?");
59+ PreparedStatement ins = session().prepare("INSERT INTO user(id, addr) VALUES (?, ?)");
60+ PreparedStatement sel = session().prepare("SELECT * FROM user WHERE id=?");
6161
62- UserType addrDef = cluster.getMetadata().getKeyspace(keyspace).getUserType("address");
63- 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");
6464
6565 UDTValue phone1 = phoneDef.newValue().setString("alias", "home").setString("number", "0123548790");
6666 UDTValue phone2 = phoneDef.newValue().setString("alias", "work").setString("number", "0698265251");
6767
6868 UDTValue addr = addrDef.newValue().setString("street", "1600 Pennsylvania Ave NW").setInt(quote("ZIP"), 20500).setSet("phones", ImmutableSet.of(phone1, phone2));
6969
70- session.execute(ins.bind(userId, addr));
70+ session().execute(ins.bind(userId, addr));
7171
72- Row r = session.execute(sel.bind(userId)).one();
72+ Row r = session().execute(sel.bind(userId)).one();
7373
7474 assertEquals(r.getInt("id"), 0);
7575 assertEquals(r.getUDTValue("addr"), addr);
@@ -83,17 +83,17 @@
8383 @Test(groups = "short")
8484 public void simpleUnpreparedWriteReadTest() throws Exception {
8585 int userId = 1;
86- UserType addrDef = cluster.getMetadata().getKeyspace(keyspace).getUserType("address");
87- UserType phoneDef = cluster.getMetadata().getKeyspace(keyspace).getUserType("phone");
86+ UserType addrDef = cluster().getMetadata().getKeyspace(keyspace).getUserType("address");
87+ UserType phoneDef = cluster().getMetadata().getKeyspace(keyspace).getUserType("phone");
8888
8989 UDTValue phone1 = phoneDef.newValue().setString("alias", "home").setString("number", "0123548790");
9090 UDTValue phone2 = phoneDef.newValue().setString("alias", "work").setString("number", "0698265251");
9191
9292 UDTValue addr = addrDef.newValue().setString("street", "1600 Pennsylvania Ave NW").setInt(quote("ZIP"), 20500).setSet("phones", ImmutableSet.of(phone1, phone2));
9393
94- session.execute("INSERT INTO user(id, addr) VALUES (?, ?)", userId, addr);
94+ session().execute("INSERT INTO user(id, addr) VALUES (?, ?)", userId, addr);
9595
96- Row r = session.execute("SELECT * FROM user WHERE id=?", userId).one();
96+ Row r = session().execute("SELECT * FROM user WHERE id=?", userId).one();
9797
9898 assertEquals(r.getInt("id"), 1);
9999 assertEquals(r.getUDTValue("addr"), addr);
@@ -106,31 +106,31 @@
106106 */
107107 @Test(groups = "short")
108108 public void nonExistingTypesTest() throws Exception {
109- UserType addrDef = cluster.getMetadata().getKeyspace(keyspace).getUserType("address1");
110- UserType phoneDef = cluster.getMetadata().getKeyspace(keyspace).getUserType("phone1");
109+ UserType addrDef = cluster().getMetadata().getKeyspace(keyspace).getUserType("address1");
110+ UserType phoneDef = cluster().getMetadata().getKeyspace(keyspace).getUserType("phone1");
111111 assertEquals(addrDef, null);
112112 assertEquals(phoneDef, null);
113113
114- addrDef = cluster.getMetadata().getKeyspace(keyspace).getUserType("address");
115- phoneDef = cluster.getMetadata().getKeyspace(keyspace).getUserType("phone");
114+ addrDef = cluster().getMetadata().getKeyspace(keyspace).getUserType("address");
115+ phoneDef = cluster().getMetadata().getKeyspace(keyspace).getUserType("phone");
116116 assertNotEquals(addrDef, null);
117117 assertNotEquals(phoneDef, null);
118118
119119 // create keyspace
120120 String nonExistingKeyspace = keyspace + "_nonEx";
121- session.execute("CREATE KEYSPACE " + nonExistingKeyspace + " " +
121+ session().execute("CREATE KEYSPACE " + nonExistingKeyspace + " " +
122122 "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
123- session.execute("USE " + nonExistingKeyspace);
123+ session().execute("USE " + nonExistingKeyspace);
124124
125- addrDef = cluster.getMetadata().getKeyspace(nonExistingKeyspace).getUserType("address");
126- phoneDef = cluster.getMetadata().getKeyspace(nonExistingKeyspace).getUserType("phone");
125+ addrDef = cluster().getMetadata().getKeyspace(nonExistingKeyspace).getUserType("address");
126+ phoneDef = cluster().getMetadata().getKeyspace(nonExistingKeyspace).getUserType("phone");
127127 assertEquals(addrDef, null);
128128 assertEquals(phoneDef, null);
129129
130- session.execute("USE " + keyspace);
130+ session().execute("USE " + keyspace);
131131
132- addrDef = cluster.getMetadata().getKeyspace(keyspace).getUserType("address");
133- phoneDef = cluster.getMetadata().getKeyspace(keyspace).getUserType("phone");
132+ addrDef = cluster().getMetadata().getKeyspace(keyspace).getUserType("address");
133+ phoneDef = cluster().getMetadata().getKeyspace(keyspace).getUserType("phone");
134134 assertNotEquals(addrDef, null);
135135 assertNotEquals(phoneDef, null);
136136 }
@@ -145,9 +145,9 @@
145145 public void udtSizesTest() throws Exception {
146146 int MAX_TEST_LENGTH = 1024;
147147 // create keyspace
148- session.execute("CREATE KEYSPACE test_udt_sizes " +
148+ session().execute("CREATE KEYSPACE test_udt_sizes " +
149149 "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
150- session.execute("USE test_udt_sizes");
150+ session().execute("USE test_udt_sizes");
151151
152152 // create the seed udt
153153 StringBuilder sb = new StringBuilder();
@@ -157,13 +157,13 @@
157157 if (i + 1 < MAX_TEST_LENGTH)
158158 sb.append(",");
159159 }
160- session.execute(String.format("CREATE TYPE lengthy_udt (%s)", sb.toString()));
160+ session().execute(String.format("CREATE TYPE lengthy_udt (%s)", sb.toString()));
161161
162162 // create a table with multiple sizes of udts
163- session.execute("CREATE TABLE mytable (k int PRIMARY KEY, v frozen<lengthy_udt>)");
163+ session().execute("CREATE TABLE mytable (k int PRIMARY KEY, v frozen<lengthy_udt>)");
164164
165165 // hold onto the UserType for future use
166- UserType udtDef = cluster.getMetadata().getKeyspace("test_udt_sizes").getUserType("lengthy_udt");
166+ UserType udtDef = cluster().getMetadata().getKeyspace("test_udt_sizes").getUserType("lengthy_udt");
167167
168168 // verify inserts and reads
169169 for (int i : Arrays.asList(0, 1, 2, 3, MAX_TEST_LENGTH)) {
@@ -174,10 +174,10 @@
174174 }
175175
176176 // write udt
177- session.execute("INSERT INTO mytable (k, v) VALUES (0, ?)", createdUDT);
177+ session().execute("INSERT INTO mytable (k, v) VALUES (0, ?)", createdUDT);
178178
179179 // verify udt was written and read correctly
180- UDTValue r = session.execute("SELECT v FROM mytable WHERE k=0")
180+ UDTValue r = session().execute("SELECT v FROM mytable WHERE k=0")
181181 .one().getUDTValue("v");
182182 assertEquals(r.toString(), createdUDT.toString());
183183 }
@@ -192,9 +192,9 @@
192192 @Test(groups = "short")
193193 public void testPrimitiveDatatypes() throws Exception {
194194 // create keyspace
195- session.execute("CREATE KEYSPACE testPrimitiveDatatypes " +
195+ session().execute("CREATE KEYSPACE testPrimitiveDatatypes " +
196196 "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
197- session.execute("USE testPrimitiveDatatypes");
197+ session().execute("USE testPrimitiveDatatypes");
198198
199199 // create UDT
200200 List<String> alpha_type_list = new ArrayList<String>();
@@ -204,11 +204,11 @@
204204 DATA_TYPE_PRIMITIVES.get(i).getName()));
205205 }
206206
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>)");
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>)");
209209
210210 // insert UDT data
211- UserType alldatatypesDef = cluster.getMetadata().getKeyspace("testPrimitiveDatatypes").getUserType("alldatatypes");
211+ UserType alldatatypesDef = cluster().getMetadata().getKeyspace("testPrimitiveDatatypes").getUserType("alldatatypes");
212212 UDTValue alldatatypes = alldatatypesDef.newValue();
213213
214214 for (int i = 0; i < DATA_TYPE_PRIMITIVES.size(); i++) {
@@ -265,11 +265,11 @@
265265 }
266266 }
267267
268- PreparedStatement ins = session.prepare("INSERT INTO mytable (a, b) VALUES (?, ?)");
269- session.execute(ins.bind(0, alldatatypes));
268+ PreparedStatement ins = session().prepare("INSERT INTO mytable (a, b) VALUES (?, ?)");
269+ session().execute(ins.bind(0, alldatatypes));
270270
271271 // retrieve and verify data
272- ResultSet rs = session.execute("SELECT * FROM mytable");
272+ ResultSet rs = session().execute("SELECT * FROM mytable");
273273 List<Row> rows = rs.all();
274274 assertEquals(1, rows.size());
275275
@@ -288,9 +288,9 @@
288288 @Test(groups = "short")
289289 public void testNonPrimitiveDatatypes() throws Exception {
290290 // create keyspace
291- session.execute("CREATE KEYSPACE test_nonprimitive_datatypes " +
291+ session().execute("CREATE KEYSPACE test_nonprimitive_datatypes " +
292292 "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
293- session.execute("USE test_nonprimitive_datatypes");
293+ session().execute("USE test_nonprimitive_datatypes");
294294
295295 // counters are not allowed inside collections
296296 DATA_TYPE_PRIMITIVES.remove(DataType.counter());
@@ -317,11 +317,11 @@
317317 alpha_type_list.add(typeString);
318318 }
319319
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>)");
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>)");
322322
323323 // insert UDT data
324- UserType alldatatypesDef = cluster.getMetadata().getKeyspace("test_nonprimitive_datatypes").getUserType("alldatatypes");
324+ UserType alldatatypesDef = cluster().getMetadata().getKeyspace("test_nonprimitive_datatypes").getUserType("alldatatypes");
325325 UDTValue alldatatypes = alldatatypesDef.newValue();
326326
327327 for (int i = 0; i < DATA_TYPE_NON_PRIMITIVE_NAMES.size(); i++)
@@ -346,11 +346,11 @@
346346 }
347347 }
348348
349- PreparedStatement ins = session.prepare("INSERT INTO mytable (a, b) VALUES (?, ?)");
350- session.execute(ins.bind(0, alldatatypes));
349+ PreparedStatement ins = session().prepare("INSERT INTO mytable (a, b) VALUES (?, ?)");
350+ session().execute(ins.bind(0, alldatatypes));
351351
352352 // retrieve and verify data
353- ResultSet rs = session.execute("SELECT * FROM mytable");
353+ ResultSet rs = session().execute("SELECT * FROM mytable");
354354 List<Row> rows = rs.all();
355355 assertEquals(1, rows.size());
356356
@@ -370,41 +370,41 @@
370370 public void udtNestedTest() throws Exception {
371371 final int MAX_NESTING_DEPTH = 4;
372372 // create keyspace
373- session.execute("CREATE KEYSPACE udtNestedTest " +
373+ session().execute("CREATE KEYSPACE udtNestedTest " +
374374 "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
375- session.execute("USE udtNestedTest");
375+ session().execute("USE udtNestedTest");
376376
377377 // create UDT
378- session.execute("CREATE TYPE depth_0 (age int, name text)");
378+ session().execute("CREATE TYPE depth_0 (age int, name text)");
379379
380380 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)));
381+ session().execute(String.format("CREATE TYPE depth_%s (value frozen<depth_%s>)", String.valueOf(i), String.valueOf(i - 1)));
382382 }
383383
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>," +
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>," +
385385 "f frozen<depth_%s>)", MAX_NESTING_DEPTH));
386386
387387 // insert UDT data
388- UserType depthZeroDef = cluster.getMetadata().getKeyspace("udtNestedTest").getUserType("depth_0");
388+ UserType depthZeroDef = cluster().getMetadata().getKeyspace("udtNestedTest").getUserType("depth_0");
389389 UDTValue depthZero = depthZeroDef.newValue().setInt("age", 42).setString("name", "Bob");
390390
391- UserType depthOneDef = cluster.getMetadata().getKeyspace("udtNestedTest").getUserType("depth_1");
391+ UserType depthOneDef = cluster().getMetadata().getKeyspace("udtNestedTest").getUserType("depth_1");
392392 UDTValue depthOne = depthOneDef.newValue().setUDTValue("value", depthZero);
393393
394- UserType depthTwoDef = cluster.getMetadata().getKeyspace("udtNestedTest").getUserType("depth_2");
394+ UserType depthTwoDef = cluster().getMetadata().getKeyspace("udtNestedTest").getUserType("depth_2");
395395 UDTValue depthTwo = depthTwoDef.newValue().setUDTValue("value", depthOne);
396396
397- UserType depthThreeDef = cluster.getMetadata().getKeyspace("udtNestedTest").getUserType("depth_3");
397+ UserType depthThreeDef = cluster().getMetadata().getKeyspace("udtNestedTest").getUserType("depth_3");
398398 UDTValue depthThree = depthThreeDef.newValue().setUDTValue("value", depthTwo);
399399
400- UserType depthFourDef = cluster.getMetadata().getKeyspace("udtNestedTest").getUserType("depth_4");
400+ UserType depthFourDef = cluster().getMetadata().getKeyspace("udtNestedTest").getUserType("depth_4");
401401 UDTValue depthFour = depthFourDef.newValue().setUDTValue("value", depthThree);
402402
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));
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));
405405
406406 // retrieve and verify data
407- ResultSet rs = session.execute("SELECT * FROM mytable");
407+ ResultSet rs = session().execute("SELECT * FROM mytable");
408408 List<Row> rows = rs.all();
409409 assertEquals(1, rows.size());
410410
@@ -427,23 +427,23 @@
427427 @Test(groups = "short")
428428 public void testUdtsWithNulls() throws Exception {
429429 // create keyspace
430- session.execute("CREATE KEYSPACE testUdtsWithNulls " +
430+ session().execute("CREATE KEYSPACE testUdtsWithNulls " +
431431 "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
432- session.execute("USE testUdtsWithNulls");
432+ session().execute("USE testUdtsWithNulls");
433433
434434 // 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>)");
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>)");
437437
438438 // insert UDT data
439- UserType userTypeDef = cluster.getMetadata().getKeyspace("testUdtsWithNulls").getUserType("user");
439+ UserType userTypeDef = cluster().getMetadata().getKeyspace("testUdtsWithNulls").getUserType("user");
440440 UDTValue userType = userTypeDef.newValue().setString("a", null).setInt("b", 0).setUUID("c", null).setBytes("d", null);
441441
442- PreparedStatement ins = session.prepare("INSERT INTO mytable (a, b) VALUES (?, ?)");
443- session.execute(ins.bind(0, userType));
442+ PreparedStatement ins = session().prepare("INSERT INTO mytable (a, b) VALUES (?, ?)");
443+ session().execute(ins.bind(0, userType));
444444
445445 // retrieve and verify data
446- ResultSet rs = session.execute("SELECT * FROM mytable");
446+ ResultSet rs = session().execute("SELECT * FROM mytable");
447447 List<Row> rows = rs.all();
448448 assertEquals(1, rows.size());
449449
@@ -454,10 +454,10 @@
454454
455455 // test empty strings
456456 userType = userTypeDef.newValue().setString("a", "").setInt("b", 0).setUUID("c", null).setBytes("d", ByteBuffer.allocate(0));
457- session.execute(ins.bind(0, userType));
457+ session().execute(ins.bind(0, userType));
458458
459459 // retrieve and verify data
460- rs = session.execute("SELECT * FROM mytable");
460+ rs = session().execute("SELECT * FROM mytable");
461461 rows = rs.all();
462462 assertEquals(1, rows.size());
463463
@@ -475,38 +475,38 @@
475475 @Test(groups = "short")
476476 public void testUdtsWithCollectionNulls() throws Exception {
477477 // create keyspace
478- session.execute("CREATE KEYSPACE testUdtsWithCollectionNulls " +
478+ session().execute("CREATE KEYSPACE testUdtsWithCollectionNulls " +
479479 "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
480- session.execute("USE testUdtsWithCollectionNulls");
480+ session().execute("USE testUdtsWithCollectionNulls");
481481
482482 // 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>)");
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>)");
485485
486486 // insert null UDT data
487- PreparedStatement ins = session.prepare("INSERT INTO mytable (a, b) " +
487+ PreparedStatement ins = session().prepare("INSERT INTO mytable (a, b) " +
488488 "VALUES (0, { a: ?, b: ?, c: ?, d: ? })");
489- session.execute(ins.bind().setList(0, null).setSet(1, null).setMap(2, null).setTupleValue(3, null));
489+ session().execute(ins.bind().setList(0, null).setSet(1, null).setMap(2, null).setTupleValue(3, null));
490490
491491 // retrieve and verify data
492- ResultSet rs = session.execute("SELECT * FROM mytable");
492+ ResultSet rs = session().execute("SELECT * FROM mytable");
493493 List<Row> rows = rs.all();
494494 assertEquals(1, rows.size());
495495
496496 Row row = rows.get(0);
497497 assertEquals(row.getInt("a"), 0);
498498
499- UserType userTypeDef = cluster.getMetadata().getKeyspace("testUdtsWithCollectionNulls").getUserType("user");
499+ UserType userTypeDef = cluster().getMetadata().getKeyspace("testUdtsWithCollectionNulls").getUserType("user");
500500 UDTValue userType = userTypeDef.newValue().setList("a", null).setSet("b", null).setMap("c", null).setTupleValue("d", null);
501501 assertEquals(row.getUDTValue("b"), userType);
502502
503503 // test missing UDT args
504- ins = session.prepare("INSERT INTO mytable (a, b) " +
504+ ins = session().prepare("INSERT INTO mytable (a, b) " +
505505 "VALUES (1, { a: ? })");
506- session.execute(ins.bind().setList(0, new ArrayList<Object>()));
506+ session().execute(ins.bind().setList(0, new ArrayList<Object>()));
507507
508508 // retrieve and verify data
509- rs = session.execute("SELECT * FROM mytable");
509+ rs = session().execute("SELECT * FROM mytable");
510510 rows = rs.all();
511511 assertEquals(2, rows.size());
512512
modified driver-core/src/test/java/com/datastax/driver/core/exceptions/ExceptionsTest.java +10 −10
@@ -53,35 +53,35 @@
5353 };
5454
5555 // Create the schema once
56- session.execute(cqlCommands[0]);
57- session.execute(cqlCommands[1]);
58- session.execute(cqlCommands[2]);
56+ session().execute(cqlCommands[0]);
57+ session().execute(cqlCommands[1]);
58+ session().execute(cqlCommands[2]);
5959
6060 // Try creating the keyspace again
6161 try {
62- session.execute(cqlCommands[0]);
62+ session().execute(cqlCommands[0]);
6363 } catch (AlreadyExistsException e) {
6464 String expected = String.format("Keyspace %s already exists", keyspace.toLowerCase());
6565 assertEquals(e.getMessage(), expected);
6666 assertEquals(e.getKeyspace(), keyspace.toLowerCase());
6767 assertEquals(e.getTable(), null);
6868 assertEquals(e.wasTableCreation(), false);
69- assertEquals(e.getHost(), ccm.addressOfNode(1).getAddress());
70- assertEquals(e.getAddress(), ccm.addressOfNode(1));
69+ assertEquals(e.getHost(), ccm().addressOfNode(1).getAddress());
70+ assertEquals(e.getAddress(), ccm().addressOfNode(1));
7171 }
7272
73- session.execute(cqlCommands[1]);
73+ session().execute(cqlCommands[1]);
7474
7575 // Try creating the table again
7676 try {
77- session.execute(cqlCommands[2]);
77+ session().execute(cqlCommands[2]);
7878 } catch (AlreadyExistsException e) {
7979 // is released
8080 assertEquals(e.getKeyspace(), keyspace.toLowerCase());
8181 assertEquals(e.getTable(), table.toLowerCase());
8282 assertEquals(e.wasTableCreation(), true);
83- assertEquals(e.getHost(), ccm.addressOfNode(1).getAddress());
84- assertEquals(e.getAddress(), ccm.addressOfNode(1));
83+ assertEquals(e.getHost(), ccm().addressOfNode(1).getAddress());
84+ assertEquals(e.getAddress(), ccm().addressOfNode(1));
8585 }
8686 }
8787
modified driver-core/src/test/java/com/datastax/driver/core/policies/CloseableLoadBalancingPolicyTest.java +3 −3
@@ -30,8 +30,8 @@
3030 @Test(groups = "short")
3131 public void should_be_invoked_at_shutdown() {
3232 try {
33- cluster.connect();
34- cluster.close();
33+ cluster().connect();
34+ cluster().close();
3535 } finally {
3636 assertThat(policy.wasClosed).isTrue();
3737 }
@@ -41,7 +41,7 @@
4141 public Cluster.Builder createClusterBuilder() {
4242 policy = new CloseMonitoringPolicy(Policies.defaultLoadBalancingPolicy());
4343 return Cluster.builder()
44- .addContactPoints(ccm.addressOfNode(1).getAddress())
44+ .addContactPoints(getContactPoints().get(0))
4545 .withLoadBalancingPolicy(policy);
4646 }
4747
modified driver-core/src/test/java/com/datastax/driver/core/policies/DowngradingConsistencyRetryPolicyIntegrationTest.java +18 −7
@@ -37,19 +37,30 @@
3737 * receivedResponses in primed responses.
3838 * If that becomes possible in the future, we could refactor this test.
3939 */
40-@CCMConfig(dirtiesContext = true, createCluster = false, numberOfNodes = 3)
40+@CCMConfig(
41+ dirtiesContext = true,
42+ createCluster = false,
43+ numberOfNodes = 3,
44+ config = {
45+ // tests fail often with write or read timeouts
46+ "hinted_handoff_enabled:true",
47+ "phi_convict_threshold:5",
48+ "read_request_timeout_in_ms:100000",
49+ "write_request_timeout_in_ms:100000"
50+ }
51+)
4152 public class DowngradingConsistencyRetryPolicyIntegrationTest extends CCMTestsSupport {
4253
4354 @Test(groups = "long")
4455 public void should_downgrade_if_not_enough_replicas_for_requested_CL() {
4556 Cluster cluster = register(Cluster.builder()
46- .addContactPoints(ccm.addressOfNode(1).getAddress())
47- .withPort(ccm.getBinaryPort())
57+ .addContactPoints(getContactPoints().get(0))
58+ .withPort(ccm().getBinaryPort())
4859 .withRetryPolicy(Mockito.spy(DowngradingConsistencyRetryPolicy.INSTANCE))
4960 .build());
5061 Session session = cluster.connect();
5162
52- String ks = TestUtils.getAvailableKeyspaceName();
63+ String ks = TestUtils.generateIdentifier("ks_");
5364 session.execute(String.format("CREATE KEYSPACE %s WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 3}", ks));
5465 // tests fail randomly here with InvalidQueryException: Keyspace 'xxx' does not exist
5566 Uninterruptibles.sleepUninterruptibly(5, TimeUnit.SECONDS);
@@ -79,9 +90,9 @@
7990 }
8091
8192 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
93+ ccm().stop(node);
94+ ccm().waitForDown(node);// this uses port ping
95+ TestUtils.waitForDown(ipOfNode(node), cluster); // this uses UP/DOWN events
8596 }
8697
8798 private void checkAchievedConsistency(ConsistencyLevel requested, ConsistencyLevel expected, Session session) {
modified driver-core/src/test/java/com/datastax/driver/core/policies/TokenAwarePolicyTest.java +3 −3
@@ -323,13 +323,13 @@
323323 // given: a 3 node cluster with a keyspace with RF 1.
324324 Cluster cluster = register(Cluster.builder()
325325 .withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy()))
326- .addContactPointsWithPorts(ccm.addressOfNode(1))
327- .withPort(ccm.getBinaryPort())
326+ .addContactPoints(getContactPoints().get(0))
327+ .withPort(ccm().getBinaryPort())
328328 .build());
329329 Session session = cluster.connect();
330330
331331 String table = "composite";
332- String ks = TestUtils.getAvailableKeyspaceName();
332+ String ks = TestUtils.generateIdentifier("ks_");
333333 session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, ks, 1));
334334 session.execute("USE " + ks);
335335 session.execute(String.format("CREATE TABLE %s (k1 int, k2 int, i int, PRIMARY KEY ((k1, k2)))", table));
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilder21ExecutionTest.java +10 −13
@@ -22,9 +22,6 @@
2222 import com.datastax.driver.core.utils.CassandraVersion;
2323 import org.testng.annotations.Test;
2424
25-import java.util.Arrays;
26-import java.util.Collection;
27-
2825 import static com.datastax.driver.core.Assertions.assertThat;
2926 import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
3027
@@ -32,9 +29,9 @@
3229 public class QueryBuilder21ExecutionTest extends CCMTestsSupport {
3330
3431 @Override
35- public Collection<String> createTestFixtures() {
32+ public void onTestContextInitialized() {
3633 // Taken from http://www.datastax.com/dev/blog/cql-in-2-1
37- return Arrays.asList(
34+ execute(
3835 "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>)",
3936 "CREATE INDEX cat_index ON products(categories)",
4037 "CREATE INDEX buyers_index ON products(buyers)",
@@ -51,11 +48,11 @@
5148
5249 @Test(groups = "short")
5350 public void should_handle_contains_on_set_with_index() {
54- PreparedStatement byCategory = session.prepare(select("id", "description", "categories")
51+ PreparedStatement byCategory = session().prepare(select("id", "description", "categories")
5552 .from("products")
5653 .where(contains("categories", bindMarker("category"))));
5754
58- ResultSet results = session.execute(byCategory.bind().setString("category", "hdtv"));
55+ ResultSet results = session().execute(byCategory.bind().setString("category", "hdtv"));
5956
6057 assertThat(results.getAvailableWithoutFetching()).isEqualTo(2);
6158 for (Row row : results) {
@@ -65,11 +62,11 @@
6562
6663 @Test(groups = "short")
6764 public void should_handle_contains_on_list_with_index() {
68- PreparedStatement byBuyer = session.prepare(select("id", "description", "buyers")
65+ PreparedStatement byBuyer = session().prepare(select("id", "description", "buyers")
6966 .from("products")
7067 .where(contains("buyers", bindMarker("buyer"))));
7168
72- ResultSet results = session.execute(byBuyer.bind().setInt("buyer", 4));
69+ ResultSet results = session().execute(byBuyer.bind().setInt("buyer", 4));
7370
7471 Row row = results.one();
7572 assertThat(row).isNotNull();
@@ -79,11 +76,11 @@
7976
8077 @Test(groups = "short")
8178 public void should_handle_contains_on_map_with_index() {
82- PreparedStatement byFeatures = session.prepare(select("id", "description", "features_values")
79+ PreparedStatement byFeatures = session().prepare(select("id", "description", "features_values")
8380 .from("products")
8481 .where(contains("features_values", bindMarker("feature"))));
8582
86- ResultSet results = session.execute(byFeatures.bind().setString("feature", "LED"));
83+ ResultSet results = session().execute(byFeatures.bind().setString("feature", "LED"));
8784
8885 Row row = results.one();
8986 assertThat(row).isNotNull();
@@ -94,11 +91,11 @@
9491
9592 @Test(groups = "short")
9693 public void should_handle_contains_key_on_map_with_index() {
97- PreparedStatement byFeatures = session.prepare(select("id", "description", "features_keys")
94+ PreparedStatement byFeatures = session().prepare(select("id", "description", "features_keys")
9895 .from("products")
9996 .where(containsKey("features_keys", bindMarker("feature"))));
10097
101- ResultSet results = session.execute(byFeatures.bind().setString("feature", "refresh-rate"));
98+ ResultSet results = session().execute(byFeatures.bind().setString("feature", "refresh-rate"));
10299
103100 Row row = results.one();
104101 assertThat(row).isNotNull();
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderExecutionTest.java +34 −31
@@ -18,7 +18,10 @@
1818 import com.datastax.driver.core.*;
1919 import org.testng.annotations.Test;
2020
21-import java.util.*;
21+import java.util.Date;
22+import java.util.List;
23+import java.util.Map;
24+import java.util.Set;
2225
2326 import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
2427 import static org.assertj.core.api.Assertions.assertThat;
@@ -30,8 +33,8 @@
3033 private static final String TABLE1 = "test1";
3134
3235 @Override
33- public Collection<String> createTestFixtures() {
34- return Arrays.asList(
36+ public void onTestContextInitialized() {
37+ execute(
3538 String.format(TestUtils.CREATE_TABLE_SIMPLE_FORMAT, TABLE1),
3639 "CREATE TABLE dateTest (t timestamp PRIMARY KEY)",
3740 "CREATE TABLE test_coll (k int PRIMARY KEY, a list<int>, b map<int,text>, c set<text>)");
@@ -40,10 +43,10 @@
4043 @Test(groups = "short")
4144 public void executeTest() throws Exception {
4245
43- session.execute(insertInto(TABLE1).value("k", "k1").value("t", "This is a test").value("i", 3).value("f", 0.42));
44- session.execute(update(TABLE1).with(set("t", "Another test")).where(eq("k", "k2")));
46+ session().execute(insertInto(TABLE1).value("k", "k1").value("t", "This is a test").value("i", 3).value("f", 0.42));
47+ session().execute(update(TABLE1).with(set("t", "Another test")).where(eq("k", "k2")));
4548
46- List<Row> rows = session.execute(select().from(TABLE1).where(in("k", "k1", "k2"))).all();
49+ List<Row> rows = session().execute(select().from(TABLE1).where(in("k", "k1", "k2"))).all();
4750
4851 assertEquals(2, rows.size());
4952
@@ -64,9 +67,9 @@
6467 public void dateHandlingTest() throws Exception {
6568
6669 Date d = new Date();
67- session.execute(insertInto("dateTest").value("t", d));
70+ session().execute(insertInto("dateTest").value("t", d));
6871 String query = select().from("dateTest").where(eq(token("t"), fcall("token", d))).toString();
69- List<Row> rows = session.execute(query).all();
72+ List<Row> rows = session().execute(query).all();
7073
7174 assertEquals(1, rows.size());
7275
@@ -91,9 +94,9 @@
9194 public void batchNonBuiltStatementTest() throws Exception {
9295 SimpleStatement simple = new SimpleStatement("INSERT INTO " + TABLE1 + " (k, t) VALUES ('batchTest1', 'val1')");
9396 RegularStatement built = insertInto(TABLE1).value("k", "batchTest2").value("t", "val2");
94- session.execute(batch().add(simple).add(built));
97+ session().execute(batch().add(simple).add(built));
9598
96- List<Row> rows = session.execute(select().from(TABLE1).where(in("k", "batchTest1", "batchTest2"))).all();
99+ List<Row> rows = session().execute(select().from(TABLE1).where(in("k", "batchTest1", "batchTest2"))).all();
97100 assertEquals(2, rows.size());
98101
99102 Row r1 = rows.get(0);
@@ -108,75 +111,75 @@
108111 @Test(groups = "short")
109112 public void should_delete_list_element() throws Exception {
110113 //given
111- session.execute("INSERT INTO test_coll (k, a, b) VALUES (1, [1,2,3], null)");
114+ session().execute("INSERT INTO test_coll (k, a, b) VALUES (1, [1,2,3], null)");
112115 //when
113116 BuiltStatement statement = delete().listElt("a", 1).from("test_coll").where(eq("k", 1));
114- session.execute(statement);
117+ session().execute(statement);
115118 //then
116- List<Integer> actual = session.execute("SELECT a FROM test_coll WHERE k = 1").one().getList("a", Integer.class);
119+ List<Integer> actual = session().execute("SELECT a FROM test_coll WHERE k = 1").one().getList("a", Integer.class);
117120 assertThat(actual).containsExactly(1, 3);
118121 }
119122
120123 @Test(groups = "short")
121124 public void should_delete_list_element_with_bind_marker() throws Exception {
122125 //given
123- session.execute("INSERT INTO test_coll (k, a) VALUES (1, [1,2,3])");
126+ session().execute("INSERT INTO test_coll (k, a) VALUES (1, [1,2,3])");
124127 //when
125128 BuiltStatement statement = delete().listElt("a", bindMarker()).from("test_coll").where(eq("k", 1));
126- PreparedStatement ps = session.prepare(statement);
127- session.execute(ps.bind(1));
129+ PreparedStatement ps = session().prepare(statement);
130+ session().execute(ps.bind(1));
128131 //then
129- List<Integer> actual = session.execute("SELECT a FROM test_coll WHERE k = 1").one().getList("a", Integer.class);
132+ List<Integer> actual = session().execute("SELECT a FROM test_coll WHERE k = 1").one().getList("a", Integer.class);
130133 assertThat(actual).containsExactly(1, 3);
131134 }
132135
133136 @Test(groups = "short")
134137 public void should_delete_set_element() throws Exception {
135138 //given
136- session.execute("INSERT INTO test_coll (k, c) VALUES (1, {'foo','bar','qix'})");
139+ session().execute("INSERT INTO test_coll (k, c) VALUES (1, {'foo','bar','qix'})");
137140 //when
138141 BuiltStatement statement = delete().setElt("c", "foo").from("test_coll").where(eq("k", 1));
139- session.execute(statement);
142+ session().execute(statement);
140143 //then
141- Set<String> actual = session.execute("SELECT c FROM test_coll WHERE k = 1").one().getSet("c", String.class);
144+ Set<String> actual = session().execute("SELECT c FROM test_coll WHERE k = 1").one().getSet("c", String.class);
142145 assertThat(actual).containsOnly("bar", "qix");
143146 }
144147
145148 @Test(groups = "short")
146149 public void should_delete_set_element_with_bind_marker() throws Exception {
147150 //given
148- session.execute("INSERT INTO test_coll (k, c) VALUES (1, {'foo','bar','qix'})");
151+ session().execute("INSERT INTO test_coll (k, c) VALUES (1, {'foo','bar','qix'})");
149152 //when
150153 BuiltStatement statement = delete().setElt("c", bindMarker()).from("test_coll").where(eq("k", 1));
151- PreparedStatement ps = session.prepare(statement);
152- session.execute(ps.bind("foo"));
154+ PreparedStatement ps = session().prepare(statement);
155+ session().execute(ps.bind("foo"));
153156 //then
154- Set<String> actual = session.execute("SELECT c FROM test_coll WHERE k = 1").one().getSet("c", String.class);
157+ Set<String> actual = session().execute("SELECT c FROM test_coll WHERE k = 1").one().getSet("c", String.class);
155158 assertThat(actual).containsOnly("bar", "qix");
156159 }
157160
158161 @Test(groups = "short")
159162 public void should_delete_map_entry() throws Exception {
160163 //given
161- session.execute("INSERT INTO test_coll (k, b) VALUES (1, {1:'foo', 2:'bar'})");
164+ session().execute("INSERT INTO test_coll (k, b) VALUES (1, {1:'foo', 2:'bar'})");
162165 //when
163166 BuiltStatement statement = delete().mapElt("b", 1).from("test_coll").where(eq("k", 1));
164- session.execute(statement);
167+ session().execute(statement);
165168 //then
166- Map<Integer, String> actual = session.execute("SELECT b FROM test_coll WHERE k = 1").one().getMap("b", Integer.class, String.class);
169+ Map<Integer, String> actual = session().execute("SELECT b FROM test_coll WHERE k = 1").one().getMap("b", Integer.class, String.class);
167170 assertThat(actual).containsExactly(entry(2, "bar"));
168171 }
169172
170173 @Test(groups = "short")
171174 public void should_delete_map_entry_with_bind_marker() throws Exception {
172175 //given
173- session.execute("INSERT INTO test_coll (k, a, b) VALUES (1, null, {1:'foo', 2:'bar'})");
176+ session().execute("INSERT INTO test_coll (k, a, b) VALUES (1, null, {1:'foo', 2:'bar'})");
174177 //when
175178 BuiltStatement statement = delete().mapElt("b", bindMarker()).from("test_coll").where(eq("k", 1));
176- PreparedStatement ps = session.prepare(statement);
177- session.execute(ps.bind().setInt(0, 1));
179+ PreparedStatement ps = session().prepare(statement);
180+ session().execute(ps.bind().setInt(0, 1));
178181 //then
179- Map<Integer, String> actual = session.execute("SELECT b FROM test_coll WHERE k = 1").one().getMap("b", Integer.class, String.class);
182+ Map<Integer, String> actual = session().execute("SELECT b FROM test_coll WHERE k = 1").one().getMap("b", Integer.class, String.class);
180183 assertThat(actual).containsExactly(entry(2, "bar"));
181184 }
182185
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderITest.java +22 −23
@@ -21,7 +21,6 @@
2121 import org.testng.annotations.Test;
2222
2323 import java.util.Arrays;
24-import java.util.Collection;
2524 import java.util.TreeSet;
2625
2726 import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
@@ -34,8 +33,8 @@
3433 private static final String TABLE_INT = "test_int";
3534
3635 @Override
37- public Collection<String> createTestFixtures() {
38- return Arrays.asList(String.format("CREATE TABLE %s (k text PRIMARY KEY, a int, b int)", TABLE_TEXT),
36+ public void onTestContextInitialized() {
37+ execute(String.format("CREATE TABLE %s (k text PRIMARY KEY, a int, b int)", TABLE_TEXT),
3938 String.format("CREATE TABLE %s (k int PRIMARY KEY, a int, b int)", TABLE_INT));
4039 }
4140
@@ -43,14 +42,14 @@
4342 public void remainingDeleteTests() throws Exception {
4443
4544 Statement query;
46- TableMetadata table = cluster.getMetadata().getKeyspace(keyspace).getTable(TABLE_TEXT);
45+ TableMetadata table = cluster().getMetadata().getKeyspace(keyspace).getTable(TABLE_TEXT);
4746 assertNotNull(table);
4847
4948 String expected = String.format("DELETE k FROM %s.test_text;", keyspace);
5049 query = delete("k").from(table);
5150 assertEquals(query.toString(), expected);
5251 try {
53- session.execute(query);
52+ session().execute(query);
5453 fail();
5554 } catch (SyntaxError e) {
5655 // Missing WHERE clause
@@ -65,16 +64,16 @@
6564 PreparedStatement ps;
6665 BoundStatement bs;
6766
68- session.execute("CREATE KEYSPACE foo WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1};");
69- session.execute("CREATE TABLE foo.foo ( k ascii PRIMARY KEY , i int, s ascii )");
70- session.execute("USE foo");
67+ session().execute("CREATE KEYSPACE foo WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1};");
68+ session().execute("CREATE TABLE foo.foo ( k ascii PRIMARY KEY , i int, s ascii )");
69+ session().execute("USE foo");
7170
7271 query = "SELECT * FROM foo WHERE k=?;";
7372 select = select().all().from("foo").where(eq("k", QueryBuilder.bindMarker()));
74- ps = session.prepare(select.toString());
73+ ps = session().prepare(select.toString());
7574 bs = ps.bind();
7675 assertEquals(select.toString(), query);
77- session.execute(bs.setString("k", "4 AND c=5"));
76+ session().execute(bs.setString("k", "4 AND c=5"));
7877
7978 query = "SELECT * FROM foo WHERE k='4'' AND c=''5';";
8079 select = select().all().from("foo").where(eq("k", "4' AND c='5"));
@@ -211,58 +210,58 @@
211210 @Test(groups = "short")
212211 @CassandraVersion(major = 2.0, minor = 7, description = "DELETE..IF EXISTS only supported in 2.0.7+ (CASSANDRA-5708)")
213212 public void conditionalDeletesTest() throws Exception {
214- session.execute(String.format("INSERT INTO %s.test_int (k, a, b) VALUES (1, 1, 1)", keyspace));
213+ session().execute(String.format("INSERT INTO %s.test_int (k, a, b) VALUES (1, 1, 1)", keyspace));
215214
216215 Statement delete;
217216 Row row;
218217 delete = delete().from(keyspace, TABLE_INT).where(eq("k", 2)).ifExists();
219- row = session.execute(delete).one();
218+ row = session().execute(delete).one();
220219 assertFalse(row.getBool("[applied]"));
221220
222221 delete = delete().from(keyspace, TABLE_INT).where(eq("k", 1)).ifExists();
223- row = session.execute(delete).one();
222+ row = session().execute(delete).one();
224223 assertTrue(row.getBool("[applied]"));
225224
226- session.execute(String.format("INSERT INTO %s.test_int (k, a, b) VALUES (1, 1, 1)", keyspace));
225+ session().execute(String.format("INSERT INTO %s.test_int (k, a, b) VALUES (1, 1, 1)", keyspace));
227226
228227 delete = delete().from(keyspace, TABLE_INT).where(eq("k", 1)).onlyIf(eq("a", 1)).and(eq("b", 2));
229- row = session.execute(delete).one();
228+ row = session().execute(delete).one();
230229 assertFalse(row.getBool("[applied]"));
231230
232231 delete = delete().from(keyspace, TABLE_INT).where(eq("k", 1)).onlyIf(eq("a", 1)).and(eq("b", 1));
233- row = session.execute(delete).one();
232+ row = session().execute(delete).one();
234233 assertTrue(row.getBool("[applied]"));
235234 }
236235
237236 @Test(groups = "short")
238237 @CassandraVersion(major = 2.0, minor = 13, description = "Allow IF EXISTS for UPDATE statements (CASSANDRA-8610)")
239238 public void conditionalUpdatesTest() throws Exception {
240- session.execute(String.format("INSERT INTO %s.test_int (k, a, b) VALUES (1, 1, 1)", keyspace));
239+ session().execute(String.format("INSERT INTO %s.test_int (k, a, b) VALUES (1, 1, 1)", keyspace));
241240
242241 Statement update;
243242 Row row;
244243 update = update(TABLE_INT).with(set("a", 2)).and(set("b", 2)).where(eq("k", 2)).ifExists();
245- row = session.execute(update).one();
244+ row = session().execute(update).one();
246245 assertFalse(row.getBool("[applied]"));
247246
248247 update = update(TABLE_INT).with(set("a", 2)).and(set("b", 2)).where(eq("k", 1)).ifExists();
249- row = session.execute(update).one();
248+ row = session().execute(update).one();
250249 assertTrue(row.getBool("[applied]"));
251250
252251 update = update(TABLE_INT).with(set("a", 2)).and(set("b", 2)).where(eq("k", 2)).onlyIf(eq("a", 1)).and(eq("b", 2));
253- row = session.execute(update).one();
252+ row = session().execute(update).one();
254253 assertFalse(row.getBool("[applied]"));
255254
256255 update = update(TABLE_INT).with(set("a", 3)).and(set("b", 3)).where(eq("k", 1)).onlyIf(eq("a", 2)).and(eq("b", 2));
257- row = session.execute(update).one();
256+ row = session().execute(update).one();
258257 assertTrue(row.getBool("[applied]"));
259258
260259 update = update(TABLE_INT).with(set("a", 4)).and(set("b", 4)).onlyIf(eq("a", 2)).and(eq("b", 2)).where(eq("k", 1));
261- row = session.execute(update).one();
260+ row = session().execute(update).one();
262261 assertFalse(row.getBool("[applied]"));
263262
264263 update = update(TABLE_INT).with(set("a", 4)).and(set("b", 4)).onlyIf(eq("a", 3)).and(eq("b", 3)).where(eq("k", 1));
265- row = session.execute(update).one();
264+ row = session().execute(update).one();
266265 assertTrue(row.getBool("[applied]"));
267266 }
268267 }
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderRoutingKeyTest.java +13 −15
@@ -19,8 +19,6 @@
1919 import org.testng.annotations.Test;
2020
2121 import java.nio.ByteBuffer;
22-import java.util.Arrays;
23-import java.util.Collection;
2422
2523 import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
2624 import static org.testng.Assert.assertEquals;
@@ -33,8 +31,8 @@
3331 private static final String TABLE_INT = "test_int";
3432
3533 @Override
36- public Collection<String> createTestFixtures() {
37- return Arrays.asList(String.format("CREATE TABLE %s (k text PRIMARY KEY, a int, b int)", TABLE_TEXT),
34+ public void onTestContextInitialized() {
35+ execute(String.format("CREATE TABLE %s (k text PRIMARY KEY, a int, b int)", TABLE_TEXT),
3836 String.format("CREATE TABLE %s (k int PRIMARY KEY, a int, b int)", TABLE_INT));
3937 }
4038
@@ -42,17 +40,17 @@
4240 public void textRoutingKeyTest() throws Exception {
4341
4442 Statement query;
45- TableMetadata table = cluster.getMetadata().getKeyspace(keyspace).getTable(TABLE_TEXT);
43+ TableMetadata table = cluster().getMetadata().getKeyspace(keyspace).getTable(TABLE_TEXT);
4644 assertNotNull(table);
4745
4846 String txt = "If she weighs the same as a duck... she's made of wood.";
4947 query = insertInto(table).values(new String[]{"k", "a", "b"}, new Object[]{txt, 1, 2});
5048 assertEquals(query.getRoutingKey(), ByteBuffer.wrap(txt.getBytes()));
51- session.execute(query);
49+ session().execute(query);
5250
5351 query = select().from(table).where(eq("k", txt));
5452 assertEquals(query.getRoutingKey(), ByteBuffer.wrap(txt.getBytes()));
55- Row row = session.execute(query).one();
53+ Row row = session().execute(query).one();
5654 assertEquals(row.getString("k"), txt);
5755 assertEquals(row.getInt("a"), 1);
5856 assertEquals(row.getInt("b"), 2);
@@ -62,18 +60,18 @@
6260 public void intRoutingKeyTest() throws Exception {
6361
6462 Statement query;
65- TableMetadata table = cluster.getMetadata().getKeyspace(keyspace).getTable(TABLE_INT);
63+ TableMetadata table = cluster().getMetadata().getKeyspace(keyspace).getTable(TABLE_INT);
6664 assertNotNull(table);
6765
6866 query = insertInto(table).values(new String[]{"k", "a", "b"}, new Object[]{42, 1, 2});
6967 ByteBuffer bb = ByteBuffer.allocate(4);
7068 bb.putInt(0, 42);
7169 assertEquals(query.getRoutingKey(), bb);
72- session.execute(query);
70+ session().execute(query);
7371
7472 query = select().from(table).where(eq("k", 42));
7573 assertEquals(query.getRoutingKey(), bb);
76- Row row = session.execute(query).one();
74+ Row row = session().execute(query).one();
7775 assertEquals(row.getInt("k"), 42);
7876 assertEquals(row.getInt("a"), 1);
7977 assertEquals(row.getInt("b"), 2);
@@ -83,7 +81,7 @@
8381 public void intRoutingBatchKeyTest() throws Exception {
8482
8583 RegularStatement query;
86- TableMetadata table = cluster.getMetadata().getKeyspace(keyspace).getTable(TABLE_INT);
84+ TableMetadata table = cluster().getMetadata().getKeyspace(keyspace).getTable(TABLE_INT);
8785 assertNotNull(table);
8886
8987 ByteBuffer bb = ByteBuffer.allocate(4);
@@ -103,7 +101,7 @@
103101 .add(update(table).using(ttl(400)));
104102 assertEquals(batch.getRoutingKey(), bb);
105103 assertEquals(batch.toString(), batch_query);
106- // TODO: rs = session.execute(batch); // Not guaranteed to be valid CQL
104+ // TODO: rs = session().execute(batch); // Not guaranteed to be valid CQL
107105
108106 batch_query = "BEGIN BATCH ";
109107 batch_query += String.format("SELECT * FROM %s.test_int WHERE k=42;", keyspace);
@@ -111,7 +109,7 @@
111109 batch = batch(query);
112110 assertEquals(batch.getRoutingKey(), bb);
113111 assertEquals(batch.toString(), batch_query);
114- // TODO: rs = session.execute(batch); // Not guaranteed to be valid CQL
112+ // TODO: rs = session().execute(batch); // Not guaranteed to be valid CQL
115113
116114 batch_query = "BEGIN BATCH ";
117115 batch_query += "SELECT * FROM foo WHERE k=42;";
@@ -119,7 +117,7 @@
119117 batch = batch().add(select().from("foo").where(eq("k", 42)));
120118 assertEquals(batch.getRoutingKey(), null);
121119 assertEquals(batch.toString(), batch_query);
122- // TODO: rs = session.execute(batch); // Not guaranteed to be valid CQL
120+ // TODO: rs = session().execute(batch); // Not guaranteed to be valid CQL
123121
124122 batch_query = "BEGIN BATCH USING TIMESTAMP 42 ";
125123 batch_query += "INSERT INTO foo.bar (a) VALUES (123);";
@@ -127,6 +125,6 @@
127125 batch = batch().using(timestamp(42)).add(insertInto("foo", "bar").value("a", 123));
128126 assertEquals(batch.getRoutingKey(), null);
129127 assertEquals(batch.toString(), batch_query);
130- // TODO: rs = session.execute(batch); // Not guaranteed to be valid CQL
128+ // TODO: rs = session().execute(batch); // Not guaranteed to be valid CQL
131129 }
132130 }
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderUDTExecutionTest.java +10 −12
@@ -22,8 +22,6 @@
2222 import org.testng.annotations.Test;
2323
2424 import java.net.InetAddress;
25-import java.util.Arrays;
26-import java.util.Collection;
2725 import java.util.List;
2826 import java.util.Map;
2927
@@ -35,22 +33,22 @@
3533 public class QueryBuilderUDTExecutionTest extends CCMTestsSupport {
3634
3735 @Override
38- public Collection<String> createTestFixtures() {
39- return Arrays.asList("CREATE TYPE udt (i int, a inet)",
36+ public void onTestContextInitialized() {
37+ execute("CREATE TYPE udt (i int, a inet)",
4038 "CREATE TABLE udtTest(k int PRIMARY KEY, t frozen<udt>, l list<frozen<udt>>, m map<int, frozen<udt>>)");
4139 }
4240
4341 @Test(groups = "short")
4442 public void insertUdtTest() throws Exception {
45- UserType udtType = cluster.getMetadata().getKeyspace(keyspace).getUserType("udt");
43+ UserType udtType = cluster().getMetadata().getKeyspace(keyspace).getUserType("udt");
4644 UDTValue udtValue = udtType.newValue().setInt("i", 2).setInet("a", InetAddress.getByName("localhost"));
4745
4846 Statement insert = insertInto("udtTest").value("k", 1).value("t", udtValue);
4947 assertEquals(insert.toString(), "INSERT INTO udtTest (k,t) VALUES (1,{i:2, a:'127.0.0.1'});");
5048
51- session.execute(insert);
49+ session().execute(insert);
5250
53- List<Row> rows = session.execute(select().from("udtTest").where(eq("k", 1))).all();
51+ List<Row> rows = session().execute(select().from("udtTest").where(eq("k", 1))).all();
5452
5553 assertEquals(rows.size(), 1);
5654
@@ -60,16 +58,16 @@
6058
6159 @Test(groups = "short")
6260 public void should_handle_collections_of_UDT() throws Exception {
63- UserType udtType = cluster.getMetadata().getKeyspace(keyspace).getUserType("udt");
61+ UserType udtType = cluster().getMetadata().getKeyspace(keyspace).getUserType("udt");
6462 UDTValue udtValue = udtType.newValue().setInt("i", 2).setInet("a", InetAddress.getByName("localhost"));
6563 UDTValue udtValue2 = udtType.newValue().setInt("i", 3).setInet("a", InetAddress.getByName("localhost"));
6664
6765 Statement insert = insertInto("udtTest").value("k", 1).value("l", ImmutableList.of(udtValue));
6866 assertThat(insert.toString()).isEqualTo("INSERT INTO udtTest (k,l) VALUES (1,[{i:2, a:'127.0.0.1'}]);");
6967
70- session.execute(insert);
68+ session().execute(insert);
7169
72- List<Row> rows = session.execute(select().from("udtTest").where(eq("k", 1))).all();
70+ List<Row> rows = session().execute(select().from("udtTest").where(eq("k", 1))).all();
7371
7472 assertThat(rows.size()).isEqualTo(1);
7573
@@ -83,9 +81,9 @@
8381 assertThat(updateMap.toString())
8482 .isEqualTo("UPDATE udtTest SET m=m+{0:{i:2, a:'127.0.0.1'},2:{i:3, a:'127.0.0.1'}} WHERE k=1;");
8583
86- session.execute(updateMap);
84+ session().execute(updateMap);
8785
88- rows = session.execute(select().from("udtTest").where(eq("k", 1))).all();
86+ rows = session().execute(select().from("udtTest").where(eq("k", 1))).all();
8987 r1 = rows.get(0);
9088 assertThat(r1.getMap("m", Integer.class, UDTValue.class)).isEqualTo(map);
9189 }
modified driver-core/src/test/java/com/datastax/driver/core/schemabuilder/SchemaBuilderIT.java +22 −22
@@ -35,7 +35,7 @@
3535 @CassandraVersion(major = 2.1, minor = 2)
3636 public void should_modify_table_metadata() {
3737 // Create a table
38- session.execute(SchemaBuilder.createTable("ks", "TableMetadata")
38+ session().execute(SchemaBuilder.createTable("ks", "TableMetadata")
3939 .addPartitionKey("a", DataType.cint())
4040 .addPartitionKey("b", DataType.cint())
4141 .addClusteringColumn("c", DataType.cint())
@@ -45,7 +45,7 @@
4545 );
4646
4747 // Modify the table metadata
48- session.execute(SchemaBuilder.alterTable("TableMetadata")
48+ session().execute(SchemaBuilder.alterTable("TableMetadata")
4949 .withOptions()
5050 .defaultTimeToLive(1337)
5151 .bloomFilterFPChance(0.42)
@@ -68,7 +68,7 @@
6868 .compressionOptions(snappy()));
6969
7070 // Retrieve the metadata from Cassandra
71- ResultSet rows = session.execute("SELECT "
71+ ResultSet rows = session().execute("SELECT "
7272 + "bloom_filter_fp_chance, "
7373 + "caching, "
7474 + "cf_id, "
@@ -131,12 +131,12 @@
131131 @CassandraVersion(major = 2.1)
132132 public void should_create_a_table_and_a_udt() {
133133 // Create a UDT and a table
134- session.execute(SchemaBuilder.createType("MyUDT")
134+ session().execute(SchemaBuilder.createType("MyUDT")
135135 .ifNotExists()
136136 .addColumn("x", DataType.cint())
137137 );
138138 UDTType myUDT = UDTType.frozen("MyUDT");
139- session.execute(SchemaBuilder.createTable("ks", "CreateTable")
139+ session().execute(SchemaBuilder.createTable("ks", "CreateTable")
140140 .ifNotExists()
141141 .addPartitionKey("a", DataType.cint())
142142 .addUDTPartitionKey("b", myUDT)
@@ -152,7 +152,7 @@
152152 );
153153
154154 // Check columns a to k
155- ResultSet rows = session.execute(
155+ ResultSet rows = session().execute(
156156 "SELECT column_name, type, validator "
157157 + "FROM system.schema_columns "
158158 + "WHERE keyspace_name='ks' AND columnfamily_name='createtable'");
@@ -177,22 +177,22 @@
177177 @Test(groups = "short")
178178 public void should_add_and_drop_a_column() {
179179 // Create a table, add a column to it with an alter table statement and delete that column
180- session.execute(SchemaBuilder.createTable("ks", "DropColumn")
180+ session().execute(SchemaBuilder.createTable("ks", "DropColumn")
181181 .ifNotExists()
182182 .addPartitionKey("a", DataType.cint())
183183 );
184184
185185 // Add and then drop a column
186- session.execute(SchemaBuilder.alterTable("ks", "DropColumn")
186+ session().execute(SchemaBuilder.alterTable("ks", "DropColumn")
187187 .addColumn("b")
188188 .type(DataType.cint())
189189 );
190- session.execute(SchemaBuilder.alterTable("ks", "DropColumn")
190+ session().execute(SchemaBuilder.alterTable("ks", "DropColumn")
191191 .dropColumn("b")
192192 );
193193
194194 // Check that only column a exist
195- ResultSet rows = session.execute(
195+ ResultSet rows = session().execute(
196196 "SELECT column_name, type, validator "
197197 + "FROM system.schema_columns "
198198 + "WHERE keyspace_name='ks' AND columnfamily_name='dropcolumn'");
@@ -214,15 +214,15 @@
214214 @Test(groups = "short")
215215 public void should_drop_a_table() {
216216 // Create a table
217- session.execute(SchemaBuilder.createTable("ks", "DropTable")
217+ session().execute(SchemaBuilder.createTable("ks", "DropTable")
218218 .addPartitionKey("a", DataType.cint())
219219 );
220220
221221 // Drop the table
222- session.execute(SchemaBuilder.dropTable("ks", "DropTable"));
223- session.execute(SchemaBuilder.dropTable("DropTable").ifExists());
222+ session().execute(SchemaBuilder.dropTable("ks", "DropTable"));
223+ session().execute(SchemaBuilder.dropTable("DropTable").ifExists());
224224
225- ResultSet rows = session.execute(
225+ ResultSet rows = session().execute(
226226 "SELECT columnfamily_name "
227227 + "FROM system.schema_columnfamilies "
228228 + "WHERE keyspace_name='ks' AND columnfamily_name='droptable'");
@@ -234,24 +234,24 @@
234234 @Test(groups = "short")
235235 public void should_create_an_index() {
236236 // Create a table
237- session.execute(SchemaBuilder.createTable("ks", "CreateIndex")
237+ session().execute(SchemaBuilder.createTable("ks", "CreateIndex")
238238 .addPartitionKey("a", DataType.cint())
239239 .addClusteringColumn("b", DataType.cint())
240240 .addColumn("c", DataType.map(DataType.cint(), DataType.cint()))
241241 );
242242
243243 // Create an index on a regular column of the table
244- session.execute(SchemaBuilder.createIndex("ks_Index")
244+ session().execute(SchemaBuilder.createIndex("ks_Index")
245245 .onTable("ks", "CreateIndex")
246246 .andColumn("b")
247247 );
248- session.execute(SchemaBuilder.createIndex("ks_IndexOnMap")
248+ session().execute(SchemaBuilder.createIndex("ks_IndexOnMap")
249249 .onTable("ks", "CreateIndex")
250250 .andKeysOfColumn("c")
251251 );
252252
253253 // Verify that the indexes exist on the right columns
254- ResultSet rows = session.execute(
254+ ResultSet rows = session().execute(
255255 "SELECT column_name, index_name, index_options, index_type, component_index "
256256 + "FROM system.schema_columns "
257257 + "WHERE keyspace_name='ks' "
@@ -275,7 +275,7 @@
275275 @Test(groups = "short")
276276 public void should_drop_an_index() {
277277 // Create a table
278- session.execute(SchemaBuilder.createTable("ks", "DropIndex")
278+ session().execute(SchemaBuilder.createTable("ks", "DropIndex")
279279 .addPartitionKey("a", DataType.cint())
280280 .addClusteringColumn("b", DataType.cint())
281281 );
@@ -284,7 +284,7 @@
284284 // Note: we have to pick a lower-case name because Cassandra uses the CamelCase index name at creation
285285 // but a lowercase index name at deletion
286286 // See : https://issues.apache.org/jira/browse/CASSANDRA-8365
287- session.execute(SchemaBuilder.createIndex("ks_index")
287+ session().execute(SchemaBuilder.createIndex("ks_index")
288288 .onTable("ks", "DropIndex")
289289 .andColumn("b")
290290 );
@@ -293,14 +293,14 @@
293293 assertThat(numberOfIndexedColumns()).isEqualTo(1);
294294
295295 // Delete the index
296- session.execute(SchemaBuilder.dropIndex("ks", "ks_index"));
296+ session().execute(SchemaBuilder.dropIndex("ks", "ks_index"));
297297
298298 // Verify that only the PK index exists
299299 assertThat(numberOfIndexedColumns()).isEqualTo(0);
300300 }
301301
302302 private int numberOfIndexedColumns() {
303- ResultSet columns = session.execute(
303+ ResultSet columns = session().execute(
304304 "SELECT * "
305305 + "FROM system.schema_columns "
306306 + "WHERE keyspace_name='ks' "
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperAccessorParamsTest.java +15 −16
@@ -20,17 +20,16 @@
2020 import com.datastax.driver.core.Row;
2121 import com.datastax.driver.core.utils.CassandraVersion;
2222 import com.datastax.driver.mapping.annotations.*;
23-import com.google.common.collect.Lists;
2423 import org.testng.annotations.Test;
2524
26-import java.util.Collection;
27-
2825 import static org.assertj.core.api.Assertions.assertThat;
2926
27+@SuppressWarnings("unused")
3028 public class MapperAccessorParamsTest extends CCMTestsSupport {
29+
3130 @Override
32- public Collection<String> createTestFixtures() {
33- return Lists.newArrayList(
31+ public void onTestContextInitialized() {
32+ execute(
3433 "CREATE TABLE user ( key int primary key, gender int, home_phone text, work_phone text)",
3534 "CREATE INDEX on user(gender)",
3635 "CREATE TABLE user_str ( key int primary key, gender text)",
@@ -40,7 +39,7 @@
4039
4140 @Test(groups = "short")
4241 public void should_allow_enum_as_int_in_accessor_params() {
43- UserAccessor accessor = new MappingManager(session)
42+ UserAccessor accessor = new MappingManager(session())
4443 .createAccessor(UserAccessor.class);
4544
4645 accessor.addUser(0, Enum.FEMALE);
@@ -55,7 +54,7 @@
5554
5655 @Test(groups = "short")
5756 public void should_allow_enum_as_string_in_accessor_params() {
58- UserAccessor accessor = new MappingManager(session)
57+ UserAccessor accessor = new MappingManager(session())
5958 .createAccessor(UserAccessor.class);
6059
6160 accessor.addUserStr(0, Enum.FEMALE);
@@ -71,44 +70,44 @@
7170 @Test(groups = "short")
7271 @CassandraVersion(major = 2.0, description = "Uses named parameters")
7372 public void should_allow_less_parameters_than_bind_markers_if_there_are_repeated_names() {
74- UserPhoneAccessor accessor = new MappingManager(session)
73+ UserPhoneAccessor accessor = new MappingManager(session())
7574 .createAccessor(UserPhoneAccessor.class);
7675
77- session.execute("delete from user where key = 0");
76+ session().execute("delete from user where key = 0");
7877 accessor.updatePhones_positional("1111", "2222", 0);
7978 assertPhonesEqual(0, "1111", "2222");
8079
81- session.execute("delete from user where key = 0");
80+ session().execute("delete from user where key = 0");
8281 accessor.updatePhones_named(0, "1111", "2222");
8382 assertPhonesEqual(0, "1111", "2222");
8483
85- session.execute("delete from user where key = 0");
84+ session().execute("delete from user where key = 0");
8685 accessor.updatePhones_fallback("1111", "2222", 0);
8786 assertPhonesEqual(0, "1111", "2222");
8887
89- session.execute("delete from user where key = 0");
88+ session().execute("delete from user where key = 0");
9089 accessor.updateBothPhones(0, "1111");
9190 assertPhonesEqual(0, "1111", "1111");
9291
93- session.execute("delete from user where key = 0");
92+ session().execute("delete from user where key = 0");
9493 accessor.updatePhones_fallback2("1111", "2222", 0);
9594 assertPhonesEqual(0, "1111", "2222");
9695 }
9796
9897 @Test(groups = "short", expectedExceptions = RuntimeException.class)
9998 public void should_fail_if_not_enough_parameters() {
100- new MappingManager(session)
99+ new MappingManager(session())
101100 .createAccessor(UserPhoneAccessor_NotEnoughParams.class);
102101 }
103102
104103 @Test(groups = "short", expectedExceptions = RuntimeException.class)
105104 public void should_fail_if_too_many_parameters() {
106- new MappingManager(session)
105+ new MappingManager(session())
107106 .createAccessor(UserPhoneAccessor_TooManyParams.class);
108107 }
109108
110109 private void assertPhonesEqual(int key, String home, String work) {
111- Row row = session.execute("select * from user where key = " + key).one();
110+ Row row = session().execute("select * from user where key = " + key).one();
112111 assertThat(row.getString("home_phone")).isEqualTo(home);
113112 assertThat(row.getString("work_phone")).isEqualTo(work);
114113 }
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperAccessorTest.java +10 −13
@@ -22,23 +22,20 @@
2222 import com.datastax.driver.mapping.annotations.Accessor;
2323 import com.datastax.driver.mapping.annotations.Param;
2424 import com.datastax.driver.mapping.annotations.Query;
25-import com.google.common.collect.Lists;
2625 import org.testng.annotations.Test;
2726
28-import java.util.Collection;
29-
3027 import static org.assertj.core.api.Assertions.assertThat;
3128
3229 public class MapperAccessorTest extends CCMTestsSupport {
3330
3431 @Override
35- public Collection<String> createTestFixtures() {
36- return Lists.newArrayList("CREATE TABLE foo (k int primary key, v text)");
32+ public void onTestContextInitialized() {
33+ execute("CREATE TABLE foo (k int primary key, v text)");
3734 }
3835
3936 @Test(groups = "short")
4037 public void should_implement_toString() {
41- SystemAccessor accessor = new MappingManager(session)
38+ SystemAccessor accessor = new MappingManager(session())
4239 .createAccessor(SystemAccessor.class);
4340
4441 assertThat(accessor.toString())
@@ -47,7 +44,7 @@
4744
4845 @Test(groups = "short")
4946 public void should_implement_equals_and_hashCode() {
50- SystemAccessor accessor = new MappingManager(session)
47+ SystemAccessor accessor = new MappingManager(session())
5148 .createAccessor(SystemAccessor.class);
5249
5350 assertThat(accessor).isNotEqualTo(new Object());
@@ -57,32 +54,32 @@
5754 @Test(groups = "short")
5855 @CassandraVersion(major = 2.0)
5956 public void should_allow_null_argument_in_accessor_when_set_by_name() {
60- FooAccessor accessor = new MappingManager(session)
57+ FooAccessor accessor = new MappingManager(session())
6158 .createAccessor(FooAccessor.class);
6259
6360 accessor.insert(1, null);
64- Row row = session.execute("select * from foo where k = 1").one();
61+ Row row = session().execute("select * from foo where k = 1").one();
6562
6663 assertThat(row.getString("v")).isNull();
6764 }
6865
6966 @Test(groups = "short")
7067 public void should_allow_null_argument_in_accessor_when_set_by_index() {
71- FooBindMarkerAccessor accessor = new MappingManager(session)
68+ FooBindMarkerAccessor accessor = new MappingManager(session())
7269 .createAccessor(FooBindMarkerAccessor.class);
7370
7471 accessor.insert(1, null);
7572
76- Row row = session.execute("select * from foo where k = 1").one();
73+ Row row = session().execute("select * from foo where k = 1").one();
7774
7875 assertThat(row.getString("v")).isNull();
7976 }
8077
8178 @Test(groups = "short")
8279 public void should_allow_void_return_type_in_accessor() {
83- VoidAccessor accessor = new MappingManager(session).createAccessor(VoidAccessor.class);
80+ VoidAccessor accessor = new MappingManager(session()).createAccessor(VoidAccessor.class);
8481 accessor.insert(1, "bar");
85- Row row = session.execute("select * from foo where k = 1").one();
82+ Row row = session().execute("select * from foo where k = 1").one();
8683 assertThat(row.getInt("k")).isEqualTo(1);
8784 assertThat(row.getString("v")).isEqualTo("bar");
8885 }
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperCompositeKeyTest.java +3 −6
@@ -21,17 +21,14 @@
2121 import com.datastax.driver.mapping.annotations.Table;
2222 import org.testng.annotations.Test;
2323
24-import java.util.Collection;
25-import java.util.Collections;
26-
2724 /**
2825 * Tests for the mapper with composite partition keys and multiple clustering columns.
2926 */
3027 public class MapperCompositeKeyTest extends CCMTestsSupport {
3128
3229 @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))");
30+ public void onTestContextInitialized() {
31+ execute("CREATE TABLE test_table (pk1 int, pk2 int, cc1 int, cc2 int, PRIMARY KEY ((pk1, pk2), cc1, cc2))");
3532 }
3633
3734 @SuppressWarnings("unused")
@@ -84,6 +81,6 @@
8481
8582 @Test(groups = "short")
8683 public void testCreateMapper() throws Exception {
87- new MappingManager(session).mapper(TestTable.class);
84+ new MappingManager(session()).mapper(TestTable.class);
8885 }
8986 }
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperComputedFieldsTest.java +6 −9
@@ -19,13 +19,10 @@
1919 import com.datastax.driver.core.exceptions.InvalidQueryException;
2020 import com.datastax.driver.core.utils.CassandraVersion;
2121 import com.datastax.driver.mapping.annotations.*;
22-import com.google.common.collect.Lists;
2322 import org.testng.SkipException;
2423 import org.testng.annotations.BeforeMethod;
2524 import org.testng.annotations.Test;
2625
27-import java.util.Collection;
28-
2926 import static com.datastax.driver.core.Assertions.assertThat;
3027 import static com.datastax.driver.core.ProtocolVersion.V1;
3128 import static org.assertj.core.api.Assertions.fail;
@@ -38,8 +35,8 @@
3835 public class MapperComputedFieldsTest extends CCMTestsSupport {
3936
4037 @Override
41- public Collection<String> createTestFixtures() {
42- return Lists.newArrayList(
38+ public void onTestContextInitialized() {
39+ execute(
4340 "CREATE TABLE user (login text primary key, name text)",
4441 "INSERT INTO user (login, name) VALUES ('testlogin', 'test name')");
4542 }
@@ -50,8 +47,8 @@
5047
5148 @BeforeMethod(groups = "short")
5249 void setup() {
53- mappingManager = new MappingManager(session);
54- protocolVersion = cluster.getConfiguration().getProtocolOptions().getProtocolVersionEnum();
50+ mappingManager = new MappingManager(session());
51+ protocolVersion = cluster().getConfiguration().getProtocolOptions().getProtocolVersionEnum();
5552 if (protocolVersion.compareTo(V1) > 0)
5653 userMapper = mappingManager.mapper(User.class);
5754 }
@@ -81,7 +78,7 @@
8178 assertThat(fetched.getTtl()).isNull(); // TTL should be null since it was not set.
8279
8380 // Overwrite with TTL
84- session.execute("insert into user (login, name) values ('testlogin2', 'blah') using TTL 600");
81+ session().execute("insert into user (login, name) values ('testlogin2', 'blah') using TTL 600");
8582 fetched = userMapper.get("testlogin2");
8683 assertThat(fetched.getWriteTime()).isGreaterThanOrEqualTo(writeTime).isLessThan(writeTime + 30000000L);
8784 assertThat(fetched.getTtl()).isBetween(570, 600); // TTL should be within 30 secs.
@@ -103,7 +100,7 @@
103100 public void should_map_aliased_resultset_to_objects() {
104101 Statement getQuery = userMapper.getQuery("testlogin");
105102 getQuery.setConsistencyLevel(ConsistencyLevel.QUORUM);
106- ResultSet rs = session.execute(getQuery);
103+ ResultSet rs = session().execute(getQuery);
107104
108105 Result<User> result = userMapper.mapAliased(rs);
109106 User user = result.one();
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperDefaultKeyspaceTest.java +11 −13
@@ -23,8 +23,6 @@
2323 import com.google.common.base.Objects;
2424 import org.testng.annotations.Test;
2525
26-import java.util.Arrays;
27-import java.util.Collection;
2826 import java.util.UUID;
2927
3028 import static org.testng.Assert.assertEquals;
@@ -40,8 +38,8 @@
4038 private static final String KEYSPACE = "mapper_default_keyspace_test_ks";
4139
4240 @Override
43- public Collection<String> createTestFixtures() {
44- return Arrays.asList(
41+ public void onTestContextInitialized() {
42+ execute(
4543 "CREATE TABLE groups (group_id uuid PRIMARY KEY, name text)",
4644 "CREATE TYPE IF NOT EXISTS group_name (name text)");
4745 }
@@ -102,9 +100,9 @@
102100 @Test(groups = "short")
103101 public void testTableWithDefaultKeyspace() throws Exception {
104102 // Ensure that the test session is logged into the "ks" keyspace.
105- session.execute("USE " + keyspace);
103+ session().execute("USE " + keyspace);
106104
107- MappingManager manager = new MappingManager(session);
105+ MappingManager manager = new MappingManager(session());
108106 Mapper<Group> m = manager.mapper(Group.class);
109107 Group group = new Group("testGroup");
110108 UUID groupId = group.getGroupId();
@@ -212,13 +210,13 @@
212210 @Test(groups = "short")
213211 public void testUDTWithDefaultKeyspace() throws Exception {
214212 // Create test specific keyspace and table.
215- session.execute(String.format("CREATE KEYSPACE IF NOT EXISTS %s WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 }", KEYSPACE));
216- session.execute(String.format("CREATE TYPE IF NOT EXISTS %s.group_name (name text)", KEYSPACE));
217- session.execute(String.format("CREATE TABLE IF NOT EXISTS %s.groups2 (group_id uuid PRIMARY KEY, name frozen<group_name>)", KEYSPACE));
213+ session().execute(String.format("CREATE KEYSPACE IF NOT EXISTS %s WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 }", KEYSPACE));
214+ session().execute(String.format("CREATE TYPE IF NOT EXISTS %s.group_name (name text)", KEYSPACE));
215+ session().execute(String.format("CREATE TABLE IF NOT EXISTS %s.groups2 (group_id uuid PRIMARY KEY, name frozen<group_name>)", KEYSPACE));
218216 // Ensure that the test session is logged into the keyspace.
219- session.execute("USE " + keyspace);
217+ session().execute("USE " + keyspace);
220218
221- MappingManager manager = new MappingManager(session);
219+ MappingManager manager = new MappingManager(session());
222220 Mapper<Group2> m = manager.mapper(Group2.class);
223221 Group2 group = new Group2(new GroupName("testGroup"));
224222 UUID groupId = group.getGroupId();
@@ -239,7 +237,7 @@
239237 expectedExceptions = IllegalArgumentException.class,
240238 expectedExceptionsMessageRegExp = "Error creating mapper for class Group, the @Table annotation declares no default keyspace, and the session is not currently logged to any keyspace")
241239 public void should_throw_a_meaningful_error_message_when_no_default_table_keyspace_and_session_not_logged() {
242- Session session2 = cluster.connect();
240+ Session session2 = cluster().connect();
243241 MappingManager manager = new MappingManager(session2);
244242 manager.mapper(Group.class);
245243 }
@@ -248,7 +246,7 @@
248246 expectedExceptions = IllegalArgumentException.class,
249247 expectedExceptionsMessageRegExp = "Error creating UDT mapper for class GroupName, the @UDT annotation declares no default keyspace, and the session is not currently logged to any keyspace")
250248 public void should_throw_a_meaningful_error_message_when_no_default_udt_keyspace_and_session_not_logged() {
251- Session session2 = cluster.connect();
249+ Session session2 = cluster().connect();
252250 MappingManager manager = new MappingManager(session2);
253251 manager.udtMapper(GroupName.class);
254252 }
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperEnumTest.java +4 −7
@@ -19,11 +19,8 @@
1919 import com.datastax.driver.mapping.annotations.Enumerated;
2020 import com.datastax.driver.mapping.annotations.PartitionKey;
2121 import com.datastax.driver.mapping.annotations.Table;
22-import com.google.common.collect.Lists;
2322 import org.testng.annotations.Test;
2423
25-import java.util.Collection;
26-
2724 import static org.junit.Assert.assertNull;
2825
2926 /**
@@ -33,8 +30,8 @@
3330 public class MapperEnumTest extends CCMTestsSupport {
3431
3532 @Override
36- public Collection<String> createTestFixtures() {
37- return Lists.newArrayList("CREATE TABLE asOrdinal (k int primary key, v int)",
33+ public void onTestContextInitialized() {
34+ execute("CREATE TABLE asOrdinal (k int primary key, v int)",
3835 "CREATE TABLE asString (k int primary key, v text)");
3936 }
4037
@@ -44,7 +41,7 @@
4441
4542 @Test(groups = "short")
4643 public void should_handle_null_enum_as_ordinal() {
47- Mapper<AsOrdinal> mapper = new MappingManager(session).mapper(AsOrdinal.class);
44+ Mapper<AsOrdinal> mapper = new MappingManager(session()).mapper(AsOrdinal.class);
4845
4946 mapper.save(new AsOrdinal(1, null));
5047 AsOrdinal o = mapper.get(1);
@@ -54,7 +51,7 @@
5451
5552 @Test(groups = "short")
5653 public void should_handle_null_enum_as_string() {
57- Mapper<AsString> mapper = new MappingManager(session).mapper(AsString.class);
54+ Mapper<AsString> mapper = new MappingManager(session()).mapper(AsString.class);
5855
5956 mapper.save(new AsString(1, null));
6057 AsString o = mapper.get(1);
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperInvalidCollectionTypesTest.java +8 −6
@@ -20,14 +20,16 @@
2020 import com.datastax.driver.mapping.annotations.Table;
2121 import org.testng.annotations.Test;
2222
23-import java.util.*;
23+import java.util.ArrayList;
24+import java.util.HashSet;
25+import java.util.TreeMap;
2426
2527 @SuppressWarnings("unused")
2628 public class MapperInvalidCollectionTypesTest extends CCMTestsSupport {
2729
2830 @Override
29- public Collection<String> createTestFixtures() {
30- return Arrays.asList(
31+ public void onTestContextInitialized() {
32+ execute(
3133 "CREATE TABLE table_list (id int PRIMARY KEY, l list<int>)",
3234 "CREATE TABLE table_set (id int PRIMARY KEY, s set<int>)",
3335 "CREATE TABLE table_map (id int PRIMARY KEY, m map<int, int>)");
@@ -107,16 +109,16 @@
107109
108110 @Test(groups = "short", expectedExceptions = IllegalArgumentException.class)
109111 public void list_type_is_enforced() {
110- new MappingManager(session).mapper(InvalidList.class);
112+ new MappingManager(session()).mapper(InvalidList.class);
111113 }
112114
113115 @Test(groups = "short", expectedExceptions = IllegalArgumentException.class)
114116 public void map_type_is_enforced() {
115- new MappingManager(session).mapper(InvalidMap.class);
117+ new MappingManager(session()).mapper(InvalidMap.class);
116118 }
117119
118120 @Test(groups = "short", expectedExceptions = IllegalArgumentException.class)
119121 public void set_type_is_enforced() {
120- new MappingManager(session).mapper(InvalidSet.class);
122+ new MappingManager(session()).mapper(InvalidSet.class);
121123 }
122124 }
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperNestedCollectionsTest.java +8 −5
@@ -24,7 +24,10 @@
2424 import com.google.common.collect.Sets;
2525 import org.testng.annotations.Test;
2626
27-import java.util.*;
27+import java.util.ArrayList;
28+import java.util.List;
29+import java.util.Map;
30+import java.util.Set;
2831
2932 import static com.datastax.driver.core.Assertions.assertThat;
3033
@@ -33,8 +36,8 @@
3336 public class MapperNestedCollectionsTest extends CCMTestsSupport {
3437
3538 @Override
36- public Collection<String> createTestFixtures() {
37- return Lists.newArrayList(
39+ public void onTestContextInitialized() {
40+ execute(
3841 "CREATE TYPE testType(i int, ls list<frozen<set<int>>>)",
3942 "CREATE TABLE testTable (k int primary key, "
4043 + "m1 map<text, frozen<map<int, int>>>, " // nested collection
@@ -44,7 +47,7 @@
4447
4548 @Test(groups = "short")
4649 public void should_map_fields_to_nested_collections() {
47- Mapper<TestTable> mapper = new MappingManager(session).mapper(TestTable.class);
50+ Mapper<TestTable> mapper = new MappingManager(session()).mapper(TestTable.class);
4851
4952 TestTable testTable = new TestTable();
5053 testTable.setK(1);
@@ -67,7 +70,7 @@
6770
6871 @Test(groups = "short")
6972 public void should_map_accessor_params_to_nested_collections() {
70- MappingManager manager = new MappingManager(session);
73+ MappingManager manager = new MappingManager(session());
7174 Mapper<TestTable> mapper = manager.mapper(TestTable.class);
7275 TestAccessor accessor = manager.createAccessor(TestAccessor.class);
7376
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperOptionTest.java +11 −13
@@ -21,12 +21,10 @@
2121 import com.datastax.driver.core.utils.CassandraVersion;
2222 import com.datastax.driver.mapping.annotations.PartitionKey;
2323 import com.datastax.driver.mapping.annotations.Table;
24-import com.google.common.collect.Lists;
2524 import org.testng.SkipException;
2625 import org.testng.annotations.BeforeMethod;
2726 import org.testng.annotations.Test;
2827
29-import java.util.Collection;
3028 import java.util.concurrent.ExecutionException;
3129
3230 import static com.datastax.driver.core.ConsistencyLevel.*;
@@ -42,14 +40,14 @@
4240 Mapper<User> mapper;
4341
4442 @Override
45- public Collection<String> createTestFixtures() {
46- return Lists.newArrayList("CREATE TABLE user (key int primary key, v text)");
43+ public void onTestContextInitialized() {
44+ execute("CREATE TABLE user (key int primary key, v text)");
4745 }
4846
4947 @BeforeMethod(groups = "short")
5048 public void setup() {
51- mapper = new MappingManager(session).mapper(User.class);
52- protocolVersion = cluster.getConfiguration().getProtocolOptions().getProtocolVersionEnum();
49+ mapper = new MappingManager(session()).mapper(User.class);
50+ protocolVersion = cluster().getConfiguration().getProtocolOptions().getProtocolVersionEnum();
5351 }
5452
5553 @Test(groups = "short")
@@ -58,7 +56,7 @@
5856 Long tsValue = futureTimestamp();
5957 mapper.save(new User(42, "helloworld"), Option.timestamp(tsValue), Option.tracing(true));
6058 assertThat(mapper.get(42).getV()).isEqualTo("helloworld");
61- Long tsReturned = session.execute("SELECT writetime(v) FROM user WHERE key=" + 42).one().getLong(0);
59+ Long tsReturned = session().execute("SELECT writetime(v) FROM user WHERE key=" + 42).one().getLong(0);
6260 assertThat(tsReturned).isEqualTo(tsValue);
6361 }
6462
@@ -83,7 +81,7 @@
8381 assertThat(bs.isTracing()).isTrue();
8482 assertThat(bs.getConsistencyLevel()).isEqualTo(ALL);
8583
86- ResultSet rs = session.execute(bs);
84+ ResultSet rs = session().execute(bs);
8785 assertThat(rs.getExecutionInfo().getQueryTrace()).isNotNull();
8886 User us = mapper.mapAliased(rs).one();
8987 assertThat(us.getV()).isEqualTo("toget");
@@ -97,7 +95,7 @@
9795 Long tsValue = futureTimestamp();
9896 mapper.save(new User(43, "helloworld"), Option.timestamp(tsValue));
9997 mapper.save(new User(44, "test"));
100- Long tsReturned = session.execute("SELECT writetime(v) FROM user WHERE key=" + 44).one().getLong(0);
98+ Long tsReturned = session().execute("SELECT writetime(v) FROM user WHERE key=" + 44).one().getLong(0);
10199 // Assuming we cannot go back in time (yet) and execute the write at ts=1
102100 assertThat(tsReturned).isNotEqualTo(tsValue);
103101 }
@@ -165,7 +163,7 @@
165163 mapper.setDefaultSaveOptions(Option.timestamp(defaultTimestamp));
166164
167165 mapper.save(new User(42, "helloworld"), Option.timestamp(explicitTimestamp));
168- Long savedTimestamp = session.execute("SELECT writetime(v) FROM user WHERE key=" + 42).one().getLong(0);
166+ Long savedTimestamp = session().execute("SELECT writetime(v) FROM user WHERE key=" + 42).one().getLong(0);
169167 assertThat(savedTimestamp).isEqualTo(explicitTimestamp);
170168 }
171169
@@ -186,7 +184,7 @@
186184 assertThat(getWriteTime(user.getKey())).isEqualTo(timestamp);
187185 mapper.delete(user.getKey());
188186
189- session.execute(mapper.saveQuery(user, Option.timestamp(timestamp)));
187+ session().execute(mapper.saveQuery(user, Option.timestamp(timestamp)));
190188 assertThat(getWriteTime(user.getKey())).isEqualTo(timestamp);
191189 mapper.delete(user.getKey());
192190
@@ -201,13 +199,13 @@
201199 assertThat(getWriteTime(user.getKey())).isEqualTo(timestamp);
202200 mapper.delete(user.getKey());
203201
204- session.execute(mapper.saveQuery(user));
202+ session().execute(mapper.saveQuery(user));
205203 assertThat(getWriteTime(user.getKey())).isEqualTo(timestamp);
206204 mapper.delete(user.getKey());
207205 }
208206
209207 private Long getWriteTime(int key) {
210- Row row = session.execute("SELECT writetime(v) FROM user WHERE key=" + key).one();
208+ Row row = session().execute("SELECT writetime(v) FROM user WHERE key=" + key).one();
211209 return row.getLong(0);
212210 }
213211
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperPrimitiveTypesTest.java +3 −5
@@ -26,8 +26,6 @@
2626 import java.math.BigInteger;
2727 import java.net.InetAddress;
2828 import java.nio.ByteBuffer;
29-import java.util.Collection;
30-import java.util.Collections;
3129 import java.util.Date;
3230 import java.util.UUID;
3331
@@ -38,8 +36,8 @@
3836 */
3937 public class MapperPrimitiveTypesTest extends CCMTestsSupport {
4038
41- public Collection<String> createTestFixtures() {
42- return Collections.singletonList("CREATE TABLE primitiveTypes ("
39+ public void onTestContextInitialized() {
40+ execute("CREATE TABLE primitiveTypes ("
4341 + "byteBufferCol blob primary key,"
4442 + "intCol int, intWrapperCol int,"
4543 + "longCol bigint, longWrapperCol bigint,"
@@ -96,7 +94,7 @@
9694 primitiveTypes.setUuidCol(uuidCol);
9795 primitiveTypes.setTimeUuidCol(timeUuidCol);
9896
99- Mapper<PrimitiveTypes> mapper = new MappingManager(session).mapper(PrimitiveTypes.class);
97+ Mapper<PrimitiveTypes> mapper = new MappingManager(session()).mapper(PrimitiveTypes.class);
10098 mapper.save(primitiveTypes);
10199 PrimitiveTypes primitiveTypes2 = mapper.get(byteBufferCol);
102100
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperSaveNullFieldsTest.java +4 −7
@@ -20,12 +20,9 @@
2020 import com.datastax.driver.mapping.Mapper.Option;
2121 import com.datastax.driver.mapping.annotations.PartitionKey;
2222 import com.datastax.driver.mapping.annotations.Table;
23-import com.google.common.collect.Lists;
2423 import org.testng.annotations.BeforeMethod;
2524 import org.testng.annotations.Test;
2625
27-import java.util.Collection;
28-
2926 import static org.assertj.core.api.Assertions.assertThat;
3027
3128 @SuppressWarnings("unused")
@@ -34,13 +31,13 @@
3431 Mapper<User> mapper;
3532
3633 @Override
37- public Collection<String> createTestFixtures() {
38- return Lists.newArrayList("CREATE TABLE user (login text primary key, name text, phone text)");
34+ public void onTestContextInitialized() {
35+ execute("CREATE TABLE user (login text primary key, name text, phone text)");
3936 }
4037
4138 @BeforeMethod(groups = "short")
4239 public void setup() {
43- mapper = new MappingManager(session).mapper(User.class);
40+ mapper = new MappingManager(session()).mapper(User.class);
4441 }
4542
4643 @Test(groups = "short")
@@ -74,7 +71,7 @@
7471
7572 private void should_save_null_fields(boolean nullName, boolean nullPhone, boolean saveExpected, Option... options) {
7673 // Start with clean data
77- session.execute("insert into user(login, name, phone) "
74+ session().execute("insert into user(login, name, phone) "
7875 + "values ('test_login', 'previous_name', 'previous_phone')");
7976
8077 String newName = nullName ? null : "new_name";
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperTest.java +13 −10
@@ -24,7 +24,10 @@
2424 import org.testng.annotations.Test;
2525
2626 import java.net.InetAddress;
27-import java.util.*;
27+import java.util.Arrays;
28+import java.util.HashSet;
29+import java.util.Set;
30+import java.util.UUID;
2831
2932 import static org.assertj.core.api.Assertions.assertThat;
3033 import static org.testng.Assert.assertEquals;
@@ -37,10 +40,10 @@
3740 public class MapperTest extends CCMTestsSupport {
3841
3942 @Override
40- public Collection<String> createTestFixtures() {
43+ public void onTestContextInitialized() {
4144 // We'll allow to generate those create statement from the annotated entities later, but it's currently
4245 // a TODO
43- return Arrays.asList("CREATE TABLE users (user_id uuid PRIMARY KEY, name text, email text, year int, gender text)",
46+ execute("CREATE TABLE users (user_id uuid PRIMARY KEY, name text, email text, year int, gender text)",
4447 "CREATE TABLE posts (user_id uuid, post_id timeuuid, title text, content text, device inet, tags set<text>, PRIMARY KEY(user_id, post_id))");
4548 }
4649
@@ -301,7 +304,7 @@
301304 // Very simple mapping a User, saving and getting it. Note that here we
302305 // don't use the Accessor stuff since the queries we use are directly
303306 // supported by the Mapper object.
304- Mapper<User> m = new MappingManager(session).mapper(User.class);
307+ Mapper<User> m = new MappingManager(session()).mapper(User.class);
305308
306309 User u1 = new User("Paul", "paul@yahoo.com", User.Gender.MALE);
307310 u1.setYear(2014);
@@ -317,7 +320,7 @@
317320 @Test(groups = "short")
318321 @CassandraVersion(major = 2.0)
319322 public void testDynamicEntity() throws Exception {
320- MappingManager manager = new MappingManager(session);
323+ MappingManager manager = new MappingManager(session());
321324
322325 Mapper<Post> m = manager.mapper(Post.class);
323326
@@ -386,7 +389,7 @@
386389
387390 @Test(groups = "short")
388391 public void should_map_objects_from_partial_queries() throws Exception {
389- MappingManager manager = new MappingManager(session);
392+ MappingManager manager = new MappingManager(session());
390393
391394 Mapper<Post> m = manager.mapper(Post.class);
392395
@@ -404,7 +407,7 @@
404407 m.save(p3);
405408
406409 // Retrieve posts with a projection query that only retrieves some of the fields
407- ResultSet rs = session.execute("select user_id, post_id, title from posts where user_id = " + u1.getUserId());
410+ ResultSet rs = session().execute("select user_id, post_id, title from posts where user_id = " + u1.getUserId());
408411
409412 Result<Post> result = m.map(rs);
410413 for (Post post : result) {
@@ -417,13 +420,13 @@
417420 }
418421
419422 // cleanup
420- session.execute("delete from posts where user_id = " + u1.getUserId());
423+ session().execute("delete from posts where user_id = " + u1.getUserId());
421424 }
422425
423426
424427 @Test(groups = "short")
425428 public void should_return_table_metadata() throws Exception {
426- MappingManager manager = new MappingManager(session);
429+ MappingManager manager = new MappingManager(session());
427430
428431 Mapper<Post> m = manager.mapper(Post.class);
429432
@@ -434,7 +437,7 @@
434437
435438 @Test(groups = "short")
436439 public void should_not_initialize_session_when_protocol_version_provided() {
437- Session newSession = cluster.newSession();
440+ Session newSession = cluster().newSession();
438441
439442 // Ensures that a Session is not initialized when a protocol version is provided.
440443 MappingManager manager = new MappingManager(newSession, ProtocolVersion.V1);
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperUDTCollectionsTest.java +7 −5
@@ -23,7 +23,9 @@
2323 import org.testng.annotations.Test;
2424 import org.testng.collections.Lists;
2525
26-import java.util.*;
26+import java.util.List;
27+import java.util.Map;
28+import java.util.Set;
2729
2830 import static org.testng.Assert.assertEquals;
2931
@@ -34,8 +36,8 @@
3436 public class MapperUDTCollectionsTest extends CCMTestsSupport {
3537
3638 @Override
37- public Collection<String> createTestFixtures() {
38- return Arrays.asList("CREATE TYPE sub(i int)",
39+ public void onTestContextInitialized() {
40+ execute("CREATE TYPE sub(i int)",
3941 "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>>)");
4042 }
4143
@@ -174,7 +176,7 @@
174176
175177 @Test(groups = "short")
176178 public void testCollections() throws Exception {
177- Mapper<CollectionExamples> m = new MappingManager(session).mapper(CollectionExamples.class);
179+ Mapper<CollectionExamples> m = new MappingManager(session()).mapper(CollectionExamples.class);
178180
179181 CollectionExamples c = new CollectionExamples(1, 1);
180182 m.save(c);
@@ -184,7 +186,7 @@
184186
185187 @Test(groups = "short")
186188 public void testNullCollection() {
187- Mapper<CollectionExamples> m = new MappingManager(session).mapper(CollectionExamples.class);
189+ Mapper<CollectionExamples> m = new MappingManager(session()).mapper(CollectionExamples.class);
188190
189191 CollectionExamples c = new CollectionExamples(1, 1);
190192 c.setL(null);
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperUDTTest.java +7 −7
@@ -33,14 +33,14 @@
3333 public class MapperUDTTest extends CCMTestsSupport {
3434
3535 @Override
36- public Collection<String> createTestFixtures() {
37- return Arrays.asList("CREATE TYPE address (street text, city text, zip_code int, phones set<text>)",
36+ public void onTestContextInitialized() {
37+ execute("CREATE TYPE address (street text, city text, zip_code int, phones set<text>)",
3838 "CREATE TABLE users (user_id uuid PRIMARY KEY, name text, mainaddress frozen<address>, other_addresses map<text,frozen<address>>)");
3939 }
4040
4141 @BeforeMethod(groups = "short")
4242 public void clean() {
43- session.execute("TRUNCATE users");
43+ session().execute("TRUNCATE users");
4444 }
4545
4646 @Table(name = "users",
@@ -208,7 +208,7 @@
208208
209209 @Test(groups = "short")
210210 public void testSimpleEntity() throws Exception {
211- Mapper<User> m = new MappingManager(session).mapper(User.class);
211+ Mapper<User> m = new MappingManager(session()).mapper(User.class);
212212
213213 User u1 = new User("Paul", new Address("12 4th Street", "Springfield", 12345, "12341343", "435423245"));
214214 u1.addOtherAddress("work", new Address("5 Main Street", "Springfield", 12345, "23431342"));
@@ -219,7 +219,7 @@
219219
220220 @Test(groups = "short")
221221 public void should_handle_null_UDT_value() throws Exception {
222- Mapper<User> m = new MappingManager(session).mapper(User.class);
222+ Mapper<User> m = new MappingManager(session()).mapper(User.class);
223223
224224 User u1 = new User("Paul", null);
225225 m.save(u1);
@@ -229,9 +229,9 @@
229229
230230 @Test(groups = "short")
231231 public void testAccessor() throws Exception {
232- MappingManager manager = new MappingManager(session);
232+ MappingManager manager = new MappingManager(session());
233233
234- Mapper<User> m = new MappingManager(session).mapper(User.class);
234+ Mapper<User> m = new MappingManager(session()).mapper(User.class);
235235 User u1 = new User("Paul", new Address("12 4th Street", "Springfield", 12345, "12341343", "435423245"));
236236 m.save(u1);
237237
modified driver-mapping/src/test/java/com/datastax/driver/mapping/SyntheticFieldsMapperTest.java +3 −5
@@ -25,8 +25,6 @@
2525 import java.io.IOException;
2626 import java.io.InputStream;
2727 import java.lang.reflect.Constructor;
28-import java.util.Collection;
29-import java.util.Collections;
3028
3129 import static org.testng.Assert.assertEquals;
3230
@@ -34,8 +32,8 @@
3432 public class SyntheticFieldsMapperTest extends CCMTestsSupport {
3533
3634 @Override
37- public Collection<String> createTestFixtures() {
38- return Collections.singletonList("CREATE TABLE synthetic_fields (id int PRIMARY KEY)");
35+ public void onTestContextInitialized() {
36+ execute("CREATE TABLE synthetic_fields (id int PRIMARY KEY)");
3937 }
4038
4139 /**
@@ -61,7 +59,7 @@
6159 // Instead, it is a different Class (identity + ClassLoader), a modified version of ClassWithSyntheticField
6260 // Nice ClassCastException will be thrown if we try to cast it to ClassWithSyntheticField
6361 @SuppressWarnings("unchecked")
64- Mapper<Object> m = (Mapper<Object>) new MappingManager(session).mapper(classWithSyntheticFields);
62+ Mapper<Object> m = (Mapper<Object>) new MappingManager(session()).mapper(classWithSyntheticFields);
6563 m.save(instance);
6664
6765 assertEquals(m.get(42), instance);
modified driver-mapping/src/test/java/com/datastax/driver/mapping/UDTFieldMapperTest.java +19 −19
@@ -34,11 +34,11 @@
3434
3535 @Test(groups = "short")
3636 public void udt_and_tables_with_ks_created_in_another_session_should_be_mapped() {
37- Cluster cluster = register(Cluster.builder()
38- .addContactPointsWithPorts(ccm.addressOfNode(1))
39- .withPort(ccm.getBinaryPort())
37+ Cluster cluster1 = register(Cluster.builder()
38+ .addContactPoints(getContactPoints().get(0))
39+ .withPort(ccm().getBinaryPort())
4040 .build());
41- Session session1 = cluster.connect();
41+ Session session1 = cluster1.connect();
4242 // Create type and table
4343 session1.execute("create schema if not exists java_509 " +
4444 "with replication = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 };");
@@ -48,14 +48,14 @@
4848 session1.execute("create table java_509.my_hash (" +
4949 "key int primary key, " +
5050 "properties map<text, frozen<java_509.my_tuple>>);");
51- cluster.close();
51+ cluster1.close();
5252
5353 // Create entities with another connection
54- cluster = register(Cluster.builder()
55- .addContactPointsWithPorts(ccm.addressOfNode(1))
56- .withPort(ccm.getBinaryPort())
54+ Cluster cluster2 = register(Cluster.builder()
55+ .addContactPoints(getContactPoints().get(0))
56+ .withPort(ccm().getBinaryPort())
5757 .build());
58- Session session2 = cluster.newSession();
58+ Session session2 = cluster2.newSession();
5959 Mapper<MyHashWithKeyspace> hashMapper = new MappingManager(session2).mapper(MyHashWithKeyspace.class);
6060 hashMapper.save(new MyHashWithKeyspace(
6161 1,
@@ -76,11 +76,11 @@
7676
7777 @Test(groups = "short")
7878 public void udt_and_tables_without_ks_created_in_another_session_should_be_mapped() {
79- Cluster cluster = register(Cluster.builder()
80- .addContactPointsWithPorts(ccm.addressOfNode(1))
81- .withPort(ccm.getBinaryPort())
79+ Cluster cluster1 = register(Cluster.builder()
80+ .addContactPoints(getContactPoints().get(0))
81+ .withPort(ccm().getBinaryPort())
8282 .build());
83- Session session1 = cluster.connect();
83+ Session session1 = cluster1.connect();
8484 session1.execute("create schema if not exists java_509b " +
8585 "with replication = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 };");
8686 session1.execute("use java_509b");
@@ -90,14 +90,14 @@
9090 session1.execute("create table my_hash (" +
9191 "key int primary key, " +
9292 "properties map<text, frozen<my_tuple>>);");
93- cluster.close();
93+ cluster1.close();
9494
9595 // Create entities with another connection
96- cluster = Cluster.builder()
97- .addContactPointsWithPorts(ccm.addressOfNode(1))
98- .withPort(ccm.getBinaryPort())
99- .build();
100- Session session2 = cluster.newSession();
96+ Cluster cluster2 = register(Cluster.builder()
97+ .addContactPoints(getContactPoints().get(0))
98+ .withPort(ccm().getBinaryPort())
99+ .build());
100+ Session session2 = cluster2.newSession();
101101
102102 session2.execute("use java_509b");
103103 Mapper<MyHash> hashMapper = new MappingManager(session2).mapper(MyHash.class);