Elffuss BraidHub

kikocis/java-driver public

Backport DataTypeIntegrationTest from 2.1 branch.
Changesetfef94230b0fd987417465c7817dc831a595aac480c4970cc36459aef9799875e
Authorolim7t <omichallat+github@gmail.com> · 2015-03-23 19:42 +01:00
Committerolim7t <omichallat+github@gmail.com> · 2015-03-27 10:56 +01:00
Parents4a6953c67318

Browse the files at this changeset

4 files changed

modified driver-core/src/main/java/com/datastax/driver/core/VersionNumber.java +13 −0
@@ -159,6 +159,19 @@
159159 return build;
160160 }
161161
162+ /**
163+ * The next stable version, i.e. the version stripped of its pre-release labels and build metadata.
164+ * <p>
165+ * This is mostly used during our development stage, where we test the driver against pre-release
166+ * versions of Cassandra like 2.1.0-rc7-SNAPSHOT, but need to compare to the stable version 2.1.0
167+ * when testing for native protocol compatibility, etc.
168+ *
169+ * @return the next stable version.
170+ */
171+ public VersionNumber nextStable() {
172+ return new VersionNumber(major, minor, patch, dsePatch, null, null);
173+ }
174+
162175 public int compareTo(VersionNumber other) {
163176 if (major < other.major)
164177 return -1;
added driver-core/src/test/java/com/datastax/driver/core/DataTypeIntegrationTest.java +184 −0
@@ -0,0 +1,184 @@
1+/*
2+ * Copyright (C) 2012-2014 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core;
17+
18+import java.util.*;
19+import java.util.concurrent.atomic.AtomicInteger;
20+
21+import com.google.common.collect.*;
22+import org.slf4j.Logger;
23+import org.slf4j.LoggerFactory;
24+import org.testng.annotations.Test;
25+
26+import static org.assertj.core.api.Assertions.assertThat;
27+
28+import com.datastax.driver.core.utils.CassandraVersion;
29+
30+/**
31+ * The goal of this test is to cover the serialization and deserialization of datatypes.
32+ *
33+ * It creates a table with a column of a given type, inserts a value and then tries to retrieve it.
34+ * There are 3 variants for the insert query: a raw string, a simple statement with a parameter
35+ * (protocol > v2 only) and a prepared statement.
36+ * This is repeated with a large number of datatypes.
37+ */
38+public class DataTypeIntegrationTest extends CCMBridge.PerClassSingleNodeCluster {
39+ private static final Logger logger = LoggerFactory.getLogger(DataTypeIntegrationTest.class);
40+
41+ List<TestTable> tables = allTables();
42+ VersionNumber cassandraVersion;
43+
44+ enum StatementType {RAW_STRING, SIMPLE_WITH_PARAM, PREPARED}
45+
46+ @Override
47+ protected Collection<String> getTableDefinitions() {
48+ Host host = cluster.getMetadata().getAllHosts().iterator().next();
49+ cassandraVersion = host.getCassandraVersion().nextStable();
50+
51+ List<String> statements = Lists.newArrayList();
52+ for (TestTable table : tables) {
53+ if (cassandraVersion.compareTo(table.minCassandraVersion) < 0)
54+ logger.debug("Skipping table because it uses a feature not supported by Cassandra {}: {}",
55+ cassandraVersion, table.createStatement);
56+ else
57+ statements.add(table.createStatement);
58+ }
59+
60+ return statements;
61+ }
62+
63+ @Test(groups = "long")
64+ public void should_insert_and_retrieve_data_with_legacy_statements() {
65+ should_insert_and_retrieve_data(StatementType.RAW_STRING);
66+ }
67+
68+ @Test(groups = "long")
69+ public void should_insert_and_retrieve_data_with_prepared_statements() {
70+ should_insert_and_retrieve_data(StatementType.PREPARED);
71+ }
72+
73+ @Test(groups = "long")
74+ @CassandraVersion(major = 2.0, description = "Uses parameterized simple statements, which are only available with protocol v2")
75+ public void should_insert_and_retrieve_data_with_parameterized_simple_statements() {
76+ should_insert_and_retrieve_data(StatementType.SIMPLE_WITH_PARAM);
77+ }
78+
79+ protected void should_insert_and_retrieve_data(StatementType statementType) {
80+ for (TestTable table : tables) {
81+ if (cassandraVersion.compareTo(table.minCassandraVersion) < 0)
82+ continue;
83+
84+ switch (statementType) {
85+ case RAW_STRING:
86+ session.execute(table.insertStatement.replace("?", table.testColumnType.format(table.sampleValue)));
87+ break;
88+ case SIMPLE_WITH_PARAM:
89+ session.execute(table.insertStatement, table.sampleValue);
90+ break;
91+ case PREPARED:
92+ PreparedStatement ps = session.prepare(table.insertStatement);
93+ session.execute(ps.bind(table.sampleValue));
94+ break;
95+ }
96+
97+ Row row = session.execute(table.selectStatement).one();
98+ Object queriedValue = table.testColumnType.deserialize(row.getBytesUnsafe("v"));
99+
100+ assertThat(queriedValue)
101+ .as("Test failure on %s statement with table:%n%s;%n" +
102+ "insert statement:%n%s;%n",
103+ statementType,
104+ table.createStatement,
105+ table.insertStatement)
106+ .isEqualTo(table.sampleValue);
107+
108+ session.execute(table.truncateStatement);
109+ }
110+ }
111+
112+ /**
113+ * Abstracts information about a table (corresponding to a given column type).
114+ */
115+ static class TestTable {
116+ private static final AtomicInteger counter = new AtomicInteger();
117+ private String tableName = "date_type_test" + counter.incrementAndGet();
118+
119+ final DataType testColumnType;
120+ final Object sampleValue;
121+
122+ final String createStatement;
123+ final String insertStatement = String.format("INSERT INTO %s (k, v) VALUES (1, ?)", tableName);
124+ final String selectStatement = String.format("SELECT v FROM %s WHERE k = 1", tableName);
125+ final String truncateStatement = String.format("TRUNCATE %s", tableName);
126+
127+ final VersionNumber minCassandraVersion;
128+
129+ TestTable(DataType testColumnType, Object sampleValue, String minCassandraVersion) {
130+ this.testColumnType = testColumnType;
131+ this.sampleValue = sampleValue;
132+ this.minCassandraVersion = VersionNumber.parse(minCassandraVersion);
133+
134+ this.createStatement = String.format("CREATE TABLE %s (k int PRIMARY KEY, v %s)", tableName, testColumnType);
135+ }
136+ }
137+
138+ private static List<TestTable> allTables() {
139+ List<TestTable> tables = Lists.newArrayList();
140+
141+ tables.addAll(tablesWithPrimitives());
142+ tables.addAll(tablesWithCollectionsOfPrimitives());
143+ tables.addAll(tablesWithMapsOfPrimitives());
144+
145+ return ImmutableList.copyOf(tables);
146+ }
147+
148+ private static List<TestTable> tablesWithPrimitives() {
149+ List<TestTable> tables = Lists.newArrayList();
150+ for (Map.Entry<DataType, Object> entry : PrimitiveTypeSamples.ALL.entrySet())
151+ tables.add(new TestTable(entry.getKey(), entry.getValue(), "1.2.0"));
152+ return tables;
153+ }
154+
155+ private static List<TestTable> tablesWithCollectionsOfPrimitives() {
156+ List<TestTable> tables = Lists.newArrayList();
157+ for (Map.Entry<DataType, Object> entry : PrimitiveTypeSamples.ALL.entrySet()) {
158+
159+ DataType elementType = entry.getKey();
160+ Object elementSample = entry.getValue();
161+
162+ tables.add(new TestTable(DataType.list(elementType), Lists.newArrayList(elementSample, elementSample), "1.2.0"));
163+ tables.add(new TestTable(DataType.set(elementType), Sets.newHashSet(elementSample), "1.2.0"));
164+ }
165+ return tables;
166+ }
167+
168+ private static List<TestTable> tablesWithMapsOfPrimitives() {
169+ List<TestTable> tables = Lists.newArrayList();
170+ for (Map.Entry<DataType, Object> keyEntry : PrimitiveTypeSamples.ALL.entrySet()) {
171+ DataType keyType = keyEntry.getKey();
172+ Object keySample = keyEntry.getValue();
173+ for (Map.Entry<DataType, Object> valueEntry : PrimitiveTypeSamples.ALL.entrySet()) {
174+ DataType valueType = valueEntry.getKey();
175+ Object valueSample = valueEntry.getValue();
176+
177+ tables.add(new TestTable(DataType.map(keyType, valueType),
178+ ImmutableMap.builder().put(keySample, valueSample).build(),
179+ "1.2.0"));
180+ }
181+ }
182+ return tables;
183+ }
184+}
No newline at the end of the file
modified driver-core/src/test/java/com/datastax/driver/core/DataTypeTest.java +10 −607
@@ -15,475 +15,24 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.math.BigDecimal;
19-import java.math.BigInteger;
20-import java.net.InetAddress;
2118 import java.nio.ByteBuffer;
22-import java.text.SimpleDateFormat;
23-import java.util.*;
19+import java.util.Arrays;
20+import java.util.List;
2421
2522 import org.testng.annotations.Test;
26-import static org.testng.Assert.*;
2723
28-import com.datastax.driver.core.exceptions.InvalidTypeException;
29-import com.datastax.driver.core.utils.CassandraVersion;
30-
31-/**
32- * Tests DataType class to ensure data sent in is the same as data received
33- * All tests are executed via a Simple Statements
34- * Counters are the only datatype not tested within the entirety of the suite.
35- * There is, however, an isolated test case that needs to be implemented.
36- * All statements and sample data is easily exportable via the print_*() methods.
37- */
38-public class DataTypeTest extends CCMBridge.PerClassSingleNodeCluster {
39-
40- private final static Set<DataType> DATA_TYPE_PRIMITIVES = DataType.allPrimitiveTypes();
41- private final static Set<DataType.Name> DATA_TYPE_NON_PRIMITIVE_NAMES = EnumSet.of(DataType.Name.MAP, DataType.Name.SET, DataType.Name.LIST);
42-
43- private final static String PRIMITIVE_INSERT_FORMAT = "INSERT INTO %1$s (k, v) VALUES (%2$s, %2$s);";
44- private final static String BASIC_SELECT_FORMAT = "SELECT k, v FROM %1$s;";
45-
46- private final static String COLLECTION_INSERT_FORMAT = "INSERT INTO %1$s (k, v) VALUES (%2$s, %3$s);";
47- private final static String MAP_INSERT_FORMAT = "INSERT INTO %1$s (k, v) VALUES (%3$s, {%2$s: %3$s});";
48-
49- private final static HashMap<DataType, Object> SAMPLE_DATA = getSampleData();
50- private final static HashMap<DataType, Object> SAMPLE_COLLECTIONS = getSampleCollections();
51-
52- private final static Collection<String> PRIMITIVE_INSERT_STATEMENTS = getPrimitiveInsertStatements();
53- private final static HashMap<DataType, String> PRIMITIVE_SELECT_STATEMENTS = getPrimitiveSelectStatements();
54-
55- private final static Collection<String> COLLECTION_INSERT_STATEMENTS = getCollectionInsertStatements();
56- private final static HashMap<DataType, String> COLLECTION_SELECT_STATEMENTS = getCollectionSelectStatements();
57-
58-
59- private static boolean exclude(DataType t) {
60- return t.getName() == DataType.Name.COUNTER;
61- }
62-
63- /**
64- * Generates the table definitions that will be used in testing
65- */
66- @Override
67- protected Collection<String> getTableDefinitions() {
68- ArrayList<String> tableDefinitions = new ArrayList<String>();
69-
70- // Create primitive data type definitions
71- for (DataType dataType : DATA_TYPE_PRIMITIVES) {
72- if (exclude(dataType))
73- continue;
74-
75- tableDefinitions.add(String.format("CREATE TABLE %1$s (k %2$s PRIMARY KEY, v %1$s)", dataType, dataType));
76- }
77-
78- // Create collection data type definitions
79- for (DataType.Name dataTypeName : DATA_TYPE_NON_PRIMITIVE_NAMES) {
80- // Create MAP data type definitions
81- if (dataTypeName == DataType.Name.MAP) {
82- for (DataType typeArgument1 : DATA_TYPE_PRIMITIVES) {
83- if (exclude(typeArgument1))
84- continue;
85-
86- for (DataType typeArgument2 : DATA_TYPE_PRIMITIVES) {
87- if (exclude(typeArgument2))
88- continue;
89-
90- tableDefinitions.add(String.format("CREATE TABLE %1$s_%2$s_%3$s (k %3$s PRIMARY KEY, v %1$s<%2$s, %3$s>)", dataTypeName, typeArgument1, typeArgument2));
91- }
92- }
93- // Create SET and LIST data type definitions
94- } else {
95- for (DataType typeArgument : DATA_TYPE_PRIMITIVES) {
96- if (exclude(typeArgument))
97- continue;
98-
99- tableDefinitions.add(String.format("CREATE TABLE %1$s_%2$s (k %2$s PRIMARY KEY, v %1$s<%2$s>)", dataTypeName, typeArgument));
100- }
101- }
102- }
103-
104- return tableDefinitions;
105- }
106-
107- /**
108- * Generates the sample data that will be used in testing
109- */
110- private static HashMap<DataType, Object> getSampleData() {
111- HashMap<DataType, Object> sampleData = new HashMap<DataType, Object>();
112-
113- for (DataType dataType : DATA_TYPE_PRIMITIVES) {
114- switch (dataType.getName()) {
115- case ASCII:
116- sampleData.put(dataType, new String("ascii"));
117- break;
118- case BIGINT:
119- sampleData.put(dataType, Long.MAX_VALUE);
120- break;
121- case BLOB:
122- ByteBuffer bb = ByteBuffer.allocate(58);
123- bb.putShort((short) 0xCAFE);
124- bb.flip();
125- sampleData.put(dataType, bb);
126- break;
127- case BOOLEAN:
128- sampleData.put(dataType, Boolean.TRUE);
129- break;
130- case COUNTER:
131- // Not supported in an insert statement
132- break;
133- case DECIMAL:
134- sampleData.put(dataType, new BigDecimal("12.3E+7"));
135- break;
136- case DOUBLE:
137- sampleData.put(dataType, Double.MAX_VALUE);
138- break;
139- case FLOAT:
140- sampleData.put(dataType, Float.MAX_VALUE);
141- break;
142- case INET:
143- try {
144- sampleData.put(dataType, InetAddress.getByName("123.123.123.123"));
145- } catch (java.net.UnknownHostException e) {}
146- break;
147- case INT:
148- sampleData.put(dataType, Integer.MAX_VALUE);
149- break;
150- case TEXT:
151- sampleData.put(dataType, new String("text"));
152- break;
153- case TIMESTAMP:
154- sampleData.put(dataType, new Date(872835240000L));
155- break;
156- case TIMEUUID:
157- sampleData.put(dataType, UUID.fromString("FE2B4360-28C6-11E2-81C1-0800200C9A66"));
158- break;
159- case UUID:
160- sampleData.put(dataType, UUID.fromString("067e6162-3b6f-4ae2-a171-2470b63dff00"));
161- break;
162- case VARCHAR:
163- sampleData.put(dataType, new String("varchar"));
164- break;
165- case VARINT:
166- sampleData.put(dataType, new BigInteger(Integer.toString(Integer.MAX_VALUE) + "000"));
167- break;
168- default:
169- throw new RuntimeException("Missing handling of " + dataType);
170- }
171- }
172-
173- return sampleData;
174- }
175-
176- /**
177- * Generates the sample collections that will be used in testing
178- */ private static HashMap<DataType, Object> getSampleCollections() {
179- HashMap<DataType, Object> sampleCollections = new HashMap<DataType, Object>();
180- HashMap<DataType, Object> setAndListCollection;
181- HashMap<DataType, HashMap<DataType, Object>> mapCollection;
182-
183- for (DataType.Name dataTypeName : DATA_TYPE_NON_PRIMITIVE_NAMES) {
184- switch (dataTypeName) {
185- case LIST:
186- for (DataType typeArgument : DATA_TYPE_PRIMITIVES) {
187- if (exclude(typeArgument))
188- continue;
189-
190- List<Object> list = new ArrayList<Object>();
191- for (int i = 0; i < 5; i++) {
192- list.add(SAMPLE_DATA.get(typeArgument));
193- }
194-
195- setAndListCollection = new HashMap<DataType, Object>();
196- setAndListCollection.put(typeArgument, list);
197- sampleCollections.put(DataType.list(typeArgument), setAndListCollection);
198- }
199- break;
200- case SET:
201- for (DataType typeArgument : DATA_TYPE_PRIMITIVES) {
202- if (exclude(typeArgument))
203- continue;
204-
205- Set<Object> set = new HashSet<Object>();
206- for (int i = 0; i < 5; i++) {
207- set.add(SAMPLE_DATA.get(typeArgument));
208- }
209-
210- setAndListCollection = new HashMap<DataType, Object>();
211- setAndListCollection.put(typeArgument, set);
212- sampleCollections.put(DataType.set(typeArgument), setAndListCollection);
213- }
214- break;
215- case MAP:
216- for (DataType typeArgument1 : DATA_TYPE_PRIMITIVES) {
217- if (exclude(typeArgument1))
218- continue;
219-
220- for (DataType typeArgument2 : DATA_TYPE_PRIMITIVES) {
221- if (exclude(typeArgument2))
222- continue;
223-
224- HashMap<DataType, Object> map = new HashMap<DataType, Object>();
225- map.put(typeArgument1, SAMPLE_DATA.get(typeArgument2));
226-
227- mapCollection = new HashMap<DataType, HashMap<DataType, Object>>();
228- mapCollection.put(typeArgument1, map);
229- sampleCollections.put(DataType.map(typeArgument1, typeArgument2), mapCollection);
230- }
231- }
232- break;
233- default:
234- throw new RuntimeException("Missing handling of " + dataTypeName);
235- }
236- }
237-
238- return sampleCollections;
239- }
240-
241- /**
242- * Helper method to stringify SAMPLE_DATA for simple insert statements
243- */
244- private static String helperStringifiedData(DataType dataType) {
245- String value = SAMPLE_DATA.get(dataType).toString();
246-
247- switch (dataType.getName()) {
248- case BLOB:
249- value = "0xCAFE";
250- break;
251-
252- case INET:
253- InetAddress v1 = (InetAddress) SAMPLE_DATA.get(dataType);
254- value = String.format("'%s'", v1.getHostAddress());
255- break;
256-
257- case TIMESTAMP:
258- Date v2 = (Date) SAMPLE_DATA.get(dataType);
259- value = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").format(v2);
260- case ASCII:
261- case TEXT:
262- case VARCHAR:
263- value = String.format("'%s'", value);
264- break;
265-
266- default:
267- break;
268- }
269-
270- return value;
271- }
272-
273- /**
274- * Generates the insert statements that will be used in testing
275- */
276- private static Collection<String> getPrimitiveInsertStatements() {
277- ArrayList<String> insertStatements = new ArrayList<String>();
278-
279- for (DataType dataType : SAMPLE_DATA.keySet()) {
280- String value = helperStringifiedData(dataType);
281- insertStatements.add(String.format(PRIMITIVE_INSERT_FORMAT, dataType, value));
282- }
283-
284- return insertStatements;
285- }
286-
287- /**
288- * Generates the select statements that will be used in testing
289- */
290- private static HashMap<DataType, String> getPrimitiveSelectStatements() {
291- HashMap<DataType, String> selectStatements = new HashMap<DataType, String>();
292-
293- for (DataType dataType : SAMPLE_DATA.keySet()) {
294- selectStatements.put(dataType, String.format(BASIC_SELECT_FORMAT, dataType));
295- }
296-
297- return selectStatements;
298- }
299-
300- /**
301- * Helper method to generate table names in the form of:
302- * DataType_TypeArgument[_TypeArgument]
303- */
304- private static String helperGenerateTableName(DataType dataType) {
305- String tableName = dataType.getName().toString();
306- for (DataType typeArgument : dataType.getTypeArguments())
307- tableName += "_" + typeArgument;
308-
309- return tableName;
310- }
311-
312- /**
313- * Generates the insert statements that will be used in testing
314- */
315- @SuppressWarnings("unchecked")
316- private static Collection<String> getCollectionInsertStatements() {
317- ArrayList<String> insertStatements = new ArrayList<String>();
318-
319- String tableName;
320- String key;
321- String value;
322- for (DataType dataType : SAMPLE_COLLECTIONS.keySet()) {
323- HashMap<DataType, Object> sampleValueMap = (HashMap<DataType, Object>) SAMPLE_COLLECTIONS.get(dataType);
324-
325- // Create tableName in form of: DataType_TypeArgument[_TypeArgument]
326- tableName = helperGenerateTableName(dataType);
327-
328- if (dataType.getName() == DataType.Name.MAP) {
329- List<DataType> typeArgument = dataType.getTypeArguments();
330-
331- key = helperStringifiedData(typeArgument.get(0));
332- value = helperStringifiedData(typeArgument.get(1));
333-
334- insertStatements.add(String.format(MAP_INSERT_FORMAT, tableName, key, value));
335- } else if (dataType.getName() == DataType.Name.LIST) {
336- DataType typeArgument = sampleValueMap.keySet().iterator().next();
337- key = helperStringifiedData(typeArgument);
338-
339- // Create the value to be a list of the same 5 elements
340- value = "[";
341- for (int i = 0; i < 5; i++)
342- value += key + ',';
343- value = value.substring(0, value.length() - 1) + ']';
344-
345- insertStatements.add(String.format(COLLECTION_INSERT_FORMAT, tableName, key, value));
346- } else {
347- DataType typeArgument = sampleValueMap.keySet().iterator().next();
348- key = helperStringifiedData(typeArgument);
349- value = '{' + key + '}';
350-
351- insertStatements.add(String.format(COLLECTION_INSERT_FORMAT, tableName, key, value));
352- }
353- }
24+import static org.testng.Assert.assertEquals;
25+import static org.testng.Assert.fail;
35426
355- return insertStatements;
356- }
357-
358- /**
359- * Generates the select statements that will be used in testing
360- */
361- private static HashMap<DataType, String> getCollectionSelectStatements() {
362- HashMap<DataType, String> selectStatements = new HashMap<DataType, String>();
363-
364- String tableName;
365- for (DataType dataType : SAMPLE_COLLECTIONS.keySet()) {
366- tableName = helperGenerateTableName(dataType);
367- selectStatements.put(dataType, String.format(BASIC_SELECT_FORMAT, tableName));
368- }
369-
370- return selectStatements;
371- }
372-
373- /**
374- * Test simple statement inserts for all primitive data types
375- */
376- public void primitiveInsertTest() throws Throwable {
377- ResultSet rs;
378- for (String execute_string : PRIMITIVE_INSERT_STATEMENTS) {
379- rs = session.execute(execute_string);
380- assertTrue(rs.isExhausted());
381- }
382- assertEquals(SAMPLE_DATA.size(), 15);
383- assertEquals(PRIMITIVE_INSERT_STATEMENTS.size(), SAMPLE_DATA.size());
384- }
385-
386- /**
387- * Validate simple statement selects for all primitive data types
388- */
389- public void primitiveSelectTest() throws Throwable {
390- String execute_string;
391- Object value;
392- Row row;
393- for (DataType dataType : PRIMITIVE_SELECT_STATEMENTS.keySet()) {
394- execute_string = PRIMITIVE_SELECT_STATEMENTS.get(dataType);
395- row = session.execute(execute_string).one();
396-
397- value = SAMPLE_DATA.get(dataType);
398- assertEquals(TestUtils.getValue(row, "k", dataType), value);
399- assertEquals(TestUtils.getValue(row, "v", dataType), value);
400- }
401- assertEquals(SAMPLE_DATA.size(), 15);
402- assertEquals(PRIMITIVE_SELECT_STATEMENTS.keySet().size(), SAMPLE_DATA.size());
403- }
404-
405- /**
406- * Test simple statement inserts and selects for all primitive data types
407- */
408- @Test(groups = "long")
409- public void primitiveTests() throws Throwable {
410- primitiveInsertTest();
411- primitiveSelectTest();
412- }
413-
414- /**
415- * Test simple statement inserts for all collection data types
416- */
417- public void collectionInsertTest() throws Throwable {
418- ResultSet rs;
419- for (String execute_string : COLLECTION_INSERT_STATEMENTS) {
420- rs = session.execute(execute_string);
421- assertTrue(rs.isExhausted());
422- }
423- assertEquals(SAMPLE_COLLECTIONS.size(), 255);
424- assertEquals(COLLECTION_INSERT_STATEMENTS.size(), SAMPLE_COLLECTIONS.size());
425- }
426-
427- /**
428- * Test simple statement selects for all collection data types
429- */
430- @SuppressWarnings("unchecked")
431- public void collectionSelectTest() throws Throwable {
432- HashMap<DataType, Object> sampleValueMap;
433- String execute_string;
434- DataType typeArgument1;
435- DataType typeArgument2;
436- Row row;
437- for (DataType dataType : COLLECTION_SELECT_STATEMENTS.keySet()) {
438- execute_string = COLLECTION_SELECT_STATEMENTS.get(dataType);
439- row = session.execute(execute_string).one();
440-
441- sampleValueMap = (HashMap<DataType, Object>) SAMPLE_COLLECTIONS.get(dataType);
442- typeArgument1 = dataType.getTypeArguments().get(0);
443- if (dataType.getName() == DataType.Name.MAP) {
444- typeArgument2 = dataType.getTypeArguments().get(1);
445-
446- // Create a copy of the map that is being expected
447- HashMap<DataType, Object> sampleMap = (HashMap<DataType, Object>) sampleValueMap.get(typeArgument1);
448- Object mapKey = SAMPLE_DATA.get(sampleMap.keySet().iterator().next());
449- Object mapValue = sampleMap.values().iterator().next();
450- HashMap<Object, Object> expectedMap = new HashMap<Object, Object>();
451- expectedMap.put(mapKey, mapValue);
452-
453- assertEquals(TestUtils.getValue(row, "k", typeArgument2), SAMPLE_DATA.get(typeArgument2));
454- assertEquals(TestUtils.getValue(row, "v", dataType), expectedMap);
455- } else {
456- Object expectedValue = sampleValueMap.get(typeArgument1);
457-
458- assertEquals(TestUtils.getValue(row, "k", typeArgument1), SAMPLE_DATA.get(typeArgument1));
459- assertEquals(TestUtils.getValue(row, "v", dataType), expectedValue);
460- }
461- }
462- assertEquals(SAMPLE_COLLECTIONS.size(), 255);
463- assertEquals(COLLECTION_SELECT_STATEMENTS.keySet().size(), SAMPLE_COLLECTIONS.size());
464- }
27+import com.datastax.driver.core.exceptions.InvalidTypeException;
46528
466- /**
467- * Test simple statement inserts and selects for all collection data types
468- */
469- @Test(groups = "long")
470- public void collectionTest() throws Throwable {
471- collectionInsertTest();
472- collectionSelectTest();
473- }
29+public class DataTypeTest {
47430
475- // The two following tests a really unit tests, but since the whole uses
476- // CCMBridge.PerClassSingleNodeCluster, they'll still spawn a cluster even
477- // you execute only them, so we keep them in the "long" group. We could
478- // move them in another class but not sure where honestly (one could argue
479- // that it would make more sense to move all the *other* tests to some
480- // DataTypeIntegrationTest class).
481- @Test(groups = "long")
31+ @Test(groups = "unit")
48232 public void serializeDeserializeTest() {
48333
484- for (DataType dt : DataType.allPrimitiveTypes())
485- {
486- if (exclude(dt))
34+ for (DataType dt : DataType.allPrimitiveTypes()) {
35+ if (dt.getName() == DataType.Name.COUNTER)
48736 continue;
48837
48938 Object value = TestUtils.getFixedValue(dt);
@@ -502,7 +51,7 @@
50251 } catch (InvalidTypeException e) { /* That's what we want */ }
50352 }
50453
505- @Test(groups = "long")
54+ @Test(groups = "unit")
50655 public void serializeDeserializeCollectionsTest() {
50756
50857 List<String> l = Arrays.asList("foo", "bar");
@@ -515,150 +64,4 @@
51564 fail("This should not have worked");
51665 } catch (InvalidTypeException e) { /* That's what we want */ }
51766 }
518-
519- @Test(groups = "short")
520- @CassandraVersion(major=2.0, minor=0, description="This feature requires protocol v2")
521- public void primitiveInsertWithValueTest() throws Throwable {
522- for (DataType dt : DataType.allPrimitiveTypes()) {
523- if (exclude(dt))
524- continue;
525-
526- session.execute(String.format(PRIMITIVE_INSERT_FORMAT, dt, "?"), SAMPLE_DATA.get(dt), SAMPLE_DATA.get(dt));
527- }
528- // Kind of checking results (kind of because the schema used by this class make it ultra painful
529- // somehow to use a different partition for different tests, so that the insert done here actually
530- // conflict with the one in primitiveInsertTest. So all we check is that we don't write something
531- // horribly wrong, but if the inserts of this test where to do nothing, the following check might
532- // not work. We should fix the schema used by this class)
533- primitiveSelectTest();
534- }
535-
536- /**
537- * Prints the table definitions that will be used in testing
538- * (for exporting purposes)
539- */
540- @Test(groups = "doc")
541- public void printTableDefinitions() {
542- String objective = "Table Definitions";
543- System.out.println(String.format("Printing %s...", objective));
544-
545- // Prints the full list of table definitions
546- for (String definition : getTableDefinitions()) {
547- System.out.println(definition);
548- }
549-
550- System.out.println(String.format("\nEnd of %s\n\n", objective));
551- }
552-
553- /**
554- * Prints the sample data that will be used in testing
555- * (for exporting purposes)
556- */
557- @Test(groups = "doc")
558- public void printSampleData() {
559- String objective = "Sample Data";
560- System.out.println(String.format("Printing %s...", objective));
561-
562- for (DataType dataType : SAMPLE_DATA.keySet()) {
563- Object sampleValue = SAMPLE_DATA.get(dataType);
564- System.out.println(String.format("%1$-10s %2$s", dataType, sampleValue));
565- }
566-
567- System.out.println(String.format("\nEnd of %s\n\n", objective));
568- }
569-
570- /**
571- * Prints the sample collections that will be used in testing
572- * (for exporting purposes)
573- */
574- @Test(groups = "doc")
575- @SuppressWarnings("unchecked")
576- public void printSampleCollections() {
577- String objective = "Sample Collections";
578- System.out.println(String.format("Printing %s...", objective));
579-
580- for (DataType dataType : SAMPLE_COLLECTIONS.keySet()) {
581- HashMap<DataType, Object> sampleValueMap = (HashMap<DataType, Object>) SAMPLE_COLLECTIONS.get(dataType);
582-
583- if (dataType.getName() == DataType.Name.MAP) {
584- DataType typeArgument = sampleValueMap.keySet().iterator().next();
585- HashMap<DataType, Object> sampleMap = (HashMap<DataType, Object>) sampleValueMap.get(typeArgument);
586-
587- Object mapKey = SAMPLE_DATA.get(typeArgument);
588- Object mapValue = sampleMap.get(typeArgument);
589- System.out.println(String.format("%1$-30s {%2$s : %3$s}", dataType, mapKey, mapValue));
590- } else {
591- DataType typeArgument = sampleValueMap.keySet().iterator().next();
592- Object sampleValue = sampleValueMap.get(typeArgument);
593-
594- System.out.println(String.format("%1$-30s %2$s", dataType, sampleValue));
595- }
596- }
597-
598- System.out.println(String.format("\nEnd of %s\n\n", objective));
599- }
600-
601- /**
602- * Prints the simple insert statements that will be used in testing
603- * (for exporting purposes)
604- */
605- @Test(groups = "doc")
606- public void printPrimitiveInsertStatements() {
607- String objective = "Primitive Insert Statements";
608- System.out.println(String.format("Printing %s...", objective));
609-
610- for (String execute_string : PRIMITIVE_INSERT_STATEMENTS) {
611- System.out.println(execute_string);
612- }
613-
614- System.out.println(String.format("\nEnd of %s\n\n", objective));
615- }
616-
617- /**
618- * Prints the simple select statements that will be used in testing
619- * (for exporting purposes)
620- */
621- @Test(groups = "doc")
622- public void printPrimitiveSelectStatements() {
623- String objective = "Primitive Select Statements";
624- System.out.println(String.format("Printing %s...", objective));
625-
626- for (String execute_string : PRIMITIVE_SELECT_STATEMENTS.values()) {
627- System.out.println(execute_string);
628- }
629-
630- System.out.println(String.format("\nEnd of %s\n\n", objective));
631- }
632-
633- /**
634- * Prints the simple insert statements that will be used in testing
635- * (for exporting purposes)
636- */
637- @Test(groups = "doc")
638- public void printCollectionInsertStatements() {
639- String objective = "Collection Insert Statements";
640- System.out.println(String.format("Printing %s...", objective));
641-
642- for (String execute_string : COLLECTION_INSERT_STATEMENTS) {
643- System.out.println(execute_string);
644- }
645-
646- System.out.println(String.format("\nEnd of %s\n\n", objective));
647- }
648-
649- /**
650- * Prints the simple insert statements that will be used in testing
651- * (for exporting purposes)
652- */
653- @Test(groups = "doc")
654- public void printCollectionSelectStatements() {
655- String objective = "Collection Select Statements";
656- System.out.println(String.format("Printing %s...", objective));
657-
658- for (String execute_string : COLLECTION_SELECT_STATEMENTS.values()) {
659- System.out.println(execute_string);
660- }
661-
662- System.out.println(String.format("\nEnd of %s\n\n", objective));
663- }
66467 }
added driver-core/src/test/java/com/datastax/driver/core/PrimitiveTypeSamples.java +75 −0
@@ -0,0 +1,75 @@
1+/*
2+ * Copyright (C) 2012-2014 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core;
17+
18+import java.math.BigDecimal;
19+import java.math.BigInteger;
20+import java.net.InetAddress;
21+import java.net.UnknownHostException;
22+import java.util.Date;
23+import java.util.List;
24+import java.util.Map;
25+import java.util.UUID;
26+
27+import com.google.common.collect.ImmutableMap;
28+import com.google.common.collect.Lists;
29+
30+import static org.assertj.core.api.Assertions.assertThat;
31+
32+import com.datastax.driver.core.utils.Bytes;
33+
34+/**
35+ * This class provides sample values for each primitive data type.
36+ *
37+ * These values have no particular meaning, the goal is just to have an instance that can be used in automated tests.
38+ */
39+public class PrimitiveTypeSamples {
40+
41+ public static final Map<DataType, Object> ALL = generateAll();
42+
43+ private static Map<DataType, Object> generateAll() {
44+ try {
45+ ImmutableMap<DataType, Object> result = ImmutableMap.<DataType, Object>builder()
46+ .put(DataType.ascii(), "ascii")
47+ .put(DataType.bigint(), Long.MAX_VALUE)
48+ .put(DataType.blob(), Bytes.fromHexString("0xCAFE"))
49+ .put(DataType.cboolean(), Boolean.TRUE)
50+ .put(DataType.decimal(), new BigDecimal("12.3E+7"))
51+ .put(DataType.cdouble(), Double.MAX_VALUE)
52+ .put(DataType.cfloat(), Float.MAX_VALUE)
53+ .put(DataType.inet(), InetAddress.getByName("123.123.123.123"))
54+ .put(DataType.cint(), Integer.MAX_VALUE)
55+ .put(DataType.text(), "text")
56+ .put(DataType.varchar(), "text")
57+ .put(DataType.timestamp(), new Date(872835240000L))
58+ .put(DataType.timeuuid(), UUID.fromString("FE2B4360-28C6-11E2-81C1-0800200C9A66"))
59+ .put(DataType.uuid(), UUID.fromString("067e6162-3b6f-4ae2-a171-2470b63dff00"))
60+ .put(DataType.varint(), new BigInteger(Integer.toString(Integer.MAX_VALUE) + "000"))
61+ .build();
62+
63+ // Check that we cover all types (except counter)
64+ List<DataType> tmp = Lists.newArrayList(DataType.allPrimitiveTypes());
65+ tmp.removeAll(result.keySet());
66+ assertThat(tmp)
67+ .as("new datatype not covered in test")
68+ .containsOnly(DataType.counter());
69+
70+ return result;
71+ } catch (UnknownHostException e) {
72+ throw new AssertionError(e);
73+ }
74+ }
75+}
No newline at the end of the file