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);
84 public void testMusicDataStore() {
85 //MusicDataStore mds = new MusicDataStore();
89 public void testMusicDataStoreClusterSession() {
90 Session session = Mockito.mock(Session.class);
91 Cluster cluster = Mockito.mock(Cluster.class);
93 CodecRegistry cr = Mockito.mock(CodecRegistry.class);
94 Configuration config = Mockito.mock(Configuration.class);
95 Mockito.when(cluster.getConfiguration()).thenReturn(config);
96 Mockito.when(config.getCodecRegistry()).thenReturn(cr);
99 MusicDataStore mds = new MusicDataStore(cluster, session);
100 assertEquals(session, mds.getSession());
101 assertEquals(cluster, mds.getCluster());
105 public void testSession() {
106 Session session = Mockito.mock(Session.class);
107 dataStore.setSession(session);
108 assertEquals(session, dataStore.getSession());
112 public void testCluster() {
113 Cluster cluster = Mockito.mock(Cluster.class);
114 CodecRegistry cr = Mockito.mock(CodecRegistry.class);
115 Configuration config = Mockito.mock(Configuration.class);
116 Mockito.when(cluster.getConfiguration()).thenReturn(config);
117 Mockito.when(config.getCodecRegistry()).thenReturn(cr);
119 dataStore.setCluster(cluster);
120 assertEquals(cluster, dataStore.getCluster());
124 public void testClose() {
126 Mockito.verify(session).close();
130 public void testReturnColumnDataType() {
131 Metadata meta = Mockito.mock(Metadata.class);
132 Mockito.when(cluster.getMetadata()).thenReturn(meta);
133 KeyspaceMetadata ksmd = Mockito.mock(KeyspaceMetadata.class);
134 Mockito.when(meta.getKeyspace("keyspace")).thenReturn(ksmd);
135 TableMetadata tmd = Mockito.mock(TableMetadata.class);
136 Mockito.when(ksmd.getTable("table")).thenReturn(tmd);
137 ColumnMetadata cmd = Mockito.mock(ColumnMetadata.class);
138 Mockito.when(tmd.getColumn("columnName")).thenReturn(cmd);
139 Mockito.when(cmd.getType()).thenReturn(com.datastax.driver.core.DataType.text());
141 com.datastax.driver.core.DataType dt = dataStore.returnColumnDataType("keyspace", "table", "columnName");
142 assertEquals(com.datastax.driver.core.DataType.text(), dt);
146 public void testReturnColumnMetadata() {
147 Metadata meta = Mockito.mock(Metadata.class);
148 Mockito.when(cluster.getMetadata()).thenReturn(meta);
149 KeyspaceMetadata ksmd = Mockito.mock(KeyspaceMetadata.class);
150 Mockito.when(meta.getKeyspace("keyspace")).thenReturn(ksmd);
151 TableMetadata tmd = Mockito.mock(TableMetadata.class);
152 Mockito.when(ksmd.getTable("tableName")).thenReturn(tmd);
154 dataStore.returnColumnMetadata("keyspace", "tableName");
155 assertEquals(tmd, dataStore.returnColumnMetadata("keyspace", "tableName"));
159 public void testReturnKeyspaceMetadata() {
160 Metadata meta = Mockito.mock(Metadata.class);
161 Mockito.when(cluster.getMetadata()).thenReturn(meta);
162 KeyspaceMetadata ksmd = Mockito.mock(KeyspaceMetadata.class);
163 Mockito.when(meta.getKeyspace("keyspace")).thenReturn(ksmd);
165 assertEquals(ksmd, dataStore.returnKeyspaceMetadata("keyspace"));
169 public void testGetColValue() {
170 Row row = Mockito.mock(Row.class);
171 Mockito.when(row.getString("columnName")).thenReturn("value");
172 UUID uuid = UUID.randomUUID();
173 Mockito.when(row.getUUID("columnName")).thenReturn(uuid);
174 Mockito.when(row.getVarint("columnName")).thenReturn(BigInteger.ONE);
175 Mockito.when(row.getLong("columnName")).thenReturn((long) 117);
176 Mockito.when(row.getInt("columnName")).thenReturn(5);
177 Mockito.when(row.getFloat("columnName")).thenReturn(Float.MAX_VALUE);
178 Mockito.when(row.getDouble("columnName")).thenReturn(Double.valueOf("2.5"));
179 Mockito.when(row.getBool("columnName")).thenReturn(true);
180 Mockito.when(row.getMap("columnName", String.class, String.class)).thenReturn(new HashMap<String, String>());
181 Mockito.when(row.getList("columnName", String.class)).thenReturn(new ArrayList<String>());
184 assertEquals("value", dataStore.getColValue(row, "columnName", DataType.varchar()));
185 assertEquals(uuid, dataStore.getColValue(row, "columnName", DataType.uuid()));
186 assertEquals(BigInteger.ONE, dataStore.getColValue(row, "columnName", DataType.varint()));
187 assertEquals((long) 117, dataStore.getColValue(row, "columnName", DataType.bigint()));
188 assertEquals(5, dataStore.getColValue(row, "columnName", DataType.cint()));
189 assertEquals(Float.MAX_VALUE, dataStore.getColValue(row, "columnName", DataType.cfloat()));
190 assertEquals(2.5, dataStore.getColValue(row, "columnName", DataType.cdouble()));
191 assertEquals(true, dataStore.getColValue(row, "columnName", DataType.cboolean()));
192 assertEquals(0, ((Map<String, String>) dataStore.getColValue(row, "columnName",
193 DataType.map(DataType.varchar(), DataType.varchar()))).size());
195 ((List<String>) dataStore.getColValue(row, "columnName", DataType.list(DataType.varchar()))).size());
199 public void testGetBlobValue() {
200 Row row = Mockito.mock(Row.class);
201 Mockito.when(row.getBytes("col")).thenReturn(ByteBuffer.allocate(16));
203 byte[] byteArray = dataStore.getBlobValue(row, "col", DataType.blob());
204 assertEquals(16, byteArray.length);
208 public void testDoesRowSatisfyCondition() throws Exception {
209 Row row = Mockito.mock(Row.class);
210 ColumnDefinitions cd = Mockito.mock(ColumnDefinitions.class);
211 Mockito.when(row.getColumnDefinitions()).thenReturn(cd);
212 Mockito.when(cd.getType("col1")).thenReturn(DataType.varchar());
214 Map<String, Object> condition = new HashMap<>();
215 condition.put("col1", "val1");
217 Mockito.when(row.getString("col1")).thenReturn("val1");
219 assertTrue(dataStore.doesRowSatisfyCondition(row, condition));
221 condition.put("col1", "val2");
222 assertFalse(dataStore.doesRowSatisfyCondition(row, condition));
226 public void testMarshalData() {
227 ResultSet results = Mockito.mock(ResultSet.class);
228 Row row = Mockito.mock(Row.class);
229 Mockito.when(row.getString("colName")).thenReturn("rowValue");
230 //mock for (Row row: results)
231 Iterator mockIterator = Mockito.mock(Iterator.class);
232 //Mockito.doCallRealMethod().when(results).forEach(Mockito.any(Consumer.class));
233 Mockito.when(results.iterator()).thenReturn(mockIterator);
234 Mockito.when(mockIterator.hasNext()).thenReturn(true, false);
235 Mockito.when(mockIterator.next()).thenReturn(row);
237 ColumnDefinitions cd = Mockito.mock(ColumnDefinitions.class);
238 Mockito.when(row.getColumnDefinitions()).thenReturn(cd);
239 //for (Definition: colDefinitions)
240 Iterator mockIterator2 = Mockito.mock(Iterator.class);
241 //Mockito.doCallRealMethod().when(cd).forEach(Mockito.any(Consumer.class));
242 Mockito.when(cd.iterator()).thenReturn(mockIterator2);
243 Mockito.when(mockIterator2.hasNext()).thenReturn(true, false);
244 Definition def = Mockito.mock(Definition.class);
245 Mockito.when(mockIterator2.next()).thenReturn(def);
246 Mockito.when(def.getType()).thenReturn(DataType.varchar());
247 Mockito.when(def.getName()).thenReturn("colName");
249 Map<String, HashMap<String, Object>> data = dataStore.marshalData(results);
250 System.out.println("Marshalled data: " + data);
252 assertTrue(data.containsKey("row 0"));
253 assertEquals("rowValue", data.get("row 0").get("colName"));
256 private ArgumentCaptor<SimpleStatement> sessionExecuteResponse() {
257 ResultSet rs = Mockito.mock(ResultSet.class);
258 Mockito.when(session.execute(Mockito.any(Statement.class))).thenReturn(rs);
260 ArgumentCaptor<SimpleStatement> argument = ArgumentCaptor.forClass(SimpleStatement.class);
265 public void testExecutePutPreparedQueryObjectString() throws Exception {
266 ArgumentCaptor<SimpleStatement> argument = sessionExecuteResponse();
267 String queryString = "INSERT INTO cycling.cyclist_name (lastname, firstname) VALUES (?,?);";
268 String lastName = "KRUIKSWIJK";
269 String firstName = "Steven";
271 PreparedQueryObject query = new PreparedQueryObject(queryString, lastName, firstName);
272 dataStore.executePut(query, MusicUtil.CRITICAL);
274 Mockito.verify(session).execute(argument.capture());
275 assertEquals(ConsistencyLevel.QUORUM, argument.getValue().getConsistencyLevel());
276 assertEquals(queryString, argument.getValue().getQueryString());
277 assertEquals(2, argument.getValue().valuesCount());
281 public void testExecutePut_ONE() throws Exception {
282 ArgumentCaptor<SimpleStatement> argument = sessionExecuteResponse();
283 String queryString = "INSERT INTO cycling.cyclist_name (lastname, firstname) VALUES (?,?);";
284 String lastName = "KRUIKSWIJK";
285 String firstName = "Steven";
287 PreparedQueryObject query = new PreparedQueryObject(queryString, lastName, firstName);
288 dataStore.executePut(query, MusicUtil.ONE);
290 Mockito.verify(session).execute(argument.capture());
291 assertEquals(ConsistencyLevel.ONE, argument.getValue().getConsistencyLevel());
292 assertEquals(queryString, argument.getValue().getQueryString());
293 assertEquals(2, argument.getValue().valuesCount());
297 public void testExecutePut_quorum() throws Exception {
298 ArgumentCaptor<SimpleStatement> argument = sessionExecuteResponse();
299 String queryString = "INSERT INTO cycling.cyclist_name (lastname, firstname) VALUES (?,?);";
300 String lastName = "KRUIKSWIJK";
301 String firstName = "Steven";
303 PreparedQueryObject query = new PreparedQueryObject(queryString, lastName, firstName);
304 dataStore.executePut(query, MusicUtil.QUORUM);
306 Mockito.verify(session).execute(argument.capture());
308 assertEquals(ConsistencyLevel.LOCAL_QUORUM, argument.getValue().getConsistencyLevel());
309 assertEquals(queryString, argument.getValue().getQueryString());
310 assertEquals(2, argument.getValue().valuesCount());
314 public void testExecutePut_ALL() throws Exception {
315 ArgumentCaptor<SimpleStatement> argument = sessionExecuteResponse();
316 String queryString = "INSERT INTO cycling.cyclist_name (lastname, firstname) VALUES (?,?);";
317 String lastName = "KRUIKSWIJK";
318 String firstName = "Steven";
320 PreparedQueryObject query = new PreparedQueryObject(queryString, lastName, firstName);
321 dataStore.executePut(query, MusicUtil.ALL);
323 Mockito.verify(session).execute(argument.capture());
324 assertEquals(ConsistencyLevel.ALL, argument.getValue().getConsistencyLevel());
325 assertEquals(queryString, argument.getValue().getQueryString());
326 assertEquals(2, argument.getValue().valuesCount());
329 @Test(expected = MusicQueryException.class)
330 public void testExecutePut_BadQueryObj() throws Exception {
331 String queryString = "INSERT INTO cycling.cyclist_name (lastname, firstname) VALUES (?,?);";
332 String lastName = "KRUIKSWIJK";
333 String firstName = "Steven";
335 //Provide extra value here, middle initial
336 PreparedQueryObject query = new PreparedQueryObject(queryString, lastName, firstName, "P");
338 dataStore.executePut(query, MusicUtil.CRITICAL);
339 } catch (Exception e) {
340 System.out.println(e.getMessage());
344 fail("Should have throw error");
348 public void testExecutePutPreparedQueryObjectStringLong() throws Exception {
349 ArgumentCaptor<SimpleStatement> argument = sessionExecuteResponse();
350 String queryString = "INSERT INTO cycling.cyclist_name (lastname, firstname) VALUES ('KRUIKSWIJK','Steven');";
353 PreparedQueryObject query = new PreparedQueryObject(queryString);
354 dataStore.executePut(query, MusicUtil.EVENTUAL, 10);
356 Mockito.verify(session).execute(argument.capture());
357 assertEquals(ConsistencyLevel.ONE, argument.getValue().getConsistencyLevel());
358 assertEquals(queryString, argument.getValue().getQueryString());
362 public void testExecuteGet() throws Exception {
363 ArgumentCaptor<SimpleStatement> argument = sessionExecuteResponse();
365 PreparedQueryObject query = new PreparedQueryObject("SELECT * FROM KEYSPACE.TABLE");
367 dataStore.executeGet(query, MusicUtil.ONE);
369 Mockito.verify(session).execute(argument.capture());
370 assertEquals(ConsistencyLevel.ONE, argument.getValue().getConsistencyLevel());
371 assertEquals("SELECT * FROM KEYSPACE.TABLE", argument.getValue().getQueryString());
374 @Test (expected = MusicQueryException.class)
375 public void testExecuteGet_badQuery() throws Exception {
376 ArgumentCaptor<SimpleStatement> argument = sessionExecuteResponse();
378 PreparedQueryObject query = new PreparedQueryObject("SELECT * FROM KEYSPACE.TABLE", "broken");
380 dataStore.executeGet(query, MusicUtil.ONE);
382 Mockito.verify(session).execute(argument.capture());
383 assertEquals(ConsistencyLevel.ONE, argument.getValue().getConsistencyLevel());
384 assertEquals("SELECT * FROM KEYSPACE.TABLE", argument.getValue().getQueryString());
388 public void testExecuteOneConsistencyGet() throws Exception {
389 ArgumentCaptor<SimpleStatement> argument = sessionExecuteResponse();
390 PreparedQueryObject query = new PreparedQueryObject("SELECT * FROM KEYSPACE.TABLE");
392 dataStore.executeOneConsistencyGet(query);
395 Mockito.verify(session).execute(argument.capture());
396 assertEquals(ConsistencyLevel.ONE, argument.getValue().getConsistencyLevel());
397 assertEquals("SELECT * FROM KEYSPACE.TABLE", argument.getValue().getQueryString());
401 public void testExecuteLocalQuorumConsistencyGet() throws Exception {
402 ArgumentCaptor<SimpleStatement> argument = sessionExecuteResponse();
403 PreparedQueryObject query = new PreparedQueryObject("SELECT * FROM KEYSPACE.TABLE");
405 dataStore.executeLocalQuorumConsistencyGet(query);
407 Mockito.verify(session).execute(argument.capture());
408 assertEquals(ConsistencyLevel.LOCAL_QUORUM, argument.getValue().getConsistencyLevel());
409 assertEquals("SELECT * FROM KEYSPACE.TABLE", argument.getValue().getQueryString());
413 public void testExecuteQuorumConsistencyGet() throws Exception {
414 ArgumentCaptor<SimpleStatement> argument = sessionExecuteResponse();
415 PreparedQueryObject query = new PreparedQueryObject("SELECT * FROM KEYSPACE.TABLE");
417 dataStore.executeQuorumConsistencyGet(query);
419 Mockito.verify(session).execute(argument.capture());
420 assertEquals(ConsistencyLevel.QUORUM, argument.getValue().getConsistencyLevel());
421 assertEquals("SELECT * FROM KEYSPACE.TABLE", argument.getValue().getQueryString());
426 public void testExecutePut() {
427 Mockito.when(session.execute(Mockito.any(SimpleStatement.class)))
428 .thenThrow(new WriteTimeoutException(ConsistencyLevel.QUORUM, WriteType.CAS, 1, 3));
431 dataStore.executePut(new PreparedQueryObject("Test query"), "critical");
432 } catch (MusicServiceException e) {
434 } catch (MusicQueryException e) {
435 // should never reach here