Elffuss BraidHub

kikocis/java-driver public

Add more Integration Tests for JAVA-312.

Added Integration Tests for clusters using VNodes.

Added Integration Test for verifying Metadata is updated when nodes are
added and removed.

Added CCMBridge#remove(n) for removing a node from the cluster.

Added more tests to TokenIntegrationTest.

Added more unit tests to TokenRangeTest.
Changesetffaefeab81b6f7b56ee4fde6b2a8cabd6400ba098e6958b8f4b157f16b6e2d32
AuthorAndrew Tolbert <andrew.tolbert@datastax.com> · 2015-02-17 21:54 -06:00
Committerolim7t <omichallat+github@gmail.com> · 2015-02-19 14:57 +01:00
Parents33520f173c29

Browse the files at this changeset

12 files changed

modified driver-core/src/test/java/com/datastax/driver/core/CCMBridge.java +5 −0
@@ -151,6 +151,11 @@
151151 execute("ccm remove");
152152 }
153153
154+ public void remove(int n) {
155+ logger.info("Removing: " + IP_PREFIX + n);
156+ execute("ccm node%d remove", n);
157+ }
158+
154159 public void ring() {
155160 ring(1);
156161 }
modified driver-core/src/test/java/com/datastax/driver/core/ClusterAssert.java +61 −0
@@ -1,6 +1,12 @@
11 package com.datastax.driver.core;
22
3+import java.util.Iterator;
4+import java.util.Set;
5+import java.util.TreeSet;
6+
37 import static org.assertj.core.api.Assertions.assertThat;
8+
9+import com.google.common.collect.Iterators;
410 import org.assertj.core.api.AbstractAssert;
511
612 public class ClusterAssert extends AbstractAssert<ClusterAssert, Cluster> {
@@ -22,4 +28,59 @@
2228
2329 return new HostAssert(host, actual);
2430 }
31+
32+ /**
33+ * Asserts that {@link Cluster}'s {@link Host}s have valid {@link TokenRange}s with the given keyspace.
34+ *
35+ * Ensures that no ranges intersect and that they cover the entire ring.
36+ * @param keyspace Keyspace to grab {@link TokenRange}s from.
37+ */
38+ public ClusterAssert hasValidTokenRanges(String keyspace) {
39+ // Sort the token ranges so they are in order (needed for vnodes).
40+ Set<TokenRange> ranges = new TreeSet<TokenRange>();
41+ for(Host host : actual.getMetadata().getAllHosts()) {
42+ ranges.addAll(actual.getMetadata().getTokenRanges(keyspace, host));
43+ }
44+ return hasValidTokenRanges(ranges);
45+ }
46+
47+ /**
48+ * Asserts that {@link Cluster}'s {@link Host}s have valid {@link TokenRange}s.
49+ *
50+ * Ensures that no ranges intersect and that they cover the entire ring.
51+ */
52+ public ClusterAssert hasValidTokenRanges() {
53+ // Sort the token ranges so they are in order (needed for vnodes).
54+ Set<TokenRange> ranges = new TreeSet<TokenRange>(actual.getMetadata().getTokenRanges());
55+ return hasValidTokenRanges(ranges);
56+ }
57+
58+ /**
59+ * Asserts that given Set of {@link TokenRange}s are valid.
60+ *
61+ * Ensures that no ranges intersect and that they cover the entire ring.
62+ */
63+ private ClusterAssert hasValidTokenRanges(Set<TokenRange> ranges) {
64+ // Ensure no ranges intersect.
65+ Iterator<TokenRange> it = ranges.iterator();
66+ while(it.hasNext()) {
67+ TokenRange range = it.next();
68+ Assertions.assertThat(range).doesNotIntersect(Iterators.toArray(it, TokenRange.class));
69+ }
70+
71+ // Ensure the defined ranges cover the entire ring.
72+ it = ranges.iterator();
73+ TokenRange mergedRange = it.next();
74+ while(it.hasNext()) {
75+ TokenRange next = it.next();
76+ mergedRange = mergedRange.mergeWith(next);
77+ }
78+ boolean isFullRing = mergedRange.getStart().equals(mergedRange.getEnd())
79+ && !mergedRange.isEmpty();
80+ assertThat(isFullRing)
81+ .as("Ring is not fully defined for Cluster.")
82+ .isTrue();
83+
84+ return this;
85+ }
2586 }
modified driver-core/src/test/java/com/datastax/driver/core/M3PTokenFactoryTest.java +2 −0
@@ -5,6 +5,7 @@
55 import org.testng.annotations.Test;
66
77 import static org.assertj.core.api.Assertions.assertThat;
8+import static org.testng.Assert.fail;
89
910 public class M3PTokenFactoryTest {
1011 Token.Factory factory = Token.M3PToken.FACTORY;
@@ -74,4 +75,5 @@
7475 factory.fromString("3074457345618258602")
7576 );
7677 }
78+
7779 }
No newline at the end of the file
added driver-core/src/test/java/com/datastax/driver/core/M3PTokenVnodeIntegrationTest.java +11 −0
@@ -0,0 +1,11 @@
1+package com.datastax.driver.core;
2+
3+public class M3PTokenVnodeIntegrationTest extends TokenIntegrationTest {
4+ public M3PTokenVnodeIntegrationTest() {
5+ super("", DataType.bigint(), true);
6+ }
7+
8+ @Override protected Token.Factory tokenFactory() {
9+ return Token.M3PToken.FACTORY;
10+ }
11+}
added driver-core/src/test/java/com/datastax/driver/core/MetadataTest.java +113 −0
@@ -0,0 +1,113 @@
1+package com.datastax.driver.core;
2+
3+import java.util.Map;
4+
5+import com.google.common.collect.Maps;
6+import org.testng.annotations.Test;
7+
8+import static com.datastax.driver.core.Assertions.assertThat;
9+import static com.datastax.driver.core.TestUtils.waitFor;
10+
11+public class MetadataTest {
12+
13+ /**
14+ * <p>
15+ * Validates that when the topology of the cluster changes that Cluster Metadata is properly updated.
16+ * </p>
17+ *
18+ * <p>
19+ * This test does the following:
20+ *
21+ * <ol>
22+ * <li>Creates a 3 node cluster and capture token range data from the {@link Cluster}'s {@link Metadata}</li>
23+ * <li>Decommission node 3.</li>
24+ * <li>Validates that the token range data was updated to reflect node 3 leaving and the other nodes
25+ * taking on its token range.</li>
26+ * <li>Adds a new node, node 4.</li>
27+ * <li>Validates that the token range data was updated to reflect node 4 joining the {@link Cluster} and
28+ * the token ranges reflecting this.</li>
29+ * </ol>
30+ *
31+ * @test_category metadata:token
32+ * @expected_result cluster metadata is properly updated in response to node remove and add events.
33+ * @jira_ticket JAVA-312
34+ * @since 2.0.10, 2.1.5
35+ */
36+ @Test(groups="long")
37+ public void should_update_metadata_on_topology_change() {
38+ CCMBridge ccm = null;
39+ Cluster cluster = null;
40+
41+ try {
42+ ccm = CCMBridge.create("test", 3);
43+
44+ cluster = Cluster.builder()
45+ .addContactPoint(CCMBridge.ipOfNode(1))
46+ .build();
47+ Session session = cluster.connect();
48+
49+ String keyspace = "test";
50+ session.execute("CREATE KEYSPACE IF NOT EXISTS " + keyspace + " WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}");
51+ Metadata metadata = cluster.getMetadata();
52+
53+ // Capture all Token data.
54+ assertThat(metadata.getTokenRanges()).hasSize(3);
55+ Map<Host, Token> tokensForHost = getTokenForHosts(metadata);
56+
57+ // Capture host3s token and range before we take it down.
58+ Host host3 = TestUtils.findHost(cluster, 3);
59+ Token host3Token = tokensForHost.get(host3);
60+
61+ ccm.decommissionNode(3);
62+ ccm.remove(3);
63+
64+ // Ensure that the token ranges were updated, there should only be 2 ranges now.
65+ assertThat(metadata.getTokenRanges()).hasSize(2);
66+
67+ // The token should not be present for any Host.
68+ assertThat(getTokenForHosts(metadata)).doesNotContainValue(host3Token);
69+
70+ // The ring should be fully accounted for.
71+ assertThat(cluster).hasValidTokenRanges("test");
72+ assertThat(cluster).hasValidTokenRanges();
73+
74+ // Add an additional node.
75+ ccm.bootstrapNode(4);
76+ waitFor(CCMBridge.IP_PREFIX + '4', cluster);
77+
78+ // Ensure that the token ranges were updated, there should only be 3 ranges now.
79+ assertThat(metadata.getTokenRanges()).hasSize(3);
80+
81+ Host host4 = TestUtils.findHost(cluster, 4);
82+ TokenRange host4Range = metadata.getTokenRanges(keyspace, host4).iterator().next();
83+
84+ // Ensure no host token range intersects with node 4.
85+ for(Host host : metadata.getAllHosts()) {
86+ if(!host.equals(host4)) {
87+ TokenRange hostRange = metadata.getTokenRanges(keyspace, host).iterator().next();
88+ assertThat(host4Range).doesNotIntersect(hostRange);
89+ }
90+ }
91+
92+ // The ring should be fully accounted for.
93+ assertThat(cluster).hasValidTokenRanges("test");
94+ assertThat(cluster).hasValidTokenRanges();
95+ } finally {
96+ if (cluster != null)
97+ cluster.close();
98+ if (ccm != null)
99+ ccm.remove();
100+ }
101+ }
102+
103+ /**
104+ * @return A mapping of Host -> Token for each Host in the given {@link Metadata}
105+ */
106+ private Map<Host, Token> getTokenForHosts(Metadata metadata) {
107+ Map<Host, Token> tokensByHost = Maps.newHashMap();
108+ for(Host host : metadata.getAllHosts()) {
109+ tokensByHost.put(host, host.getTokens().iterator().next());
110+ }
111+ return tokensByHost;
112+ }
113+}
modified driver-core/src/test/java/com/datastax/driver/core/OPPTokenFactoryTest.java +45 −2
@@ -1,5 +1,6 @@
11 package com.datastax.driver.core;
22
3+import java.math.BigInteger;
34 import java.nio.ByteBuffer;
45 import java.util.List;
56
@@ -7,9 +8,12 @@
78 import org.testng.annotations.Test;
89
910 import static org.assertj.core.api.Assertions.assertThat;
11+import static org.testng.Assert.fail;
1012
1113 public class OPPTokenFactoryTest {
12- Token.Factory factory = Token.OPPToken.FACTORY;
14+ private static final Token.Factory factory = Token.OPPToken.FACTORY;
15+
16+ private static final Token minToken = factory.deserialize(ByteBuffer.allocate(0));
1317
1418 @Test(groups = "unit")
1519 public void should_split_range() {
@@ -22,7 +26,6 @@
2226
2327 @Test(groups = "unit")
2428 public void should_split_range_producing_empty_splits_near_ring_end() {
25- Token minToken = factory.deserialize(ByteBuffer.allocate(0));
2629 // the first token following min
2730 Token zero = factory.deserialize(ByteBuffer.wrap(new byte[]{0}));
2831
@@ -34,7 +37,47 @@
3437 );
3538 }
3639
40+ @Test(groups = "unit")
41+ public void should_strip_trailing_0_bytes() {
42+ Token with0Bytes = factory.deserialize(ByteBuffer.wrap(new byte[]{4,0,0,0}));
43+ Token without0Bytes = factory.deserialize(ByteBuffer.wrap(new byte[]{4}));
44+ Token fromStringWith0Bytes = factory.fromString("040000");
45+
46+ assertThat(with0Bytes)
47+ .isEqualTo(without0Bytes)
48+ .isEqualTo(fromStringWith0Bytes);
49+
50+ Token withMixed0Bytes = factory.fromString("0004000400");
51+ Token withoutMixed0Bytes = factory.fromString("00040004");
52+
53+ assertThat(withMixed0Bytes)
54+ .isEqualTo(withoutMixed0Bytes);
55+ }
56+
57+ @Test(groups = "unit")
58+ public void should_split_range_that_wraps_around_the_ring() {
59+ for(int start = 1; start < 128; start++) {
60+ for(int end = start; end < start; end++) {
61+ // Take the midpoint of the ring and offset by the midpoint of start+end.
62+ long expected = 0x81 + ((start + end) / 2);
63+ TokenRange tr = new TokenRange(token(start), token(end), factory);
64+ assertThat(factory.split(tr.getStart(), tr.getEnd(), 2))
65+ .as("Expected 0x%X for start: %d, end: %d", expected, start, end)
66+ .containsExactly(token(expected));
67+ }
68+ }
69+ }
70+
71+ @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class)
72+ public void should_not_be_allowed_to_split_with_min_token() {
73+ factory.split(minToken, minToken, 1);
74+ }
75+
3776 private Token token(char c) {
3877 return new Token.OPPToken(ByteBuffer.wrap(new byte[]{ (byte)c }));
3978 }
79+
80+ private Token token(long i) {
81+ return new Token.OPPToken(ByteBuffer.wrap(BigInteger.valueOf(i).toByteArray()));
82+ }
4083 }
added driver-core/src/test/java/com/datastax/driver/core/OPPTokenVnodeIntegrationTest.java +11 −0
@@ -0,0 +1,11 @@
1+package com.datastax.driver.core;
2+
3+public class OPPTokenVnodeIntegrationTest extends TokenIntegrationTest {
4+ public OPPTokenVnodeIntegrationTest() {
5+ super("-p ByteOrderedPartitioner", DataType.blob(), true);
6+ }
7+
8+ @Override protected Token.Factory tokenFactory() {
9+ return Token.OPPToken.FACTORY;
10+ }
11+}
modified driver-core/src/test/java/com/datastax/driver/core/RPTokenFactoryTest.java +1 −0
@@ -5,6 +5,7 @@
55 import org.testng.annotations.Test;
66
77 import static org.assertj.core.api.Assertions.assertThat;
8+import static org.testng.Assert.fail;
89
910 public class RPTokenFactoryTest {
1011 Token.Factory factory = Token.RPToken.FACTORY;
added driver-core/src/test/java/com/datastax/driver/core/RPTokenVnodeIntegrationTest.java +11 −0
@@ -0,0 +1,11 @@
1+package com.datastax.driver.core;
2+
3+public class RPTokenVnodeIntegrationTest extends TokenIntegrationTest {
4+ public RPTokenVnodeIntegrationTest() {
5+ super("-p RandomPartitioner", DataType.varint(), true);
6+ }
7+
8+ @Override protected Token.Factory tokenFactory() {
9+ return Token.RPToken.FACTORY;
10+ }
11+}
modified driver-core/src/test/java/com/datastax/driver/core/TokenIntegrationTest.java +173 −33
@@ -1,16 +1,16 @@
11 package com.datastax.driver.core;
22
33 import java.net.InetSocketAddress;
4-import java.util.Iterator;
5-import java.util.List;
6-import java.util.Set;
7-
8-import com.beust.jcommander.internal.Sets;
4+import java.util.*;
5+
6+import com.google.common.base.Function;
7+import com.google.common.collect.Iterables;
98 import com.google.common.collect.Lists;
109 import org.testng.annotations.AfterClass;
1110 import org.testng.annotations.BeforeClass;
1211 import org.testng.annotations.Test;
1312
13+import com.datastax.driver.core.exceptions.InvalidTypeException;
1414 import com.datastax.driver.core.policies.LoadBalancingPolicy;
1515 import com.datastax.driver.core.policies.RoundRobinPolicy;
1616 import com.datastax.driver.core.policies.WhiteListPolicy;
@@ -39,13 +39,21 @@
3939
4040 private final String ccmOptions;
4141 private final DataType expectedTokenType;
42+ private final int numTokens;
43+ private final boolean useVnodes;
4244 CCMBridge ccm;
4345 Cluster cluster;
4446 Session session;
4547
4648 public TokenIntegrationTest(String ccmOptions, DataType expectedTokenType) {
47- this.ccmOptions = ccmOptions;
49+ this(ccmOptions, expectedTokenType, false);
50+ }
51+
52+ public TokenIntegrationTest(String ccmOptions, DataType expectedTokenType, boolean useVnodes) {
4853 this.expectedTokenType = expectedTokenType;
54+ this.numTokens = useVnodes ? 256 : 1;
55+ this.ccmOptions = useVnodes ? ccmOptions + " --vnodes" : ccmOptions;
56+ this.useVnodes = useVnodes;
4957 }
5058
5159 @BeforeClass(groups = "short")
@@ -75,6 +83,17 @@
7583 ccm.remove();
7684 }
7785
86+ /**
87+ * <p>
88+ * Validates that {@link TokenRange}s are exposed via a {@link Cluster}'s {@link Metadata} and they
89+ * can be used to query data.
90+ * </p>
91+ *
92+ * @test_category metadata:token
93+ * @expected_result token ranges are exposed and usable.
94+ * @jira_ticket JAVA-312
95+ * @since 2.0.10, 2.1.5
96+ */
7897 @Test(groups = "short")
7998 public void should_expose_token_ranges() throws Exception {
8099 Metadata metadata = cluster.getMetadata();
@@ -115,6 +134,31 @@
115134 return rows;
116135 }
117136
137+ /**
138+ * <p>
139+ * Validates that a {@link Token} can be retrieved and parsed by executing 'select token(name)' and
140+ * then used to find data matching that token.
141+ * </p>
142+ *
143+ * <p>
144+ * This test does the following:
145+ *
146+ * <ol>
147+ * <li>Retrieve the token for the key with value '1', get it by index, and ensure if is of the expected token type.</li>
148+ * <li>Retrieve the token for the key with value '1', get it by name, and ensure it matches the token by index.</li>
149+ * <li>Retrieve the token by alias for the key '1', and ensure it matches the token by index.</li>
150+ * <li>Retrieve the token for a case sensitive key.</li>
151+ * <li>Select data by token with a BoundStatement.</li>
152+ * <li>Select data by token using setToken by index.</li>
153+ * <li>Select data by token using setToken by name.</li>
154+ * <li>Select data by token with a SimpleStatement</li>
155+ * </ol>
156+ *
157+ * @test_category token
158+ * @expected_result tokens are selectable, properly parsed, and usable as input.
159+ * @jira_ticket JAVA-312
160+ * @since 2.0.10, 2.1.5
161+ */
118162 @Test(groups = "short")
119163 public void should_get_token_from_row_and_set_token_in_query() {
120164 // get by index:
@@ -145,54 +189,96 @@
145189 row = session.execute(pst.bind().setToken(0, token)).one();
146190 assertThat(row.getInt(0)).isEqualTo(1);
147191
192+ PreparedStatement pst2 = session.prepare("SELECT * FROM test.foo WHERE token(i) = :myToken");
193+ row = session.execute(pst2.bind().setToken("myToken", token)).one();
194+ assertThat(row.getInt(0)).isEqualTo(1);
195+
148196 row = session.execute("SELECT * FROM test.foo WHERE token(i) = ?", token).one();
149197 assertThat(row.getInt(0)).isEqualTo(1);
150198 }
151199
200+ /**
201+ * <p>
202+ * Ensures that an exception is raised when attempting to retrieve a token a non-token column.
203+ * </p>
204+ *
205+ * @test_category token
206+ * @expected_result an exception is raised.
207+ * @jira_ticket JAVA-312
208+ * @since 2.0.10, 2.1.5
209+ */
210+ @Test(groups = "short", expectedExceptions = InvalidTypeException.class)
211+ public void should_raise_exception_when_get_token_on_non_token() {
212+ Row row = session.execute("SELECT i FROM test.foo WHERE i = 1").one();
213+ row.getToken(0);
214+ }
215+
216+ /**
217+ * <p>
218+ * Ensures that @{link TokenRange}s are exposed at a per host level, the ranges are complete,
219+ * the entire ring is represented, and that ranges do not overlap.
220+ * </p>
221+ *
222+ * <p>
223+ * Also ensures that ranges from another replica are present when a Host is a replica for
224+ * another node.
225+ * </p>
226+ *
227+ * @test_category metadata:token
228+ * @expected_result The entire token range is represented collectively and the ranges do not overlap.
229+ * @jira_ticket JAVA-312
230+ * @since 2.0.10, 2.1.5
231+ */
152232 @Test(groups = "short")
153233 public void should_expose_token_ranges_per_host() {
154234 checkRangesPerHost("test", 1);
155235 checkRangesPerHost("test2", 2);
236+ assertThat(cluster).hasValidTokenRanges();
156237 }
157238
158239 private void checkRangesPerHost(String keyspace, int replicationFactor) {
159- Set<TokenRange> allRanges = Sets.newHashSet();
240+ List<TokenRange> allRangesWithReplicas = Lists.newArrayList();
160241
161242 // Get each host's ranges, the count should match the replication factor
162243 for (int i = 1; i <= 3; i++) {
163244 Host host = TestUtils.findHost(cluster, i);
164245 Set<TokenRange> hostRanges = cluster.getMetadata().getTokenRanges(keyspace, host);
165- assertThat(hostRanges).hasSize(replicationFactor);
166- allRanges.addAll(hostRanges);
246+ // Special case: When using vnodes the tokens are not evenly assigned to each replica.
247+ if(!useVnodes) {
248+ assertThat(hostRanges).hasSize(replicationFactor * numTokens);
249+ }
250+ allRangesWithReplicas.addAll(hostRanges);
167251 }
168252
253+ // Special case check for vnodes to ensure that total number of replicated ranges is correct.
254+ assertThat(allRangesWithReplicas).hasSize(3 * numTokens * replicationFactor);
255+
169256 // Once we ignore duplicates, the number of ranges should match the number of nodes.
170- assertThat(allRanges).hasSize(3);
171- Iterator<TokenRange> it = allRanges.iterator();
172- TokenRange range1 = it.next();
173- TokenRange range2 = it.next();
174- TokenRange range3 = it.next();
175-
176- // No two ranges should intersect
177- assertThat(range1)
178- .doesNotIntersect(range2)
179- .doesNotIntersect(range3);
180- assertThat(range2)
181- .doesNotIntersect(range3);
182-
183- // And the ranges should cover the whole ring
184- TokenRange mergedRange = range1.mergeWith(range2.mergeWith(range3));
185- boolean isFullRing = mergedRange.getStart().equals(mergedRange.getEnd())
186- && !mergedRange.isEmpty();
187- assertThat(isFullRing).isTrue();
257+ Set<TokenRange> allRanges = new HashSet<TokenRange>(allRangesWithReplicas);
258+ assertThat(allRanges).hasSize(3*numTokens);
259+
260+ // And the ranges should cover the whole ring and no ranges intersect.
261+ assertThat(cluster).hasValidTokenRanges(keyspace);
188262 }
189263
264+ /**
265+ * <p>
266+ * Ensures that Tokens are exposed for each Host and that the match those in the system tables.
267+ * </p>
268+ *
269+ * <p>
270+ * Also validates that tokens are not present for multiple hosts.
271+ * </p>
272+ *
273+ * @test_category metadata:token
274+ * @expected_result Tokens are exposed by Host and match those in the system tables.
275+ * @jira_ticket JAVA-312
276+ * @since 2.0.10, 2.1.5
277+ */
190278 @Test(groups = "short")
191279 public void should_expose_tokens_per_host() {
192280 for (Host host : cluster.getMetadata().allHosts()) {
193- // We don't use virtual nodes in this test, so there is only one token
194- assertThat(host.getTokens()).hasSize(1);
195- Token tokenFromMetadata = host.getTokens().iterator().next();
281+ assertThat(host.getTokens()).hasSize(numTokens);
196282
197283 // Check against the info in the system tables, which is a bit weak since it's exactly how the metadata is
198284 // constructed in the first place, but there's not much else we can do.
@@ -201,10 +287,64 @@
201287 ? session.execute("select tokens from system.local").one()
202288 : session.execute("select tokens from system.peers where peer = ?", host.listenAddress).one();
203289 Set<String> tokenStrings = row.getSet("tokens", String.class);
204- assertThat(tokenStrings).hasSize(1);
205- Token tokenFromSystemTable = tokenFactory().fromString(tokenStrings.iterator().next());
290+ assertThat(tokenStrings).hasSize(numTokens);
291+ Iterable<Token> tokensFromSystemTable = Iterables.transform(tokenStrings, new Function<String, Token>() {
292+ @Override public Token apply(String input) {
293+ return tokenFactory().fromString(input);
294+ }
295+ });
296+
297+ assertThat(host.getTokens()).containsOnlyOnce(Iterables.toArray(tokensFromSystemTable, Token.class));
298+ }
299+ }
300+
301+ /**
302+ * <p>
303+ * Ensures that for the {@link TokenRange}s returned by {@link Metadata#getTokenRanges()} that there exists at
304+ * most one {@link TokenRange} for which calling {@link TokenRange#isWrappedAround()} returns true and
305+ * {@link TokenRange#unwrap()} returns two {@link TokenRange}s.
306+ * </p>
307+ *
308+ * @test_category metadata:token
309+ * @expected_result Tokens are exposed by Host and match those in the system tables.
310+ * @jira_ticket JAVA-312
311+ * @since 2.0.10, 2.1.5
312+ */
313+ @Test(groups = "short")
314+ public void should_only_unwrap_one_range_for_all_ranges() {
315+ Set<TokenRange> ranges = cluster.getMetadata().getTokenRanges();
316+
317+ assertOnlyOneWrapped(ranges);
318+
319+ Iterable<TokenRange> splitRanges = Iterables.concat(Iterables.transform(ranges,
320+ new Function<TokenRange, Iterable<TokenRange>>() {
321+ @Override public Iterable<TokenRange> apply(TokenRange input) {
322+ return input.splitEvenly(10);
323+ }
324+ })
325+ );
206326
207- assertThat(tokenFromMetadata).isEqualTo(tokenFromSystemTable);
327+ assertOnlyOneWrapped(splitRanges);
328+ }
329+
330+ /**
331+ * Asserts that given the input {@link TokenRange}s that at most one of them wraps the token ring.
332+ * @param ranges Ranges to validate against.
333+ */
334+ protected void assertOnlyOneWrapped(Iterable<TokenRange> ranges) {
335+ TokenRange wrappedRange = null;
336+
337+ for(TokenRange range : ranges) {
338+ if(range.isWrappedAround()) {
339+ assertThat(wrappedRange)
340+ .as("Found a wrapped around TokenRange (%s) when one already exists (%s).", range, wrappedRange)
341+ .isNull();
342+ wrappedRange = range;
343+
344+ assertThat(range).unwrapsOverMinToken(tokenFactory());
345+ } else {
346+ assertThat(range).unwrapsToItself();
347+ }
208348 }
209349 }
210350
modified driver-core/src/test/java/com/datastax/driver/core/TokenRangeAssert.java +28 −7
@@ -1,5 +1,8 @@
11 package com.datastax.driver.core;
22
3+import java.util.Iterator;
4+import java.util.List;
5+
36 import org.assertj.core.api.AbstractAssert;
47
58 import static org.assertj.core.api.Assertions.assertThat;
@@ -19,13 +22,15 @@
1922 return this;
2023 }
2124
22- public TokenRangeAssert doesNotIntersect(TokenRange that) {
23- assertThat(actual.intersects(that))
24- .as("%s should not intersect %s", actual, that)
25- .isFalse();
26- assertThat(that.intersects(actual))
27- .as("%s should not intersect %s", that, actual)
28- .isFalse();
25+ public TokenRangeAssert doesNotIntersect(TokenRange ... that) {
26+ for(TokenRange thatRange : that) {
27+ assertThat(actual.intersects(thatRange))
28+ .as("%s should not intersect %s", actual, thatRange)
29+ .isFalse();
30+ assertThat(thatRange.intersects(actual))
31+ .as("%s should not intersect %s", thatRange, actual)
32+ .isFalse();
33+ }
2934 return this;
3035 }
3136
@@ -34,6 +39,22 @@
3439 return this;
3540 }
3641
42+ public TokenRangeAssert unwrapsOverMinToken(Token.Factory factory) {
43+ List<TokenRange> unwrapped = actual.unwrap();
44+ assertThat(unwrapped.size())
45+ .as("%s should unwrap to two ranges, but unwrapped to %s", actual, unwrapped)
46+ .isEqualTo(2);
47+
48+ Iterator<TokenRange> unwrappedIt = unwrapped.iterator();
49+ TokenRange firstRange = unwrappedIt.next();
50+ assertThat(firstRange.getEnd()).isEqualTo(factory.minToken());
51+
52+ TokenRange secondRange = unwrappedIt.next();
53+ assertThat(secondRange.getStart()).isEqualTo(factory.minToken());
54+
55+ return this;
56+ }
57+
3758 public TokenRangeAssert unwrapsTo(TokenRange... subRanges) {
3859 assertThat(actual.unwrap()).containsExactly(subRanges);
3960 return this;
modified driver-core/src/test/java/com/datastax/driver/core/TokenRangeTest.java +66 −3
@@ -1,9 +1,14 @@
11 package com.datastax.driver.core;
22
33 import java.math.BigInteger;
4+import java.util.List;
45
56 import org.testng.annotations.Test;
67
8+import static org.testng.Assert.fail;
9+
10+import com.datastax.driver.core.Token.M3PToken;
11+
712 import static com.datastax.driver.core.Assertions.assertThat;
813
914 public class TokenRangeTest {
@@ -121,6 +126,16 @@
121126 assertThat(tokenRange(minToken, 5).mergeWith(tokenRange(5, 7))).isEqualTo(tokenRange(minToken, 7));
122127 }
123128
129+ @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class)
130+ public void should_not_merge_with_nonadjacent_and_disjoint_ranges() {
131+ tokenRange(0,5).mergeWith(tokenRange(7,14));
132+ }
133+
134+ @Test(groups = "unit")
135+ public void should_return_non_empty_range_if_other_range_is_empty() {
136+ assertThat(tokenRange(1,5).mergeWith(tokenRange(5,5))).isEqualTo(tokenRange(1,5));
137+ }
138+
124139 @Test(groups = "unit")
125140 public void should_unwrap_to_non_wrapping_ranges() {
126141 assertThat(tokenRange(9, 3)).unwrapsTo(tokenRange(9, minToken), tokenRange(minToken, 3));
@@ -131,19 +146,67 @@
131146 assertThat(tokenRange(minToken, minToken)).unwrapsToItself();
132147 }
133148
149+ @Test(groups = "unit")
150+ public void should_split_evenly() {
151+ // Simply exercise splitEvenly, split logic is exercised in TokenFactoryTest implementation for each partitioner.
152+ List<TokenRange> splits = tokenRange(3, 9).splitEvenly(3);
153+
154+ assertThat(splits).hasSize(3);
155+ assertThat(splits).containsExactly(tokenRange(3, 5), tokenRange(5, 7), tokenRange(7, 9));
156+ }
157+
158+
159+ @Test(groups = "unit")
160+ public void should_throw_error_with_less_than_1_splits() {
161+ for(int i = -255; i < 1; i++) {
162+ try {
163+ tokenRange(0, 1).splitEvenly(i);
164+ fail("Expected error when providing " + i + " splits.");
165+ } catch(IllegalArgumentException e) {
166+ // expected.
167+ }
168+ }
169+ }
170+
171+ @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class)
172+ public void should_not_split_empty_token_range() {
173+ tokenRange(0, 0).splitEvenly(1);
174+ }
175+
176+ @Test(groups = "unit")
177+ public void should_create_empty_token_ranges_if_too_many_splits() {
178+ TokenRange range = tokenRange(0,10);
179+
180+ List<TokenRange> ranges = range.splitEvenly(255);
181+ assertThat(ranges).hasSize(255);
182+
183+ for(int i = 0; i < ranges.size(); i++) {
184+ TokenRange tr = ranges.get(i);
185+ if(i < 10) {
186+ assertThat(tr).isEqualTo(tokenRange(i, i+1));
187+ } else {
188+ assertThat(tr.isEmpty());
189+ }
190+ }
191+ }
192+
134193 private TokenRange tokenRange(long start, long end) {
135- return new TokenRange(factory.newToken(BigInteger.valueOf(start)), factory.newToken(BigInteger.valueOf(end)), factory);
194+ return new TokenRange(newM3PToken(start), newM3PToken(end), factory);
136195 }
137196
138197 private TokenRange tokenRange(Token start, long end) {
139- return new TokenRange(start, factory.newToken(BigInteger.valueOf(end)), factory);
198+ return new TokenRange(start, newM3PToken(end), factory);
140199 }
141200
142201 private TokenRange tokenRange(long start, Token end) {
143- return new TokenRange(factory.newToken(BigInteger.valueOf(start)), end, factory);
202+ return new TokenRange(newM3PToken(start), end, factory);
144203 }
145204
146205 private TokenRange tokenRange(Token start, Token end) {
147206 return new TokenRange(start, end, factory);
148207 }
208+
209+ private Token newM3PToken(long value) {
210+ return factory.fromString(Long.toString(value));
211+ }
149212 }
No newline at the end of the file