Elffuss BraidHub

kikocis/java-driver public

Merge pull request #275 from tolbertam/CorePoolTestFixes

Fix Integration Tests that were assuming 2 default core connections or depending on onUp for a new node
Changesetb1ca3ae13f03619da6d70c23fb749e9026b0827088e0435fdb7d2164dda6b07e
AuthorOlivier Michallat <olim7t@users.noreply.github.com> · 2015-02-13 14:28 +01:00
CommitterOlivier Michallat <olim7t@users.noreply.github.com> · 2015-02-13 14:28 +01:00
Parents895c38bf77aa, a2da54e31385

Browse the files at this changeset

18 files changed

modified driver-core/src/main/java/com/datastax/driver/core/Host.java +9 −6
@@ -205,14 +205,17 @@
205205 }
206206
207207 /**
208- * Triggers an asynchronous one-time reconnection attempt to this host.
208+ * Triggers an asynchronous reconnection attempt to this host.
209209 * <p>
210- * If reconnection succeeds, the host will be marked {@code UP} and its connection pool(s)
211- * will be initialized (unless the load balancing policy returns {@link HostDistance#IGNORED}
212- * for it). If reconnection fails, no further attempts will be scheduled.
210+ * This method is intended for load balancing policies that mark hosts as {@link HostDistance#IGNORED IGNORED},
211+ * but still need a way to periodically check these hosts' states (UP / DOWN).
213212 * <p>
214- * This method has no effect if the node is already {@code UP}, or if a reconnection attempt
215- * is already in progress.
213+ * For a host that is at distance {@code IGNORED}, this method will try to reconnect exactly once: if
214+ * reconnection succeeds, the host is marked {@code UP}; otherwise, no further attempts will be scheduled.
215+ * It has no effect if the node is already {@code UP}, or if a reconnection attempt is already in progress.
216+ * <p>
217+ * Note that if the host is <em>not</em> a distance {@code IGNORED}, this method <em>will</em> trigger a periodic
218+ * reconnection attempt if the reconnection fails.
216219 */
217220 public void tryReconnectOnce() {
218221 this.manager.startSingleReconnectionAttempt(this);
modified driver-core/src/test/java/com/datastax/driver/core/BatchStatementTest.java +4 −5
@@ -20,12 +20,12 @@
2020
2121 import org.testng.annotations.Test;
2222
23-import com.datastax.driver.core.exceptions.UnsupportedFeatureException;
24-
25-import static com.datastax.driver.core.TestUtils.versionCheck;
2623 import static org.testng.Assert.assertEquals;
2724 import static org.testng.Assert.assertTrue;
2825
26+import com.datastax.driver.core.exceptions.UnsupportedFeatureException;
27+import com.datastax.driver.core.utils.CassandraVersion;
28+
2929 public class BatchStatementTest extends CCMBridge.PerClassSingleNodeCluster {
3030
3131 @Override
@@ -80,9 +80,8 @@
8080 }
8181
8282 @Test(groups = "short")
83+ @CassandraVersion(major=2.0, minor=9, description="This will only work with C* 2.0.9 (CASSANDRA-7337)")
8384 public void casBatchTest() throws Throwable {
84- versionCheck(2.0, 9, "This will only work with C* 2.0.9 (CASSANDRA-7337)");
85-
8685 try {
8786 PreparedStatement st = session.prepare("INSERT INTO test (k, v) VALUES (?, ?) IF NOT EXISTS");
8887
modified driver-core/src/test/java/com/datastax/driver/core/ClusterInitTest.java +20 −11
@@ -18,10 +18,13 @@
1818 import static org.mockito.Mockito.verify;
1919
2020 import com.datastax.driver.core.policies.ConstantReconnectionPolicy;
21+import com.datastax.driver.core.querybuilder.Insert;
2122 import com.datastax.driver.core.utils.UUIDs;
2223
2324 import static com.datastax.driver.core.FakeHost.Behavior.THROWING_CONNECT_TIMEOUTS;
2425
26+import static com.datastax.driver.core.querybuilder.QueryBuilder.insertInto;
27+
2528 public class ClusterInitTest {
2629 private static final Logger logger = LoggerFactory.getLogger(ClusterInitTest.class);
2730
@@ -68,6 +71,7 @@
6871 CCMBridge.ipOfNode(4), CCMBridge.ipOfNode(5), CCMBridge.ipOfNode(6))
6972 .withSocketOptions(socketOptions)
7073 .withReconnectionPolicy(reconnectionPolicy)
74+ .withProtocolVersion(TestUtils.getDesiredProtocolVersion())
7175 .build();
7276 cluster.connect();
7377
@@ -75,9 +79,12 @@
7579 long initTimeMs = TimeUnit.MILLISECONDS.convert(System.nanoTime() - start, TimeUnit.NANOSECONDS);
7680 logger.info("Cluster and session initialized in {} ms", initTimeMs);
7781
78- // We have one live host so 3 successful connections (1 control connection and 2 core connections in the pool).
82+ // We have one live host so we expect 1 control connection + core connection count successful connections.
7983 // The other 5 hosts are unreachable, we should attempt to connect to each of them only once.
80- verify(socketOptions, times(3 + 5)).getKeepAlive();
84+ int coreConnections = cluster.getConfiguration()
85+ .getPoolingOptions()
86+ .getCoreConnectionsPerHost(HostDistance.LOCAL);
87+ verify(socketOptions, times(1 + coreConnections + 5)).getKeepAlive();
8188 } finally {
8289 if (cluster != null)
8390 cluster.close();
@@ -97,15 +104,17 @@
97104 String releaseVersion = session.execute("SELECT release_version FROM local")
98105 .one().getString("release_version");
99106
100- for (int i = 2; i <= 6; i++)
101- session.execute("INSERT INTO peers (peer, data_center, host_id, rack, release_version, rpc_address, schema_version) " +
102- "VALUES (?, 'datacenter1', ?, 'rack1', ?, ?, ?)",
103- InetAddress.getByName(CCMBridge.ipOfNode(i)),
104- UUIDs.random(),
105- releaseVersion,
106- InetAddress.getByName(CCMBridge.ipOfNode(i)),
107- UUIDs.random()
108- );
107+ for (int i = 2; i <= 6; i++) {
108+ Insert insertStmt = insertInto("peers")
109+ .value("peer", InetAddress.getByName(CCMBridge.ipOfNode(i)))
110+ .value("data_center", "datacenter1")
111+ .value("host_id", UUIDs.random())
112+ .value("rack", "rack1")
113+ .value("release_version", releaseVersion)
114+ .value("rpc_address", InetAddress.getByName(CCMBridge.ipOfNode(i)))
115+ .value("schema_version", UUIDs.random());
116+ session.execute(insertStmt);
117+ }
109118 } catch (Exception e) {
110119 fail("Error while inserting fake peer rows", e);
111120 } finally {
modified driver-core/src/test/java/com/datastax/driver/core/ConditionalUpdateTest.java +3 −0
@@ -6,9 +6,12 @@
66 import org.testng.annotations.Test;
77 import static org.testng.Assert.*;
88
9+import com.datastax.driver.core.utils.CassandraVersion;
10+
911 /**
1012 * Test {@link ResultSet#wasApplied()} for conditional updates.
1113 */
14+@CassandraVersion(major=2.0, description="Conditional Updates requires 2.0+.")
1215 public class ConditionalUpdateTest extends CCMBridge.PerClassSingleNodeCluster {
1316
1417 @Override
modified driver-core/src/test/java/com/datastax/driver/core/DataTypeTest.java +2 −2
@@ -26,7 +26,7 @@
2626 import static org.testng.Assert.*;
2727
2828 import com.datastax.driver.core.exceptions.InvalidTypeException;
29-
29+import com.datastax.driver.core.utils.CassandraVersion;
3030
3131 /**
3232 * Tests DataType class to ensure data sent in is the same as data received
@@ -517,8 +517,8 @@
517517 }
518518
519519 @Test(groups = "short")
520+ @CassandraVersion(major=2.0, minor=0, description="This feature requires protocol v2")
520521 public void primitiveInsertWithValueTest() throws Throwable {
521- TestUtils.versionCheck(2.0, 0, "This feature requires protocol v2");
522522 for (DataType dt : DataType.allPrimitiveTypes()) {
523523 if (exclude(dt))
524524 continue;
modified driver-core/src/test/java/com/datastax/driver/core/HostAssert.java +9 −0
@@ -35,9 +35,18 @@
3535 public HostAssert comesUpWithin(long duration, TimeUnit unit) {
3636 final CountDownLatch upSignal = new CountDownLatch(1);
3737 StateListener upListener = new StateListenerBase() {
38+
39+ @Override
3840 public void onUp(Host host) {
3941 upSignal.countDown();
4042 }
43+
44+ @Override
45+ public void onAdd(Host host) {
46+ // Special case, cassandra will sometimes not send an 'UP' topology change event
47+ // for a new node, because of this we also listen for add events.
48+ upSignal.countDown();
49+ }
4150 };
4251 cluster.register(upListener);
4352 try {
modified driver-core/src/test/java/com/datastax/driver/core/LargeDataTest.java +4 −0
@@ -23,6 +23,8 @@
2323
2424 import com.datastax.driver.core.querybuilder.Batch;
2525 import com.datastax.driver.core.querybuilder.Insert;
26+import com.datastax.driver.core.utils.CassandraVersion;
27+
2628 import static com.datastax.driver.core.TestUtils.CREATE_KEYSPACE_SIMPLE_FORMAT;
2729 import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
2830
@@ -180,6 +182,7 @@
180182 * @throws Throwable
181183 */
182184 @Test(groups = "long")
185+ @CassandraVersion(major=2.0, minor=0, description="< 2.0 is skipped as 1.2 does not handle reading wide rows well.")
183186 public void wideRows() throws Throwable {
184187 Cluster.Builder builder = Cluster.builder();
185188 CCMBridge.CCMCluster c = CCMBridge.buildCluster(1, builder);
@@ -203,6 +206,7 @@
203206 * @throws Throwable
204207 */
205208 @Test(groups = "short")
209+ @CassandraVersion(major=2.0, minor=0, description="< 2.0 is skipped as 1.2 does not handle large batches well.")
206210 public void wideBatchRows() throws Throwable {
207211 Cluster.Builder builder = Cluster.builder();
208212 CCMBridge.CCMCluster c = CCMBridge.buildCluster(1, builder);
modified driver-core/src/test/java/com/datastax/driver/core/MissingRpcAddressTest.java +4 −2
@@ -22,10 +22,10 @@
2222 @Test(groups = "short")
2323 public void testMissingRpcAddressAtStartup() throws Exception {
2424 CCMBridge ccm = CCMBridge.create("ccm", 2);
25- deleteNode2RpcAddressFromNode1();
2625
2726 Cluster cluster = null;
2827 try {
28+ deleteNode2RpcAddressFromNode1();
2929 // Use only one contact point to make sure that the control connection is on node1
3030 cluster = Cluster.builder()
3131 .addContactPoint(CCMBridge.IP_PREFIX + "1")
@@ -53,7 +53,9 @@
5353 Lists.newArrayList(socketAddress(1))))
5454 .build();
5555 Session session = cluster.connect();
56- session.execute("DELETE rpc_address FROM system.peers WHERE peer = ?", InetAddress.getByName(CCMBridge.IP_PREFIX + "2"));
56+ String deleteStmt = String.format("DELETE rpc_address FROM system.peers WHERE peer = '%s'",
57+ InetAddress.getByName(CCMBridge.IP_PREFIX + "2").getHostName());
58+ session.execute(deleteStmt);
5759 session.close();
5860 } finally {
5961 if (cluster != null)
modified driver-core/src/test/java/com/datastax/driver/core/PoolingOptionsTest.java +4 −3
@@ -48,8 +48,9 @@
4848 .hasState(State.UP)
4949 .isAtDistance(HostDistance.LOCAL);
5050 // Wait for the node to be up, because apparently on Jenkins it's still only ADDED when we reach this line
51+ // Waiting for NEW_NODE_DELAY_SECONDS+1 allows the driver to create a connection pool and mark the node up
5152 assertThat(cluster).host(2)
52- .comesUpWithin(120, SECONDS)
53+ .comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS+1, SECONDS)
5354 .isAtDistance(HostDistance.LOCAL);
5455
5556 // Bring host 3 up, its presence should be acknowledged but it should be ignored
@@ -63,13 +64,13 @@
6364 .hasState(State.UP)
6465 .isAtDistance(HostDistance.LOCAL);
6566 assertThat(cluster).host(3)
66- .comesUpWithin(120, SECONDS)
67+ .comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS+1, SECONDS)
6768 .isAtDistance(HostDistance.IGNORED);
6869 assertThat(session).hasNoPoolFor(3);
6970
7071 // Kill host 2, host 3 should take its place
7172 ccm.stop(2);
72- TestUtils.waitFor(CCMBridge.ipOfNode(3), cluster, 120);
73+ TestUtils.waitFor(CCMBridge.ipOfNode(3), cluster);
7374
7475 assertThat(cluster).host(1)
7576 .hasState(State.UP)
modified driver-core/src/test/java/com/datastax/driver/core/ReconnectionTest.java +42 −19
@@ -5,6 +5,8 @@
55 import java.util.Collections;
66 import java.util.Iterator;
77 import java.util.Map;
8+import java.util.concurrent.ConcurrentHashMap;
9+import java.util.concurrent.ConcurrentMap;
810 import java.util.concurrent.TimeUnit;
911 import java.util.concurrent.atomic.AtomicInteger;
1012
@@ -12,7 +14,9 @@
1214
1315 import com.google.common.base.Charsets;
1416 import com.google.common.collect.ImmutableMap;
17+import com.google.common.util.concurrent.ListenableFuture;
1518 import org.testng.annotations.Test;
19+
1620 import static org.assertj.core.api.Assertions.assertThat;
1721
1822 import com.datastax.driver.core.Host.State;
@@ -33,9 +37,9 @@
3337 ccm = CCMBridge.create("test", 2);
3438 int reconnectionDelay = 1000;
3539 cluster = Cluster.builder()
36- .addContactPoint(CCMBridge.ipOfNode(1))
37- .withReconnectionPolicy(new ConstantReconnectionPolicy(reconnectionDelay))
38- .build();
40+ .addContactPoint(CCMBridge.ipOfNode(1))
41+ .withReconnectionPolicy(new ConstantReconnectionPolicy(reconnectionDelay))
42+ .build();
3943 cluster.connect();
4044
4145 assertThat(cluster).usesControlHost(1);
@@ -78,11 +82,11 @@
7882 CountingReconnectionPolicy reconnectionPolicy = new CountingReconnectionPolicy(new ConstantReconnectionPolicy(reconnectionDelayMs));
7983
8084 cluster = Cluster.builder()
81- .addContactPoint(CCMBridge.ipOfNode(1))
82- // Start with the correct auth so that we can initialize the server
83- .withAuthProvider(authProvider)
84- .withReconnectionPolicy(reconnectionPolicy)
85- .build();
85+ .addContactPoint(CCMBridge.ipOfNode(1))
86+ // Start with the correct auth so that we can initialize the server
87+ .withAuthProvider(authProvider)
88+ .withReconnectionPolicy(reconnectionPolicy)
89+ .build();
8690
8791 cluster.init();
8892 assertThat(cluster).usesControlHost(1);
@@ -128,9 +132,9 @@
128132 try {
129133 ccm = CCMBridge.create("test", 2);
130134 cluster = Cluster.builder()
131- .addContactPoint(CCMBridge.ipOfNode(1))
132- .withReconnectionPolicy(reconnectionPolicy)
133- .build();
135+ .addContactPoint(CCMBridge.ipOfNode(1))
136+ .withReconnectionPolicy(reconnectionPolicy)
137+ .build();
134138 cluster.connect();
135139
136140 // Stop a node and cancel the reconnection attempts to it
@@ -169,22 +173,25 @@
169173 try {
170174 ccm = CCMBridge.create("test", 1);
171175 cluster = Cluster.builder()
172- .addContactPoint(CCMBridge.ipOfNode(1))
173- .withLoadBalancingPolicy(loadBalancingPolicy)
174- .withReconnectionPolicy(new ConstantReconnectionPolicy(reconnectionDelayMillis))
175- .build();
176+ .addContactPoint(CCMBridge.ipOfNode(1))
177+ .withLoadBalancingPolicy(loadBalancingPolicy)
178+ .withReconnectionPolicy(new ConstantReconnectionPolicy(reconnectionDelayMillis))
179+ .build();
176180 cluster.connect();
177181
178182 // Tweak the LBP so that the control connection never reconnects, otherwise
179183 // it would interfere with the rest of the test (this is a bit of a hack)
180184 loadBalancingPolicy.returnEmptyQueryPlan = true;
181185
182- // Stop the node and cancel the reconnection attempts to it
186+ // Stop the node, ignore it and cancel reconnection attempts to it
183187 ccm.stop(1);
184188 ccm.waitForDown(1);
185189 assertThat(cluster).host(1).goesDownWithin(20, SECONDS);
186190 Host host1 = TestUtils.findHost(cluster, 1);
187- host1.getReconnectionAttemptFuture().cancel(false);
191+ loadBalancingPolicy.setDistance(TestUtils.findHost(cluster, 1), HostDistance.IGNORED);
192+ ListenableFuture<?> reconnectionAttemptFuture = host1.getReconnectionAttemptFuture();
193+ if (reconnectionAttemptFuture != null)
194+ reconnectionAttemptFuture.cancel(false);
188195
189196 // Trigger a one-time reconnection attempt (this will fail)
190197 host1.tryReconnectOnce();
@@ -260,8 +267,9 @@
260267
261268 @Override
262269 Map<String, String> getCredentials() {
270+ count.incrementAndGet();
263271 return ImmutableMap.of("username", username,
264- "password", password);
272+ "password", password);
265273 }
266274 }
267275 }
@@ -298,16 +306,31 @@
298306 }
299307
300308 /**
301- * A load balancing policy that can be "disabled" by having its query plan return no hosts.
309+ * A load balancing policy that:
310+ * - can be "disabled" by having its query plan return no hosts.
311+ * - can be instructed to return a specific distance for some hosts.
302312 */
303313 public static class TogglabePolicy extends DelegatingLoadBalancingPolicy {
304314
305315 volatile boolean returnEmptyQueryPlan;
316+ final ConcurrentMap<Host, HostDistance> distances = new ConcurrentHashMap<Host, HostDistance>();
306317
307318 public TogglabePolicy(LoadBalancingPolicy delegate) {
308319 super(delegate);
309320 }
310321
322+ @Override
323+ public HostDistance distance(Host host) {
324+ HostDistance distance = distances.get(host);
325+ return (distance != null)
326+ ? distance
327+ : super.distance(host);
328+ }
329+
330+ public void setDistance(Host host, HostDistance distance) {
331+ distances.put(host, distance);
332+ }
333+
311334 @Override
312335 public Iterator<Host> newQueryPlan(String loggedKeyspace, Statement statement) {
313336 if (returnEmptyQueryPlan)
modified driver-core/src/test/java/com/datastax/driver/core/SchemaChangesTest.java +8 −2
@@ -9,6 +9,7 @@
99 import org.testng.annotations.BeforeClass;
1010 import org.testng.annotations.Test;
1111
12+import com.datastax.driver.core.exceptions.InvalidQueryException;
1213 import com.datastax.driver.core.utils.Bytes;
1314
1415 import static com.datastax.driver.core.Assertions.assertThat;
@@ -101,8 +102,13 @@
101102
102103 @AfterMethod(groups = "short")
103104 public void cleanup() {
104- session.execute("DROP TABLE IF EXISTS ks.table1");
105- session.execute("DROP KEYSPACE IF EXISTS ks2");
105+ try {
106+ session.execute("DROP TABLE ks.table1");
107+ } catch(InvalidQueryException ex) {}
108+
109+ try {
110+ session.execute("DROP KEYSPACE ks2");
111+ } catch(InvalidQueryException ex) {}
106112 }
107113
108114 @AfterClass(groups = "short")
modified driver-core/src/test/java/com/datastax/driver/core/SessionTest.java +21 −8
@@ -149,13 +149,20 @@
149149 Thread.sleep(10);
150150
151151 // create a new cluster object and ensure 0 sessions and connections
152- Cluster cluster = Cluster.builder().addContactPoints(CCMBridge.IP_PREFIX + '1').build();
152+ int corePoolSize = 2;
153+ PoolingOptions poolingOptions = new PoolingOptions()
154+ .setCoreConnectionsPerHost(HostDistance.LOCAL, corePoolSize);
155+ Cluster cluster = Cluster.builder()
156+ .addContactPoints(CCMBridge.IP_PREFIX + '1')
157+ .withPoolingOptions(poolingOptions)
158+ .build();
159+
153160 assertEquals(cluster.manager.sessions.size(), 0);
154161 assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 0);
155162
156163 Session session = cluster.connect();
157164 assertEquals(cluster.manager.sessions.size(), 1);
158- assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 3);
165+ assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1 + corePoolSize);
159166
160167 // ensure sessions.size() returns to 0 with only 1 active connection
161168 session.close();
@@ -174,7 +181,7 @@
174181 // ensure a new session gets registered and control connections are established
175182 session = cluster.connect();
176183 assertEquals(cluster.manager.sessions.size(), 1);
177- assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 3);
184+ assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1 + corePoolSize);
178185 session.close();
179186
180187 // give the driver time to close sessions
@@ -198,14 +205,20 @@
198205
199206 // create a new cluster object and ensure 0 sessions and connections
200207 Cluster cluster = Cluster.builder().addContactPoints(CCMBridge.IP_PREFIX + '1').build();
208+
209+ int corePoolSize = cluster.getConfiguration()
210+ .getPoolingOptions()
211+ .getCoreConnectionsPerHost(HostDistance.LOCAL);
212+
201213 assertEquals(cluster.manager.sessions.size(), 0);
202214 assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 0);
203215
216+ // ensure sessions.size() returns with 1 control connection + core pool size.
204217 Session session = cluster.connect();
205218 assertEquals(cluster.manager.sessions.size(), 1);
206- assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 3);
219+ assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1 + corePoolSize);
207220
208- // ensure sessions.size() returns to 0 with only 1 active connection
221+ // ensure sessions.size() returns to 0 with only 1 active connection (the control connection)
209222 session.close();
210223 assertEquals(cluster.manager.sessions.size(), 0);
211224 assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1);
@@ -218,11 +231,11 @@
218231 assertEquals(cluster.manager.sessions.size(), 0);
219232 assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1);
220233
221- // ensure a new session gets registered and control connections are established
222- // an additional 2 control connections should be seen for node2
234+ // ensure a new session gets registered and core connections are established
235+ // there should be corePoolSize more connections to accommodate for the new host.
223236 thisSession = cluster.connect();
224237 assertEquals(cluster.manager.sessions.size(), 1);
225- assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 5);
238+ assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1 + (corePoolSize * 2));
226239
227240 // ensure bootstrapping a node does not create additional connections that won't get cleaned up
228241 thisSession.close();
modified driver-core/src/test/java/com/datastax/driver/core/StateListenerTest.java +1 −1
@@ -29,7 +29,7 @@
2929 */
3030 public class StateListenerTest {
3131
32- @Test(groups = "short")
32+ @Test(groups = "long")
3333 public void listenerTest() throws Throwable {
3434
3535 CCMBridge.CCMCluster c = CCMBridge.buildCluster(1, Cluster.builder());
modified driver-core/src/test/java/com/datastax/driver/core/TestListener.java +32 −4
@@ -15,12 +15,16 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import org.testng.ITestResult;
19-import org.testng.TestListenerAdapter;
20-
18+import org.testng.*;
19+import org.testng.internal.ConstructorOrMethod;
20+
21+import java.lang.annotation.Annotation;
22+import java.lang.reflect.Method;
2123 import java.util.concurrent.TimeUnit;
2224
23-public class TestListener extends TestListenerAdapter {
25+import com.datastax.driver.core.utils.CassandraVersion;
26+
27+public class TestListener extends TestListenerAdapter implements IInvokedMethodListener {
2428
2529 private long start_time = System.nanoTime();
2630 private int test_index = 0;
@@ -78,4 +82,28 @@
7882 + ':' + (minutes < 10 ? "0" : "") + minutes
7983 + ':' + (seconds< 10 ? "0" : "") + seconds);
8084 }
85+
86+ @Override public void beforeInvocation(IInvokedMethod testMethod, ITestResult testResult) {
87+ // Check to see if the class or method is annotated with 'CassandraVersion', if so ensure the
88+ // version we are testing with meets the requirement, if not a SkipException is thrown
89+ // and this test is skipped.
90+ ITestNGMethod testNgMethod = testResult.getMethod();
91+ ConstructorOrMethod constructorOrMethod = testNgMethod.getConstructorOrMethod();
92+
93+ Class<?> clazz = testNgMethod.getInstance().getClass();
94+ if(clazz != null && clazz.isAnnotationPresent(CassandraVersion.class)) {
95+ CassandraVersion cassandraVersion = clazz.getAnnotation(CassandraVersion.class);
96+ TestUtils.versionCheck(cassandraVersion.major(), cassandraVersion.minor(), cassandraVersion.description());
97+ }
98+
99+ Method method = constructorOrMethod.getMethod();
100+ if(method != null && method.isAnnotationPresent(CassandraVersion.class)) {
101+ CassandraVersion cassandraVersion = method.getAnnotation(CassandraVersion.class);
102+ TestUtils.versionCheck(cassandraVersion.major(), cassandraVersion.minor(), cassandraVersion.description());
103+ }
104+ }
105+
106+ @Override public void afterInvocation(IInvokedMethod testMethod, ITestResult testResult) {
107+ // Do nothing
108+ }
81109 }
modified driver-core/src/test/java/com/datastax/driver/core/TestUtils.java +23 −7
@@ -49,6 +49,8 @@
4949 public static final String INSERT_FORMAT = "INSERT INTO %s (k, t, i, f) VALUES ('%s', '%s', %d, %f)";
5050 public static final String SELECT_ALL_FORMAT = "SELECT * FROM %s";
5151
52+ public static final int TEST_BASE_NODE_WAIT = SystemProperties.getInt("com.datastax.driver.TEST_BASE_NODE_WAIT", 60);
53+
5254 @SuppressWarnings({ "unchecked", "rawtypes" })
5355 public static BoundStatement setBoundValue(BoundStatement bs, String name, DataType type, Object value) {
5456 switch (type.getName()) {
@@ -181,7 +183,7 @@
181183 case FLOAT:
182184 return 3.142519f;
183185 case INET:
184- return InetAddress.getByAddress(new byte[]{(byte)127, (byte)0, (byte)0, (byte)1});
186+ return InetAddress.getByAddress(new byte[]{ (byte)127, (byte)0, (byte)0, (byte)1 });
185187 case INT:
186188 return 24;
187189 case TEXT:
@@ -267,7 +269,7 @@
267269 // This is used because there is some delay between when a node has been
268270 // added through ccm and when it's actually available for querying
269271 public static void waitFor(String node, Cluster cluster) {
270- waitFor(node, cluster, 60, false, false);
272+ waitFor(node, cluster, TEST_BASE_NODE_WAIT, false, false);
271273 }
272274
273275 public static void waitFor(String node, Cluster cluster, int maxTry) {
@@ -275,11 +277,11 @@
275277 }
276278
277279 public static void waitForDown(String node, Cluster cluster) {
278- waitFor(node, cluster, 180, true, false);
280+ waitFor(node, cluster, TEST_BASE_NODE_WAIT * 3, true, false);
279281 }
280282
281283 public static void waitForDownWithWait(String node, Cluster cluster, int waitTime) {
282- waitFor(node, cluster, 180, true, false);
284+ waitForDown(node, cluster);
283285
284286 // FIXME: Once stop() works, remove this line
285287 try {
@@ -299,7 +301,7 @@
299301 }
300302
301303 public static void waitForDecommission(String node, Cluster cluster) {
302- waitFor(node, cluster, 30, true, true);
304+ waitFor(node, cluster, TEST_BASE_NODE_WAIT / 2, true, true);
303305 }
304306
305307 public static void waitForDecommission(String node, Cluster cluster, int maxTry) {
@@ -372,7 +374,7 @@
372374 int minor = Integer.parseInt(versionArray[2]);
373375
374376 if (major < majorCheck || (major == majorCheck && minor < minorCheck)) {
375- throw new SkipException(skipString);
377+ throw new SkipException("Version >= " + majorCheck + "." + minorCheck + " required. Description: " + skipString);
376378 }
377379 }
378380
@@ -404,7 +406,7 @@
404406 */
405407 public static int findAvailablePort(int startingWith) {
406408 IOException last = null;
407- for(int port = startingWith; port < startingWith+100; port++) {
409+ for (int port = startingWith; port < startingWith + 100; port++) {
408410 try {
409411 ServerSocket s = new ServerSocket(port);
410412 s.close();
@@ -416,4 +418,18 @@
416418 // If for whatever reason a port could not be acquired throw the last encountered exception.
417419 throw new RuntimeException("Could not acquire an available port", last);
418420 }
421+
422+ /**
423+ * @return The desired target protocol version based on the 'cassandra.version' System property.
424+ */
425+ public static int getDesiredProtocolVersion() {
426+ String version = System.getProperty("cassandra.version");
427+ String[] versionArray = version.split("\\.|-");
428+ double major = Double.parseDouble(versionArray[0] + "." + versionArray[1]);
429+ if(major < 2.0) {
430+ return 1;
431+ } else {
432+ return 2;
433+ }
434+ }
419435 }
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderExecutionTest.java +1 −2
@@ -85,8 +85,7 @@
8585
8686 @Test(groups = "short")
8787 public void batchNonBuiltStatementTest() throws Exception {
88-
89- SimpleStatement simple = new SimpleStatement("INSERT INTO " + TABLE1 + " (k, t) VALUES (?, ?)", "batchTest1", "val1");
88+ SimpleStatement simple = new SimpleStatement("INSERT INTO " + TABLE1 + " (k, t) VALUES ('batchTest1', 'val1')");
9089 RegularStatement built = insertInto(TABLE1).value("k", "batchTest2").value("t", "val2");
9190 session.execute(batch().add(simple).add(built));
9291
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderITest.java +4 −1
@@ -25,6 +25,8 @@
2525
2626 import com.datastax.driver.core.*;
2727 import com.datastax.driver.core.exceptions.SyntaxError;
28+import com.datastax.driver.core.utils.CassandraVersion;
29+
2830 import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
2931
3032 public class QueryBuilderITest extends CCMBridge.PerClassSingleNodeCluster {
@@ -206,7 +208,8 @@
206208 }
207209
208210 @Test(groups = "short")
209- public void conditionalDeletesTest() throws Exception {
211+ @CassandraVersion(major=2.0, minor=7, description="DELETE..IF EXISTS only supported in 2.0.7+ (CASSANDRA-5708)")
212+ public void conditionalDeletesTest() throws Exception {
210213 session.execute("INSERT INTO ks.test_int (k, a, b) VALUES (1, 1, 1)");
211214
212215 Statement delete;
added driver-core/src/test/java/com/datastax/driver/core/utils/CassandraVersion.java +28 −0
@@ -0,0 +1,28 @@
1+package com.datastax.driver.core.utils;
2+
3+import java.lang.annotation.Retention;
4+import java.lang.annotation.RetentionPolicy;
5+
6+/**
7+ * <p>Annotation for a Class or Method that defines a Cassandra Version requirement. If the cassandra verison in used
8+ * does not meet the version requirement, the test is skipped.</p>
9+ *
10+ * @see {@link com.datastax.driver.core.TestListener#beforeInvocation(org.testng.IInvokedMethod, org.testng.ITestResult)} for usage.
11+ */
12+@Retention(RetentionPolicy.RUNTIME)
13+public @interface CassandraVersion {
14+ /**
15+ * @return The major version required to execute this test, i.e. "2.0"
16+ */
17+ public double major();
18+
19+ /**
20+ * @return The minor version required to execute this test, i.e. "0"
21+ */
22+ public int minor() default 0;
23+
24+ /**
25+ * @return The description returned if this version requirement is not met.
26+ */
27+ public String description() default "Does not meet minimum version requirement.";
28+}