Conditional test cases
[music.git] / src / test / java / org / onap / music / unittests / TstRestMusicConditionalAPI.java
1 /*
2  * ============LICENSE_START========================================== org.onap.music
3  * =================================================================== Copyright (c) 2017 AT&T
4  * Intellectual Property ===================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
6  * in compliance with the License. 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 distributed under the License
11  * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
12  * or implied. See the License for the specific language governing permissions and limitations under
13  * the License.
14  * 
15  * ============LICENSE_END=============================================
16  * ====================================================================
17  */
18
19 package org.onap.music.unittests;
20
21 import static org.junit.Assert.assertEquals;
22 import java.math.BigInteger;
23 import java.util.ArrayList;
24 import java.util.HashMap;
25 import java.util.List;
26 import java.util.Map;
27 import java.util.UUID;
28 import javax.servlet.http.HttpServletResponse;
29 import javax.ws.rs.core.MultivaluedHashMap;
30 import javax.ws.rs.core.MultivaluedMap;
31 import javax.ws.rs.core.Response;
32 import javax.ws.rs.core.UriInfo;
33 import org.junit.After;
34 import org.junit.AfterClass;
35 import org.junit.BeforeClass;
36 import org.junit.Ignore;
37 import org.junit.Test;
38 import org.junit.runner.RunWith;
39 import org.mindrot.jbcrypt.BCrypt;
40 import org.mockito.Mock;
41 import org.mockito.Mockito;
42 import org.mockito.junit.MockitoJUnitRunner;
43 import org.onap.music.conductor.conditionals.JsonConditional;
44 import org.onap.music.conductor.conditionals.RestMusicConditionalAPI;
45 import org.onap.music.datastore.MusicDataStoreHandle;
46 import org.onap.music.datastore.PreparedQueryObject;
47 import org.onap.music.datastore.jsonobjects.JsonDelete;
48 import org.onap.music.datastore.jsonobjects.JsonInsert;
49 import org.onap.music.datastore.jsonobjects.JsonKeySpace;
50 import org.onap.music.datastore.jsonobjects.JsonSelect;
51 import org.onap.music.datastore.jsonobjects.JsonTable;
52 import org.onap.music.datastore.jsonobjects.JsonUpdate;
53 import org.onap.music.exceptions.MusicServiceException;
54 import org.onap.music.main.CachingUtil;
55 import org.onap.music.main.MusicCore;
56 import org.onap.music.main.MusicUtil;
57 import org.onap.music.main.ResultType;
58 import org.onap.music.rest.RestMusicDataAPI;
59 import com.datastax.driver.core.DataType;
60 import com.datastax.driver.core.ResultSet;
61 import com.datastax.driver.core.Row;
62 import com.sun.jersey.core.util.Base64;
63 import com.sun.jersey.core.util.MultivaluedMapImpl;
64
65 @RunWith(MockitoJUnitRunner.class)
66 public class TstRestMusicConditionalAPI {
67
68     RestMusicDataAPI data = new RestMusicDataAPI();
69         RestMusicConditionalAPI cond = new RestMusicConditionalAPI();
70         static PreparedQueryObject testObject;
71
72         @Mock
73         HttpServletResponse http;
74
75         @Mock
76         UriInfo info;
77
78         static String appName = "TestApp";
79         static String userId = "TestUser";
80         static String password = "TestPassword";
81         static String authData = userId+":"+password;
82         static String wrongAuthData = userId+":"+"pass";
83         static String authorization = new String(Base64.encode(authData.getBytes()));
84         static String wrongAuthorization = new String(Base64.encode(wrongAuthData.getBytes()));
85         static boolean isAAF = false;
86         static UUID uuid = UUID.fromString("abc66ccc-d857-4e90-b1e5-df98a3d40ce6");
87         static String keyspaceName = "testcassa";
88         static String tableName = "employees";
89         static String xLatestVersion = "X-latestVersion";
90         static String onboardUUID = null;
91
92         @BeforeClass
93         public static void init() throws Exception {
94                 System.out.println("Testing RestMusicConditional class");
95                 try {
96                         createKeyspace();
97                 } catch (Exception e) {
98                         e.printStackTrace();
99                         throw new Exception("Unable to initialize before TestRestMusicData test class. " + e.getMessage());
100                 }
101         }
102         
103         @After
104         public void afterEachTest( ) throws MusicServiceException {
105                 clearAllTablesFromKeyspace();
106         }
107
108         @AfterClass
109         public static void tearDownAfterClass() throws Exception {
110                 testObject = new PreparedQueryObject();
111                 testObject.appendQueryString("DROP KEYSPACE IF EXISTS " + keyspaceName);
112                 MusicCore.eventualPut(testObject);
113         }
114         
115         @Test
116         public void test_insertIntoTable() throws Exception {
117                 System.out.println("Testing conditional insert into table");
118                 createTable();
119                 
120                 JsonConditional jsonCond = new JsonConditional();
121         Map<String, String> consistencyInfo = new HashMap<>();
122         Map<String, Object> values = new HashMap<>();
123         values.put("id", "test_id");
124         consistencyInfo.put("type", "eventual");
125         HashMap<String, Object> cascadeData = new HashMap<>();
126         HashMap<String, String> cascadeValue = new HashMap<>();
127         cascadeValue.put("created", "hello");
128         cascadeValue.put("updated", "world");
129         cascadeData.put("key", "p1");
130         cascadeData.put("value", cascadeValue);
131         HashMap<String, Map<String, String>> condition = new HashMap<>();
132         HashMap<String, String> exists = new HashMap<>();
133         exists.put("status", "parked");
134         HashMap<String, String> nonexists = new HashMap<>();
135         nonexists.put("status", "underway");
136         condition.put("exists", exists);
137         condition.put("nonexists", nonexists);
138         
139         jsonCond.setPrimaryKey("id");
140         jsonCond.setPrimaryKeyValue("testname");
141         jsonCond.setCasscadeColumnName("plans");
142         jsonCond.setTableValues(values);
143         jsonCond.setCasscadeColumnData(cascadeData);
144         jsonCond.setConditions(condition);
145
146                 Response response = cond.insertConditional("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6",
147                         appName, authorization, keyspaceName, tableName, jsonCond);
148
149                 System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity());
150
151                 assertEquals(200, response.getStatus());
152         }
153 /*
154         @Test
155         public void test4_insertIntoTable2() throws Exception {
156                 System.out.println("Testing insert into table #2");
157                 createTable();
158                 JsonInsert jsonInsert = new JsonInsert();
159                 Map<String, String> consistencyInfo = new HashMap<>();
160                 Map<String, Object> values = new HashMap<>();
161                 values.put("uuid", "cfd66ccc-d857-4e90-b1e5-df98a3d40cd6");
162                 values.put("emp_name", "test1");
163                 values.put("emp_salary", 1500);
164                 consistencyInfo.put("type", "eventual");
165                 jsonInsert.setConsistencyInfo(consistencyInfo);
166                 jsonInsert.setKeyspaceName(keyspaceName);
167                 jsonInsert.setTableName(tableName);
168                 jsonInsert.setValues(values);
169                 Response response = data.insertIntoTable("1", "1", "1",
170                                 "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization,
171                                 jsonInsert, keyspaceName, tableName);
172                 System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity());
173                 
174                 assertEquals(200, response.getStatus());
175         }
176
177         // Auth Error
178         @Test
179         public void test4_insertIntoTable3() throws Exception {
180                 System.out.println("Testing insert into table with bad credentials");
181                 createTable();
182                 JsonInsert jsonInsert = new JsonInsert();
183                 Map<String, String> consistencyInfo = new HashMap<>();
184                 Map<String, Object> values = new HashMap<>();
185                 values.put("uuid", "cfd66ccc-d857-4e90-b1e5-df98a3d40cd6");
186                 values.put("emp_name", "test1");
187                 values.put("emp_salary", 1500);
188                 consistencyInfo.put("type", "eventual");
189                 jsonInsert.setConsistencyInfo(consistencyInfo);
190                 jsonInsert.setKeyspaceName(keyspaceName);
191                 jsonInsert.setTableName(tableName);
192                 jsonInsert.setValues(values);
193                 Response response = data.insertIntoTable("1", "1", "1",
194                                 "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, wrongAuthorization,
195                                 jsonInsert, keyspaceName, tableName);
196                 System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity());
197
198                 assertEquals(401, response.getStatus());
199         }
200
201         // Table wrong
202         @Test
203         public void test4_insertIntoTable4() throws Exception {
204                 System.out.println("Testing insert into wrong table");
205                 createTable();
206                 JsonInsert jsonInsert = new JsonInsert();
207                 Map<String, String> consistencyInfo = new HashMap<>();
208                 Map<String, Object> values = new HashMap<>();
209                 values.put("uuid", "cfd66ccc-d857-4e90-b1e5-df98a3d40cd6");
210                 values.put("emp_name", "test1");
211                 values.put("emp_salary", 1500);
212                 consistencyInfo.put("type", "eventual");
213                 jsonInsert.setConsistencyInfo(consistencyInfo);
214                 jsonInsert.setKeyspaceName(keyspaceName);
215                 jsonInsert.setTableName(tableName);
216                 jsonInsert.setValues(values);
217                 Response response = data.insertIntoTable("1", "1", "1",
218                                 "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization,
219                                 jsonInsert, keyspaceName, "wrong");
220                 System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity());
221
222                 assertEquals(400, response.getStatus());
223         }
224 */
225
226         @Test
227         public void test5_updateTable() throws Exception {
228                 System.out.println("Testing conditional update table");
229                 createAndInsertIntoTable();
230                 
231         Map<String, String> consistencyInfo = new HashMap<>();
232         consistencyInfo.put("type", "eventual");
233         
234         JsonConditional jsonCond = new JsonConditional();
235         Map<String, Object> values = new HashMap<>();
236         values.put("id", "test_id");
237         HashMap<String, Object> cascadeData = new HashMap<>();
238         HashMap<String, String> cascadeValue = new HashMap<>();
239         cascadeValue.put("created", "hello");
240         cascadeValue.put("updated", "world");
241         cascadeData.put("key", "p1");
242         cascadeData.put("value", cascadeValue);
243         
244         jsonCond.setPrimaryKey("id");
245         jsonCond.setPrimaryKeyValue("test_id");
246         jsonCond.setCasscadeColumnName("plans");
247         jsonCond.setTableValues(values);
248         jsonCond.setCasscadeColumnData(cascadeData);
249                 
250                 Response response = cond.updateConditional("1", "1", "1",
251                         "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization,
252                         keyspaceName, tableName, jsonCond);
253                 System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity());
254                 
255                 assertEquals(200, response.getStatus());
256         } 
257 /*
258         // need mock code to create error for MusicCore methods
259         @Test
260         public void test5_updateTableAuthE() throws Exception {
261                 System.out.println("Testing update table #2");
262                 createTable();
263                 //MockitoAnnotations.initMocks(this);
264                 JsonUpdate jsonUpdate = new JsonUpdate();
265                 Map<String, String> consistencyInfo = new HashMap<>();
266                 MultivaluedMap<String, String> row = new MultivaluedMapImpl();
267                 Map<String, Object> values = new HashMap<>();
268                 row.add("emp_name", "testname");
269                 values.put("emp_salary", 2500);
270                 consistencyInfo.put("type", "atomic");
271                 jsonUpdate.setConsistencyInfo(consistencyInfo);
272                 jsonUpdate.setKeyspaceName(keyspaceName);
273                 jsonUpdate.setTableName(tableName);
274                 jsonUpdate.setValues(values);
275                 //add ttl & timestamp
276                 //Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
277                 Mockito.when(info.getQueryParameters()).thenReturn(row);
278                 //Map<String, Object> m1= new HashMap<>() ;
279                 //Mockito.when(MusicCore.autheticateUser(appName,userId,password,keyspaceName,"abc66ccc-d857-4e90-b1e5-df98a3d40ce6","updateTable")).thenReturn(m1);
280                 Response response = data.updateTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName,
281                                 authorization, jsonUpdate, keyspaceName, tableName, info);
282                 System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity());
283
284                 assertEquals(200, response.getStatus());
285         } 
286
287         @Ignore
288         @Test
289         public void test5_updateTableAuthException1() throws Exception {
290                 System.out.println("Testing update table authentication error");
291                 createTable();
292                 JsonUpdate jsonUpdate = new JsonUpdate();
293                 Map<String, String> consistencyInfo = new HashMap<>();
294                 MultivaluedMap<String, String> row = new MultivaluedMapImpl();
295                 Map<String, Object> values = new HashMap<>();
296                 row.add("emp_name", "testname");
297                 values.put("emp_salary", 2500);
298                 consistencyInfo.put("type", "atomic");
299                 jsonUpdate.setConsistencyInfo(consistencyInfo);
300                 jsonUpdate.setKeyspaceName(keyspaceName);
301                 jsonUpdate.setTableName(tableName);
302                 jsonUpdate.setValues(values);
303                 
304                 Mockito.when(info.getQueryParameters()).thenReturn(row);
305                 String authDatax = ":";
306                 String authorizationx = new String(Base64.encode(authDatax.getBytes()));
307                 Response response = data.updateTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName,
308                                 authorizationx, jsonUpdate, keyspaceName, tableName, info);
309                 System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity());
310
311                 assertEquals(401, response.getStatus());
312         }
313
314         @Ignore
315         @Test
316         public void test5_updateTableAuthEmpty() throws Exception {
317                 System.out.println("Testing update table without authentication");
318                 createTable();
319                 
320                 JsonUpdate jsonUpdate = new JsonUpdate();
321                 Map<String, String> consistencyInfo = new HashMap<>();
322                 MultivaluedMap<String, String> row = new MultivaluedMapImpl();
323                 Map<String, Object> values = new HashMap<>();
324                 row.add("emp_name", "testname");
325                 values.put("emp_salary", 2500);
326                 consistencyInfo.put("type", "atomic");
327                 jsonUpdate.setConsistencyInfo(consistencyInfo);
328                 jsonUpdate.setKeyspaceName(keyspaceName);
329                 jsonUpdate.setTableName(tableName);
330                 jsonUpdate.setValues(values);
331
332                 Mockito.when(info.getQueryParameters()).thenReturn(row);
333                 String authDatax =":"+password;
334                 String authorizationx = new String(Base64.encode(authDatax.getBytes()));
335                 String appNamex="xx";
336                 Response response = data.updateTable("1", "1", "1", "", appNamex,
337                                 authorizationx, jsonUpdate, keyspaceName, tableName, info);
338                 System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity());
339
340                 assertEquals(401, response.getStatus());
341         }
342
343 */
344         
345         private static void createAdminTable() throws Exception {
346                 testObject = new PreparedQueryObject();
347                 testObject.appendQueryString(CassandraCQL.createAdminKeyspace);
348                 MusicCore.eventualPut(testObject);
349                 testObject = new PreparedQueryObject();
350                 testObject.appendQueryString(CassandraCQL.createAdminTable);
351                 MusicCore.eventualPut(testObject);
352
353                 testObject = new PreparedQueryObject();
354                 testObject.appendQueryString(
355                                 "INSERT INTO admin.keyspace_master (uuid, keyspace_name, application_name, is_api, "
356                                                 + "password, username, is_aaf) VALUES (?,?,?,?,?,?,?)");
357                 testObject.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), uuid));
358                 testObject.addValue(MusicUtil.convertToActualDataType(DataType.text(),
359                                 MusicUtil.DEFAULTKEYSPACENAME));
360                 testObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName));
361                 testObject.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), "True"));
362                 testObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), BCrypt.hashpw(password, BCrypt.gensalt())));
363                 testObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), userId));
364                 testObject.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), isAAF));
365                 MusicCore.eventualPut(testObject);
366
367                 testObject = new PreparedQueryObject();
368                 testObject.appendQueryString(
369                                 "select uuid from admin.keyspace_master where application_name = ? allow filtering");
370                 testObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName));
371                 ResultSet rs = MusicCore.get(testObject);
372                 List<Row> rows = rs.all();
373                 if (rows.size() > 0) {
374                         System.out.println("#######UUID is:" + rows.get(0).getUUID("uuid"));
375                 }
376         }
377         
378
379         private static void createKeyspace() throws Exception {
380                 //shouldn't really be doing this here, but create keyspace is currently turned off
381                 PreparedQueryObject query = new PreparedQueryObject();
382                 query.appendQueryString(CassandraCQL.createKeySpace);
383                 MusicCore.eventualPut(query);
384                 
385                 boolean isAAF = false;
386         String hashedpwd = BCrypt.hashpw(password, BCrypt.gensalt());
387         query = new PreparedQueryObject();
388         query.appendQueryString(
389                     "INSERT into admin.keyspace_master (uuid, keyspace_name, application_name, is_api, "
390                                     + "password, username, is_aaf) values (?,?,?,?,?,?,?)");
391         query.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), uuid));
392         query.addValue(MusicUtil.convertToActualDataType(DataType.text(), keyspaceName));
393         query.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName));
394         query.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), "True"));
395         query.addValue(MusicUtil.convertToActualDataType(DataType.text(), hashedpwd));
396         query.addValue(MusicUtil.convertToActualDataType(DataType.text(), userId));
397         query.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), isAAF));
398         CachingUtil.updateMusicCache(keyspaceName, appName);
399         CachingUtil.updateMusicValidateCache(appName, userId, hashedpwd);
400         MusicCore.eventualPut(query);
401         }
402         
403         private void clearAllTablesFromKeyspace() throws MusicServiceException {
404                 ArrayList<String> tableNames = new ArrayList<>();
405                 PreparedQueryObject query = new PreparedQueryObject();
406                 query.appendQueryString("SELECT table_name FROM system_schema.tables WHERE keyspace_name = '"+keyspaceName+"';");
407                 ResultSet rs = MusicCore.get(query);
408                 for (Row row: rs) {
409                         tableNames.add(row.getString("table_name"));
410                 }
411                 for (String table: tableNames) {
412                         query = new PreparedQueryObject();
413                         query.appendQueryString("DROP TABLE " + keyspaceName + "." + table);
414                         MusicCore.eventualPut(query);
415                 }
416         }
417         
418         /**
419          * Create a table {@link tableName} in {@link keyspaceName}
420          * @throws Exception
421          */
422         private void createTable() throws Exception {
423                 JsonTable jsonTable = new JsonTable();
424                 Map<String, String> consistencyInfo = new HashMap<>();
425                 Map<String, String> fields = new HashMap<>();
426                 fields.put("id", "text");
427                 fields.put("plans", "map<text,text>");
428                 fields.put("PRIMARY KEY", "(id)");
429                 consistencyInfo.put("type", "eventual");
430                 jsonTable.setConsistencyInfo(consistencyInfo);
431                 jsonTable.setKeyspaceName(keyspaceName);
432                 jsonTable.setPrimaryKey("id");
433                 jsonTable.setTableName(tableName);
434                 jsonTable.setFields(fields);
435                 Response response = data.createTable("1", "1", "1",
436                                 "abc66ccc-d857-4e90-b1e5-df98a3d40ce6",appName, authorization, 
437                                 jsonTable, keyspaceName, tableName);
438         }
439         
440         /**
441          * Create table {@link createTable} and insert into said table
442          * @throws Exception
443          */
444         private void createAndInsertIntoTable() throws Exception {
445                 createTable();
446                 
447         Map<String, String> consistencyInfo = new HashMap<>();
448         consistencyInfo.put("type", "eventual");
449         JsonConditional jsonCond = new JsonConditional();
450         Map<String, Object> values = new HashMap<>();
451         values.put("id", "test_id");
452         HashMap<String, Object> cascadeData = new HashMap<>();
453         HashMap<String, String> cascadeValue = new HashMap<>();
454         cascadeValue.put("created", "hello");
455         cascadeValue.put("updated", "world");
456         cascadeData.put("key", "p1");
457         cascadeData.put("value", cascadeValue);
458         HashMap<String, Map<String, String>> condition = new HashMap<>();
459         HashMap<String, String> exists = new HashMap<>();
460         exists.put("status", "parked");
461         HashMap<String, String> nonexists = new HashMap<>();
462         nonexists.put("status", "underway");
463         condition.put("exists", exists);
464         condition.put("nonexists", nonexists);
465         
466         jsonCond.setPrimaryKey("id");
467         jsonCond.setPrimaryKeyValue("test_id");
468         jsonCond.setCasscadeColumnName("plans");
469         jsonCond.setTableValues(values);
470         jsonCond.setCasscadeColumnData(cascadeData);
471         jsonCond.setConditions(condition);
472
473         Response response = cond.insertConditional("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6",
474                 appName, authorization, keyspaceName, tableName, jsonCond);
475         }
476 }