1 /*******************************************************************************
2 * ============LICENSE_START==========================================
4 * ===================================================================
5 * Copyright (c) 2019 AT&T Intellectual Property
6 * ===================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
19 * ============LICENSE_END=============================================
20 * ====================================================================
21 *******************************************************************************/
22 package org.onap.music.datastore;
24 import static org.junit.Assert.*;
25 import java.math.BigInteger;
26 import java.nio.ByteBuffer;
27 import java.util.ArrayList;
28 import java.util.HashMap;
29 import java.util.Iterator;
30 import java.util.List;
32 import java.util.UUID;
33 import java.util.function.Consumer;
34 import org.junit.Before;
35 import org.junit.Test;
36 import org.junit.runner.RunWith;
37 import org.mockito.ArgumentCaptor;
38 import org.mockito.Mock;
39 import org.mockito.Mockito;
40 import org.mockito.junit.MockitoJUnitRunner;
41 import org.onap.music.exceptions.MusicQueryException;
42 import org.onap.music.exceptions.MusicServiceException;
43 import org.onap.music.main.MusicUtil;
44 import com.datastax.driver.core.Cluster;
45 import com.datastax.driver.core.CodecRegistry;
46 import com.datastax.driver.core.ColumnDefinitions;
47 import com.datastax.driver.core.ColumnDefinitions.Definition;
48 import com.datastax.driver.core.exceptions.WriteTimeoutException;
49 import com.datastax.driver.core.ColumnMetadata;
50 import com.datastax.driver.core.Configuration;
51 import com.datastax.driver.core.ConsistencyLevel;
52 import com.datastax.driver.core.DataType;
53 import com.datastax.driver.core.KeyspaceMetadata;
54 import com.datastax.driver.core.Metadata;
55 import com.datastax.driver.core.ResultSet;
56 import com.datastax.driver.core.Row;
57 import com.datastax.driver.core.Session;
58 import com.datastax.driver.core.SimpleStatement;
59 import com.datastax.driver.core.Statement;
60 import com.datastax.driver.core.TableMetadata;
61 import com.datastax.driver.core.WriteType;
63 @RunWith(MockitoJUnitRunner.class)
64 public class MusicDataStoreTest {
66 MusicDataStore dataStore;
75 public void before() {
76 CodecRegistry cr = Mockito.mock(CodecRegistry.class);
77 Configuration config = Mockito.mock(Configuration.class);
78 Mockito.when(cluster.getConfiguration()).thenReturn(config);
79 Mockito.when(config.getCodecRegistry()).thenReturn(cr);
80 dataStore = new MusicDataStore(cluster, session);
85 public void testMusicDataStoreClusterSession() {
86 Session session = Mockito.mock(Session.class);
87 Cluster cluster = Mockito.mock(Cluster.class);
89 CodecRegistry cr = Mockito.mock(CodecRegistry.class);
90 Configuration config = Mockito.mock(Configuration.class);
91 Mockito.when(cluster.getConfiguration()).thenReturn(config);
92 Mockito.when(config.getCodecRegistry()).thenReturn(cr);
95 MusicDataStore mds = new MusicDataStore(cluster, session);
96 assertEquals(session, mds.getSession());
97 assertEquals(cluster, mds.getCluster());
101 public void testSession() {
102 Session session = Mockito.mock(Session.class);
103 dataStore.setSession(session);
104 assertEquals(session, dataStore.getSession());
108 public void testCluster() {
109 Cluster cluster = Mockito.mock(Cluster.class);
110 CodecRegistry cr = Mockito.mock(CodecRegistry.class);
111 Configuration config = Mockito.mock(Configuration.class);
112 Mockito.when(cluster.getConfiguration()).thenReturn(config);
113 Mockito.when(config.getCodecRegistry()).thenReturn(cr);
115 dataStore.setCluster(cluster);
116 assertEquals(cluster, dataStore.getCluster());
120 public void testClose() {
122 Mockito.verify(session).close();
126 public void testReturnColumnDataType() {
127 Metadata meta = Mockito.mock(Metadata.class);
128 Mockito.when(cluster.getMetadata()).thenReturn(meta);
129 KeyspaceMetadata ksmd = Mockito.mock(KeyspaceMetadata.class);
130 Mockito.when(meta.getKeyspace("keyspace")).thenReturn(ksmd);
131 TableMetadata tmd = Mockito.mock(TableMetadata.class);
132 Mockito.when(ksmd.getTable("table")).thenReturn(tmd);
133 ColumnMetadata cmd = Mockito.mock(ColumnMetadata.class);
134 Mockito.when(tmd.getColumn("columnName")).thenReturn(cmd);
135 Mockito.when(cmd.getType()).thenReturn(com.datastax.driver.core.DataType.text());
137 com.datastax.driver.core.DataType dt = dataStore.returnColumnDataType("keyspace", "table", "columnName");
138 assertEquals(com.datastax.driver.core.DataType.text(), dt);
142 public void testReturnColumnMetadata() {
143 Metadata meta = Mockito.mock(Metadata.class);
144 Mockito.when(cluster.getMetadata()).thenReturn(meta);
145 KeyspaceMetadata ksmd = Mockito.mock(KeyspaceMetadata.class);
146 Mockito.when(meta.getKeyspace("keyspace")).thenReturn(ksmd);
147 TableMetadata tmd = Mockito.mock(TableMetadata.class);
148 Mockito.when(ksmd.getTable("tableName")).thenReturn(tmd);
150 dataStore.returnColumnMetadata("keyspace", "tableName");
151 assertEquals(tmd, dataStore.returnColumnMetadata("keyspace", "tableName"));
155 public void testReturnKeyspaceMetadata() {
156 Metadata meta = Mockito.mock(Metadata.class);
157 Mockito.when(cluster.getMetadata()).thenReturn(meta);
158 KeyspaceMetadata ksmd = Mockito.mock(KeyspaceMetadata.class);
159 Mockito.when(meta.getKeyspace("keyspace")).thenReturn(ksmd);
161 assertEquals(ksmd, dataStore.returnKeyspaceMetadata("keyspace"));
165 public void testGetColValue() {
166 Row row = Mockito.mock(Row.class);
167 Mockito.when(row.getString("columnName")).thenReturn("value");
168 UUID uuid = UUID.randomUUID();
169 Mockito.when(row.getUUID("columnName")).thenReturn(uuid);
170 Mockito.when(row.getVarint("columnName")).thenReturn(BigInteger.ONE);
171 Mockito.when(row.getLong("columnName")).thenReturn((long) 117);
172 Mockito.when(row.getInt("columnName")).thenReturn(5);
173 Mockito.when(row.getFloat("columnName")).thenReturn(Float.MAX_VALUE);
174 Mockito.when(row.getDouble("columnName")).thenReturn(Double.valueOf("2.5"));
175 Mockito.when(row.getBool("columnName")).thenReturn(true);
176 Mockito.when(row.getMap("columnName", String.class, String.class)).thenReturn(new HashMap<String, String>());
177 Mockito.when(row.getList("columnName", String.class)).thenReturn(new ArrayList<String>());
180 assertEquals("value", dataStore.getColValue(row, "columnName", DataType.varchar()));
181 assertEquals(uuid, dataStore.getColValue(row, "columnName", DataType.uuid()));
182 assertEquals(BigInteger.ONE, dataStore.getColValue(row, "columnName", DataType.varint()));
183 assertEquals((long) 117, dataStore.getColValue(row, "columnName", DataType.bigint()));
184 assertEquals(5, dataStore.getColValue(row, "columnName", DataType.cint()));
185 assertEquals(Float.MAX_VALUE, dataStore.getColValue(row, "columnName", DataType.cfloat()));
186 assertEquals(2.5, dataStore.getColValue(row, "columnName", DataType.cdouble()));
187 assertEquals(true, dataStore.getColValue(row, "columnName", DataType.cboolean()));
188 assertEquals(0, ((Map<String, String>) dataStore.getColValue(row, "columnName",
189 DataType.map(DataType.varchar(), DataType.varchar()))).size());
191 ((List<String>) dataStore.getColValue(row, "columnName", DataType.list(DataType.varchar()))).size());
195 public void testGetBlobValue() {
196 Row row = Mockito.mock(Row.class);
197 Mockito.when(row.getBytes("col")).thenReturn(ByteBuffer.allocate(16));
199 byte[] byteArray = dataStore.getBlobValue(row, "col", DataType.blob());
200 assertEquals(16, byteArray.length);
204 public void testDoesRowSatisfyCondition() throws Exception {
205 Row row = Mockito.mock(Row.class);
206 ColumnDefinitions cd = Mockito.mock(ColumnDefinitions.class);
207 Mockito.when(row.getColumnDefinitions()).thenReturn(cd);
208 Mockito.when(cd.getType("col1")).thenReturn(DataType.varchar());
210 Map<String, Object> condition = new HashMap<>();
211 condition.put("col1", "val1");
213 Mockito.when(row.getString("col1")).thenReturn("val1");
215 assertTrue(dataStore.doesRowSatisfyCondition(row, condition));
217 condition.put("col1", "val2");
218 assertFalse(dataStore.doesRowSatisfyCondition(row, condition));
222 public void testMarshalData() {
223 ResultSet results = Mockito.mock(ResultSet.class);
224 Row row = Mockito.mock(Row.class);
225 Mockito.when(row.getString("colName")).thenReturn("rowValue");
226 //mock for (Row row: results)
227 Iterator mockIterator = Mockito.mock(Iterator.class);
228 //Mockito.doCallRealMethod().when(results).forEach(Mockito.any(Consumer.class));
229 Mockito.when(results.iterator()).thenReturn(mockIterator);
230 Mockito.when(mockIterator.hasNext()).thenReturn(true, false);
231 Mockito.when(mockIterator.next()).thenReturn(row);
233 ColumnDefinitions cd = Mockito.mock(ColumnDefinitions.class);
234 Mockito.when(row.getColumnDefinitions()).thenReturn(cd);
235 //for (Definition: colDefinitions)
236 Iterator mockIterator2 = Mockito.mock(Iterator.class);
237 //Mockito.doCallRealMethod().when(cd).forEach(Mockito.any(Consumer.class));
238 Mockito.when(cd.iterator()).thenReturn(mockIterator2);
239 Mockito.when(mockIterator2.hasNext()).thenReturn(true, false);
240 Definition def = Mockito.mock(Definition.class);
241 Mockito.when(mockIterator2.next()).thenReturn(def);
242 Mockito.when(def.getType()).thenReturn(DataType.varchar());
243 Mockito.when(def.getName()).thenReturn("colName");
245 Map<String, HashMap<String, Object>> data = dataStore.marshalData(results);
246 System.out.println("Marshalled data: " + data);
248 assertTrue(data.containsKey("row 0"));
249 assertEquals("rowValue", data.get("row 0").get("colName"));
252 private ArgumentCaptor<SimpleStatement> sessionExecuteResponse() {
253 ResultSet rs = Mockito.mock(ResultSet.class);
254 Mockito.when(session.execute(Mockito.any(Statement.class))).thenReturn(rs);
256 ArgumentCaptor<SimpleStatement> argument = ArgumentCaptor.forClass(SimpleStatement.class);
261 public void testExecutePutPreparedQueryObjectString() throws Exception {
262 ArgumentCaptor<SimpleStatement> argument = sessionExecuteResponse();
263 String queryString = "INSERT INTO cycling.cyclist_name (lastname, firstname) VALUES (?,?);";
264 String lastName = "KRUIKSWIJK";
265 String firstName = "Steven";
267 PreparedQueryObject query = new PreparedQueryObject(queryString, lastName, firstName);
268 dataStore.executePut(query, MusicUtil.CRITICAL);
270 Mockito.verify(session).execute(argument.capture());
271 assertEquals(ConsistencyLevel.QUORUM, argument.getValue().getConsistencyLevel());
272 assertEquals(queryString, argument.getValue().getQueryString());
273 assertEquals(2, argument.getValue().valuesCount());
277 public void testExecutePut_ONE() throws Exception {
278 ArgumentCaptor<SimpleStatement> argument = sessionExecuteResponse();
279 String queryString = "INSERT INTO cycling.cyclist_name (lastname, firstname) VALUES (?,?);";
280 String lastName = "KRUIKSWIJK";
281 String firstName = "Steven";
283 PreparedQueryObject query = new PreparedQueryObject(queryString, lastName, firstName);
284 dataStore.executePut(query, MusicUtil.ONE);
286 Mockito.verify(session).execute(argument.capture());
287 assertEquals(ConsistencyLevel.ONE, argument.getValue().getConsistencyLevel());
288 assertEquals(queryString, argument.getValue().getQueryString());
289 assertEquals(2, argument.getValue().valuesCount());
293 public void testExecutePut_quorum() throws Exception {
294 ArgumentCaptor<SimpleStatement> argument = sessionExecuteResponse();
295 String queryString = "INSERT INTO cycling.cyclist_name (lastname, firstname) VALUES (?,?);";
296 String lastName = "KRUIKSWIJK";
297 String firstName = "Steven";
299 PreparedQueryObject query = new PreparedQueryObject(queryString, lastName, firstName);
300 dataStore.executePut(query, MusicUtil.QUORUM);
302 Mockito.verify(session).execute(argument.capture());
304 assertEquals(ConsistencyLevel.LOCAL_QUORUM, argument.getValue().getConsistencyLevel());
305 assertEquals(queryString, argument.getValue().getQueryString());
306 assertEquals(2, argument.getValue().valuesCount());
310 public void testExecutePut_ALL() throws Exception {
311 ArgumentCaptor<SimpleStatement> argument = sessionExecuteResponse();
312 String queryString = "INSERT INTO cycling.cyclist_name (lastname, firstname) VALUES (?,?);";
313 String lastName = "KRUIKSWIJK";
314 String firstName = "Steven";
316 PreparedQueryObject query = new PreparedQueryObject(queryString, lastName, firstName);
317 dataStore.executePut(query, MusicUtil.ALL);
319 Mockito.verify(session).execute(argument.capture());
320 assertEquals(ConsistencyLevel.ALL, argument.getValue().getConsistencyLevel());
321 assertEquals(queryString, argument.getValue().getQueryString());
322 assertEquals(2, argument.getValue().valuesCount());
325 @Test(expected = MusicQueryException.class)
326 public void testExecutePut_BadQueryObj() throws Exception {
327 String queryString = "INSERT INTO cycling.cyclist_name (lastname, firstname) VALUES (?,?);";
328 String lastName = "KRUIKSWIJK";
329 String firstName = "Steven";
331 //Provide extra value here, middle initial
332 PreparedQueryObject query = new PreparedQueryObject(queryString, lastName, firstName, "P");
334 dataStore.executePut(query, MusicUtil.CRITICAL);
335 } catch (Exception e) {
336 System.out.println(e.getMessage());
340 fail("Should have throw error");
344 public void testExecutePutPreparedQueryObjectStringLong() throws Exception {
345 ArgumentCaptor<SimpleStatement> argument = sessionExecuteResponse();
346 String queryString = "INSERT INTO cycling.cyclist_name (lastname, firstname) VALUES ('KRUIKSWIJK','Steven');";
349 PreparedQueryObject query = new PreparedQueryObject(queryString);
350 dataStore.executePut(query, MusicUtil.EVENTUAL, 10);
352 Mockito.verify(session).execute(argument.capture());
353 assertEquals(ConsistencyLevel.ONE, argument.getValue().getConsistencyLevel());
354 assertEquals(queryString, argument.getValue().getQueryString());
358 public void testExecuteGet() throws Exception {
359 ArgumentCaptor<SimpleStatement> argument = sessionExecuteResponse();
361 PreparedQueryObject query = new PreparedQueryObject("SELECT * FROM KEYSPACE.TABLE");
363 dataStore.executeGet(query, MusicUtil.ONE);
365 Mockito.verify(session).execute(argument.capture());
366 assertEquals(ConsistencyLevel.ONE, argument.getValue().getConsistencyLevel());
367 assertEquals("SELECT * FROM KEYSPACE.TABLE", argument.getValue().getQueryString());
370 @Test (expected = MusicQueryException.class)
371 public void testExecuteGet_badQuery() throws Exception {
372 ArgumentCaptor<SimpleStatement> argument = sessionExecuteResponse();
374 PreparedQueryObject query = new PreparedQueryObject("SELECT * FROM KEYSPACE.TABLE", "broken");
376 dataStore.executeGet(query, MusicUtil.ONE);
378 Mockito.verify(session).execute(argument.capture());
379 assertEquals(ConsistencyLevel.ONE, argument.getValue().getConsistencyLevel());
380 assertEquals("SELECT * FROM KEYSPACE.TABLE", argument.getValue().getQueryString());
384 public void testExecuteOneConsistencyGet() throws Exception {
385 ArgumentCaptor<SimpleStatement> argument = sessionExecuteResponse();
386 PreparedQueryObject query = new PreparedQueryObject("SELECT * FROM KEYSPACE.TABLE");
388 dataStore.executeOneConsistencyGet(query);
391 Mockito.verify(session).execute(argument.capture());
392 assertEquals(ConsistencyLevel.ONE, argument.getValue().getConsistencyLevel());
393 assertEquals("SELECT * FROM KEYSPACE.TABLE", argument.getValue().getQueryString());
397 public void testExecuteLocalQuorumConsistencyGet() throws Exception {
398 ArgumentCaptor<SimpleStatement> argument = sessionExecuteResponse();
399 PreparedQueryObject query = new PreparedQueryObject("SELECT * FROM KEYSPACE.TABLE");
401 dataStore.executeLocalQuorumConsistencyGet(query);
403 Mockito.verify(session).execute(argument.capture());
404 assertEquals(ConsistencyLevel.LOCAL_QUORUM, argument.getValue().getConsistencyLevel());
405 assertEquals("SELECT * FROM KEYSPACE.TABLE", argument.getValue().getQueryString());
409 public void testExecuteQuorumConsistencyGet() throws Exception {
410 ArgumentCaptor<SimpleStatement> argument = sessionExecuteResponse();
411 PreparedQueryObject query = new PreparedQueryObject("SELECT * FROM KEYSPACE.TABLE");
413 dataStore.executeQuorumConsistencyGet(query);
415 Mockito.verify(session).execute(argument.capture());
416 assertEquals(ConsistencyLevel.QUORUM, argument.getValue().getConsistencyLevel());
417 assertEquals("SELECT * FROM KEYSPACE.TABLE", argument.getValue().getQueryString());
422 public void testExecutePut() {
423 Mockito.when(session.execute(Mockito.any(SimpleStatement.class)))
424 .thenThrow(new WriteTimeoutException(ConsistencyLevel.QUORUM, WriteType.CAS, 1, 3));
427 dataStore.executePut(new PreparedQueryObject("Test query"), "critical");
428 } catch (MusicServiceException e) {
430 } catch (MusicQueryException e) {
431 // should never reach here