4de995f7144028d23b807f8785a82876dcda57ae
[music.git] / music-core / src / test / java / org / onap / music / datastore / MusicDataStoreTest.java
1 /*******************************************************************************
2  * ============LICENSE_START==========================================
3  * org.onap.music
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
10  *
11  *     http://www.apache.org/licenses/LICENSE-2.0
12  *
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.
18  *  
19  * ============LICENSE_END=============================================
20  * ====================================================================
21  *******************************************************************************/
22 package org.onap.music.datastore;
23
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;
31 import java.util.Map;
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;
62
63 @RunWith(MockitoJUnitRunner.class)
64 public class MusicDataStoreTest {
65     
66     MusicDataStore dataStore;
67     
68     @Mock
69     Session session;
70     
71     @Mock
72     Cluster cluster;
73     
74     @Before
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);
81     }
82
83     @Test
84     public void testMusicDataStore() {
85         //MusicDataStore mds = new MusicDataStore();
86     }
87     
88     @Test
89     public void testMusicDataStoreClusterSession() {
90         Session session = Mockito.mock(Session.class);
91         Cluster cluster = Mockito.mock(Cluster.class);
92         
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);
97         
98         
99         MusicDataStore mds = new MusicDataStore(cluster, session);
100         assertEquals(session, mds.getSession());
101         assertEquals(cluster, mds.getCluster());
102     }
103
104     @Test
105     public void testSession() {
106         Session session = Mockito.mock(Session.class);
107         dataStore.setSession(session);
108         assertEquals(session, dataStore.getSession());
109     }
110
111     @Test
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);
118         
119         dataStore.setCluster(cluster);
120         assertEquals(cluster, dataStore.getCluster());
121     }
122
123     @Test
124     public void testClose() {
125         dataStore.close();
126         Mockito.verify(session).close();
127     }
128
129     @Test
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());
140             
141         com.datastax.driver.core.DataType dt = dataStore.returnColumnDataType("keyspace", "table", "columnName");
142         assertEquals(com.datastax.driver.core.DataType.text(), dt);
143     }
144
145     @Test
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);
153         
154         dataStore.returnColumnMetadata("keyspace", "tableName");
155         assertEquals(tmd, dataStore.returnColumnMetadata("keyspace", "tableName"));
156     }
157
158     @Test
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);
164         
165         assertEquals(ksmd, dataStore.returnKeyspaceMetadata("keyspace"));
166     }
167
168     @Test
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>());
182         
183         
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());
194         assertEquals(0,
195                 ((List<String>) dataStore.getColValue(row, "columnName", DataType.list(DataType.varchar()))).size());
196     }
197
198     @Test
199     public void testGetBlobValue() {
200         Row row = Mockito.mock(Row.class);
201         Mockito.when(row.getBytes("col")).thenReturn(ByteBuffer.allocate(16));
202         
203         byte[] byteArray = dataStore.getBlobValue(row, "col", DataType.blob());
204         assertEquals(16, byteArray.length);
205     }
206
207     @Test
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());
213
214         Map<String, Object> condition = new HashMap<>();
215         condition.put("col1",  "val1");
216         
217         Mockito.when(row.getString("col1")).thenReturn("val1");
218         
219         assertTrue(dataStore.doesRowSatisfyCondition(row, condition));
220         
221         condition.put("col1",  "val2");
222         assertFalse(dataStore.doesRowSatisfyCondition(row, condition));
223     }
224
225     @Test
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);
236         
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");
248         
249         Map<String, HashMap<String, Object>> data = dataStore.marshalData(results); 
250         System.out.println("Marshalled data: " + data);
251         
252         assertTrue(data.containsKey("row 0"));
253         assertEquals("rowValue", data.get("row 0").get("colName"));
254     }
255
256     private ArgumentCaptor<SimpleStatement> sessionExecuteResponse() {
257         ResultSet rs = Mockito.mock(ResultSet.class);
258         Mockito.when(session.execute(Mockito.any(Statement.class))).thenReturn(rs);
259         
260         ArgumentCaptor<SimpleStatement> argument = ArgumentCaptor.forClass(SimpleStatement.class);
261         return argument;
262     }
263
264     @Test
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";
270         
271         PreparedQueryObject query = new PreparedQueryObject(queryString, lastName, firstName);
272         dataStore.executePut(query, MusicUtil.CRITICAL);
273
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());
278     }
279     
280     @Test
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";
286         
287         PreparedQueryObject query = new PreparedQueryObject(queryString, lastName, firstName);
288         dataStore.executePut(query, MusicUtil.ONE);
289
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());
294     }
295     
296     @Test
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";
302         
303         PreparedQueryObject query = new PreparedQueryObject(queryString, lastName, firstName);
304         dataStore.executePut(query, MusicUtil.QUORUM);
305
306         Mockito.verify(session).execute(argument.capture());
307         //should be quorum!
308         assertEquals(ConsistencyLevel.LOCAL_QUORUM, argument.getValue().getConsistencyLevel());
309         assertEquals(queryString, argument.getValue().getQueryString());
310         assertEquals(2, argument.getValue().valuesCount());
311     }
312     
313     @Test
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";
319         
320         PreparedQueryObject query = new PreparedQueryObject(queryString, lastName, firstName);
321         dataStore.executePut(query, MusicUtil.ALL);
322
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());
327     }
328     
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";
334         
335         //Provide extra value here, middle initial
336         PreparedQueryObject query = new PreparedQueryObject(queryString, lastName, firstName, "P");
337         try {
338             dataStore.executePut(query, MusicUtil.CRITICAL);
339         } catch (Exception e) {
340             System.out.println(e.getMessage());
341             throw e;
342         }
343
344         fail("Should have throw error");
345     }
346
347     @Test
348     public void testExecutePutPreparedQueryObjectStringLong() throws Exception {
349         ArgumentCaptor<SimpleStatement> argument = sessionExecuteResponse();
350         String queryString = "INSERT INTO cycling.cyclist_name (lastname, firstname) VALUES ('KRUIKSWIJK','Steven');";
351
352         
353         PreparedQueryObject query = new PreparedQueryObject(queryString);
354         dataStore.executePut(query, MusicUtil.EVENTUAL, 10);
355         
356         Mockito.verify(session).execute(argument.capture());
357         assertEquals(ConsistencyLevel.ONE, argument.getValue().getConsistencyLevel());
358         assertEquals(queryString, argument.getValue().getQueryString());
359     }
360
361     @Test
362     public void testExecuteGet() throws Exception {
363         ArgumentCaptor<SimpleStatement> argument = sessionExecuteResponse();
364
365         PreparedQueryObject query = new PreparedQueryObject("SELECT * FROM KEYSPACE.TABLE");
366         
367         dataStore.executeGet(query, MusicUtil.ONE);
368         
369         Mockito.verify(session).execute(argument.capture());
370         assertEquals(ConsistencyLevel.ONE, argument.getValue().getConsistencyLevel());
371         assertEquals("SELECT * FROM KEYSPACE.TABLE", argument.getValue().getQueryString());
372     }
373     
374     @Test (expected = MusicQueryException.class)
375     public void testExecuteGet_badQuery() throws Exception {
376         ArgumentCaptor<SimpleStatement> argument = sessionExecuteResponse();
377
378         PreparedQueryObject query = new PreparedQueryObject("SELECT * FROM KEYSPACE.TABLE", "broken");
379         
380         dataStore.executeGet(query, MusicUtil.ONE);
381         
382         Mockito.verify(session).execute(argument.capture());
383         assertEquals(ConsistencyLevel.ONE, argument.getValue().getConsistencyLevel());
384         assertEquals("SELECT * FROM KEYSPACE.TABLE", argument.getValue().getQueryString());
385     }
386
387     @Test
388     public void testExecuteOneConsistencyGet() throws Exception {
389         ArgumentCaptor<SimpleStatement> argument = sessionExecuteResponse();
390         PreparedQueryObject query = new PreparedQueryObject("SELECT * FROM KEYSPACE.TABLE");
391         
392         dataStore.executeOneConsistencyGet(query);
393         
394         
395         Mockito.verify(session).execute(argument.capture());
396         assertEquals(ConsistencyLevel.ONE, argument.getValue().getConsistencyLevel());
397         assertEquals("SELECT * FROM KEYSPACE.TABLE", argument.getValue().getQueryString());
398     }
399
400     @Test
401     public void testExecuteLocalQuorumConsistencyGet() throws Exception {
402         ArgumentCaptor<SimpleStatement> argument = sessionExecuteResponse();
403         PreparedQueryObject query = new PreparedQueryObject("SELECT * FROM KEYSPACE.TABLE");
404         
405         dataStore.executeLocalQuorumConsistencyGet(query);
406         
407         Mockito.verify(session).execute(argument.capture());
408         assertEquals(ConsistencyLevel.LOCAL_QUORUM, argument.getValue().getConsistencyLevel());
409         assertEquals("SELECT * FROM KEYSPACE.TABLE", argument.getValue().getQueryString());
410     }
411
412     @Test
413     public void testExecuteQuorumConsistencyGet() throws Exception {
414         ArgumentCaptor<SimpleStatement> argument = sessionExecuteResponse();
415         PreparedQueryObject query = new PreparedQueryObject("SELECT * FROM KEYSPACE.TABLE");
416         
417         dataStore.executeQuorumConsistencyGet(query);
418         
419         Mockito.verify(session).execute(argument.capture());
420         assertEquals(ConsistencyLevel.QUORUM, argument.getValue().getConsistencyLevel());
421         assertEquals("SELECT * FROM KEYSPACE.TABLE", argument.getValue().getQueryString());
422     }
423
424     
425     @Test
426     public void testExecutePut() {
427         Mockito.when(session.execute(Mockito.any(SimpleStatement.class)))
428                 .thenThrow(new WriteTimeoutException(ConsistencyLevel.QUORUM, WriteType.CAS, 1, 3));
429         
430         try {
431             dataStore.executePut(new PreparedQueryObject("Test query"), "critical");
432         } catch (MusicServiceException e) {
433             return;
434         } catch (MusicQueryException e) {
435             // should never reach here
436             fail();
437         }
438         fail();
439     }
440 }