Improved tests performance
[policy/engine.git] / ONAP-REST / src / test / java / org / onap / policy / rest / daoimpl / PolicyValidationDaoImplTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP-REST
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * Modifications copyright (c) 2019 Nokia
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21 package org.onap.policy.rest.daoimpl;
22
23 import static org.junit.Assert.*;
24
25 import java.io.File;
26 import java.util.ArrayList;
27 import java.util.Date;
28 import java.util.List;
29 import java.util.Properties;
30
31 import javax.script.SimpleBindings;
32
33 import org.apache.tomcat.dbcp.dbcp2.BasicDataSource;
34 import org.h2.tools.Server;
35 import org.hibernate.Query;
36 import org.hibernate.Session;
37 import org.hibernate.SessionFactory;
38 import org.hibernate.Transaction;
39 import org.junit.After;
40 import org.junit.AfterClass;
41 import org.junit.BeforeClass;
42 import org.junit.Test;
43 import org.onap.policy.common.logging.flexlogger.FlexLogger;
44 import org.onap.policy.common.logging.flexlogger.Logger;
45 import org.onap.policy.rest.jpa.OnapName;
46 import org.onap.policy.rest.jpa.PolicyEntity;
47 import org.onap.policy.rest.jpa.PolicyRoles;
48 import org.onap.policy.rest.jpa.PolicyVersion;
49 import org.onap.policy.rest.jpa.SystemLogDB;
50 import org.onap.policy.rest.jpa.UserInfo;
51 import org.onap.policy.rest.jpa.WatchPolicyNotificationTable;
52 import org.springframework.orm.hibernate4.LocalSessionFactoryBuilder;
53 import org.springframework.transaction.annotation.Transactional;
54 import org.springframework.test.annotation.Rollback;
55
56
57 public class PolicyValidationDaoImplTest {
58
59     private static Logger logger = FlexLogger.getLogger(PolicyValidationDaoImplTest.class);
60
61     static SessionFactory sessionFactory;
62     static Server server;
63     static PolicyValidationDaoImpl commonClassDao;
64
65     @BeforeClass
66     public static void setupAll() {
67         try {
68             BasicDataSource dataSource = new BasicDataSource();
69             dataSource.setDriverClassName("org.h2.Driver");
70             // In-memory DB for testing
71             dataSource.setUrl("jdbc:h2:mem:test");
72             dataSource.setUsername("sa");
73             dataSource.setPassword("");
74             LocalSessionFactoryBuilder sessionBuilder = new LocalSessionFactoryBuilder(dataSource);
75             sessionBuilder.scanPackages("org.onap.*", "com.*");
76
77             Properties properties = new Properties();
78             properties.put("hibernate.show_sql", "false");
79             properties.put("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
80             properties.put("hibernate.hbm2ddl.auto", "drop");
81             properties.put("hibernate.hbm2ddl.auto", "create");
82
83             sessionBuilder.addProperties(properties);
84             sessionFactory = sessionBuilder.buildSessionFactory();
85
86             // Set up dao with SessionFactory
87             commonClassDao = new PolicyValidationDaoImpl();
88             PolicyValidationDaoImpl.setSessionfactory(sessionFactory);
89             //PolicyController.setLogTableLimit("1");
90             //HibernateSession.setSession(sessionFactory);
91             SystemLogDB data1 = new SystemLogDB();
92             data1.setDate(new Date());
93             data1.setLogtype("INFO");
94             data1.setRemote("Test");
95             data1.setSystem("Test");
96             data1.setType("Test");
97             SystemLogDB data2 = new SystemLogDB();
98             data2.setDate(new Date());
99             data2.setLogtype("error");
100             data2.setRemote("Test");
101             data2.setSystem("Test");
102             data2.setType("Test");
103             //HibernateSession.getSession().save(data1);
104             //HibernateSession.getSession().save(data2);
105
106             // Create TCP server for troubleshooting
107             server = Server.createTcpServer("-tcpAllowOthers").start();
108             System.out.println("URL: jdbc:h2:" + server.getURL() + "/mem:test");
109
110         }catch(Exception e){
111             System.err.println(e);
112             fail();
113         }
114     }
115
116     @AfterClass
117     public static void deleteDB() {
118         sessionFactory.close();
119         server.stop();
120     }
121
122     @After
123     public void tearDown() {
124         truncateAllTables();
125     }
126
127     @Test
128     @Transactional
129     @Rollback(true)
130     public void testDB(){
131         try{
132             // Add data
133             UserInfo userinfo = new UserInfo();
134             userinfo.setUserLoginId("Test");
135             userinfo.setUserName("Test");
136             commonClassDao.save(userinfo);
137             OnapName onapName = new OnapName();
138             onapName.setOnapName("Test");
139             onapName.setUserCreatedBy(userinfo);
140             onapName.setUserModifiedBy(userinfo);
141             onapName.setModifiedDate(new Date());
142             commonClassDao.save(onapName);
143
144
145             List<Object> list = commonClassDao.getData(OnapName.class);
146             assertTrue(list.size() == 1);
147             logger.debug(list.size());
148             logger.debug(list.get(0));
149         }catch(Exception e){
150             logger.debug("Exception Occured"+e);
151             fail();
152         }
153     }
154
155     @Test
156     @Transactional
157     @Rollback(true)
158     public void testUser(){
159         try{
160             // Add data
161             UserInfo userinfo = new UserInfo();
162             String loginId_userName = "Test";
163             userinfo.setUserLoginId(loginId_userName);
164             userinfo.setUserName(loginId_userName);
165             commonClassDao.save(userinfo);
166
167
168             List<Object> dataCur = commonClassDao.getDataByQuery("from UserInfo", new SimpleBindings());
169
170             assertEquals(1, dataCur.size());
171             UserInfo cur = (UserInfo) dataCur.get(0);
172             assertEquals(loginId_userName, cur.getUserLoginId());
173             assertEquals(loginId_userName, cur.getUserName());
174
175             assertFalse(dataCur.isEmpty());
176
177         }catch(Exception e){
178             logger.debug("Exception Occured"+e);
179             fail();
180         }
181     }
182
183     @Test
184     @Transactional
185     @Rollback(true)
186     public void getDataByQuery_DashboardController(){
187         try{
188             // Add data
189             PolicyEntity pe = new PolicyEntity();
190             String name = "TestPolicy";
191             pe.setPolicyName(name);
192             pe.setPolicyData("dummyData");
193             pe.prePersist();
194             pe.setScope("dummyScope");
195             pe.setDescription("descr");
196             pe.setDeleted(false);
197             pe.setCreatedBy("Test");
198             commonClassDao.save(pe);
199
200             List<Object> dataCur = commonClassDao.getDataByQuery("from PolicyEntity", new SimpleBindings());
201
202             assertTrue(1 == dataCur.size());
203             assertTrue( dataCur.get(0) instanceof PolicyEntity);
204             assertEquals( name,  ((PolicyEntity)dataCur.get(0)).getPolicyName());
205             assertEquals( pe, ((PolicyEntity)dataCur.get(0)));
206
207
208         }catch(Exception e){
209             logger.debug("Exception Occured"+e);
210             fail();
211         }
212     }
213
214     @Test
215     @Transactional
216     @Rollback(true)
217     public void getDataByQuery_AutoPushController(){
218         try{
219             // Add data
220             PolicyVersion pv = new PolicyVersion();
221             pv.setActiveVersion(2);
222             pv.setPolicyName("myPname");
223             pv.prePersist();
224             pv.setCreatedBy("Test");
225             pv.setModifiedBy("Test");
226
227             PolicyVersion pv2 = new PolicyVersion();
228             pv2.setActiveVersion(1);
229             pv2.setPolicyName("test");
230             pv2.prePersist();
231             pv2.setCreatedBy("Test");
232             pv2.setModifiedBy("Test");
233
234             commonClassDao.save(pv);
235             commonClassDao.save(pv2);
236
237             String scope = "my";
238             scope += "%";
239             String query = "From PolicyVersion where policy_name like :scope and id > 0";
240             SimpleBindings params = new SimpleBindings();
241             params.put("scope", scope);
242             List<Object> dataCur = commonClassDao.getDataByQuery(query, params);
243
244
245             assertTrue(1 == dataCur.size());
246             assertEquals(pv, (PolicyVersion) dataCur.get(0));
247
248         }catch(Exception e){
249             logger.debug("Exception Occured"+e);
250             fail();
251         }
252     }
253
254     @Test
255     @Transactional
256     @Rollback(true)
257     public void getDataByQuery_PolicyNotificationMail(){
258         try{
259             // Add data
260             WatchPolicyNotificationTable watch = new WatchPolicyNotificationTable();
261             String policyFileName = "banana";
262             watch.setLoginIds("Test");
263             watch.setPolicyName("bananaWatch");
264             commonClassDao.save(watch);
265
266             if(policyFileName.contains("/")){
267                 policyFileName = policyFileName.substring(0, policyFileName.indexOf("/"));
268                 policyFileName = policyFileName.replace("/", File.separator);
269             }
270             if(policyFileName.contains("\\")){
271                 policyFileName = policyFileName.substring(0, policyFileName.indexOf("\\"));
272                 policyFileName = policyFileName.replace("\\", "\\\\");
273             }
274
275
276             // Current Implementation
277             policyFileName += "%";
278             String query = "from WatchPolicyNotificationTable where policyName like:policyFileName";
279             SimpleBindings params = new SimpleBindings();
280             params.put("policyFileName", policyFileName);
281             List<Object> dataCur = commonClassDao.getDataByQuery(query, params);
282
283             // Assertions
284             assertTrue(dataCur.size() == 1);
285             assertTrue(dataCur.get(0) instanceof WatchPolicyNotificationTable);
286             assertEquals(watch, (WatchPolicyNotificationTable) dataCur.get(0));
287
288         }catch(Exception e){
289             logger.debug("Exception Occured"+e);
290             fail();
291         }
292     }
293
294
295     @Test
296     @Transactional
297     @Rollback(true)
298     public void getDataByQuery_PolicyController(){
299         try{
300             // Add data
301             PolicyEntity pe = new PolicyEntity();
302             String name = "actionDummy";
303             pe.setPolicyName(name);
304             pe.setPolicyData("dummyData");
305             pe.prePersist();
306             pe.setScope("dummyScope");
307             pe.setDescription("descr");
308             pe.setDeleted(false);
309             pe.setCreatedBy("Test");
310             commonClassDao.save(pe);
311
312             String dbCheckName = "dummyScope:action";
313             String[] splitDBCheckName = dbCheckName.split(":");
314
315
316             // Current Implementation
317             String query =   "FROM PolicyEntity where policyName like :splitDBCheckName1 and scope = :splitDBCheckName0";
318             SimpleBindings params = new SimpleBindings();
319             params.put("splitDBCheckName1", splitDBCheckName[1] + "%");
320             params.put("splitDBCheckName0", splitDBCheckName[0]);
321             List<Object> dataCur = commonClassDao.getDataByQuery(query, params);
322
323             // Assertions
324             assertTrue(dataCur.size() == 1);
325             assertTrue(dataCur.get(0) instanceof PolicyEntity);
326             assertEquals(pe, (PolicyEntity) dataCur.get(0));
327
328         }catch(Exception e){
329             logger.debug("Exception Occured"+e);
330             fail();
331         }
332     }
333
334     @Test
335     @Transactional
336     @Rollback(true)
337     public void getDataByQuery_PolicyNotificationController(){
338         try{
339             // Add data
340             WatchPolicyNotificationTable watch = new WatchPolicyNotificationTable();
341             String finalName = "banana"; // Policy File Name
342             String userId = "Test";
343             watch.setLoginIds(userId);
344             watch.setPolicyName(finalName);
345             commonClassDao.save(watch);
346
347
348             // Current Implementation
349             String query = "from WatchPolicyNotificationTable where POLICYNAME = :finalName and LOGINIDS = :userId";
350             SimpleBindings params = new SimpleBindings();
351             params.put("finalName", finalName);
352             params.put("userId", userId);
353             List<Object> dataCur = commonClassDao.getDataByQuery(query, params);
354
355             // Assertions
356             assertTrue(dataCur.size() == 1);
357             assertTrue(dataCur.get(0) instanceof WatchPolicyNotificationTable);
358             assertEquals(watch, (WatchPolicyNotificationTable) dataCur.get(0) );
359
360         }catch(Exception e){
361             logger.debug("Exception Occured"+e);
362             fail();
363         }
364     }
365
366
367      /* Test for SQL Injection Protection
368      */
369
370     @Test
371     @Transactional
372     @Rollback(true)
373     public void getDataByQuery_PolicyNotificationController_Injection(){
374         try{
375             // Add data
376             WatchPolicyNotificationTable watch = new WatchPolicyNotificationTable();
377             String userId = "Test";
378             watch.setLoginIds(userId);
379             watch.setPolicyName("banana");
380             commonClassDao.save(watch);
381
382             WatchPolicyNotificationTable watch2 = new WatchPolicyNotificationTable();
383             watch2.setLoginIds(userId);
384             watch2.setPolicyName("banana2");
385             commonClassDao.save(watch2);
386
387             // SQL Injection attempt
388             String finalName = "banana' OR '1'='1";
389
390
391             // Current Implementation
392             String query = "from WatchPolicyNotificationTable where POLICYNAME = :finalName and LOGINIDS = :userId";
393             SimpleBindings params = new SimpleBindings();
394             params.put("finalName", finalName);
395             params.put("userId", userId);
396             List<Object> dataCur = commonClassDao.getDataByQuery(query, params);
397
398             // Assertions
399             assertTrue(dataCur.size() <= 1);
400
401             if(dataCur.size() >= 1){
402                 assertTrue(dataCur.get(0) instanceof WatchPolicyNotificationTable);
403                 assertFalse(watch.equals((WatchPolicyNotificationTable) dataCur.get(0)));
404                 assertFalse(watch.equals((WatchPolicyNotificationTable) dataCur.get(0)));
405             }
406         }catch(Exception e){
407             logger.debug("Exception Occured"+e);
408             fail();
409         }
410     }
411
412     @Test
413     public void testCommonClassDaoImplMethods(){
414         try{
415             UserInfo userInfo = new UserInfo();
416             userInfo.setUserLoginId("TestID");
417             userInfo.setUserName("Test");
418             commonClassDao.save(userInfo);
419             List<Object> data = commonClassDao.getDataById(UserInfo.class, "userLoginId:userName", "TestID:Test");
420             assertTrue(data.size() == 1);
421             UserInfo userInfoUpdate = (UserInfo) data.get(0);
422             userInfoUpdate.setUserName("Test1");
423             commonClassDao.update(userInfoUpdate);
424             List<String> data1 = commonClassDao.getDataByColumn(UserInfo.class, "userLoginId");
425             assertTrue(data1.size() == 1);
426             UserInfo data2 = (UserInfo) commonClassDao.getEntityItem(UserInfo.class, "userLoginId:userName", "TestID:Test1");
427             assertTrue("TestID".equals(data2.getUserLoginId()));
428             List<Object> data3 = commonClassDao.checkDuplicateEntry("TestID:Test1", "userLoginId:userName", UserInfo.class);
429             assertTrue(data3.size() == 1);
430             PolicyRoles roles = new PolicyRoles();
431             roles.setRole("admin");
432             roles.setLoginId(userInfo);
433             roles.setScope("test");
434             commonClassDao.save(roles);
435             List<PolicyRoles> roles1 = commonClassDao.getUserRoles();
436             assertTrue(roles1.size() == 1);
437             List<String> multipleData = new ArrayList<>();
438             multipleData.add("TestID:Test1");
439             List<Object> data4 = commonClassDao.getMultipleDataOnAddingConjunction(UserInfo.class, "userLoginId:userName", multipleData);
440             assertTrue(data4.size() == 1);
441             commonClassDao.delete(data2);
442         }catch(Exception e){
443             logger.debug("Exception Occured"+e);
444             fail();
445         }
446     }
447
448
449     private void truncateAllTables() {
450         Session session = sessionFactory.openSession();
451         Transaction transaction = session.beginTransaction();
452         sessionFactory.getAllClassMetadata().forEach((tableName, x) -> {
453             Query query = session.createQuery("DELETE FROM " + tableName);
454             query.executeUpdate();
455         });
456         transaction.commit();
457         session.close();
458     }
459
460 }