Fixed sonar blocker issue
[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     
84     @Test
85     public void testMusicDataStoreClusterSession() {
86         Session session = Mockito.mock(Session.class);
87         Cluster cluster = Mockito.mock(Cluster.class);
88         
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);
93         
94         
95         MusicDataStore mds = new MusicDataStore(cluster, session);
96         assertEquals(session, mds.getSession());
97         assertEquals(cluster, mds.getCluster());
98     }
99
100     @Test
101     public void testSession() {
102         Session session = Mockito.mock(Session.class);
103         dataStore.setSession(session);
104         assertEquals(session, dataStore.getSession());
105     }
106
107     @Test
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);
114         
115         dataStore.setCluster(cluster);
116         assertEquals(cluster, dataStore.getCluster());
117     }
118
119     @Test
120     public void testClose() {
121         dataStore.close();
122         Mockito.verify(session).close();
123     }
124
125     @Test
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());
136             
137         com.datastax.driver.core.DataType dt = dataStore.returnColumnDataType("keyspace", "table", "columnName");
138         assertEquals(com.datastax.driver.core.DataType.text(), dt);
139     }
140
141     @Test
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);
149         
150         dataStore.returnColumnMetadata("keyspace", "tableName");
151         assertEquals(tmd, dataStore.returnColumnMetadata("keyspace", "tableName"));
152     }
153
154     @Test
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);
160         
161         assertEquals(ksmd, dataStore.returnKeyspaceMetadata("keyspace"));
162     }
163
164     @Test
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>());
178         
179         
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());
190         assertEquals(0,
191                 ((List<String>) dataStore.getColValue(row, "columnName", DataType.list(DataType.varchar()))).size());
192     }
193
194     @Test
195     public void testGetBlobValue() {
196         Row row = Mockito.mock(Row.class);
197         Mockito.when(row.getBytes("col")).thenReturn(ByteBuffer.allocate(16));
198         
199         byte[] byteArray = dataStore.getBlobValue(row, "col", DataType.blob());
200         assertEquals(16, byteArray.length);
201     }
202
203     @Test
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());
209
210         Map<String, Object> condition = new HashMap<>();
211         condition.put("col1",  "val1");
212         
213         Mockito.when(row.getString("col1")).thenReturn("val1");
214         
215         assertTrue(dataStore.doesRowSatisfyCondition(row, condition));
216         
217         condition.put("col1",  "val2");
218         assertFalse(dataStore.doesRowSatisfyCondition(row, condition));
219     }
220
221     @Test
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);
232         
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");
244         
245         Map<String, HashMap<String, Object>> data = dataStore.marshalData(results); 
246         System.out.println("Marshalled data: " + data);
247         
248         assertTrue(data.containsKey("row 0"));
249         assertEquals("rowValue", data.get("row 0").get("colName"));
250     }
251
252     private ArgumentCaptor<SimpleStatement> sessionExecuteResponse() {
253         ResultSet rs = Mockito.mock(ResultSet.class);
254         Mockito.when(session.execute(Mockito.any(Statement.class))).thenReturn(rs);
255         
256         ArgumentCaptor<SimpleStatement> argument = ArgumentCaptor.forClass(SimpleStatement.class);
257         return argument;
258     }
259
260     @Test
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";
266         
267         PreparedQueryObject query = new PreparedQueryObject(queryString, lastName, firstName);
268         dataStore.executePut(query, MusicUtil.CRITICAL);
269
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());
274     }
275     
276     @Test
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";
282         
283         PreparedQueryObject query = new PreparedQueryObject(queryString, lastName, firstName);
284         dataStore.executePut(query, MusicUtil.ONE);
285
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());
290     }
291     
292     @Test
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";
298         
299         PreparedQueryObject query = new PreparedQueryObject(queryString, lastName, firstName);
300         dataStore.executePut(query, MusicUtil.QUORUM);
301
302         Mockito.verify(session).execute(argument.capture());
303         //should be quorum!
304         assertEquals(ConsistencyLevel.LOCAL_QUORUM, argument.getValue().getConsistencyLevel());
305         assertEquals(queryString, argument.getValue().getQueryString());
306         assertEquals(2, argument.getValue().valuesCount());
307     }
308     
309     @Test
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";
315         
316         PreparedQueryObject query = new PreparedQueryObject(queryString, lastName, firstName);
317         dataStore.executePut(query, MusicUtil.ALL);
318
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());
323     }
324     
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";
330         
331         //Provide extra value here, middle initial
332         PreparedQueryObject query = new PreparedQueryObject(queryString, lastName, firstName, "P");
333         try {
334             dataStore.executePut(query, MusicUtil.CRITICAL);
335         } catch (Exception e) {
336             System.out.println(e.getMessage());
337             throw e;
338         }
339
340         fail("Should have throw error");
341     }
342
343     @Test
344     public void testExecutePutPreparedQueryObjectStringLong() throws Exception {
345         ArgumentCaptor<SimpleStatement> argument = sessionExecuteResponse();
346         String queryString = "INSERT INTO cycling.cyclist_name (lastname, firstname) VALUES ('KRUIKSWIJK','Steven');";
347
348         
349         PreparedQueryObject query = new PreparedQueryObject(queryString);
350         dataStore.executePut(query, MusicUtil.EVENTUAL, 10);
351         
352         Mockito.verify(session).execute(argument.capture());
353         assertEquals(ConsistencyLevel.ONE, argument.getValue().getConsistencyLevel());
354         assertEquals(queryString, argument.getValue().getQueryString());
355     }
356
357     @Test
358     public void testExecuteGet() throws Exception {
359         ArgumentCaptor<SimpleStatement> argument = sessionExecuteResponse();
360
361         PreparedQueryObject query = new PreparedQueryObject("SELECT * FROM KEYSPACE.TABLE");
362         
363         dataStore.executeGet(query, MusicUtil.ONE);
364         
365         Mockito.verify(session).execute(argument.capture());
366         assertEquals(ConsistencyLevel.ONE, argument.getValue().getConsistencyLevel());
367         assertEquals("SELECT * FROM KEYSPACE.TABLE", argument.getValue().getQueryString());
368     }
369     
370     @Test (expected = MusicQueryException.class)
371     public void testExecuteGet_badQuery() throws Exception {
372         ArgumentCaptor<SimpleStatement> argument = sessionExecuteResponse();
373
374         PreparedQueryObject query = new PreparedQueryObject("SELECT * FROM KEYSPACE.TABLE", "broken");
375         
376         dataStore.executeGet(query, MusicUtil.ONE);
377         
378         Mockito.verify(session).execute(argument.capture());
379         assertEquals(ConsistencyLevel.ONE, argument.getValue().getConsistencyLevel());
380         assertEquals("SELECT * FROM KEYSPACE.TABLE", argument.getValue().getQueryString());
381     }
382
383     @Test
384     public void testExecuteOneConsistencyGet() throws Exception {
385         ArgumentCaptor<SimpleStatement> argument = sessionExecuteResponse();
386         PreparedQueryObject query = new PreparedQueryObject("SELECT * FROM KEYSPACE.TABLE");
387         
388         dataStore.executeOneConsistencyGet(query);
389         
390         
391         Mockito.verify(session).execute(argument.capture());
392         assertEquals(ConsistencyLevel.ONE, argument.getValue().getConsistencyLevel());
393         assertEquals("SELECT * FROM KEYSPACE.TABLE", argument.getValue().getQueryString());
394     }
395
396     @Test
397     public void testExecuteLocalQuorumConsistencyGet() throws Exception {
398         ArgumentCaptor<SimpleStatement> argument = sessionExecuteResponse();
399         PreparedQueryObject query = new PreparedQueryObject("SELECT * FROM KEYSPACE.TABLE");
400         
401         dataStore.executeLocalQuorumConsistencyGet(query);
402         
403         Mockito.verify(session).execute(argument.capture());
404         assertEquals(ConsistencyLevel.LOCAL_QUORUM, argument.getValue().getConsistencyLevel());
405         assertEquals("SELECT * FROM KEYSPACE.TABLE", argument.getValue().getQueryString());
406     }
407
408     @Test
409     public void testExecuteQuorumConsistencyGet() throws Exception {
410         ArgumentCaptor<SimpleStatement> argument = sessionExecuteResponse();
411         PreparedQueryObject query = new PreparedQueryObject("SELECT * FROM KEYSPACE.TABLE");
412         
413         dataStore.executeQuorumConsistencyGet(query);
414         
415         Mockito.verify(session).execute(argument.capture());
416         assertEquals(ConsistencyLevel.QUORUM, argument.getValue().getConsistencyLevel());
417         assertEquals("SELECT * FROM KEYSPACE.TABLE", argument.getValue().getQueryString());
418     }
419
420     
421     @Test
422     public void testExecutePut() {
423         Mockito.when(session.execute(Mockito.any(SimpleStatement.class)))
424                 .thenThrow(new WriteTimeoutException(ConsistencyLevel.QUORUM, WriteType.CAS, 1, 3));
425         
426         try {
427             dataStore.executePut(new PreparedQueryObject("Test query"), "critical");
428         } catch (MusicServiceException e) {
429             return;
430         } catch (MusicQueryException e) {
431             // should never reach here
432             fail();
433         }
434         fail();
435     }
436 }