Elffuss BraidHub

kikocis/java-driver public

Merge branch '2.1' into 3.0

Conflicts:
	driver-core/src/test/java/com/datastax/driver/core/AuthenticationTest.java
	driver-core/src/test/java/com/datastax/driver/core/BatchStatementTest.java
	driver-core/src/test/java/com/datastax/driver/core/CustomTypeTest.java
	driver-core/src/test/java/com/datastax/driver/core/DataTypeIntegrationTest.java
	driver-core/src/test/java/com/datastax/driver/core/FetchingTest.java
	driver-core/src/test/java/com/datastax/driver/core/IndexMetadataTest.java
	driver-core/src/test/java/com/datastax/driver/core/LoadBalancingPolicyRefreshTest.java
	driver-core/src/test/java/com/datastax/driver/core/MetricsTest.java
	driver-core/src/test/java/com/datastax/driver/core/PreparedStatementTest.java
	driver-core/src/test/java/com/datastax/driver/core/QueryLoggerTest.java
	driver-core/src/test/java/com/datastax/driver/core/SSLEncryptionTest.java
	driver-core/src/test/java/com/datastax/driver/core/SchemaRefreshDebouncerTest.java
	driver-core/src/test/java/com/datastax/driver/core/SchemaTest.java
	driver-core/src/test/java/com/datastax/driver/core/SessionLeakTest.java
	driver-core/src/test/java/com/datastax/driver/core/SessionTest.java
	driver-core/src/test/java/com/datastax/driver/core/TableMetadataTest.java
	driver-core/src/test/java/com/datastax/driver/core/TestUtils.java
	driver-core/src/test/java/com/datastax/driver/core/TokenIntegrationTest.java
	driver-core/src/test/java/com/datastax/driver/core/UserTypesTest.java
	driver-core/src/test/java/com/datastax/driver/core/policies/DowngradingConsistencyRetryPolicyIntegrationTest.java
	driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderExecutionTest.java
	driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderRoutingKeyTest.java
	driver-mapping/src/test/java/com/datastax/driver/mapping/MapperAccessorParamsTest.java
	driver-mapping/src/test/java/com/datastax/driver/mapping/MapperComputedFieldsTest.java
	driver-mapping/src/test/java/com/datastax/driver/mapping/MapperDefaultKeyspaceTest.java
	driver-mapping/src/test/java/com/datastax/driver/mapping/MapperEnumTest.java
	driver-mapping/src/test/java/com/datastax/driver/mapping/MapperInvalidCollectionTypesTest.java
	driver-mapping/src/test/java/com/datastax/driver/mapping/MapperOptionTest.java
	driver-mapping/src/test/java/com/datastax/driver/mapping/MapperUDTCollectionsTest.java
	driver-mapping/src/test/java/com/datastax/driver/mapping/MapperUDTTest.java
Changeseta6b44c4c2439e462b5992b43feaedbff5687552cc11a313f3ea990aa144ab628
AuthorAlexandre Dutra <alexandre.dutra@datastax.com> · 2016-01-28 11:17 +01:00
CommitterAlexandre Dutra <alexandre.dutra@datastax.com> · 2016-01-28 11:17 +01:00
Parents95e17baa7f4f, b1d245a67292

Browse the files at this changeset

126 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
@@ -33,6 +33,7 @@
3333 import java.util.concurrent.*;
3434 import java.util.concurrent.atomic.AtomicReference;
3535
36+import static com.datastax.driver.core.ConditionChecker.check;
3637 import static org.assertj.core.api.Assertions.assertThat;
3738 import static org.mockito.Mockito.*;
3839 import static org.testng.Assert.fail;
@@ -43,8 +44,14 @@
4344 ScheduledExecutorService executor;
4445 MockReconnectionSchedule schedule;
4546 MockReconnectionWork work;
46- final AtomicReference<ListenableFuture<?>> future = new AtomicReference<ListenableFuture<?>>();
47+ AtomicReference<ListenableFuture<?>> future = new AtomicReference<ListenableFuture<?>>();
4748 AbstractReconnectionHandler handler;
49+ Callable<Boolean> nextTryAssigned = new Callable<Boolean>() {
50+ @Override
51+ public Boolean call() throws Exception {
52+ return handler.handlerFuture.nextTry != null;
53+ }
54+ };
4855
4956 @BeforeMethod(groups = {"unit", "short"})
5057 public void setup() {
@@ -60,7 +67,7 @@
6067
6168 @Override
6269 protected void onReconnection(Connection connection) {
63- work.onReconnection(connection);
70+ work.onReconnection();
6471 }
6572 };
6673 }
@@ -151,12 +158,7 @@
151158 verify(executor, timeout(10000)).schedule(handler, schedule.delay, TimeUnit.MILLISECONDS);
152159
153160 // Wait until nextTry is assigned after schedule completes.
154- ConditionChecker.awaitUntil(new Callable<Boolean>() {
155- @Override
156- public Boolean call() throws Exception {
157- return handler.handlerFuture.nextTry != null;
158- }
159- }, 10000);
161+ check().before(10000).that(nextTryAssigned).becomesTrue();
160162
161163 future.get().cancel(false);
162164
@@ -343,7 +345,7 @@
343345 tries += 1;
344346 logger.debug("in reconnection work, wait for tick from main thread");
345347 try {
346- barrier.await(10, TimeUnit.SECONDS);
348+ barrier.await(60, TimeUnit.SECONDS);
347349 logger.debug("in reconnection work, got tick from main thread, proceeding");
348350 } catch (Exception e) {
349351 fail("Error while waiting for tick", e);
@@ -364,14 +366,14 @@
364366 public void tick() {
365367 logger.debug("send tick to reconnection work");
366368 try {
367- barrier.await(10, TimeUnit.SECONDS);
369+ barrier.await(60, TimeUnit.SECONDS);
368370 } catch (Exception e) {
369371 fail("Error while sending tick, no thread was waiting", e);
370372 }
371373 barrier.reset();
372374 }
373375
374- protected void onReconnection(Connection connection) {
376+ protected void onReconnection() {
375377 success = true;
376378 }
377379 }
modified driver-core/src/test/java/com/datastax/driver/core/AggregateMetadataTest.java +18 −21
@@ -18,12 +18,9 @@
1818 import com.datastax.driver.core.utils.CassandraVersion;
1919 import org.testng.annotations.Test;
2020
21-import java.util.Collection;
22-
2321 import static com.datastax.driver.core.Assertions.assertThat;
2422 import static com.datastax.driver.core.DataType.cint;
2523 import static com.datastax.driver.core.DataType.text;
26-import static com.google.common.collect.Lists.newArrayList;
2724
2825 @CassandraVersion(major = 2.2)
2926 @CCMConfig(config = "enable_user_defined_functions:true")
@@ -35,10 +32,10 @@
3532 String cqlFunction = String.format("CREATE FUNCTION %s.cat(s text,v int) RETURNS NULL ON NULL INPUT RETURNS text LANGUAGE java AS 'return s+v;';", keyspace);
3633 String cqlAggregate = String.format("CREATE AGGREGATE %s.cat_tos(int) SFUNC cat STYPE text INITCOND '0';", keyspace);
3734 // when
38- session.execute(cqlFunction);
39- session.execute(cqlAggregate);
35+ session().execute(cqlFunction);
36+ session().execute(cqlAggregate);
4037 // then
41- KeyspaceMetadata keyspace = cluster.getMetadata().getKeyspace(this.keyspace);
38+ KeyspaceMetadata keyspace = cluster().getMetadata().getKeyspace(this.keyspace);
4239 FunctionMetadata stateFunc = keyspace.getFunction("cat", text(), cint());
4340 AggregateMetadata aggregate = keyspace.getAggregate("cat_tos", cint());
4441 assertThat(aggregate).isNotNull();
@@ -62,10 +59,10 @@
6259 String cqlFunction = String.format("CREATE FUNCTION %s.inc(i int) RETURNS NULL ON NULL INPUT RETURNS int LANGUAGE java AS 'return i+1;';", keyspace);
6360 String cqlAggregate = String.format("CREATE AGGREGATE %s.mycount() SFUNC inc STYPE int INITCOND 0;", keyspace);
6461 // when
65- session.execute(cqlFunction);
66- session.execute(cqlAggregate);
62+ session().execute(cqlFunction);
63+ session().execute(cqlAggregate);
6764 // then
68- KeyspaceMetadata keyspace = cluster.getMetadata().getKeyspace(this.keyspace);
65+ KeyspaceMetadata keyspace = cluster().getMetadata().getKeyspace(this.keyspace);
6966 FunctionMetadata stateFunc = keyspace.getFunction("inc", cint());
7067 AggregateMetadata aggregate = keyspace.getAggregate("mycount");
7168 assertThat(aggregate).isNotNull();
@@ -90,11 +87,11 @@
9087 String cqlFunction2 = String.format("CREATE FUNCTION %s.announce(i int) RETURNS NULL ON NULL INPUT RETURNS int LANGUAGE java AS 'return i;';", keyspace);
9188 String cqlAggregate = String.format("CREATE AGGREGATE %s.prettysum(int) SFUNC plus STYPE int FINALFUNC announce INITCOND 0;", keyspace);
9289 // when
93- session.execute(cqlFunction1);
94- session.execute(cqlFunction2);
95- session.execute(cqlAggregate);
90+ session().execute(cqlFunction1);
91+ session().execute(cqlFunction2);
92+ session().execute(cqlAggregate);
9693 // then
97- KeyspaceMetadata keyspace = cluster.getMetadata().getKeyspace(this.keyspace);
94+ KeyspaceMetadata keyspace = cluster().getMetadata().getKeyspace(this.keyspace);
9895 FunctionMetadata stateFunc = keyspace.getFunction("plus", cint(), cint());
9996 FunctionMetadata finalFunc = keyspace.getFunction("announce", cint());
10097 AggregateMetadata aggregate = keyspace.getAggregate("prettysum", cint());
@@ -120,10 +117,10 @@
120117 String cqlFunction = String.format("CREATE FUNCTION %s.plus2(i int, j int) CALLED ON NULL INPUT RETURNS int LANGUAGE java AS 'return i+j;';", keyspace);
121118 String cqlAggregate = String.format("CREATE AGGREGATE %s.sum(int) SFUNC plus2 STYPE int;", keyspace);
122119 // when
123- session.execute(cqlFunction);
124- session.execute(cqlAggregate);
120+ session().execute(cqlFunction);
121+ session().execute(cqlAggregate);
125122 // then
126- KeyspaceMetadata keyspace = cluster.getMetadata().getKeyspace(this.keyspace);
123+ KeyspaceMetadata keyspace = cluster().getMetadata().getKeyspace(this.keyspace);
127124 FunctionMetadata stateFunc = keyspace.getFunction("plus2", cint(), cint());
128125 AggregateMetadata aggregate = keyspace.getAggregate("sum", cint());
129126 assertThat(aggregate).isNotNull();
@@ -155,10 +152,10 @@
155152 + "STYPE \"Address\";",
156153 keyspace);
157154 // when
158- session.execute(cqlFunction);
159- session.execute(cqlAggregate);
155+ session().execute(cqlFunction);
156+ session().execute(cqlAggregate);
160157 // then
161- KeyspaceMetadata keyspace = cluster.getMetadata().getKeyspace(this.keyspace);
158+ KeyspaceMetadata keyspace = cluster().getMetadata().getKeyspace(this.keyspace);
162159 UserType addressType = keyspace.getUserType("\"Address\"");
163160 FunctionMetadata stateFunc = keyspace.getFunction("\"MY_FUNC\"", addressType, addressType);
164161 AggregateMetadata aggregate = keyspace.getAggregate("\"MY_AGGREGATE\"", addressType);
@@ -175,8 +172,8 @@
175172 }
176173
177174 @Override
178- public Collection<String> createTestFixtures() {
179- return newArrayList(
175+ public void onTestContextInitialized() {
176+ execute(
180177 String.format("CREATE TYPE IF NOT EXISTS %s.phone (number text)", keyspace),
181178 String.format("CREATE TYPE IF NOT EXISTS %s.\"Address\" ("
182179 + " street text,"
modified driver-core/src/test/java/com/datastax/driver/core/AsyncQueryTest.java +22 −32
@@ -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,26 +69,20 @@
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
78- Cluster cluster2 = null;
79- try {
80- cluster2 = Cluster.builder()
81- .addContactPointsWithPorts(Lists.newArrayList(host.getSocketAddress()))
82- .build();
83- Session session2 = cluster2.newSession();
84-
85- // Neither cluster2 nor session2 are initialized at this point
86- assertThat(cluster2.manager.metadata).isNull();
87-
88- ResultSetFuture future = session2.executeAsync("select release_version from system.local");
89- Row row = Uninterruptibles.getUninterruptibly(future).one();
90-
91- assertThat(row.getString(0)).isNotEmpty();
92- } finally {
93- if (cluster2 != null)
94- cluster2.close();
95- }
74+ Cluster cluster2 = register(Cluster.builder()
75+ .addContactPointsWithPorts(Lists.newArrayList(host.getSocketAddress()))
76+ .build());
77+ Session session2 = cluster2.newSession();
78+
79+ // Neither cluster2 nor session2 are initialized at this point
80+ assertThat(cluster2.manager.metadata).isNull();
81+
82+ ResultSetFuture future = session2.executeAsync("select release_version from system.local");
83+ Row row = Uninterruptibles.getUninterruptibly(future).one();
84+
85+ assertThat(row.getString(0)).isNotEmpty();
9686 }
9787
9888 @Test(groups = "short", dataProvider = "keyspace", enabled = false,
@@ -130,7 +120,7 @@
130120 }
131121
132122 private ListenableFuture<Integer> connectAndQuery(String keyspace, Executor executor) {
133- ListenableFuture<Session> sessionFuture = cluster.connectAsync(keyspace);
123+ ListenableFuture<Session> sessionFuture = cluster().connectAsync(keyspace);
134124 ListenableFuture<ResultSet> queryFuture = Futures.transform(sessionFuture, new AsyncFunction<Session, ResultSet>() {
135125 @Override
136126 public ListenableFuture<ResultSet> apply(Session session) throws Exception {
modified driver-core/src/test/java/com/datastax/driver/core/AsyncResultSetTest.java +7 −8
@@ -16,14 +16,12 @@
1616 package com.datastax.driver.core;
1717
1818 import com.datastax.driver.core.utils.CassandraVersion;
19-import com.google.common.collect.Lists;
2019 import com.google.common.util.concurrent.AsyncFunction;
2120 import com.google.common.util.concurrent.Futures;
2221 import com.google.common.util.concurrent.ListenableFuture;
2322 import org.testng.annotations.BeforeMethod;
2423 import org.testng.annotations.Test;
2524
26-import java.util.Collection;
2725 import java.util.Set;
2826 import java.util.concurrent.ConcurrentSkipListSet;
2927
@@ -31,15 +29,16 @@
3129
3230 @CassandraVersion(major = 2.0, description = "uses paging")
3331 public class AsyncResultSetTest extends CCMTestsSupport {
32+
3433 @Override
35- public Collection<String> createTestFixtures() {
36- return Lists.newArrayList(
34+ public void onTestContextInitialized() {
35+ execute(
3736 "create table ints (i int primary key)");
3837 }
3938
4039 @BeforeMethod(groups = "short")
4140 public void cleanup() {
42- session.execute("truncate ints");
41+ session().execute("truncate ints");
4342 }
4443
4544 @Test(groups = "short")
@@ -54,13 +53,13 @@
5453
5554 private void should_iterate_result_set_asynchronously(int totalCount, int fetchSize) {
5655 for (int i = 0; i < totalCount; i++)
57- session.execute(String.format("insert into ints (i) values (%d)", i));
56+ session().execute(String.format("insert into ints (i) values (%d)", i));
5857
5958 Statement statement = new SimpleStatement("select * from ints").setFetchSize(fetchSize);
6059 ResultsAccumulator results = new ResultsAccumulator();
6160
6261 ListenableFuture<ResultSet> future = Futures.transform(
63- session.executeAsync(statement),
62+ session().executeAsync(statement),
6463 results);
6564
6665 Futures.getUnchecked(future);
@@ -69,7 +68,7 @@
6968 }
7069
7170 /**
72- * Dummy tranformation that accumulates all traversed results
71+ * Dummy transformation that accumulates all traversed results
7372 */
7473 static class ResultsAccumulator implements AsyncFunction<ResultSet, ResultSet> {
7574 final Set<Integer> all = new ConcurrentSkipListSet<Integer>();
modified driver-core/src/test/java/com/datastax/driver/core/AuthenticationTest.java +7 −7
@@ -40,7 +40,7 @@
4040 public void sleepIf12() {
4141 // For C* 1.2, sleep before attempting to connect as there is a small delay between
4242 // user being created.
43- if (ccm.getVersion().getMajor() < 2) {
43+ if (ccm().getVersion().getMajor() < 2) {
4444 Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
4545 }
4646 }
@@ -49,8 +49,8 @@
4949 public void should_connect_with_credentials() throws InterruptedException {
5050 PlainTextAuthProvider authProvider = spy(new PlainTextAuthProvider("cassandra", "cassandra"));
5151 Cluster cluster = Cluster.builder()
52- .addContactPointsWithPorts(getInitialContactPoints())
53- .withPort(ccm.getBinaryPort())
52+ .addContactPoints(getContactPoints())
53+ .withPort(ccm().getBinaryPort())
5454 .withAuthProvider(authProvider)
5555 .build();
5656 cluster.connect();
@@ -60,8 +60,8 @@
6060 @Test(groups = "short", expectedExceptions = AuthenticationException.class)
6161 public void should_fail_to_connect_with_wrong_credentials() throws InterruptedException {
6262 Cluster cluster = register(Cluster.builder()
63- .addContactPointsWithPorts(getInitialContactPoints())
64- .withPort(ccm.getBinaryPort())
63+ .addContactPoints(getContactPoints())
64+ .withPort(ccm().getBinaryPort())
6565 .withCredentials("bogus", "bogus")
6666 .build());
6767 cluster.connect();
@@ -70,8 +70,8 @@
7070 @Test(groups = "short", expectedExceptions = AuthenticationException.class)
7171 public void should_fail_to_connect_without_credentials() throws InterruptedException {
7272 Cluster cluster = register(Cluster.builder()
73- .addContactPointsWithPorts(getInitialContactPoints())
74- .withPort(ccm.getBinaryPort())
73+ .addContactPoints(getContactPoints())
74+ .withPort(ccm().getBinaryPort())
7575 .build());
7676 cluster.connect();
7777 }
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().getProtocolVersion(), ProtocolVersion.V1);
69+ assertEquals(cluster().getConfiguration().getProtocolOptions().getProtocolVersion(), 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;
@@ -384,7 +383,17 @@
384383 return;
385384 if (logger.isDebugEnabled())
386385 logger.debug("Starting: {} - free memory: {} MB", this, TestUtils.getFreeMemoryMB());
387- execute(CCM_COMMAND + " start --wait-other-notice --wait-for-binary-proto" + jvmArgs);
386+ try {
387+ execute(CCM_COMMAND + " start --wait-other-notice --wait-for-binary-proto" + jvmArgs);
388+ } catch (CCMException e) {
389+ logger.error("Could not start " + this, e);
390+ logger.error("CCM output:\n{}", e.getOut());
391+ setKeepLogs(true);
392+ String errors = checkForErrors();
393+ if (errors != null)
394+ logger.error("CCM check errors:\n{}", errors);
395+ throw e;
396+ }
388397 if (logger.isDebugEnabled())
389398 logger.debug("Started: {} - Free memory: {} MB", this, TestUtils.getFreeMemoryMB());
390399 started = true;
@@ -396,7 +405,6 @@
396405 return;
397406 if (logger.isDebugEnabled())
398407 logger.debug("Stopping: {} - free memory: {} MB", this, TestUtils.getFreeMemoryMB());
399- execute(CCM_COMMAND + " stop");
400408 if (logger.isDebugEnabled())
401409 logger.debug("Stopped: {} - free memory: {} MB", this, TestUtils.getFreeMemoryMB());
402410 closed = true;
@@ -411,10 +419,38 @@
411419 closed = true;
412420 }
413421
422+ @Override
423+ public synchronized void remove() {
424+ stop();
425+ logger.debug("Removing: {}", this);
426+ execute(CCM_COMMAND + " remove");
427+ }
428+
429+ @Override
430+ public String checkForErrors() {
431+ logger.debug("Checking for errors in: {}", this);
432+ try {
433+ return execute(CCM_COMMAND + " checklogerror");
434+ } catch (CCMException e) {
435+ logger.warn("Check for errors failed");
436+ return null;
437+ }
438+ }
439+
414440 @Override
415441 public void start(int n) {
416442 logger.debug(String.format("Starting: node %s (%s%s:%s) in %s", n, TestUtils.IP_PREFIX, n, binaryPort, this));
417- execute(CCM_COMMAND + " node%d start --wait-other-notice --wait-for-binary-proto" + jvmArgs, n);
443+ try {
444+ execute(CCM_COMMAND + " node%d start --wait-other-notice --wait-for-binary-proto" + jvmArgs, n);
445+ } catch (CCMException e) {
446+ logger.error(String.format("Could not start node %s in %s", n, this), e);
447+ logger.error("CCM output:\n{}", e.getOut());
448+ setKeepLogs(true);
449+ String errors = checkForErrors();
450+ if (errors != null)
451+ logger.error("CCM check errors:\n{}", errors);
452+ throw e;
453+ }
418454 }
419455
420456 @Override
@@ -429,13 +465,6 @@
429465 execute(CCM_COMMAND + " node%d stop --not-gently", n);
430466 }
431467
432- @Override
433- public synchronized void remove() {
434- stop();
435- logger.debug("Removing: {}", this);
436- execute(CCM_COMMAND + " remove");
437- }
438-
439468 @Override
440469 public void remove(int n) {
441470 logger.debug(String.format("Removing: node %s (%s%s:%s) from %s", n, TestUtils.IP_PREFIX, n, binaryPort, this));
@@ -509,31 +538,36 @@
509538 }
510539
511540 @Override
512- public void setWorkload(int node, String workload) {
541+ public void setWorkload(int node, Workload workload) {
513542 execute(CCM_COMMAND + " node%d setworkload %s", node, workload);
514543 }
515544
516- private void execute(String command, Object... args) {
517-
545+ private String execute(String command, Object... args) {
518546 String fullCommand = String.format(command, args) + " --config-dir=" + ccmDir;
519547 Closer closer = Closer.create();
520548 // 10 minutes timeout
521549 ExecuteWatchdog watchDog = new ExecuteWatchdog(TimeUnit.MINUTES.toMillis(10));
550+ StringWriter sw = new StringWriter();
551+ final PrintWriter pw = new PrintWriter(sw);
552+ closer.register(pw);
522553 try {
523554 logger.trace("Executing: " + fullCommand);
524555 CommandLine cli = CommandLine.parse(fullCommand);
525556 Executor executor = new DefaultExecutor();
526-
527557 LogOutputStream outStream = new LogOutputStream() {
528558 @Override
529559 protected void processLine(String line, int logLevel) {
530- logger.debug("ccmout> " + line);
560+ String out = "ccmout> " + line;
561+ logger.debug(out);
562+ pw.println(out);
531563 }
532564 };
533565 LogOutputStream errStream = new LogOutputStream() {
534566 @Override
535567 protected void processLine(String line, int logLevel) {
536- logger.error("ccmerr> " + line);
568+ String err = "ccmerr> " + line;
569+ logger.error(err);
570+ pw.println(err);
537571 }
538572 };
539573 closer.register(outStream);
@@ -541,16 +575,17 @@
541575 ExecuteStreamHandler streamHandler = new PumpStreamHandler(outStream, errStream);
542576 executor.setStreamHandler(streamHandler);
543577 executor.setWatchdog(watchDog);
544-
545578 int retValue = executor.execute(cli, ENVIRONMENT_MAP);
546579 if (retValue != 0) {
547580 logger.error("Non-zero exit code ({}) returned from executing ccm command: {}", retValue, fullCommand);
548- throw new RuntimeException();
581+ pw.flush();
582+ throw new CCMException(String.format("Non-zero exit code (%s) returned from executing ccm command: %s", retValue, fullCommand), sw.toString());
549583 }
550584 } catch (IOException e) {
551585 if (watchDog.killedProcess())
552- logger.error("The command {} was killed after 5 minutes", fullCommand);
553- throw new RuntimeException(String.format("The command %s failed to execute", fullCommand), e);
586+ logger.error("The command {} was killed after 10 minutes", fullCommand);
587+ pw.flush();
588+ throw new CCMException(String.format("The command %s failed to execute", fullCommand), sw.toString(), e);
554589 } finally {
555590 try {
556591 closer.close();
@@ -558,6 +593,7 @@
558593 Throwables.propagate(e);
559594 }
560595 }
596+ return sw.toString();
561597 }
562598
563599 /**
@@ -626,8 +662,7 @@
626662 * use {@link #builder()} to get an instance
627663 */
628664 public static class Builder {
629- private static final AtomicInteger COUNTER = new AtomicInteger(0);
630- private final String clusterName = "test_" + COUNTER.incrementAndGet();
665+ private final String clusterName = TestUtils.generateIdentifier("cluster_");
631666 int[] nodes = {1};
632667 private boolean start = true;
633668 private boolean isDSE = isDSE();
@@ -640,6 +675,7 @@
640675 private int thriftPort = -1;
641676 private int binaryPort = -1;
642677 private int storagePort = -1;
678+ private Map<Integer, Workload> workloads = new HashMap<Integer, Workload>();
643679
644680 private Builder() {
645681 }
@@ -714,7 +750,7 @@
714750
715751 /**
716752 * Free-form options that will be added at the end of the {@code ccm create} command
717- * (defaults to {@link #getInstallArguments()} if this is never called).
753+ * (defaults to {@link #getInstallArguments()} if this is never called).
718754 */
719755 public Builder withCreateOptions(String... createOptions) {
720756 Collections.addAll(this.createOptions, createOptions);
@@ -762,6 +798,18 @@
762798 return this;
763799 }
764800
801+ /**
802+ * Sets the DSE workload for a given node.
803+ *
804+ * @param node The node to set the workload for (starting with 1).
805+ * @param workload The workload (e.g. solr, spark, hadoop)
806+ * @return This builder
807+ */
808+ public Builder withWorkload(int node, Workload workload) {
809+ this.workloads.put(node, workload);
810+ return this;
811+ }
812+
765813 public CCMBridge build() {
766814 // be careful NOT to alter internal state (hashCode/equals) during build!
767815 int storagePort = this.storagePort == -1 ? findAvailablePort() : this.storagePort;
@@ -785,6 +833,9 @@
785833 ccm.updateConfig(config);
786834 if (!dseConfiguration.isEmpty())
787835 ccm.updateDSEConfig(dseConfiguration);
836+ for (Map.Entry<Integer, Workload> entry : workloads.entrySet()) {
837+ ccm.setWorkload(entry.getKey(), entry.getValue());
838+ }
788839 if (start)
789840 ccm.start();
790841 return ccm;
@@ -890,8 +941,9 @@
890941 if (!Arrays.equals(nodes, builder.nodes)) return false;
891942 if (!createOptions.equals(builder.createOptions)) return false;
892943 if (!jvmArgs.equals(builder.jvmArgs)) return false;
893- if (!dseConfiguration.equals(builder.dseConfiguration)) return false;
894944 if (!cassandraConfiguration.equals(builder.cassandraConfiguration)) return false;
945+ if (!dseConfiguration.equals(builder.dseConfiguration)) return false;
946+ if (!workloads.equals(builder.workloads)) return false;
895947 return version.equals(builder.version);
896948 }
897949
@@ -905,6 +957,7 @@
905957 result = 31 * result + jvmArgs.hashCode();
906958 result = 31 * result + cassandraConfiguration.hashCode();
907959 result = 31 * result + dseConfiguration.hashCode();
960+ result = 31 * result + workloads.hashCode();
908961 result = 31 * result + thriftPort;
909962 result = 31 * result + binaryPort;
910963 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();
@@ -609,20 +681,85 @@
609681 }
610682
611683 /**
612- * The CQL statements to execute before the tests in this class.
613- * Useful to create tables or other objects inside the test keyspace,
614- * or to insert test data.
684+ * Hook invoked when the test context is ready, but before the test itself.
685+ * Useful to create fixtures or to insert test data.
686+ * <p/>
687+ * This method is invoked once per class is the {@link TestMode} is {@link TestMode#PER_CLASS}
688+ * or before each test method, if the {@link TestMode} is {@link TestMode#PER_METHOD}.
689+ * <p/>
690+ * When this method is called, the cluster and the session are ready
691+ * to be used (unless the configuration specifies that such objects
692+ * should not be created).
693+ * <p/>
694+ * Statements executed inside this method do not need to be qualified with a keyspace name,
695+ * in which case they are executed with the default keyspace for the test
696+ * (unless the configuration specifies that no keyspace should be creaed for the test).
697+ * <p/>
698+ * The default implementation does nothing (no fixtures required).
699+ */
700+ public void onTestContextInitialized() {
701+ // nothing to do by default
702+ }
703+
704+ /**
705+ * @return The {@link CCMAccess} instance to use with this test.
706+ */
707+ public CCMAccess ccm() {
708+ return ccm;
709+ }
710+
711+ /**
712+ * @return The {@link Cluster} instance to use with this test.
713+ * Can be null if CCM configuration specifies {@code createCluster = false}.
714+ */
715+ public Cluster cluster() {
716+ return cluster;
717+ }
718+
719+ /**
720+ * @return The {@link Session} instance to use with this test.
721+ * Can be null if CCM configuration specifies {@code createSession = false}.
722+ */
723+ public Session session() {
724+ return session;
725+ }
726+
727+ /**
728+ * Executes the given statements with the test's session object.
615729 * <p/>
616- * Statements do not need to be qualified with keyspace name.
730+ * Useful to create test fixtures and/or load data before tests.
617731 * <p/>
618- * The default implementation returns an empty list (no fixtures required).
732+ * This method should not be called if a session object hasn't been created
733+ * (if CCM configuration specifies {@code createSession = false})
619734 *
620- * @return The DDL statements to execute before the tests.
735+ * @param statements The statements to execute.
621736 */
622- public Collection<String> createTestFixtures() {
623- return Collections.emptyList();
737+ public void execute(String... statements) {
738+ execute(Arrays.asList(statements));
624739 }
625740
741+ /**
742+ * Executes the given statements with the test's session object.
743+ * <p/>
744+ * Useful to create test fixtures and/or load data before tests.
745+ * <p/>
746+ * This method should not be called if a session object hasn't been created
747+ * (if CCM configuration specifies {@code createSession = false})
748+ *
749+ * @param statements The statements to execute.
750+ */
751+ public void execute(Collection<String> statements) {
752+ assert session != null;
753+ for (String stmt : statements) {
754+ try {
755+ session.execute(stmt);
756+ } catch (Exception e) {
757+ errorOut();
758+ LOGGER.error("Could not execute statement: " + stmt, e);
759+ Throwables.propagate(e);
760+ }
761+ }
762+ }
626763 /**
627764 * Signals that the test has encountered an unexpected error.
628765 * <p/>
@@ -637,8 +774,40 @@
637774 */
638775 public void errorOut() {
639776 erroredOut = true;
640- if (ccm != null)
777+ if (ccm != null) {
641778 ccm.setKeepLogs(true);
779+ }
780+ }
781+
782+ /**
783+ * Returns the contact points to use to contact the CCM cluster.
784+ * <p/>
785+ * This method returns as many contact points as the number of nodes initially present in the CCM cluster,
786+ * according to {@link CCMConfig} annotations.
787+ * <p/>
788+ * On a multi-DC setup, this will include nodes in all data centers.
789+ * <p/>
790+ * This method should not be called before the test has started, nor after the test is finished.
791+ *
792+ * @return the contact points to use to contact the CCM cluster.
793+ */
794+ public List<InetAddress> getContactPoints() {
795+ assert ccmTestConfig != null;
796+ List<InetAddress> contactPoints = new ArrayList<InetAddress>();
797+ int n = 1;
798+ int[] numberOfNodes = ccmTestConfig.numberOfNodes();
799+ for (int dc = 1; dc <= numberOfNodes.length; dc++) {
800+ int nodesInDc = numberOfNodes[dc - 1];
801+ for (int i = 0; i < nodesInDc; i++) {
802+ try {
803+ contactPoints.add(InetAddress.getByName(ipOfNode(n)));
804+ } catch (UnknownHostException e) {
805+ Throwables.propagate(e);
806+ }
807+ n++;
808+ }
809+ }
810+ return contactPoints;
642811 }
643812
644813 /**
@@ -653,7 +822,7 @@
653822 *
654823 * @return the contact points to use to contact the CCM cluster.
655824 */
656- public List<InetSocketAddress> getInitialContactPoints() {
825+ public List<InetSocketAddress> getContactPointsWithPorts() {
657826 assert ccmTestConfig != null;
658827 List<InetSocketAddress> contactPoints = new ArrayList<InetSocketAddress>();
659828 int n = 1;
@@ -681,52 +850,73 @@
681850 return closeable;
682851 }
683852
684- private void initTestContext(Object testInstance, Method testMethod) throws Exception {
853+ /**
854+ * Tests fail randomly with InvalidQueryException: Keyspace 'xxx' does not exist;
855+ * this method tries at most 3 times to issue a successful USE statement.
856+ *
857+ * @param ks The keyspace to use
858+ */
859+ public void useKeyspace(String ks) {
860+ final int maxTries = 3;
861+ for (int i = 1; i <= maxTries; i++) {
862+ try {
863+ session.execute("USE " + ks);
864+ } catch (InvalidQueryException e) {
865+ if (i == maxTries)
866+ throw e;
867+ LOGGER.error("Could not USE keyspace, retrying");
868+ Uninterruptibles.sleepUninterruptibly(1, TimeUnit.MINUTES);
869+ }
870+ }
871+ }
872+
873+ protected void initTestContext(Object testInstance, Method testMethod) throws Exception {
685874 erroredOut = false;
686875 ccmTestConfig = createCCMTestConfig(testInstance, testMethod);
687876 assert ccmTestConfig != null;
688877 if (ccmTestConfig.createCcm()) {
689- CCMAccess ccm = CCMCache.get(ccmTestConfig.ccmBuilder());
878+ ccmBuilder = ccmTestConfig.ccmBuilder(testInstance);
879+ CCMAccess ccm = CCMCache.get(ccmBuilder);
690880 assert ccm != null;
691881 if (ccmTestConfig.dirtiesContext()) {
692882 this.ccm = ccm;
693883 } else {
694- this.ccm = new ReadOnlyCCMBridge(ccm);
884+ this.ccm = new ReadOnlyCCMAccess(ccm);
695885 }
696886 try {
697887 ccm.start();
698- } catch (RuntimeException e) {
699- LOGGER.error("Could not start " + ccm, e);
888+ } catch (CCMException e) {
889+ errorOut();
700890 fail(e.getMessage());
701891 }
702892 LOGGER.debug("Using {}", ccm);
703893 }
704894 }
705895
706- private void initTestCluster(Object testInstance) throws Exception {
896+ protected void initTestCluster(Object testInstance) throws Exception {
707897 if (ccmTestConfig.createCcm() && ccmTestConfig.createCluster()) {
708- Cluster.Builder builder = ccmTestConfig.clusterBuilder(testInstance);
898+ Cluster.Builder builder = ccmTestConfig.clusterProvider(testInstance);
709899 // add contact points only if the provided builder didn't do so
710900 if (builder.getContactPoints().isEmpty())
711- builder.addContactPointsWithPorts(getInitialContactPoints());
901+ builder.addContactPoints(getContactPoints());
712902 builder.withPort(ccm.getBinaryPort());
713903 cluster = register(builder.build());
714904 cluster.init();
715905 }
716906 }
717907
718- private void initTestSession() throws Exception {
908+ protected void initTestSession() throws Exception {
719909 if (ccmTestConfig.createCcm() && ccmTestConfig.createCluster() && ccmTestConfig.createSession())
720910 session = register(cluster.connect());
721911 }
722912
723- private void initTestKeyspace() {
913+ protected void initTestKeyspace() {
724914 if (ccmTestConfig.createCcm() && ccmTestConfig.createCluster() && ccmTestConfig.createSession() && ccmTestConfig.createKeyspace()) {
725915 try {
726- keyspace = TestUtils.getAvailableKeyspaceName();
916+ keyspace = TestUtils.generateIdentifier("ks_");
727917 LOGGER.debug("Using keyspace " + keyspace);
728918 session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, 1));
729- session.execute("USE " + keyspace);
919+ useKeyspace(keyspace);
730920 } catch (Exception e) {
731921 errorOut();
732922 LOGGER.error("Could not create test keyspace", e);
@@ -735,35 +925,25 @@
735925 }
736926 }
737927
738- private void initTestFixtures(Object testInstance) throws Exception {
739- if (ccmTestConfig.createCcm() && ccmTestConfig.createCluster() && ccmTestConfig.createSession()) {
740- for (String stmt : ccmTestConfig.fixtures(testInstance)) {
741- try {
742- session.execute(stmt);
743- } catch (Exception e) {
744- errorOut();
745- LOGGER.error("Could not execute statement: " + stmt, e);
746- Throwables.propagate(e);
747- }
748- }
749- }
928+ protected void initTest(Object testInstance) throws Exception {
929+ ccmTestConfig.invokeInitTest(testInstance);
750930 }
751931
752- private void closeTestContext() {
753- if (ccmTestConfig != null && ccm != null) {
754- CCMBridge.Builder key = ccmTestConfig.ccmBuilder();
932+ protected void closeTestContext() throws Exception {
933+ if (ccmTestConfig != null && ccmBuilder != null && ccm != null) {
755934 if (ccmTestConfig.dirtiesContext()) {
756- CCMCache.remove(key);
935+ CCMCache.remove(ccmBuilder);
757936 ccm.close();
758937 } else {
759- ((ReadOnlyCCMBridge) ccm).delegate.close();
938+ ((ReadOnlyCCMAccess) ccm).delegate.close();
760939 }
761940 }
762941 ccmTestConfig = null;
942+ ccmBuilder = null;
763943 ccm = null;
764944 }
765945
766- private void closeTestCluster() {
946+ protected void closeTestCluster() {
767947 if (cluster != null && !cluster.isClosed())
768948 executeNoFail(new Runnable() {
769949 @Override
@@ -776,7 +956,7 @@
776956 keyspace = null;
777957 }
778958
779- private void closeCloseables() {
959+ protected void closeCloseables() {
780960 if (closer != null)
781961 executeNoFail(new Callable<Void>() {
782962 @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/ClusterInitTest.java +4 −3
@@ -32,7 +32,6 @@
3232 import java.net.InetAddress;
3333 import java.net.InetSocketAddress;
3434 import java.net.UnknownHostException;
35-import java.util.Collections;
3635 import java.util.List;
3736 import java.util.Map;
3837 import java.util.concurrent.TimeUnit;
@@ -134,7 +133,7 @@
134133 // There is a possible race here in that the host is marked down in a separate Executor in onDown
135134 // and then starts a periodic reconnection attempt shortly after. Since setDown is called before
136135 // startPeriodicReconnectionAttempt, we add a slight delay here if the future isn't set yet.
137- if (host.getReconnectionAttemptFuture() == null || host.getReconnectionAttemptFuture().isDone()) {
136+ if (host != null && (host.getReconnectionAttemptFuture() == null || host.getReconnectionAttemptFuture().isDone())) {
138137 logger.warn("Periodic Reconnection Attempt hasn't started yet for {}, waiting 1 second and then checking.", host);
139138 Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
140139 }
@@ -198,7 +197,7 @@
198197 @Test(groups = "short")
199198 public void should_be_able_to_close_cluster_that_never_successfully_connected() throws Exception {
200199 Cluster cluster = Cluster.builder()
201- .addContactPointsWithPorts(Collections.singleton(new InetSocketAddress("127.0.0.1", 65534)))
200+ .addContactPointsWithPorts(new InetSocketAddress("127.0.0.1", 65534))
202201 .withNettyOptions(nonQuietClusterCloseOptions)
203202 .build();
204203 try {
@@ -212,6 +211,8 @@
212211 } catch (TimeoutException e1) {
213212 fail("Close Future did not complete quickly.");
214213 }
214+ } finally {
215+ cluster.close();
215216 }
216217 }
217218
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/ConnectionReleaseTest.java +3 −2
@@ -24,7 +24,6 @@
2424 import org.testng.annotations.Test;
2525
2626 import java.util.Collection;
27-import java.util.Collections;
2827 import java.util.concurrent.TimeUnit;
2928 import java.util.concurrent.TimeoutException;
3029
@@ -84,7 +83,9 @@
8483 .build()
8584 );
8685
87- cluster = Cluster.builder().addContactPointsWithPorts(Collections.singletonList(hostAddress))
86+ cluster = Cluster.builder()
87+ .addContactPoints(hostAddress.getAddress())
88+ .withPort(scassandra.getBinaryPort())
8889 .withProtocolVersion(ProtocolVersion.V2)
8990 .withPoolingOptions(new PoolingOptions()
9091 .setCoreConnectionsPerHost(HostDistance.LOCAL, 1)
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 +17 −17
@@ -47,7 +47,6 @@
4747 @Test(groups = "short")
4848 @CCMConfig(numberOfNodes = 2)
4949 public void should_prevent_simultaneous_reconnection_attempts() throws InterruptedException {
50- Cluster cluster;
5150
5251 // Custom load balancing policy that counts the number of calls to newQueryPlan().
5352 // Since we don't open any session from our Cluster, only the control connection reattempts are calling this
@@ -60,20 +59,20 @@
6059 ReconnectionPolicy reconnectionPolicy = new ConstantReconnectionPolicy(60 * 1000);
6160
6261 // We pass only the first host as contact point, so we know the control connection will be on this host
63- cluster = register(Cluster.builder()
64- .addContactPoints(ccm.addressOfNode(1).getAddress())
65- .withPort(ccm.getBinaryPort())
62+ Cluster cluster = register(Cluster.builder()
63+ .addContactPoints(getContactPoints().get(0))
64+ .withPort(ccm().getBinaryPort())
6665 .withReconnectionPolicy(reconnectionPolicy)
6766 .withLoadBalancingPolicy(loadBalancingPolicy)
6867 .build());
6968 cluster.init();
7069
7170 // Kill the control connection host, there should be exactly one reconnection attempt
72- ccm.stop(1);
71+ ccm().stop(1);
7372 TimeUnit.SECONDS.sleep(1); // Sleep for a while to make sure our final count is not the result of lucky timing
7473 assertThat(reconnectionAttempts.get()).isEqualTo(1);
7574
76- ccm.stop(2);
75+ ccm().stop(2);
7776 TimeUnit.SECONDS.sleep(1);
7877 assertThat(reconnectionAttempts.get()).isEqualTo(2);
7978 }
@@ -87,12 +86,10 @@
8786 @Test(groups = "short")
8887 @CassandraVersion(major = 2.1)
8988 public void should_parse_UDT_definitions_when_using_default_protocol_version() {
90- Cluster cluster;
91- InetSocketAddress firstHost = ccm.addressOfNode(1);
9289 // First driver instance: create UDT
93- cluster = register(Cluster.builder()
94- .addContactPointsWithPorts(firstHost)
95- .withPort(ccm.getBinaryPort())
90+ Cluster cluster = register(Cluster.builder()
91+ .addContactPoints(getContactPoints().get(0))
92+ .withPort(ccm().getBinaryPort())
9693 .build());
9794 Session session = cluster.connect();
9895 session.execute("create keyspace ks WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}");
@@ -100,8 +97,11 @@
10097 cluster.close();
10198
10299 // Second driver instance: read UDT definition
103- cluster = register(Cluster.builder().addContactPointsWithPorts(firstHost).build());
104- UserType fooType = cluster.getMetadata().getKeyspace("ks").getUserType("foo");
100+ Cluster cluster2 = register(Cluster.builder()
101+ .addContactPoints(getContactPoints().get(0))
102+ .withPort(ccm().getBinaryPort())
103+ .build());
104+ UserType fooType = cluster2.getMetadata().getKeyspace("ks").getUserType("foo");
105105
106106 assertThat(fooType.getFieldNames()).containsExactly("i");
107107 }
@@ -118,10 +118,10 @@
118118 @Test(groups = "long")
119119 @CCMConfig(numberOfNodes = 3)
120120 public void should_reestablish_if_control_node_decommissioned() throws InterruptedException {
121- InetSocketAddress firstHost = ccm.addressOfNode(1);
121+ InetSocketAddress firstHost = ccm().addressOfNode(1);
122122 Cluster cluster = register(Cluster.builder()
123- .addContactPointsWithPorts(firstHost)
124- .withPort(ccm.getBinaryPort())
123+ .addContactPoints(firstHost.getAddress())
124+ .withPort(ccm().getBinaryPort())
125125 .withQueryOptions(nonDebouncingQueryOptions())
126126 .build());
127127 cluster.init();
@@ -131,7 +131,7 @@
131131 assertThat(controlHost).isEqualTo(firstHost.getAddress());
132132
133133 // Decommission the node.
134- ccm.decommission(1);
134+ ccm().decommission(1);
135135
136136 // Ensure that the new control connection is not null and it's host is not equal to the decommissioned node.
137137 Host newHost = cluster.manager.controlConnection.connectedHost();
modified driver-core/src/test/java/com/datastax/driver/core/CustomPayloadTest.java +26 −35
@@ -26,8 +26,6 @@
2626 import org.testng.annotations.Test;
2727
2828 import java.nio.ByteBuffer;
29-import java.util.Collection;
30-import java.util.Collections;
3129 import java.util.HashMap;
3230 import java.util.Map;
3331
@@ -64,7 +62,7 @@
6462 public void should_echo_custom_payload_when_executing_statement() throws Exception {
6563 Statement statement = new SimpleStatement("SELECT c2 FROM t1 where c1 = ?", 1);
6664 statement.setOutgoingPayload(payload1);
67- ResultSet rows = session.execute(statement);
65+ ResultSet rows = session().execute(statement);
6866 Map<String, ByteBuffer> actual = rows.getExecutionInfo().getIncomingPayload();
6967 assertThat(actual).isEqualTo(payload1);
7068 }
@@ -73,7 +71,7 @@
7371 public void should_echo_custom_payload_when_executing_batch_statement() throws Exception {
7472 Statement statement = new BatchStatement().add(new SimpleStatement("INSERT INTO t1 (c1, c2) values (1, 'foo')"));
7573 statement.setOutgoingPayload(payload1);
76- ResultSet rows = session.execute(statement);
74+ ResultSet rows = session().execute(statement);
7775 Map<String, ByteBuffer> actual = rows.getExecutionInfo().getIncomingPayload();
7876 assertThat(actual).isEqualTo(payload1);
7977 }
@@ -81,7 +79,7 @@
8179 @Test(groups = "short")
8280 public void should_echo_custom_payload_when_building_statement() throws Exception {
8381 Statement statement = select("c2").from("t1").where(eq("c1", 1)).setOutgoingPayload(payload1);
84- ResultSet rows = session.execute(statement);
82+ ResultSet rows = session().execute(statement);
8583 Map<String, ByteBuffer> actual = rows.getExecutionInfo().getIncomingPayload();
8684 assertThat(actual).isEqualTo(payload1);
8785 }
@@ -97,7 +95,7 @@
9795 public void should_propagate_incoming_payload_to_bound_statement() throws Exception {
9896 RegularStatement statement = new SimpleStatement("SELECT c2 as col1 FROM t1 where c1 = ?");
9997 statement.setOutgoingPayload(payload1);
100- PreparedStatement ps = session.prepare(statement);
98+ PreparedStatement ps = session().prepare(statement);
10199 // Prepared statement should inherit outgoing payload
102100 assertThat(ps.getOutgoingPayload()).isEqualTo(payload1);
103101 // Prepared statement should receive incoming payload
@@ -105,12 +103,12 @@
105103 ps.setOutgoingPayload(null); // unset outgoing payload
106104 // bound statement should inherit from prepared statement's incoming payload
107105 BoundStatement bs = ps.bind(1);
108- ResultSet rows = session.execute(bs);
106+ ResultSet rows = session().execute(bs);
109107 Map<String, ByteBuffer> actual = rows.getExecutionInfo().getIncomingPayload();
110108 assertThat(actual).isEqualTo(payload1);
111109 bs = ps.bind();
112110 bs.setInt(0, 1);
113- rows = session.execute(bs);
111+ rows = session().execute(bs);
114112 actual = rows.getExecutionInfo().getIncomingPayload();
115113 assertThat(actual).isEqualTo(payload1);
116114 }
@@ -125,7 +123,7 @@
125123 public void should_override_incoming_payload_when_outgoing_payload_explicitly_set_on_preparing_statement() throws Exception {
126124 RegularStatement statement = new SimpleStatement("SELECT c2 as col2 FROM t1 where c1 = ?");
127125 statement.setOutgoingPayload(payload1);
128- PreparedStatement ps = session.prepare(statement);
126+ PreparedStatement ps = session().prepare(statement);
129127 // Prepared statement should inherit outgoing payload
130128 assertThat(ps.getOutgoingPayload()).isEqualTo(payload1);
131129 // Prepared statement should receive incoming payload
@@ -133,12 +131,12 @@
133131 ps.setOutgoingPayload(payload2); // override outgoing payload
134132 // bound statement should inherit from prepared statement's outgoing payload
135133 BoundStatement bs = ps.bind(1);
136- ResultSet rows = session.execute(bs);
134+ ResultSet rows = session().execute(bs);
137135 Map<String, ByteBuffer> actual = rows.getExecutionInfo().getIncomingPayload();
138136 assertThat(actual).isEqualTo(payload2);
139137 bs = ps.bind();
140138 bs.setInt(0, 1);
141- rows = session.execute(bs);
139+ rows = session().execute(bs);
142140 actual = rows.getExecutionInfo().getIncomingPayload();
143141 assertThat(actual).isEqualTo(payload2);
144142 }
@@ -152,7 +150,7 @@
152150 @Test(groups = "short")
153151 public void should_not_set_any_payload_on_bound_statement() throws Exception {
154152 RegularStatement statement = new SimpleStatement("SELECT c2 as col3 FROM t1 where c1 = ?");
155- PreparedStatement ps = session.prepare(statement);
153+ PreparedStatement ps = session().prepare(statement);
156154 assertThat(ps.getOutgoingPayload()).isNull();
157155 assertThat(ps.getIncomingPayload()).isNull();
158156 // bound statement should not have outgoing payload
@@ -160,14 +158,14 @@
160158 assertThat(bs.getOutgoingPayload()).isNull();
161159 // explicitly set a payload for this boudn statement only
162160 bs.setOutgoingPayload(payload1);
163- ResultSet rows = session.execute(bs);
161+ ResultSet rows = session().execute(bs);
164162 Map<String, ByteBuffer> actual = rows.getExecutionInfo().getIncomingPayload();
165163 assertThat(actual).isEqualTo(payload1);
166164 // a second bound statement should not have any payload
167165 bs = ps.bind();
168166 assertThat(bs.getOutgoingPayload()).isNull();
169167 bs.setInt(0, 1);
170- rows = session.execute(bs);
168+ rows = session().execute(bs);
171169 actual = rows.getExecutionInfo().getIncomingPayload();
172170 assertThat(actual).isNull();
173171 }
@@ -181,12 +179,12 @@
181179 */
182180 @Test(groups = "short")
183181 public void should_echo_custom_payload_when_paginating() throws Exception {
184- session.execute("INSERT INTO t1 (c1, c2) VALUES (1, 'a')");
185- session.execute("INSERT INTO t1 (c1, c2) VALUES (1, 'b')");
182+ session().execute("INSERT INTO t1 (c1, c2) VALUES (1, 'a')");
183+ session().execute("INSERT INTO t1 (c1, c2) VALUES (1, 'b')");
186184 Statement statement = new SimpleStatement("SELECT c2 FROM t1 where c1 = 1");
187185 statement.setFetchSize(1);
188186 statement.setOutgoingPayload(payload1);
189- ResultSet rows = session.execute(statement);
187+ ResultSet rows = session().execute(statement);
190188 rows.all();
191189 assertThat(rows.getAllExecutionInfo()).extracting("incomingPayload").containsOnly(payload1);
192190 }
@@ -201,7 +199,7 @@
201199 payload.put("k1", Statement.NULL_PAYLOAD_VALUE);
202200 Statement statement = new SimpleStatement("SELECT c2 FROM t1 where c1 = ?", 1);
203201 statement.setOutgoingPayload(payload);
204- ResultSet rows = session.execute(statement);
202+ ResultSet rows = session().execute(statement);
205203 Map<String, ByteBuffer> actual = rows.getExecutionInfo().getIncomingPayload();
206204 assertThat(actual).isEqualTo(payload);
207205 }
@@ -224,28 +222,26 @@
224222 public void should_throw_npe_when_null_key_on_prepared_statement() throws Exception {
225223 Map<String, ByteBuffer> payload = new HashMap<String, ByteBuffer>();
226224 payload.put(null, ByteBuffer.wrap(new byte[]{1}));
227- session.prepare(new SimpleStatement("SELECT c2 FROM t1 where c1 = 1")).setOutgoingPayload(payload);
225+ session().prepare(new SimpleStatement("SELECT c2 FROM t1 where c1 = 1")).setOutgoingPayload(payload);
228226 }
229227
230228 @Test(groups = "short", expectedExceptions = NullPointerException.class)
231229 public void should_throw_npe_when_null_value_on_prepared_statement() throws Exception {
232230 Map<String, ByteBuffer> payload = new HashMap<String, ByteBuffer>();
233231 payload.put("k1", null);
234- session.prepare(new SimpleStatement("SELECT c2 FROM t1 where c1 = 2")).setOutgoingPayload(payload);
232+ session().prepare(new SimpleStatement("SELECT c2 FROM t1 where c1 = 2")).setOutgoingPayload(payload);
235233 }
236234
237235 @Test(groups = "short")
238236 public void should_throw_ufe_when_protocol_version_lesser_than_4() throws Exception {
239- Cluster v3cluster = null;
240- Session v3session = null;
241237 try {
242- v3cluster = Cluster.builder()
243- .addContactPointsWithPorts(getInitialContactPoints())
244- .withPort(ccm.getBinaryPort())
238+ Cluster v3cluster = register(Cluster.builder()
239+ .addContactPoints(getContactPoints())
240+ .withPort(ccm().getBinaryPort())
245241 .withProtocolVersion(V3)
246- .build()
242+ .build())
247243 .init();
248- v3session = v3cluster.connect();
244+ Session v3session = v3cluster.connect();
249245 Statement statement = new SimpleStatement("SELECT c2 FROM t1 where c1 = ?", 1);
250246 statement.setOutgoingPayload(payload1);
251247 v3session.execute(statement);
@@ -261,11 +257,6 @@
261257 .hasOnlyElementsOfType(UnsupportedFeatureException.class)
262258 .extracting("message")
263259 .containsOnly("Unsupported feature with the native protocol V3 (which is currently in use): Custom payloads are only supported since native protocol V4");
264- } finally {
265- if (v3session != null)
266- v3session.close();
267- if (v3cluster != null)
268- v3cluster.close();
269260 }
270261 }
271262
@@ -285,7 +276,7 @@
285276 logger.addAppender(appender);
286277 Statement statement = new SimpleStatement("SELECT c2 FROM t1 where c1 = ?", 1);
287278 statement.setOutgoingPayload(payload1);
288- session.execute(statement);
279+ session().execute(statement);
289280 String logs = appender.waitAndGet(10000);
290281 assertThat(logs)
291282 .contains("Sending payload: {k1:0x010203, k2:0x040506} (20 bytes total)")
@@ -297,8 +288,8 @@
297288 }
298289
299290 @Override
300- public Collection<String> createTestFixtures() {
301- return Collections.singletonList("CREATE TABLE t1 (c1 int, c2 text, PRIMARY KEY (c1, c2))");
291+ public void onTestContextInitialized() {
292+ execute("CREATE TABLE t1 (c1 int, c2 text, PRIMARY KEY (c1, c2))");
302293 }
303294
304295 }
modified driver-core/src/test/java/com/datastax/driver/core/CustomTypeTest.java +16 −18
@@ -16,12 +16,10 @@
1616 package com.datastax.driver.core;
1717
1818 import com.datastax.driver.core.utils.CassandraVersion;
19-import com.google.common.collect.Lists;
2019 import org.testng.annotations.Test;
2120
2221 import java.nio.ByteBuffer;
2322 import java.util.ArrayList;
24-import java.util.Collection;
2523 import java.util.List;
2624 import java.util.Map;
2725
@@ -45,8 +43,8 @@
4543 + "org.apache.cassandra.db.marshal.Int32Type)");
4644
4745 @Override
48- public Collection<String> createTestFixtures() {
49- return Lists.newArrayList(
46+ public void onTestContextInitialized() {
47+ execute(
5048 "CREATE TABLE test ("
5149 + " k int,"
5250 + " c1 'DynamicCompositeType(s => UTF8Type, i => Int32Type)',"
@@ -77,17 +75,17 @@
7775 @Test(groups = "short")
7876 public void should_serialize_and_deserialize_custom_types() {
7977
80- TableMetadata table = cluster.getMetadata().getKeyspace(keyspace).getTable("test");
78+ TableMetadata table = cluster().getMetadata().getKeyspace(keyspace).getTable("test");
8179
8280 assertThat(table.getColumn("c1")).isClusteringColumn().hasType(CUSTOM_DYNAMIC_COMPOSITE);
8381 assertThat(table.getColumn("c2")).isClusteringColumn().hasType(CUSTOM_COMPOSITE).hasClusteringOrder(ClusteringOrder.DESC);
8482 assertThat(table.getColumn("c3")).hasType(cint());
8583
86- session.execute("INSERT INTO test(k, c1, c2, c3) VALUES (0, 's@foo:i@32', 'foo:32', 1)");
87- session.execute("INSERT INTO test(k, c1, c2, c3) VALUES (0, 'i@42', ':42', 2)");
88- session.execute("INSERT INTO test(k, c1, c2, c3) VALUES (0, 'i@12:i@3', 'foo', 3)");
84+ session().execute("INSERT INTO test(k, c1, c2, c3) VALUES (0, 's@foo:i@32', 'foo:32', 1)");
85+ session().execute("INSERT INTO test(k, c1, c2, c3) VALUES (0, 'i@42', ':42', 2)");
86+ session().execute("INSERT INTO test(k, c1, c2, c3) VALUES (0, 'i@12:i@3', 'foo', 3)");
8987
90- ResultSet rs = session.execute("SELECT * FROM test");
88+ ResultSet rs = session().execute("SELECT * FROM test");
9189
9290 Row r = rs.one();
9391
@@ -121,13 +119,13 @@
121119 */
122120 @Test(groups = "short")
123121 public void should_serialize_and_deserialize_collections_of_custom_types() {
124- TableMetadata table = cluster.getMetadata().getKeyspace(keyspace).getTable("test_collection");
122+ TableMetadata table = cluster().getMetadata().getKeyspace(keyspace).getTable("test_collection");
125123 assertThat(table.getColumn("c1")).hasType(DataType.list(CUSTOM_DYNAMIC_COMPOSITE));
126124 assertThat(table.getColumn("c2")).hasType(DataType.map(CUSTOM_DYNAMIC_COMPOSITE, CUSTOM_DYNAMIC_COMPOSITE));
127125
128- session.execute("INSERT INTO test_collection(k, c1, c2) VALUES (0, [ 's@foo:i@32' ], { 's@foo:i@32': 's@bar:i@42' })");
126+ session().execute("INSERT INTO test_collection(k, c1, c2) VALUES (0, [ 's@foo:i@32' ], { 's@foo:i@32': 's@bar:i@42' })");
129127
130- Row r = session.execute("SELECT * FROM test_collection").one();
128+ Row r = session().execute("SELECT * FROM test_collection").one();
131129
132130 assertThat(r.getColumnDefinitions().getType("c1")).isEqualTo(DataType.list(CUSTOM_DYNAMIC_COMPOSITE));
133131 List<ByteBuffer> c1 = r.getList("c1", ByteBuffer.class);
@@ -156,26 +154,26 @@
156154 @CassandraVersion(major = 2.1)
157155 public void should_handle_udt_with_custom_type() {
158156 // Given: a UDT with custom types, and a table using it.
159- session.execute("CREATE TYPE custom_udt (regular int, c1 'DynamicCompositeType(s => UTF8Type, i => Int32Type)', c2 'LongType')");
160- session.execute("CREATE TABLE custom_udt_tbl (k int primary key, v frozen<custom_udt>)");
157+ session().execute("CREATE TYPE custom_udt (regular int, c1 'DynamicCompositeType(s => UTF8Type, i => Int32Type)', c2 'LongType')");
158+ session().execute("CREATE TABLE custom_udt_tbl (k int primary key, v frozen<custom_udt>)");
161159
162160 // When: Retrieving User Type via schema metadata.
163- UserType custom_udt = cluster.getMetadata().getKeyspace(keyspace).getUserType("custom_udt");
161+ UserType custom_udt = cluster().getMetadata().getKeyspace(keyspace).getUserType("custom_udt");
164162 assertThat(custom_udt.getFieldType("regular")).isEqualTo(cint());
165163 // Then: The fields with custom types should be appropriately represented with their defined types.
166164 assertThat(custom_udt.getFieldType("c1")).isEqualTo(CUSTOM_DYNAMIC_COMPOSITE);
167165 assertThat(custom_udt.getFieldType("c2")).isEqualTo(DataType.bigint());
168166
169167 // When: Retrieving Table via schema metadata.
170- TableMetadata table = cluster.getMetadata().getKeyspace(keyspace).getTable("custom_udt_tbl");
168+ TableMetadata table = cluster().getMetadata().getKeyspace(keyspace).getTable("custom_udt_tbl");
171169 // Then: The column with the user type should be represented and match the type previously retrieved.
172170 assertThat(table.getColumn("v")).hasType(custom_udt);
173171
174172 // Given: Existing data in table with a UDT with custom types.
175- session.execute("INSERT INTO custom_udt_tbl (k, v) VALUES (0, {regular: 5, c1: 's@hello:i@93', c2: 400})");
173+ session().execute("INSERT INTO custom_udt_tbl (k, v) VALUES (0, {regular: 5, c1: 's@hello:i@93', c2: 400})");
176174
177175 // When: Data is retrieved.
178- Row row = session.execute("select * from custom_udt_tbl").one();
176+ Row row = session().execute("select * from custom_udt_tbl").one();
179177
180178 // Then: The resulting row's column definitions should match the table definition.
181179 assertThat(row.getColumnDefinitions().getType("k")).isEqualTo(cint());
modified driver-core/src/test/java/com/datastax/driver/core/DataTypeCqlNameParserTest.java +44 −47
@@ -16,11 +16,8 @@
1616 package com.datastax.driver.core;
1717
1818 import com.datastax.driver.core.utils.CassandraVersion;
19-import com.google.common.collect.Lists;
2019 import org.testng.annotations.Test;
2120
22-import java.util.Collection;
23-
2421 import static com.datastax.driver.core.Assertions.assertThat;
2522 import static com.datastax.driver.core.DataType.*;
2623 import static com.datastax.driver.core.DataTypeCqlNameParser.parse;
@@ -31,96 +28,96 @@
3128
3229 @Test(groups = "short")
3330 public void should_parse_native_types() {
34- assertThat(parse("ascii", cluster, null, null, null, false, false)).isEqualTo(ascii());
35- assertThat(parse("bigint", cluster, null, null, null, false, false)).isEqualTo(bigint());
36- assertThat(parse("blob", cluster, null, null, null, false, false)).isEqualTo(blob());
37- assertThat(parse("boolean", cluster, null, null, null, false, false)).isEqualTo(cboolean());
38- assertThat(parse("counter", cluster, null, null, null, false, false)).isEqualTo(counter());
39- assertThat(parse("decimal", cluster, null, null, null, false, false)).isEqualTo(decimal());
40- assertThat(parse("double", cluster, null, null, null, false, false)).isEqualTo(cdouble());
41- assertThat(parse("float", cluster, null, null, null, false, false)).isEqualTo(cfloat());
42- assertThat(parse("inet", cluster, null, null, null, false, false)).isEqualTo(inet());
43- assertThat(parse("int", cluster, null, null, null, false, false)).isEqualTo(cint());
44- assertThat(parse("text", cluster, null, null, null, false, false)).isEqualTo(text());
45- assertThat(parse("varchar", cluster, null, null, null, false, false)).isEqualTo(varchar());
46- assertThat(parse("timestamp", cluster, null, null, null, false, false)).isEqualTo(timestamp());
47- assertThat(parse("date", cluster, null, null, null, false, false)).isEqualTo(date());
48- assertThat(parse("time", cluster, null, null, null, false, false)).isEqualTo(time());
49- assertThat(parse("uuid", cluster, null, null, null, false, false)).isEqualTo(uuid());
50- assertThat(parse("varint", cluster, null, null, null, false, false)).isEqualTo(varint());
51- assertThat(parse("timeuuid", cluster, null, null, null, false, false)).isEqualTo(timeuuid());
52- assertThat(parse("tinyint", cluster, null, null, null, false, false)).isEqualTo(tinyint());
53- assertThat(parse("smallint", cluster, null, null, null, false, false)).isEqualTo(smallint());
31+ assertThat(parse("ascii", cluster(), null, null, null, false, false)).isEqualTo(ascii());
32+ assertThat(parse("bigint", cluster(), null, null, null, false, false)).isEqualTo(bigint());
33+ assertThat(parse("blob", cluster(), null, null, null, false, false)).isEqualTo(blob());
34+ assertThat(parse("boolean", cluster(), null, null, null, false, false)).isEqualTo(cboolean());
35+ assertThat(parse("counter", cluster(), null, null, null, false, false)).isEqualTo(counter());
36+ assertThat(parse("decimal", cluster(), null, null, null, false, false)).isEqualTo(decimal());
37+ assertThat(parse("double", cluster(), null, null, null, false, false)).isEqualTo(cdouble());
38+ assertThat(parse("float", cluster(), null, null, null, false, false)).isEqualTo(cfloat());
39+ assertThat(parse("inet", cluster(), null, null, null, false, false)).isEqualTo(inet());
40+ assertThat(parse("int", cluster(), null, null, null, false, false)).isEqualTo(cint());
41+ assertThat(parse("text", cluster(), null, null, null, false, false)).isEqualTo(text());
42+ assertThat(parse("varchar", cluster(), null, null, null, false, false)).isEqualTo(varchar());
43+ assertThat(parse("timestamp", cluster(), null, null, null, false, false)).isEqualTo(timestamp());
44+ assertThat(parse("date", cluster(), null, null, null, false, false)).isEqualTo(date());
45+ assertThat(parse("time", cluster(), null, null, null, false, false)).isEqualTo(time());
46+ assertThat(parse("uuid", cluster(), null, null, null, false, false)).isEqualTo(uuid());
47+ assertThat(parse("varint", cluster(), null, null, null, false, false)).isEqualTo(varint());
48+ assertThat(parse("timeuuid", cluster(), null, null, null, false, false)).isEqualTo(timeuuid());
49+ assertThat(parse("tinyint", cluster(), null, null, null, false, false)).isEqualTo(tinyint());
50+ assertThat(parse("smallint", cluster(), null, null, null, false, false)).isEqualTo(smallint());
5451 }
5552
5653 @Test(groups = "short")
5754 public void should_ignore_whitespace() {
58- assertThat(parse(" int ", cluster, null, null, null, false, false)).isEqualTo(cint());
59- assertThat(parse(" set < bigint > ", cluster, null, null, null, false, false)).isEqualTo(set(bigint()));
60- assertThat(parse(" map < date , timeuuid > ", cluster, null, null, null, false, false)).isEqualTo(map(date(), timeuuid()));
55+ assertThat(parse(" int ", cluster(), null, null, null, false, false)).isEqualTo(cint());
56+ assertThat(parse(" set < bigint > ", cluster(), null, null, null, false, false)).isEqualTo(set(bigint()));
57+ assertThat(parse(" map < date , timeuuid > ", cluster(), null, null, null, false, false)).isEqualTo(map(date(), timeuuid()));
6158 }
6259
6360 @Test(groups = "short")
6461 public void should_ignore_case() {
65- assertThat(parse("INT", cluster, null, null, null, false, false)).isEqualTo(cint());
66- assertThat(parse("SET<BIGint>", cluster, null, null, null, false, false)).isEqualTo(set(bigint()));
67- assertThat(parse("FROZEN<mAp<Date,Tuple<timeUUID>>>", cluster, null, null, null, false, false)).isEqualTo(map(date(), cluster.getMetadata().newTupleType(timeuuid()), true));
62+ assertThat(parse("INT", cluster(), null, null, null, false, false)).isEqualTo(cint());
63+ assertThat(parse("SET<BIGint>", cluster(), null, null, null, false, false)).isEqualTo(set(bigint()));
64+ assertThat(parse("FROZEN<mAp<Date,Tuple<timeUUID>>>", cluster(), null, null, null, false, false)).isEqualTo(map(date(), cluster().getMetadata().newTupleType(timeuuid()), true));
6865 }
6966
7067 @Test(groups = "short")
7168 public void should_parse_collection_types() {
72- assertThat(parse("list<int>", cluster, null, null, null, false, false)).isEqualTo(list(cint()));
73- assertThat(parse("set<bigint>", cluster, null, null, null, false, false)).isEqualTo(set(bigint()));
74- assertThat(parse("map<date,timeuuid>", cluster, null, null, null, false, false)).isEqualTo(map(date(), timeuuid()));
69+ assertThat(parse("list<int>", cluster(), null, null, null, false, false)).isEqualTo(list(cint()));
70+ assertThat(parse("set<bigint>", cluster(), null, null, null, false, false)).isEqualTo(set(bigint()));
71+ assertThat(parse("map<date,timeuuid>", cluster(), null, null, null, false, false)).isEqualTo(map(date(), timeuuid()));
7572 }
7673
7774 @Test(groups = "short")
7875 public void should_parse_frozen_collection_types() {
79- assertThat(parse("frozen<list<int>>", cluster, null, null, null, false, false)).isEqualTo(list(cint(), true));
80- assertThat(parse("frozen<set<bigint>>", cluster, null, null, null, false, false)).isEqualTo(set(bigint(), true));
81- assertThat(parse("frozen<map<date,timeuuid>>", cluster, null, null, null, false, false)).isEqualTo(map(date(), timeuuid(), true));
76+ assertThat(parse("frozen<list<int>>", cluster(), null, null, null, false, false)).isEqualTo(list(cint(), true));
77+ assertThat(parse("frozen<set<bigint>>", cluster(), null, null, null, false, false)).isEqualTo(set(bigint(), true));
78+ assertThat(parse("frozen<map<date,timeuuid>>", cluster(), null, null, null, false, false)).isEqualTo(map(date(), timeuuid(), true));
8279 }
8380
8481 @Test(groups = "short")
8582 public void should_parse_nested_collection_types() {
86- Metadata metadata = cluster.getMetadata();
83+ Metadata metadata = cluster().getMetadata();
8784 KeyspaceMetadata keyspaceMetadata = metadata.getKeyspace(this.keyspace);
88- assertThat(parse("list<list<int>>", cluster, null, null, null, false, false)).isEqualTo(list(list(cint())));
89- assertThat(parse("set<list<frozen<map<bigint,varchar>>>>", cluster, null, null, null, false, false)).isEqualTo(set(list(map(bigint(), varchar(), true))));
85+ assertThat(parse("list<list<int>>", cluster(), null, null, null, false, false)).isEqualTo(list(list(cint())));
86+ assertThat(parse("set<list<frozen<map<bigint,varchar>>>>", cluster(), null, null, null, false, false)).isEqualTo(set(list(map(bigint(), varchar(), true))));
9087
9188 UserType keyType = keyspaceMetadata.getUserType(quote("Incr,edibly\" EvilTy<>><<><p\"e"));
9289 UserType valueType = keyspaceMetadata.getUserType(quote("A"));
93- assertThat(parse("map<frozen<\"Incr,edibly\"\" EvilTy<>><<><p\"\"e\">,frozen<\"A\">>", cluster, keyspace, keyspaceMetadata.userTypes, null, false, false))
90+ assertThat(parse("map<frozen<\"Incr,edibly\"\" EvilTy<>><<><p\"\"e\">,frozen<\"A\">>", cluster(), keyspace, keyspaceMetadata.userTypes, null, false, false))
9491 .isEqualTo(map(keyType, valueType, false));
9592 }
9693
9794 @Test(groups = "short")
9895 public void should_parse_tuple_types() {
99- assertThat(parse("tuple<int,list<text>>", cluster, null, null, null, false, false)).isEqualTo(cluster.getMetadata().newTupleType(cint(), list(text())));
96+ assertThat(parse("tuple<int,list<text>>", cluster(), null, null, null, false, false)).isEqualTo(cluster().getMetadata().newTupleType(cint(), list(text())));
10097 }
10198
10299 @Test(groups = "short")
103100 public void should_parse_user_defined_type_when_definition_in_current_user_types() {
104- Metadata metadata = cluster.getMetadata();
101+ Metadata metadata = cluster().getMetadata();
105102 KeyspaceMetadata keyspaceMetadata = metadata.getKeyspace(this.keyspace);
106- assertThat(parse("frozen<\"A\">", cluster, keyspace, keyspaceMetadata.userTypes, null, false, false)).isUserType(keyspace, "A");
103+ assertThat(parse("frozen<\"A\">", cluster(), keyspace, keyspaceMetadata.userTypes, null, false, false)).isUserType(keyspace, "A");
107104 }
108105
109106 @Test(groups = "short")
110107 public void should_parse_user_defined_type_when_definition_in_old_user_types() {
111- Metadata metadata = cluster.getMetadata();
108+ Metadata metadata = cluster().getMetadata();
112109 KeyspaceMetadata keyspaceMetadata = metadata.getKeyspace(this.keyspace);
113- assertThat(parse("\"A\"", cluster, keyspace, null, keyspaceMetadata.userTypes, false, false)).isUserType(keyspace, "A");
110+ assertThat(parse("\"A\"", cluster(), keyspace, null, keyspaceMetadata.userTypes, false, false)).isUserType(keyspace, "A");
114111 }
115112
116113 @Test(groups = "short")
117114 public void should_parse_user_defined_type_to_shallow_type_if_requested() {
118- assertThat(parse("\"A\"", cluster, keyspace, null, null, false, true)).isShallowUserType(keyspace, "A");
115+ assertThat(parse("\"A\"", cluster(), keyspace, null, null, false, true)).isShallowUserType(keyspace, "A");
119116 }
120117
121118 @Override
122- public Collection<String> createTestFixtures() {
123- return Lists.newArrayList(
119+ public void onTestContextInitialized() {
120+ execute(
124121 String.format("CREATE TYPE %s.\"A\" (f1 int)", keyspace),
125122 String.format("CREATE TYPE %s.\"Incr,edibly\"\" EvilTy<>><<><p\"\"e\" (a frozen<\"A\">)", keyspace)
126123 );
modified driver-core/src/test/java/com/datastax/driver/core/DataTypeIntegrationTest.java +13 −15
@@ -46,10 +46,9 @@
4646 enum StatementType {RAW_STRING, SIMPLE_WITH_PARAM, PREPARED}
4747
4848 @Override
49- public Collection<String> createTestFixtures() {
50- Host host = cluster.getMetadata().getAllHosts().iterator().next();
49+ public void onTestContextInitialized() {
50+ Host host = cluster().getMetadata().getAllHosts().iterator().next();
5151 cassandraVersion = host.getCassandraVersion().nextStable();
52-
5352 List<String> statements = Lists.newArrayList();
5453 for (TestTable table : tables) {
5554 if (cassandraVersion.compareTo(table.minCassandraVersion) < 0)
@@ -58,8 +57,7 @@
5857 else
5958 statements.add(table.createStatement);
6059 }
61-
62- return statements;
60+ execute(statements);
6361 }
6462
6563 @Test(groups = "long")
@@ -79,8 +77,8 @@
7977 }
8078
8179 protected void should_insert_and_retrieve_data(StatementType statementType) {
82- ProtocolVersion protocolVersion = cluster.getConfiguration().getProtocolOptions().getProtocolVersion();
83- CodecRegistry codecRegistry = cluster.getConfiguration().getCodecRegistry();
80+ ProtocolVersion protocolVersion = cluster().getConfiguration().getProtocolOptions().getProtocolVersion();
81+ CodecRegistry codecRegistry = cluster().getConfiguration().getCodecRegistry();
8482
8583 for (TestTable table : tables) {
8684 if (cassandraVersion.compareTo(table.minCassandraVersion) < 0)
@@ -92,22 +90,22 @@
9290 String formatValue = codec.format(table.sampleValue);
9391 assertThat(formatValue).isNotNull();
9492 String query = table.insertStatement.replace("?", formatValue);
95- session.execute(query);
93+ session().execute(query);
9694 break;
9795 case SIMPLE_WITH_PARAM:
9896 SimpleStatement statement = new SimpleStatement(table.insertStatement, table.sampleValue);
9997 checkGetValuesReturnsSerializedValue(protocolVersion, statement, table);
100- session.execute(statement);
98+ session().execute(statement);
10199 break;
102100 case PREPARED:
103- PreparedStatement ps = session.prepare(table.insertStatement);
101+ PreparedStatement ps = session().prepare(table.insertStatement);
104102 BoundStatement bs = ps.bind(table.sampleValue);
105103 checkGetterReturnsValue(bs, table);
106- session.execute(bs);
104+ session().execute(bs);
107105 break;
108106 }
109107
110- Row row = session.execute(table.selectStatement).one();
108+ Row row = session().execute(table.selectStatement).one();
111109 Object queriedValue = codec.deserialize(row.getBytesUnsafe("v"), protocolVersion);
112110
113111 // Since codec.deserialize will get the unboxed version for primitive check against expected unboxed value.
@@ -130,7 +128,7 @@
130128 .isEqualTo(table.expectedPrimitiveValue);
131129
132130
133- session.execute(table.truncateStatement);
131+ session().execute(table.truncateStatement);
134132 }
135133 }
136134
@@ -145,7 +143,7 @@
145143 }
146144
147145 public void checkGetValuesReturnsSerializedValue(ProtocolVersion protocolVersion, SimpleStatement statement, TestTable table) {
148- CodecRegistry codecRegistry = cluster.getConfiguration().getCodecRegistry();
146+ CodecRegistry codecRegistry = cluster().getConfiguration().getCodecRegistry();
149147 ByteBuffer[] values = statement.getValues(protocolVersion, codecRegistry);
150148 assertThat(values.length).isEqualTo(1);
151149 assertThat(values[0])
@@ -415,7 +413,7 @@
415413
416414 private Object getValue(GettableByIndexData data, DataType dataType) {
417415 // This is kind of lame, but better than testing all getters manually
418- CodecRegistry codecRegistry = cluster.getConfiguration().getCodecRegistry();
416+ CodecRegistry codecRegistry = cluster().getConfiguration().getCodecRegistry();
419417 switch (dataType.getName()) {
420418 case ASCII:
421419 return data.getString(0);
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().getProtocolVersion(), ProtocolVersion.V1);
59+ assertEquals(cluster().getConfiguration().getProtocolOptions().getProtocolVersion(), ProtocolVersion.V1);
6360 }
6461 }
6562 }
modified driver-core/src/test/java/com/datastax/driver/core/FunctionMetadataTest.java +8 −11
@@ -18,11 +18,8 @@
1818 import com.datastax.driver.core.utils.CassandraVersion;
1919 import org.testng.annotations.Test;
2020
21-import java.util.Collection;
22-
2321 import static com.datastax.driver.core.Assertions.assertThat;
2422 import static com.datastax.driver.core.DataType.cint;
25-import static com.google.common.collect.Lists.newArrayList;
2623 import static org.assertj.core.api.Assertions.entry;
2724
2825 @CassandraVersion(major = 2.2)
@@ -34,9 +31,9 @@
3431 // given
3532 String cql = String.format("CREATE FUNCTION %s.plus(s int,v int) RETURNS NULL ON NULL INPUT RETURNS int LANGUAGE java AS 'return s+v;';", keyspace);
3633 // when
37- session.execute(cql);
34+ session().execute(cql);
3835 // then
39- KeyspaceMetadata keyspace = cluster.getMetadata().getKeyspace(this.keyspace);
36+ KeyspaceMetadata keyspace = cluster().getMetadata().getKeyspace(this.keyspace);
4037 FunctionMetadata function = keyspace.getFunction("plus", cint(), cint());
4138 assertThat(function).isNotNull();
4239 assertThat(function.getKeyspace()).isEqualTo(keyspace);
@@ -66,9 +63,9 @@
6663 // given
6764 String cql = String.format("CREATE FUNCTION %s.pi() CALLED ON NULL INPUT RETURNS double LANGUAGE java AS 'return Math.PI;';", keyspace);
6865 // when
69- session.execute(cql);
66+ session().execute(cql);
7067 // then
71- KeyspaceMetadata keyspace = cluster.getMetadata().getKeyspace(this.keyspace);
68+ KeyspaceMetadata keyspace = cluster().getMetadata().getKeyspace(this.keyspace);
7269 FunctionMetadata function = keyspace.getFunction("pi");
7370 assertThat(function).isNotNull();
7471 assertThat(function.getKeyspace()).isEqualTo(keyspace);
@@ -108,9 +105,9 @@
108105 + body
109106 + "';", keyspace);
110107 // when
111- session.execute(cqlFunction);
108+ session().execute(cqlFunction);
112109 // then
113- KeyspaceMetadata keyspace = cluster.getMetadata().getKeyspace(this.keyspace);
110+ KeyspaceMetadata keyspace = cluster().getMetadata().getKeyspace(this.keyspace);
114111 UserType addressType = keyspace.getUserType("\"Address\"");
115112 FunctionMetadata function = keyspace.getFunction("\"NUM_PHONES_ACCU\"", cint(), addressType);
116113 assertThat(function).isNotNull();
@@ -127,8 +124,8 @@
127124 }
128125
129126 @Override
130- public Collection<String> createTestFixtures() {
131- return newArrayList(
127+ public void onTestContextInitialized() {
128+ execute(
132129 String.format("CREATE TYPE IF NOT EXISTS %s.\"Phone\" (number text)", keyspace),
133130 String.format("CREATE TYPE IF NOT EXISTS %s.\"Address\" ("
134131 + " street text,"
modified driver-core/src/test/java/com/datastax/driver/core/GettableDataIntegrationTest.java +10 −10
@@ -44,10 +44,10 @@
4444 AtomicInteger keyCounter = new AtomicInteger(0);
4545
4646 @Override
47- public Collection<String> createTestFixtures() {
48- is21 = ccm.getVersion().compareTo(VersionNumber.parse("2.1.3")) > 0;
47+ public void onTestContextInitialized() {
48+ is21 = ccm().getVersion().compareTo(VersionNumber.parse("2.1.3")) > 0;
4949 // only add tuples / nested collections at > 2.1.3.
50- return newArrayList("CREATE TABLE codec_mapping (k int PRIMARY KEY, "
50+ execute("CREATE TABLE codec_mapping (k int PRIMARY KEY, "
5151 + "v int, l list<int>, m map<int,int>" +
5252 (is21 ? ", t tuple<int,int>, s set<frozen<list<int>>>)" : ")"));
5353 }
@@ -140,11 +140,11 @@
140140 @Test(groups = "short")
141141 public void should_allow_getting_and_setting_by_type_if_codec_registered() {
142142 String insertStmt = "INSERT INTO codec_mapping (k,v,l,m" + (is21 ? ",t,s" : "") + ") values (?,?,?,?" + (is21 ? ",?,?)" : ")");
143- PreparedStatement insert = session.prepare(insertStmt);
144- PreparedStatement select = session.prepare("SELECT v,l,m" + (is21 ? ",t,s" : "") + " from codec_mapping where k=?");
143+ PreparedStatement insert = session().prepare(insertStmt);
144+ PreparedStatement select = session().prepare("SELECT v,l,m" + (is21 ? ",t,s" : "") + " from codec_mapping where k=?");
145145
146146 TupleType tupleType = new TupleType(newArrayList(DataType.cint(), DataType.cint()),
147- cluster.getConfiguration().getProtocolOptions().getProtocolVersion(), registry);
147+ cluster().getConfiguration().getProtocolOptions().getProtocolVersion(), registry);
148148
149149 for (TypeMapping<?> mapping : mappings) {
150150 // Keys used to insert data in this iteration.
@@ -170,7 +170,7 @@
170170 byName.setTupleValue("t", tupleValue);
171171 byName.setSet("s", set, TypeTokens.listOf(mapping.javaType));
172172 }
173- session.execute(byName);
173+ session().execute(byName);
174174
175175 // Insert by index.
176176 BoundStatement byIndex = insert.bind();
@@ -184,7 +184,7 @@
184184 byIndex.setTupleValue(4, tupleValue);
185185 byIndex.setSet(5, set, TypeTokens.listOf(mapping.javaType));
186186 }
187- session.execute(byIndex);
187+ session().execute(byIndex);
188188
189189 // Insert by binding all at once.
190190 BoundStatement fullBind;
@@ -195,11 +195,11 @@
195195 } else {
196196 fullBind = insert.bind(fullBindKey, mapping.value, list, map);
197197 }
198- session.execute(fullBind);
198+ session().execute(fullBind);
199199
200200 for (int key : keys) {
201201 // Retrieve by name.
202- Row row = session.execute(select.bind(key)).one();
202+ Row row = session().execute(select.bind(key)).one();
203203 assertThat(getValue(row, "v", mapping.outerType, registry)).isEqualTo(mapping.value);
204204 assertThat(row.getList("l", mapping.codec.getJavaType())).isEqualTo(list);
205205 assertThat(row.getMap("m", mapping.codec.getJavaType(), mapping.codec.getJavaType())).isEqualTo(map);
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 −8
@@ -79,13 +79,6 @@
7979 return requests;
8080 }
8181
82- @Override
83- protected Cluster.Builder configure(Cluster.Builder builder) {
84- // Use version 2 at highest.
85- ProtocolVersion versionToUse = TestUtils.getDesiredProtocolVersion(ProtocolVersion.V2);
86- return builder.withProtocolVersion(versionToUse);
87- }
88-
8982 /**
9083 * Completes count requests by simulating a successful response.
9184 */
@@ -433,7 +426,6 @@
433426 // On returning of the connection, should detect that there are no available streams and trash it.
434427 assertThat(pool.trash).hasSize(0);
435428 pool.returnConnection(extra1);
436- assertThat(pool.connections).hasSize(1);
437429 assertThat(pool.trash).hasSize(1);
438430 } finally {
439431 completeRequests(requests);
modified driver-core/src/test/java/com/datastax/driver/core/IndexMetadataTest.java +24 −28
@@ -24,7 +24,6 @@
2424 import org.testng.annotations.Test;
2525
2626 import java.nio.ByteBuffer;
27-import java.util.Collection;
2827 import java.util.List;
2928 import java.util.Map;
3029
@@ -63,10 +62,9 @@
6362 private ProtocolVersion protocolVersion;
6463
6564 @Override
66- public Collection<String> createTestFixtures() {
67- protocolVersion = cluster.getConfiguration().getProtocolOptions().getProtocolVersion();
68- ImmutableList.Builder<String> builder = ImmutableList.builder();
69- builder.add("CREATE TABLE indexing ("
65+ public void onTestContextInitialized() {
66+ protocolVersion = cluster().getConfiguration().getProtocolOptions().getProtocolVersion();
67+ String createTable = "CREATE TABLE indexing ("
7068 + "id int,"
7169 + "id2 int,"
7270 + "map_values map<text, int>,"
@@ -77,23 +75,21 @@
7775 + "\"MixedCaseColumn\" list<text>,"
7876 +
7977 // Frozen collections was introduced only in C* 2.1.3
80- (ccm.getVersion().compareTo(VersionNumber.parse("2.1.3")) >= 0
78+ (ccm().getVersion().compareTo(VersionNumber.parse("2.1.3")) >= 0
8179 ?
8280 ", map_full frozen<map<text, int>>,"
8381 + "set_full frozen<set<text>>,"
8482 + "list_full frozen<list<text>>,"
8583 :
8684 "")
87- + "PRIMARY KEY (id, id2));"
88- );
89-
90- return builder.build();
85+ + "PRIMARY KEY (id, id2));";
86+ execute(createTable);
9187 }
9288
9389 @Test(groups = "short")
9490 public void should_create_metadata_for_simple_index() {
9591 String createValuesIndex = String.format("CREATE INDEX text_column_index ON %s.indexing (text_column);", keyspace);
96- session.execute(createValuesIndex);
92+ session().execute(createValuesIndex);
9793 ColumnMetadata column = getColumn("text_column");
9894 IndexMetadata index = getIndex("text_column_index");
9995 assertThat(index)
@@ -110,17 +106,17 @@
110106 @CassandraVersion(major = 2.1, description = "index names with quoted identifiers and collection indexes not supported until 2.1")
111107 public void should_create_metadata_for_values_index_on_mixed_case_column() {
112108 // 3.0 assumes the 'values' keyword if index on a collection
113- String createValuesIndex = ccm.getVersion().getMajor() > 2 ?
109+ String createValuesIndex = ccm().getVersion().getMajor() > 2 ?
114110 String.format("CREATE INDEX \"MixedCaseIndex\" ON %s.indexing (values(\"MixedCaseColumn\"));", keyspace) :
115111 String.format("CREATE INDEX \"MixedCaseIndex\" ON %s.indexing (\"MixedCaseColumn\");", keyspace);
116- session.execute(createValuesIndex);
112+ session().execute(createValuesIndex);
117113 ColumnMetadata column = getColumn("\"MixedCaseColumn\"");
118114 IndexMetadata index = getIndex("\"MixedCaseIndex\"");
119115 assertThat(index)
120116 .hasName("MixedCaseIndex")
121117 .hasParent((TableMetadata) column.getParent())
122118 .isNotCustomIndex()
123- .hasTarget(ccm.getVersion().getMajor() > 2 ? "values(\"MixedCaseColumn\")" : "\"MixedCaseColumn\"")
119+ .hasTarget(ccm().getVersion().getMajor() > 2 ? "values(\"MixedCaseColumn\")" : "\"MixedCaseColumn\"")
124120 .hasKind(COMPOSITES)
125121 .asCqlQuery(createValuesIndex);
126122 assertThat((TableMetadata) column.getParent()).hasIndex(index);
@@ -130,17 +126,17 @@
130126 @CassandraVersion(major = 2.1)
131127 public void should_create_metadata_for_index_on_map_values() {
132128 // 3.0 assumes the 'values' keyword if index on a collection
133- String createValuesIndex = ccm.getVersion().getMajor() > 2 ?
129+ String createValuesIndex = ccm().getVersion().getMajor() > 2 ?
134130 String.format("CREATE INDEX map_values_index ON %s.indexing (values(map_values));", keyspace) :
135131 String.format("CREATE INDEX map_values_index ON %s.indexing (map_values);", keyspace);
136- session.execute(createValuesIndex);
132+ session().execute(createValuesIndex);
137133 ColumnMetadata column = getColumn("map_values");
138134 IndexMetadata index = getIndex("map_values_index");
139135 assertThat(index)
140136 .hasName("map_values_index")
141137 .hasParent((TableMetadata) column.getParent())
142138 .isNotCustomIndex()
143- .hasTarget(ccm.getVersion().getMajor() > 2 ? "values(map_values)" : "map_values")
139+ .hasTarget(ccm().getVersion().getMajor() > 2 ? "values(map_values)" : "map_values")
144140 .hasKind(COMPOSITES)
145141 .asCqlQuery(createValuesIndex);
146142 assertThat((TableMetadata) column.getParent()).hasIndex(index);
@@ -150,7 +146,7 @@
150146 @CassandraVersion(major = 2.1)
151147 public void should_create_metadata_for_index_on_map_keys() {
152148 String createKeysIndex = String.format("CREATE INDEX map_keys_index ON %s.indexing (keys(map_keys));", keyspace);
153- session.execute(createKeysIndex);
149+ session().execute(createKeysIndex);
154150 ColumnMetadata column = getColumn("map_keys");
155151 IndexMetadata index = getIndex("map_keys_index");
156152 assertThat(index)
@@ -167,7 +163,7 @@
167163 @CassandraVersion(major = 2.1, minor = 3)
168164 public void should_create_metadata_for_full_index_on_map() {
169165 String createFullIndex = String.format("CREATE INDEX map_full_index ON %s.indexing (full(map_full));", keyspace);
170- session.execute(createFullIndex);
166+ session().execute(createFullIndex);
171167 ColumnMetadata column = getColumn("map_full");
172168 IndexMetadata index = getIndex("map_full_index");
173169 assertThat(index)
@@ -184,7 +180,7 @@
184180 @CassandraVersion(major = 2.1, minor = 3)
185181 public void should_create_metadata_for_full_index_on_set() {
186182 String createFullIndex = String.format("CREATE INDEX set_full_index ON %s.indexing (full(set_full));", keyspace);
187- session.execute(createFullIndex);
183+ session().execute(createFullIndex);
188184 ColumnMetadata column = getColumn("set_full");
189185 IndexMetadata index = getIndex("set_full_index");
190186 assertThat(index)
@@ -201,7 +197,7 @@
201197 @CassandraVersion(major = 2.1, minor = 3)
202198 public void should_create_metadata_for_full_index_on_list() {
203199 String createFullIndex = String.format("CREATE INDEX list_full_index ON %s.indexing (full(list_full));", keyspace);
204- session.execute(createFullIndex);
200+ session().execute(createFullIndex);
205201 ColumnMetadata column = getColumn("list_full");
206202 IndexMetadata index = getIndex("list_full_index");
207203 assertThat(index)
@@ -218,7 +214,7 @@
218214 @CassandraVersion(major = 2.2)
219215 public void should_create_metadata_for_index_on_map_entries() {
220216 String createEntriesIndex = String.format("CREATE INDEX map_entries_index ON %s.indexing (entries(map_entries));", keyspace);
221- session.execute(createEntriesIndex);
217+ session().execute(createEntriesIndex);
222218 ColumnMetadata column = getColumn("map_entries");
223219 IndexMetadata index = getIndex("map_entries_index");
224220 assertThat(index)
@@ -235,11 +231,11 @@
235231 @CassandraVersion(major = 3.0)
236232 public void should_allow_multiple_indexes_on_map_column() {
237233 String createEntriesIndex = String.format("CREATE INDEX map_all_entries_index ON %s.indexing (entries(map_all));", keyspace);
238- session.execute(createEntriesIndex);
234+ session().execute(createEntriesIndex);
239235 String createKeysIndex = String.format("CREATE INDEX map_all_keys_index ON %s.indexing (keys(map_all));", keyspace);
240- session.execute(createKeysIndex);
236+ session().execute(createKeysIndex);
241237 String createValuesIndex = String.format("CREATE INDEX map_all_values_index ON %s.indexing (values(map_all));", keyspace);
242- session.execute(createValuesIndex);
238+ session().execute(createValuesIndex);
243239
244240 ColumnMetadata column = getColumn("map_all");
245241 TableMetadata table = (TableMetadata) column.getParent();
@@ -335,7 +331,7 @@
335331 wrap("org.apache.cassandra.db.marshal.BytesType"), // validator
336332 wrap("null") // index options
337333 );
338- Row row = ArrayBackedRow.fromData(legacyColumnDefs, M3PToken.FACTORY, cluster.getConfiguration().getProtocolOptions().getProtocolVersion(), data);
334+ Row row = ArrayBackedRow.fromData(legacyColumnDefs, M3PToken.FACTORY, cluster().getConfiguration().getProtocolOptions().getProtocolVersion(), data);
339335 Raw raw = Raw.fromRow(row, VersionNumber.parse("2.1"));
340336 ColumnMetadata column = ColumnMetadata.fromRaw(table, raw, DataType.blob());
341337 IndexMetadata index = IndexMetadata.fromLegacy(column, raw);
@@ -375,10 +371,10 @@
375371 }
376372
377373 private TableMetadata getTable(String name) {
378- return cluster.getMetadata().getKeyspace(keyspace).getTable(name);
374+ return cluster().getMetadata().getKeyspace(keyspace).getTable(name);
379375 }
380376
381377 private MaterializedViewMetadata getMaterializedView(String name) {
382- return cluster.getMetadata().getKeyspace(keyspace).getMaterializedView(name);
378+ return cluster().getMetadata().getKeyspace(keyspace).getMaterializedView(name);
383379 }
384380 }
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 < 4000; ++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 +6 −6
@@ -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()) {
86- if (h.getAddress().equals(ccm.addressOfNode(1).getAddress()))
85+ for (Host h : cluster().getMetadata().getAllHosts()) {
86+ if (h.getAddress().equals(ccm().addressOfNode(1).getAddress()))
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/MaterializedViewMetadataTest.java +8 −15
@@ -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 com.datastax.driver.core.Assertions.assertThat;
2522 import static com.datastax.driver.core.ClusteringOrder.DESC;
2623 import static com.datastax.driver.core.DataType.cint;
@@ -58,12 +55,12 @@
5855 keyspace, keyspace);
5956
6057 // when
61- session.execute(createTable);
62- session.execute(createMV);
58+ session().execute(createTable);
59+ session().execute(createMV);
6360
6461 // then
65- TableMetadata table = cluster.getMetadata().getKeyspace(keyspace).getTable("scores");
66- MaterializedViewMetadata mv = cluster.getMetadata().getKeyspace(keyspace).getMaterializedView("monthlyhigh");
62+ TableMetadata table = cluster().getMetadata().getKeyspace(keyspace).getTable("scores");
63+ MaterializedViewMetadata mv = cluster().getMetadata().getKeyspace(keyspace).getMaterializedView("monthlyhigh");
6764
6865 assertThat(table).isNotNull().hasName("scores").hasMaterializedView(mv).hasNumberOfColumns(6);
6966 assertThat(table.getColumns().get(0)).isNotNull().hasName("user").isPartitionKey();
@@ -107,11 +104,11 @@
107104 + "PRIMARY KEY (\"theKey\", \"the;Clustering\")",
108105 keyspace, keyspace);
109106 // when
110- session.execute(createTable);
111- session.execute(createMV);
107+ session().execute(createTable);
108+ session().execute(createMV);
112109 // then
113- TableMetadata table = cluster.getMetadata().getKeyspace(keyspace).getTable("\"T1\"");
114- MaterializedViewMetadata mv = cluster.getMetadata().getKeyspace(keyspace).getMaterializedView("\"Mv1\"");
110+ TableMetadata table = cluster().getMetadata().getKeyspace(keyspace).getTable("\"T1\"");
111+ MaterializedViewMetadata mv = cluster().getMetadata().getKeyspace(keyspace).getMaterializedView("\"Mv1\"");
115112 assertThat(table).isNotNull().hasName("T1").hasMaterializedView(mv).hasNumberOfColumns(3);
116113 assertThat(table.getViews()).hasSize(1).containsOnly(mv);
117114 assertThat(table.getColumns().get(0)).isNotNull().hasName("theKey").isPartitionKey().hasType(cint());
@@ -124,8 +121,4 @@
124121 assertThat(mv.asCQLQuery(false)).contains(createMV);
125122 }
126123
127- @Override
128- public Collection<String> createTestFixtures() {
129- return Collections.emptyList();
130- }
131124 }
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 +13 −15
@@ -19,7 +19,6 @@
1919 import com.datastax.driver.core.exceptions.DriverException;
2020 import com.datastax.driver.core.policies.RetryPolicy;
2121 import com.datastax.driver.core.policies.RetryPolicy.RetryDecision;
22-import com.google.common.collect.Lists;
2322 import org.testng.annotations.Test;
2423
2524 import javax.management.InstanceNotFoundException;
@@ -27,7 +26,6 @@
2726 import javax.management.MBeanServer;
2827 import javax.management.ObjectName;
2928 import java.lang.management.ManagementFactory;
30-import java.util.Collection;
3129
3230 import static com.datastax.driver.core.Assertions.assertThat;
3331 import static org.testng.Assert.assertEquals;
@@ -71,8 +69,8 @@
7169 }
7270
7371 @Override
74- public Collection<String> createTestFixtures() {
75- return Lists.newArrayList("CREATE TABLE test (k int primary key, v int)",
72+ public void onTestContextInitialized() {
73+ execute("CREATE TABLE test (k int primary key, v int)",
7674 "INSERT INTO test (k, v) VALUES (1, 1)");
7775 }
7876
@@ -82,15 +80,15 @@
8280
8381 // We only have one node, this will throw an unavailable exception
8482 Statement statement = new SimpleStatement("SELECT v FROM test WHERE k = 1").setConsistencyLevel(ConsistencyLevel.TWO);
85- session.execute(statement);
83+ session().execute(statement);
8684
87- Errors errors = cluster.getMetrics().getErrorMetrics();
85+ Errors errors = cluster().getMetrics().getErrorMetrics();
8886 assertEquals(errors.getUnavailables().getCount(), 1);
8987 assertEquals(errors.getRetries().getCount(), 1);
9088 assertEquals(errors.getRetriesOnUnavailable().getCount(), 1);
9189
9290 retryDecision = RetryDecision.ignore();
93- session.execute(statement);
91+ session().execute(statement);
9492
9593 assertEquals(errors.getUnavailables().getCount(), 2);
9694 assertEquals(errors.getIgnores().getCount(), 1);
@@ -106,13 +104,13 @@
106104 */
107105 @Test(groups = "short")
108106 public void should_enable_metrics_and_jmx_by_default() throws Exception {
109- assertThat(cluster.getMetrics()).isNotNull();
110- ObjectName clusterMetricsON = ObjectName.getInstance(cluster.getClusterName() + "-metrics:name=connected-to");
107+ assertThat(cluster().getMetrics()).isNotNull();
108+ ObjectName clusterMetricsON = ObjectName.getInstance(cluster().getClusterName() + "-metrics:name=connected-to");
111109 MBeanInfo mBean = server.getMBeanInfo(clusterMetricsON);
112110 assertThat(mBean).isNotNull();
113111
114- assertThat(cluster.getConfiguration().getMetricsOptions().isEnabled()).isTrue();
115- assertThat(cluster.getConfiguration().getMetricsOptions().isJMXReportingEnabled()).isTrue();
112+ assertThat(cluster().getConfiguration().getMetricsOptions().isEnabled()).isTrue();
113+ assertThat(cluster().getConfiguration().getMetricsOptions().isJMXReportingEnabled()).isTrue();
116114 }
117115
118116 /**
@@ -125,8 +123,8 @@
125123 @Test(groups = "short", expectedExceptions = InstanceNotFoundException.class)
126124 public void metrics_should_be_null_when_metrics_disabled() throws Exception {
127125 Cluster cluster = register(Cluster.builder()
128- .addContactPointsWithPorts(getInitialContactPoints())
129- .withPort(ccm.getBinaryPort())
126+ .addContactPoints(getContactPoints())
127+ .withPort(ccm().getBinaryPort())
130128 .withoutMetrics()
131129 .build());
132130 try {
@@ -150,8 +148,8 @@
150148 @Test(groups = "short", expectedExceptions = InstanceNotFoundException.class)
151149 public void should_be_no_jmx_mbean_when_jmx_is_disabled() throws Exception {
152150 Cluster cluster = register(Cluster.builder()
153- .addContactPointsWithPorts(getInitialContactPoints())
154- .withPort(ccm.getBinaryPort())
151+ .addContactPoints(getContactPoints())
152+ .withPort(ccm().getBinaryPort())
155153 .withoutJMXReporting()
156154 .build());
157155 try {
modified driver-core/src/test/java/com/datastax/driver/core/MissingRpcAddressTest.java +6 −7
@@ -24,7 +24,6 @@
2424 import java.net.InetSocketAddress;
2525
2626 import static com.datastax.driver.core.CreateCCM.TestMode.PER_METHOD;
27-import static java.util.Collections.singleton;
2827 import static org.testng.Assert.assertEquals;
2928 import static org.testng.Assert.assertNull;
3029
@@ -42,22 +41,22 @@
4241 deleteNode2RpcAddressFromNode1();
4342 // Use only one contact point to make sure that the control connection is on node1
4443 Cluster cluster = register(Cluster.builder()
45- .addContactPoints(ccm.addressOfNode(1).getAddress())
46- .withPort(ccm.getBinaryPort())
44+ .addContactPoints(getContactPoints().get(0))
45+ .withPort(ccm().getBinaryPort())
4746 .build());
4847 cluster.connect();
4948
5049 // Since node2's RPC address is unknown on our control host, it should have been ignored
5150 assertEquals(cluster.getMetrics().getConnectedToHosts().getValue().intValue(), 1);
52- assertNull(cluster.getMetadata().getHost(getInitialContactPoints().get(1)));
51+ assertNull(cluster.getMetadata().getHost(getContactPointsWithPorts().get(1)));
5352 }
5453
5554 // Artificially modify the system tables to simulate the missing rpc_address.
5655 private void deleteNode2RpcAddressFromNode1() throws Exception {
57- InetSocketAddress firstHost = ccm.addressOfNode(1);
56+ InetSocketAddress firstHost = ccm().addressOfNode(1);
5857 Cluster cluster = register(Cluster.builder()
59- .addContactPointsWithPorts(singleton(firstHost))
60- .withPort(ccm.getBinaryPort())
58+ .addContactPoints(firstHost.getAddress())
59+ .withPort(ccm().getBinaryPort())
6160 // ensure we will only connect to node1
6261 .withLoadBalancingPolicy(new WhiteListPolicy(Policies.defaultLoadBalancingPolicy(),
6362 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/PreparedIdTest.java +5 −8
@@ -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 com.datastax.driver.core.Assertions.assertThat;
2421
2522 public class PreparedIdTest extends CCMTestsSupport {
2623
2724 @Override
28- public Collection<String> createTestFixtures() {
29- return Lists.newArrayList(
25+ public void onTestContextInitialized() {
26+ execute(
3027 "CREATE TABLE foo(k1 int, k2 int, k3 int, v int, PRIMARY KEY ((k1, k2, k3)))"
3128 );
3229 }
@@ -38,7 +35,7 @@
3835 */
3936 @Test(groups = "short")
4037 public void should_have_routing_key_indexes_when_all_bound() {
41- PreparedStatement pst = session.prepare("INSERT INTO foo (k3, k1, k2, v) VALUES (?, ?, ?, ?)");
38+ PreparedStatement pst = session().prepare("INSERT INTO foo (k3, k1, k2, v) VALUES (?, ?, ?, ?)");
4239 assertThat(pst.getPreparedId().routingKeyIndexes).containsExactly(1, 2, 0);
4340 }
4441
@@ -49,7 +46,7 @@
4946 */
5047 @Test(groups = "short")
5148 public void should_not_have_routing_key_indexes_when_some_not_bound() {
52- PreparedStatement pst = session.prepare("INSERT INTO foo (k3, k1, k2, v) VALUES (1, ?, ?, ?)");
49+ PreparedStatement pst = session().prepare("INSERT INTO foo (k3, k1, k2, v) VALUES (1, ?, ?, ?)");
5350 assertThat(pst.getPreparedId().routingKeyIndexes).isNull();
5451 }
5552
@@ -60,7 +57,7 @@
6057 */
6158 @Test(groups = "short")
6259 public void should_not_have_routing_key_indexes_when_none_bound() {
63- PreparedStatement pst = session.prepare("INSERT INTO foo (k3, k1, k2, v) VALUES (1, 1, 1, 1)");
60+ PreparedStatement pst = session().prepare("INSERT INTO foo (k3, k1, k2, v) VALUES (1, 1, 1, 1)");
6461 assertThat(pst.getPreparedId().routingKeyIndexes).isNull();
6562 }
6663 }
modified driver-core/src/test/java/com/datastax/driver/core/PreparedStatementTest.java +86 −90
@@ -51,8 +51,11 @@
5151 }
5252
5353 @Override
54- public Collection<String> createTestFixtures() {
54+ public void onTestContextInitialized() {
55+ execute(createTestFixtures());
56+ }
5557
58+ private List<String> createTestFixtures() {
5659 List<String> defs = new ArrayList<String>(4);
5760
5861 StringBuilder sb = new StringBuilder();
@@ -105,7 +108,6 @@
105108
106109 defs.add(String.format("CREATE TABLE %s (k text PRIMARY KEY, i int)", SIMPLE_TABLE));
107110 defs.add(String.format("CREATE TABLE %s (k text PRIMARY KEY, v text)", SIMPLE_TABLE2));
108-
109111 return defs;
110112 }
111113
@@ -118,13 +120,13 @@
118120 continue;
119121
120122 String name = "c_" + type;
121- PreparedStatement ps = session.prepare(String.format("INSERT INTO %s(k, %s) VALUES ('prepared_native', ?)", ALL_NATIVE_TABLE, name));
123+ PreparedStatement ps = session().prepare(String.format("INSERT INTO %s(k, %s) VALUES ('prepared_native', ?)", ALL_NATIVE_TABLE, name));
122124 BoundStatement bs = ps.bind();
123125 setValue(bs, name, type, getFixedValue(type));
124- session.execute(bs);
126+ session().execute(bs);
125127
126- Row row = session.execute(String.format("SELECT %s FROM %s WHERE k='prepared_native'", name, ALL_NATIVE_TABLE)).one();
127- assertEquals(getValue(row, name, type, cluster.getConfiguration().getCodecRegistry()), getFixedValue(type), "For type " + type);
128+ Row row = session().execute(String.format("SELECT %s FROM %s WHERE k='prepared_native'", name, ALL_NATIVE_TABLE)).one();
129+ assertEquals(getValue(row, name, type, cluster().getConfiguration().getCodecRegistry()), getFixedValue(type), "For type " + type);
128130 }
129131 }
130132
@@ -140,13 +142,13 @@
140142 continue;
141143
142144 String name = "c_" + type;
143- PreparedStatement ps = session.prepare(String.format("INSERT INTO %s(k, %s) VALUES ('prepared_native', ?)", ALL_NATIVE_TABLE, name));
145+ PreparedStatement ps = session().prepare(String.format("INSERT INTO %s(k, %s) VALUES ('prepared_native', ?)", ALL_NATIVE_TABLE, name));
144146 BoundStatement bs = ps.bind();
145147 setValue(bs, name, type, getFixedValue2(type));
146- session.execute(bs);
148+ session().execute(bs);
147149
148- Row row = session.execute(String.format("SELECT %s FROM %s WHERE k='prepared_native'", name, ALL_NATIVE_TABLE)).one();
149- assertEquals(getValue(row, name, type, cluster.getConfiguration().getCodecRegistry()), getFixedValue2(type), "For type " + type);
150+ Row row = session().execute(String.format("SELECT %s FROM %s WHERE k='prepared_native'", name, ALL_NATIVE_TABLE)).one();
151+ assertEquals(getValue(row, name, type, cluster().getConfiguration().getCodecRegistry()), getFixedValue2(type), "For type " + type);
150152 }
151153 }
152154
@@ -162,13 +164,13 @@
162164 String name = "c_list_" + rawType;
163165 DataType type = DataType.list(rawType);
164166 List<Object> value = (List<Object>) getFixedValue(type);
165- PreparedStatement ps = session.prepare(String.format("INSERT INTO %s(k, %s) VALUES ('prepared_list', ?)", ALL_LIST_TABLE, name));
167+ PreparedStatement ps = session().prepare(String.format("INSERT INTO %s(k, %s) VALUES ('prepared_list', ?)", ALL_LIST_TABLE, name));
166168 BoundStatement bs = ps.bind();
167169 setValue(bs, name, type, value);
168- session.execute(bs);
170+ session().execute(bs);
169171
170- Row row = session.execute(String.format("SELECT %s FROM %s WHERE k='prepared_list'", name, ALL_LIST_TABLE)).one();
171- assertEquals(getValue(row, name, type, cluster.getConfiguration().getCodecRegistry()), value, "For type " + type);
172+ Row row = session().execute(String.format("SELECT %s FROM %s WHERE k='prepared_list'", name, ALL_LIST_TABLE)).one();
173+ assertEquals(getValue(row, name, type, cluster().getConfiguration().getCodecRegistry()), value, "For type " + type);
172174 }
173175 }
174176
@@ -187,13 +189,13 @@
187189 String name = "c_list_" + rawType;
188190 DataType type = DataType.list(rawType);
189191 List<Object> value = (List<Object>) getFixedValue2(type);
190- PreparedStatement ps = session.prepare(String.format("INSERT INTO %s(k, %s) VALUES ('prepared_list', ?)", ALL_LIST_TABLE, name));
192+ PreparedStatement ps = session().prepare(String.format("INSERT INTO %s(k, %s) VALUES ('prepared_list', ?)", ALL_LIST_TABLE, name));
191193 BoundStatement bs = ps.bind();
192194 setValue(bs, name, type, value);
193- session.execute(bs);
195+ session().execute(bs);
194196
195- Row row = session.execute(String.format("SELECT %s FROM %s WHERE k='prepared_list'", name, ALL_LIST_TABLE)).one();
196- assertEquals(getValue(row, name, type, cluster.getConfiguration().getCodecRegistry()), value, "For type " + type);
197+ Row row = session().execute(String.format("SELECT %s FROM %s WHERE k='prepared_list'", name, ALL_LIST_TABLE)).one();
198+ assertEquals(getValue(row, name, type, cluster().getConfiguration().getCodecRegistry()), value, "For type " + type);
197199 }
198200 }
199201
@@ -209,13 +211,13 @@
209211 String name = "c_set_" + rawType;
210212 DataType type = DataType.set(rawType);
211213 Set<Object> value = (Set<Object>) getFixedValue(type);
212- PreparedStatement ps = session.prepare(String.format("INSERT INTO %s(k, %s) VALUES ('prepared_set', ?)", ALL_SET_TABLE, name));
214+ PreparedStatement ps = session().prepare(String.format("INSERT INTO %s(k, %s) VALUES ('prepared_set', ?)", ALL_SET_TABLE, name));
213215 BoundStatement bs = ps.bind();
214216 setValue(bs, name, type, value);
215- session.execute(bs);
217+ session().execute(bs);
216218
217- Row row = session.execute(String.format("SELECT %s FROM %s WHERE k='prepared_set'", name, ALL_SET_TABLE)).one();
218- assertEquals(getValue(row, name, type, cluster.getConfiguration().getCodecRegistry()), value, "For type " + type);
219+ Row row = session().execute(String.format("SELECT %s FROM %s WHERE k='prepared_set'", name, ALL_SET_TABLE)).one();
220+ assertEquals(getValue(row, name, type, cluster().getConfiguration().getCodecRegistry()), value, "For type " + type);
219221 }
220222 }
221223
@@ -234,13 +236,13 @@
234236 String name = "c_set_" + rawType;
235237 DataType type = DataType.set(rawType);
236238 Set<Object> value = (Set<Object>) getFixedValue2(type);
237- PreparedStatement ps = session.prepare(String.format("INSERT INTO %s(k, %s) VALUES ('prepared_set', ?)", ALL_SET_TABLE, name));
239+ PreparedStatement ps = session().prepare(String.format("INSERT INTO %s(k, %s) VALUES ('prepared_set', ?)", ALL_SET_TABLE, name));
238240 BoundStatement bs = ps.bind();
239241 setValue(bs, name, type, value);
240- session.execute(bs);
242+ session().execute(bs);
241243
242- Row row = session.execute(String.format("SELECT %s FROM %s WHERE k='prepared_set'", name, ALL_SET_TABLE)).one();
243- assertEquals(getValue(row, name, type, cluster.getConfiguration().getCodecRegistry()), value, "For type " + type);
244+ Row row = session().execute(String.format("SELECT %s FROM %s WHERE k='prepared_set'", name, ALL_SET_TABLE)).one();
245+ assertEquals(getValue(row, name, type, cluster().getConfiguration().getCodecRegistry()), value, "For type " + type);
244246 }
245247 }
246248
@@ -261,13 +263,13 @@
261263 String name = "c_map_" + rawKeyType + '_' + rawValueType;
262264 DataType type = DataType.map(rawKeyType, rawValueType);
263265 Map<Object, Object> value = (Map<Object, Object>) getFixedValue(type);
264- PreparedStatement ps = session.prepare(String.format("INSERT INTO %s(k, %s) VALUES ('prepared_map', ?)", ALL_MAP_TABLE, name));
266+ PreparedStatement ps = session().prepare(String.format("INSERT INTO %s(k, %s) VALUES ('prepared_map', ?)", ALL_MAP_TABLE, name));
265267 BoundStatement bs = ps.bind();
266268 setValue(bs, name, type, value);
267- session.execute(bs);
269+ session().execute(bs);
268270
269- Row row = session.execute(String.format("SELECT %s FROM %s WHERE k='prepared_map'", name, ALL_MAP_TABLE)).one();
270- assertEquals(getValue(row, name, type, cluster.getConfiguration().getCodecRegistry()), value, "For type " + type);
271+ Row row = session().execute(String.format("SELECT %s FROM %s WHERE k='prepared_map'", name, ALL_MAP_TABLE)).one();
272+ assertEquals(getValue(row, name, type, cluster().getConfiguration().getCodecRegistry()), value, "For type " + type);
271273 }
272274 }
273275 }
@@ -292,13 +294,13 @@
292294 String name = "c_map_" + rawKeyType + '_' + rawValueType;
293295 DataType type = DataType.map(rawKeyType, rawValueType);
294296 Map<Object, Object> value = (Map<Object, Object>) getFixedValue2(type);
295- PreparedStatement ps = session.prepare(String.format("INSERT INTO %s(k, %s) VALUES ('prepared_map', ?)", ALL_MAP_TABLE, name));
297+ PreparedStatement ps = session().prepare(String.format("INSERT INTO %s(k, %s) VALUES ('prepared_map', ?)", ALL_MAP_TABLE, name));
296298 BoundStatement bs = ps.bind();
297299 setValue(bs, name, type, value);
298- session.execute(bs);
300+ session().execute(bs);
299301
300- Row row = session.execute(String.format("SELECT %s FROM %s WHERE k='prepared_map'", name, ALL_MAP_TABLE)).one();
301- assertEquals(getValue(row, name, type, cluster.getConfiguration().getCodecRegistry()), value, "For type " + type);
302+ Row row = session().execute(String.format("SELECT %s FROM %s WHERE k='prepared_map'", name, ALL_MAP_TABLE)).one();
303+ assertEquals(getValue(row, name, type, cluster().getConfiguration().getCodecRegistry()), value, "For type " + type);
302304 }
303305 }
304306 }
@@ -306,16 +308,16 @@
306308 @Test(groups = "short")
307309 public void prepareWithNullValuesTest() throws Exception {
308310
309- PreparedStatement ps = session.prepare("INSERT INTO " + SIMPLE_TABLE2 + "(k, v) VALUES (?, ?)");
311+ PreparedStatement ps = session().prepare("INSERT INTO " + SIMPLE_TABLE2 + "(k, v) VALUES (?, ?)");
310312
311- session.execute(ps.bind("prepWithNull1", null));
313+ session().execute(ps.bind("prepWithNull1", null));
312314
313315 BoundStatement bs = ps.bind();
314316 bs.setString("k", "prepWithNull2");
315317 bs.setString("v", null);
316- session.execute(bs);
318+ session().execute(bs);
317319
318- ResultSet rs = session.execute("SELECT * FROM " + SIMPLE_TABLE2 + " WHERE k IN ('prepWithNull1', 'prepWithNull2')");
320+ ResultSet rs = session().execute("SELECT * FROM " + SIMPLE_TABLE2 + " WHERE k IN ('prepWithNull1', 'prepWithNull2')");
319321 Row r1 = rs.one();
320322 Row r2 = rs.one();
321323 assertTrue(rs.isExhausted());
@@ -334,7 +336,7 @@
334336 toPrepare.setConsistencyLevel(ConsistencyLevel.QUORUM);
335337 toPrepare.enableTracing();
336338
337- PreparedStatement prepared = session.prepare(toPrepare);
339+ PreparedStatement prepared = session().prepare(toPrepare);
338340 BoundStatement bs = prepared.bind("someValue");
339341
340342 assertEquals(ConsistencyLevel.QUORUM, bs.getConsistencyLevel());
@@ -356,17 +358,17 @@
356358 public void batchTest() throws Exception {
357359
358360 try {
359- PreparedStatement ps1 = session.prepare("INSERT INTO " + SIMPLE_TABLE2 + "(k, v) VALUES (?, ?)");
360- PreparedStatement ps2 = session.prepare("INSERT INTO " + SIMPLE_TABLE2 + "(k, v) VALUES (?, 'bar')");
361+ PreparedStatement ps1 = session().prepare("INSERT INTO " + SIMPLE_TABLE2 + "(k, v) VALUES (?, ?)");
362+ PreparedStatement ps2 = session().prepare("INSERT INTO " + SIMPLE_TABLE2 + "(k, v) VALUES (?, 'bar')");
361363
362364 BatchStatement bs = new BatchStatement();
363365 bs.add(ps1.bind("one", "foo"));
364366 bs.add(ps2.bind("two"));
365367 bs.add(new SimpleStatement("INSERT INTO " + SIMPLE_TABLE2 + " (k, v) VALUES ('three', 'foobar')"));
366368
367- session.execute(bs);
369+ session().execute(bs);
368370
369- List<Row> all = session.execute("SELECT * FROM " + SIMPLE_TABLE2).all();
371+ List<Row> all = session().execute("SELECT * FROM " + SIMPLE_TABLE2).all();
370372
371373 assertEquals("three", all.get(0).getString("k"));
372374 assertEquals("foobar", all.get(0).getString("v"));
@@ -378,29 +380,29 @@
378380 assertEquals("bar", all.get(2).getString("v"));
379381 } catch (UnsupportedFeatureException e) {
380382 // This is expected when testing the protocol v1
381- if (cluster.getConfiguration().getProtocolOptions().getProtocolVersion() != ProtocolVersion.V1)
383+ if (cluster().getConfiguration().getProtocolOptions().getProtocolVersion() != ProtocolVersion.V1)
382384 throw e;
383385 }
384386 }
385387
386388 @Test(groups = "short")
387389 public void should_set_routing_key_on_case_insensitive_keyspace_and_table() {
388- session.execute(String.format("CREATE TABLE %s.foo (i int PRIMARY KEY)", keyspace));
390+ session().execute(String.format("CREATE TABLE %s.foo (i int PRIMARY KEY)", keyspace));
389391
390- PreparedStatement ps = session.prepare(String.format("INSERT INTO %s.foo (i) VALUES (?)", keyspace));
392+ PreparedStatement ps = session().prepare(String.format("INSERT INTO %s.foo (i) VALUES (?)", keyspace));
391393 BoundStatement bs = ps.bind(1);
392394 assertThat(bs.getRoutingKey(ProtocolVersion.NEWEST_SUPPORTED, CodecRegistry.DEFAULT_INSTANCE)).isNotNull();
393395 }
394396
395397 @Test(groups = "short")
396398 public void should_set_routing_key_on_case_sensitive_keyspace_and_table() {
397- session.execute("CREATE KEYSPACE \"Test\" WITH replication = { "
399+ session().execute("CREATE KEYSPACE \"Test\" WITH replication = { "
398400 + " 'class': 'SimpleStrategy',"
399401 + " 'replication_factor': '1'"
400402 + "}");
401- session.execute("CREATE TABLE \"Test\".\"Foo\" (i int PRIMARY KEY)");
403+ session().execute("CREATE TABLE \"Test\".\"Foo\" (i int PRIMARY KEY)");
402404
403- PreparedStatement ps = session.prepare("INSERT INTO \"Test\".\"Foo\" (i) VALUES (?)");
405+ PreparedStatement ps = session().prepare("INSERT INTO \"Test\".\"Foo\" (i) VALUES (?)");
404406 BoundStatement bs = ps.bind(1);
405407 assertThat(bs.getRoutingKey(ProtocolVersion.NEWEST_SUPPORTED, CodecRegistry.DEFAULT_INSTANCE)).isNotNull();
406408 }
@@ -408,15 +410,15 @@
408410 @Test(groups = "short", expectedExceptions = InvalidQueryException.class)
409411 public void should_fail_when_prepared_on_another_cluster() throws Exception {
410412 Cluster otherCluster = Cluster.builder()
411- .addContactPointsWithPorts(getInitialContactPoints())
412- .withPort(ccm.getBinaryPort())
413+ .addContactPoints(getContactPoints())
414+ .withPort(ccm().getBinaryPort())
413415 .build();
414416 try {
415417 PreparedStatement pst = otherCluster.connect().prepare("select * from system.peers where inet = ?");
416418 BoundStatement bs = pst.bind().setInet(0, InetAddress.getByName("localhost"));
417419
418420 // We expect that the error gets detected without a roundtrip to the server, so use executeAsync
419- session.executeAsync(bs);
421+ session().executeAsync(bs);
420422 } finally {
421423 otherCluster.close();
422424 }
@@ -434,11 +436,11 @@
434436 */
435437 @Test(groups = "short")
436438 public void should_not_allow_unbound_value_on_bound_statement_when_protocol_lesser_than_v4() {
437- Cluster cluster = Cluster.builder()
438- .addContactPointsWithPorts(getInitialContactPoints())
439- .withPort(ccm.getBinaryPort())
439+ Cluster cluster = register(Cluster.builder()
440+ .addContactPoints(getContactPoints())
441+ .withPort(ccm().getBinaryPort())
440442 .withProtocolVersion(TestUtils.getDesiredProtocolVersion(ProtocolVersion.V3))
441- .build();
443+ .build());
442444 Session session = cluster.connect();
443445 try {
444446 PreparedStatement ps = session.prepare("INSERT INTO " + keyspace + "." + SIMPLE_TABLE + " (k, i) VALUES (?, ?)");
@@ -448,9 +450,6 @@
448450 fail("Should not have executed statement with UNSET values in protocol V3");
449451 } catch (IllegalStateException e) {
450452 assertThat(e.getMessage()).contains("Unset value at index 1");
451- } finally {
452- session.close();
453- cluster.close();
454453 }
455454 }
456455
@@ -467,11 +466,11 @@
467466 @Test(groups = "short")
468467 @CassandraVersion(major = 2.0)
469468 public void should_not_allow_unbound_value_on_batch_statement_when_protocol_lesser_than_v4() {
470- Cluster cluster = Cluster.builder()
471- .addContactPointsWithPorts(getInitialContactPoints())
472- .withPort(ccm.getBinaryPort())
469+ Cluster cluster = register(Cluster.builder()
470+ .addContactPoints(getContactPoints())
471+ .withPort(ccm().getBinaryPort())
473472 .withProtocolVersion(TestUtils.getDesiredProtocolVersion(ProtocolVersion.V3))
474- .build();
473+ .build());
475474 Session session = cluster.connect();
476475 try {
477476 PreparedStatement ps = session.prepare("INSERT INTO " + keyspace + "." + SIMPLE_TABLE + " (k, i) VALUES (?, ?)");
@@ -482,9 +481,6 @@
482481 fail("Should not have executed statement with UNSET values in protocol V3");
483482 } catch (IllegalStateException e) {
484483 assertThat(e.getMessage()).contains("Unset value at index 1");
485- } finally {
486- session.close();
487- cluster.close();
488484 }
489485 }
490486
@@ -500,18 +496,18 @@
500496 @Test(groups = "short")
501497 @CassandraVersion(major = 2.2)
502498 public void should_not_create_tombstone_when_unbound_value_on_bound_statement_and_protocol_v4() {
503- PreparedStatement prepared = session.prepare("INSERT INTO " + SIMPLE_TABLE + " (k, i) VALUES (?, ?)");
499+ PreparedStatement prepared = session().prepare("INSERT INTO " + SIMPLE_TABLE + " (k, i) VALUES (?, ?)");
504500 BoundStatement st1 = prepared.bind();
505501 st1.setString(0, "foo");
506502 st1.setInt(1, 1234);
507- session.execute(st1);
503+ session().execute(st1);
508504 BoundStatement st2 = prepared.bind();
509505 st2.setString(0, "foo");
510506 // i is UNSET
511- session.execute(st2);
507+ session().execute(st2);
512508 Statement st3 = new SimpleStatement("SELECT i from " + SIMPLE_TABLE + " where k = 'foo'");
513509 st3.enableTracing();
514- ResultSet rows = session.execute(st3);
510+ ResultSet rows = session().execute(st3);
515511 assertThat(rows.one().getInt("i")).isEqualTo(1234);
516512 // sleep 10 seconds to make sure the trace will be complete
517513 Uninterruptibles.sleepUninterruptibly(10, TimeUnit.SECONDS);
@@ -530,16 +526,16 @@
530526 @Test(groups = "short")
531527 @CassandraVersion(major = 2.2)
532528 public void should_unset_value_by_index() {
533- PreparedStatement prepared = session.prepare("INSERT INTO " + SIMPLE_TABLE + " (k, i) VALUES (?, ?)");
529+ PreparedStatement prepared = session().prepare("INSERT INTO " + SIMPLE_TABLE + " (k, i) VALUES (?, ?)");
534530 BoundStatement bound = prepared.bind();
535531 bound.setString(0, "foo");
536532 bound.setInt(1, 1234);
537533
538534 bound.unset(1);
539535 assertThat(bound.isSet(1)).isFalse();
540- session.execute(bound);
536+ session().execute(bound);
541537
542- ResultSet rows = session.execute(
538+ ResultSet rows = session().execute(
543539 new SimpleStatement("SELECT i from " + SIMPLE_TABLE + " where k = 'foo'")
544540 .enableTracing());
545541
@@ -561,16 +557,16 @@
561557 @Test(groups = "short")
562558 @CassandraVersion(major = 2.2)
563559 public void should_unset_value_by_name() {
564- PreparedStatement prepared = session.prepare("INSERT INTO " + SIMPLE_TABLE + " (k, i) VALUES (:k, :i)");
560+ PreparedStatement prepared = session().prepare("INSERT INTO " + SIMPLE_TABLE + " (k, i) VALUES (:k, :i)");
565561 BoundStatement bound = prepared.bind();
566562 bound.setString("k", "foo");
567563 bound.setInt("i", 1234);
568564
569565 bound.unset("i");
570566 assertThat(bound.isSet("i")).isFalse();
571- session.execute(bound);
567+ session().execute(bound);
572568
573- ResultSet rows = session.execute(
569+ ResultSet rows = session().execute(
574570 new SimpleStatement("SELECT i from " + SIMPLE_TABLE + " where k = 'foo'")
575571 .enableTracing());
576572
@@ -593,18 +589,18 @@
593589 @Test(groups = "short")
594590 @CassandraVersion(major = 2.2)
595591 public void should_not_create_tombstone_when_unbound_value_on_batch_statement_and_protocol_v4() {
596- PreparedStatement prepared = session.prepare("INSERT INTO " + SIMPLE_TABLE + " (k, i) VALUES (?, ?)");
592+ PreparedStatement prepared = session().prepare("INSERT INTO " + SIMPLE_TABLE + " (k, i) VALUES (?, ?)");
597593 BoundStatement st1 = prepared.bind();
598594 st1.setString(0, "foo");
599595 st1.setInt(1, 1234);
600- session.execute(new BatchStatement().add(st1));
596+ session().execute(new BatchStatement().add(st1));
601597 BoundStatement st2 = prepared.bind();
602598 st2.setString(0, "foo");
603599 // i is UNSET
604- session.execute(new BatchStatement().add(st2));
600+ session().execute(new BatchStatement().add(st2));
605601 Statement st3 = new SimpleStatement("SELECT i from " + SIMPLE_TABLE + " where k = 'foo'");
606602 st3.enableTracing();
607- ResultSet rows = session.execute(st3);
603+ ResultSet rows = session().execute(st3);
608604 assertThat(rows.one().getInt("i")).isEqualTo(1234);
609605 // sleep 10 seconds to make sure the trace will be complete
610606 Uninterruptibles.sleepUninterruptibly(10, TimeUnit.SECONDS);
@@ -621,14 +617,14 @@
621617 */
622618 @Test(groups = "long")
623619 public void should_create_tombstone_when_null_value_on_bound_statement() {
624- PreparedStatement prepared = session.prepare("INSERT INTO " + SIMPLE_TABLE + " (k, i) VALUES (?, ?)");
620+ PreparedStatement prepared = session().prepare("INSERT INTO " + SIMPLE_TABLE + " (k, i) VALUES (?, ?)");
625621 BoundStatement st1 = prepared.bind();
626622 st1.setString(0, "foo");
627623 st1.setToNull(1);
628- session.execute(st1);
624+ session().execute(st1);
629625 Statement st2 = new SimpleStatement("SELECT i from " + SIMPLE_TABLE + " where k = 'foo'");
630626 st2.enableTracing();
631- ResultSet rows = session.execute(st2);
627+ ResultSet rows = session().execute(st2);
632628 assertThat(rows.one().isNull(0)).isTrue();
633629 // sleep 10 seconds to make sure the trace will be complete
634630 Uninterruptibles.sleepUninterruptibly(10, TimeUnit.SECONDS);
@@ -646,14 +642,14 @@
646642 @Test(groups = "short")
647643 @CassandraVersion(major = 2.0)
648644 public void should_create_tombstone_when_null_value_on_batch_statement() {
649- PreparedStatement prepared = session.prepare("INSERT INTO " + SIMPLE_TABLE + " (k, i) VALUES (?, ?)");
645+ PreparedStatement prepared = session().prepare("INSERT INTO " + SIMPLE_TABLE + " (k, i) VALUES (?, ?)");
650646 BoundStatement st1 = prepared.bind();
651647 st1.setString(0, "foo");
652648 st1.setToNull(1);
653- session.execute(new BatchStatement().add(st1));
649+ session().execute(new BatchStatement().add(st1));
654650 Statement st2 = new SimpleStatement("SELECT i from " + SIMPLE_TABLE + " where k = 'foo'");
655651 st2.enableTracing();
656- ResultSet rows = session.execute(st2);
652+ ResultSet rows = session().execute(st2);
657653 assertThat(rows.one().isNull(0)).isTrue();
658654 // sleep 10 seconds to make sure the trace will be complete
659655 Uninterruptibles.sleepUninterruptibly(10, TimeUnit.SECONDS);
@@ -671,7 +667,7 @@
671667
672668 @Test(groups = "short")
673669 public void should_propagate_idempotence_in_statements() {
674- session.execute(String.format("CREATE TABLE %s.idempotencetest (i int PRIMARY KEY)", keyspace));
670+ session().execute(String.format("CREATE TABLE %s.idempotencetest (i int PRIMARY KEY)", keyspace));
675671
676672 SimpleStatement statement;
677673 PreparedStatement prepared;
@@ -679,21 +675,21 @@
679675
680676 statement = new SimpleStatement(String.format("SELECT * FROM %s.idempotencetest WHERE i = ?", keyspace));
681677
682- prepared = session.prepare(statement);
678+ prepared = session().prepare(statement);
683679 bound = prepared.bind(1);
684680
685681 assertThat(prepared.isIdempotent()).isNull();
686682 assertThat(bound.isIdempotent()).isNull();
687683
688684 statement.setIdempotent(true);
689- prepared = session.prepare(statement);
685+ prepared = session().prepare(statement);
690686 bound = prepared.bind(1);
691687
692688 assertThat(prepared.isIdempotent()).isTrue();
693689 assertThat(bound.isIdempotent()).isTrue();
694690
695691 statement.setIdempotent(false);
696- prepared = session.prepare(statement);
692+ prepared = session().prepare(statement);
697693 bound = prepared.bind(1);
698694
699695 assertThat(prepared.isIdempotent()).isFalse();
modified driver-core/src/test/java/com/datastax/driver/core/QueryLoggerTest.java +72 −72
@@ -123,8 +123,8 @@
123123
124124 @AfterMethod(groups = {"short", "unit"}, alwaysRun = true)
125125 public void unregisterQueryLogger() {
126- if (cluster != null && queryLogger != null) {
127- cluster.unregister(queryLogger);
126+ if (cluster() != null && queryLogger != null) {
127+ cluster().unregister(queryLogger);
128128 }
129129 }
130130
@@ -137,9 +137,9 @@
137137 queryLogger = QueryLogger.builder()
138138 .withConstantThreshold(Long.MAX_VALUE)
139139 .build();
140- cluster.register(queryLogger);
140+ cluster().register(queryLogger);
141141 String query = "SELECT c_text FROM test WHERE pk = 42";
142- session.execute(query);
142+ session().execute(query);
143143 // then
144144 String line = normalAppender.waitAndGet(10000);
145145 assertThat(line)
@@ -156,11 +156,11 @@
156156 queryLogger = QueryLogger.builder()
157157 .withConstantThreshold(Long.MAX_VALUE)
158158 .build();
159- cluster.register(queryLogger);
159+ cluster().register(queryLogger);
160160 String query = "SELECT * FROM test where pk = ?";
161- PreparedStatement ps = session.prepare(query);
161+ PreparedStatement ps = session().prepare(query);
162162 BoundStatement bs = ps.bind(42);
163- session.execute(bs);
163+ session().execute(bs);
164164 // then
165165 String line = normalAppender.waitAndGet(10000);
166166 assertThat(line)
@@ -179,16 +179,16 @@
179179 .withConstantThreshold(Long.MAX_VALUE)
180180 .withMaxQueryStringLength(Integer.MAX_VALUE)
181181 .build();
182- cluster.register(queryLogger);
182+ cluster().register(queryLogger);
183183 // when
184184 String query1 = "INSERT INTO test (pk) VALUES (?)";
185185 String query2 = "UPDATE test SET c_int = ? WHERE pk = 42";
186- PreparedStatement ps1 = session.prepare(query1);
187- PreparedStatement ps2 = session.prepare(query2);
186+ PreparedStatement ps1 = session().prepare(query1);
187+ PreparedStatement ps2 = session().prepare(query2);
188188 BatchStatement batch = new BatchStatement();
189189 batch.add(ps1.bind(42));
190190 batch.add(ps2.bind(1234));
191- session.execute(batch);
191+ session().execute(batch);
192192 // then
193193 String line = normalAppender.waitAndGet(10000);
194194 assertThat(line)
@@ -210,16 +210,16 @@
210210 .withConstantThreshold(Long.MAX_VALUE)
211211 .withMaxQueryStringLength(Integer.MAX_VALUE)
212212 .build();
213- cluster.register(queryLogger);
213+ cluster().register(queryLogger);
214214 // when
215215 String query1 = "INSERT INTO test (pk) VALUES (?)";
216216 String query2 = "UPDATE test SET c_int = ? WHERE pk = 42";
217- PreparedStatement ps1 = session.prepare(query1);
218- PreparedStatement ps2 = session.prepare(query2);
217+ PreparedStatement ps1 = session().prepare(query1);
218+ PreparedStatement ps2 = session().prepare(query2);
219219 BatchStatement batch = new BatchStatement(UNLOGGED);
220220 batch.add(ps1.bind(42));
221221 batch.add(ps2.bind(1234));
222- session.execute(batch);
222+ session().execute(batch);
223223 // then
224224 String line = normalAppender.waitAndGet(10000);
225225 assertThat(line)
@@ -236,7 +236,7 @@
236236 @CassandraVersion(major = 2.0)
237237 public void should_log_counter_batch_statements() throws Exception {
238238 // Create a special table for testing with counters.
239- session.execute(
239+ session().execute(
240240 "CREATE TABLE IF NOT EXISTS counter_test (pk int PRIMARY KEY, c_count COUNTER, c_count2 COUNTER)");
241241
242242 // given
@@ -245,16 +245,16 @@
245245 .withConstantThreshold(Long.MAX_VALUE)
246246 .withMaxQueryStringLength(Integer.MAX_VALUE)
247247 .build();
248- cluster.register(queryLogger);
248+ cluster().register(queryLogger);
249249 // when
250250 String query1 = "UPDATE counter_test SET c_count = c_count + ? WHERE pk = 42";
251251 String query2 = "UPDATE counter_test SET c_count2 = c_count2 + ? WHERE pk = 42";
252- PreparedStatement ps1 = session.prepare(query1);
253- PreparedStatement ps2 = session.prepare(query2);
252+ PreparedStatement ps1 = session().prepare(query1);
253+ PreparedStatement ps2 = session().prepare(query2);
254254 BatchStatement batch = new BatchStatement(COUNTER);
255255 batch.add(ps1.bind(1234L));
256256 batch.add(ps2.bind(5678L));
257- session.execute(batch);
257+ session().execute(batch);
258258 // then
259259 String line = normalAppender.waitAndGet(10000);
260260 assertThat(line)
@@ -356,12 +356,12 @@
356356 .withConstantThreshold(Long.MAX_VALUE)
357357 .withMaxQueryStringLength(Integer.MAX_VALUE)
358358 .build();
359- cluster.register(queryLogger);
359+ cluster().register(queryLogger);
360360 // when
361361 String query = "SELECT * FROM test where pk = ?";
362- PreparedStatement ps = session.prepare(query);
362+ PreparedStatement ps = session().prepare(query);
363363 BoundStatement bs = ps.bind(42);
364- session.execute(bs);
364+ session().execute(bs);
365365 // then
366366 String line = normalAppender.waitAndGet(10000);
367367 assertThat(line)
@@ -384,14 +384,14 @@
384384 .withConstantThreshold(Long.MAX_VALUE)
385385 .withMaxQueryStringLength(Integer.MAX_VALUE)
386386 .build();
387- cluster.register(queryLogger);
387+ cluster().register(queryLogger);
388388 // when
389389 String query = "UPDATE test SET c_text = :param1 WHERE pk = :param2";
390- PreparedStatement ps = session.prepare(query);
390+ PreparedStatement ps = session().prepare(query);
391391 BoundStatement bs = ps.bind();
392392 bs.setString("param1", "foo");
393393 bs.setInt("param2", 42);
394- session.execute(bs);
394+ session().execute(bs);
395395 // then
396396 String line = normalAppender.waitAndGet(10000);
397397 assertThat(line)
@@ -407,14 +407,14 @@
407407 // given
408408 normal.setLevel(TRACE);
409409 queryLogger = QueryLogger.builder().build();
410- cluster.register(queryLogger);
410+ cluster().register(queryLogger);
411411 // when
412412 String query = "UPDATE test SET c_text = ? WHERE pk = ?";
413- PreparedStatement ps = session.prepare(query);
413+ PreparedStatement ps = session().prepare(query);
414414 BoundStatement bs = ps.bind();
415415 bs.setString("c_text", "foo");
416416 bs.setInt("pk", 42);
417- session.execute(bs);
417+ session().execute(bs);
418418 // then
419419 String line = normalAppender.waitAndGet(10000);
420420 assertThat(line)
@@ -430,14 +430,14 @@
430430 // given
431431 normal.setLevel(TRACE);
432432 queryLogger = QueryLogger.builder().build();
433- cluster.register(queryLogger);
433+ cluster().register(queryLogger);
434434 // when
435435 String query = "UPDATE test SET c_text = ? WHERE pk = ?";
436- PreparedStatement ps = session.prepare(query);
436+ PreparedStatement ps = session().prepare(query);
437437 BoundStatement bs = ps.bind();
438438 bs.setString("c_text", null);
439439 bs.setInt("pk", 42);
440- session.execute(bs);
440+ session().execute(bs);
441441 // then
442442 String line = normalAppender.waitAndGet(10000);
443443 assertThat(line)
@@ -454,13 +454,13 @@
454454 // given
455455 normal.setLevel(TRACE);
456456 queryLogger = QueryLogger.builder().build();
457- cluster.register(queryLogger);
457+ cluster().register(queryLogger);
458458 // when
459459 String query = "UPDATE test SET c_text = ? WHERE pk = ?";
460- PreparedStatement ps = session.prepare(query);
460+ PreparedStatement ps = session().prepare(query);
461461 BoundStatement bs = ps.bind();
462462 bs.setInt("pk", 42);
463- session.execute(bs);
463+ session().execute(bs);
464464 // then
465465 String line = normalAppender.waitAndGet(10000);
466466 assertThat(line)
@@ -477,14 +477,14 @@
477477 // given
478478 normal.setLevel(TRACE);
479479 queryLogger = QueryLogger.builder().build();
480- cluster.register(queryLogger);
480+ cluster().register(queryLogger);
481481 // when
482482 String query1 = "UPDATE test SET c_text = ? WHERE pk = ?";
483483 String query2 = "UPDATE test SET c_int = ? WHERE pk = ?";
484484 BatchStatement batch = new BatchStatement();
485- batch.add(session.prepare(query1).bind("foo", 42));
486- batch.add(session.prepare(query2).bind(12345, 43));
487- session.execute(batch);
485+ batch.add(session().prepare(query1).bind("foo", 42));
486+ batch.add(session().prepare(query2).bind(12345, 43));
487+ session().execute(batch);
488488 // then
489489 String line = normalAppender.waitAndGet(10000);
490490 assertThat(line)
@@ -506,19 +506,19 @@
506506 queryLogger = QueryLogger.builder()
507507 .withMaxParameterValueLength(Integer.MAX_VALUE)
508508 .build();
509- cluster.register(queryLogger);
509+ cluster().register(queryLogger);
510510 // when
511511 String query = "UPDATE test SET " + assignments + " WHERE pk = 42";
512- PreparedStatement ps = session.prepare(query);
512+ PreparedStatement ps = session().prepare(query);
513513 BoundStatement bs = ps.bind(values.toArray());
514- session.execute(bs);
514+ session().execute(bs);
515515 // then
516516 String line = normalAppender.waitAndGet(10000);
517517 assertThat(line)
518518 .contains("Query completed normally")
519519 .contains(ipOfNode(1))
520520 .contains(query);
521- CodecRegistry codecRegistry = cluster.getConfiguration().getCodecRegistry();
521+ CodecRegistry codecRegistry = cluster().getConfiguration().getCodecRegistry();
522522 for (DataType type : dataTypes) {
523523 TypeCodec<Object> codec = codecRegistry.codecFor(type);
524524 assertThat(line).contains(codec.format(getFixedValue(type)));
@@ -534,10 +534,10 @@
534534 queryLogger = QueryLogger.builder()
535535 .withMaxQueryStringLength(5)
536536 .build();
537- cluster.register(queryLogger);
537+ cluster().register(queryLogger);
538538 // when
539539 String query = "SELECT * FROM test WHERE pk = 42";
540- session.execute(query);
540+ session().execute(query);
541541 // then
542542 String line = normalAppender.waitAndGet(10000);
543543 assertThat(line)
@@ -555,14 +555,14 @@
555555 queryLogger = QueryLogger.builder()
556556 .withMaxQueryStringLength(5)
557557 .build();
558- cluster.register(queryLogger);
558+ cluster().register(queryLogger);
559559 // when
560560 String query1 = "UPDATE test SET c_text = ? WHERE pk = ?";
561561 String query2 = "UPDATE test SET c_int = ? WHERE pk = ?";
562562 BatchStatement batch = new BatchStatement();
563- batch.add(session.prepare(query1).bind("foo", 42));
564- batch.add(session.prepare(query2).bind(12345, 43));
565- session.execute(batch);
563+ batch.add(session().prepare(query1).bind("foo", 42));
564+ batch.add(session().prepare(query2).bind(12345, 43));
565+ session().execute(batch);
566566 // then
567567 String line = normalAppender.waitAndGet(10000);
568568 assertThat(line)
@@ -581,10 +581,10 @@
581581 queryLogger = QueryLogger.builder()
582582 .withMaxQueryStringLength(-1)
583583 .build();
584- cluster.register(queryLogger);
584+ cluster().register(queryLogger);
585585 // when
586586 String query = "SELECT * FROM test WHERE pk = 42";
587- session.execute(query);
587+ session().execute(query);
588588 // then
589589 String line = normalAppender.waitAndGet(10000);
590590 assertThat(line)
@@ -602,14 +602,14 @@
602602 queryLogger = QueryLogger.builder()
603603 .withMaxParameterValueLength(5)
604604 .build();
605- cluster.register(queryLogger);
605+ cluster().register(queryLogger);
606606 // when
607607 String query = "UPDATE test SET c_int = ? WHERE pk = ?";
608- PreparedStatement ps = session.prepare(query);
608+ PreparedStatement ps = session().prepare(query);
609609 BoundStatement bs = ps.bind();
610610 bs.setInt("c_int", 123456);
611611 bs.setInt("pk", 42);
612- session.execute(bs);
612+ session().execute(bs);
613613 // then
614614 String line = normalAppender.waitAndGet(10000);
615615 assertThat(line)
@@ -626,14 +626,14 @@
626626 queryLogger = QueryLogger.builder()
627627 .withMaxParameterValueLength(6)
628628 .build();
629- cluster.register(queryLogger);
629+ cluster().register(queryLogger);
630630 // when
631631 String query = "UPDATE test SET c_blob = ? WHERE pk = ?";
632- PreparedStatement ps = session.prepare(query);
632+ PreparedStatement ps = session().prepare(query);
633633 BoundStatement bs = ps.bind();
634634 bs.setBytes("c_blob", ByteBuffer.wrap(Bytes.toArray(Lists.newArrayList(1, 2, 3))));
635635 bs.setInt("pk", 42);
636- session.execute(bs);
636+ session().execute(bs);
637637 // then
638638 String line = normalAppender.waitAndGet(10000);
639639 assertThat(line)
@@ -650,14 +650,14 @@
650650 queryLogger = QueryLogger.builder()
651651 .withMaxParameterValueLength(-1)
652652 .build();
653- cluster.register(queryLogger);
653+ cluster().register(queryLogger);
654654 // when
655655 String query = "UPDATE test SET c_int = ? WHERE pk = ?";
656- PreparedStatement ps = session.prepare(query);
656+ PreparedStatement ps = session().prepare(query);
657657 BoundStatement bs = ps.bind();
658658 bs.setInt("c_int", 123456);
659659 bs.setInt("pk", 42);
660- session.execute(bs);
660+ session().execute(bs);
661661 // then
662662 String line = normalAppender.waitAndGet(10000);
663663 assertThat(line)
@@ -674,14 +674,14 @@
674674 queryLogger = QueryLogger.builder()
675675 .withMaxLoggedParameters(1)
676676 .build();
677- cluster.register(queryLogger);
677+ cluster().register(queryLogger);
678678 // when
679679 String query = "UPDATE test SET c_int = ? WHERE pk = ?";
680- PreparedStatement ps = session.prepare(query);
680+ PreparedStatement ps = session().prepare(query);
681681 BoundStatement bs = ps.bind();
682682 bs.setInt("c_int", 123456);
683683 bs.setInt("pk", 42);
684- session.execute(bs);
684+ session().execute(bs);
685685 // then
686686 String line = normalAppender.waitAndGet(10000);
687687 assertThat(line)
@@ -700,14 +700,14 @@
700700 queryLogger = QueryLogger.builder()
701701 .withMaxLoggedParameters(1)
702702 .build();
703- cluster.register(queryLogger);
703+ cluster().register(queryLogger);
704704 // when
705705 String query1 = "UPDATE test SET c_text = ? WHERE pk = ?";
706706 String query2 = "UPDATE test SET c_int = ? WHERE pk = ?";
707707 BatchStatement batch = new BatchStatement();
708- batch.add(session.prepare(query1).bind("foo", 42));
709- batch.add(session.prepare(query2).bind(12345, 43));
710- session.execute(batch);
708+ batch.add(session().prepare(query1).bind("foo", 42));
709+ batch.add(session().prepare(query2).bind(12345, 43));
710+ session().execute(batch);
711711 // then
712712 String line = normalAppender.waitAndGet(10000);
713713 assertThat(line)
@@ -729,14 +729,14 @@
729729 queryLogger = QueryLogger.builder()
730730 .withMaxLoggedParameters(-1)
731731 .build();
732- cluster.register(queryLogger);
732+ cluster().register(queryLogger);
733733 // when
734734 String query = "UPDATE test SET c_int = ? WHERE pk = ?";
735- PreparedStatement ps = session.prepare(query);
735+ PreparedStatement ps = session().prepare(query);
736736 BoundStatement bs = ps.bind();
737737 bs.setInt("c_int", 123456);
738738 bs.setInt("pk", 42);
739- session.execute(bs);
739+ session().execute(bs);
740740 // then
741741 String line = normalAppender.waitAndGet(10000);
742742 assertThat(line)
@@ -747,8 +747,8 @@
747747 }
748748
749749 @Override
750- public List<String> createTestFixtures() {
751- return Lists.newArrayList("CREATE TABLE test (pk int PRIMARY KEY, " + definitions + ")");
750+ public void onTestContextInitialized() {
751+ execute("CREATE TABLE test (pk int PRIMARY KEY, " + definitions + ")");
752752 }
753753
754754 }
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+ .addContactPoints(getContactPoints().get(0))
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+ .addContactPoints(getContactPoints().get(0))
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+ .addContactPoints(getContactPoints().get(0))
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", dataProvider = "sslImplementation", dataProviderClass = SSLTestBase.class)
9494 public void should_reconnect_with_ssl_on_node_up(SslImplementation sslImplementation) throws Exception {
9595 Cluster cluster = register(Cluster.builder()
96- .addContactPointsWithPorts(this.getInitialContactPoints())
97- .withPort(ccm.getBinaryPort())
96+ .addContactPoints(this.getContactPoints())
97+ .withPort(ccm().getBinaryPort())
9898 .withSSL(getSSLOptions(sslImplementation, true, true))
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
@@ -55,8 +55,8 @@
5555 */
5656 protected void connectWithSSLOptions(SSLOptions sslOptions) throws Exception {
5757 Cluster cluster = register(Cluster.builder()
58- .addContactPointsWithPorts(this.getInitialContactPoints())
59- .withPort(ccm.getBinaryPort())
58+ .addContactPoints(getContactPoints())
59+ .withPort(ccm().getBinaryPort())
6060 .withSSL(sslOptions)
6161 .build());
6262 cluster.connect();
@@ -73,8 +73,8 @@
7373 */
7474 protected void connectWithSSL() throws Exception {
7575 Cluster cluster = register(Cluster.builder()
76- .addContactPointsWithPorts(this.getInitialContactPoints())
77- .withPort(ccm.getBinaryPort())
76+ .addContactPoints(getContactPoints())
77+ .withPort(ccm().getBinaryPort())
7878 .withSSL()
7979 .build());
8080 cluster.connect();
modified driver-core/src/test/java/com/datastax/driver/core/ScassandraTestBase.java +5 −22
@@ -19,15 +19,12 @@
1919 import org.scassandra.http.client.ActivityClient;
2020 import org.scassandra.http.client.CurrentClient;
2121 import org.scassandra.http.client.PrimingClient;
22-import org.slf4j.Logger;
23-import org.slf4j.LoggerFactory;
2422 import org.testng.annotations.AfterClass;
2523 import org.testng.annotations.AfterMethod;
2624 import org.testng.annotations.BeforeClass;
2725 import org.testng.annotations.BeforeMethod;
2826
2927 import java.net.InetSocketAddress;
30-import java.util.Collections;
3128
3229 import static org.assertj.core.api.Assertions.fail;
3330
@@ -41,8 +38,6 @@
4138 */
4239 public abstract class ScassandraTestBase {
4340
44- private static final Logger logger = LoggerFactory.getLogger(ScassandraTestBase.class);
45-
4641 protected Scassandra scassandra;
4742
4843 protected InetSocketAddress hostAddress;
@@ -80,28 +75,16 @@
8075 }
8176
8277 protected Cluster.Builder createClusterBuilder() {
83- Cluster.Builder builder = Cluster.builder()
78+ return Cluster.builder()
79+ .withPort(scassandra.getBinaryPort())
80+ .addContactPoints(hostAddress.getAddress())
8481 .withPort(scassandra.getBinaryPort())
85- .addContactPoints(Collections.singletonList(hostAddress.getAddress()))
8682 // Scassandra does not support V3 yet, and V4 may cause the server to crash
87- .withProtocolVersion(ProtocolVersion.V2)
83+ .withProtocolVersion(TestUtils.getDesiredProtocolVersion(ProtocolVersion.V2))
8884 .withPoolingOptions(new PoolingOptions()
8985 .setCoreConnectionsPerHost(HostDistance.LOCAL, 1)
9086 .setMaxConnectionsPerHost(HostDistance.LOCAL, 1)
91- .setHeartbeatIntervalSeconds(0))
92- .withPort(scassandra.getBinaryPort());
93- return builder;
94- }
95-
96- /**
97- * An overrideable method for building on to the Cluster.Builder used for this
98- * class.
99- *
100- * @param builder
101- * @return
102- */
103- protected Cluster.Builder configure(Cluster.Builder builder) {
104- return builder;
87+ .setHeartbeatIntervalSeconds(0));
10588 }
10689
10790 protected Host retrieveSingleHost(Cluster cluster) {
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+ .addContactPoints(getContactPoints().get(0))
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+ .addContactPoints(getContactPoints().get(1))
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)
@@ -512,7 +515,8 @@
512515 @Test(groups = "short", expectedExceptions = IllegalStateException.class)
513516 public void should_throw_illegal_state_exception_on_newToken_with_metadata_disabled() {
514517 Cluster cluster = Cluster.builder()
515- .addContactPointsWithPorts(getInitialContactPoints())
518+ .addContactPoints(getContactPoints())
519+ .withPort(ccm().getBinaryPort())
516520 .withQueryOptions(nonDebouncingQueryOptions()
517521 .setMetadataEnabled(false)
518522 ).build();
@@ -536,7 +540,8 @@
536540 @Test(groups = "short", expectedExceptions = IllegalStateException.class)
537541 public void should_throw_illegal_state_exception_on_newTokenRange_with_metadata_disabled() {
538542 Cluster cluster = Cluster.builder()
539- .addContactPointsWithPorts(getInitialContactPoints())
543+ .addContactPoints(getContactPoints())
544+ .withPort(ccm().getBinaryPort())
540545 .withQueryOptions(nonDebouncingQueryOptions()
541546 .setMetadataEnabled(false)
542547 ).build();
modified driver-core/src/test/java/com/datastax/driver/core/SchemaRefreshDebouncerTest.java +21 −25
@@ -54,10 +54,11 @@
5454 queryOptions.setRefreshSchemaIntervalMillis(DEBOUNCE_TIME);
5555 queryOptions.setMaxPendingRefreshSchemaRequests(5);
5656 // Create a separate cluster that will receive the schema events on its control connection.
57- cluster2 = Cluster.builder()
58- .addContactPointsWithPorts(getInitialContactPoints())
57+ cluster2 = register(Cluster.builder()
58+ .addContactPoints(getContactPoints())
59+ .withPort(ccm().getBinaryPort())
5960 .withQueryOptions(queryOptions)
60- .build();
61+ .build());
6162 session2 = cluster2.connect();
6263
6364 // Create a spy of the Cluster's control connection and replace it with the spy.
@@ -72,11 +73,6 @@
7273 reset(controlConnection);
7374 }
7475
75- @AfterMethod(groups = "short")
76- public void beforeMethod() {
77- cluster2.close();
78- }
79-
8076 /**
8177 * Ensures that when a CREATED and UPDATED schema_change events are received on a control
8278 * connection for the same keyspace within {@link QueryOptions#getRefreshSchemaIntervalMillis()}
@@ -88,9 +84,9 @@
8884 */
8985 @Test(groups = "short")
9086 public void should_debounce_and_coalesce_create_and_alter_keyspace_into_refresh_keyspace() throws Exception {
91- String keyspace = "sdaccaak";
92- session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, 1));
93- session.execute(String.format("ALTER KEYSPACE %s WITH DURABLE_WRITES=false", keyspace));
87+ String keyspace = TestUtils.generateIdentifier("ks_");
88+ session().execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, 1));
89+ session().execute(String.format("ALTER KEYSPACE %s WITH DURABLE_WRITES=false", keyspace));
9490
9591 ArgumentCaptor<KeyspaceMetadata> captor = forClass(KeyspaceMetadata.class);
9692 verify(listener, timeout(DEBOUNCE_TIME * 2).only()).onKeyspaceAdded(captor.capture());
@@ -119,17 +115,17 @@
119115 */
120116 @Test(groups = "short")
121117 public void should_debounce_and_coalesce_create_keyspace_and_table_into_refresh_keyspace() throws Exception {
122- String keyspace = "sdacckt";
118+ String keyspace = TestUtils.generateIdentifier("ks_");
123119 String table = "tbl1";
124- session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, 1));
125- session.execute(String.format("CREATE TABLE %s (k text PRIMARY KEY, t text, i int, f float)", keyspace + "." + table));
120+ session().execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, 1));
121+ session().execute(String.format("CREATE TABLE %s (k text PRIMARY KEY, t text, i int, f float)", keyspace + "." + table));
126122
127123 ArgumentCaptor<KeyspaceMetadata> keyspaceCaptor = forClass(KeyspaceMetadata.class);
128124 verify(listener, timeout(DEBOUNCE_TIME * 2).times(1)).onKeyspaceAdded(keyspaceCaptor.capture());
129125 assertThat(keyspaceCaptor.getValue()).hasName(keyspace);
130126
131127 ArgumentCaptor<TableMetadata> tableCaptor = forClass(TableMetadata.class);
132- verify(listener, times(1)).onTableAdded(tableCaptor.capture());
128+ verify(listener, timeout(DEBOUNCE_TIME * 2).times(1)).onTableAdded(tableCaptor.capture());
133129 assertThat(tableCaptor.getValue()).hasName(table);
134130
135131 // Verify the schema refresh was debounced and coalesced when a keyspace event and table event
@@ -154,7 +150,7 @@
154150 */
155151 @Test(groups = "short")
156152 public void should_debounce_and_coalesce_tables_in_same_keyspace_into_refresh_keyspace() throws Exception {
157- String keyspace = "sdactisk";
153+ String keyspace = TestUtils.generateIdentifier("ks_");
158154 session2.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, 1));
159155 // Reset invocations as creating keyspace causes a keyspace refresh.
160156 reset(controlConnection);
@@ -162,7 +158,7 @@
162158
163159 int tableCount = 3;
164160 for (int i = 0; i < tableCount; i++) {
165- session.execute(String.format("CREATE TABLE %s (k text PRIMARY KEY, t text, i int, f float)", keyspace + "." + "tbl" + i));
161+ session().execute(String.format("CREATE TABLE %s (k text PRIMARY KEY, t text, i int, f float)", keyspace + "." + "tbl" + i));
166162 }
167163
168164 verify(listener, timeout(DEBOUNCE_TIME * 3).times(3)).onTableAdded(any(TableMetadata.class));
@@ -194,10 +190,10 @@
194190 */
195191 @Test(groups = "short")
196192 public void should_debounce_and_coalesce_multiple_alter_events_on_same_table_into_refresh_table() throws Exception {
197- if (ccm.getVersion().getMajor() > 2 || ccm.getVersion().getMajor() == 2 && ccm.getVersion().getMinor() > 1)
193+ if (ccm().getVersion().getMajor() > 2 || ccm().getVersion().getMajor() == 2 && ccm().getVersion().getMinor() > 1)
198194 throw new SkipException("Disabled in Cassandra 2.2+ because of CASSANDRA-9996");
199195
200- String keyspace = "sdacmaeost";
196+ String keyspace = TestUtils.generateIdentifier("ks_");
201197 String table = "tbl1";
202198 String comment = "I am changing this table.";
203199 String columnName = "added_column";
@@ -207,8 +203,8 @@
207203 reset(controlConnection);
208204 reset(listener);
209205
210- session.execute(String.format("ALTER TABLE %s.%s WITH comment = '%s'", keyspace, table, comment));
211- session.execute(String.format("ALTER TABLE %s.%s ADD %s int", keyspace, table, columnName));
206+ session().execute(String.format("ALTER TABLE %s.%s WITH comment = '%s'", keyspace, table, comment));
207+ session().execute(String.format("ALTER TABLE %s.%s ADD %s int", keyspace, table, columnName));
212208
213209 ArgumentCaptor<TableMetadata> original = forClass(TableMetadata.class);
214210 ArgumentCaptor<TableMetadata> captor = forClass(TableMetadata.class);
@@ -250,9 +246,9 @@
250246 */
251247 @Test(groups = "short")
252248 public void should_debounce_and_coalesce_multiple_keyspace_creates_into_refresh_entire_schema() throws Exception {
253- String prefix = "sdacmkc";
249+ String prefix = TestUtils.generateIdentifier("ks_");
254250 for (int i = 0; i < 3; i++) {
255- session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, prefix + i, 1));
251+ session().execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, prefix + i, 1));
256252 }
257253
258254 verify(listener, timeout(DEBOUNCE_TIME * 3).times(3)).onKeyspaceAdded(any(KeyspaceMetadata.class));
@@ -276,9 +272,9 @@
276272 */
277273 @Test(groups = "short")
278274 public void should_refresh_when_max_pending_requests_reached() throws Exception {
279- String prefix = "srwmprr";
275+ String prefix = TestUtils.generateIdentifier("ks_");
280276 for (int i = 0; i < 5; i++) {
281- session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, prefix + i, 1));
277+ session().execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, prefix + i, 1));
282278 }
283279
284280 // Event should be processed immediately as we hit our threshold.
modified driver-core/src/test/java/com/datastax/driver/core/SessionLeakTest.java +21 −21
@@ -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,45 +50,45 @@
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);
70- ccm.waitForUp(2);
68+ ccm().add(2);
69+ ccm().start(2);
70+ ccm().waitForUp(2);
7171 assertThat(cluster).host(2).comesUpWithin(2, MINUTES);
7272
7373 assertThat(cluster.manager.sessions.size()).isEqualTo(0);
74- assertOpenConnections(1);
74+ assertOpenConnections(1, cluster);
7575
7676 // ensure a new session gets registered and core connections are established
7777 // there should be corePoolSize more connections to accommodate for the new host.
7878 Session thisSession = cluster.connect();
7979 assertThat(cluster.manager.sessions.size()).isEqualTo(1);
80- assertOpenConnections(1 + (corePoolSize * 2));
80+ assertOpenConnections(1 + (corePoolSize * 2), cluster);
8181
8282 // ensure bootstrapping a node does not create additional connections that won't get cleaned up
8383 thisSession.close();
8484
8585 assertThat(cluster.manager.sessions.size()).isEqualTo(0);
86- assertOpenConnections(1);
86+ assertOpenConnections(1, cluster);
8787 cluster.close();
8888 // Ensure no channels remain open.
8989 channelMonitor.stop();
9090 channelMonitor.report();
91- assertThat(channelMonitor.openChannels(newArrayList(ccm.addressOfNode(1), ccm.addressOfNode(2))).size()).isEqualTo(0);
91+ assertThat(channelMonitor.openChannels(newArrayList(ccm().addressOfNode(1), ccm().addressOfNode(2))).size()).isEqualTo(0);
9292 }
9393
9494 @Test(groups = "short")
@@ -96,16 +96,16 @@
9696 // Checking for JAVA-806
9797 channelMonitor = new SocketChannelMonitor();
9898 channelMonitor.reportAtFixedInterval(1, TimeUnit.SECONDS);
99- cluster = register(Cluster.builder()
100- .addContactPoints(ccm.addressOfNode(1).getAddress())
101- .withPort(ccm.getBinaryPort())
99+ Cluster cluster = register(Cluster.builder()
100+ .addContactPoints(getContactPoints().get(0))
101+ .withPort(ccm().getBinaryPort())
102102 .withNettyOptions(channelMonitor.nettyOptions())
103103 .build());
104104 cluster.init();
105105 assertThat(cluster.manager.sessions.size()).isEqualTo(0);
106106 try {
107107 // Should be 1 control connection after initialization.
108- assertOpenConnections(1);
108+ assertOpenConnections(1, cluster);
109109 cluster.connect("wrong_keyspace");
110110 fail("Should not have connected to a wrong keyspace");
111111 } catch (InvalidQueryException e) {
@@ -116,11 +116,11 @@
116116 // Ensure no channels remain open.
117117 channelMonitor.stop();
118118 channelMonitor.report();
119- assertThat(channelMonitor.openChannels(ccm.addressOfNode(1), ccm.addressOfNode(2)).size()).isEqualTo(0);
119+ assertThat(channelMonitor.openChannels(ccm().addressOfNode(1), ccm().addressOfNode(2)).size()).isEqualTo(0);
120120 }
121121
122- private void assertOpenConnections(int expected) {
123- assertThat((cluster.getMetrics().getOpenConnections().getValue())).isEqualTo(expected);
124- assertThat(channelMonitor.openChannels(ccm.addressOfNode(1), ccm.addressOfNode(2)).size()).isEqualTo(expected);
122+ private void assertOpenConnections(int expected, Cluster cluster) {
123+ assertThat(cluster.getMetrics().getOpenConnections().getValue()).isEqualTo(expected);
124+ assertThat(channelMonitor.openChannels(ccm().addressOfNode(1), ccm().addressOfNode(2)).size()).isEqualTo(expected);
125125 }
126126 }
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("CREATE TABLE %s (k text PRIMARY KEY, t text, i int, f float)", TABLE1),
42+ public void onTestContextInitialized() {
43+ execute(String.format("CREATE TABLE %s (k text PRIMARY KEY, t text, i int, f float)", TABLE1),
4644 String.format("CREATE TABLE %s (k text PRIMARY KEY, t text, i int, f float)", TABLE2),
4745 String.format("CREATE TABLE %s (k text PRIMARY KEY, t text, i int, f float)", 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, "INSERT INTO %s (k, t, i, f) VALUES ('%s', '%s', %d, %f)", TABLE1, key, "foo", 42, 24.03f));
53+ ResultSet rs = session().execute(String.format(Locale.US, "INSERT INTO %s (k, t, i, f) VALUES ('%s', '%s', %d, %f)", 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, "INSERT INTO %s (k, t, i, f) VALUES ('%s', '%s', %d, %f)", TABLE2, key, "foo", 42, 24.03f));
70+ ResultSet rs = session().execute(String.format(Locale.US, "INSERT INTO %s (k, t, i, f) VALUES ('%s', '%s', %d, %f)", 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/SimpleStatementIntegrationTest.java +9 −11
@@ -19,18 +19,16 @@
1919 import com.datastax.driver.core.exceptions.UnsupportedFeatureException;
2020 import com.datastax.driver.core.utils.CassandraVersion;
2121 import com.google.common.collect.ImmutableMap;
22-import com.google.common.collect.Lists;
2322 import org.testng.SkipException;
2423 import org.testng.annotations.Test;
2524
26-import java.util.Collection;
27-
2825 import static org.assertj.core.api.Assertions.assertThat;
2926
3027 public class SimpleStatementIntegrationTest extends CCMTestsSupport {
28+
3129 @Override
32- public Collection<String> createTestFixtures() {
33- return Lists.newArrayList(
30+ public void onTestContextInitialized() {
31+ execute(
3432 "CREATE TABLE users(id int, id2 int, name text, primary key (id, id2))",
3533 "INSERT INTO users(id, id2, name) VALUES (1, 2, 'test')"
3634 );
@@ -44,7 +42,7 @@
4442 ImmutableMap.<String, Object>of("id", 1, "id2", 2));
4543
4644 // When
47- Row row = session.execute(statement).one();
45+ Row row = session().execute(statement).one();
4846
4947 // Then
5048 assertThat(row).isNotNull();
@@ -59,7 +57,7 @@
5957 ImmutableMap.<String, Object>of("id2", 2));
6058
6159 // When
62- session.execute(statement).one();
60+ session().execute(statement).one();
6361
6462 // Then - The driver does allow this because it doesn't know what parameters are required, but C* should
6563 // throw an InvalidQueryException.
@@ -73,7 +71,7 @@
7371 ImmutableMap.<String, Object>of("id", 2.7, "id2", 2));
7472
7573 // When
76- session.execute(statement).one();
74+ session().execute(statement).one();
7775
7876 // Then - The driver does allow this because it doesn't know the type information, but C* should throw an
7977 // InvalidQueryException.
@@ -81,7 +79,7 @@
8179
8280 public void useNamedValuesWithProtocol(ProtocolVersion version) {
8381 Cluster vCluster = createClusterBuilder()
84- .addContactPointsWithPorts(getInitialContactPoints())
82+ .addContactPoints(getContactPoints())
8583 .withProtocolVersion(version).build();
8684 try {
8785 Session vSession = vCluster.connect(this.keyspace);
@@ -101,7 +99,7 @@
10199 @Test(groups = "short", expectedExceptions = UnsupportedFeatureException.class)
102100 @CassandraVersion(major = 2.0)
103101 public void should_fail_if_query_with_named_values_if_protocol_is_V2() {
104- if (ccm.getVersion().getMajor() >= 3) {
102+ if (ccm().getVersion().getMajor() >= 3) {
105103 throw new SkipException("Skipping since Cassandra 3.0+ does not support protocol v2");
106104 }
107105 useNamedValuesWithProtocol(ProtocolVersion.V2);
@@ -109,7 +107,7 @@
109107
110108 @Test(groups = "short", expectedExceptions = UnsupportedFeatureException.class)
111109 public void should_fail_if_query_with_named_values_if_protocol_is_V1() {
112- if (ccm.getVersion().getMajor() >= 3) {
110+ if (ccm().getVersion().getMajor() >= 3) {
113111 throw new SkipException("Skipping since Cassandra 3.0+ does not support protocol v1");
114112 }
115113 useNamedValuesWithProtocol(ProtocolVersion.V1);
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
@@ -43,10 +43,10 @@
4343 loadBalancingPolicy.customStatementsHandled.set(0);
4444
4545 SimpleStatement s = new SimpleStatement("select * from system.local");
46- session.execute(s);
46+ session().execute(s);
4747 assertThat(loadBalancingPolicy.customStatementsHandled.get()).isEqualTo(0);
4848
49- session.execute(new CustomStatement(s));
49+ session().execute(new CustomStatement(s));
5050 assertThat(loadBalancingPolicy.customStatementsHandled.get()).isEqualTo(1);
5151 }
5252
@@ -55,10 +55,10 @@
5555 speculativeExecutionPolicy.customStatementsHandled.set(0);
5656
5757 SimpleStatement s = new SimpleStatement("select * from system.local");
58- session.execute(s);
58+ session().execute(s);
5959 assertThat(speculativeExecutionPolicy.customStatementsHandled.get()).isEqualTo(0);
6060
61- session.execute(new CustomStatement(s));
61+ session().execute(new CustomStatement(s));
6262 assertThat(speculativeExecutionPolicy.customStatementsHandled.get()).isEqualTo(1);
6363 }
6464
@@ -71,10 +71,10 @@
7171 Statement s = new SimpleStatement("select * from system.local")
7272 .setConsistencyLevel(ConsistencyLevel.TWO);
7373
74- session.execute(s);
74+ session().execute(s);
7575 assertThat(retryPolicy.customStatementsHandled.get()).isEqualTo(0);
7676
77- session.execute(new CustomStatement(s));
77+ session().execute(new CustomStatement(s));
7878 assertThat(retryPolicy.customStatementsHandled.get()).isEqualTo(1);
7979 }
8080
modified driver-core/src/test/java/com/datastax/driver/core/TableMetadataTest.java +28 −28
@@ -41,8 +41,8 @@
4141 + " PRIMARY KEY (k)\n"
4242 + ");", keyspace);
4343 // when
44- session.execute(cql);
45- TableMetadata table = cluster.getMetadata().getKeyspace(keyspace).getTable("static");
44+ session().execute(cql);
45+ TableMetadata table = cluster().getMetadata().getKeyspace(keyspace).getTable("static");
4646 // then
4747 assertThat(table).isNotNull().hasName("static").hasNumberOfColumns(4).isNotCompactStorage();
4848 assertThat(table.getColumns().get(0)).isNotNull().hasName("k").isPartitionKey().hasType(text());
@@ -63,8 +63,8 @@
6363 + " PRIMARY KEY (k, c1, c2)\n"
6464 + ") WITH CLUSTERING ORDER BY (c1 ASC, c2 DESC);", keyspace);
6565 // when
66- session.execute(cql);
67- TableMetadata table = cluster.getMetadata().getKeyspace(keyspace).getTable("sparse");
66+ session().execute(cql);
67+ TableMetadata table = cluster().getMetadata().getKeyspace(keyspace).getTable("sparse");
6868 // then
6969 assertThat(table).isNotNull().hasName("sparse").hasNumberOfColumns(5).isNotCompactStorage();
7070 assertThat(table.getColumns().get(0)).isNotNull().hasName("k").isPartitionKey().hasType(text());
@@ -83,8 +83,8 @@
8383 + " PRIMARY KEY (k)\n"
8484 + ");", keyspace);
8585 // when
86- session.execute(cql);
87- TableMetadata table = cluster.getMetadata().getKeyspace(keyspace).getTable("counters");
86+ session().execute(cql);
87+ TableMetadata table = cluster().getMetadata().getKeyspace(keyspace).getTable("counters");
8888 // then
8989 assertThat(table).isNotNull().hasName("counters").hasNumberOfColumns(2).isNotCompactStorage();
9090 assertThat(table.getColumns().get(0)).isNotNull().hasName("k").isPartitionKey().hasType(text());
@@ -102,8 +102,8 @@
102102 + " PRIMARY KEY (k)\n"
103103 + ") WITH COMPACT STORAGE;", keyspace);
104104 // when
105- session.execute(cql);
106- TableMetadata table = cluster.getMetadata().getKeyspace(keyspace).getTable("compact_static");
105+ session().execute(cql);
106+ TableMetadata table = cluster().getMetadata().getKeyspace(keyspace).getTable("compact_static");
107107 // then
108108 assertThat(table).isNotNull().hasName("compact_static").hasNumberOfColumns(4).isCompactStorage();
109109 assertThat(table.getColumns().get(0)).isNotNull().hasName("k").isPartitionKey().hasType(text());
@@ -121,8 +121,8 @@
121121 + " PRIMARY KEY (k, c)\n"
122122 + " ) WITH COMPACT STORAGE;", keyspace);
123123 // when
124- session.execute(cql);
125- TableMetadata table = cluster.getMetadata().getKeyspace(keyspace).getTable("dense");
124+ session().execute(cql);
125+ TableMetadata table = cluster().getMetadata().getKeyspace(keyspace).getTable("dense");
126126 // then
127127 assertThat(table).isNotNull().hasName("dense").hasNumberOfColumns(2).isCompactStorage();
128128 assertThat(table.getColumns().get(0)).isNotNull().hasName("k").isPartitionKey().hasType(cint());
@@ -139,8 +139,8 @@
139139 + " PRIMARY KEY (k, c)\n"
140140 + ") WITH COMPACT STORAGE;", keyspace);
141141 // when
142- session.execute(cql);
143- TableMetadata table = cluster.getMetadata().getKeyspace(keyspace).getTable("compact_dynamic");
142+ session().execute(cql);
143+ TableMetadata table = cluster().getMetadata().getKeyspace(keyspace).getTable("compact_dynamic");
144144 // then
145145 assertThat(table).isNotNull().hasName("compact_dynamic").hasNumberOfColumns(3).isCompactStorage();
146146 assertThat(table.getColumns().get(0)).isNotNull().hasName("k").isPartitionKey().hasType(text());
@@ -160,8 +160,8 @@
160160 + " PRIMARY KEY (k, c1, c2, c3)\n"
161161 + ") WITH COMPACT STORAGE;", keyspace);
162162 // when
163- session.execute(cql);
164- TableMetadata table = cluster.getMetadata().getKeyspace(keyspace).getTable("compact_composite");
163+ session().execute(cql);
164+ TableMetadata table = cluster().getMetadata().getKeyspace(keyspace).getTable("compact_composite");
165165 // then
166166 assertThat(table).isNotNull().hasName("compact_composite").hasNumberOfColumns(5).isCompactStorage();
167167 assertThat(table.getColumns().get(0)).isNotNull().hasName("k").isPartitionKey().hasType(text());
@@ -173,7 +173,7 @@
173173
174174 @Test(groups = "short")
175175 public void should_parse_table_options() {
176- VersionNumber version = TestUtils.findHost(cluster, 1).getCassandraVersion();
176+ VersionNumber version = TestUtils.findHost(cluster(), 1).getCassandraVersion();
177177
178178 // given
179179 String cql;
@@ -223,8 +223,8 @@
223223 }
224224
225225 // when
226- session.execute(cql);
227- TableMetadata table = cluster.getMetadata().getKeyspace(keyspace).getTable("with_options");
226+ session().execute(cql);
227+ TableMetadata table = cluster().getMetadata().getKeyspace(keyspace).getTable("with_options");
228228
229229 // then
230230 assertThat(table).isNotNull().hasName("with_options").hasNumberOfColumns(4).isNotCompactStorage();
@@ -421,8 +421,8 @@
421421 keyspace);
422422
423423 // when
424- session.execute(cql);
425- TableMetadata table = cluster.getMetadata().getKeyspace(keyspace).getTable("new_compression_options");
424+ session().execute(cql);
425+ TableMetadata table = cluster().getMetadata().getKeyspace(keyspace).getTable("new_compression_options");
426426
427427 // then
428428 assertThat(table.getOptions().getCompression())
@@ -438,8 +438,8 @@
438438 + ") WITH comment = 'comment with single quote '' should work'",
439439 keyspace);
440440 // when
441- session.execute(cql);
442- TableMetadata table = cluster.getMetadata().getKeyspace(keyspace).getTable("single_quote");
441+ session().execute(cql);
442+ TableMetadata table = cluster().getMetadata().getKeyspace(keyspace).getTable("single_quote");
443443 // then
444444 assertThat(table.getOptions().getComment()).isEqualTo("comment with single quote ' should work");
445445 assertThat(table.asCQLQuery()).contains("comment = 'comment with single quote '' should work'");
@@ -454,10 +454,10 @@
454454 "CREATE INDEX test_d on test_cd (d);",
455455 };
456456 for (String statement : statements)
457- session.execute(statement);
457+ session().execute(statement);
458458
459- TableMetadata table_ab = cluster.getMetadata().getKeyspace(keyspace).getTable("test_ab");
460- TableMetadata table_cd = cluster.getMetadata().getKeyspace(keyspace).getTable("test_cd");
459+ TableMetadata table_ab = cluster().getMetadata().getKeyspace(keyspace).getTable("test_ab");
460+ TableMetadata table_cd = cluster().getMetadata().getKeyspace(keyspace).getTable("test_cd");
461461
462462 assertThat(table_ab.getIndexes().size()).isEqualTo(1);
463463 assertThat(table_ab.getIndexes()).extracting("name").containsOnly("test_b");
@@ -485,15 +485,15 @@
485485 + " v timeuuid,\n"
486486 + " PRIMARY KEY (k, c)\n"
487487 + ");", keyspace);
488- session.execute(cql);
488+ session().execute(cql);
489489
490490 // Manually change column value in system_schema.tables and force a schema refresh on that table.
491491 ImmutableMap<String, ByteBuffer> extensions = ImmutableMap.of("Hello", ByteBuffer.wrap("World".getBytes("UTF-8")));
492- session.execute("update system_schema.tables set extensions=? where keyspace_name=? and table_name=?", extensions, keyspace, "table_with_extensions");
493- cluster.manager.controlConnection.refreshSchema(SchemaElement.TABLE, keyspace, "table_with_extensions", null);
492+ session().execute("update system_schema.tables set extensions=? where keyspace_name=? and table_name=?", extensions, keyspace, "table_with_extensions");
493+ cluster().manager.controlConnection.refreshSchema(SchemaElement.TABLE, keyspace, "table_with_extensions", null);
494494
495495 // when retrieving the table's metadata.
496- TableMetadata table = cluster.getMetadata().getKeyspace(keyspace).getTable("table_with_extensions");
496+ TableMetadata table = cluster().getMetadata().getKeyspace(keyspace).getTable("table_with_extensions");
497497 // then the table's options should contain populated extensions.
498498 assertThat(table.getOptions().getExtensions()).isEqualTo(extensions);
499499 }
modified driver-core/src/test/java/com/datastax/driver/core/TestUtils.java +60 −35
@@ -35,12 +35,14 @@
3535 import java.net.*;
3636 import java.nio.ByteBuffer;
3737 import java.util.*;
38-import java.util.concurrent.Callable;
39-import java.util.concurrent.CountDownLatch;
40-import java.util.concurrent.TimeUnit;
38+import java.util.concurrent.*;
4139 import java.util.concurrent.atomic.AtomicInteger;
4240 import java.util.concurrent.locks.ReentrantLock;
4341
42+import static com.datastax.driver.core.ConditionChecker.check;
43+import static java.util.concurrent.TimeUnit.MINUTES;
44+import static java.util.concurrent.TimeUnit.SECONDS;
45+
4446 /**
4547 * A number of static fields/methods handy for tests.
4648 */
@@ -61,15 +63,10 @@
6163 public static final String CREATE_KEYSPACE_SIMPLE_FORMAT = "CREATE KEYSPACE %s WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor' : %d }";
6264 public static final String CREATE_KEYSPACE_GENERIC_FORMAT = "CREATE KEYSPACE %s WITH replication = { 'class' : '%s', %s }";
6365
64- public static final String SIMPLE_KEYSPACE = "ks";
65- public static final String SIMPLE_TABLE = "test";
66-
6766 public static final String SELECT_ALL_FORMAT = "SELECT * FROM %s";
6867
6968 public static final int TEST_BASE_NODE_WAIT = SystemProperties.getInt("com.datastax.driver.TEST_BASE_NODE_WAIT", 60);
7069
71- private static final AtomicInteger KS_COUNTER = new AtomicInteger(1);
72-
7370 public static void setValue(SettableByIndexData<?> data, int i, DataType type, Object value) {
7471 switch (type.getName()) {
7572 case ASCII:
@@ -470,28 +467,20 @@
470467 // Wait for a node to be up and running
471468 // This is used because there is some delay between when a node has been
472469 // added through ccm and when it's actually available for querying
473- public static void waitFor(String node, Cluster cluster) {
470+ public static void waitForUp(String node, Cluster cluster) {
474471 waitFor(node, cluster, TEST_BASE_NODE_WAIT, false);
475472 }
476473
477- public static void waitFor(String node, Cluster cluster, int maxTry) {
478- waitFor(node, cluster, maxTry, false);
474+ public static void waitForUp(String node, Cluster cluster, int timeoutSeconds) {
475+ waitFor(node, cluster, timeoutSeconds, false);
479476 }
480477
481478 public static void waitForDown(String node, Cluster cluster) {
482479 waitFor(node, cluster, TEST_BASE_NODE_WAIT * 3, true);
483480 }
484481
485- public static void waitForDown(String node, Cluster cluster, int maxTry) {
486- waitFor(node, cluster, maxTry, true);
487- }
488-
489- public static void waitForDecommission(String node, Cluster cluster) {
490- waitFor(node, cluster, TEST_BASE_NODE_WAIT / 2, true);
491- }
492-
493- public static void waitForDecommission(String node, Cluster cluster, int maxTry) {
494- waitFor(node, cluster, maxTry, true);
482+ public static void waitForDown(String node, Cluster cluster, int timeoutSeconds) {
483+ waitFor(node, cluster, timeoutSeconds, true);
495484 }
496485
497486 private static void waitFor(String node, Cluster cluster, int timeoutSeconds, boolean waitForDown) {
@@ -503,23 +492,30 @@
503492 // tried doing an actual query, the driver won't realize that last node is dead until
504493 // keep alive kicks in, but that's a fairly long time. So we cheat and trigger a force
505494 // the detection by forcing a request.
506- if (waitForDown) {
495+ if (waitForDown)
507496 Futures.getUnchecked(cluster.manager.submitSchemaRefresh(null, null, null, null));
508- }
509497 if (waitForDown) {
510- ConditionChecker.awaitUntil(new HostIsDownCondition(cluster, node), timeoutSeconds * 1000);
498+ check()
499+ .every(1, SECONDS)
500+ .before(timeoutSeconds, SECONDS)
501+ .that(new HostIsDown(cluster, node))
502+ .becomesTrue();
511503 } else {
512- ConditionChecker.awaitUntil(new HostIsUpCondition(cluster, node), timeoutSeconds * 1000);
504+ check()
505+ .every(1, SECONDS)
506+ .before(timeoutSeconds, SECONDS)
507+ .that(new HostIsUp(cluster, node))
508+ .becomesTrue();
513509 }
514510 }
515511
516- private static class HostIsDownCondition implements Callable<Boolean> {
512+ private static class HostIsDown implements Callable<Boolean> {
517513
518514 private final Cluster cluster;
519515
520516 private final String ip;
521517
522- public HostIsDownCondition(Cluster cluster, String ip) {
518+ public HostIsDown(Cluster cluster, String ip) {
523519 this.cluster = cluster;
524520 this.ip = ip;
525521 }
@@ -531,13 +527,13 @@
531527 }
532528 }
533529
534- private static class HostIsUpCondition implements Callable<Boolean> {
530+ private static class HostIsUp implements Callable<Boolean> {
535531
536532 private final Cluster cluster;
537533
538534 private final String ip;
539535
540- public HostIsUpCondition(Cluster cluster, String ip) {
536+ public HostIsUp(Cluster cluster, String ip) {
541537 this.cluster = cluster;
542538 this.ip = ip;
543539 }
@@ -660,8 +656,20 @@
660656 return ScassandraFactory.createServer(ipOfNode(1), binaryPort, ipOfNode(1), adminPort);
661657 }
662658
663- public static String getAvailableKeyspaceName() {
664- return SIMPLE_KEYSPACE + "_" + KS_COUNTER.getAndIncrement();
659+ private static final ConcurrentMap<String, AtomicInteger> IDENTIFIERS = new ConcurrentHashMap<String, AtomicInteger>();
660+
661+ /**
662+ * Generates a unique CQL identifier with the given prefix.
663+ *
664+ * @param prefix The prefix for the identifier
665+ * @return a unique CQL identifier.
666+ */
667+ public static String generateIdentifier(String prefix) {
668+ AtomicInteger seq = new AtomicInteger(0);
669+ AtomicInteger previous = IDENTIFIERS.putIfAbsent(prefix, seq);
670+ if (previous != null)
671+ seq = previous;
672+ return prefix + seq.incrementAndGet();
665673 }
666674
667675 // use ports in the ephemeral range
@@ -718,11 +726,11 @@
718726 };
719727
720728 public static void waitUntilPortIsUp(InetSocketAddress address) {
721- ConditionChecker.awaitUntil(address, PORT_IS_UP, TimeUnit.SECONDS.toMillis(10));
729+ check().before(5, MINUTES).that(address, PORT_IS_UP).becomesTrue();
722730 }
723731
724732 public static void waitUntilPortIsDown(InetSocketAddress address) {
725- ConditionChecker.awaitWhile(address, PORT_IS_UP, TimeUnit.SECONDS.toMillis(10));
733+ check().before(5, MINUTES).that(address, PORT_IS_UP).becomesFalse();
726734 }
727735
728736 public static boolean pingPort(InetAddress address, int port) {
@@ -780,7 +788,7 @@
780788 Host controlHost = cluster.manager.controlConnection.connectedHost();
781789 List<InetSocketAddress> singleAddress = Collections.singletonList(controlHost.getSocketAddress());
782790 return Cluster.builder()
783- .addContactPointsWithPorts(singleAddress)
791+ .addContactPoints(controlHost.getSocketAddress().getAddress())
784792 .withPort(ccm.getBinaryPort())
785793 .withLoadBalancingPolicy(new WhiteListPolicy(new RoundRobinPolicy(), singleAddress))
786794 .build();
@@ -803,10 +811,16 @@
803811 public static NettyOptions nonQuietClusterCloseOptions = new NettyOptions() {
804812 @Override
805813 public void onClusterClose(EventLoopGroup eventLoopGroup) {
806- eventLoopGroup.shutdownGracefully(0, 15, TimeUnit.SECONDS).syncUninterruptibly();
814+ eventLoopGroup.shutdownGracefully(0, 15, SECONDS).syncUninterruptibly();
807815 }
808816 };
809817
818+ /**
819+ * Executes a task and catches any exception.
820+ *
821+ * @param task The task to execute.
822+ * @param logException Whether to log the exception, if any.
823+ */
810824 public static void executeNoFail(Runnable task, boolean logException) {
811825 try {
812826 task.run();
@@ -816,6 +830,12 @@
816830 }
817831 }
818832
833+ /**
834+ * Executes a task and catches any exception.
835+ *
836+ * @param task The task to execute.
837+ * @param logException Whether to log the exception, if any.
838+ */
819839 public static void executeNoFail(Callable<?> task, boolean logException) {
820840 try {
821841 task.call();
@@ -825,6 +845,11 @@
825845 }
826846 }
827847
848+ /**
849+ * Returns the system's free memory in megabytes.
850+ * <p/>
851+ * This includes the free physical memory + the free swap memory.
852+ */
828853 public static long getFreeMemoryMB() {
829854 OperatingSystemMXBean bean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
830855 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 +41 −37
@@ -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,19 @@
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+ .addContactPoints(getContactPoints().get(0))
63+ .withPort(ccm().getBinaryPort())
6064 .withLoadBalancingPolicy(lbp)
6165 .withQueryOptions(TestUtils.nonDebouncingQueryOptions());
6266 }
6367
6468 @Override
65- public Collection<String> createTestFixtures() {
66- ks1 = TestUtils.getAvailableKeyspaceName();
67- ks2 = TestUtils.getAvailableKeyspaceName();
68- return Lists.newArrayList(
69+ public void onTestContextInitialized() {
70+ ks1 = TestUtils.generateIdentifier("ks_");
71+ ks2 = TestUtils.generateIdentifier("ks_");
72+ execute(
6973 String.format("CREATE KEYSPACE %s WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}", ks1),
7074 String.format("CREATE KEYSPACE %s WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 2}", ks2),
7175 String.format("USE %s", ks1),
@@ -89,18 +93,18 @@
8993 */
9094 @Test(groups = "short")
9195 public void should_expose_token_ranges() throws Exception {
92- Metadata metadata = cluster.getMetadata();
96+ Metadata metadata = cluster().getMetadata();
9397
9498 // Find the replica for a given partition key
9599 int testKey = 1;
96- Set<Host> replicas = metadata.getReplicas(ks1, TypeCodec.cint().serialize(testKey, cluster.getConfiguration().getProtocolOptions().getProtocolVersion()));
100+ Set<Host> replicas = metadata.getReplicas(ks1, TypeCodec.cint().serialize(testKey, cluster().getConfiguration().getProtocolOptions().getProtocolVersion()));
97101 assertThat(replicas).hasSize(1);
98102 Host replica = replicas.iterator().next();
99103
100104 // Iterate the cluster's token ranges. For each one, use a range query to ask Cassandra which partition keys
101105 // are in this range.
102106
103- PreparedStatement rangeStmt = session.prepare("SELECT i FROM foo WHERE token(i) > ? and token(i) <= ?");
107+ PreparedStatement rangeStmt = session().prepare("SELECT i FROM foo WHERE token(i) > ? and token(i) <= ?");
104108
105109 TokenRange foundRange = null;
106110 for (TokenRange range : metadata.getTokenRanges()) {
@@ -124,7 +128,7 @@
124128 List<Row> rows = Lists.newArrayList();
125129 for (TokenRange subRange : range.unwrap()) {
126130 Statement statement = rangeStmt.bind(subRange.getStart(), subRange.getEnd());
127- rows.addAll(session.execute(statement).all());
131+ rows.addAll(session().execute(statement).all());
128132 }
129133 return rows;
130134 }
@@ -154,7 +158,7 @@
154158 @Test(groups = "short")
155159 public void should_get_token_from_row_and_set_token_in_query() {
156160 // get by index:
157- Row row = session.execute("SELECT token(i) FROM foo WHERE i = 1").one();
161+ Row row = session().execute("SELECT token(i) FROM foo WHERE i = 1").one();
158162 Token token = row.getToken(0);
159163 assertThat(token.getType()).isEqualTo(expectedTokenType);
160164
@@ -162,14 +166,14 @@
162166 row.getPartitionKeyToken()
163167 ).isEqualTo(token);
164168
165- PreparedStatement pst = session.prepare("SELECT * FROM foo WHERE token(i) = ?");
166- row = session.execute(pst.bind(token)).one();
169+ PreparedStatement pst = session().prepare("SELECT * FROM foo WHERE token(i) = ?");
170+ row = session().execute(pst.bind(token)).one();
167171 assertThat(row.getInt(0)).isEqualTo(1);
168172
169- row = session.execute(pst.bind().setToken(0, token)).one();
173+ row = session().execute(pst.bind().setToken(0, token)).one();
170174 assertThat(row.getInt(0)).isEqualTo(1);
171175
172- row = session.execute(pst.bind().setPartitionKeyToken(token)).one();
176+ row = session().execute(pst.bind().setPartitionKeyToken(token)).one();
173177 assertThat(row.getInt(0)).isEqualTo(1);
174178 }
175179
@@ -190,15 +194,15 @@
190194 @Test(groups = "short")
191195 @CassandraVersion(major = 2)
192196 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();
197+ Row row = session().execute("SELECT token(i) AS t FROM foo WHERE i = 1").one();
194198 Token token = row.getToken("t");
195199 assertThat(token.getType()).isEqualTo(expectedTokenType);
196200
197- PreparedStatement pst = session.prepare("SELECT * FROM foo WHERE token(i) = :myToken");
198- row = session.execute(pst.bind().setToken("myToken", token)).one();
201+ PreparedStatement pst = session().prepare("SELECT * FROM foo WHERE token(i) = :myToken");
202+ row = session().execute(pst.bind().setToken("myToken", token)).one();
199203 assertThat(row.getInt(0)).isEqualTo(1);
200204
201- row = session.execute("SELECT * FROM foo WHERE token(i) = ?", token).one();
205+ row = session().execute("SELECT * FROM foo WHERE token(i) = ?", token).one();
202206 assertThat(row.getInt(0)).isEqualTo(1);
203207 }
204208
@@ -214,7 +218,7 @@
214218 */
215219 @Test(groups = "short", expectedExceptions = InvalidTypeException.class)
216220 public void should_raise_exception_when_get_token_on_non_token() {
217- Row row = session.execute("SELECT i FROM foo WHERE i = 1").one();
221+ Row row = session().execute("SELECT i FROM foo WHERE i = 1").one();
218222 row.getToken(0);
219223 }
220224
@@ -238,7 +242,7 @@
238242 public void should_expose_token_ranges_per_host() {
239243 checkRangesPerHost(ks1, 1);
240244 checkRangesPerHost(ks2, 2);
241- assertThat(cluster).hasValidTokenRanges();
245+ assertThat(cluster()).hasValidTokenRanges();
242246 }
243247
244248 private void checkRangesPerHost(String keyspace, int replicationFactor) {
@@ -246,8 +250,8 @@
246250
247251 // Get each host's ranges, the count should match the replication factor
248252 for (int i = 1; i <= 3; i++) {
249- Host host = TestUtils.findHost(cluster, i);
250- Set<TokenRange> hostRanges = cluster.getMetadata().getTokenRanges(keyspace, host);
253+ Host host = TestUtils.findHost(cluster(), i);
254+ Set<TokenRange> hostRanges = cluster().getMetadata().getTokenRanges(keyspace, host);
251255 // Special case: When using vnodes the tokens are not evenly assigned to each replica.
252256 if (!useVnodes) {
253257 assertThat(hostRanges).hasSize(replicationFactor * numTokens);
@@ -263,7 +267,7 @@
263267 assertThat(allRanges).hasSize(3 * numTokens);
264268
265269 // And the ranges should cover the whole ring and no ranges intersect.
266- assertThat(cluster).hasValidTokenRanges(keyspace);
270+ assertThat(cluster()).hasValidTokenRanges(keyspace);
267271 }
268272
269273 /**
@@ -282,19 +286,19 @@
282286 */
283287 @Test(groups = "short")
284288 public void should_expose_tokens_per_host() {
285- for (Host host : cluster.getMetadata().allHosts()) {
289+ for (Host host : cluster().getMetadata().allHosts()) {
286290 assertThat(host.getTokens()).hasSize(numTokens);
287291 // Check against the info in the system tables, which is a bit weak since it's exactly how the metadata is
288292 // constructed in the first place, but there's not much else we can do.
289293 // Note that this relies on all queries going to node 1, which is why we use a WhiteList LBP in setup().
290- boolean isControlHost = host.getSocketAddress().equals(cluster.manager.controlConnection.connectionRef.get().address);
294+ boolean isControlHost = host.getSocketAddress().equals(cluster().manager.controlConnection.connectionRef.get().address);
291295 Row row;
292296 if (isControlHost) {
293- row = session.execute("select tokens from system.local").one();
297+ row = session().execute("select tokens from system.local").one();
294298 } else {
295299 // non-control hosts are populated from system.peers and their broadcast address should be known
296300 assertThat(host.getBroadcastAddress()).isNotNull();
297- row = session.execute("select tokens from system.peers where peer = '" + host.getBroadcastAddress().getHostAddress() + "'").one();
301+ row = session().execute("select tokens from system.peers where peer = '" + host.getBroadcastAddress().getHostAddress() + "'").one();
298302 }
299303 Set<String> tokenStrings = row.getSet("tokens", String.class);
300304 assertThat(tokenStrings).hasSize(numTokens);
@@ -323,17 +327,17 @@
323327 */
324328 @Test(groups = "short")
325329 public void should_only_unwrap_one_range_for_all_ranges() {
326- Set<TokenRange> ranges = cluster.getMetadata().getTokenRanges();
330+ Set<TokenRange> ranges = cluster().getMetadata().getTokenRanges();
327331
328332 assertOnlyOneWrapped(ranges);
329333
330334 Iterable<TokenRange> splitRanges = Iterables.concat(Iterables.transform(ranges,
331- new Function<TokenRange, Iterable<TokenRange>>() {
332- @Override
333- public Iterable<TokenRange> apply(TokenRange input) {
334- return input.splitEvenly(10);
335- }
336- })
335+ new Function<TokenRange, Iterable<TokenRange>>() {
336+ @Override
337+ public Iterable<TokenRange> apply(TokenRange input) {
338+ return input.splitEvenly(10);
339+ }
340+ })
337341 );
338342
339343 assertOnlyOneWrapped(splitRanges);
@@ -363,7 +367,7 @@
363367
364368 @Test(groups = "short")
365369 public void should_expose_token_and_range_creation_methods() {
366- Metadata metadata = cluster.getMetadata();
370+ Metadata metadata = cluster().getMetadata();
367371
368372 // Pick a random range
369373 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 +76 −76
@@ -33,13 +33,13 @@
3333 ProtocolVersion protocolVersion = TestUtils.getDesiredProtocolVersion();
3434
3535 @Override
36- public Collection<String> createTestFixtures() {
37- return Collections.singleton("CREATE TABLE t (k int PRIMARY KEY, v frozen<tuple<int, text, float>>)");
36+ public void onTestContextInitialized() {
37+ execute("CREATE TABLE t (k int PRIMARY KEY, v frozen<tuple<int, text, float>>)");
3838 }
3939
4040 @Test(groups = "short")
4141 public void simpleValueTest() throws Exception {
42- TupleType t = cluster.getMetadata().newTupleType(DataType.cint(), DataType.text(), DataType.cfloat());
42+ TupleType t = cluster().getMetadata().newTupleType(DataType.cint(), DataType.text(), DataType.cfloat());
4343 TupleValue v = t.newValue();
4444 v.setInt(0, 1);
4545 v.setString(1, "a");
@@ -58,17 +58,17 @@
5858
5959 @Test(groups = "short")
6060 public void simpleWriteReadTest() throws Exception {
61- session.execute("USE " + keyspace);
62- PreparedStatement ins = session.prepare("INSERT INTO t(k, v) VALUES (?, ?)");
63- PreparedStatement sel = session.prepare("SELECT * FROM t WHERE k=?");
61+ session().execute("USE " + keyspace);
62+ PreparedStatement ins = session().prepare("INSERT INTO t(k, v) VALUES (?, ?)");
63+ PreparedStatement sel = session().prepare("SELECT * FROM t WHERE k=?");
6464
65- TupleType t = cluster.getMetadata().newTupleType(DataType.cint(), DataType.text(), DataType.cfloat());
65+ TupleType t = cluster().getMetadata().newTupleType(DataType.cint(), DataType.text(), DataType.cfloat());
6666
6767 int k = 1;
6868 TupleValue v = t.newValue(1, "a", 1.0f);
6969
70- session.execute(ins.bind(k, v));
71- TupleValue v2 = session.execute(sel.bind(k)).one().getTupleValue("v");
70+ session().execute(ins.bind(k, v));
71+ TupleValue v2 = session().execute(sel.bind(k)).one().getTupleValue("v");
7272
7373 assertEquals(v2, v);
7474
@@ -76,8 +76,8 @@
7676 k = 2;
7777 v = t.newValue(2, "b", 2.0f);
7878
79- session.execute("INSERT INTO t(k, v) VALUES (?, ?)", k, v);
80- v2 = session.execute(sel.bind(k)).one().getTupleValue("v");
79+ session().execute("INSERT INTO t(k, v) VALUES (?, ?)", k, v);
80+ v2 = session().execute(sel.bind(k)).one().getTupleValue("v");
8181
8282 assertEquals(v2, v);
8383 }
@@ -90,17 +90,17 @@
9090 */
9191 @Test(groups = "short")
9292 public void tupleTypeTest() throws Exception {
93- session.execute("CREATE KEYSPACE test_tuple_type " +
93+ session().execute("CREATE KEYSPACE test_tuple_type " +
9494 "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
95- session.execute("USE test_tuple_type");
96- session.execute("CREATE TABLE mytable (a int PRIMARY KEY, b frozen<tuple<ascii, int, boolean>>)");
95+ session().execute("USE test_tuple_type");
96+ session().execute("CREATE TABLE mytable (a int PRIMARY KEY, b frozen<tuple<ascii, int, boolean>>)");
9797
98- TupleType t = cluster.getMetadata().newTupleType(DataType.ascii(), DataType.cint(), DataType.cboolean());
98+ TupleType t = cluster().getMetadata().newTupleType(DataType.ascii(), DataType.cint(), DataType.cboolean());
9999
100100 // test non-prepared statement
101101 TupleValue complete = t.newValue("foo", 123, true);
102- session.execute("INSERT INTO mytable (a, b) VALUES (0, ?)", complete);
103- TupleValue r = session.execute("SELECT b FROM mytable WHERE a=0").one().getTupleValue("b");
102+ session().execute("INSERT INTO mytable (a, b) VALUES (0, ?)", complete);
103+ TupleValue r = session().execute("SELECT b FROM mytable WHERE a=0").one().getTupleValue("b");
104104 assertEquals(r, complete);
105105
106106 // test incomplete tuples
@@ -112,11 +112,11 @@
112112 }
113113
114114 // test incomplete tuples with new TupleType
115- TupleType t1 = cluster.getMetadata().newTupleType(DataType.ascii(), DataType.cint());
115+ TupleType t1 = cluster().getMetadata().newTupleType(DataType.ascii(), DataType.cint());
116116 TupleValue partial = t1.newValue("bar", 456);
117117 TupleValue partionResult = t.newValue("bar", 456, null);
118- session.execute("INSERT INTO mytable (a, b) VALUES (0, ?)", partial);
119- r = session.execute("SELECT b FROM mytable WHERE a=0").one().getTupleValue("b");
118+ session().execute("INSERT INTO mytable (a, b) VALUES (0, ?)", partial);
119+ r = session().execute("SELECT b FROM mytable WHERE a=0").one().getTupleValue("b");
120120 assertEquals(r, partionResult);
121121
122122 // test single value tuples
@@ -128,23 +128,23 @@
128128 }
129129
130130 // test single value tuples with new TupleType
131- TupleType t2 = cluster.getMetadata().newTupleType(DataType.ascii());
131+ TupleType t2 = cluster().getMetadata().newTupleType(DataType.ascii());
132132 TupleValue subpartial = t2.newValue("zoo");
133133 TupleValue subpartialResult = t.newValue("zoo", null, null);
134- session.execute("INSERT INTO mytable (a, b) VALUES (0, ?)", subpartial);
135- r = session.execute("SELECT b FROM mytable WHERE a=0").one().getTupleValue("b");
134+ session().execute("INSERT INTO mytable (a, b) VALUES (0, ?)", subpartial);
135+ r = session().execute("SELECT b FROM mytable WHERE a=0").one().getTupleValue("b");
136136 assertEquals(r, subpartialResult);
137137
138138 // test prepared statements
139- PreparedStatement prepared = session.prepare("INSERT INTO mytable (a, b) VALUES (?, ?)");
140- session.execute(prepared.bind(3, complete));
141- session.execute(prepared.bind(4, partial));
142- session.execute(prepared.bind(5, subpartial));
143-
144- prepared = session.prepare("SELECT b FROM mytable WHERE a=?");
145- assertEquals(session.execute(prepared.bind(3)).one().getTupleValue("b"), complete);
146- assertEquals(session.execute(prepared.bind(4)).one().getTupleValue("b"), partionResult);
147- assertEquals(session.execute(prepared.bind(5)).one().getTupleValue("b"), subpartialResult);
139+ PreparedStatement prepared = session().prepare("INSERT INTO mytable (a, b) VALUES (?, ?)");
140+ session().execute(prepared.bind(3, complete));
141+ session().execute(prepared.bind(4, partial));
142+ session().execute(prepared.bind(5, subpartial));
143+
144+ prepared = session().prepare("SELECT b FROM mytable WHERE a=?");
145+ assertEquals(session().execute(prepared.bind(3)).one().getTupleValue("b"), complete);
146+ assertEquals(session().execute(prepared.bind(4)).one().getTupleValue("b"), partionResult);
147+ assertEquals(session().execute(prepared.bind(5)).one().getTupleValue("b"), subpartialResult);
148148 }
149149
150150 /**
@@ -156,9 +156,9 @@
156156 */
157157 @Test(groups = "short")
158158 public void tupleTestTypeVaryingLengths() throws Exception {
159- session.execute("CREATE KEYSPACE test_tuple_type_varying_lengths " +
159+ session().execute("CREATE KEYSPACE test_tuple_type_varying_lengths " +
160160 "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
161- session.execute("USE test_tuple_type_varying_lengths");
161+ session().execute("USE test_tuple_type_varying_lengths");
162162
163163 // programmatically create the table with tuples of said sizes
164164 int[] lengths = {1, 2, 3, 384};
@@ -170,7 +170,7 @@
170170 }
171171 valueSchema.add(String.format(" v_%d frozen<tuple<%s>>", i, Joiner.on(',').join(ints)));
172172 }
173- session.execute(String.format("CREATE TABLE mytable (k int PRIMARY KEY, %s)", Joiner.on(',').join(valueSchema)));
173+ session().execute(String.format("CREATE TABLE mytable (k int PRIMARY KEY, %s)", Joiner.on(',').join(valueSchema)));
174174
175175 // insert tuples into same key using different columns
176176 // and verify the results
@@ -182,14 +182,14 @@
182182 dataTypes.add(DataType.cint());
183183 values.add(j);
184184 }
185- TupleType t = new TupleType(dataTypes, protocolVersion, cluster.getConfiguration().getCodecRegistry());
185+ TupleType t = new TupleType(dataTypes, protocolVersion, cluster().getConfiguration().getCodecRegistry());
186186 TupleValue createdTuple = t.newValue(values.toArray());
187187
188188 // write tuple
189- session.execute(String.format("INSERT INTO mytable (k, v_%s) VALUES (0, ?)", i), createdTuple);
189+ session().execute(String.format("INSERT INTO mytable (k, v_%s) VALUES (0, ?)", i), createdTuple);
190190
191191 // read tuple
192- TupleValue r = session.execute(String.format("SELECT v_%s FROM mytable WHERE k=0", i)).one().getTupleValue(String.format("v_%s", i));
192+ TupleValue r = session().execute(String.format("SELECT v_%s FROM mytable WHERE k=0", i)).one().getTupleValue(String.format("v_%s", i));
193193 assertEquals(r, createdTuple);
194194 }
195195 }
@@ -204,12 +204,12 @@
204204 public void tupleSubtypesTest() throws Exception {
205205
206206 List<DataType> DATA_TYPE_PRIMITIVES = Lists.newArrayList(PrimitiveTypeSamples.ALL.keySet());
207- session.execute("CREATE KEYSPACE test_tuple_subtypes " +
207+ session().execute("CREATE KEYSPACE test_tuple_subtypes " +
208208 "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
209- session.execute("USE test_tuple_subtypes");
209+ session().execute("USE test_tuple_subtypes");
210210
211211 // programmatically create the table with a tuple of all datatypes
212- session.execute(String.format("CREATE TABLE mytable (k int PRIMARY KEY, v frozen<tuple<%s>>)", Joiner.on(',').join(DATA_TYPE_PRIMITIVES)));
212+ session().execute(String.format("CREATE TABLE mytable (k int PRIMARY KEY, v frozen<tuple<%s>>)", Joiner.on(',').join(DATA_TYPE_PRIMITIVES)));
213213
214214 // insert tuples into same key using different columns
215215 // and verify the results
@@ -237,16 +237,16 @@
237237 }
238238
239239 // actually create the tuples
240- TupleType t = new TupleType(dataTypes, protocolVersion, cluster.getConfiguration().getCodecRegistry());
241- TupleType t2 = new TupleType(completeDataTypes, protocolVersion, cluster.getConfiguration().getCodecRegistry());
240+ TupleType t = new TupleType(dataTypes, protocolVersion, cluster().getConfiguration().getCodecRegistry());
241+ TupleType t2 = new TupleType(completeDataTypes, protocolVersion, cluster().getConfiguration().getCodecRegistry());
242242 TupleValue createdTuple = t.newValue(createdValues.toArray());
243243 TupleValue completeTuple = t2.newValue(completeValues.toArray());
244244
245245 // write tuple
246- session.execute(String.format("INSERT INTO mytable (k, v) VALUES (%s, ?)", i), createdTuple);
246+ session().execute(String.format("INSERT INTO mytable (k, v) VALUES (%s, ?)", i), createdTuple);
247247
248248 // read tuple
249- TupleValue r = session.execute("SELECT v FROM mytable WHERE k=?", i).one().getTupleValue("v");
249+ TupleValue r = session().execute("SELECT v FROM mytable WHERE k=?", i).one().getTupleValue("v");
250250
251251 assertEquals(r, completeTuple);
252252 ++i;
@@ -263,9 +263,9 @@
263263 public void tupleNonPrimitiveSubTypesTest() throws Exception {
264264
265265 List<DataType> DATA_TYPE_PRIMITIVES = Lists.newArrayList(PrimitiveTypeSamples.ALL.keySet());
266- session.execute("CREATE KEYSPACE test_tuple_non_primitive_subtypes " +
266+ session().execute("CREATE KEYSPACE test_tuple_non_primitive_subtypes " +
267267 "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
268- session.execute("USE test_tuple_non_primitive_subtypes");
268+ session().execute("USE test_tuple_non_primitive_subtypes");
269269
270270 ArrayList<String> values = new ArrayList<String>();
271271
@@ -285,7 +285,7 @@
285285 }
286286
287287 // create table
288- session.execute(String.format("CREATE TABLE mytable (k int PRIMARY KEY, %s)", Joiner.on(',').join(values)));
288+ session().execute(String.format("CREATE TABLE mytable (k int PRIMARY KEY, %s)", Joiner.on(',').join(values)));
289289
290290
291291 int i = 0;
@@ -298,14 +298,14 @@
298298 dataTypes.add(DataType.list(datatype));
299299 createdValues.add(Collections.singletonList(PrimitiveTypeSamples.ALL.get(datatype)));
300300
301- TupleType t = new TupleType(dataTypes, protocolVersion, cluster.getConfiguration().getCodecRegistry());
301+ TupleType t = new TupleType(dataTypes, protocolVersion, cluster().getConfiguration().getCodecRegistry());
302302 TupleValue createdTuple = t.newValue(createdValues.toArray());
303303
304304 // write tuple
305- session.execute(String.format("INSERT INTO mytable (k, v_%s) VALUES (0, ?)", i), createdTuple);
305+ session().execute(String.format("INSERT INTO mytable (k, v_%s) VALUES (0, ?)", i), createdTuple);
306306
307307 // read tuple
308- TupleValue r = session.execute(String.format("SELECT v_%s FROM mytable WHERE k=0", i))
308+ TupleValue r = session().execute(String.format("SELECT v_%s FROM mytable WHERE k=0", i))
309309 .one().getTupleValue(String.format("v_%s", i));
310310
311311 assertEquals(r, createdTuple);
@@ -321,14 +321,14 @@
321321 dataTypes.add(DataType.set(datatype));
322322 createdValues.add(new HashSet<Object>(Collections.singletonList(PrimitiveTypeSamples.ALL.get(datatype))));
323323
324- TupleType t = new TupleType(dataTypes, protocolVersion, cluster.getConfiguration().getCodecRegistry());
324+ TupleType t = new TupleType(dataTypes, protocolVersion, cluster().getConfiguration().getCodecRegistry());
325325 TupleValue createdTuple = t.newValue(createdValues.toArray());
326326
327327 // write tuple
328- session.execute(String.format("INSERT INTO mytable (k, v_%s) VALUES (0, ?)", i), createdTuple);
328+ session().execute(String.format("INSERT INTO mytable (k, v_%s) VALUES (0, ?)", i), createdTuple);
329329
330330 // read tuple
331- TupleValue r = session.execute(String.format("SELECT v_%s FROM mytable WHERE k=0", i))
331+ TupleValue r = session().execute(String.format("SELECT v_%s FROM mytable WHERE k=0", i))
332332 .one().getTupleValue(String.format("v_%s", i));
333333
334334 assertEquals(r, createdTuple);
@@ -347,14 +347,14 @@
347347 dataTypes.add(DataType.map(datatype, datatype));
348348 createdValues.add(hm);
349349
350- TupleType t = new TupleType(dataTypes, protocolVersion, cluster.getConfiguration().getCodecRegistry());
350+ TupleType t = new TupleType(dataTypes, protocolVersion, cluster().getConfiguration().getCodecRegistry());
351351 TupleValue createdTuple = t.newValue(createdValues.toArray());
352352
353353 // write tuple
354- session.execute(String.format("INSERT INTO mytable (k, v_%s) VALUES (0, ?)", i), createdTuple);
354+ session().execute(String.format("INSERT INTO mytable (k, v_%s) VALUES (0, ?)", i), createdTuple);
355355
356356 // read tuple
357- TupleValue r = session.execute(String.format("SELECT v_%s FROM mytable WHERE k=0", i))
357+ TupleValue r = session().execute(String.format("SELECT v_%s FROM mytable WHERE k=0", i))
358358 .one().getTupleValue(String.format("v_%s", i));
359359
360360 assertEquals(r, createdTuple);
@@ -374,7 +374,7 @@
374374 DataType.cint(), DataType.text(), DataType.cfloat());
375375 TupleValue detachedValue = detachedType.newValue(1, "hello", 2.0f);
376376
377- TupleType attachedType = cluster.getMetadata().newTupleType(DataType.cint(), DataType.text(), DataType.cfloat());
377+ TupleType attachedType = cluster().getMetadata().newTupleType(DataType.cint(), DataType.text(), DataType.cfloat());
378378 TupleValue attachedValue = attachedType.newValue(1, "hello", 2.0f);
379379
380380 assertThat(detachedValue).isEqualTo(attachedValue);
@@ -395,11 +395,11 @@
395395 */
396396 private TupleValue nestedTuplesCreatorHelper(int depth) {
397397 if (depth == 1) {
398- TupleType baseTuple = cluster.getMetadata().newTupleType(DataType.cint());
398+ TupleType baseTuple = cluster().getMetadata().newTupleType(DataType.cint());
399399 return baseTuple.newValue(303);
400400 } else {
401401 TupleValue innerTuple = nestedTuplesCreatorHelper(depth - 1);
402- TupleType t = cluster.getMetadata().newTupleType(innerTuple.getType());
402+ TupleType t = cluster().getMetadata().newTupleType(innerTuple.getType());
403403 return t.newValue(innerTuple);
404404 }
405405 }
@@ -412,12 +412,12 @@
412412 */
413413 @Test(groups = "short")
414414 public void nestedTuplesTest() throws Exception {
415- session.execute("CREATE KEYSPACE test_nested_tuples " +
415+ session().execute("CREATE KEYSPACE test_nested_tuples " +
416416 "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
417- session.execute("USE test_nested_tuples");
417+ session().execute("USE test_nested_tuples");
418418
419419 // create a table with multiple sizes of nested tuples
420- session.execute(String.format("CREATE TABLE mytable (" +
420+ session().execute(String.format("CREATE TABLE mytable (" +
421421 "k int PRIMARY KEY, " +
422422 "v_1 %s, " +
423423 "v_2 %s, " +
@@ -432,10 +432,10 @@
432432 TupleValue createdTuple = nestedTuplesCreatorHelper(i);
433433
434434 // write tuple
435- session.execute(String.format("INSERT INTO mytable (k, v_%s) VALUES (?, ?)", i), i, createdTuple);
435+ session().execute(String.format("INSERT INTO mytable (k, v_%s) VALUES (?, ?)", i), i, createdTuple);
436436
437437 // verify tuple was written and read correctly
438- TupleValue r = session.execute(String.format("SELECT v_%s FROM mytable WHERE k=?", i), i)
438+ TupleValue r = session().execute(String.format("SELECT v_%s FROM mytable WHERE k=?", i), i)
439439 .one().getTupleValue(String.format("v_%s", i));
440440
441441 assertEquals(r, createdTuple);
@@ -451,27 +451,27 @@
451451 @Test(groups = "short")
452452 public void testTuplesWithNulls() throws Exception {
453453 // create keyspace
454- session.execute("CREATE KEYSPACE testTuplesWithNulls " +
454+ session().execute("CREATE KEYSPACE testTuplesWithNulls " +
455455 "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
456- session.execute("USE testTuplesWithNulls");
456+ session().execute("USE testTuplesWithNulls");
457457
458458 // create UDT
459- session.execute("CREATE TYPE user (a text, b frozen<tuple<text, int, uuid, blob>>)");
460- session.execute("CREATE TABLE mytable (a int PRIMARY KEY, b frozen<user>)");
459+ session().execute("CREATE TYPE user (a text, b frozen<tuple<text, int, uuid, blob>>)");
460+ session().execute("CREATE TABLE mytable (a int PRIMARY KEY, b frozen<user>)");
461461
462462 // insert UDT data
463- UserType userTypeDef = cluster.getMetadata().getKeyspace("testTuplesWithNulls").getUserType("user");
463+ UserType userTypeDef = cluster().getMetadata().getKeyspace("testTuplesWithNulls").getUserType("user");
464464 UDTValue userType = userTypeDef.newValue();
465465
466- TupleType t = cluster.getMetadata().newTupleType(DataType.text(), DataType.cint(), DataType.uuid(), DataType.blob());
466+ TupleType t = cluster().getMetadata().newTupleType(DataType.text(), DataType.cint(), DataType.uuid(), DataType.blob());
467467 TupleValue v = t.newValue(null, null, null, null);
468468 userType.setTupleValue("b", v);
469469
470- PreparedStatement ins = session.prepare("INSERT INTO mytable (a, b) VALUES (?, ?)");
471- session.execute(ins.bind(0, userType));
470+ PreparedStatement ins = session().prepare("INSERT INTO mytable (a, b) VALUES (?, ?)");
471+ session().execute(ins.bind(0, userType));
472472
473473 // retrieve and verify data
474- ResultSet rs = session.execute("SELECT * FROM mytable");
474+ ResultSet rs = session().execute("SELECT * FROM mytable");
475475 List<Row> rows = rs.all();
476476 assertEquals(1, rows.size());
477477
@@ -483,10 +483,10 @@
483483 // test empty strings
484484 v = t.newValue("", null, null, ByteBuffer.allocate(0));
485485 userType.setTupleValue("b", v);
486- session.execute(ins.bind(0, userType));
486+ session().execute(ins.bind(0, userType));
487487
488488 // retrieve and verify data
489- rs = session.execute("SELECT * FROM mytable");
489+ rs = session().execute("SELECT * FROM mytable");
490490 rows = rs.all();
491491 assertEquals(1, rows.size());
492492
modified driver-core/src/test/java/com/datastax/driver/core/TypeCodecCollectionsIntegrationTest.java +17 −18
@@ -24,7 +24,6 @@
2424
2525 import java.math.BigDecimal;
2626 import java.math.BigInteger;
27-import java.util.Collection;
2827 import java.util.List;
2928 import java.util.Map;
3029 import java.util.Set;
@@ -46,15 +45,15 @@
4645
4746 private int n_int = 42;
4847 private List<Integer> l_int = newArrayList(42, 43);
49- private List<Long> l_bigint = newArrayList(42l, 43l);
48+ private List<Long> l_bigint = newArrayList(42L, 43L);
5049 private Set<Float> s_float = newHashSet(42.42f, 43.43f);
5150 private Set<Double> s_double = newHashSet(42.42d, 43.43d);
5251 private Map<Integer, BigInteger> m_varint = ImmutableMap.of(42, new BigInteger("424242"), 43, new BigInteger("434343"));
5352 private Map<Integer, BigDecimal> m_decimal = ImmutableMap.of(42, new BigDecimal("424242.42"), 43, new BigDecimal("434343.43"));
5453
5554 @Override
56- public Collection<String> createTestFixtures() {
57- return newArrayList(
55+ public void onTestContextInitialized() {
56+ execute(
5857 "CREATE TABLE IF NOT EXISTS \"myTable2\" ("
5958 + "c_int int PRIMARY KEY, "
6059 + "l_int list<int>, "
@@ -83,24 +82,24 @@
8382
8483 @Test(groups = "short")
8584 public void should_use_collection_codecs_with_simple_statements() {
86- session.execute(insertQuery, n_int, l_int, l_bigint, s_float, s_double, m_varint, m_decimal);
87- ResultSet rows = session.execute(selectQuery, n_int);
85+ session().execute(insertQuery, n_int, l_int, l_bigint, s_float, s_double, m_varint, m_decimal);
86+ ResultSet rows = session().execute(selectQuery, n_int);
8887 Row row = rows.one();
8988 assertRow(row);
9089 }
9190
9291 @Test(groups = "short")
9392 public void should_use_collection_codecs_with_prepared_statements_1() {
94- session.execute(session.prepare(insertQuery).bind(n_int, l_int, l_bigint, s_float, s_double, m_varint, m_decimal));
95- PreparedStatement ps = session.prepare(selectQuery);
96- ResultSet rows = session.execute(ps.bind(n_int));
93+ session().execute(session().prepare(insertQuery).bind(n_int, l_int, l_bigint, s_float, s_double, m_varint, m_decimal));
94+ PreparedStatement ps = session().prepare(selectQuery);
95+ ResultSet rows = session().execute(ps.bind(n_int));
9796 Row row = rows.one();
9897 assertRow(row);
9998 }
10099
101100 @Test(groups = "short")
102101 public void should_use_collection_codecs_with_prepared_statements_2() {
103- session.execute(session.prepare(insertQuery).bind()
102+ session().execute(session().prepare(insertQuery).bind()
104103 .setInt(0, n_int)
105104 .setList(1, l_int)
106105 .setList(2, l_bigint, Long.class) // variant with element type explicitly set
@@ -109,8 +108,8 @@
109108 .setMap(5, m_varint)
110109 .setMap(6, m_decimal, Integer.class, BigDecimal.class) // variant with element type explicitly set
111110 );
112- PreparedStatement ps = session.prepare(selectQuery);
113- ResultSet rows = session.execute(ps.bind()
111+ PreparedStatement ps = session().prepare(selectQuery);
112+ ResultSet rows = session().execute(ps.bind()
114113 .setInt(0, n_int)
115114 );
116115 Row row = rows.one();
@@ -119,7 +118,7 @@
119118
120119 @Test(groups = "short")
121120 public void should_use_collection_codecs_with_prepared_statements_3() {
122- session.execute(session.prepare(insertQuery).bind()
121+ session().execute(session().prepare(insertQuery).bind()
123122 .setInt(0, n_int)
124123 .set(1, l_int, TypeTokens.listOf(Integer.class))
125124 .set(2, l_bigint, TypeTokens.listOf(Long.class))
@@ -128,8 +127,8 @@
128127 .set(5, m_varint, TypeTokens.mapOf(Integer.class, BigInteger.class))
129128 .set(6, m_decimal, TypeTokens.mapOf(Integer.class, BigDecimal.class))
130129 );
131- PreparedStatement ps = session.prepare(selectQuery);
132- ResultSet rows = session.execute(ps.bind()
130+ PreparedStatement ps = session().prepare(selectQuery);
131+ ResultSet rows = session().execute(ps.bind()
133132 .setInt(0, n_int)
134133 );
135134 Row row = rows.one();
@@ -138,7 +137,7 @@
138137
139138 @Test(groups = "short")
140139 public void should_use_collection_codecs_with_built_statements() {
141- session.execute(session.prepare(insertStmt).bind()
140+ session().execute(session().prepare(insertStmt).bind()
142141 .setInt(0, n_int)
143142 .set(1, l_int, TypeTokens.listOf(Integer.class))
144143 .set(2, l_bigint, TypeTokens.listOf(Long.class))
@@ -147,8 +146,8 @@
147146 .set(5, m_varint, TypeTokens.mapOf(Integer.class, BigInteger.class))
148147 .set(6, m_decimal, TypeTokens.mapOf(Integer.class, BigDecimal.class))
149148 );
150- PreparedStatement ps = session.prepare(selectStmt);
151- ResultSet rows = session.execute(ps.bind()
149+ PreparedStatement ps = session().prepare(selectStmt);
150+ ResultSet rows = session().execute(ps.bind()
152151 .setInt(0, n_int)
153152 );
154153 Row row = rows.one();
modified driver-core/src/test/java/com/datastax/driver/core/TypeCodecEncapsulationIntegrationTest.java +16 −18
@@ -27,10 +27,8 @@
2727 import java.math.BigDecimal;
2828 import java.math.BigInteger;
2929 import java.nio.ByteBuffer;
30-import java.util.Collection;
3130
3231 import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
33-import static com.google.common.collect.Lists.newArrayList;
3432 import static org.assertj.core.api.Assertions.assertThat;
3533
3634 public class TypeCodecEncapsulationIntegrationTest extends CCMTestsSupport {
@@ -59,8 +57,8 @@
5957 private BigDecimal n_decimal = new BigDecimal("424242.42");
6058
6159 @Override
62- public Collection<String> createTestFixtures() {
63- return newArrayList(
60+ public void onTestContextInitialized() {
61+ execute(
6462 "CREATE TABLE \"myTable\" ("
6563 + "c_int int, "
6664 + "c_bigint bigint, "
@@ -106,36 +104,36 @@
106104 @Test(groups = "short")
107105 @CassandraVersion(major = 2.0)
108106 public void should_use_custom_codecs_with_simple_statements() {
109- session.execute(insertQuery,
107+ session().execute(insertQuery,
110108 n_int,
111109 new NumberBox<Long>(n_bigint),
112110 new NumberBox<Float>(n_float),
113111 new NumberBox<Double>(n_double),
114112 new NumberBox<BigInteger>(n_varint),
115113 new NumberBox<BigDecimal>(n_decimal));
116- ResultSet rows = session.execute(selectQuery, n_int, new NumberBox<Long>(n_bigint));
114+ ResultSet rows = session().execute(selectQuery, n_int, new NumberBox<Long>(n_bigint));
117115 Row row = rows.one();
118116 assertRow(row);
119117 }
120118
121119 @Test(groups = "short")
122120 public void should_use_custom_codecs_with_prepared_statements_1() {
123- session.execute(session.prepare(insertQuery).bind(
121+ session().execute(session().prepare(insertQuery).bind(
124122 n_int,
125123 new NumberBox<Long>(n_bigint),
126124 new NumberBox<Float>(n_float),
127125 new NumberBox<Double>(n_double),
128126 new NumberBox<BigInteger>(n_varint),
129127 new NumberBox<BigDecimal>(n_decimal)));
130- PreparedStatement ps = session.prepare(selectQuery);
131- ResultSet rows = session.execute(ps.bind(n_int, new NumberBox<Long>(n_bigint)));
128+ PreparedStatement ps = session().prepare(selectQuery);
129+ ResultSet rows = session().execute(ps.bind(n_int, new NumberBox<Long>(n_bigint)));
132130 Row row = rows.one();
133131 assertRow(row);
134132 }
135133
136134 @Test(groups = "short")
137135 public void should_use_custom_codecs_with_prepared_statements_2() {
138- session.execute(session.prepare(insertQuery).bind()
136+ session().execute(session().prepare(insertQuery).bind()
139137 .set(0, new NumberBox<Integer>(n_int), NUMBERBOX_OF_INTEGER_TOKEN)
140138 .set(1, new NumberBox<Long>(n_bigint), NUMBERBOX_OF_LONG_TOKEN)
141139 .set(2, new NumberBox<Float>(n_float), NUMBERBOX_OF_FLOAT_TOKEN)
@@ -143,8 +141,8 @@
143141 .set(4, new NumberBox<BigInteger>(n_varint), NUMBERBOX_OF_BIGINTEGER_TOKEN)
144142 .set(5, new NumberBox<BigDecimal>(n_decimal), NUMBERBOX_OF_BIGDECIMAL_TOKEN)
145143 );
146- PreparedStatement ps = session.prepare(selectQuery);
147- ResultSet rows = session.execute(ps.bind()
144+ PreparedStatement ps = session().prepare(selectQuery);
145+ ResultSet rows = session().execute(ps.bind()
148146 .set(0, new NumberBox<Integer>(n_int), NUMBERBOX_OF_INTEGER_TOKEN)
149147 .set(1, new NumberBox<Long>(n_bigint), NUMBERBOX_OF_LONG_TOKEN)
150148 );
@@ -154,30 +152,30 @@
154152
155153 @Test(groups = "short")
156154 public void should_use_custom_codecs_with_built_statements_1() {
157- session.execute(session.prepare(insertStmt).bind(
155+ session().execute(session().prepare(insertStmt).bind(
158156 n_int,
159157 new NumberBox<Long>(n_bigint),
160158 new NumberBox<Float>(n_float),
161159 new NumberBox<Double>(n_double),
162160 new NumberBox<BigInteger>(n_varint),
163161 new NumberBox<BigDecimal>(n_decimal)));
164- PreparedStatement ps = session.prepare(selectStmt);
165- ResultSet rows = session.execute(ps.bind(n_int, new NumberBox<Long>(n_bigint)));
162+ PreparedStatement ps = session().prepare(selectStmt);
163+ ResultSet rows = session().execute(ps.bind(n_int, new NumberBox<Long>(n_bigint)));
166164 Row row = rows.one();
167165 assertRow(row);
168166 }
169167
170168 @Test(groups = "short")
171169 public void should_use_custom_codecs_with_built_statements_2() {
172- session.execute(session.prepare(insertStmt).bind()
170+ session().execute(session().prepare(insertStmt).bind()
173171 .set(0, new NumberBox<Integer>(n_int), NUMBERBOX_OF_INTEGER_TOKEN)
174172 .set(1, new NumberBox<Long>(n_bigint), NUMBERBOX_OF_LONG_TOKEN)
175173 .set(2, new NumberBox<Float>(n_float), NUMBERBOX_OF_FLOAT_TOKEN)
176174 .set(3, new NumberBox<Double>(n_double), NUMBERBOX_OF_DOUBLE_TOKEN)
177175 .set(4, new NumberBox<BigInteger>(n_varint), NUMBERBOX_OF_BIGINTEGER_TOKEN)
178176 .set(5, new NumberBox<BigDecimal>(n_decimal), NUMBERBOX_OF_BIGDECIMAL_TOKEN));
179- PreparedStatement ps = session.prepare(selectStmt);
180- ResultSet rows = session.execute(ps.bind()
177+ PreparedStatement ps = session().prepare(selectStmt);
178+ ResultSet rows = session().execute(ps.bind()
181179 .set(0, new NumberBox<Integer>(n_int), NUMBERBOX_OF_INTEGER_TOKEN)
182180 .set(1, new NumberBox<Long>(n_bigint), NUMBERBOX_OF_LONG_TOKEN));
183181
modified driver-core/src/test/java/com/datastax/driver/core/TypeCodecNestedCollectionsIntegrationTest.java +17 −17
@@ -29,7 +29,6 @@
2929 import java.util.*;
3030
3131 import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
32-import static com.google.common.collect.Lists.newArrayList;
3332 import static org.assertj.core.api.Assertions.assertThat;
3433
3534 /**
@@ -54,9 +53,10 @@
5453 private TypeToken<Set<Map<MyInt, String>>> elementsType = new TypeToken<Set<Map<MyInt, String>>>() {};
5554 // @formatter:on
5655
56+
5757 @Override
58- public Collection<String> createTestFixtures() {
59- return newArrayList(
58+ public void onTestContextInitialized() {
59+ execute(
6060 "CREATE TABLE IF NOT EXISTS \"myTable\" ("
6161 + "pk int PRIMARY KEY, "
6262 + "v frozen<list<frozen<set<frozen<map<int,text>>>>>>"
@@ -91,29 +91,29 @@
9191
9292 @Test(groups = "short")
9393 public void should_work_with_simple_statements() {
94- session.execute(insertQuery, pk, v);
95- ResultSet rows = session.execute(selectQuery, pk);
94+ session().execute(insertQuery, pk, v);
95+ ResultSet rows = session().execute(selectQuery, pk);
9696 Row row = rows.one();
9797 assertRow(row);
9898 }
9999
100100 @Test(groups = "short")
101101 public void should_work_with_prepared_statements_1() {
102- session.execute(session.prepare(insertQuery).bind(pk, v));
103- PreparedStatement ps = session.prepare(selectQuery);
104- ResultSet rows = session.execute(ps.bind(pk));
102+ session().execute(session().prepare(insertQuery).bind(pk, v));
103+ PreparedStatement ps = session().prepare(selectQuery);
104+ ResultSet rows = session().execute(ps.bind(pk));
105105 Row row = rows.one();
106106 assertRow(row);
107107 }
108108
109109 @Test(groups = "short")
110110 public void should_work_with_prepared_statements_2() {
111- session.execute(session.prepare(insertQuery).bind()
111+ session().execute(session().prepare(insertQuery).bind()
112112 .setInt(0, pk)
113113 .setList(1, v, elementsType) // variant with element type explicitly set
114114 );
115- PreparedStatement ps = session.prepare(selectQuery);
116- ResultSet rows = session.execute(ps.bind()
115+ PreparedStatement ps = session().prepare(selectQuery);
116+ ResultSet rows = session().execute(ps.bind()
117117 .setInt(0, pk)
118118 );
119119 Row row = rows.one();
@@ -122,12 +122,12 @@
122122
123123 @Test(groups = "short")
124124 public void should_work_with_prepared_statements_3() {
125- session.execute(session.prepare(insertQuery).bind()
125+ session().execute(session().prepare(insertQuery).bind()
126126 .setInt(0, pk)
127127 .set(1, v, listType)
128128 );
129- PreparedStatement ps = session.prepare(selectQuery);
130- ResultSet rows = session.execute(ps.bind()
129+ PreparedStatement ps = session().prepare(selectQuery);
130+ ResultSet rows = session().execute(ps.bind()
131131 .setInt(0, pk)
132132 );
133133 Row row = rows.one();
@@ -136,12 +136,12 @@
136136
137137 @Test(groups = "short")
138138 public void should_work_with_built_statements() {
139- session.execute(session.prepare(insertStmt).bind()
139+ session().execute(session().prepare(insertStmt).bind()
140140 .setInt(0, pk)
141141 .set(1, v, listType)
142142 );
143- PreparedStatement ps = session.prepare(selectStmt);
144- ResultSet rows = session.execute(ps.bind()
143+ PreparedStatement ps = session().prepare(selectStmt);
144+ ResultSet rows = session().execute(ps.bind()
145145 .setInt(0, pk)
146146 );
147147 Row row = rows.one();
modified driver-core/src/test/java/com/datastax/driver/core/TypeCodecNestedUDTAndTupleIntegrationTest.java +17 −20
@@ -16,11 +16,8 @@
1616 package com.datastax.driver.core;
1717
1818 import com.datastax.driver.core.utils.CassandraVersion;
19-import com.google.common.collect.Lists;
2019 import org.testng.annotations.Test;
2120
22-import java.util.Collection;
23-
2421 import static org.assertj.core.api.Assertions.assertThat;
2522
2623 /**
@@ -35,8 +32,8 @@
3532 public class TypeCodecNestedUDTAndTupleIntegrationTest extends CCMTestsSupport {
3633
3734 @Override
38- public Collection<String> createTestFixtures() {
39- return Lists.newArrayList(
35+ public void onTestContextInitialized() {
36+ execute(
4037 "CREATE TYPE IF NOT EXISTS \"udt3\" (f3 text)",
4138 "CREATE TYPE IF NOT EXISTS \"udt2\" (f2 frozen<udt3>)",
4239 "CREATE TYPE IF NOT EXISTS \"udt1\" (f1 frozen<udt2>)",
@@ -56,51 +53,51 @@
5653
5754 @Test(groups = "short")
5855 public void should_set_registry_on_nested_udts() {
59- ResultSet rows = session.execute("SELECT c1 FROM t1 WHERE pk = 1");
56+ ResultSet rows = session().execute("SELECT c1 FROM t1 WHERE pk = 1");
6057 Row row = rows.one();
6158 // here the CodecRegistry will create a codec on-the-fly using the UserType received from the resultset metadata
6259 UDTValue udt1 = row.getUDTValue("c1");
63- assertThat(udt1.getCodecRegistry()).isSameAs(cluster.getConfiguration().getCodecRegistry());
60+ assertThat(udt1.getCodecRegistry()).isSameAs(cluster().getConfiguration().getCodecRegistry());
6461 UDTValue udt2 = udt1.getUDTValue("f1");
65- assertThat(udt2.getCodecRegistry()).isSameAs(cluster.getConfiguration().getCodecRegistry());
62+ assertThat(udt2.getCodecRegistry()).isSameAs(cluster().getConfiguration().getCodecRegistry());
6663 UDTValue udt3 = udt2.getUDTValue("f2");
67- assertThat(udt3.getCodecRegistry()).isSameAs(cluster.getConfiguration().getCodecRegistry());
64+ assertThat(udt3.getCodecRegistry()).isSameAs(cluster().getConfiguration().getCodecRegistry());
6865 String f3 = udt3.getString("f3");
6966 assertThat(f3).isEqualTo("foo");
7067 }
7168
7269 @Test(groups = "short")
7370 public void should_set_registry_on_nested_tuples() {
74- ResultSet rows = session.execute("SELECT c2 FROM t1 WHERE pk = 2");
71+ ResultSet rows = session().execute("SELECT c2 FROM t1 WHERE pk = 2");
7572 Row row = rows.one();
7673 // here the CodecRegistry will create a codec on-the-fly using the TupleType received from the resultset metadata
7774 TupleValue tuple1 = row.getTupleValue("c2");
78- assertThat(tuple1.getCodecRegistry()).isSameAs(cluster.getConfiguration().getCodecRegistry());
75+ assertThat(tuple1.getCodecRegistry()).isSameAs(cluster().getConfiguration().getCodecRegistry());
7976 TupleValue tuple2 = tuple1.getTupleValue(0);
80- assertThat(tuple2.getCodecRegistry()).isSameAs(cluster.getConfiguration().getCodecRegistry());
77+ assertThat(tuple2.getCodecRegistry()).isSameAs(cluster().getConfiguration().getCodecRegistry());
8178 TupleValue tuple3 = tuple2.getTupleValue(0);
82- assertThat(tuple3.getCodecRegistry()).isSameAs(cluster.getConfiguration().getCodecRegistry());
79+ assertThat(tuple3.getCodecRegistry()).isSameAs(cluster().getConfiguration().getCodecRegistry());
8380 String s = tuple3.getString(0);
8481 assertThat(s).isEqualTo("foo");
8582 }
8683
8784 @Test(groups = "short")
8885 public void should_set_registry_on_nested_tuples_and_udts() {
89- ResultSet rows = session.execute("SELECT c3 FROM t1 WHERE pk = 3");
86+ ResultSet rows = session().execute("SELECT c3 FROM t1 WHERE pk = 3");
9087 Row row = rows.one();
9188 // here the CodecRegistry will create a codec on-the-fly using the TupleType received from the resultset metadata
9289 TupleValue tuple1 = row.getTupleValue("c3");
93- assertThat(tuple1.getCodecRegistry()).isSameAs(cluster.getConfiguration().getCodecRegistry());
90+ assertThat(tuple1.getCodecRegistry()).isSameAs(cluster().getConfiguration().getCodecRegistry());
9491 TupleValue tuple2 = tuple1.getTupleValue(0);
95- assertThat(tuple2.getCodecRegistry()).isSameAs(cluster.getConfiguration().getCodecRegistry());
92+ assertThat(tuple2.getCodecRegistry()).isSameAs(cluster().getConfiguration().getCodecRegistry());
9693 TupleValue tuple3 = tuple2.getTupleValue(0);
97- assertThat(tuple3.getCodecRegistry()).isSameAs(cluster.getConfiguration().getCodecRegistry());
94+ assertThat(tuple3.getCodecRegistry()).isSameAs(cluster().getConfiguration().getCodecRegistry());
9895 UDTValue udt1 = tuple3.getUDTValue(0);
99- assertThat(udt1.getCodecRegistry()).isSameAs(cluster.getConfiguration().getCodecRegistry());
96+ assertThat(udt1.getCodecRegistry()).isSameAs(cluster().getConfiguration().getCodecRegistry());
10097 UDTValue udt2 = udt1.getUDTValue("f1");
101- assertThat(udt2.getCodecRegistry()).isSameAs(cluster.getConfiguration().getCodecRegistry());
98+ assertThat(udt2.getCodecRegistry()).isSameAs(cluster().getConfiguration().getCodecRegistry());
10299 UDTValue udt3 = udt2.getUDTValue("f2");
103- assertThat(udt3.getCodecRegistry()).isSameAs(cluster.getConfiguration().getCodecRegistry());
100+ assertThat(udt3.getCodecRegistry()).isSameAs(cluster().getConfiguration().getCodecRegistry());
104101 String f3 = udt3.getString("f3");
105102 assertThat(f3).isEqualTo("foo");
106103 }
modified driver-core/src/test/java/com/datastax/driver/core/TypeCodecNumbersIntegrationTest.java +13 −16
@@ -20,9 +20,7 @@
2020
2121 import java.math.BigDecimal;
2222 import java.math.BigInteger;
23-import java.util.Collection;
2423
25-import static com.google.common.collect.Lists.newArrayList;
2624 import static org.assertj.core.api.Assertions.assertThat;
2725
2826 public class TypeCodecNumbersIntegrationTest extends CCMTestsSupport {
@@ -38,10 +36,9 @@
3836 private BigInteger n_varint = new BigInteger("424242");
3937 private BigDecimal n_decimal = new BigDecimal("424242.42");
4038
41-
4239 @Override
43- public Collection<String> createTestFixtures() {
44- return newArrayList(
40+ public void onTestContextInitialized() {
41+ execute(
4542 "CREATE TABLE \"myTable\" ("
4643 + "c_int int, "
4744 + "c_bigint bigint, "
@@ -57,24 +54,24 @@
5754 @Test(groups = "short")
5855 @CassandraVersion(major = 2.0)
5956 public void should_use_defaut_codecs_with_simple_statements() {
60- session.execute(insertQuery, n_int, n_bigint, n_float, n_double, n_varint, n_decimal);
61- ResultSet rows = session.execute(selectQuery, n_int, n_bigint);
57+ session().execute(insertQuery, n_int, n_bigint, n_float, n_double, n_varint, n_decimal);
58+ ResultSet rows = session().execute(selectQuery, n_int, n_bigint);
6259 Row row = rows.one();
6360 assertRow(row);
6461 }
6562
6663 @Test(groups = "short")
6764 public void should_use_defaut_codecs_with_prepared_statements_1() {
68- session.execute(session.prepare(insertQuery).bind(n_int, n_bigint, n_float, n_double, n_varint, n_decimal));
69- PreparedStatement ps = session.prepare(selectQuery);
70- ResultSet rows = session.execute(ps.bind(n_int, n_bigint));
65+ session().execute(session().prepare(insertQuery).bind(n_int, n_bigint, n_float, n_double, n_varint, n_decimal));
66+ PreparedStatement ps = session().prepare(selectQuery);
67+ ResultSet rows = session().execute(ps.bind(n_int, n_bigint));
7168 Row row = rows.one();
7269 assertRow(row);
7370 }
7471
7572 @Test(groups = "short")
7673 public void should_use_default_codecs_with_prepared_statements_2() {
77- session.execute(session.prepare(insertQuery).bind()
74+ session().execute(session().prepare(insertQuery).bind()
7875 .setInt(0, n_int)
7976 .setLong(1, n_bigint)
8077 .setFloat(2, n_float)
@@ -82,8 +79,8 @@
8279 .setVarint(4, n_varint)
8380 .setDecimal(5, n_decimal)
8481 );
85- PreparedStatement ps = session.prepare(selectQuery);
86- ResultSet rows = session.execute(ps.bind()
82+ PreparedStatement ps = session().prepare(selectQuery);
83+ ResultSet rows = session().execute(ps.bind()
8784 .setInt(0, n_int)
8885 .setLong(1, n_bigint)
8986 );
@@ -93,7 +90,7 @@
9390
9491 @Test(groups = "short")
9592 public void should_use_default_codecs_with_prepared_statements_3() {
96- session.execute(session.prepare(insertQuery).bind()
93+ session().execute(session().prepare(insertQuery).bind()
9794 .set(0, n_int, Integer.class)
9895 .set(1, n_bigint, Long.class)
9996 .set(2, n_float, Float.class)
@@ -101,8 +98,8 @@
10198 .set(4, n_varint, BigInteger.class)
10299 .set(5, n_decimal, BigDecimal.class)
103100 );
104- PreparedStatement ps = session.prepare(selectQuery);
105- ResultSet rows = session.execute(ps.bind()
101+ PreparedStatement ps = session().prepare(selectQuery);
102+ ResultSet rows = session().execute(ps.bind()
106103 .setInt(0, n_int)
107104 .setLong(1, n_bigint)
108105 );
modified driver-core/src/test/java/com/datastax/driver/core/TypeCodecOverlappingJavaTypeIntegrationTest.java +8 −9
@@ -19,7 +19,6 @@
1919 import org.testng.annotations.Test;
2020
2121 import java.nio.ByteBuffer;
22-import java.util.Collection;
2322
2423 import static com.google.common.collect.Lists.newArrayList;
2524 import static org.assertj.core.api.Assertions.assertThat;
@@ -36,8 +35,8 @@
3635 private static final String selectQuery = "SELECT c_int, l_int, c_text FROM \"myTable\" WHERE c_int = ?";
3736
3837 @Override
39- public Collection<String> createTestFixtures() {
40- return newArrayList(
38+ public void onTestContextInitialized() {
39+ execute(
4140 "CREATE TABLE \"myTable\" ("
4241 + "c_int int PRIMARY KEY, "
4342 + "l_int list<int>, "
@@ -54,22 +53,22 @@
5453
5554 @Test(groups = "short")
5655 public void should_use_custom_codecs_with_prepared_statements() {
57- PreparedStatement ps = session.prepare(insertQuery);
58- session.execute(
56+ PreparedStatement ps = session().prepare(insertQuery);
57+ session().execute(
5958 ps.bind()
6059 .setInt(0, 42)
6160 .setList(1, newArrayList(42))
6261 .setString(2, "42") // here we have the CQL type so VarcharCodec will be used even if IntToStringCodec accepts it
6362 );
64- session.execute(
63+ session().execute(
6564 ps.bind()
6665 .setString(0, "42")
6766 .setList(1, newArrayList("42"), String.class)
6867 .setString(2, "42") // here we have the CQL type so VarcharCodec will be used even if IntToStringCodec accepts it
6968 );
70- ps = session.prepare(selectQuery);
71- assertRow(session.execute(ps.bind().setInt(0, 42)).one());
72- assertRow(session.execute(ps.bind().setString(0, "42")).one());
69+ ps = session().prepare(selectQuery);
70+ assertRow(session().execute(ps.bind().setInt(0, 42)).one());
71+ assertRow(session().execute(ps.bind().setString(0, "42")).one());
7372 }
7473
7574 private void assertRow(Row row) {
modified driver-core/src/test/java/com/datastax/driver/core/TypeCodecTupleIntegrationTest.java +22 −24
@@ -16,10 +16,8 @@
1616 package com.datastax.driver.core;
1717
1818 import com.datastax.driver.core.utils.CassandraVersion;
19-import com.google.common.collect.Lists;
2019 import org.testng.annotations.Test;
2120
22-import java.util.Collection;
2321 import java.util.UUID;
2422
2523 import static com.datastax.driver.core.DataType.cfloat;
@@ -41,50 +39,50 @@
4139 private TupleValue partialLocationValueRetrieved;
4240
4341 @Override
44- public Collection<String> createTestFixtures() {
45- return Lists.newArrayList(
42+ public void onTestContextInitialized() {
43+ execute(
4644 "CREATE TABLE IF NOT EXISTS \"users\" (id uuid PRIMARY KEY, name text, location frozen<tuple<float,float>>)"
4745 );
4846 }
4947
5048 @Test(groups = "short")
5149 public void should_handle_tuples_with_default_codecs() {
52- setUpTupleTypes(cluster);
50+ setUpTupleTypes(cluster());
5351 // simple statement
54- session.execute(insertQuery, uuid, "John Doe", locationValue);
55- ResultSet rows = session.execute(selectQuery, uuid);
52+ session().execute(insertQuery, uuid, "John Doe", locationValue);
53+ ResultSet rows = session().execute(selectQuery, uuid);
5654 Row row = rows.one();
5755 assertRow(row);
5856 // prepared + values
59- PreparedStatement ps = session.prepare(insertQuery);
60- session.execute(ps.bind(uuid, "John Doe", locationValue));
61- rows = session.execute(selectQuery, uuid);
57+ PreparedStatement ps = session().prepare(insertQuery);
58+ session().execute(ps.bind(uuid, "John Doe", locationValue));
59+ rows = session().execute(selectQuery, uuid);
6260 row = rows.one();
6361 assertRow(row);
6462 // bound with setTupleValue
65- session.execute(ps.bind().setUUID(0, uuid).setString(1, "John Doe").setTupleValue("location", locationValue));
66- rows = session.execute(selectQuery, uuid);
63+ session().execute(ps.bind().setUUID(0, uuid).setString(1, "John Doe").setTupleValue("location", locationValue));
64+ rows = session().execute(selectQuery, uuid);
6765 row = rows.one();
6866 assertRow(row);
6967 }
7068
7169 @Test(groups = "short")
7270 public void should_handle_partial_tuples_with_default_codecs() {
73- setUpTupleTypes(cluster);
71+ setUpTupleTypes(cluster());
7472 // simple statement
75- session.execute(insertQuery, uuid, "John Doe", partialLocationValueInserted);
76- ResultSet rows = session.execute(selectQuery, uuid);
73+ session().execute(insertQuery, uuid, "John Doe", partialLocationValueInserted);
74+ ResultSet rows = session().execute(selectQuery, uuid);
7775 Row row = rows.one();
7876 assertPartialRow(row);
7977 // prepared + values
80- PreparedStatement ps = session.prepare(insertQuery);
81- session.execute(ps.bind(uuid, "John Doe", partialLocationValueInserted));
82- rows = session.execute(selectQuery, uuid);
78+ PreparedStatement ps = session().prepare(insertQuery);
79+ session().execute(ps.bind(uuid, "John Doe", partialLocationValueInserted));
80+ rows = session().execute(selectQuery, uuid);
8381 row = rows.one();
8482 assertPartialRow(row);
8583 // bound with setTupleValue
86- session.execute(ps.bind().setUUID(0, uuid).setString(1, "John Doe").setTupleValue("location", partialLocationValueInserted));
87- rows = session.execute(selectQuery, uuid);
84+ session().execute(ps.bind().setUUID(0, uuid).setString(1, "John Doe").setTupleValue("location", partialLocationValueInserted));
85+ rows = session().execute(selectQuery, uuid);
8886 row = rows.one();
8987 assertPartialRow(row);
9088 }
@@ -93,8 +91,8 @@
9391 public void should_handle_tuples_with_custom_codecs() {
9492 CodecRegistry codecRegistry = new CodecRegistry();
9593 Cluster cluster = register(Cluster.builder()
96- .addContactPointsWithPorts(getInitialContactPoints())
97- .withPort(ccm.getBinaryPort())
94+ .addContactPoints(getContactPoints())
95+ .withPort(ccm().getBinaryPort())
9896 .withCodecRegistry(codecRegistry)
9997 .build());
10098 Session session = cluster.connect(keyspace);
@@ -123,8 +121,8 @@
123121 public void should_handle_partial_tuples_with_custom_codecs() {
124122 CodecRegistry codecRegistry = new CodecRegistry();
125123 Cluster cluster = register(Cluster.builder()
126- .addContactPointsWithPorts(getInitialContactPoints())
127- .withPort(ccm.getBinaryPort())
124+ .addContactPoints(getContactPoints())
125+ .withPort(ccm().getBinaryPort())
128126 .withCodecRegistry(codecRegistry)
129127 .build());
130128 Session session = cluster.connect(keyspace);
modified driver-core/src/test/java/com/datastax/driver/core/TypeCodecUDTIntegrationTest.java +12 −13
@@ -20,7 +20,6 @@
2020 import com.google.common.collect.Sets;
2121 import org.testng.annotations.Test;
2222
23-import java.util.Collection;
2423 import java.util.List;
2524 import java.util.Set;
2625 import java.util.UUID;
@@ -45,8 +44,8 @@
4544 private UDTValue addressValue;
4645
4746 @Override
48- public Collection<String> createTestFixtures() {
49- return Lists.newArrayList(
47+ public void onTestContextInitialized() {
48+ execute(
5049 "CREATE TYPE IF NOT EXISTS \"phone\" (number text, tags set<text>)",
5150 "CREATE TYPE IF NOT EXISTS \"address\" (street text, zipcode int, phones list<frozen<phone>>)",
5251 "CREATE TABLE IF NOT EXISTS \"users\" (id uuid PRIMARY KEY, name text, address frozen<address>)"
@@ -55,21 +54,21 @@
5554
5655 @Test(groups = "short")
5756 public void should_handle_udts_with_default_codecs() {
58- setUpUserTypes(cluster);
57+ setUpUserTypes(cluster());
5958 // simple statement
60- session.execute(insertQuery, uuid, "John Doe", addressValue);
61- ResultSet rows = session.execute(selectQuery, uuid);
59+ session().execute(insertQuery, uuid, "John Doe", addressValue);
60+ ResultSet rows = session().execute(selectQuery, uuid);
6261 Row row = rows.one();
6362 assertRow(row);
6463 // prepared + values
65- PreparedStatement ps = session.prepare(insertQuery);
66- session.execute(ps.bind(uuid, "John Doe", addressValue));
67- rows = session.execute(selectQuery, uuid);
64+ PreparedStatement ps = session().prepare(insertQuery);
65+ session().execute(ps.bind(uuid, "John Doe", addressValue));
66+ rows = session().execute(selectQuery, uuid);
6867 row = rows.one();
6968 assertRow(row);
7069 // bound with setUDTValue
71- session.execute(ps.bind().setUUID(0, uuid).setString(1, "John Doe").setUDTValue(2, addressValue));
72- rows = session.execute(selectQuery, uuid);
70+ session().execute(ps.bind().setUUID(0, uuid).setString(1, "John Doe").setUDTValue(2, addressValue));
71+ rows = session().execute(selectQuery, uuid);
7372 row = rows.one();
7473 assertRow(row);
7574 }
@@ -78,8 +77,8 @@
7877 public void should_handle_udts_with_custom_codecs() {
7978 CodecRegistry codecRegistry = new CodecRegistry();
8079 Cluster cluster = register(Cluster.builder()
81- .addContactPointsWithPorts(getInitialContactPoints())
82- .withPort(ccm.getBinaryPort())
80+ .addContactPoints(getContactPoints())
81+ .withPort(ccm().getBinaryPort())
8382 .withCodecRegistry(codecRegistry)
8483 .build());
8584 Session session = cluster.connect(keyspace);
modified driver-core/src/test/java/com/datastax/driver/core/UnresolvedUserTypeTest.java +5 −7
@@ -16,10 +16,8 @@
1616 package com.datastax.driver.core;
1717
1818 import com.datastax.driver.core.utils.CassandraVersion;
19-import com.google.common.collect.Lists;
2019 import org.testng.annotations.Test;
2120
22-import java.util.Collection;
2321 import java.util.concurrent.ExecutionException;
2422
2523 import static com.datastax.driver.core.Assertions.assertThat;
@@ -29,8 +27,8 @@
2927 public class UnresolvedUserTypeTest extends CCMTestsSupport {
3028
3129 @Override
32- public Collection<String> createTestFixtures() {
33- return Lists.newArrayList(
30+ public void onTestContextInitialized() {
31+ execute(
3432 /*
3533 Creates the following acyclic graph (edges directed upwards
3634 meaning "depends on"):
@@ -63,13 +61,13 @@
6361
6462 // Each CREATE TYPE statement in getTableDefinitions() has triggered a partial schema refresh that
6563 // should have used previous UDT definitions for dependencies.
66- checkUserTypes(cluster.getMetadata());
64+ checkUserTypes(cluster().getMetadata());
6765
6866 // Create a different Cluster instance to force a full refresh where all UDTs are loaded at once.
6967 // The parsing logic should sort them to make sure they are loaded in the right order.
7068 Cluster newCluster = register(Cluster.builder()
71- .addContactPointsWithPorts(getInitialContactPoints())
72- .withPort(ccm.getBinaryPort())
69+ .addContactPoints(getContactPoints())
70+ .withPort(ccm().getBinaryPort())
7371 .build());
7472 checkUserTypes(newCluster.getMetadata());
7573 }
modified driver-core/src/test/java/com/datastax/driver/core/UserTypesTest.java +82 −82
@@ -46,11 +46,11 @@
4646 new ArrayList<DataType.Name>(EnumSet.of(DataType.Name.LIST, DataType.Name.SET, DataType.Name.MAP, DataType.Name.TUPLE));
4747
4848 @Override
49- public Collection<String> createTestFixtures() {
49+ public void onTestContextInitialized() {
5050 String type1 = "CREATE TYPE phone (alias text, number text)";
5151 String type2 = "CREATE TYPE \"\"\"User Address\"\"\" (street text, \"ZIP\"\"\" int, phones set<frozen<phone>>)";
5252 String table = "CREATE TABLE user (id int PRIMARY KEY, addr frozen<\"\"\"User Address\"\"\">)";
53- return Arrays.asList(type1, type2, table);
53+ execute(type1, type2, table);
5454 }
5555
5656 /**
@@ -61,20 +61,20 @@
6161 @Test(groups = "short")
6262 public void simpleWriteReadTest() throws Exception {
6363 int userId = 0;
64- PreparedStatement ins = session.prepare("INSERT INTO user(id, addr) VALUES (?, ?)");
65- PreparedStatement sel = session.prepare("SELECT * FROM user WHERE id=?");
64+ PreparedStatement ins = session().prepare("INSERT INTO user(id, addr) VALUES (?, ?)");
65+ PreparedStatement sel = session().prepare("SELECT * FROM user WHERE id=?");
6666
67- UserType addrDef = cluster.getMetadata().getKeyspace(keyspace).getUserType(quote("\"User Address\""));
68- UserType phoneDef = cluster.getMetadata().getKeyspace(keyspace).getUserType("phone");
67+ UserType addrDef = cluster().getMetadata().getKeyspace(keyspace).getUserType(quote("\"User Address\""));
68+ UserType phoneDef = cluster().getMetadata().getKeyspace(keyspace).getUserType("phone");
6969
7070 UDTValue phone1 = phoneDef.newValue().setString("alias", "home").setString("number", "0123548790");
7171 UDTValue phone2 = phoneDef.newValue().setString("alias", "work").setString("number", "0698265251");
7272
7373 UDTValue addr = addrDef.newValue().setString("street", "1600 Pennsylvania Ave NW").setInt(quote("ZIP\""), 20500).setSet("phones", ImmutableSet.of(phone1, phone2));
7474
75- session.execute(ins.bind(userId, addr));
75+ session().execute(ins.bind(userId, addr));
7676
77- Row r = session.execute(sel.bind(userId)).one();
77+ Row r = session().execute(sel.bind(userId)).one();
7878
7979 assertEquals(r.getInt("id"), 0);
8080 assertEquals(r.getUDTValue("addr"), addr);
@@ -88,18 +88,18 @@
8888 @Test(groups = "short")
8989 public void simpleUnpreparedWriteReadTest() throws Exception {
9090 int userId = 1;
91- session.execute("USE " + keyspace);
92- UserType addrDef = cluster.getMetadata().getKeyspace(keyspace).getUserType(quote("\"User Address\""));
93- UserType phoneDef = cluster.getMetadata().getKeyspace(keyspace).getUserType("phone");
91+ session().execute("USE " + keyspace);
92+ UserType addrDef = cluster().getMetadata().getKeyspace(keyspace).getUserType(quote("\"User Address\""));
93+ UserType phoneDef = cluster().getMetadata().getKeyspace(keyspace).getUserType("phone");
9494
9595 UDTValue phone1 = phoneDef.newValue().setString("alias", "home").setString("number", "0123548790");
9696 UDTValue phone2 = phoneDef.newValue().setString("alias", "work").setString("number", "0698265251");
9797
9898 UDTValue addr = addrDef.newValue().setString("street", "1600 Pennsylvania Ave NW").setInt(quote("ZIP\""), 20500).setSet("phones", ImmutableSet.of(phone1, phone2));
9999
100- session.execute("INSERT INTO user(id, addr) VALUES (?, ?)", userId, addr);
100+ session().execute("INSERT INTO user(id, addr) VALUES (?, ?)", userId, addr);
101101
102- Row r = session.execute("SELECT * FROM user WHERE id=?", userId).one();
102+ Row r = session().execute("SELECT * FROM user WHERE id=?", userId).one();
103103
104104 assertEquals(r.getInt("id"), 1);
105105 assertEquals(r.getUDTValue("addr"), addr);
@@ -112,31 +112,31 @@
112112 */
113113 @Test(groups = "short")
114114 public void nonExistingTypesTest() throws Exception {
115- UserType addrDef = cluster.getMetadata().getKeyspace(keyspace).getUserType("address1");
116- UserType phoneDef = cluster.getMetadata().getKeyspace(keyspace).getUserType("phone1");
115+ UserType addrDef = cluster().getMetadata().getKeyspace(keyspace).getUserType("address1");
116+ UserType phoneDef = cluster().getMetadata().getKeyspace(keyspace).getUserType("phone1");
117117 assertEquals(addrDef, null);
118118 assertEquals(phoneDef, null);
119119
120- addrDef = cluster.getMetadata().getKeyspace(keyspace).getUserType(quote("\"User Address\""));
121- phoneDef = cluster.getMetadata().getKeyspace(keyspace).getUserType("phone");
120+ addrDef = cluster().getMetadata().getKeyspace(keyspace).getUserType(quote("\"User Address\""));
121+ phoneDef = cluster().getMetadata().getKeyspace(keyspace).getUserType("phone");
122122 assertNotEquals(addrDef, null);
123123 assertNotEquals(phoneDef, null);
124124
125125 // create keyspace
126126 String nonExistingKeyspace = keyspace + "_nonEx";
127- session.execute("CREATE KEYSPACE " + nonExistingKeyspace + " " +
127+ session().execute("CREATE KEYSPACE " + nonExistingKeyspace + " " +
128128 "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
129- session.execute("USE " + nonExistingKeyspace);
129+ session().execute("USE " + nonExistingKeyspace);
130130
131- addrDef = cluster.getMetadata().getKeyspace(nonExistingKeyspace).getUserType(quote("\"User Address\""));
132- phoneDef = cluster.getMetadata().getKeyspace(nonExistingKeyspace).getUserType("phone");
131+ addrDef = cluster().getMetadata().getKeyspace(nonExistingKeyspace).getUserType(quote("\"User Address\""));
132+ phoneDef = cluster().getMetadata().getKeyspace(nonExistingKeyspace).getUserType("phone");
133133 assertEquals(addrDef, null);
134134 assertEquals(phoneDef, null);
135135
136- session.execute("USE " + keyspace);
136+ session().execute("USE " + keyspace);
137137
138- addrDef = cluster.getMetadata().getKeyspace(keyspace).getUserType(quote("\"User Address\""));
139- phoneDef = cluster.getMetadata().getKeyspace(keyspace).getUserType("phone");
138+ addrDef = cluster().getMetadata().getKeyspace(keyspace).getUserType(quote("\"User Address\""));
139+ phoneDef = cluster().getMetadata().getKeyspace(keyspace).getUserType("phone");
140140 assertNotEquals(addrDef, null);
141141 assertNotEquals(phoneDef, null);
142142 }
@@ -151,9 +151,9 @@
151151 public void udtSizesTest() throws Exception {
152152 int MAX_TEST_LENGTH = 1024;
153153 // create keyspace
154- session.execute("CREATE KEYSPACE test_udt_sizes " +
154+ session().execute("CREATE KEYSPACE test_udt_sizes " +
155155 "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
156- session.execute("USE test_udt_sizes");
156+ session().execute("USE test_udt_sizes");
157157
158158 // create the seed udt
159159 StringBuilder sb = new StringBuilder();
@@ -163,13 +163,13 @@
163163 if (i + 1 < MAX_TEST_LENGTH)
164164 sb.append(",");
165165 }
166- session.execute(String.format("CREATE TYPE lengthy_udt (%s)", sb.toString()));
166+ session().execute(String.format("CREATE TYPE lengthy_udt (%s)", sb.toString()));
167167
168168 // create a table with multiple sizes of udts
169- session.execute("CREATE TABLE mytable (k int PRIMARY KEY, v frozen<lengthy_udt>)");
169+ session().execute("CREATE TABLE mytable (k int PRIMARY KEY, v frozen<lengthy_udt>)");
170170
171171 // hold onto the UserType for future use
172- UserType udtDef = cluster.getMetadata().getKeyspace("test_udt_sizes").getUserType("lengthy_udt");
172+ UserType udtDef = cluster().getMetadata().getKeyspace("test_udt_sizes").getUserType("lengthy_udt");
173173
174174 // verify inserts and reads
175175 for (int i : Arrays.asList(0, 1, 2, 3, MAX_TEST_LENGTH)) {
@@ -180,10 +180,10 @@
180180 }
181181
182182 // write udt
183- session.execute("INSERT INTO mytable (k, v) VALUES (0, ?)", createdUDT);
183+ session().execute("INSERT INTO mytable (k, v) VALUES (0, ?)", createdUDT);
184184
185185 // verify udt was written and read correctly
186- UDTValue r = session.execute("SELECT v FROM mytable WHERE k=0")
186+ UDTValue r = session().execute("SELECT v FROM mytable WHERE k=0")
187187 .one().getUDTValue("v");
188188 assertEquals(r.toString(), createdUDT.toString());
189189 }
@@ -198,9 +198,9 @@
198198 @Test(groups = "short")
199199 public void testPrimitiveDatatypes() throws Exception {
200200 // create keyspace
201- session.execute("CREATE KEYSPACE testPrimitiveDatatypes " +
201+ session().execute("CREATE KEYSPACE testPrimitiveDatatypes " +
202202 "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
203- session.execute("USE testPrimitiveDatatypes");
203+ session().execute("USE testPrimitiveDatatypes");
204204
205205 // create UDT
206206 List<String> alpha_type_list = new ArrayList<String>();
@@ -210,11 +210,11 @@
210210 DATA_TYPE_PRIMITIVES.get(i).getName()));
211211 }
212212
213- session.execute(String.format("CREATE TYPE alldatatypes (%s)", Joiner.on(',').join(alpha_type_list)));
214- session.execute("CREATE TABLE mytable (a int PRIMARY KEY, b frozen<alldatatypes>)");
213+ session().execute(String.format("CREATE TYPE alldatatypes (%s)", Joiner.on(',').join(alpha_type_list)));
214+ session().execute("CREATE TABLE mytable (a int PRIMARY KEY, b frozen<alldatatypes>)");
215215
216216 // insert UDT data
217- UserType alldatatypesDef = cluster.getMetadata().getKeyspace("testPrimitiveDatatypes").getUserType("alldatatypes");
217+ UserType alldatatypesDef = cluster().getMetadata().getKeyspace("testPrimitiveDatatypes").getUserType("alldatatypes");
218218 UDTValue alldatatypes = alldatatypesDef.newValue();
219219
220220 for (int i = 0; i < DATA_TYPE_PRIMITIVES.size(); i++) {
@@ -283,11 +283,11 @@
283283 }
284284 }
285285
286- PreparedStatement ins = session.prepare("INSERT INTO mytable (a, b) VALUES (?, ?)");
287- session.execute(ins.bind(0, alldatatypes));
286+ PreparedStatement ins = session().prepare("INSERT INTO mytable (a, b) VALUES (?, ?)");
287+ session().execute(ins.bind(0, alldatatypes));
288288
289289 // retrieve and verify data
290- ResultSet rs = session.execute("SELECT * FROM mytable");
290+ ResultSet rs = session().execute("SELECT * FROM mytable");
291291 List<Row> rows = rs.all();
292292 assertEquals(1, rows.size());
293293
@@ -306,9 +306,9 @@
306306 @Test(groups = "short")
307307 public void testNonPrimitiveDatatypes() throws Exception {
308308 // create keyspace
309- session.execute("CREATE KEYSPACE test_nonprimitive_datatypes " +
309+ session().execute("CREATE KEYSPACE test_nonprimitive_datatypes " +
310310 "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
311- session.execute("USE test_nonprimitive_datatypes");
311+ session().execute("USE test_nonprimitive_datatypes");
312312
313313 // counters are not allowed inside collections
314314 DATA_TYPE_PRIMITIVES.remove(DataType.counter());
@@ -335,11 +335,11 @@
335335 alpha_type_list.add(typeString);
336336 }
337337
338- session.execute(String.format("CREATE TYPE alldatatypes (%s)", Joiner.on(',').join(alpha_type_list)));
339- session.execute("CREATE TABLE mytable (a int PRIMARY KEY, b frozen<alldatatypes>)");
338+ session().execute(String.format("CREATE TYPE alldatatypes (%s)", Joiner.on(',').join(alpha_type_list)));
339+ session().execute("CREATE TABLE mytable (a int PRIMARY KEY, b frozen<alldatatypes>)");
340340
341341 // insert UDT data
342- UserType alldatatypesDef = cluster.getMetadata().getKeyspace("test_nonprimitive_datatypes").getUserType("alldatatypes");
342+ UserType alldatatypesDef = cluster().getMetadata().getKeyspace("test_nonprimitive_datatypes").getUserType("alldatatypes");
343343 UDTValue alldatatypes = alldatatypesDef.newValue();
344344
345345 for (int i = 0; i < DATA_TYPE_NON_PRIMITIVE_NAMES.size(); i++)
@@ -360,15 +360,15 @@
360360 alldatatypes.setMap(index, ImmutableMap.of(sampleElement, sampleElement));
361361 break;
362362 case TUPLE:
363- alldatatypes.setTupleValue(index, cluster.getMetadata().newTupleType(dataType).newValue(sampleElement));
363+ alldatatypes.setTupleValue(index, cluster().getMetadata().newTupleType(dataType).newValue(sampleElement));
364364 }
365365 }
366366
367- PreparedStatement ins = session.prepare("INSERT INTO mytable (a, b) VALUES (?, ?)");
368- session.execute(ins.bind(0, alldatatypes));
367+ PreparedStatement ins = session().prepare("INSERT INTO mytable (a, b) VALUES (?, ?)");
368+ session().execute(ins.bind(0, alldatatypes));
369369
370370 // retrieve and verify data
371- ResultSet rs = session.execute("SELECT * FROM mytable");
371+ ResultSet rs = session().execute("SELECT * FROM mytable");
372372 List<Row> rows = rs.all();
373373 assertEquals(1, rows.size());
374374
@@ -388,41 +388,41 @@
388388 public void udtNestedTest() throws Exception {
389389 final int MAX_NESTING_DEPTH = 4;
390390 // create keyspace
391- session.execute("CREATE KEYSPACE udtNestedTest " +
391+ session().execute("CREATE KEYSPACE udtNestedTest " +
392392 "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
393- session.execute("USE udtNestedTest");
393+ session().execute("USE udtNestedTest");
394394
395395 // create UDT
396- session.execute("CREATE TYPE depth_0 (age int, name text)");
396+ session().execute("CREATE TYPE depth_0 (age int, name text)");
397397
398398 for (int i = 1; i <= MAX_NESTING_DEPTH; i++) {
399- session.execute(String.format("CREATE TYPE depth_%s (value frozen<depth_%s>)", String.valueOf(i), String.valueOf(i - 1)));
399+ session().execute(String.format("CREATE TYPE depth_%s (value frozen<depth_%s>)", String.valueOf(i), String.valueOf(i - 1)));
400400 }
401401
402- session.execute(String.format("CREATE TABLE mytable (a int PRIMARY KEY, b frozen<depth_0>, c frozen<depth_1>, d frozen<depth_2>, e frozen<depth_3>," +
402+ session().execute(String.format("CREATE TABLE mytable (a int PRIMARY KEY, b frozen<depth_0>, c frozen<depth_1>, d frozen<depth_2>, e frozen<depth_3>," +
403403 "f frozen<depth_%s>)", MAX_NESTING_DEPTH));
404404
405405 // insert UDT data
406- UserType depthZeroDef = cluster.getMetadata().getKeyspace("udtNestedTest").getUserType("depth_0");
406+ UserType depthZeroDef = cluster().getMetadata().getKeyspace("udtNestedTest").getUserType("depth_0");
407407 UDTValue depthZero = depthZeroDef.newValue().setInt("age", 42).setString("name", "Bob");
408408
409- UserType depthOneDef = cluster.getMetadata().getKeyspace("udtNestedTest").getUserType("depth_1");
409+ UserType depthOneDef = cluster().getMetadata().getKeyspace("udtNestedTest").getUserType("depth_1");
410410 UDTValue depthOne = depthOneDef.newValue().setUDTValue("value", depthZero);
411411
412- UserType depthTwoDef = cluster.getMetadata().getKeyspace("udtNestedTest").getUserType("depth_2");
412+ UserType depthTwoDef = cluster().getMetadata().getKeyspace("udtNestedTest").getUserType("depth_2");
413413 UDTValue depthTwo = depthTwoDef.newValue().setUDTValue("value", depthOne);
414414
415- UserType depthThreeDef = cluster.getMetadata().getKeyspace("udtNestedTest").getUserType("depth_3");
415+ UserType depthThreeDef = cluster().getMetadata().getKeyspace("udtNestedTest").getUserType("depth_3");
416416 UDTValue depthThree = depthThreeDef.newValue().setUDTValue("value", depthTwo);
417417
418- UserType depthFourDef = cluster.getMetadata().getKeyspace("udtNestedTest").getUserType("depth_4");
418+ UserType depthFourDef = cluster().getMetadata().getKeyspace("udtNestedTest").getUserType("depth_4");
419419 UDTValue depthFour = depthFourDef.newValue().setUDTValue("value", depthThree);
420420
421- PreparedStatement ins = session.prepare("INSERT INTO mytable (a, b, c, d, e, f) VALUES (?, ?, ?, ?, ?, ?)");
422- session.execute(ins.bind(0, depthZero, depthOne, depthTwo, depthThree, depthFour));
421+ PreparedStatement ins = session().prepare("INSERT INTO mytable (a, b, c, d, e, f) VALUES (?, ?, ?, ?, ?, ?)");
422+ session().execute(ins.bind(0, depthZero, depthOne, depthTwo, depthThree, depthFour));
423423
424424 // retrieve and verify data
425- ResultSet rs = session.execute("SELECT * FROM mytable");
425+ ResultSet rs = session().execute("SELECT * FROM mytable");
426426 List<Row> rows = rs.all();
427427 assertEquals(1, rows.size());
428428
@@ -445,23 +445,23 @@
445445 @Test(groups = "short")
446446 public void testUdtsWithNulls() throws Exception {
447447 // create keyspace
448- session.execute("CREATE KEYSPACE testUdtsWithNulls " +
448+ session().execute("CREATE KEYSPACE testUdtsWithNulls " +
449449 "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
450- session.execute("USE testUdtsWithNulls");
450+ session().execute("USE testUdtsWithNulls");
451451
452452 // create UDT
453- session.execute("CREATE TYPE user (a text, b int, c uuid, d blob)");
454- session.execute("CREATE TABLE mytable (a int PRIMARY KEY, b frozen<user>)");
453+ session().execute("CREATE TYPE user (a text, b int, c uuid, d blob)");
454+ session().execute("CREATE TABLE mytable (a int PRIMARY KEY, b frozen<user>)");
455455
456456 // insert UDT data
457- UserType userTypeDef = cluster.getMetadata().getKeyspace("testUdtsWithNulls").getUserType("user");
457+ UserType userTypeDef = cluster().getMetadata().getKeyspace("testUdtsWithNulls").getUserType("user");
458458 UDTValue userType = userTypeDef.newValue().setString("a", null).setInt("b", 0).setUUID("c", null).setBytes("d", null);
459459
460- PreparedStatement ins = session.prepare("INSERT INTO mytable (a, b) VALUES (?, ?)");
461- session.execute(ins.bind(0, userType));
460+ PreparedStatement ins = session().prepare("INSERT INTO mytable (a, b) VALUES (?, ?)");
461+ session().execute(ins.bind(0, userType));
462462
463463 // retrieve and verify data
464- ResultSet rs = session.execute("SELECT * FROM mytable");
464+ ResultSet rs = session().execute("SELECT * FROM mytable");
465465 List<Row> rows = rs.all();
466466 assertEquals(1, rows.size());
467467
@@ -472,10 +472,10 @@
472472
473473 // test empty strings
474474 userType = userTypeDef.newValue().setString("a", "").setInt("b", 0).setUUID("c", null).setBytes("d", ByteBuffer.allocate(0));
475- session.execute(ins.bind(0, userType));
475+ session().execute(ins.bind(0, userType));
476476
477477 // retrieve and verify data
478- rs = session.execute("SELECT * FROM mytable");
478+ rs = session().execute("SELECT * FROM mytable");
479479 rows = rs.all();
480480 assertEquals(1, rows.size());
481481
@@ -493,38 +493,38 @@
493493 @Test(groups = "short")
494494 public void testUdtsWithCollectionNulls() throws Exception {
495495 // create keyspace
496- session.execute("CREATE KEYSPACE testUdtsWithCollectionNulls " +
496+ session().execute("CREATE KEYSPACE testUdtsWithCollectionNulls " +
497497 "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
498- session.execute("USE testUdtsWithCollectionNulls");
498+ session().execute("USE testUdtsWithCollectionNulls");
499499
500500 // create UDT
501- session.execute("CREATE TYPE user (a List<text>, b Set<text>, c Map<text, text>, d frozen<Tuple<text>>)");
502- session.execute("CREATE TABLE mytable (a int PRIMARY KEY, b frozen<user>)");
501+ session().execute("CREATE TYPE user (a List<text>, b Set<text>, c Map<text, text>, d frozen<Tuple<text>>)");
502+ session().execute("CREATE TABLE mytable (a int PRIMARY KEY, b frozen<user>)");
503503
504504 // insert null UDT data
505- PreparedStatement ins = session.prepare("INSERT INTO mytable (a, b) " +
505+ PreparedStatement ins = session().prepare("INSERT INTO mytable (a, b) " +
506506 "VALUES (0, { a: ?, b: ?, c: ?, d: ? })");
507- session.execute(ins.bind().setList(0, null).setSet(1, null).setMap(2, null).setTupleValue(3, null));
507+ session().execute(ins.bind().setList(0, null).setSet(1, null).setMap(2, null).setTupleValue(3, null));
508508
509509 // retrieve and verify data
510- ResultSet rs = session.execute("SELECT * FROM mytable");
510+ ResultSet rs = session().execute("SELECT * FROM mytable");
511511 List<Row> rows = rs.all();
512512 assertEquals(1, rows.size());
513513
514514 Row row = rows.get(0);
515515 assertEquals(row.getInt("a"), 0);
516516
517- UserType userTypeDef = cluster.getMetadata().getKeyspace("testUdtsWithCollectionNulls").getUserType("user");
517+ UserType userTypeDef = cluster().getMetadata().getKeyspace("testUdtsWithCollectionNulls").getUserType("user");
518518 UDTValue userType = userTypeDef.newValue().setList("a", null).setSet("b", null).setMap("c", null).setTupleValue("d", null);
519519 assertEquals(row.getUDTValue("b"), userType);
520520
521521 // test missing UDT args
522- ins = session.prepare("INSERT INTO mytable (a, b) " +
522+ ins = session().prepare("INSERT INTO mytable (a, b) " +
523523 "VALUES (1, { a: ? })");
524- session.execute(ins.bind().setList(0, new ArrayList<Object>()));
524+ session().execute(ins.bind().setList(0, new ArrayList<Object>()));
525525
526526 // retrieve and verify data
527- rs = session.execute("SELECT * FROM mytable");
527+ rs = session().execute("SELECT * FROM mytable");
528528 rows = rs.all();
529529 assertEquals(2, rows.size());
530530
modified driver-core/src/test/java/com/datastax/driver/core/WarningsTest.java +3 −7
@@ -17,10 +17,8 @@
1717
1818 import com.datastax.driver.core.utils.CassandraVersion;
1919 import com.google.common.base.Strings;
20-import com.google.common.collect.Lists;
2120 import org.testng.annotations.Test;
2221
23-import java.util.Collection;
2422 import java.util.List;
2523
2624 import static org.assertj.core.api.Assertions.assertThat;
@@ -33,16 +31,14 @@
3331 private static final int BATCH_SIZE_WARN_THRESHOLD_IN_BYTES = 5 * 1024;
3432
3533 @Override
36- public Collection<String> createTestFixtures() {
37- return Lists.newArrayList(
38- "CREATE TABLE foo(k int primary key, v text)"
39- );
34+ public void onTestContextInitialized() {
35+ execute("CREATE TABLE foo(k int primary key, v text)");
4036 }
4137
4238 @CassandraVersion(major = 2.2)
4339 @Test(groups = "short")
4440 public void should_expose_warnings_on_execution_info() {
45- ResultSet rs = session.execute(String.format("BEGIN UNLOGGED BATCH INSERT INTO foo (k, v) VALUES (1, '%s') APPLY BATCH",
41+ ResultSet rs = session().execute(String.format("BEGIN UNLOGGED BATCH INSERT INTO foo (k, v) VALUES (1, '%s') APPLY BATCH",
4642 Strings.repeat("1", BATCH_SIZE_WARN_THRESHOLD_IN_BYTES)));
4743
4844 List<String> warnings = rs.getExecutionInfo().getWarnings();
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/exceptions/FunctionExecutionExceptionTest.java +4 −6
@@ -18,18 +18,16 @@
1818 import com.datastax.driver.core.CCMConfig;
1919 import com.datastax.driver.core.CCMTestsSupport;
2020 import com.datastax.driver.core.utils.CassandraVersion;
21-import com.google.common.collect.Lists;
2221 import org.testng.annotations.Test;
2322
24-import java.util.Collection;
25-
2623 @CassandraVersion(major = 2.2)
2724 @CCMConfig(config = "enable_user_defined_functions:true")
2825 public class FunctionExecutionExceptionTest extends CCMTestsSupport {
2926
27+
3028 @Override
31- public Collection<String> createTestFixtures() {
32- return Lists.newArrayList(
29+ public void onTestContextInitialized() {
30+ execute(
3331 "CREATE TABLE foo (k int primary key, i int, l list<int>)",
3432 "INSERT INTO foo (k, i, l) VALUES (1, 1, [1])",
3533 "CREATE FUNCTION element_at(l list<int>, i int) RETURNS NULL ON NULL INPUT RETURNS int LANGUAGE java AS 'return (Integer) l.get(i);'"
@@ -38,6 +36,6 @@
3836
3937 @Test(groups = "short", expectedExceptions = FunctionExecutionException.class)
4038 public void should_throw_when_function_execution_fails() {
41- session.execute("SELECT element_at(l, i) FROM foo WHERE k = 1");
39+ session().execute("SELECT element_at(l, i) FROM foo WHERE k = 1");
4240 }
4341 }
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/TokenAwarePolicyTest.java +3 −3
@@ -325,13 +325,13 @@
325325 // given: a 3 node cluster with a keyspace with RF 1.
326326 Cluster cluster = register(Cluster.builder()
327327 .withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy()))
328- .addContactPointsWithPorts(ccm.addressOfNode(1))
329- .withPort(ccm.getBinaryPort())
328+ .addContactPoints(getContactPoints().get(0))
329+ .withPort(ccm().getBinaryPort())
330330 .build());
331331 Session session = cluster.connect();
332332
333333 String table = "composite";
334- String ks = TestUtils.getAvailableKeyspaceName();
334+ String ks = TestUtils.generateIdentifier("ks_");
335335 session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, ks, 1));
336336 session.execute("USE " + ks);
337337 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/policies/WhiteListPolicyTest.java +1 −0
@@ -109,6 +109,7 @@
109109 List<InetSocketAddress> whiteList = Lists.newArrayList(sCluster.address(2));
110110 Cluster cluster = Cluster.builder()
111111 .addContactPointsWithPorts(sCluster.address(3))
112+ .withPort(sCluster.getBinaryPort())
112113 .withLoadBalancingPolicy(new WhiteListPolicy(new RoundRobinPolicy(), whiteList))
113114 .withNettyOptions(nonQuietClusterCloseOptions)
114115 .build();
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("CREATE TABLE %s (k text PRIMARY KEY, t text, i int, f float)", 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
@@ -90,9 +93,9 @@
9093 public void batchNonBuiltStatementTest() throws Exception {
9194 SimpleStatement simple = new SimpleStatement("INSERT INTO " + TABLE1 + " (k, t) VALUES ('batchTest1', 'val1')");
9295 RegularStatement built = insertInto(TABLE1).value("k", "batchTest2").value("t", "val2");
93- session.execute(batch().add(simple).add(built));
96+ session().execute(batch().add(simple).add(built));
9497
95- List<Row> rows = session.execute(select().from(TABLE1).where(in("k", "batchTest1", "batchTest2"))).all();
98+ List<Row> rows = session().execute(select().from(TABLE1).where(in("k", "batchTest1", "batchTest2"))).all();
9699 assertEquals(2, rows.size());
97100
98101 Row r1 = rows.get(0);
@@ -107,75 +110,75 @@
107110 @Test(groups = "short")
108111 public void should_delete_list_element() throws Exception {
109112 //given
110- session.execute("INSERT INTO test_coll (k, a, b) VALUES (1, [1,2,3], null)");
113+ session().execute("INSERT INTO test_coll (k, a, b) VALUES (1, [1,2,3], null)");
111114 //when
112115 BuiltStatement statement = delete().listElt("a", 1).from("test_coll").where(eq("k", 1));
113- session.execute(statement);
116+ session().execute(statement);
114117 //then
115- List<Integer> actual = session.execute("SELECT a FROM test_coll WHERE k = 1").one().getList("a", Integer.class);
118+ List<Integer> actual = session().execute("SELECT a FROM test_coll WHERE k = 1").one().getList("a", Integer.class);
116119 assertThat(actual).containsExactly(1, 3);
117120 }
118121
119122 @Test(groups = "short")
120123 public void should_delete_list_element_with_bind_marker() throws Exception {
121124 //given
122- session.execute("INSERT INTO test_coll (k, a) VALUES (1, [1,2,3])");
125+ session().execute("INSERT INTO test_coll (k, a) VALUES (1, [1,2,3])");
123126 //when
124127 BuiltStatement statement = delete().listElt("a", bindMarker()).from("test_coll").where(eq("k", 1));
125- PreparedStatement ps = session.prepare(statement);
126- session.execute(ps.bind(1));
128+ PreparedStatement ps = session().prepare(statement);
129+ session().execute(ps.bind(1));
127130 //then
128- List<Integer> actual = session.execute("SELECT a FROM test_coll WHERE k = 1").one().getList("a", Integer.class);
131+ List<Integer> actual = session().execute("SELECT a FROM test_coll WHERE k = 1").one().getList("a", Integer.class);
129132 assertThat(actual).containsExactly(1, 3);
130133 }
131134
132135 @Test(groups = "short")
133136 public void should_delete_set_element() throws Exception {
134137 //given
135- session.execute("INSERT INTO test_coll (k, c) VALUES (1, {'foo','bar','qix'})");
138+ session().execute("INSERT INTO test_coll (k, c) VALUES (1, {'foo','bar','qix'})");
136139 //when
137140 BuiltStatement statement = delete().setElt("c", "foo").from("test_coll").where(eq("k", 1));
138- session.execute(statement);
141+ session().execute(statement);
139142 //then
140- Set<String> actual = session.execute("SELECT c FROM test_coll WHERE k = 1").one().getSet("c", String.class);
143+ Set<String> actual = session().execute("SELECT c FROM test_coll WHERE k = 1").one().getSet("c", String.class);
141144 assertThat(actual).containsOnly("bar", "qix");
142145 }
143146
144147 @Test(groups = "short")
145148 public void should_delete_set_element_with_bind_marker() throws Exception {
146149 //given
147- session.execute("INSERT INTO test_coll (k, c) VALUES (1, {'foo','bar','qix'})");
150+ session().execute("INSERT INTO test_coll (k, c) VALUES (1, {'foo','bar','qix'})");
148151 //when
149152 BuiltStatement statement = delete().setElt("c", bindMarker()).from("test_coll").where(eq("k", 1));
150- PreparedStatement ps = session.prepare(statement);
151- session.execute(ps.bind("foo"));
153+ PreparedStatement ps = session().prepare(statement);
154+ session().execute(ps.bind("foo"));
152155 //then
153- Set<String> actual = session.execute("SELECT c FROM test_coll WHERE k = 1").one().getSet("c", String.class);
156+ Set<String> actual = session().execute("SELECT c FROM test_coll WHERE k = 1").one().getSet("c", String.class);
154157 assertThat(actual).containsOnly("bar", "qix");
155158 }
156159
157160 @Test(groups = "short")
158161 public void should_delete_map_entry() throws Exception {
159162 //given
160- session.execute("INSERT INTO test_coll (k, b) VALUES (1, {1:'foo', 2:'bar'})");
163+ session().execute("INSERT INTO test_coll (k, b) VALUES (1, {1:'foo', 2:'bar'})");
161164 //when
162165 BuiltStatement statement = delete().mapElt("b", 1).from("test_coll").where(eq("k", 1));
163- session.execute(statement);
166+ session().execute(statement);
164167 //then
165- Map<Integer, String> actual = session.execute("SELECT b FROM test_coll WHERE k = 1").one().getMap("b", Integer.class, String.class);
168+ Map<Integer, String> actual = session().execute("SELECT b FROM test_coll WHERE k = 1").one().getMap("b", Integer.class, String.class);
166169 assertThat(actual).containsExactly(entry(2, "bar"));
167170 }
168171
169172 @Test(groups = "short")
170173 public void should_delete_map_entry_with_bind_marker() throws Exception {
171174 //given
172- session.execute("INSERT INTO test_coll (k, a, b) VALUES (1, null, {1:'foo', 2:'bar'})");
175+ session().execute("INSERT INTO test_coll (k, a, b) VALUES (1, null, {1:'foo', 2:'bar'})");
173176 //when
174177 BuiltStatement statement = delete().mapElt("b", bindMarker()).from("test_coll").where(eq("k", 1));
175- PreparedStatement ps = session.prepare(statement);
176- session.execute(ps.bind().setInt(0, 1));
178+ PreparedStatement ps = session().prepare(statement);
179+ session().execute(ps.bind().setInt(0, 1));
177180 //then
178- Map<Integer, String> actual = session.execute("SELECT b FROM test_coll WHERE k = 1").one().getMap("b", Integer.class, String.class);
181+ Map<Integer, String> actual = session().execute("SELECT b FROM test_coll WHERE k = 1").one().getMap("b", Integer.class, String.class);
179182 assertThat(actual).containsExactly(entry(2, "bar"));
180183 }
181184
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 +16 −18
@@ -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,19 +40,19 @@
4240 public void textRoutingKeyTest() throws Exception {
4341
4442 BuiltStatement query;
45- TableMetadata table = cluster.getMetadata().getKeyspace(keyspace).getTable(TABLE_TEXT);
43+ TableMetadata table = cluster().getMetadata().getKeyspace(keyspace).getTable(TABLE_TEXT);
4644 assertNotNull(table);
47- ProtocolVersion protocolVersion = cluster.getConfiguration().getProtocolOptions().getProtocolVersion();
45+ ProtocolVersion protocolVersion = cluster().getConfiguration().getProtocolOptions().getProtocolVersion();
4846 CodecRegistry codecRegistry = CodecRegistry.DEFAULT_INSTANCE;
4947
5048 String txt = "If she weighs the same as a duck... she's made of wood.";
5149 query = insertInto(table).values(new String[]{"k", "a", "b"}, new Object[]{txt, 1, 2});
5250 assertEquals(query.getRoutingKey(protocolVersion, codecRegistry), ByteBuffer.wrap(txt.getBytes()));
53- session.execute(query);
51+ session().execute(query);
5452
5553 query = select().from(table).where(eq("k", txt));
5654 assertEquals(query.getRoutingKey(protocolVersion, codecRegistry), ByteBuffer.wrap(txt.getBytes()));
57- Row row = session.execute(query).one();
55+ Row row = session().execute(query).one();
5856 assertEquals(row.getString("k"), txt);
5957 assertEquals(row.getInt("a"), 1);
6058 assertEquals(row.getInt("b"), 2);
@@ -64,20 +62,20 @@
6462 public void intRoutingKeyTest() throws Exception {
6563
6664 BuiltStatement query;
67- TableMetadata table = cluster.getMetadata().getKeyspace(keyspace).getTable(TABLE_INT);
65+ TableMetadata table = cluster().getMetadata().getKeyspace(keyspace).getTable(TABLE_INT);
6866 assertNotNull(table);
69- ProtocolVersion protocolVersion = cluster.getConfiguration().getProtocolOptions().getProtocolVersion();
67+ ProtocolVersion protocolVersion = cluster().getConfiguration().getProtocolOptions().getProtocolVersion();
7068 CodecRegistry codecRegistry = CodecRegistry.DEFAULT_INSTANCE;
7169
7270 query = insertInto(table).values(new String[]{"k", "a", "b"}, new Object[]{42, 1, 2});
7371 ByteBuffer bb = ByteBuffer.allocate(4);
7472 bb.putInt(0, 42);
7573 assertEquals(query.getRoutingKey(protocolVersion, codecRegistry), bb);
76- session.execute(query);
74+ session().execute(query);
7775
7876 query = select().from(table).where(eq("k", 42));
7977 assertEquals(query.getRoutingKey(protocolVersion, codecRegistry), bb);
80- Row row = session.execute(query).one();
78+ Row row = session().execute(query).one();
8179 assertEquals(row.getInt("k"), 42);
8280 assertEquals(row.getInt("a"), 1);
8381 assertEquals(row.getInt("b"), 2);
@@ -87,9 +85,9 @@
8785 public void intRoutingBatchKeyTest() throws Exception {
8886
8987 BuiltStatement query;
90- TableMetadata table = cluster.getMetadata().getKeyspace(keyspace).getTable(TABLE_INT);
88+ TableMetadata table = cluster().getMetadata().getKeyspace(keyspace).getTable(TABLE_INT);
9189 assertNotNull(table);
92- ProtocolVersion protocolVersion = cluster.getConfiguration().getProtocolOptions().getProtocolVersion();
90+ ProtocolVersion protocolVersion = cluster().getConfiguration().getProtocolOptions().getProtocolVersion();
9391 CodecRegistry codecRegistry = CodecRegistry.DEFAULT_INSTANCE;
9492
9593 ByteBuffer bb = ByteBuffer.allocate(4);
@@ -109,7 +107,7 @@
109107 .add(update(table).using(ttl(400)));
110108 assertEquals(batch.getRoutingKey(protocolVersion, codecRegistry), bb);
111109 assertEquals(batch.toString(), batch_query);
112- // TODO: rs = session.execute(batch); // Not guaranteed to be valid CQL
110+ // TODO: rs = session().execute(batch); // Not guaranteed to be valid CQL
113111
114112 batch_query = "BEGIN BATCH ";
115113 batch_query += String.format("SELECT * FROM %s.test_int WHERE k=42;", keyspace);
@@ -117,7 +115,7 @@
117115 batch = batch(query);
118116 assertEquals(batch.getRoutingKey(protocolVersion, codecRegistry), bb);
119117 assertEquals(batch.toString(), batch_query);
120- // TODO: rs = session.execute(batch); // Not guaranteed to be valid CQL
118+ // TODO: rs = session().execute(batch); // Not guaranteed to be valid CQL
121119
122120 batch_query = "BEGIN BATCH ";
123121 batch_query += "SELECT * FROM foo WHERE k=42;";
@@ -125,7 +123,7 @@
125123 batch = batch().add(select().from("foo").where(eq("k", 42)));
126124 assertEquals(batch.getRoutingKey(protocolVersion, codecRegistry), null);
127125 assertEquals(batch.toString(), batch_query);
128- // TODO: rs = session.execute(batch); // Not guaranteed to be valid CQL
126+ // TODO: rs = session().execute(batch); // Not guaranteed to be valid CQL
129127
130128 batch_query = "BEGIN BATCH USING TIMESTAMP 42 ";
131129 batch_query += "INSERT INTO foo.bar (a) VALUES (123);";
@@ -133,6 +131,6 @@
133131 batch = batch().using(timestamp(42)).add(insertInto("foo", "bar").value("a", 123));
134132 assertEquals(batch.getRoutingKey(protocolVersion, codecRegistry), null);
135133 assertEquals(batch.toString(), batch_query);
136- // TODO: rs = session.execute(batch); // Not guaranteed to be valid CQL
134+ // TODO: rs = session().execute(batch); // Not guaranteed to be valid CQL
137135 }
138136 }
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderTupleExecutionTest.java +2 −2
@@ -35,7 +35,7 @@
3535 @Test(groups = "short")
3636 public void should_handle_tuple() throws Exception {
3737 String query = "INSERT INTO foo (k,x) VALUES (0,(1));";
38- TupleType tupleType = cluster.getMetadata().newTupleType(cint());
38+ TupleType tupleType = cluster().getMetadata().newTupleType(cint());
3939 BuiltStatement insert = insertInto("foo").value("k", 0).value("x", tupleType.newValue(1));
4040 assertEquals(insert.toString(), query);
4141 }
@@ -46,7 +46,7 @@
4646 String query;
4747 BuiltStatement statement;
4848 query = "UPDATE foo SET l=[(1,2)] WHERE k=1;";
49- TupleType tupleType = cluster.getMetadata().newTupleType(cint(), cint());
49+ TupleType tupleType = cluster().getMetadata().newTupleType(cint(), cint());
5050 List<TupleValue> list = ImmutableList.of(tupleType.newValue(1, 2));
5151 statement = update("foo").with(set("l", list)).where(eq("k", 1));
5252 assertThat(statement.toString()).isEqualTo(query);
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-extras/src/test/java/com/datastax/driver/extras/codecs/arrays/ArrayCodecsTest.java +7 −9
@@ -21,12 +21,10 @@
2121 import com.datastax.driver.mapping.annotations.Column;
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 com.google.common.primitives.Primitives;
2625 import org.testng.annotations.DataProvider;
2726 import org.testng.annotations.Test;
2827
29-import java.util.Collection;
3028 import java.util.List;
3129
3230 import static org.assertj.core.api.Assertions.assertThat;
@@ -39,8 +37,8 @@
3937 TypeCodec.varchar());
4038
4139 @Override
42- public Collection<String> createTestFixtures() {
43- return Lists.newArrayList(
40+ public void onTestContextInitialized() {
41+ execute(
4442 "CREATE TABLE lists ("
4543 + "pk int PRIMARY KEY, "
4644 + "l_int list<int>, "
@@ -95,19 +93,19 @@
9593
9694 @Test(groups = "short", dataProvider = "ArrayCodecsTest-serializing")
9795 public <A> void should_read_list_column_as_array(String columnName, Class<A> arrayClass, A expected) {
98- Row row = session.execute(String.format("SELECT %s FROM lists WHERE pk = 1", columnName)).one();
96+ Row row = session().execute(String.format("SELECT %s FROM lists WHERE pk = 1", columnName)).one();
9997 A actual = row.get(columnName, arrayClass);
10098 assertThat(actual).isEqualTo(expected);
10199 }
102100
103101 @Test(groups = "short", dataProvider = "ArrayCodecsTest-serializing")
104102 public <A> void should_set_list_column_with_array(String columnName, Class<A> arrayClass, A expected) {
105- PreparedStatement ps = session.prepare(String.format("INSERT INTO lists (pk, %s) VALUES (?, ?)", columnName));
103+ PreparedStatement ps = session().prepare(String.format("INSERT INTO lists (pk, %s) VALUES (?, ?)", columnName));
106104 BoundStatement bs = ps.bind()
107105 .setInt(0, 2)
108106 .set(columnName, expected, arrayClass);
109- session.execute(bs);
110- Row row = session.execute(String.format("SELECT %s FROM lists WHERE pk = 2", columnName)).one();
107+ session().execute(bs);
108+ Row row = session().execute(String.format("SELECT %s FROM lists WHERE pk = 2", columnName)).one();
111109 List<?> list = row.getList(columnName, Primitives.wrap(arrayClass.getComponentType()));
112110 assertThat(list.toArray()).isEqualTo(expected);
113111 }
@@ -131,7 +129,7 @@
131129 @Test(groups = "short")
132130 public void should_use_mapper_to_store_and_retrieve_values_with_custom_joda_codecs() {
133131 // given
134- MappingManager manager = new MappingManager(session);
132+ MappingManager manager = new MappingManager(session());
135133 Mapper<Mapped> mapper = manager.mapper(Mapped.class);
136134 // when
137135 Mapped pojo = new Mapped();
modified driver-extras/src/test/java/com/datastax/driver/extras/codecs/date/SimpleDateCodecsTest.java +13 −11
@@ -26,7 +26,9 @@
2626 import org.testng.annotations.BeforeClass;
2727 import org.testng.annotations.Test;
2828
29-import java.util.*;
29+import java.util.Date;
30+import java.util.List;
31+import java.util.Map;
3032
3133 import static com.google.common.collect.Lists.newArrayList;
3234 import static org.assertj.core.api.Assertions.assertThat;
@@ -35,8 +37,8 @@
3537 public class SimpleDateCodecsTest extends CCMTestsSupport {
3638
3739 @Override
38- public Collection<String> createTestFixtures() {
39- return Collections.singletonList(
40+ public void onTestContextInitialized() {
41+ execute(
4042 "CREATE TABLE IF NOT EXISTS foo ("
4143 + "c1 text PRIMARY KEY, "
4244 + "cdate date, "
@@ -48,7 +50,7 @@
4850
4951 @BeforeClass(groups = "short")
5052 public void registerCodecs() throws Exception {
51- CodecRegistry codecRegistry = cluster.getConfiguration().getCodecRegistry();
53+ CodecRegistry codecRegistry = cluster().getConfiguration().getCodecRegistry();
5254 codecRegistry
5355 .register(SimpleDateCodec.instance)
5456 .register(SimpleTimestampCodec.instance);
@@ -72,9 +74,9 @@
7274 LocalDate localDate = LocalDate.fromDaysSinceEpoch(days);
7375 // when
7476 // note: these codecs cannot work with simple statements!
75- BoundStatement bs = session.prepare("insert into foo (c1, cdate) values (?, ?)").bind("should_map_date_to_days_since_epoch", days);
76- session.execute(bs);
77- ResultSet result = session.execute("select cdate from foo where c1=?", "should_map_date_to_days_since_epoch");
77+ BoundStatement bs = session().prepare("insert into foo (c1, cdate) values (?, ?)").bind("should_map_date_to_days_since_epoch", days);
78+ session().execute(bs);
79+ ResultSet result = session().execute("select cdate from foo where c1=?", "should_map_date_to_days_since_epoch");
7880 // then
7981 assertThat(result.getAvailableWithoutFetching()).isEqualTo(1);
8082 Row row = result.one();
@@ -101,9 +103,9 @@
101103 Date date = new Date(millis);
102104 // when
103105 // note: these codecs cannot work with simple statements!
104- BoundStatement bs = session.prepare("insert into foo (c1, ctimestamp) values (?, ?)").bind("should_map_timestamp_to_millis_since_epoch", millis);
105- session.execute(bs);
106- ResultSet result = session.execute("select ctimestamp from foo where c1=?", "should_map_timestamp_to_millis_since_epoch");
106+ BoundStatement bs = session().prepare("insert into foo (c1, ctimestamp) values (?, ?)").bind("should_map_timestamp_to_millis_since_epoch", millis);
107+ session().execute(bs);
108+ ResultSet result = session().execute("select ctimestamp from foo where c1=?", "should_map_timestamp_to_millis_since_epoch");
107109 // then
108110 assertThat(result.getAvailableWithoutFetching()).isEqualTo(1);
109111 Row row = result.one();
@@ -116,7 +118,7 @@
116118 @Test(groups = "short")
117119 public void should_use_mapper_to_store_and_retrieve_values_with_simple_date_codecs() {
118120 // given
119- MappingManager manager = new MappingManager(session);
121+ MappingManager manager = new MappingManager(session());
120122 Mapper<Mapped> mapper = manager.mapper(Mapped.class);
121123 // when
122124 Mapped pojo = new Mapped();
modified driver-extras/src/test/java/com/datastax/driver/extras/codecs/enums/EnumCodecsTest.java +15 −16
@@ -24,7 +24,6 @@
2424 import org.testng.annotations.BeforeMethod;
2525 import org.testng.annotations.Test;
2626
27-import java.util.Collection;
2827 import java.util.List;
2928 import java.util.Map;
3029 import java.util.Set;
@@ -60,8 +59,8 @@
6059 private UDTValue udtValue;
6160
6261 @Override
63- public Collection<String> createTestFixtures() {
64- return newArrayList(
62+ public void onTestContextInitialized() {
63+ execute(
6564 "CREATE TYPE IF NOT EXISTS udt1 ("
6665 + "foo int,"
6766 + "bar text)",
@@ -89,11 +88,11 @@
8988
9089 @BeforeMethod(groups = "short")
9190 public void before() {
92- TupleType tup = cluster.getMetadata().newTupleType(cint(), text());
91+ TupleType tup = cluster().getMetadata().newTupleType(cint(), text());
9392 tupleValue = tup.newValue()
9493 .set(0, FOO_1, Foo.class)
9594 .set(1, BAR_1, Bar.class);
96- UserType udt = cluster.getMetadata().getKeyspace(keyspace).getUserType("udt1");
95+ UserType udt = cluster().getMetadata().getKeyspace(keyspace).getUserType("udt1");
9796 udtValue = udt.newValue()
9897 .set("foo", FOO_1, Foo.class)
9998 .set("bar", BAR_1, Bar.class);
@@ -101,24 +100,24 @@
101100
102101 @Test(groups = "short")
103102 public void should_use_enum_codecs_with_simple_statements() {
104- session.execute(insertQuery, pk, FOO_1, foos, BAR_1, bars, foobars, tupleValue, udtValue);
105- ResultSet rows = session.execute(selectQuery, pk);
103+ session().execute(insertQuery, pk, FOO_1, foos, BAR_1, bars, foobars, tupleValue, udtValue);
104+ ResultSet rows = session().execute(selectQuery, pk);
106105 Row row = rows.one();
107106 assertRow(row);
108107 }
109108
110109 @Test(groups = "short")
111110 public void should_use_enum_codecs_with_prepared_statements_1() {
112- session.execute(session.prepare(insertQuery).bind(pk, FOO_1, foos, BAR_1, bars, foobars, tupleValue, udtValue));
113- PreparedStatement ps = session.prepare(selectQuery);
114- ResultSet rows = session.execute(ps.bind(pk));
111+ session().execute(session().prepare(insertQuery).bind(pk, FOO_1, foos, BAR_1, bars, foobars, tupleValue, udtValue));
112+ PreparedStatement ps = session().prepare(selectQuery);
113+ ResultSet rows = session().execute(ps.bind(pk));
115114 Row row = rows.one();
116115 assertRow(row);
117116 }
118117
119118 @Test(groups = "short")
120119 public void should_use_enum_codecs_with_prepared_statements_2() {
121- session.execute(session.prepare(insertQuery).bind()
120+ session().execute(session().prepare(insertQuery).bind()
122121 .setInt(0, pk)
123122 .set(1, FOO_1, Foo.class)
124123 .setList(2, foos, Foo.class)
@@ -128,8 +127,8 @@
128127 .setTupleValue(6, tupleValue)
129128 .setUDTValue(7, udtValue)
130129 );
131- PreparedStatement ps = session.prepare(selectQuery);
132- ResultSet rows = session.execute(ps.bind()
130+ PreparedStatement ps = session().prepare(selectQuery);
131+ ResultSet rows = session().execute(ps.bind()
133132 .setInt(0, pk)
134133 );
135134 Row row = rows.one();
@@ -139,7 +138,7 @@
139138 @Test(groups = "short")
140139 public void should_use_mapper_to_store_and_retrieve_nulls_with_enum_codecs() {
141140 // given
142- MappingManager manager = new MappingManager(session);
141+ MappingManager manager = new MappingManager(session());
143142 Mapper<Mapped> mapper = manager.mapper(Mapped.class);
144143 Mapped pojo = new Mapped();
145144 pojo.pk = 42;
@@ -154,7 +153,7 @@
154153 @Test(groups = "short")
155154 public void should_use_mapper_to_store_and_retrieve_values_with_enum_codecs() {
156155 // given
157- MappingManager manager = new MappingManager(session);
156+ MappingManager manager = new MappingManager(session());
158157 Mapper<Mapped> mapper = manager.mapper(Mapped.class);
159158 Mapped pojo = new Mapped();
160159 pojo.pk = 42;
@@ -173,7 +172,7 @@
173172 @Test(groups = "short")
174173 public void should_use_accessor_to_store_and_retrieve_values_with_enum_codecs() {
175174 // given
176- MappedAccessor accessor = new MappingManager(session).createAccessor(MappedAccessor.class);
175+ MappedAccessor accessor = new MappingManager(session()).createAccessor(MappedAccessor.class);
177176 Mapped expected = new Mapped();
178177 expected.pk = 42;
179178 expected.foo = FOO_1;
modified driver-extras/src/test/java/com/datastax/driver/extras/codecs/guava/OptionalCodecTest.java +24 −26
@@ -24,8 +24,6 @@
2424 import org.testng.annotations.Test;
2525
2626 import java.math.BigDecimal;
27-import java.util.Collection;
28-import java.util.Collections;
2927 import java.util.List;
3028
3129 import static com.datastax.driver.core.TypeCodec.*;
@@ -43,8 +41,8 @@
4341 private BuiltStatement selectStmt;
4442
4543 @Override
46- public Collection<String> createTestFixtures() {
47- return Collections.singletonList("CREATE TABLE foo (c1 text, c2 text, c3 list<text>, c4 bigint, c5 decimal, PRIMARY KEY (c1, c2))");
44+ public void onTestContextInitialized() {
45+ execute("CREATE TABLE foo (c1 text, c2 text, c3 list<text>, c4 bigint, c5 decimal, PRIMARY KEY (c1, c2))");
4846 }
4947
5048 @Override
@@ -73,15 +71,15 @@
7371 @Test(groups = "short")
7472 @CassandraVersion(major = 2.2)
7573 public void should_map_unset_value_to_absent() {
76- PreparedStatement insertPrep = session.prepare(this.insertStmt);
77- PreparedStatement selectPrep = session.prepare(this.selectStmt);
74+ PreparedStatement insertPrep = session().prepare(this.insertStmt);
75+ PreparedStatement selectPrep = session().prepare(this.selectStmt);
7876
7977 BoundStatement bs = insertPrep.bind();
8078 bs.setString(0, "should_map_unset_value_to_absent");
8179 bs.setString(1, "1");
82- session.execute(bs);
80+ session().execute(bs);
8381
84- ResultSet results = session.execute(selectPrep.bind("should_map_unset_value_to_absent"));
82+ ResultSet results = session().execute(selectPrep.bind("should_map_unset_value_to_absent"));
8583 assertThat(results.getAvailableWithoutFetching()).isEqualTo(1);
8684
8785 Row row = results.one();
@@ -102,16 +100,16 @@
102100 */
103101 @Test(groups = "short")
104102 public void should_map_absent_null_value_to_absent() {
105- PreparedStatement insertPrep = session.prepare(this.insertStmt);
106- PreparedStatement selectPrep = session.prepare(this.selectStmt);
103+ PreparedStatement insertPrep = session().prepare(this.insertStmt);
104+ PreparedStatement selectPrep = session().prepare(this.selectStmt);
107105
108106 BoundStatement bs = insertPrep.bind();
109107 bs.setString(0, "should_map_absent_null_value_to_absent");
110108 bs.setString(1, "1");
111109 bs.set(2, Optional.<List<String>>absent(), optionalCodec.getJavaType());
112- session.execute(bs);
110+ session().execute(bs);
113111
114- ResultSet results = session.execute(selectPrep.bind("should_map_absent_null_value_to_absent"));
112+ ResultSet results = session().execute(selectPrep.bind("should_map_absent_null_value_to_absent"));
115113 assertThat(results.getAvailableWithoutFetching()).isEqualTo(1);
116114
117115 Row row = results.one();
@@ -134,8 +132,8 @@
134132 */
135133 @Test(groups = "short")
136134 public void should_map_some_back_to_itself() {
137- PreparedStatement insertPrep = session.prepare(this.insertStmt);
138- PreparedStatement selectPrep = session.prepare(this.selectStmt);
135+ PreparedStatement insertPrep = session().prepare(this.insertStmt);
136+ PreparedStatement selectPrep = session().prepare(this.selectStmt);
139137
140138 List<String> data = Lists.newArrayList("1", "2", "3");
141139
@@ -143,9 +141,9 @@
143141 bs.setString(0, "should_map_some_back_to_itself");
144142 bs.setString(1, "1");
145143 bs.set(2, Optional.of(data), optionalCodec.getJavaType());
146- session.execute(bs);
144+ session().execute(bs);
147145
148- ResultSet results = session.execute(selectPrep.bind("should_map_some_back_to_itself"));
146+ ResultSet results = session().execute(selectPrep.bind("should_map_some_back_to_itself"));
149147 assertThat(results.getAvailableWithoutFetching()).isEqualTo(1);
150148
151149 Row row = results.one();
@@ -163,18 +161,18 @@
163161 @Test(groups = "short")
164162 public void should_map_a_primitive_type_to_absent() {
165163 OptionalCodec<Long> optionalLongCodec = new OptionalCodec<Long>(bigint());
166- cluster.getConfiguration().getCodecRegistry().register(optionalLongCodec);
164+ cluster().getConfiguration().getCodecRegistry().register(optionalLongCodec);
167165
168- PreparedStatement stmt = session.prepare("insert into foo (c1, c2, c4) values (?,?,?)");
166+ PreparedStatement stmt = session().prepare("insert into foo (c1, c2, c4) values (?,?,?)");
169167
170168 BoundStatement bs = stmt.bind();
171169 bs.setString(0, "should_map_a_primitive_type_to_absent");
172170 bs.setString(1, "1");
173171 bs.set(2, Optional.<Long>absent(), optionalLongCodec.getJavaType());
174- session.execute(bs);
172+ session().execute(bs);
175173
176- PreparedStatement selectBigint = session.prepare("select c1, c4 from foo where c1=?");
177- ResultSet results = session.execute(selectBigint.bind("should_map_a_primitive_type_to_absent"));
174+ PreparedStatement selectBigint = session().prepare("select c1, c4 from foo where c1=?");
175+ ResultSet results = session().execute(selectBigint.bind("should_map_a_primitive_type_to_absent"));
178176
179177 assertThat(results.getAvailableWithoutFetching()).isEqualTo(1);
180178
@@ -187,18 +185,18 @@
187185 @Test(groups = "short")
188186 public void should_map_a_nullable_type_to_absent() {
189187 OptionalCodec<BigDecimal> optionalDecimalCodec = new OptionalCodec<BigDecimal>(decimal());
190- cluster.getConfiguration().getCodecRegistry().register(optionalDecimalCodec);
188+ cluster().getConfiguration().getCodecRegistry().register(optionalDecimalCodec);
191189
192- PreparedStatement stmt = session.prepare("insert into foo (c1, c2, c5) values (?,?,?)");
190+ PreparedStatement stmt = session().prepare("insert into foo (c1, c2, c5) values (?,?,?)");
193191
194192 BoundStatement bs = stmt.bind();
195193 bs.setString(0, "should_map_a_nullable_type_to_absent");
196194 bs.setString(1, "1");
197195 bs.set(2, Optional.<BigDecimal>absent(), optionalDecimalCodec.getJavaType());
198- session.execute(bs);
196+ session().execute(bs);
199197
200- PreparedStatement selectDecimal = session.prepare("select c1, c5 from foo where c1=?");
201- ResultSet results = session.execute(selectDecimal.bind("should_map_a_nullable_type_to_absent"));
198+ PreparedStatement selectDecimal = session().prepare("select c1, c5 from foo where c1=?");
199+ ResultSet results = session().execute(selectDecimal.bind("should_map_a_nullable_type_to_absent"));
202200
203201 assertThat(results.getAvailableWithoutFetching()).isEqualTo(1);
204202
modified driver-extras/src/test/java/com/datastax/driver/extras/codecs/jdk8/Jdk8TimeCodecsTest.java +18 −15
@@ -30,7 +30,10 @@
3030 import java.time.LocalDate;
3131 import java.time.LocalTime;
3232 import java.time.ZonedDateTime;
33-import java.util.*;
33+import java.util.Date;
34+import java.util.List;
35+import java.util.Map;
36+import java.util.Set;
3437
3538 import static com.datastax.driver.core.DataType.timestamp;
3639 import static com.datastax.driver.core.DataType.varchar;
@@ -42,8 +45,8 @@
4245 public class Jdk8TimeCodecsTest extends CCMTestsSupport {
4346
4447 @Override
45- public Collection<String> createTestFixtures() {
46- return Collections.singletonList(
48+ public void onTestContextInitialized() {
49+ execute(
4750 "CREATE TABLE IF NOT EXISTS foo ("
4851 + "c1 text PRIMARY KEY, "
4952 + "cdate date, "
@@ -59,8 +62,8 @@
5962
6063 @BeforeClass(groups = "short")
6164 public void registerCodecs() throws Exception {
62- TupleType dateWithTimeZoneType = cluster.getMetadata().newTupleType(timestamp(), varchar());
63- CodecRegistry codecRegistry = cluster.getConfiguration().getCodecRegistry();
65+ TupleType dateWithTimeZoneType = cluster().getMetadata().newTupleType(timestamp(), varchar());
66+ CodecRegistry codecRegistry = cluster().getConfiguration().getCodecRegistry();
6467 codecRegistry
6568 .register(LocalTimeCodec.instance)
6669 .register(LocalDateCodec.instance)
@@ -84,8 +87,8 @@
8487 // given
8588 LocalTime time = LocalTime.of(12, 16, 34, 999);
8689 // when
87- session.execute("insert into foo (c1, ctime) values (?, ?)", "should_map_time_to_localtime", time);
88- ResultSet result = session.execute("select ctime from foo where c1=?", "should_map_time_to_localtime");
90+ session().execute("insert into foo (c1, ctime) values (?, ?)", "should_map_time_to_localtime", time);
91+ ResultSet result = session().execute("select ctime from foo where c1=?", "should_map_time_to_localtime");
8992 // then
9093 assertThat(result.getAvailableWithoutFetching()).isEqualTo(1);
9194 Row row = result.one();
@@ -110,8 +113,8 @@
110113 LocalDate localDate = LocalDate.of(2015, 1, 1);
111114 com.datastax.driver.core.LocalDate driverLocalDate = com.datastax.driver.core.LocalDate.fromYearMonthDay(2015, 1, 1);
112115 // when
113- session.execute("insert into foo (c1, cdate) values (?, ?)", "should_map_date_to_localdate", localDate);
114- ResultSet result = session.execute("select cdate from foo where c1=?", "should_map_date_to_localdate");
116+ session().execute("insert into foo (c1, cdate) values (?, ?)", "should_map_date_to_localdate", localDate);
117+ ResultSet result = session().execute("select cdate from foo where c1=?", "should_map_date_to_localdate");
115118 // then
116119 assertThat(result.getAvailableWithoutFetching()).isEqualTo(1);
117120 Row row = result.one();
@@ -135,8 +138,8 @@
135138 // given
136139 Instant instant = Instant.parse("2010-06-30T01:20:30Z");
137140 // when
138- session.execute("insert into foo (c1, ctimestamp) values (?, ?)", "should_map_timestamp_to_instant", instant);
139- ResultSet result = session.execute("select ctimestamp from foo where c1=?", "should_map_timestamp_to_instant");
141+ session().execute("insert into foo (c1, ctimestamp) values (?, ?)", "should_map_timestamp_to_instant", instant);
142+ ResultSet result = session().execute("select ctimestamp from foo where c1=?", "should_map_timestamp_to_instant");
140143 // then
141144 assertThat(result.getAvailableWithoutFetching()).isEqualTo(1);
142145 Row row = result.one();
@@ -160,9 +163,9 @@
160163 // given
161164 ZonedDateTime expected = ZonedDateTime.parse("2010-06-30T01:20+05:30");
162165 // when
163- PreparedStatement insertStmt = session.prepare("insert into foo (c1, ctuple) values (?, ?)");
164- session.execute(insertStmt.bind("should_map_tuple_to_instant", expected));
165- ResultSet result = session.execute("select ctuple from foo where c1=?", "should_map_tuple_to_instant");
166+ PreparedStatement insertStmt = session().prepare("insert into foo (c1, ctuple) values (?, ?)");
167+ session().execute(insertStmt.bind("should_map_tuple_to_instant", expected));
168+ ResultSet result = session().execute("select ctuple from foo where c1=?", "should_map_tuple_to_instant");
166169 // then
167170 assertThat(result.getAvailableWithoutFetching()).isEqualTo(1);
168171 Row row = result.one();
@@ -177,7 +180,7 @@
177180 @Test(groups = "short")
178181 public void should_use_mapper_to_store_and_retrieve_values_with_custom_jdk8_codecs() {
179182 // given
180- MappingManager manager = new MappingManager(session);
183+ MappingManager manager = new MappingManager(session());
181184 Mapper<Mapped> mapper = manager.mapper(Mapped.class);
182185 // when
183186 Mapped pojo = new Mapped();
modified driver-extras/src/test/java/com/datastax/driver/extras/codecs/jdk8/OptionalCodecTest.java +24 −26
@@ -23,8 +23,6 @@
2323 import org.testng.annotations.Test;
2424
2525 import java.math.BigDecimal;
26-import java.util.Collection;
27-import java.util.Collections;
2826 import java.util.List;
2927 import java.util.Optional;
3028
@@ -43,8 +41,8 @@
4341 private BuiltStatement selectStmt;
4442
4543 @Override
46- public Collection<String> createTestFixtures() {
47- return Collections.singletonList("CREATE TABLE foo (c1 text, c2 text, c3 list<text>, c4 bigint, c5 decimal, PRIMARY KEY (c1, c2))");
44+ public void onTestContextInitialized() {
45+ execute("CREATE TABLE foo (c1 text, c2 text, c3 list<text>, c4 bigint, c5 decimal, PRIMARY KEY (c1, c2))");
4846 }
4947
5048 @Override
@@ -73,15 +71,15 @@
7371 @Test(groups = "short")
7472 @CassandraVersion(major = 2.2)
7573 public void should_map_unset_value_to_empty() {
76- PreparedStatement insertPrep = session.prepare(this.insertStmt);
77- PreparedStatement selectPrep = session.prepare(this.selectStmt);
74+ PreparedStatement insertPrep = session().prepare(this.insertStmt);
75+ PreparedStatement selectPrep = session().prepare(this.selectStmt);
7876
7977 BoundStatement bs = insertPrep.bind();
8078 bs.setString(0, "should_map_unset_value_to_empty");
8179 bs.setString(1, "1");
82- session.execute(bs);
80+ session().execute(bs);
8381
84- ResultSet results = session.execute(selectPrep.bind("should_map_unset_value_to_empty"));
82+ ResultSet results = session().execute(selectPrep.bind("should_map_unset_value_to_empty"));
8583 assertThat(results.getAvailableWithoutFetching()).isEqualTo(1);
8684
8785 Row row = results.one();
@@ -102,16 +100,16 @@
102100 */
103101 @Test(groups = "short")
104102 public void should_map_absent_null_value_to_empty() {
105- PreparedStatement insertPrep = session.prepare(this.insertStmt);
106- PreparedStatement selectPrep = session.prepare(this.selectStmt);
103+ PreparedStatement insertPrep = session().prepare(this.insertStmt);
104+ PreparedStatement selectPrep = session().prepare(this.selectStmt);
107105
108106 BoundStatement bs = insertPrep.bind();
109107 bs.setString(0, "should_map_absent_null_value_to_empty");
110108 bs.setString(1, "1");
111109 bs.set(2, Optional.<List<String>>empty(), optionalCodec.getJavaType());
112- session.execute(bs);
110+ session().execute(bs);
113111
114- ResultSet results = session.execute(selectPrep.bind("should_map_absent_null_value_to_empty"));
112+ ResultSet results = session().execute(selectPrep.bind("should_map_absent_null_value_to_empty"));
115113 assertThat(results.getAvailableWithoutFetching()).isEqualTo(1);
116114
117115 Row row = results.one();
@@ -134,8 +132,8 @@
134132 */
135133 @Test(groups = "short")
136134 public void should_map_some_back_to_itself() {
137- PreparedStatement insertPrep = session.prepare(this.insertStmt);
138- PreparedStatement selectPrep = session.prepare(this.selectStmt);
135+ PreparedStatement insertPrep = session().prepare(this.insertStmt);
136+ PreparedStatement selectPrep = session().prepare(this.selectStmt);
139137
140138 List<String> data = Lists.newArrayList("1", "2", "3");
141139
@@ -143,9 +141,9 @@
143141 bs.setString(0, "should_map_some_back_to_itself");
144142 bs.setString(1, "1");
145143 bs.set(2, Optional.of(data), optionalCodec.getJavaType());
146- session.execute(bs);
144+ session().execute(bs);
147145
148- ResultSet results = session.execute(selectPrep.bind("should_map_some_back_to_itself"));
146+ ResultSet results = session().execute(selectPrep.bind("should_map_some_back_to_itself"));
149147 assertThat(results.getAvailableWithoutFetching()).isEqualTo(1);
150148
151149 Row row = results.one();
@@ -163,18 +161,18 @@
163161 @Test(groups = "short")
164162 public void should_map_a_primitive_type_to_empty() {
165163 OptionalCodec<Long> optionalLongCodec = new OptionalCodec<Long>(bigint());
166- cluster.getConfiguration().getCodecRegistry().register(optionalLongCodec);
164+ cluster().getConfiguration().getCodecRegistry().register(optionalLongCodec);
167165
168- PreparedStatement stmt = session.prepare("insert into foo (c1, c2, c4) values (?,?,?)");
166+ PreparedStatement stmt = session().prepare("insert into foo (c1, c2, c4) values (?,?,?)");
169167
170168 BoundStatement bs = stmt.bind();
171169 bs.setString(0, "should_map_a_primitive_type_to_empty");
172170 bs.setString(1, "1");
173171 bs.set(2, Optional.<Long>empty(), optionalLongCodec.getJavaType());
174- session.execute(bs);
172+ session().execute(bs);
175173
176- PreparedStatement selectBigint = session.prepare("select c1, c4 from foo where c1=?");
177- ResultSet results = session.execute(selectBigint.bind("should_map_a_primitive_type_to_empty"));
174+ PreparedStatement selectBigint = session().prepare("select c1, c4 from foo where c1=?");
175+ ResultSet results = session().execute(selectBigint.bind("should_map_a_primitive_type_to_empty"));
178176
179177 assertThat(results.getAvailableWithoutFetching()).isEqualTo(1);
180178
@@ -187,18 +185,18 @@
187185 @Test(groups = "short")
188186 public void should_map_a_nullable_type_to_empty() {
189187 OptionalCodec<BigDecimal> optionalDecimalCodec = new OptionalCodec<BigDecimal>(decimal());
190- cluster.getConfiguration().getCodecRegistry().register(optionalDecimalCodec);
188+ cluster().getConfiguration().getCodecRegistry().register(optionalDecimalCodec);
191189
192- PreparedStatement stmt = session.prepare("insert into foo (c1, c2, c5) values (?,?,?)");
190+ PreparedStatement stmt = session().prepare("insert into foo (c1, c2, c5) values (?,?,?)");
193191
194192 BoundStatement bs = stmt.bind();
195193 bs.setString(0, "should_map_a_nullable_type_to_empty");
196194 bs.setString(1, "1");
197195 bs.set(2, Optional.<BigDecimal>empty(), optionalDecimalCodec.getJavaType());
198- session.execute(bs);
196+ session().execute(bs);
199197
200- PreparedStatement selectDecimal = session.prepare("select c1, c5 from foo where c1=?");
201- ResultSet results = session.execute(selectDecimal.bind("should_map_a_nullable_type_to_empty"));
198+ PreparedStatement selectDecimal = session().prepare("select c1, c5 from foo where c1=?");
199+ ResultSet results = session().execute(selectDecimal.bind("should_map_a_nullable_type_to_empty"));
202200
203201 assertThat(results.getAvailableWithoutFetching()).isEqualTo(1);
204202
modified driver-extras/src/test/java/com/datastax/driver/extras/codecs/joda/JodaTimeCodecsTest.java +17 −15
@@ -30,7 +30,9 @@
3030 import org.testng.annotations.BeforeClass;
3131 import org.testng.annotations.Test;
3232
33-import java.util.*;
33+import java.util.List;
34+import java.util.Map;
35+import java.util.Set;
3436
3537 import static com.datastax.driver.core.DataType.timestamp;
3638 import static com.datastax.driver.core.DataType.varchar;
@@ -44,8 +46,8 @@
4446 public class JodaTimeCodecsTest extends CCMTestsSupport {
4547
4648 @Override
47- public Collection<String> createTestFixtures() {
48- return Collections.singletonList(
49+ public void onTestContextInitialized() {
50+ execute(
4951 "CREATE TABLE IF NOT EXISTS foo ("
5052 + "c1 text PRIMARY KEY, "
5153 + "cdate date, "
@@ -61,8 +63,8 @@
6163
6264 @BeforeClass(groups = "short")
6365 public void registerCodecs() throws Exception {
64- TupleType dateWithTimeZoneType = cluster.getMetadata().newTupleType(timestamp(), varchar());
65- CodecRegistry codecRegistry = cluster.getConfiguration().getCodecRegistry();
66+ TupleType dateWithTimeZoneType = cluster().getMetadata().newTupleType(timestamp(), varchar());
67+ CodecRegistry codecRegistry = cluster().getConfiguration().getCodecRegistry();
6668 codecRegistry
6769 .register(LocalTimeCodec.instance)
6870 .register(LocalDateCodec.instance)
@@ -86,8 +88,8 @@
8688 // given
8789 LocalTime time = new LocalTime(12, 16, 34, 999);
8890 // when
89- session.execute("insert into foo (c1, ctime) values (?, ?)", "should_map_time_to_localtime", time);
90- ResultSet result = session.execute("select ctime from foo where c1=?", "should_map_time_to_localtime");
91+ session().execute("insert into foo (c1, ctime) values (?, ?)", "should_map_time_to_localtime", time);
92+ ResultSet result = session().execute("select ctime from foo where c1=?", "should_map_time_to_localtime");
9193 // then
9294 assertThat(result.getAvailableWithoutFetching()).isEqualTo(1);
9395 Row row = result.one();
@@ -112,8 +114,8 @@
112114 LocalDate localDate = new LocalDate(2015, 1, 1);
113115 com.datastax.driver.core.LocalDate driverLocalDate = com.datastax.driver.core.LocalDate.fromYearMonthDay(2015, 1, 1);
114116 // when
115- session.execute("insert into foo (c1, cdate) values (?, ?)", "should_map_date_to_localdate", localDate);
116- ResultSet result = session.execute("select cdate from foo where c1=?", "should_map_date_to_localdate");
117+ session().execute("insert into foo (c1, cdate) values (?, ?)", "should_map_date_to_localdate", localDate);
118+ ResultSet result = session().execute("select cdate from foo where c1=?", "should_map_date_to_localdate");
117119 // then
118120 assertThat(result.getAvailableWithoutFetching()).isEqualTo(1);
119121 Row row = result.one();
@@ -137,8 +139,8 @@
137139 // given
138140 Instant instant = Instant.parse("2010-06-30T01:20+05:00");
139141 // when
140- session.execute("insert into foo (c1, ctimestamp) values (?, ?)", "should_map_timestamp_to_datetime", instant);
141- ResultSet result = session.execute("select ctimestamp from foo where c1=?", "should_map_timestamp_to_datetime");
142+ session().execute("insert into foo (c1, ctimestamp) values (?, ?)", "should_map_timestamp_to_datetime", instant);
143+ ResultSet result = session().execute("select ctimestamp from foo where c1=?", "should_map_timestamp_to_datetime");
142144 // then
143145 assertThat(result.getAvailableWithoutFetching()).isEqualTo(1);
144146 Row row = result.one();
@@ -162,9 +164,9 @@
162164 // given
163165 DateTime expected = DateTime.parse("2010-06-30T01:20+05:30");
164166 // when
165- PreparedStatement insertStmt = session.prepare("insert into foo (c1, ctuple) values (?, ?)");
166- session.execute(insertStmt.bind("should_map_tuple_to_datetime", expected));
167- ResultSet result = session.execute("select ctuple from foo where c1=?", "should_map_tuple_to_datetime");
167+ PreparedStatement insertStmt = session().prepare("insert into foo (c1, ctuple) values (?, ?)");
168+ session().execute(insertStmt.bind("should_map_tuple_to_datetime", expected));
169+ ResultSet result = session().execute("select ctuple from foo where c1=?", "should_map_tuple_to_datetime");
168170 // then
169171 assertThat(result.getAvailableWithoutFetching()).isEqualTo(1);
170172 Row row = result.one();
@@ -178,7 +180,7 @@
178180 @Test(groups = "short")
179181 public void should_use_mapper_to_store_and_retrieve_values_with_custom_joda_codecs() {
180182 // given
181- MappingManager manager = new MappingManager(session);
183+ MappingManager manager = new MappingManager(session());
182184 Mapper<Mapped> mapper = manager.mapper(Mapped.class);
183185 // when
184186 Mapped pojo = new Mapped();
modified driver-extras/src/test/java/com/datastax/driver/extras/codecs/json/JacksonJsonCodecTest.java +14 −15
@@ -25,7 +25,6 @@
2525 import org.testng.annotations.Test;
2626
2727 import java.util.ArrayList;
28-import java.util.Collection;
2928
3029 import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
3130 import static org.assertj.core.api.Assertions.assertThat;
@@ -50,8 +49,8 @@
5049 private static final String notAJsonString = "this text is not json";
5150
5251 @Override
53- public Collection<String> createTestFixtures() {
54- return Lists.newArrayList(
52+ public void onTestContextInitialized() {
53+ execute(
5554 "CREATE TABLE t1 (c1 text, c2 text, c3 list<text>, PRIMARY KEY (c1, c2))"
5655 );
5756 }
@@ -84,8 +83,8 @@
8483 @Test(groups = "short")
8584 @CassandraVersion(major = 2.0)
8685 public void should_use_custom_codec_with_simple_statements() {
87- session.execute(insertQuery, notAJsonString, alice, bobAndCharlie);
88- ResultSet rows = session.execute(selectQuery, notAJsonString, alice);
86+ session().execute(insertQuery, notAJsonString, alice, bobAndCharlie);
87+ ResultSet rows = session().execute(selectQuery, notAJsonString, alice);
8988 Row row = rows.one();
9089 assertRow(row);
9190 }
@@ -100,8 +99,8 @@
10099 .from("t1")
101100 .where(eq("c1", bindMarker()))
102101 .and(eq("c2", bindMarker()));
103- session.execute(session.prepare(insertStmt).bind(notAJsonString, alice, bobAndCharlie));
104- ResultSet rows = session.execute(session.prepare(selectStmt).bind(notAJsonString, alice));
102+ session().execute(session().prepare(insertStmt).bind(notAJsonString, alice, bobAndCharlie));
103+ ResultSet rows = session().execute(session().prepare(selectStmt).bind(notAJsonString, alice));
105104 Row row = rows.one();
106105 assertRow(row);
107106 }
@@ -117,33 +116,33 @@
117116 .from("t1")
118117 .where(eq("c1", notAJsonString))
119118 .and(eq("c2", alice));
120- session.execute(insertStmt);
121- ResultSet rows = session.execute(selectStmt);
119+ session().execute(insertStmt);
120+ ResultSet rows = session().execute(selectStmt);
122121 Row row = rows.one();
123122 assertRow(row);
124123 }
125124
126125 @Test(groups = "short")
127126 public void should_use_custom_codec_with_prepared_statements_1() {
128- session.execute(session.prepare(insertQuery).bind(notAJsonString, alice, bobAndCharlie));
129- PreparedStatement ps = session.prepare(selectQuery);
127+ session().execute(session().prepare(insertQuery).bind(notAJsonString, alice, bobAndCharlie));
128+ PreparedStatement ps = session().prepare(selectQuery);
130129 // this bind() method does not convey information about the java type of alice
131130 // so the registry will look for a codec accepting varchar <-> ANY
132131 // and will find jsonCodec because it is the first registered
133- ResultSet rows = session.execute(ps.bind(notAJsonString, alice));
132+ ResultSet rows = session().execute(ps.bind(notAJsonString, alice));
134133 Row row = rows.one();
135134 assertRow(row);
136135 }
137136
138137 @Test(groups = "short")
139138 public void should_use_custom_codec_with_prepared_statements_2() {
140- session.execute(session.prepare(insertQuery).bind()
139+ session().execute(session().prepare(insertQuery).bind()
141140 .setString(0, notAJsonString)
142141 .set(1, alice, User.class)
143142 .setList(2, bobAndCharlie, User.class)
144143 );
145- PreparedStatement ps = session.prepare(selectQuery);
146- ResultSet rows = session.execute(ps.bind()
144+ PreparedStatement ps = session().prepare(selectQuery);
145+ ResultSet rows = session().execute(ps.bind()
147146 .setString(0, notAJsonString)
148147 // this set() method conveys information about the java type of alice
149148 // so the registry will look for a codec accepting varchar <-> User
modified driver-extras/src/test/java/com/datastax/driver/extras/codecs/json/Jsr353JsonCodecTest.java +14 −16
@@ -18,14 +18,12 @@
1818 import com.datastax.driver.core.*;
1919 import com.datastax.driver.core.querybuilder.BuiltStatement;
2020 import com.datastax.driver.core.utils.CassandraVersion;
21-import com.google.common.collect.Lists;
2221 import org.testng.annotations.DataProvider;
2322 import org.testng.annotations.Test;
2423
2524 import javax.json.*;
2625 import java.io.IOException;
2726 import java.io.StringWriter;
28-import java.util.Collection;
2927
3028 import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
3129 import static org.assertj.core.api.Assertions.assertThat;
@@ -46,8 +44,8 @@
4644 private static final String notAJsonString = "this text is not json";
4745
4846 @Override
49- public Collection<String> createTestFixtures() {
50- return Lists.newArrayList(
47+ public void onTestContextInitialized() {
48+ execute(
5149 "CREATE TABLE t1 (c1 text, c2 text, PRIMARY KEY (c1, c2))"
5250 );
5351 }
@@ -86,8 +84,8 @@
8684 @Test(groups = "short", dataProvider = "Jsr353JsonCodecTest")
8785 @CassandraVersion(major = 2.0)
8886 public void should_use_custom_codec_with_simple_statements(JsonStructure object) throws IOException {
89- session.execute(insertQuery, notAJsonString, object);
90- ResultSet rows = session.execute(selectQuery, notAJsonString, object);
87+ session().execute(insertQuery, notAJsonString, object);
88+ ResultSet rows = session().execute(selectQuery, notAJsonString, object);
9189 Row row = rows.one();
9290 assertRow(row, object);
9391 }
@@ -101,8 +99,8 @@
10199 .from("t1")
102100 .where(eq("c1", bindMarker()))
103101 .and(eq("c2", bindMarker()));
104- session.execute(session.prepare(insertStmt).bind(notAJsonString, object));
105- ResultSet rows = session.execute(session.prepare(selectStmt).bind(notAJsonString, object));
102+ session().execute(session().prepare(insertStmt).bind(notAJsonString, object));
103+ ResultSet rows = session().execute(session().prepare(selectStmt).bind(notAJsonString, object));
106104 Row row = rows.one();
107105 assertRow(row, object);
108106 }
@@ -117,29 +115,29 @@
117115 .from("t1")
118116 .where(eq("c1", notAJsonString))
119117 .and(eq("c2", object));
120- session.execute(insertStmt);
121- ResultSet rows = session.execute(selectStmt);
118+ session().execute(insertStmt);
119+ ResultSet rows = session().execute(selectStmt);
122120 Row row = rows.one();
123121 assertRow(row, object);
124122 }
125123
126124 @Test(groups = "short", dataProvider = "Jsr353JsonCodecTest")
127125 public void should_use_custom_codec_with_prepared_statements_1(JsonStructure object) throws IOException {
128- session.execute(session.prepare(insertQuery).bind(notAJsonString, object));
129- PreparedStatement ps = session.prepare(selectQuery);
130- ResultSet rows = session.execute(ps.bind(notAJsonString, object));
126+ session().execute(session().prepare(insertQuery).bind(notAJsonString, object));
127+ PreparedStatement ps = session().prepare(selectQuery);
128+ ResultSet rows = session().execute(ps.bind(notAJsonString, object));
131129 Row row = rows.one();
132130 assertRow(row, object);
133131 }
134132
135133 @Test(groups = "short", dataProvider = "Jsr353JsonCodecTest")
136134 public void should_use_custom_codec_with_prepared_statements_2(JsonStructure object) throws IOException {
137- session.execute(session.prepare(insertQuery).bind()
135+ session().execute(session().prepare(insertQuery).bind()
138136 .setString(0, notAJsonString)
139137 .set(1, object, JsonStructure.class)
140138 );
141- PreparedStatement ps = session.prepare(selectQuery);
142- ResultSet rows = session.execute(ps.bind()
139+ PreparedStatement ps = session().prepare(selectQuery);
140+ ResultSet rows = session().execute(ps.bind()
143141 .setString(0, notAJsonString)
144142 .set(1, object, JsonStructure.class)
145143 );
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperAccessorParamsTest.java +11 −14
@@ -19,19 +19,16 @@
1919 import com.datastax.driver.core.Row;
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.annotations.Test;
2423
25-import java.util.Collection;
26-
2724 import static org.assertj.core.api.Assertions.assertThat;
2825
2926 @SuppressWarnings("unused")
3027 public class MapperAccessorParamsTest extends CCMTestsSupport {
3128
3229 @Override
33- public Collection<String> createTestFixtures() {
34- return Lists.newArrayList(
30+ public void onTestContextInitialized() {
31+ execute(
3532 "CREATE TABLE user ( key int primary key, gender int, home_phone text, work_phone text)",
3633 "CREATE INDEX on user(gender)",
3734 "CREATE TABLE user_str ( key int primary key, gender text)",
@@ -42,44 +39,44 @@
4239 @Test(groups = "short")
4340 @CassandraVersion(major = 2.0, description = "Uses named parameters")
4441 public void should_allow_less_parameters_than_bind_markers_if_there_are_repeated_names() {
45- UserPhoneAccessor accessor = new MappingManager(session)
42+ UserPhoneAccessor accessor = new MappingManager(session())
4643 .createAccessor(UserPhoneAccessor.class);
4744
48- session.execute("delete from user where key = 0");
45+ session().execute("delete from user where key = 0");
4946 accessor.updatePhones_positional("1111", "2222", 0);
5047 assertPhonesEqual(0, "1111", "2222");
5148
52- session.execute("delete from user where key = 0");
49+ session().execute("delete from user where key = 0");
5350 accessor.updatePhones_named(0, "1111", "2222");
5451 assertPhonesEqual(0, "1111", "2222");
5552
56- session.execute("delete from user where key = 0");
53+ session().execute("delete from user where key = 0");
5754 accessor.updatePhones_fallback("1111", "2222", 0);
5855 assertPhonesEqual(0, "1111", "2222");
5956
60- session.execute("delete from user where key = 0");
57+ session().execute("delete from user where key = 0");
6158 accessor.updateBothPhones(0, "1111");
6259 assertPhonesEqual(0, "1111", "1111");
6360
64- session.execute("delete from user where key = 0");
61+ session().execute("delete from user where key = 0");
6562 accessor.updatePhones_fallback2("1111", "2222", 0);
6663 assertPhonesEqual(0, "1111", "2222");
6764 }
6865
6966 @Test(groups = "short", expectedExceptions = RuntimeException.class)
7067 public void should_fail_if_not_enough_parameters() {
71- new MappingManager(session)
68+ new MappingManager(session())
7269 .createAccessor(UserPhoneAccessor_NotEnoughParams.class);
7370 }
7471
7572 @Test(groups = "short", expectedExceptions = RuntimeException.class)
7673 public void should_fail_if_too_many_parameters() {
77- new MappingManager(session)
74+ new MappingManager(session())
7875 .createAccessor(UserPhoneAccessor_TooManyParams.class);
7976 }
8077
8178 private void assertPhonesEqual(int key, String home, String work) {
82- Row row = session.execute("select * from user where key = " + key).one();
79+ Row row = session().execute("select * from user where key = " + key).one();
8380 assertThat(row.getString("home_phone")).isEqualTo(home);
8481 assertThat(row.getString("work_phone")).isEqualTo(work);
8582 }
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
@@ -20,13 +20,10 @@
2020 import com.datastax.driver.core.exceptions.InvalidQueryException;
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.SkipException;
2524 import org.testng.annotations.BeforeMethod;
2625 import org.testng.annotations.Test;
2726
28-import java.util.Collection;
29-
3027 import static com.datastax.driver.core.Assertions.assertThat;
3128 import static com.datastax.driver.core.ProtocolVersion.V1;
3229 import static org.assertj.core.api.Assertions.fail;
@@ -39,8 +36,8 @@
3936 public class MapperComputedFieldsTest extends CCMTestsSupport {
4037
4138 @Override
42- public Collection<String> createTestFixtures() {
43- return Lists.newArrayList(
39+ public void onTestContextInitialized() {
40+ execute(
4441 "CREATE TABLE user (login text primary key, name text)",
4542 "INSERT INTO user (login, name) VALUES ('testlogin', 'test name')");
4643 }
@@ -51,8 +48,8 @@
5148
5249 @BeforeMethod(groups = "short")
5350 void setup() {
54- mappingManager = new MappingManager(session);
55- protocolVersion = cluster.getConfiguration().getProtocolOptions().getProtocolVersion();
51+ mappingManager = new MappingManager(session());
52+ protocolVersion = cluster().getConfiguration().getProtocolOptions().getProtocolVersion();
5653 if (protocolVersion.compareTo(V1) > 0)
5754 userMapper = mappingManager.mapper(User.class);
5855 }
@@ -82,7 +79,7 @@
8279 assertThat(fetched.getTtl()).isNull(); // TTL should be null since it was not set.
8380
8481 // Overwrite with TTL
85- session.execute("insert into user (login, name) values ('testlogin2', 'blah') using TTL 600");
82+ session().execute("insert into user (login, name) values ('testlogin2', 'blah') using TTL 600");
8683 fetched = userMapper.get("testlogin2");
8784 assertThat(fetched.getWriteTime()).isGreaterThanOrEqualTo(writeTime).isLessThan(writeTime + 30000000L);
8885 assertThat(fetched.getTtl()).isBetween(570, 600); // TTL should be within 30 secs.
@@ -104,7 +101,7 @@
104101 public void should_map_aliased_resultset_to_objects() {
105102 Statement getQuery = userMapper.getQuery("testlogin");
106103 getQuery.setConsistencyLevel(ConsistencyLevel.QUORUM);
107- ResultSet rs = session.execute(getQuery);
104+ ResultSet rs = session().execute(getQuery);
108105
109106 Result<User> result = userMapper.mapAliased(rs);
110107 User user = result.one();
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperCustomCodecTest.java +18 −19
@@ -22,7 +22,6 @@
2222 import com.google.common.base.Optional;
2323 import com.google.common.base.Predicate;
2424 import com.google.common.collect.ImmutableMap;
25-import com.google.common.collect.Lists;
2625 import com.google.common.reflect.TypeParameter;
2726 import com.google.common.reflect.TypeToken;
2827 import org.testng.annotations.Test;
@@ -39,8 +38,8 @@
3938 public class MapperCustomCodecTest extends CCMTestsSupport {
4039
4140 @Override
42- public Collection<String> createTestFixtures() {
43- return Lists.newArrayList(
41+ public void onTestContextInitialized() {
42+ execute(
4443 // Columns mapped to custom types
4544 "CREATE TABLE data1 (i int PRIMARY KEY, l bigint)",
4645 "INSERT INTO data1 (i, l) VALUES (1, 11)",
@@ -65,7 +64,7 @@
6564
6665 @Test(groups = "short")
6766 public void should_use_custom_codecs_with_basic_operations() {
68- Mapper<Data1> mapper = new MappingManager(session).mapper(Data1.class);
67+ Mapper<Data1> mapper = new MappingManager(session()).mapper(Data1.class);
6968
7069 // Get
7170 Data1 data11 = mapper.get(new CustomInt(1));
@@ -78,25 +77,25 @@
7877 data12.setL(new CustomLong(12));
7978 mapper.save(data12);
8079
81- Row row = session.execute("select * from data1 where i = 2").one();
80+ Row row = session().execute("select * from data1 where i = 2").one();
8281 assertThat(row.getInt(0)).isEqualTo(2);
8382 assertThat(row.getLong(1)).isEqualTo(12);
8483
8584 // Delete
8685 mapper.delete(new CustomInt(2));
87- row = session.execute("select * from data1 where i = 2").one();
86+ row = session().execute("select * from data1 where i = 2").one();
8887 assertThat(row).isNull();
8988 }
9089
9190 @Test(groups = "short")
9291 public void should_use_custom_codecs_with_accessors() {
93- Data1Accessor accessor = new MappingManager(session).createAccessor(Data1Accessor.class);
92+ Data1Accessor accessor = new MappingManager(session()).createAccessor(Data1Accessor.class);
9493 Data1 data1 = accessor.get(new CustomInt(1));
9594 assertThat(data1.getI()).isEqualTo(new CustomInt(1));
9695 assertThat(data1.getL()).isEqualTo(new CustomLong(11));
9796
9897 accessor.setL(1, new CustomLong(12));
99- Row row = session.execute("select l from data1 where i = 1").one();
98+ Row row = session().execute("select l from data1 where i = 1").one();
10099 assertThat(row.getLong(0)).isEqualTo(12);
101100
102101 accessor.setL(1, new CustomLong(11));
@@ -104,7 +103,7 @@
104103
105104 @Test(groups = "short")
106105 public void should_use_custom_codecs_in_UDTs() {
107- Mapper<Data2> mapper = new MappingManager(session).mapper(Data2.class);
106+ Mapper<Data2> mapper = new MappingManager(session()).mapper(Data2.class);
108107
109108 // Get
110109 Data2 data21 = mapper.get(1);
@@ -117,7 +116,7 @@
117116 data22.setData(new Holder(2, 22));
118117 mapper.save(data22);
119118
120- Row row = session.execute("select * from data2 where i = 2").one();
119+ Row row = session().execute("select * from data2 where i = 2").one();
121120 assertThat(row.getUDTValue(1).getInt("i")).isEqualTo(2);
122121 assertThat(row.getUDTValue(1).getLong("l")).isEqualTo(22);
123122
@@ -127,7 +126,7 @@
127126
128127 @Test(groups = "short")
129128 public void should_use_custom_codecs_in_nested_structures() {
130- Mapper<Data3> mapper = new MappingManager(session).mapper(Data3.class);
129+ Mapper<Data3> mapper = new MappingManager(session()).mapper(Data3.class);
131130
132131 // Get
133132 Data3 data31 = mapper.get(1);
@@ -140,7 +139,7 @@
140139 data32.setData(ImmutableMap.of(new CustomInt(2), new Holder(2, 22)));
141140 mapper.save(data32);
142141
143- Row row = session.execute("select * from data3 where i = 2").one();
142+ Row row = session().execute("select * from data3 where i = 2").one();
144143 Map<Integer, UDTValue> data = row.getMap(1, Integer.class, UDTValue.class);
145144 assertThat(data.containsKey(2));
146145 assertThat(data.get(2).getInt("i")).isEqualTo(2);
@@ -152,12 +151,12 @@
152151
153152 @Test(groups = "short", expectedExceptions = IllegalArgumentException.class)
154153 public void should_fail_when_invalid_codec_with_no_default_ctor_provided() {
155- new MappingManager(session).mapper(Data1InvalidCodecNoDefaultConstructor.class);
154+ new MappingManager(session()).mapper(Data1InvalidCodecNoDefaultConstructor.class);
156155 }
157156
158157 @Test(groups = "short", expectedExceptions = InvalidTypeException.class)
159158 public void should_fail_when_invalid_codec_type_mapping() {
160- Mapper<Data1InvalidCodecTypeMapping> mapper = new MappingManager(session).mapper(Data1InvalidCodecTypeMapping.class);
159+ Mapper<Data1InvalidCodecTypeMapping> mapper = new MappingManager(session()).mapper(Data1InvalidCodecTypeMapping.class);
161160
162161 // Get should return an InvalidTypeException.
163162 try {
@@ -176,12 +175,12 @@
176175
177176 @Test(groups = "short", expectedExceptions = IllegalArgumentException.class)
178177 public void should_fail_when_invalid_codec_with_no_default_ctor_provided_in_accessor() {
179- new MappingManager(session).createAccessor(Data1AccessorNoDefaultConstructor.class);
178+ new MappingManager(session()).createAccessor(Data1AccessorNoDefaultConstructor.class);
180179 }
181180
182181 @Test(groups = "short", expectedExceptions = InvalidTypeException.class)
183182 public void should_fail_when_invalid_codec_type_mapping_in_accessor() {
184- Data1AccessorInvalidCodecTypeMapping accessor = new MappingManager(session).createAccessor(Data1AccessorInvalidCodecTypeMapping.class);
183+ Data1AccessorInvalidCodecTypeMapping accessor = new MappingManager(session()).createAccessor(Data1AccessorInvalidCodecTypeMapping.class);
185184
186185 // Get should return an InvalidTypeException.
187186 try {
@@ -196,7 +195,7 @@
196195
197196 @Test(groups = "short")
198197 public void should_be_able_to_use_parameterized_type() {
199- Mapper<Data1ParameterizedType> mapper = new MappingManager(session).mapper(Data1ParameterizedType.class);
198+ Mapper<Data1ParameterizedType> mapper = new MappingManager(session()).mapper(Data1ParameterizedType.class);
200199
201200 Data1ParameterizedType data1 = mapper.get(1);
202201 assertThat(data1.getL()).isEqualTo(Optional.of(11L));
@@ -212,7 +211,7 @@
212211 assertThat(empty1r.getL()).isEqualTo(Optional.<Long>absent());
213212
214213 // Value should come back absent with codec, otherwise null with getObject, 0 with getLong.
215- Row row = session.execute("select l from data1 where i=1000").one();
214+ Row row = session().execute("select l from data1 where i=1000").one();
216215 assertThat(row.getObject(0)).isEqualTo(null); // should map to long codec and return null.
217216 assertThat(row.getLong(0)).isEqualTo(0L); // default boxed primitive value.
218217 assertThat(row.get(0, new OptionalOfLong())).isEqualTo(Optional.<Long>absent());
@@ -224,7 +223,7 @@
224223 mapper.save(present1);
225224
226225 // Value should come back present with codec, otherwise 20L.
227- row = session.execute("select l from data1 where i=1001").one();
226+ row = session().execute("select l from data1 where i=1001").one();
228227 assertThat(row.getObject(0)).isEqualTo(20L); // should map to long codec.
229228 assertThat(row.getLong(0)).isEqualTo(20L);
230229 assertThat(row.get(0, new OptionalOfLong())).isEqualTo(Optional.of(20L));
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperDefaultKeyspaceTest.java +8 −10
@@ -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 String.format("CREATE KEYSPACE IF NOT EXISTS %s WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 }", KEYSPACE),
4644 String.format("CREATE TYPE IF NOT EXISTS %s.group_name (name text)", KEYSPACE),
4745 String.format("CREATE TABLE IF NOT EXISTS %s.groups (group_id uuid PRIMARY KEY, name text)", KEYSPACE),
@@ -51,9 +49,9 @@
5149 @Test(groups = "short")
5250 public void testTableWithDefaultKeyspace() throws Exception {
5351 // Ensure that the test session is logged into the keyspace.
54- session.execute("USE " + KEYSPACE);
52+ session().execute("USE " + KEYSPACE);
5553
56- MappingManager manager = new MappingManager(session);
54+ MappingManager manager = new MappingManager(session());
5755 Mapper<Group> m = manager.mapper(Group.class);
5856 Group group = new Group("testGroup");
5957 UUID groupId = group.getGroupId();
@@ -73,9 +71,9 @@
7371 @Test(groups = "short")
7472 public void testUDTWithDefaultKeyspace() throws Exception {
7573 // Ensure that the test session is logged into the keyspace.
76- session.execute("USE " + KEYSPACE);
74+ session().execute("USE " + KEYSPACE);
7775
78- MappingManager manager = new MappingManager(session);
76+ MappingManager manager = new MappingManager(session());
7977 Mapper<Group2> m = manager.mapper(Group2.class);
8078 Group2 group = new Group2(new GroupName("testGroup"));
8179 UUID groupId = group.getGroupId();
@@ -96,7 +94,7 @@
9694 expectedExceptions = IllegalArgumentException.class,
9795 expectedExceptionsMessageRegExp = "Error creating mapper for class Group, the @Table annotation declares no default keyspace, and the session is not currently logged to any keyspace")
9896 public void should_throw_a_meaningful_error_message_when_no_default_table_keyspace_and_session_not_logged() {
99- Session session2 = cluster.connect();
97+ Session session2 = cluster().connect();
10098 MappingManager manager = new MappingManager(session2);
10199 manager.mapper(Group.class);
102100 }
@@ -105,7 +103,7 @@
105103 expectedExceptions = IllegalArgumentException.class,
106104 expectedExceptionsMessageRegExp = "Error creating UDT codec for class GroupName, the @UDT annotation declares no default keyspace, and the session is not currently logged to any keyspace")
107105 public void should_throw_a_meaningful_error_message_when_no_default_udt_keyspace_and_session_not_logged() {
108- Session session2 = cluster.connect();
106+ Session session2 = cluster().connect();
109107 MappingManager manager = new MappingManager(session2);
110108 manager.udtCodec(GroupName.class);
111109 }
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperMaterializedViewTest.java +6 −5
@@ -24,19 +24,19 @@
2424 import org.testng.annotations.BeforeMethod;
2525 import org.testng.annotations.Test;
2626
27-import java.util.Collection;
2827 import java.util.Iterator;
2928
30-import static com.google.common.collect.Lists.newArrayList;
3129 import static org.assertj.core.api.Assertions.assertThat;
3230
31+@SuppressWarnings("unused")
3332 @CassandraVersion(major = 3.0)
3433 public class MapperMaterializedViewTest extends CCMTestsSupport {
3534
35+
3636 @Override
37- public Collection<String> createTestFixtures() {
37+ public void onTestContextInitialized() {
3838 // Example schema taken from: http://www.datastax.com/dev/blog/new-in-cassandra-3-0-materialized-views
39- return newArrayList(
39+ execute(
4040 "CREATE TABLE scores (user TEXT, game TEXT, year INT, month INT, day INT, score INT, PRIMARY KEY(user, game, year, month, day))",
4141 "CREATE MATERIALIZED VIEW alltimehigh AS\n"
4242 + " SELECT * FROM scores\n"
@@ -77,7 +77,7 @@
7777
7878 @BeforeMethod(groups = "short")
7979 public void setUp() {
80- accessor = new MappingManager(session).createAccessor(ScoreAccessor.class);
80+ accessor = new MappingManager(session()).createAccessor(ScoreAccessor.class);
8181 }
8282
8383 /**
@@ -243,6 +243,7 @@
243243 '}';
244244 }
245245
246+ @SuppressWarnings("SimplifiableIfStatement")
246247 @Override
247248 public boolean equals(Object o) {
248249 if (this == o)
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().getProtocolVersion();
49+ mapper = new MappingManager(session()).mapper(User.class);
50+ protocolVersion = cluster().getConfiguration().getProtocolOptions().getProtocolVersion();
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/MapperPrimitiveTypes22Test.java +4 −5
@@ -24,16 +24,15 @@
2424 import org.testng.annotations.Test;
2525
2626 import java.nio.ByteBuffer;
27-import java.util.Collection;
28-import java.util.Collections;
2927
3028 import static org.testng.Assert.assertEquals;
3129
3230 @CassandraVersion(major = 2.2)
3331 public class MapperPrimitiveTypes22Test extends CCMTestsSupport {
3432
35- public Collection<String> createTestFixtures() {
36- return Collections.singletonList("CREATE TABLE primitiveTypes22 ("
33+ @Override
34+ public void onTestContextInitialized() {
35+ execute("CREATE TABLE primitiveTypes22 ("
3736 + "byteBufferCol blob primary key,"
3837 + "localDateCol date,"
3938 + "timeCol time, timeWrapperCol time,"
@@ -62,7 +61,7 @@
6261 primitiveTypes.setShortCol(shortCol);
6362 primitiveTypes.setShortWrapperCol(shortWrapperCol);
6463
65- Mapper<PrimitiveTypes22> mapper = new MappingManager(session).mapper(PrimitiveTypes22.class);
64+ Mapper<PrimitiveTypes22> mapper = new MappingManager(session()).mapper(PrimitiveTypes22.class);
6665 mapper.save(primitiveTypes);
6766 PrimitiveTypes22 primitiveTypes2 = mapper.get(byteBufferCol);
6867
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
@@ -282,7 +285,7 @@
282285 // Very simple mapping a User, saving and getting it. Note that here we
283286 // don't use the Accessor stuff since the queries we use are directly
284287 // supported by the Mapper object.
285- Mapper<User> m = new MappingManager(session).mapper(User.class);
288+ Mapper<User> m = new MappingManager(session()).mapper(User.class);
286289
287290 User u1 = new User("Paul", "paul@yahoo.com");
288291 u1.setYear(2014);
@@ -298,7 +301,7 @@
298301 @Test(groups = "short")
299302 @CassandraVersion(major = 2.0)
300303 public void testDynamicEntity() throws Exception {
301- MappingManager manager = new MappingManager(session);
304+ MappingManager manager = new MappingManager(session());
302305
303306 Mapper<Post> m = manager.mapper(Post.class);
304307
@@ -358,7 +361,7 @@
358361
359362 @Test(groups = "short")
360363 public void should_map_objects_from_partial_queries() throws Exception {
361- MappingManager manager = new MappingManager(session);
364+ MappingManager manager = new MappingManager(session());
362365
363366 Mapper<Post> m = manager.mapper(Post.class);
364367
@@ -376,7 +379,7 @@
376379 m.save(p3);
377380
378381 // Retrieve posts with a projection query that only retrieves some of the fields
379- ResultSet rs = session.execute("select user_id, post_id, title from posts where user_id = " + u1.getUserId());
382+ ResultSet rs = session().execute("select user_id, post_id, title from posts where user_id = " + u1.getUserId());
380383
381384 Result<Post> result = m.map(rs);
382385 for (Post post : result) {
@@ -389,13 +392,13 @@
389392 }
390393
391394 // cleanup
392- session.execute("delete from posts where user_id = " + u1.getUserId());
395+ session().execute("delete from posts where user_id = " + u1.getUserId());
393396 }
394397
395398
396399 @Test(groups = "short")
397400 public void should_return_table_metadata() throws Exception {
398- MappingManager manager = new MappingManager(session);
401+ MappingManager manager = new MappingManager(session());
399402
400403 Mapper<Post> m = manager.mapper(Post.class);
401404
@@ -406,7 +409,7 @@
406409
407410 @Test(groups = "short")
408411 public void should_not_initialize_session_when_protocol_version_provided() {
409- Session newSession = cluster.newSession();
412+ Session newSession = cluster().newSession();
410413
411414 // Ensures that a Session is not initialized when a protocol version is provided.
412415 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, " +
4042 "l list<frozen<\"Sub\">>, " +
4143 "s set<frozen<\"Sub\">>, " +
@@ -179,7 +181,7 @@
179181
180182 @Test(groups = "short")
181183 public void testCollections() throws Exception {
182- Mapper<CollectionExamples> m = new MappingManager(session).mapper(CollectionExamples.class);
184+ Mapper<CollectionExamples> m = new MappingManager(session()).mapper(CollectionExamples.class);
183185
184186 CollectionExamples c = new CollectionExamples(1, 1);
185187 m.save(c);
@@ -189,7 +191,7 @@
189191
190192 @Test(groups = "short")
191193 public void testNullCollection() {
192- Mapper<CollectionExamples> m = new MappingManager(session).mapper(CollectionExamples.class);
194+ Mapper<CollectionExamples> m = new MappingManager(session()).mapper(CollectionExamples.class);
193195
194196 CollectionExamples c = new CollectionExamples(1, 1);
195197 c.setL(null);
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperUDTTest.java +9 −9
@@ -35,14 +35,14 @@
3535 public class MapperUDTTest extends CCMTestsSupport {
3636
3737 @Override
38- public Collection<String> createTestFixtures() {
39- return Arrays.asList("CREATE TYPE address (street text, city text, \"ZIP_code\" int, phones set<text>)",
38+ public void onTestContextInitialized() {
39+ execute("CREATE TYPE address (street text, city text, \"ZIP_code\" int, phones set<text>)",
4040 "CREATE TABLE users (user_id uuid PRIMARY KEY, name text, mainaddress frozen<address>, other_addresses map<text,frozen<address>>)");
4141 }
4242
4343 @BeforeMethod(groups = "short")
4444 public void clean() {
45- session.execute("TRUNCATE users");
45+ session().execute("TRUNCATE users");
4646 }
4747
4848 @Table(name = "users",
@@ -245,7 +245,7 @@
245245
246246 @Test(groups = "short")
247247 public void testSimpleEntity() throws Exception {
248- Mapper<User> m = new MappingManager(session).mapper(User.class);
248+ Mapper<User> m = new MappingManager(session()).mapper(User.class);
249249
250250 User u1 = new User("Paul", new Address("12 4th Street", "Springfield", 12345, "12341343", "435423245"));
251251 u1.addOtherAddress("work", new Address("5 Main Street", "Springfield", 12345, "23431342"));
@@ -256,7 +256,7 @@
256256
257257 @Test(groups = "short")
258258 public void should_handle_null_UDT_value() throws Exception {
259- Mapper<User> m = new MappingManager(session).mapper(User.class);
259+ Mapper<User> m = new MappingManager(session()).mapper(User.class);
260260
261261 User u1 = new User("Paul", null);
262262 m.save(u1);
@@ -266,9 +266,9 @@
266266
267267 @Test(groups = "short")
268268 public void testAccessor() throws Exception {
269- MappingManager manager = new MappingManager(session);
269+ MappingManager manager = new MappingManager(session());
270270
271- Mapper<User> m = new MappingManager(session).mapper(User.class);
271+ Mapper<User> m = new MappingManager(session()).mapper(User.class);
272272 User u1 = new User("Paul", new Address("12 4th Street", "Springfield", 12345, "12341343", "435423245"));
273273 m.save(u1);
274274
@@ -309,8 +309,8 @@
309309 public void should_be_able_to_use_udtCodec_standalone() {
310310 // Create a separate Cluster/Session to start with a CodecRegistry from scratch (so not already registered).
311311 Cluster cluster = register(Cluster.builder()
312- .addContactPointsWithPorts(getInitialContactPoints())
313- .withPort(ccm.getBinaryPort())
312+ .addContactPoints(getContactPoints())
313+ .withPort(ccm().getBinaryPort())
314314 .build());
315315 CodecRegistry registry = cluster.getConfiguration().getCodecRegistry();
316316 Session session = cluster.connect(keyspace);
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);