Update MUSIC test cases.
[music.git] / src / test / java / org / onap / music / unittests / TstRestMusicLockAPI.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 static org.junit.Assert.assertTrue;
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
29 import javax.ws.rs.core.Response;
30
31 import org.junit.After;
32 import org.junit.AfterClass;
33 import org.junit.BeforeClass;
34 import org.junit.Ignore;
35 import org.junit.Test;
36 import org.junit.runner.RunWith;
37 import org.mindrot.jbcrypt.BCrypt;
38 import org.mockito.junit.MockitoJUnitRunner;
39 import org.onap.music.datastore.MusicDataStoreHandle;
40 import org.onap.music.datastore.PreparedQueryObject;
41 import org.onap.music.datastore.jsonobjects.JsonInsert;
42 import org.onap.music.datastore.jsonobjects.JsonTable;
43 import org.onap.music.exceptions.MusicServiceException;
44 import org.onap.music.lockingservice.cassandra.CassaLockStore;
45 import org.onap.music.main.CachingUtil;
46 import org.onap.music.main.MusicCore;
47 import org.onap.music.main.MusicUtil;
48 import org.onap.music.rest.RestMusicDataAPI;
49 import org.onap.music.rest.RestMusicLocksAPI;
50 import com.datastax.driver.core.DataType;
51 import com.datastax.driver.core.ResultSet;
52 import com.datastax.driver.core.Row;
53 import com.sun.jersey.core.util.Base64;
54
55 @RunWith(MockitoJUnitRunner.class)
56 public class TstRestMusicLockAPI {
57
58         RestMusicLocksAPI lock = new RestMusicLocksAPI();
59         RestMusicDataAPI data = new RestMusicDataAPI();
60         static PreparedQueryObject testObject;
61
62         static String appName = "TestApp";
63         static String userId = "TestUser";
64         static String password = "TestPassword";
65         static String authData = userId+":"+password;
66         static String wrongAuthData = userId+":"+"pass";
67         static String authorization = new String(Base64.encode(authData.getBytes()));
68         static String wrongAuthorization = new String(Base64.encode(wrongAuthData.getBytes()));
69         static boolean isAAF = false;
70         static UUID uuid = UUID.fromString("abc66ccc-d857-4e90-b1e5-df98a3d40ce6");
71         static String keyspaceName = "testcassa";
72         static String tableName = "employees";
73         static String onboardUUID = null;
74         static String lockName = "testcassa.employees.testname";
75
76         @BeforeClass
77         public static void init() throws Exception {
78                 System.out.println("Testing RestMusicLock class");
79                 try {
80                         createKeyspace();
81                 } catch (Exception e) {
82                         e.printStackTrace();
83                         throw new Exception("Unable to initialize before TestRestMusicData test class. " + e.getMessage());
84                 }
85         }
86         
87         @After
88         public void afterEachTest( ) throws MusicServiceException {
89                 clearAllTablesFromKeyspace();
90         }
91
92         @AfterClass
93         public static void tearDownAfterClass() throws Exception {
94                 testObject = new PreparedQueryObject();
95                 testObject.appendQueryString("DROP KEYSPACE IF EXISTS " + keyspaceName);
96                 MusicCore.eventualPut(testObject);
97         }
98
99     @SuppressWarnings("unchecked")
100         @Test
101     public void test_createLockReference() throws Exception {
102         System.out.println("Testing create lockref");
103         createAndInsertIntoTable();
104         Response response =lock.createLockReference(lockName,"1","1",authorization,
105                         "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName);
106                 Map<String,Object> respMap = (Map<String, Object>) response.getEntity();
107         System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity());
108
109         assertEquals(200, response.getStatus());
110         assertTrue(respMap.containsKey("lock"));
111         assertTrue(((Map<String,String>) respMap.get("lock")).containsKey("lock"));
112     }
113
114     @Test
115     public void test_accquireLock() throws Exception {
116         System.out.println("Testing acquire lock");
117                 createAndInsertIntoTable();
118         String lockRef = createLockReference();
119
120         Response response = lock.accquireLock(lockRef, "1", "1", authorization,
121                         "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName);
122         System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity());
123         assertEquals(200, response.getStatus());
124     }
125     
126     @Test
127     public void test_accquireBadLock() throws Exception {
128         System.out.println("Testing acquire lock");
129                 createAndInsertIntoTable();
130
131         String lockRef1 = createLockReference();
132         String lockRef2 = createLockReference();
133
134
135         Response response = lock.accquireLock(lockRef2, "1", "1", authorization,
136                         "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName);
137         System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity());
138         assertEquals(400, response.getStatus());
139     }
140     
141     @Test
142     public void test_currentLockHolder() throws Exception {
143         System.out.println("Testing acquire lock");
144                 createAndInsertIntoTable();
145
146         String lockRef = createLockReference();
147
148         Response response = lock.currentLockHolder(lockName, "1", "1", authorization,
149                         "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName);
150         System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity());
151         assertEquals(200, response.getStatus());
152         Map<String,Object> respMap = (Map<String, Object>) response.getEntity();
153         assertEquals(lockRef, ((Map<String,String>) respMap.get("lock")).get("lock-holder"));
154     }
155     
156     @Test
157     public void test_unLock() throws Exception {
158         System.out.println("Testing acquire lock");
159                 createAndInsertIntoTable();
160         String lockRef = createLockReference();
161
162         Response response = lock.unLock(lockRef, "1", "1", authorization,
163                         "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName);
164         System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity());
165         assertEquals(200, response.getStatus());
166     }
167         
168         /**
169          * Create table and lock reference
170          * @return the lock ref created
171          * @throws Exception 
172          */
173         @SuppressWarnings("unchecked")
174         private String createLockReference() throws Exception {
175         Response response =lock.createLockReference(lockName,"1","1",authorization,
176                         "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName);
177         Map<String,Object> respMap = (Map<String, Object>) response.getEntity();
178                 return ((Map<String,String>) respMap.get("lock")).get("lock");
179         }
180
181         
182         
183
184         private static void createKeyspace() throws Exception {
185                 //shouldn't really be doing this here, but create keyspace is currently turned off
186                 PreparedQueryObject query = new PreparedQueryObject();
187                 query.appendQueryString(CassandraCQL.createKeySpace);
188                 MusicCore.eventualPut(query);
189                 
190                 boolean isAAF = false;
191         String hashedpwd = BCrypt.hashpw(password, BCrypt.gensalt());
192         query = new PreparedQueryObject();
193         query.appendQueryString(
194                     "INSERT into admin.keyspace_master (uuid, keyspace_name, application_name, is_api, "
195                                     + "password, username, is_aaf) values (?,?,?,?,?,?,?)");
196         query.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), uuid));
197         query.addValue(MusicUtil.convertToActualDataType(DataType.text(), keyspaceName));
198         query.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName));
199         query.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), "True"));
200         query.addValue(MusicUtil.convertToActualDataType(DataType.text(), hashedpwd));
201         query.addValue(MusicUtil.convertToActualDataType(DataType.text(), userId));
202         query.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), isAAF));
203         CachingUtil.updateMusicCache(keyspaceName, appName);
204         CachingUtil.updateMusicValidateCache(appName, userId, hashedpwd);
205         MusicCore.eventualPut(query);
206         }
207         
208         private void clearAllTablesFromKeyspace() throws MusicServiceException {
209                 ArrayList<String> tableNames = new ArrayList<>();
210                 PreparedQueryObject query = new PreparedQueryObject();
211                 query.appendQueryString("SELECT table_name FROM system_schema.tables WHERE keyspace_name = '"+keyspaceName+"';");
212                 ResultSet rs = MusicCore.get(query);
213                 for (Row row: rs) {
214                         tableNames.add(row.getString("table_name"));
215                 }
216                 for (String table: tableNames) {
217                         query = new PreparedQueryObject();
218                         query.appendQueryString("DROP TABLE " + keyspaceName + "." + table);
219                         MusicCore.eventualPut(query);
220                 }
221         }
222         
223         /**
224          * Create a table {@link tableName} in {@link keyspaceName}
225          * @throws Exception
226          */
227         private void createTable() throws Exception {
228                 JsonTable jsonTable = new JsonTable();
229                 Map<String, String> consistencyInfo = new HashMap<>();
230                 Map<String, String> fields = new HashMap<>();
231                 fields.put("uuid", "text");
232                 fields.put("emp_name", "text");
233                 fields.put("emp_salary", "varint");
234                 fields.put("PRIMARY KEY", "(emp_name)");
235                 consistencyInfo.put("type", "eventual");
236                 jsonTable.setConsistencyInfo(consistencyInfo);
237                 jsonTable.setKeyspaceName(keyspaceName);
238                 jsonTable.setPrimaryKey("emp_name");
239                 jsonTable.setTableName(tableName);
240                 jsonTable.setFields(fields);
241                 //Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
242                 Response response = data.createTable("1", "1", "1",
243                                 "abc66ccc-d857-4e90-b1e5-df98a3d40ce6",appName, authorization, 
244                                 jsonTable, keyspaceName, tableName);
245         }
246         
247         /**
248          * Create table {@link createTable} and insert into said table
249          * @throws Exception
250          */
251         private void createAndInsertIntoTable() throws Exception {
252                 createTable();
253                 
254                 JsonInsert jsonInsert = new JsonInsert();
255                 Map<String, String> consistencyInfo = new HashMap<>();
256                 Map<String, Object> values = new HashMap<>();
257                 values.put("uuid", "cfd66ccc-d857-4e90-b1e5-df98a3d40cd6");
258                 values.put("emp_name", "testname");
259                 values.put("emp_salary", 500);
260                 consistencyInfo.put("type", "eventual");
261                 jsonInsert.setConsistencyInfo(consistencyInfo);
262                 jsonInsert.setKeyspaceName(keyspaceName);
263                 jsonInsert.setTableName(tableName);
264                 jsonInsert.setValues(values);
265                 Response response = data.insertIntoTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6",
266                                 appName, authorization, jsonInsert, keyspaceName, tableName);
267         }
268 }