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