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